blob: 1000ba60367001db25ad3ec80d1c951d5bd949a1 [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
Chris Lattner62b14df2002-09-02 04:59:56 +000011// instructions. This pass does not modify the CFG This pass is where algebraic
12// 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"
Dale Johannesen22c39792008-02-22 22:17:59 +000042#include "llvm/ParamAttrsList.h"
Chris Lattner79066fa2007-01-30 23:46:24 +000043#include "llvm/Analysis/ConstantFolding.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>
Reid Spencera9b81012007-03-26 17:44:01 +000061#include <sstream>
Chris Lattner67b1e1b2003-12-07 01:24:23 +000062using namespace llvm;
Chris Lattneracd1f0f2004-07-30 07:50:03 +000063using namespace llvm::PatternMatch;
Brian Gaeked0fde302003-11-11 22:41:34 +000064
Chris Lattner0e5f4992006-12-19 21:40:18 +000065STATISTIC(NumCombined , "Number of insts combined");
66STATISTIC(NumConstProp, "Number of constant folds");
67STATISTIC(NumDeadInst , "Number of dead inst eliminated");
68STATISTIC(NumDeadStore, "Number of dead stores eliminated");
69STATISTIC(NumSunkInst , "Number of instructions sunk");
Chris Lattnera92f6962002-10-01 22:38:41 +000070
Chris Lattner0e5f4992006-12-19 21:40:18 +000071namespace {
Chris Lattnerf4b54612006-06-28 22:08:15 +000072 class VISIBILITY_HIDDEN InstCombiner
73 : public FunctionPass,
74 public InstVisitor<InstCombiner, Instruction*> {
Chris Lattnerdd841ae2002-04-18 17:39:14 +000075 // Worklist of all of the instructions that need to be simplified.
Chris Lattnerdbab3862007-03-02 21:28:56 +000076 std::vector<Instruction*> Worklist;
77 DenseMap<Instruction*, unsigned> WorklistMap;
Chris Lattnerbc61e662003-11-02 05:57:39 +000078 TargetData *TD;
Chris Lattnerf964f322007-03-04 04:27:24 +000079 bool MustPreserveLCSSA;
Chris Lattnerdbab3862007-03-02 21:28:56 +000080 public:
Nick Lewyckyecd94c82007-05-06 13:37:16 +000081 static char ID; // Pass identification, replacement for typeid
Devang Patel794fd752007-05-01 21:15:47 +000082 InstCombiner() : FunctionPass((intptr_t)&ID) {}
83
Chris Lattnerdbab3862007-03-02 21:28:56 +000084 /// AddToWorkList - Add the specified instruction to the worklist if it
85 /// isn't already in it.
86 void AddToWorkList(Instruction *I) {
87 if (WorklistMap.insert(std::make_pair(I, Worklist.size())))
88 Worklist.push_back(I);
89 }
90
91 // RemoveFromWorkList - remove I from the worklist if it exists.
92 void RemoveFromWorkList(Instruction *I) {
93 DenseMap<Instruction*, unsigned>::iterator It = WorklistMap.find(I);
94 if (It == WorklistMap.end()) return; // Not in worklist.
95
96 // Don't bother moving everything down, just null out the slot.
97 Worklist[It->second] = 0;
98
99 WorklistMap.erase(It);
100 }
101
102 Instruction *RemoveOneFromWorkList() {
103 Instruction *I = Worklist.back();
104 Worklist.pop_back();
105 WorklistMap.erase(I);
106 return I;
107 }
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000108
Chris Lattnerdbab3862007-03-02 21:28:56 +0000109
Chris Lattner7bcc0e72004-02-28 05:22:00 +0000110 /// AddUsersToWorkList - When an instruction is simplified, add all users of
111 /// the instruction to the work lists because they might get more simplified
112 /// now.
113 ///
Chris Lattner6dce1a72006-02-07 06:56:34 +0000114 void AddUsersToWorkList(Value &I) {
Chris Lattner7e708292002-06-25 16:13:24 +0000115 for (Value::use_iterator UI = I.use_begin(), UE = I.use_end();
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000116 UI != UE; ++UI)
Chris Lattnerdbab3862007-03-02 21:28:56 +0000117 AddToWorkList(cast<Instruction>(*UI));
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000118 }
119
Chris Lattner7bcc0e72004-02-28 05:22:00 +0000120 /// AddUsesToWorkList - When an instruction is simplified, add operands to
121 /// the work lists because they might get more simplified now.
122 ///
123 void AddUsesToWorkList(Instruction &I) {
124 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i)
125 if (Instruction *Op = dyn_cast<Instruction>(I.getOperand(i)))
Chris Lattnerdbab3862007-03-02 21:28:56 +0000126 AddToWorkList(Op);
Chris Lattner7bcc0e72004-02-28 05:22:00 +0000127 }
Chris Lattner867b99f2006-10-05 06:55:50 +0000128
129 /// AddSoonDeadInstToWorklist - The specified instruction is about to become
130 /// dead. Add all of its operands to the worklist, turning them into
131 /// undef's to reduce the number of uses of those instructions.
132 ///
133 /// Return the specified operand before it is turned into an undef.
134 ///
135 Value *AddSoonDeadInstToWorklist(Instruction &I, unsigned op) {
136 Value *R = I.getOperand(op);
137
138 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i)
139 if (Instruction *Op = dyn_cast<Instruction>(I.getOperand(i))) {
Chris Lattnerdbab3862007-03-02 21:28:56 +0000140 AddToWorkList(Op);
Chris Lattner867b99f2006-10-05 06:55:50 +0000141 // Set the operand to undef to drop the use.
142 I.setOperand(i, UndefValue::get(Op->getType()));
143 }
144
145 return R;
146 }
Chris Lattner7bcc0e72004-02-28 05:22:00 +0000147
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000148 public:
Chris Lattner7e708292002-06-25 16:13:24 +0000149 virtual bool runOnFunction(Function &F);
Chris Lattnerec9c3582007-03-03 02:04:50 +0000150
151 bool DoOneIteration(Function &F, unsigned ItNum);
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000152
Chris Lattner97e52e42002-04-28 21:27:06 +0000153 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
Chris Lattnerbc61e662003-11-02 05:57:39 +0000154 AU.addRequired<TargetData>();
Owen Andersond1b78a12006-07-10 19:03:49 +0000155 AU.addPreservedID(LCSSAID);
Chris Lattnercb2610e2002-10-21 20:00:28 +0000156 AU.setPreservesCFG();
Chris Lattner97e52e42002-04-28 21:27:06 +0000157 }
158
Chris Lattner28977af2004-04-05 01:30:19 +0000159 TargetData &getTargetData() const { return *TD; }
160
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000161 // Visitation implementation - Implement instruction combining for different
162 // instruction types. The semantics are as follows:
163 // Return Value:
164 // null - No change was made
Chris Lattner233f7dc2002-08-12 21:17:25 +0000165 // I - Change was made, I is still valid, I may be dead though
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000166 // otherwise - Change was made, replace I with returned instruction
Misha Brukmanfd939082005-04-21 23:48:37 +0000167 //
Chris Lattner7e708292002-06-25 16:13:24 +0000168 Instruction *visitAdd(BinaryOperator &I);
169 Instruction *visitSub(BinaryOperator &I);
170 Instruction *visitMul(BinaryOperator &I);
Reid Spencer0a783f72006-11-02 01:53:59 +0000171 Instruction *visitURem(BinaryOperator &I);
172 Instruction *visitSRem(BinaryOperator &I);
173 Instruction *visitFRem(BinaryOperator &I);
174 Instruction *commonRemTransforms(BinaryOperator &I);
175 Instruction *commonIRemTransforms(BinaryOperator &I);
Reid Spencer1628cec2006-10-26 06:15:43 +0000176 Instruction *commonDivTransforms(BinaryOperator &I);
177 Instruction *commonIDivTransforms(BinaryOperator &I);
178 Instruction *visitUDiv(BinaryOperator &I);
179 Instruction *visitSDiv(BinaryOperator &I);
180 Instruction *visitFDiv(BinaryOperator &I);
Chris Lattner7e708292002-06-25 16:13:24 +0000181 Instruction *visitAnd(BinaryOperator &I);
182 Instruction *visitOr (BinaryOperator &I);
183 Instruction *visitXor(BinaryOperator &I);
Reid Spencer832254e2007-02-02 02:16:23 +0000184 Instruction *visitShl(BinaryOperator &I);
185 Instruction *visitAShr(BinaryOperator &I);
186 Instruction *visitLShr(BinaryOperator &I);
187 Instruction *commonShiftTransforms(BinaryOperator &I);
Reid Spencere4d87aa2006-12-23 06:05:41 +0000188 Instruction *visitFCmpInst(FCmpInst &I);
189 Instruction *visitICmpInst(ICmpInst &I);
190 Instruction *visitICmpInstWithCastAndCast(ICmpInst &ICI);
Chris Lattner01deb9d2007-04-03 17:43:25 +0000191 Instruction *visitICmpInstWithInstAndIntCst(ICmpInst &ICI,
192 Instruction *LHS,
193 ConstantInt *RHS);
Chris Lattner562ef782007-06-20 23:46:26 +0000194 Instruction *FoldICmpDivCst(ICmpInst &ICI, BinaryOperator *DivI,
195 ConstantInt *DivRHS);
Chris Lattner484d3cf2005-04-24 06:59:08 +0000196
Reid Spencere4d87aa2006-12-23 06:05:41 +0000197 Instruction *FoldGEPICmp(User *GEPLHS, Value *RHS,
198 ICmpInst::Predicate Cond, Instruction &I);
Reid Spencerb83eb642006-10-20 07:07:24 +0000199 Instruction *FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
Reid Spencer832254e2007-02-02 02:16:23 +0000200 BinaryOperator &I);
Reid Spencer3da59db2006-11-27 01:05:10 +0000201 Instruction *commonCastTransforms(CastInst &CI);
202 Instruction *commonIntCastTransforms(CastInst &CI);
Chris Lattnerd3e28342007-04-27 17:44:50 +0000203 Instruction *commonPointerCastTransforms(CastInst &CI);
Chris Lattner8a9f5712007-04-11 06:57:46 +0000204 Instruction *visitTrunc(TruncInst &CI);
205 Instruction *visitZExt(ZExtInst &CI);
206 Instruction *visitSExt(SExtInst &CI);
Chris Lattnerb7530652008-01-27 05:29:54 +0000207 Instruction *visitFPTrunc(FPTruncInst &CI);
Reid Spencer3da59db2006-11-27 01:05:10 +0000208 Instruction *visitFPExt(CastInst &CI);
209 Instruction *visitFPToUI(CastInst &CI);
210 Instruction *visitFPToSI(CastInst &CI);
211 Instruction *visitUIToFP(CastInst &CI);
212 Instruction *visitSIToFP(CastInst &CI);
213 Instruction *visitPtrToInt(CastInst &CI);
Chris Lattnerf9d9e452008-01-08 07:23:51 +0000214 Instruction *visitIntToPtr(IntToPtrInst &CI);
Chris Lattnerd3e28342007-04-27 17:44:50 +0000215 Instruction *visitBitCast(BitCastInst &CI);
Chris Lattner6fb5a4a2005-01-19 21:50:18 +0000216 Instruction *FoldSelectOpOp(SelectInst &SI, Instruction *TI,
217 Instruction *FI);
Chris Lattner3d69f462004-03-12 05:52:32 +0000218 Instruction *visitSelectInst(SelectInst &CI);
Chris Lattner9fe38862003-06-19 17:00:31 +0000219 Instruction *visitCallInst(CallInst &CI);
220 Instruction *visitInvokeInst(InvokeInst &II);
Chris Lattner7e708292002-06-25 16:13:24 +0000221 Instruction *visitPHINode(PHINode &PN);
222 Instruction *visitGetElementPtrInst(GetElementPtrInst &GEP);
Chris Lattner0864acf2002-11-04 16:18:53 +0000223 Instruction *visitAllocationInst(AllocationInst &AI);
Chris Lattner67b1e1b2003-12-07 01:24:23 +0000224 Instruction *visitFreeInst(FreeInst &FI);
Chris Lattner833b8a42003-06-26 05:06:25 +0000225 Instruction *visitLoadInst(LoadInst &LI);
Chris Lattner2f503e62005-01-31 05:36:43 +0000226 Instruction *visitStoreInst(StoreInst &SI);
Chris Lattnerc4d10eb2003-06-04 04:46:00 +0000227 Instruction *visitBranchInst(BranchInst &BI);
Chris Lattner46238a62004-07-03 00:26:11 +0000228 Instruction *visitSwitchInst(SwitchInst &SI);
Chris Lattnerefb47352006-04-15 01:39:45 +0000229 Instruction *visitInsertElementInst(InsertElementInst &IE);
Robert Bocchino1d7456d2006-01-13 22:48:06 +0000230 Instruction *visitExtractElementInst(ExtractElementInst &EI);
Chris Lattnera844fc4c2006-04-10 22:45:52 +0000231 Instruction *visitShuffleVectorInst(ShuffleVectorInst &SVI);
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000232
233 // visitInstruction - Specify what to return for unhandled instructions...
Chris Lattner7e708292002-06-25 16:13:24 +0000234 Instruction *visitInstruction(Instruction &I) { return 0; }
Chris Lattner8b170942002-08-09 23:47:40 +0000235
Chris Lattner9fe38862003-06-19 17:00:31 +0000236 private:
Chris Lattnera44d8a22003-10-07 22:32:43 +0000237 Instruction *visitCallSite(CallSite CS);
Chris Lattner9fe38862003-06-19 17:00:31 +0000238 bool transformConstExprCastCall(CallSite CS);
Duncan Sandscdb6d922007-09-17 10:26:40 +0000239 Instruction *transformCallThroughTrampoline(CallSite CS);
Chris Lattner9fe38862003-06-19 17:00:31 +0000240
Chris Lattner28977af2004-04-05 01:30:19 +0000241 public:
Chris Lattner8b170942002-08-09 23:47:40 +0000242 // InsertNewInstBefore - insert an instruction New before instruction Old
243 // in the program. Add the new instruction to the worklist.
244 //
Chris Lattner955f3312004-09-28 21:48:02 +0000245 Instruction *InsertNewInstBefore(Instruction *New, Instruction &Old) {
Chris Lattnere6f9a912002-08-23 18:32:43 +0000246 assert(New && New->getParent() == 0 &&
247 "New instruction already inserted into a basic block!");
Chris Lattner8b170942002-08-09 23:47:40 +0000248 BasicBlock *BB = Old.getParent();
249 BB->getInstList().insert(&Old, New); // Insert inst
Chris Lattnerdbab3862007-03-02 21:28:56 +0000250 AddToWorkList(New);
Chris Lattner4cb170c2004-02-23 06:38:22 +0000251 return New;
Chris Lattner8b170942002-08-09 23:47:40 +0000252 }
253
Chris Lattner0c967662004-09-24 15:21:34 +0000254 /// InsertCastBefore - Insert a cast of V to TY before the instruction POS.
255 /// This also adds the cast to the worklist. Finally, this returns the
256 /// cast.
Reid Spencer17212df2006-12-12 09:18:51 +0000257 Value *InsertCastBefore(Instruction::CastOps opc, Value *V, const Type *Ty,
258 Instruction &Pos) {
Chris Lattner0c967662004-09-24 15:21:34 +0000259 if (V->getType() == Ty) return V;
Misha Brukmanfd939082005-04-21 23:48:37 +0000260
Chris Lattnere2ed0572006-04-06 19:19:17 +0000261 if (Constant *CV = dyn_cast<Constant>(V))
Reid Spencer17212df2006-12-12 09:18:51 +0000262 return ConstantExpr::getCast(opc, CV, Ty);
Chris Lattnere2ed0572006-04-06 19:19:17 +0000263
Reid Spencer17212df2006-12-12 09:18:51 +0000264 Instruction *C = CastInst::create(opc, V, Ty, V->getName(), &Pos);
Chris Lattnerdbab3862007-03-02 21:28:56 +0000265 AddToWorkList(C);
Chris Lattner0c967662004-09-24 15:21:34 +0000266 return C;
267 }
Chris Lattner6d0339d2008-01-13 22:23:22 +0000268
269 Value *InsertBitCastBefore(Value *V, const Type *Ty, Instruction &Pos) {
270 return InsertCastBefore(Instruction::BitCast, V, Ty, Pos);
271 }
272
Chris Lattner0c967662004-09-24 15:21:34 +0000273
Chris Lattner8b170942002-08-09 23:47:40 +0000274 // ReplaceInstUsesWith - This method is to be used when an instruction is
275 // found to be dead, replacable with another preexisting expression. Here
276 // we add all uses of I to the worklist, replace all uses of I with the new
277 // value, then return I, so that the inst combiner will know that I was
278 // modified.
279 //
280 Instruction *ReplaceInstUsesWith(Instruction &I, Value *V) {
Chris Lattner7bcc0e72004-02-28 05:22:00 +0000281 AddUsersToWorkList(I); // Add all modified instrs to worklist
Chris Lattner15a76c02004-04-05 02:10:19 +0000282 if (&I != V) {
283 I.replaceAllUsesWith(V);
284 return &I;
285 } else {
286 // If we are replacing the instruction with itself, this must be in a
287 // segment of unreachable code, so just clobber the instruction.
Chris Lattner17be6352004-10-18 02:59:09 +0000288 I.replaceAllUsesWith(UndefValue::get(I.getType()));
Chris Lattner15a76c02004-04-05 02:10:19 +0000289 return &I;
290 }
Chris Lattner8b170942002-08-09 23:47:40 +0000291 }
Chris Lattner7bcc0e72004-02-28 05:22:00 +0000292
Chris Lattner6dce1a72006-02-07 06:56:34 +0000293 // UpdateValueUsesWith - This method is to be used when an value is
294 // found to be replacable with another preexisting expression or was
295 // updated. Here we add all uses of I to the worklist, replace all uses of
296 // I with the new value (unless the instruction was just updated), then
297 // return true, so that the inst combiner will know that I was modified.
298 //
299 bool UpdateValueUsesWith(Value *Old, Value *New) {
300 AddUsersToWorkList(*Old); // Add all modified instrs to worklist
301 if (Old != New)
302 Old->replaceAllUsesWith(New);
303 if (Instruction *I = dyn_cast<Instruction>(Old))
Chris Lattnerdbab3862007-03-02 21:28:56 +0000304 AddToWorkList(I);
Chris Lattnerf8c36f52006-02-12 08:02:11 +0000305 if (Instruction *I = dyn_cast<Instruction>(New))
Chris Lattnerdbab3862007-03-02 21:28:56 +0000306 AddToWorkList(I);
Chris Lattner6dce1a72006-02-07 06:56:34 +0000307 return true;
308 }
309
Chris Lattner7bcc0e72004-02-28 05:22:00 +0000310 // EraseInstFromFunction - When dealing with an instruction that has side
311 // effects or produces a void value, we can't rely on DCE to delete the
312 // instruction. Instead, visit methods should return the value returned by
313 // this function.
314 Instruction *EraseInstFromFunction(Instruction &I) {
315 assert(I.use_empty() && "Cannot erase instruction that is used!");
316 AddUsesToWorkList(I);
Chris Lattnerdbab3862007-03-02 21:28:56 +0000317 RemoveFromWorkList(&I);
Chris Lattner954f66a2004-11-18 21:41:39 +0000318 I.eraseFromParent();
Chris Lattner7bcc0e72004-02-28 05:22:00 +0000319 return 0; // Don't do anything with FI
320 }
321
Chris Lattneraa9c1f12003-08-13 20:16:26 +0000322 private:
Chris Lattner24c8e382003-07-24 17:35:25 +0000323 /// InsertOperandCastBefore - This inserts a cast of V to DestTy before the
324 /// InsertBefore instruction. This is specialized a bit to avoid inserting
325 /// casts that are known to not do anything...
326 ///
Reid Spencer17212df2006-12-12 09:18:51 +0000327 Value *InsertOperandCastBefore(Instruction::CastOps opcode,
328 Value *V, const Type *DestTy,
Chris Lattner24c8e382003-07-24 17:35:25 +0000329 Instruction *InsertBefore);
330
Reid Spencere4d87aa2006-12-23 06:05:41 +0000331 /// SimplifyCommutative - This performs a few simplifications for
332 /// commutative operators.
Chris Lattnerc8802d22003-03-11 00:12:48 +0000333 bool SimplifyCommutative(BinaryOperator &I);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +0000334
Reid Spencere4d87aa2006-12-23 06:05:41 +0000335 /// SimplifyCompare - This reorders the operands of a CmpInst to get them in
336 /// most-complex to least-complex order.
337 bool SimplifyCompare(CmpInst &I);
338
Reid Spencer2ec619a2007-03-23 21:24:59 +0000339 /// SimplifyDemandedBits - Attempts to replace V with a simpler value based
340 /// on the demanded bits.
Reid Spencer8cb68342007-03-12 17:25:59 +0000341 bool SimplifyDemandedBits(Value *V, APInt DemandedMask,
342 APInt& KnownZero, APInt& KnownOne,
343 unsigned Depth = 0);
344
Chris Lattner867b99f2006-10-05 06:55:50 +0000345 Value *SimplifyDemandedVectorElts(Value *V, uint64_t DemandedElts,
346 uint64_t &UndefElts, unsigned Depth = 0);
347
Chris Lattner4e998b22004-09-29 05:07:12 +0000348 // FoldOpIntoPhi - Given a binary operator or cast instruction which has a
349 // PHI node as operand #0, see if we can fold the instruction into the PHI
350 // (which is only possible if all operands to the PHI are constants).
351 Instruction *FoldOpIntoPhi(Instruction &I);
352
Chris Lattnerbac32862004-11-14 19:13:23 +0000353 // FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
354 // operator and they all are only used by the PHI, PHI together their
355 // inputs, and do the operation once, to the result of the PHI.
356 Instruction *FoldPHIArgOpIntoPHI(PHINode &PN);
Chris Lattner7da52b22006-11-01 04:51:18 +0000357 Instruction *FoldPHIArgBinOpIntoPHI(PHINode &PN);
358
359
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +0000360 Instruction *OptAndOp(Instruction *Op, ConstantInt *OpRHS,
361 ConstantInt *AndRHS, BinaryOperator &TheAnd);
Chris Lattnerc8e77562005-09-18 04:24:45 +0000362
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +0000363 Value *FoldLogicalPlusAnd(Value *LHS, Value *RHS, ConstantInt *Mask,
Chris Lattnerc8e77562005-09-18 04:24:45 +0000364 bool isSub, Instruction &I);
Chris Lattnera96879a2004-09-29 17:40:11 +0000365 Instruction *InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
Reid Spencere4d87aa2006-12-23 06:05:41 +0000366 bool isSigned, bool Inside, Instruction &IB);
Chris Lattnerd3e28342007-04-27 17:44:50 +0000367 Instruction *PromoteCastOfAllocation(BitCastInst &CI, AllocationInst &AI);
Chris Lattnerafe91a52006-06-15 19:07:26 +0000368 Instruction *MatchBSwap(BinaryOperator &I);
Chris Lattner3284d1f2007-04-15 00:07:55 +0000369 bool SimplifyStoreAtEndOfBlock(StoreInst &SI);
Chris Lattnerf497b022008-01-13 23:50:23 +0000370 Instruction *SimplifyMemTransfer(MemIntrinsic *MI);
371
Chris Lattnerafe91a52006-06-15 19:07:26 +0000372
Reid Spencerc55b2432006-12-13 18:21:21 +0000373 Value *EvaluateInDifferentType(Value *V, const Type *Ty, bool isSigned);
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000374 };
Chris Lattnerf6293092002-07-23 18:06:35 +0000375
Devang Patel19974732007-05-03 01:11:54 +0000376 char InstCombiner::ID = 0;
Chris Lattner7f8897f2006-08-27 22:42:52 +0000377 RegisterPass<InstCombiner> X("instcombine", "Combine redundant instructions");
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000378}
379
Chris Lattner4f98c562003-03-10 21:43:22 +0000380// getComplexity: Assign a complexity or rank value to LLVM Values...
Chris Lattnere87597f2004-10-16 18:11:37 +0000381// 0 -> undef, 1 -> Const, 2 -> Other, 3 -> Arg, 3 -> Unary, 4 -> OtherInst
Chris Lattner4f98c562003-03-10 21:43:22 +0000382static unsigned getComplexity(Value *V) {
383 if (isa<Instruction>(V)) {
384 if (BinaryOperator::isNeg(V) || BinaryOperator::isNot(V))
Chris Lattnere87597f2004-10-16 18:11:37 +0000385 return 3;
386 return 4;
Chris Lattner4f98c562003-03-10 21:43:22 +0000387 }
Chris Lattnere87597f2004-10-16 18:11:37 +0000388 if (isa<Argument>(V)) return 3;
389 return isa<Constant>(V) ? (isa<UndefValue>(V) ? 0 : 1) : 2;
Chris Lattner4f98c562003-03-10 21:43:22 +0000390}
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000391
Chris Lattnerc8802d22003-03-11 00:12:48 +0000392// isOnlyUse - Return true if this instruction will be deleted if we stop using
393// it.
394static bool isOnlyUse(Value *V) {
Chris Lattnerfd059242003-10-15 16:48:29 +0000395 return V->hasOneUse() || isa<Constant>(V);
Chris Lattnerc8802d22003-03-11 00:12:48 +0000396}
397
Chris Lattner4cb170c2004-02-23 06:38:22 +0000398// getPromotedType - Return the specified type promoted as it would be to pass
399// though a va_arg area...
400static const Type *getPromotedType(const Type *Ty) {
Reid Spencera54b7cb2007-01-12 07:05:14 +0000401 if (const IntegerType* ITy = dyn_cast<IntegerType>(Ty)) {
402 if (ITy->getBitWidth() < 32)
403 return Type::Int32Ty;
Chris Lattner2b7e0ad2007-05-23 01:17:04 +0000404 }
Reid Spencera54b7cb2007-01-12 07:05:14 +0000405 return Ty;
Chris Lattner4cb170c2004-02-23 06:38:22 +0000406}
407
Reid Spencer3da59db2006-11-27 01:05:10 +0000408/// getBitCastOperand - If the specified operand is a CastInst or a constant
409/// expression bitcast, return the operand value, otherwise return null.
410static Value *getBitCastOperand(Value *V) {
411 if (BitCastInst *I = dyn_cast<BitCastInst>(V))
Chris Lattnereed48272005-09-13 00:40:14 +0000412 return I->getOperand(0);
413 else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
Reid Spencer3da59db2006-11-27 01:05:10 +0000414 if (CE->getOpcode() == Instruction::BitCast)
Chris Lattnereed48272005-09-13 00:40:14 +0000415 return CE->getOperand(0);
416 return 0;
417}
418
Reid Spencer3da59db2006-11-27 01:05:10 +0000419/// This function is a wrapper around CastInst::isEliminableCastPair. It
420/// simply extracts arguments and returns what that function returns.
Reid Spencer3da59db2006-11-27 01:05:10 +0000421static Instruction::CastOps
422isEliminableCastPair(
423 const CastInst *CI, ///< The first cast instruction
424 unsigned opcode, ///< The opcode of the second cast instruction
425 const Type *DstTy, ///< The target type for the second cast instruction
426 TargetData *TD ///< The target data for pointer size
427) {
428
429 const Type *SrcTy = CI->getOperand(0)->getType(); // A from above
430 const Type *MidTy = CI->getType(); // B from above
Chris Lattner33a61132006-05-06 09:00:16 +0000431
Reid Spencer3da59db2006-11-27 01:05:10 +0000432 // Get the opcodes of the two Cast instructions
433 Instruction::CastOps firstOp = Instruction::CastOps(CI->getOpcode());
434 Instruction::CastOps secondOp = Instruction::CastOps(opcode);
Chris Lattner33a61132006-05-06 09:00:16 +0000435
Reid Spencer3da59db2006-11-27 01:05:10 +0000436 return Instruction::CastOps(
437 CastInst::isEliminableCastPair(firstOp, secondOp, SrcTy, MidTy,
438 DstTy, TD->getIntPtrType()));
Chris Lattner33a61132006-05-06 09:00:16 +0000439}
440
441/// ValueRequiresCast - Return true if the cast from "V to Ty" actually results
442/// in any code being generated. It does not require codegen if V is simple
443/// enough or if the cast can be folded into other casts.
Reid Spencere4d87aa2006-12-23 06:05:41 +0000444static bool ValueRequiresCast(Instruction::CastOps opcode, const Value *V,
445 const Type *Ty, TargetData *TD) {
Chris Lattner33a61132006-05-06 09:00:16 +0000446 if (V->getType() == Ty || isa<Constant>(V)) return false;
447
Chris Lattner01575b72006-05-25 23:24:33 +0000448 // If this is another cast that can be eliminated, it isn't codegen either.
Chris Lattner33a61132006-05-06 09:00:16 +0000449 if (const CastInst *CI = dyn_cast<CastInst>(V))
Reid Spencere4d87aa2006-12-23 06:05:41 +0000450 if (isEliminableCastPair(CI, opcode, Ty, TD))
Chris Lattner33a61132006-05-06 09:00:16 +0000451 return false;
452 return true;
453}
454
455/// InsertOperandCastBefore - This inserts a cast of V to DestTy before the
456/// InsertBefore instruction. This is specialized a bit to avoid inserting
457/// casts that are known to not do anything...
458///
Reid Spencer17212df2006-12-12 09:18:51 +0000459Value *InstCombiner::InsertOperandCastBefore(Instruction::CastOps opcode,
460 Value *V, const Type *DestTy,
Chris Lattner33a61132006-05-06 09:00:16 +0000461 Instruction *InsertBefore) {
462 if (V->getType() == DestTy) return V;
463 if (Constant *C = dyn_cast<Constant>(V))
Reid Spencer17212df2006-12-12 09:18:51 +0000464 return ConstantExpr::getCast(opcode, C, DestTy);
Chris Lattner33a61132006-05-06 09:00:16 +0000465
Reid Spencer17212df2006-12-12 09:18:51 +0000466 return InsertCastBefore(opcode, V, DestTy, *InsertBefore);
Chris Lattner33a61132006-05-06 09:00:16 +0000467}
468
Chris Lattner4f98c562003-03-10 21:43:22 +0000469// SimplifyCommutative - This performs a few simplifications for commutative
470// operators:
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000471//
Chris Lattner4f98c562003-03-10 21:43:22 +0000472// 1. Order operands such that they are listed from right (least complex) to
473// left (most complex). This puts constants before unary operators before
474// binary operators.
475//
Chris Lattnerc8802d22003-03-11 00:12:48 +0000476// 2. Transform: (op (op V, C1), C2) ==> (op V, (op C1, C2))
477// 3. Transform: (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
Chris Lattner4f98c562003-03-10 21:43:22 +0000478//
Chris Lattnerc8802d22003-03-11 00:12:48 +0000479bool InstCombiner::SimplifyCommutative(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +0000480 bool Changed = false;
481 if (getComplexity(I.getOperand(0)) < getComplexity(I.getOperand(1)))
482 Changed = !I.swapOperands();
Misha Brukmanfd939082005-04-21 23:48:37 +0000483
Chris Lattner4f98c562003-03-10 21:43:22 +0000484 if (!I.isAssociative()) return Changed;
485 Instruction::BinaryOps Opcode = I.getOpcode();
Chris Lattnerc8802d22003-03-11 00:12:48 +0000486 if (BinaryOperator *Op = dyn_cast<BinaryOperator>(I.getOperand(0)))
487 if (Op->getOpcode() == Opcode && isa<Constant>(Op->getOperand(1))) {
488 if (isa<Constant>(I.getOperand(1))) {
Chris Lattner2a9c8472003-05-27 16:40:51 +0000489 Constant *Folded = ConstantExpr::get(I.getOpcode(),
490 cast<Constant>(I.getOperand(1)),
491 cast<Constant>(Op->getOperand(1)));
Chris Lattnerc8802d22003-03-11 00:12:48 +0000492 I.setOperand(0, Op->getOperand(0));
493 I.setOperand(1, Folded);
494 return true;
495 } else if (BinaryOperator *Op1=dyn_cast<BinaryOperator>(I.getOperand(1)))
496 if (Op1->getOpcode() == Opcode && isa<Constant>(Op1->getOperand(1)) &&
497 isOnlyUse(Op) && isOnlyUse(Op1)) {
498 Constant *C1 = cast<Constant>(Op->getOperand(1));
499 Constant *C2 = cast<Constant>(Op1->getOperand(1));
500
501 // Fold (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
Chris Lattner2a9c8472003-05-27 16:40:51 +0000502 Constant *Folded = ConstantExpr::get(I.getOpcode(), C1, C2);
Chris Lattnerc8802d22003-03-11 00:12:48 +0000503 Instruction *New = BinaryOperator::create(Opcode, Op->getOperand(0),
504 Op1->getOperand(0),
505 Op1->getName(), &I);
Chris Lattnerdbab3862007-03-02 21:28:56 +0000506 AddToWorkList(New);
Chris Lattnerc8802d22003-03-11 00:12:48 +0000507 I.setOperand(0, New);
508 I.setOperand(1, Folded);
509 return true;
Misha Brukmanfd939082005-04-21 23:48:37 +0000510 }
Chris Lattner4f98c562003-03-10 21:43:22 +0000511 }
Chris Lattner4f98c562003-03-10 21:43:22 +0000512 return Changed;
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000513}
Chris Lattner8a2a3112001-12-14 16:52:21 +0000514
Reid Spencere4d87aa2006-12-23 06:05:41 +0000515/// SimplifyCompare - For a CmpInst this function just orders the operands
516/// so that theyare listed from right (least complex) to left (most complex).
517/// This puts constants before unary operators before binary operators.
518bool InstCombiner::SimplifyCompare(CmpInst &I) {
519 if (getComplexity(I.getOperand(0)) >= getComplexity(I.getOperand(1)))
520 return false;
521 I.swapOperands();
522 // Compare instructions are not associative so there's nothing else we can do.
523 return true;
524}
525
Chris Lattner8d969642003-03-10 23:06:50 +0000526// dyn_castNegVal - Given a 'sub' instruction, return the RHS of the instruction
527// if the LHS is a constant zero (which is the 'negate' form).
Chris Lattnerb35dde12002-05-06 16:49:18 +0000528//
Chris Lattner8d969642003-03-10 23:06:50 +0000529static inline Value *dyn_castNegVal(Value *V) {
530 if (BinaryOperator::isNeg(V))
Chris Lattnera1df33c2005-04-24 07:30:14 +0000531 return BinaryOperator::getNegArgument(V);
Chris Lattner8d969642003-03-10 23:06:50 +0000532
Chris Lattner0ce85802004-12-14 20:08:06 +0000533 // Constants can be considered to be negated values if they can be folded.
534 if (ConstantInt *C = dyn_cast<ConstantInt>(V))
535 return ConstantExpr::getNeg(C);
Chris Lattner8d969642003-03-10 23:06:50 +0000536 return 0;
Chris Lattnerb35dde12002-05-06 16:49:18 +0000537}
538
Chris Lattner8d969642003-03-10 23:06:50 +0000539static inline Value *dyn_castNotVal(Value *V) {
540 if (BinaryOperator::isNot(V))
Chris Lattnera1df33c2005-04-24 07:30:14 +0000541 return BinaryOperator::getNotArgument(V);
Chris Lattner8d969642003-03-10 23:06:50 +0000542
543 // Constants can be considered to be not'ed values...
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +0000544 if (ConstantInt *C = dyn_cast<ConstantInt>(V))
Zhou Sheng4a1822a2007-04-02 13:45:30 +0000545 return ConstantInt::get(~C->getValue());
Chris Lattner8d969642003-03-10 23:06:50 +0000546 return 0;
547}
548
Chris Lattnerc8802d22003-03-11 00:12:48 +0000549// dyn_castFoldableMul - If this value is a multiply that can be folded into
550// other computations (because it has a constant operand), return the
Chris Lattner50af16a2004-11-13 19:50:12 +0000551// non-constant operand of the multiply, and set CST to point to the multiplier.
552// Otherwise, return null.
Chris Lattnerc8802d22003-03-11 00:12:48 +0000553//
Chris Lattner50af16a2004-11-13 19:50:12 +0000554static inline Value *dyn_castFoldableMul(Value *V, ConstantInt *&CST) {
Chris Lattner42a75512007-01-15 02:27:26 +0000555 if (V->hasOneUse() && V->getType()->isInteger())
Chris Lattner50af16a2004-11-13 19:50:12 +0000556 if (Instruction *I = dyn_cast<Instruction>(V)) {
Chris Lattnerc8802d22003-03-11 00:12:48 +0000557 if (I->getOpcode() == Instruction::Mul)
Chris Lattner50e60c72004-11-15 05:54:07 +0000558 if ((CST = dyn_cast<ConstantInt>(I->getOperand(1))))
Chris Lattnerc8802d22003-03-11 00:12:48 +0000559 return I->getOperand(0);
Chris Lattner50af16a2004-11-13 19:50:12 +0000560 if (I->getOpcode() == Instruction::Shl)
Chris Lattner50e60c72004-11-15 05:54:07 +0000561 if ((CST = dyn_cast<ConstantInt>(I->getOperand(1)))) {
Chris Lattner50af16a2004-11-13 19:50:12 +0000562 // The multiplier is really 1 << CST.
Zhou Sheng97b52c22007-03-29 01:57:21 +0000563 uint32_t BitWidth = cast<IntegerType>(V->getType())->getBitWidth();
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +0000564 uint32_t CSTVal = CST->getLimitedValue(BitWidth);
Zhou Sheng97b52c22007-03-29 01:57:21 +0000565 CST = ConstantInt::get(APInt(BitWidth, 1).shl(CSTVal));
Chris Lattner50af16a2004-11-13 19:50:12 +0000566 return I->getOperand(0);
567 }
568 }
Chris Lattnerc8802d22003-03-11 00:12:48 +0000569 return 0;
Chris Lattnera2881962003-02-18 19:28:33 +0000570}
Chris Lattneraf2930e2002-08-14 17:51:49 +0000571
Chris Lattner574da9b2005-01-13 20:14:25 +0000572/// dyn_castGetElementPtr - If this is a getelementptr instruction or constant
573/// expression, return it.
574static User *dyn_castGetElementPtr(Value *V) {
575 if (isa<GetElementPtrInst>(V)) return cast<User>(V);
576 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
577 if (CE->getOpcode() == Instruction::GetElementPtr)
578 return cast<User>(V);
579 return false;
580}
581
Reid Spencer7177c3a2007-03-25 05:33:51 +0000582/// AddOne - Add one to a ConstantInt
Chris Lattnera96879a2004-09-29 17:40:11 +0000583static ConstantInt *AddOne(ConstantInt *C) {
Reid Spencer2149a9d2007-03-25 19:55:33 +0000584 APInt Val(C->getValue());
585 return ConstantInt::get(++Val);
Chris Lattner955f3312004-09-28 21:48:02 +0000586}
Reid Spencer7177c3a2007-03-25 05:33:51 +0000587/// SubOne - Subtract one from a ConstantInt
Chris Lattnera96879a2004-09-29 17:40:11 +0000588static ConstantInt *SubOne(ConstantInt *C) {
Reid Spencer2149a9d2007-03-25 19:55:33 +0000589 APInt Val(C->getValue());
590 return ConstantInt::get(--Val);
Reid Spencer7177c3a2007-03-25 05:33:51 +0000591}
592/// Add - Add two ConstantInts together
593static ConstantInt *Add(ConstantInt *C1, ConstantInt *C2) {
594 return ConstantInt::get(C1->getValue() + C2->getValue());
595}
596/// And - Bitwise AND two ConstantInts together
597static ConstantInt *And(ConstantInt *C1, ConstantInt *C2) {
598 return ConstantInt::get(C1->getValue() & C2->getValue());
599}
600/// Subtract - Subtract one ConstantInt from another
601static ConstantInt *Subtract(ConstantInt *C1, ConstantInt *C2) {
602 return ConstantInt::get(C1->getValue() - C2->getValue());
603}
604/// Multiply - Multiply two ConstantInts together
605static ConstantInt *Multiply(ConstantInt *C1, ConstantInt *C2) {
606 return ConstantInt::get(C1->getValue() * C2->getValue());
Chris Lattner955f3312004-09-28 21:48:02 +0000607}
Nick Lewyckye0cfecf2008-02-18 22:48:05 +0000608/// MultiplyOverflows - True if the multiply can not be expressed in an int
609/// this size.
610static bool MultiplyOverflows(ConstantInt *C1, ConstantInt *C2, bool sign) {
611 uint32_t W = C1->getBitWidth();
612 APInt LHSExt = C1->getValue(), RHSExt = C2->getValue();
613 if (sign) {
614 LHSExt.sext(W * 2);
615 RHSExt.sext(W * 2);
616 } else {
617 LHSExt.zext(W * 2);
618 RHSExt.zext(W * 2);
619 }
620
621 APInt MulExt = LHSExt * RHSExt;
622
623 if (sign) {
624 APInt Min = APInt::getSignedMinValue(W).sext(W * 2);
625 APInt Max = APInt::getSignedMaxValue(W).sext(W * 2);
626 return MulExt.slt(Min) || MulExt.sgt(Max);
627 } else
628 return MulExt.ugt(APInt::getLowBitsSet(W * 2, W));
629}
Chris Lattner955f3312004-09-28 21:48:02 +0000630
Chris Lattner68d5ff22006-02-09 07:38:58 +0000631/// ComputeMaskedBits - Determine which of the bits specified in Mask are
632/// known to be either zero or one and return them in the KnownZero/KnownOne
Reid Spencer3e7594f2007-03-08 01:46:38 +0000633/// bit sets. This code only analyzes bits in Mask, in order to short-circuit
634/// processing.
635/// NOTE: we cannot consider 'undef' to be "IsZero" here. The problem is that
636/// we cannot optimize based on the assumption that it is zero without changing
637/// it to be an explicit zero. If we don't change it to zero, other code could
638/// optimized based on the contradictory assumption that it is non-zero.
639/// Because instcombine aggressively folds operations with undef args anyway,
640/// this won't lose us code quality.
Reid Spencer55702aa2007-03-25 21:11:44 +0000641static void ComputeMaskedBits(Value *V, const APInt &Mask, APInt& KnownZero,
Reid Spencer3e7594f2007-03-08 01:46:38 +0000642 APInt& KnownOne, unsigned Depth = 0) {
Zhou Sheng771dbf72007-03-13 02:23:10 +0000643 assert(V && "No Value?");
644 assert(Depth <= 6 && "Limit Search Depth");
Reid Spencer3e7594f2007-03-08 01:46:38 +0000645 uint32_t BitWidth = Mask.getBitWidth();
Zhou Shengaa305ab2007-03-28 02:19:03 +0000646 assert(cast<IntegerType>(V->getType())->getBitWidth() == BitWidth &&
Zhou Sheng771dbf72007-03-13 02:23:10 +0000647 KnownZero.getBitWidth() == BitWidth &&
Reid Spencer3e7594f2007-03-08 01:46:38 +0000648 KnownOne.getBitWidth() == BitWidth &&
Zhou Shengaa305ab2007-03-28 02:19:03 +0000649 "V, Mask, KnownOne and KnownZero should have same BitWidth");
Reid Spencer3e7594f2007-03-08 01:46:38 +0000650 if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
651 // We know all of the bits for a constant!
Zhou Sheng771dbf72007-03-13 02:23:10 +0000652 KnownOne = CI->getValue() & Mask;
Reid Spencer3e7594f2007-03-08 01:46:38 +0000653 KnownZero = ~KnownOne & Mask;
654 return;
655 }
656
Reid Spencer3e7594f2007-03-08 01:46:38 +0000657 if (Depth == 6 || Mask == 0)
658 return; // Limit search depth.
659
660 Instruction *I = dyn_cast<Instruction>(V);
661 if (!I) return;
662
Zhou Sheng771dbf72007-03-13 02:23:10 +0000663 KnownZero.clear(); KnownOne.clear(); // Don't know anything.
Reid Spencer3e7594f2007-03-08 01:46:38 +0000664 APInt KnownZero2(KnownZero), KnownOne2(KnownOne);
Reid Spencer3e7594f2007-03-08 01:46:38 +0000665
666 switch (I->getOpcode()) {
Reid Spencer2b812072007-03-25 02:03:12 +0000667 case Instruction::And: {
Reid Spencer3e7594f2007-03-08 01:46:38 +0000668 // If either the LHS or the RHS are Zero, the result is zero.
669 ComputeMaskedBits(I->getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
Reid Spencer2b812072007-03-25 02:03:12 +0000670 APInt Mask2(Mask & ~KnownZero);
671 ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero2, KnownOne2, Depth+1);
Reid Spencer3e7594f2007-03-08 01:46:38 +0000672 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
673 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
674
675 // Output known-1 bits are only known if set in both the LHS & RHS.
676 KnownOne &= KnownOne2;
677 // Output known-0 are known to be clear if zero in either the LHS | RHS.
678 KnownZero |= KnownZero2;
679 return;
Reid Spencer2b812072007-03-25 02:03:12 +0000680 }
681 case Instruction::Or: {
Reid Spencer3e7594f2007-03-08 01:46:38 +0000682 ComputeMaskedBits(I->getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
Reid Spencer2b812072007-03-25 02:03:12 +0000683 APInt Mask2(Mask & ~KnownOne);
684 ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero2, KnownOne2, Depth+1);
Reid Spencer3e7594f2007-03-08 01:46:38 +0000685 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
686 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
687
688 // Output known-0 bits are only known if clear in both the LHS & RHS.
689 KnownZero &= KnownZero2;
690 // Output known-1 are known to be set if set in either the LHS | RHS.
691 KnownOne |= KnownOne2;
692 return;
Reid Spencer2b812072007-03-25 02:03:12 +0000693 }
Reid Spencer3e7594f2007-03-08 01:46:38 +0000694 case Instruction::Xor: {
695 ComputeMaskedBits(I->getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
696 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero2, KnownOne2, Depth+1);
697 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
698 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
699
700 // Output known-0 bits are known if clear or set in both the LHS & RHS.
701 APInt KnownZeroOut = (KnownZero & KnownZero2) | (KnownOne & KnownOne2);
702 // Output known-1 are known to be set if set in only one of the LHS, RHS.
703 KnownOne = (KnownZero & KnownOne2) | (KnownOne & KnownZero2);
704 KnownZero = KnownZeroOut;
705 return;
706 }
707 case Instruction::Select:
708 ComputeMaskedBits(I->getOperand(2), Mask, KnownZero, KnownOne, Depth+1);
709 ComputeMaskedBits(I->getOperand(1), Mask, KnownZero2, KnownOne2, Depth+1);
710 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
711 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
712
713 // Only known if known in both the LHS and RHS.
714 KnownOne &= KnownOne2;
715 KnownZero &= KnownZero2;
716 return;
717 case Instruction::FPTrunc:
718 case Instruction::FPExt:
719 case Instruction::FPToUI:
720 case Instruction::FPToSI:
721 case Instruction::SIToFP:
722 case Instruction::PtrToInt:
723 case Instruction::UIToFP:
724 case Instruction::IntToPtr:
725 return; // Can't work with floating point or pointers
Zhou Sheng771dbf72007-03-13 02:23:10 +0000726 case Instruction::Trunc: {
Reid Spencer3e7594f2007-03-08 01:46:38 +0000727 // All these have integer operands
Zhou Sheng771dbf72007-03-13 02:23:10 +0000728 uint32_t SrcBitWidth =
729 cast<IntegerType>(I->getOperand(0)->getType())->getBitWidth();
Zhou Shengaa305ab2007-03-28 02:19:03 +0000730 APInt MaskIn(Mask);
731 MaskIn.zext(SrcBitWidth);
732 KnownZero.zext(SrcBitWidth);
733 KnownOne.zext(SrcBitWidth);
734 ComputeMaskedBits(I->getOperand(0), MaskIn, KnownZero, KnownOne, Depth+1);
Zhou Sheng771dbf72007-03-13 02:23:10 +0000735 KnownZero.trunc(BitWidth);
736 KnownOne.trunc(BitWidth);
Reid Spencer3e7594f2007-03-08 01:46:38 +0000737 return;
Zhou Sheng771dbf72007-03-13 02:23:10 +0000738 }
Reid Spencer3e7594f2007-03-08 01:46:38 +0000739 case Instruction::BitCast: {
740 const Type *SrcTy = I->getOperand(0)->getType();
741 if (SrcTy->isInteger()) {
742 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero, KnownOne, Depth+1);
743 return;
744 }
745 break;
746 }
747 case Instruction::ZExt: {
748 // Compute the bits in the result that are not present in the input.
749 const IntegerType *SrcTy = cast<IntegerType>(I->getOperand(0)->getType());
Zhou Sheng771dbf72007-03-13 02:23:10 +0000750 uint32_t SrcBitWidth = SrcTy->getBitWidth();
Reid Spencer2f549172007-03-25 04:26:16 +0000751
Zhou Shengaa305ab2007-03-28 02:19:03 +0000752 APInt MaskIn(Mask);
753 MaskIn.trunc(SrcBitWidth);
754 KnownZero.trunc(SrcBitWidth);
755 KnownOne.trunc(SrcBitWidth);
756 ComputeMaskedBits(I->getOperand(0), MaskIn, KnownZero, KnownOne, Depth+1);
Reid Spencer3e7594f2007-03-08 01:46:38 +0000757 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
758 // The top bits are known to be zero.
Zhou Sheng771dbf72007-03-13 02:23:10 +0000759 KnownZero.zext(BitWidth);
760 KnownOne.zext(BitWidth);
Zhou Shengaa305ab2007-03-28 02:19:03 +0000761 KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
Reid Spencer3e7594f2007-03-08 01:46:38 +0000762 return;
763 }
764 case Instruction::SExt: {
765 // Compute the bits in the result that are not present in the input.
766 const IntegerType *SrcTy = cast<IntegerType>(I->getOperand(0)->getType());
Zhou Sheng771dbf72007-03-13 02:23:10 +0000767 uint32_t SrcBitWidth = SrcTy->getBitWidth();
Reid Spencer2f549172007-03-25 04:26:16 +0000768
Zhou Shengaa305ab2007-03-28 02:19:03 +0000769 APInt MaskIn(Mask);
770 MaskIn.trunc(SrcBitWidth);
771 KnownZero.trunc(SrcBitWidth);
772 KnownOne.trunc(SrcBitWidth);
773 ComputeMaskedBits(I->getOperand(0), MaskIn, KnownZero, KnownOne, Depth+1);
Reid Spencer3e7594f2007-03-08 01:46:38 +0000774 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
Zhou Sheng771dbf72007-03-13 02:23:10 +0000775 KnownZero.zext(BitWidth);
776 KnownOne.zext(BitWidth);
Reid Spencer3e7594f2007-03-08 01:46:38 +0000777
778 // If the sign bit of the input is known set or clear, then we know the
779 // top bits of the result.
Zhou Shengaa305ab2007-03-28 02:19:03 +0000780 if (KnownZero[SrcBitWidth-1]) // Input sign bit known zero
Zhou Sheng34a4b382007-03-28 17:38:21 +0000781 KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
Zhou Shengaa305ab2007-03-28 02:19:03 +0000782 else if (KnownOne[SrcBitWidth-1]) // Input sign bit known set
Zhou Sheng34a4b382007-03-28 17:38:21 +0000783 KnownOne |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
Reid Spencer3e7594f2007-03-08 01:46:38 +0000784 return;
785 }
786 case Instruction::Shl:
787 // (shl X, C1) & C2 == 0 iff (X & C2 >>u C1) == 0
788 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +0000789 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
Reid Spencer2b812072007-03-25 02:03:12 +0000790 APInt Mask2(Mask.lshr(ShiftAmt));
791 ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero, KnownOne, Depth+1);
Reid Spencer3e7594f2007-03-08 01:46:38 +0000792 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
Zhou Sheng430f6262007-03-12 05:44:52 +0000793 KnownZero <<= ShiftAmt;
794 KnownOne <<= ShiftAmt;
Reid Spencer2149a9d2007-03-25 19:55:33 +0000795 KnownZero |= APInt::getLowBitsSet(BitWidth, ShiftAmt); // low bits known 0
Reid Spencer3e7594f2007-03-08 01:46:38 +0000796 return;
797 }
798 break;
799 case Instruction::LShr:
800 // (ushr X, C1) & C2 == 0 iff (-1 >> C1) & C2 == 0
801 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
802 // Compute the new bits that are at the top now.
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +0000803 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
Reid Spencer3e7594f2007-03-08 01:46:38 +0000804
805 // Unsigned shift right.
Reid Spencer2b812072007-03-25 02:03:12 +0000806 APInt Mask2(Mask.shl(ShiftAmt));
807 ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero,KnownOne,Depth+1);
Reid Spencer3e7594f2007-03-08 01:46:38 +0000808 assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?");
809 KnownZero = APIntOps::lshr(KnownZero, ShiftAmt);
810 KnownOne = APIntOps::lshr(KnownOne, ShiftAmt);
Zhou Shengaa305ab2007-03-28 02:19:03 +0000811 // high bits known zero.
812 KnownZero |= APInt::getHighBitsSet(BitWidth, ShiftAmt);
Reid Spencer3e7594f2007-03-08 01:46:38 +0000813 return;
814 }
815 break;
816 case Instruction::AShr:
Zhou Shengaa305ab2007-03-28 02:19:03 +0000817 // (ashr X, C1) & C2 == 0 iff (-1 >> C1) & C2 == 0
Reid Spencer3e7594f2007-03-08 01:46:38 +0000818 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
819 // Compute the new bits that are at the top now.
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +0000820 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
Reid Spencer3e7594f2007-03-08 01:46:38 +0000821
822 // Signed shift right.
Reid Spencer2b812072007-03-25 02:03:12 +0000823 APInt Mask2(Mask.shl(ShiftAmt));
824 ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero,KnownOne,Depth+1);
Reid Spencer3e7594f2007-03-08 01:46:38 +0000825 assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?");
826 KnownZero = APIntOps::lshr(KnownZero, ShiftAmt);
827 KnownOne = APIntOps::lshr(KnownOne, ShiftAmt);
828
Zhou Shengaa305ab2007-03-28 02:19:03 +0000829 APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
830 if (KnownZero[BitWidth-ShiftAmt-1]) // New bits are known zero.
Reid Spencer3e7594f2007-03-08 01:46:38 +0000831 KnownZero |= HighBits;
Zhou Shengaa305ab2007-03-28 02:19:03 +0000832 else if (KnownOne[BitWidth-ShiftAmt-1]) // New bits are known one.
Reid Spencer3e7594f2007-03-08 01:46:38 +0000833 KnownOne |= HighBits;
Reid Spencer3e7594f2007-03-08 01:46:38 +0000834 return;
835 }
836 break;
837 }
838}
839
Reid Spencere7816b52007-03-08 01:52:58 +0000840/// MaskedValueIsZero - Return true if 'V & Mask' is known to be zero. We use
841/// this predicate to simplify operations downstream. Mask is known to be zero
842/// for bits that V cannot have.
843static bool MaskedValueIsZero(Value *V, const APInt& Mask, unsigned Depth = 0) {
Zhou Shengedd089c2007-03-12 16:54:56 +0000844 APInt KnownZero(Mask.getBitWidth(), 0), KnownOne(Mask.getBitWidth(), 0);
Reid Spencere7816b52007-03-08 01:52:58 +0000845 ComputeMaskedBits(V, Mask, KnownZero, KnownOne, Depth);
846 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
847 return (KnownZero & Mask) == Mask;
848}
849
Chris Lattner255d8912006-02-11 09:31:47 +0000850/// ShrinkDemandedConstant - Check to see if the specified operand of the
851/// specified instruction is a constant integer. If so, check to see if there
852/// are any bits set in the constant that are not demanded. If so, shrink the
853/// constant and return true.
854static bool ShrinkDemandedConstant(Instruction *I, unsigned OpNo,
Reid Spencer6b79e2d2007-03-12 17:15:10 +0000855 APInt Demanded) {
856 assert(I && "No instruction?");
857 assert(OpNo < I->getNumOperands() && "Operand index too large");
858
859 // If the operand is not a constant integer, nothing to do.
860 ConstantInt *OpC = dyn_cast<ConstantInt>(I->getOperand(OpNo));
861 if (!OpC) return false;
862
863 // If there are no bits set that aren't demanded, nothing to do.
864 Demanded.zextOrTrunc(OpC->getValue().getBitWidth());
865 if ((~Demanded & OpC->getValue()) == 0)
866 return false;
867
868 // This instruction is producing bits that are not demanded. Shrink the RHS.
869 Demanded &= OpC->getValue();
870 I->setOperand(OpNo, ConstantInt::get(Demanded));
871 return true;
872}
873
Chris Lattnerbf5d8a82006-02-12 02:07:56 +0000874// ComputeSignedMinMaxValuesFromKnownBits - Given a signed integer type and a
875// set of known zero and one bits, compute the maximum and minimum values that
876// could have the specified known zero and known one bits, returning them in
877// min/max.
878static void ComputeSignedMinMaxValuesFromKnownBits(const Type *Ty,
Reid Spencer0460fb32007-03-22 20:36:03 +0000879 const APInt& KnownZero,
880 const APInt& KnownOne,
881 APInt& Min, APInt& Max) {
882 uint32_t BitWidth = cast<IntegerType>(Ty)->getBitWidth();
883 assert(KnownZero.getBitWidth() == BitWidth &&
884 KnownOne.getBitWidth() == BitWidth &&
885 Min.getBitWidth() == BitWidth && Max.getBitWidth() == BitWidth &&
886 "Ty, KnownZero, KnownOne and Min, Max must have equal bitwidth.");
Reid Spencer2f549172007-03-25 04:26:16 +0000887 APInt UnknownBits = ~(KnownZero|KnownOne);
Chris Lattnerbf5d8a82006-02-12 02:07:56 +0000888
Chris Lattnerbf5d8a82006-02-12 02:07:56 +0000889 // The minimum value is when all unknown bits are zeros, EXCEPT for the sign
890 // bit if it is unknown.
891 Min = KnownOne;
892 Max = KnownOne|UnknownBits;
893
Zhou Sheng4acf1552007-03-28 05:15:57 +0000894 if (UnknownBits[BitWidth-1]) { // Sign bit is unknown
Zhou Sheng4a1822a2007-04-02 13:45:30 +0000895 Min.set(BitWidth-1);
896 Max.clear(BitWidth-1);
Chris Lattnerbf5d8a82006-02-12 02:07:56 +0000897 }
Chris Lattnerbf5d8a82006-02-12 02:07:56 +0000898}
899
900// ComputeUnsignedMinMaxValuesFromKnownBits - Given an unsigned integer type and
901// a set of known zero and one bits, compute the maximum and minimum values that
902// could have the specified known zero and known one bits, returning them in
903// min/max.
904static void ComputeUnsignedMinMaxValuesFromKnownBits(const Type *Ty,
Chris Lattnera9ff5eb2007-08-05 08:47:58 +0000905 const APInt &KnownZero,
906 const APInt &KnownOne,
907 APInt &Min, APInt &Max) {
908 uint32_t BitWidth = cast<IntegerType>(Ty)->getBitWidth(); BitWidth = BitWidth;
Reid Spencer0460fb32007-03-22 20:36:03 +0000909 assert(KnownZero.getBitWidth() == BitWidth &&
910 KnownOne.getBitWidth() == BitWidth &&
911 Min.getBitWidth() == BitWidth && Max.getBitWidth() &&
912 "Ty, KnownZero, KnownOne and Min, Max must have equal bitwidth.");
Reid Spencer2f549172007-03-25 04:26:16 +0000913 APInt UnknownBits = ~(KnownZero|KnownOne);
Chris Lattnerbf5d8a82006-02-12 02:07:56 +0000914
915 // The minimum value is when the unknown bits are all zeros.
916 Min = KnownOne;
917 // The maximum value is when the unknown bits are all ones.
918 Max = KnownOne|UnknownBits;
919}
Chris Lattner255d8912006-02-11 09:31:47 +0000920
Reid Spencer8cb68342007-03-12 17:25:59 +0000921/// SimplifyDemandedBits - This function attempts to replace V with a simpler
922/// value based on the demanded bits. When this function is called, it is known
923/// that only the bits set in DemandedMask of the result of V are ever used
924/// downstream. Consequently, depending on the mask and V, it may be possible
925/// to replace V with a constant or one of its operands. In such cases, this
926/// function does the replacement and returns true. In all other cases, it
927/// returns false after analyzing the expression and setting KnownOne and known
928/// to be one in the expression. KnownZero contains all the bits that are known
929/// to be zero in the expression. These are provided to potentially allow the
930/// caller (which might recursively be SimplifyDemandedBits itself) to simplify
931/// the expression. KnownOne and KnownZero always follow the invariant that
932/// KnownOne & KnownZero == 0. That is, a bit can't be both 1 and 0. Note that
933/// the bits in KnownOne and KnownZero may only be accurate for those bits set
934/// in DemandedMask. Note also that the bitwidth of V, DemandedMask, KnownZero
935/// and KnownOne must all be the same.
936bool InstCombiner::SimplifyDemandedBits(Value *V, APInt DemandedMask,
937 APInt& KnownZero, APInt& KnownOne,
938 unsigned Depth) {
939 assert(V != 0 && "Null pointer of Value???");
940 assert(Depth <= 6 && "Limit Search Depth");
941 uint32_t BitWidth = DemandedMask.getBitWidth();
942 const IntegerType *VTy = cast<IntegerType>(V->getType());
943 assert(VTy->getBitWidth() == BitWidth &&
944 KnownZero.getBitWidth() == BitWidth &&
945 KnownOne.getBitWidth() == BitWidth &&
946 "Value *V, DemandedMask, KnownZero and KnownOne \
947 must have same BitWidth");
948 if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
949 // We know all of the bits for a constant!
950 KnownOne = CI->getValue() & DemandedMask;
951 KnownZero = ~KnownOne & DemandedMask;
952 return false;
953 }
954
Zhou Sheng96704452007-03-14 03:21:24 +0000955 KnownZero.clear();
956 KnownOne.clear();
Reid Spencer8cb68342007-03-12 17:25:59 +0000957 if (!V->hasOneUse()) { // Other users may use these bits.
958 if (Depth != 0) { // Not at the root.
959 // Just compute the KnownZero/KnownOne bits to simplify things downstream.
960 ComputeMaskedBits(V, DemandedMask, KnownZero, KnownOne, Depth);
961 return false;
962 }
963 // If this is the root being simplified, allow it to have multiple uses,
964 // just set the DemandedMask to all bits.
965 DemandedMask = APInt::getAllOnesValue(BitWidth);
966 } else if (DemandedMask == 0) { // Not demanding any bits from V.
967 if (V != UndefValue::get(VTy))
968 return UpdateValueUsesWith(V, UndefValue::get(VTy));
969 return false;
970 } else if (Depth == 6) { // Limit search depth.
971 return false;
972 }
973
974 Instruction *I = dyn_cast<Instruction>(V);
975 if (!I) return false; // Only analyze instructions.
976
Reid Spencer8cb68342007-03-12 17:25:59 +0000977 APInt LHSKnownZero(BitWidth, 0), LHSKnownOne(BitWidth, 0);
978 APInt &RHSKnownZero = KnownZero, &RHSKnownOne = KnownOne;
979 switch (I->getOpcode()) {
980 default: break;
981 case Instruction::And:
982 // If either the LHS or the RHS are Zero, the result is zero.
983 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
984 RHSKnownZero, RHSKnownOne, Depth+1))
985 return true;
986 assert((RHSKnownZero & RHSKnownOne) == 0 &&
987 "Bits known to be one AND zero?");
988
989 // If something is known zero on the RHS, the bits aren't demanded on the
990 // LHS.
991 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask & ~RHSKnownZero,
992 LHSKnownZero, LHSKnownOne, Depth+1))
993 return true;
994 assert((LHSKnownZero & LHSKnownOne) == 0 &&
995 "Bits known to be one AND zero?");
996
997 // If all of the demanded bits are known 1 on one side, return the other.
998 // These bits cannot contribute to the result of the 'and'.
999 if ((DemandedMask & ~LHSKnownZero & RHSKnownOne) ==
1000 (DemandedMask & ~LHSKnownZero))
1001 return UpdateValueUsesWith(I, I->getOperand(0));
1002 if ((DemandedMask & ~RHSKnownZero & LHSKnownOne) ==
1003 (DemandedMask & ~RHSKnownZero))
1004 return UpdateValueUsesWith(I, I->getOperand(1));
1005
1006 // If all of the demanded bits in the inputs are known zeros, return zero.
1007 if ((DemandedMask & (RHSKnownZero|LHSKnownZero)) == DemandedMask)
1008 return UpdateValueUsesWith(I, Constant::getNullValue(VTy));
1009
1010 // If the RHS is a constant, see if we can simplify it.
1011 if (ShrinkDemandedConstant(I, 1, DemandedMask & ~LHSKnownZero))
1012 return UpdateValueUsesWith(I, I);
1013
1014 // Output known-1 bits are only known if set in both the LHS & RHS.
1015 RHSKnownOne &= LHSKnownOne;
1016 // Output known-0 are known to be clear if zero in either the LHS | RHS.
1017 RHSKnownZero |= LHSKnownZero;
1018 break;
1019 case Instruction::Or:
1020 // If either the LHS or the RHS are One, the result is One.
1021 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
1022 RHSKnownZero, RHSKnownOne, Depth+1))
1023 return true;
1024 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1025 "Bits known to be one AND zero?");
1026 // If something is known one on the RHS, the bits aren't demanded on the
1027 // LHS.
1028 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask & ~RHSKnownOne,
1029 LHSKnownZero, LHSKnownOne, Depth+1))
1030 return true;
1031 assert((LHSKnownZero & LHSKnownOne) == 0 &&
1032 "Bits known to be one AND zero?");
1033
1034 // If all of the demanded bits are known zero on one side, return the other.
1035 // These bits cannot contribute to the result of the 'or'.
1036 if ((DemandedMask & ~LHSKnownOne & RHSKnownZero) ==
1037 (DemandedMask & ~LHSKnownOne))
1038 return UpdateValueUsesWith(I, I->getOperand(0));
1039 if ((DemandedMask & ~RHSKnownOne & LHSKnownZero) ==
1040 (DemandedMask & ~RHSKnownOne))
1041 return UpdateValueUsesWith(I, I->getOperand(1));
1042
1043 // If all of the potentially set bits on one side are known to be set on
1044 // the other side, just use the 'other' side.
1045 if ((DemandedMask & (~RHSKnownZero) & LHSKnownOne) ==
1046 (DemandedMask & (~RHSKnownZero)))
1047 return UpdateValueUsesWith(I, I->getOperand(0));
1048 if ((DemandedMask & (~LHSKnownZero) & RHSKnownOne) ==
1049 (DemandedMask & (~LHSKnownZero)))
1050 return UpdateValueUsesWith(I, I->getOperand(1));
1051
1052 // If the RHS is a constant, see if we can simplify it.
1053 if (ShrinkDemandedConstant(I, 1, DemandedMask))
1054 return UpdateValueUsesWith(I, I);
1055
1056 // Output known-0 bits are only known if clear in both the LHS & RHS.
1057 RHSKnownZero &= LHSKnownZero;
1058 // Output known-1 are known to be set if set in either the LHS | RHS.
1059 RHSKnownOne |= LHSKnownOne;
1060 break;
1061 case Instruction::Xor: {
1062 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
1063 RHSKnownZero, RHSKnownOne, Depth+1))
1064 return true;
1065 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1066 "Bits known to be one AND zero?");
1067 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
1068 LHSKnownZero, LHSKnownOne, Depth+1))
1069 return true;
1070 assert((LHSKnownZero & LHSKnownOne) == 0 &&
1071 "Bits known to be one AND zero?");
1072
1073 // If all of the demanded bits are known zero on one side, return the other.
1074 // These bits cannot contribute to the result of the 'xor'.
1075 if ((DemandedMask & RHSKnownZero) == DemandedMask)
1076 return UpdateValueUsesWith(I, I->getOperand(0));
1077 if ((DemandedMask & LHSKnownZero) == DemandedMask)
1078 return UpdateValueUsesWith(I, I->getOperand(1));
1079
1080 // Output known-0 bits are known if clear or set in both the LHS & RHS.
1081 APInt KnownZeroOut = (RHSKnownZero & LHSKnownZero) |
1082 (RHSKnownOne & LHSKnownOne);
1083 // Output known-1 are known to be set if set in only one of the LHS, RHS.
1084 APInt KnownOneOut = (RHSKnownZero & LHSKnownOne) |
1085 (RHSKnownOne & LHSKnownZero);
1086
1087 // If all of the demanded bits are known to be zero on one side or the
1088 // other, turn this into an *inclusive* or.
1089 // e.g. (A & C1)^(B & C2) -> (A & C1)|(B & C2) iff C1&C2 == 0
1090 if ((DemandedMask & ~RHSKnownZero & ~LHSKnownZero) == 0) {
1091 Instruction *Or =
1092 BinaryOperator::createOr(I->getOperand(0), I->getOperand(1),
1093 I->getName());
1094 InsertNewInstBefore(Or, *I);
1095 return UpdateValueUsesWith(I, Or);
1096 }
1097
1098 // If all of the demanded bits on one side are known, and all of the set
1099 // bits on that side are also known to be set on the other side, turn this
1100 // into an AND, as we know the bits will be cleared.
1101 // e.g. (X | C1) ^ C2 --> (X | C1) & ~C2 iff (C1&C2) == C2
1102 if ((DemandedMask & (RHSKnownZero|RHSKnownOne)) == DemandedMask) {
1103 // all known
1104 if ((RHSKnownOne & LHSKnownOne) == RHSKnownOne) {
1105 Constant *AndC = ConstantInt::get(~RHSKnownOne & DemandedMask);
1106 Instruction *And =
1107 BinaryOperator::createAnd(I->getOperand(0), AndC, "tmp");
1108 InsertNewInstBefore(And, *I);
1109 return UpdateValueUsesWith(I, And);
1110 }
1111 }
1112
1113 // If the RHS is a constant, see if we can simplify it.
1114 // FIXME: for XOR, we prefer to force bits to 1 if they will make a -1.
1115 if (ShrinkDemandedConstant(I, 1, DemandedMask))
1116 return UpdateValueUsesWith(I, I);
1117
1118 RHSKnownZero = KnownZeroOut;
1119 RHSKnownOne = KnownOneOut;
1120 break;
1121 }
1122 case Instruction::Select:
1123 if (SimplifyDemandedBits(I->getOperand(2), DemandedMask,
1124 RHSKnownZero, RHSKnownOne, Depth+1))
1125 return true;
1126 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
1127 LHSKnownZero, LHSKnownOne, Depth+1))
1128 return true;
1129 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1130 "Bits known to be one AND zero?");
1131 assert((LHSKnownZero & LHSKnownOne) == 0 &&
1132 "Bits known to be one AND zero?");
1133
1134 // If the operands are constants, see if we can simplify them.
1135 if (ShrinkDemandedConstant(I, 1, DemandedMask))
1136 return UpdateValueUsesWith(I, I);
1137 if (ShrinkDemandedConstant(I, 2, DemandedMask))
1138 return UpdateValueUsesWith(I, I);
1139
1140 // Only known if known in both the LHS and RHS.
1141 RHSKnownOne &= LHSKnownOne;
1142 RHSKnownZero &= LHSKnownZero;
1143 break;
1144 case Instruction::Trunc: {
1145 uint32_t truncBf =
1146 cast<IntegerType>(I->getOperand(0)->getType())->getBitWidth();
Zhou Sheng01542f32007-03-29 02:26:30 +00001147 DemandedMask.zext(truncBf);
1148 RHSKnownZero.zext(truncBf);
1149 RHSKnownOne.zext(truncBf);
1150 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
1151 RHSKnownZero, RHSKnownOne, Depth+1))
Reid Spencer8cb68342007-03-12 17:25:59 +00001152 return true;
1153 DemandedMask.trunc(BitWidth);
1154 RHSKnownZero.trunc(BitWidth);
1155 RHSKnownOne.trunc(BitWidth);
1156 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1157 "Bits known to be one AND zero?");
1158 break;
1159 }
1160 case Instruction::BitCast:
1161 if (!I->getOperand(0)->getType()->isInteger())
1162 return false;
1163
1164 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
1165 RHSKnownZero, RHSKnownOne, Depth+1))
1166 return true;
1167 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1168 "Bits known to be one AND zero?");
1169 break;
1170 case Instruction::ZExt: {
1171 // Compute the bits in the result that are not present in the input.
1172 const IntegerType *SrcTy = cast<IntegerType>(I->getOperand(0)->getType());
Reid Spencer2f549172007-03-25 04:26:16 +00001173 uint32_t SrcBitWidth = SrcTy->getBitWidth();
Reid Spencer8cb68342007-03-12 17:25:59 +00001174
Zhou Shengd48653a2007-03-29 04:45:55 +00001175 DemandedMask.trunc(SrcBitWidth);
1176 RHSKnownZero.trunc(SrcBitWidth);
1177 RHSKnownOne.trunc(SrcBitWidth);
Zhou Sheng01542f32007-03-29 02:26:30 +00001178 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
1179 RHSKnownZero, RHSKnownOne, Depth+1))
Reid Spencer8cb68342007-03-12 17:25:59 +00001180 return true;
1181 DemandedMask.zext(BitWidth);
1182 RHSKnownZero.zext(BitWidth);
1183 RHSKnownOne.zext(BitWidth);
1184 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1185 "Bits known to be one AND zero?");
1186 // The top bits are known to be zero.
Zhou Sheng01542f32007-03-29 02:26:30 +00001187 RHSKnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
Reid Spencer8cb68342007-03-12 17:25:59 +00001188 break;
1189 }
1190 case Instruction::SExt: {
1191 // Compute the bits in the result that are not present in the input.
1192 const IntegerType *SrcTy = cast<IntegerType>(I->getOperand(0)->getType());
Reid Spencer2f549172007-03-25 04:26:16 +00001193 uint32_t SrcBitWidth = SrcTy->getBitWidth();
Reid Spencer8cb68342007-03-12 17:25:59 +00001194
Reid Spencer8cb68342007-03-12 17:25:59 +00001195 APInt InputDemandedBits = DemandedMask &
Zhou Sheng01542f32007-03-29 02:26:30 +00001196 APInt::getLowBitsSet(BitWidth, SrcBitWidth);
Reid Spencer8cb68342007-03-12 17:25:59 +00001197
Zhou Sheng01542f32007-03-29 02:26:30 +00001198 APInt NewBits(APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth));
Reid Spencer8cb68342007-03-12 17:25:59 +00001199 // If any of the sign extended bits are demanded, we know that the sign
1200 // bit is demanded.
1201 if ((NewBits & DemandedMask) != 0)
Zhou Sheng4a1822a2007-04-02 13:45:30 +00001202 InputDemandedBits.set(SrcBitWidth-1);
Reid Spencer8cb68342007-03-12 17:25:59 +00001203
Zhou Shengd48653a2007-03-29 04:45:55 +00001204 InputDemandedBits.trunc(SrcBitWidth);
1205 RHSKnownZero.trunc(SrcBitWidth);
1206 RHSKnownOne.trunc(SrcBitWidth);
Zhou Sheng01542f32007-03-29 02:26:30 +00001207 if (SimplifyDemandedBits(I->getOperand(0), InputDemandedBits,
1208 RHSKnownZero, RHSKnownOne, Depth+1))
Reid Spencer8cb68342007-03-12 17:25:59 +00001209 return true;
1210 InputDemandedBits.zext(BitWidth);
1211 RHSKnownZero.zext(BitWidth);
1212 RHSKnownOne.zext(BitWidth);
1213 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1214 "Bits known to be one AND zero?");
1215
1216 // If the sign bit of the input is known set or clear, then we know the
1217 // top bits of the result.
1218
1219 // If the input sign bit is known zero, or if the NewBits are not demanded
1220 // convert this into a zero extension.
Zhou Sheng01542f32007-03-29 02:26:30 +00001221 if (RHSKnownZero[SrcBitWidth-1] || (NewBits & ~DemandedMask) == NewBits)
Reid Spencer8cb68342007-03-12 17:25:59 +00001222 {
1223 // Convert to ZExt cast
1224 CastInst *NewCast = new ZExtInst(I->getOperand(0), VTy, I->getName(), I);
1225 return UpdateValueUsesWith(I, NewCast);
Zhou Sheng01542f32007-03-29 02:26:30 +00001226 } else if (RHSKnownOne[SrcBitWidth-1]) { // Input sign bit known set
Reid Spencer8cb68342007-03-12 17:25:59 +00001227 RHSKnownOne |= NewBits;
Reid Spencer8cb68342007-03-12 17:25:59 +00001228 }
1229 break;
1230 }
1231 case Instruction::Add: {
1232 // Figure out what the input bits are. If the top bits of the and result
1233 // are not demanded, then the add doesn't demand them from its input
1234 // either.
Reid Spencer55702aa2007-03-25 21:11:44 +00001235 uint32_t NLZ = DemandedMask.countLeadingZeros();
Reid Spencer8cb68342007-03-12 17:25:59 +00001236
1237 // If there is a constant on the RHS, there are a variety of xformations
1238 // we can do.
1239 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
1240 // If null, this should be simplified elsewhere. Some of the xforms here
1241 // won't work if the RHS is zero.
1242 if (RHS->isZero())
1243 break;
1244
1245 // If the top bit of the output is demanded, demand everything from the
1246 // input. Otherwise, we demand all the input bits except NLZ top bits.
Zhou Sheng01542f32007-03-29 02:26:30 +00001247 APInt InDemandedBits(APInt::getLowBitsSet(BitWidth, BitWidth - NLZ));
Reid Spencer8cb68342007-03-12 17:25:59 +00001248
1249 // Find information about known zero/one bits in the input.
1250 if (SimplifyDemandedBits(I->getOperand(0), InDemandedBits,
1251 LHSKnownZero, LHSKnownOne, Depth+1))
1252 return true;
1253
1254 // If the RHS of the add has bits set that can't affect the input, reduce
1255 // the constant.
1256 if (ShrinkDemandedConstant(I, 1, InDemandedBits))
1257 return UpdateValueUsesWith(I, I);
1258
1259 // Avoid excess work.
1260 if (LHSKnownZero == 0 && LHSKnownOne == 0)
1261 break;
1262
1263 // Turn it into OR if input bits are zero.
1264 if ((LHSKnownZero & RHS->getValue()) == RHS->getValue()) {
1265 Instruction *Or =
1266 BinaryOperator::createOr(I->getOperand(0), I->getOperand(1),
1267 I->getName());
1268 InsertNewInstBefore(Or, *I);
1269 return UpdateValueUsesWith(I, Or);
1270 }
1271
1272 // We can say something about the output known-zero and known-one bits,
1273 // depending on potential carries from the input constant and the
1274 // unknowns. For example if the LHS is known to have at most the 0x0F0F0
1275 // bits set and the RHS constant is 0x01001, then we know we have a known
1276 // one mask of 0x00001 and a known zero mask of 0xE0F0E.
1277
1278 // To compute this, we first compute the potential carry bits. These are
1279 // the bits which may be modified. I'm not aware of a better way to do
1280 // this scan.
Zhou Shengb9cb95f2007-03-31 02:38:39 +00001281 const APInt& RHSVal = RHS->getValue();
1282 APInt CarryBits((~LHSKnownZero + RHSVal) ^ (~LHSKnownZero ^ RHSVal));
Reid Spencer8cb68342007-03-12 17:25:59 +00001283
1284 // Now that we know which bits have carries, compute the known-1/0 sets.
1285
1286 // Bits are known one if they are known zero in one operand and one in the
1287 // other, and there is no input carry.
1288 RHSKnownOne = ((LHSKnownZero & RHSVal) |
1289 (LHSKnownOne & ~RHSVal)) & ~CarryBits;
1290
1291 // Bits are known zero if they are known zero in both operands and there
1292 // is no input carry.
1293 RHSKnownZero = LHSKnownZero & ~RHSVal & ~CarryBits;
1294 } else {
1295 // If the high-bits of this ADD are not demanded, then it does not demand
1296 // the high bits of its LHS or RHS.
Zhou Sheng01542f32007-03-29 02:26:30 +00001297 if (DemandedMask[BitWidth-1] == 0) {
Reid Spencer8cb68342007-03-12 17:25:59 +00001298 // Right fill the mask of bits for this ADD to demand the most
1299 // significant bit and all those below it.
Zhou Sheng01542f32007-03-29 02:26:30 +00001300 APInt DemandedFromOps(APInt::getLowBitsSet(BitWidth, BitWidth-NLZ));
Reid Spencer8cb68342007-03-12 17:25:59 +00001301 if (SimplifyDemandedBits(I->getOperand(0), DemandedFromOps,
1302 LHSKnownZero, LHSKnownOne, Depth+1))
1303 return true;
1304 if (SimplifyDemandedBits(I->getOperand(1), DemandedFromOps,
1305 LHSKnownZero, LHSKnownOne, Depth+1))
1306 return true;
1307 }
1308 }
1309 break;
1310 }
1311 case Instruction::Sub:
1312 // If the high-bits of this SUB are not demanded, then it does not demand
1313 // the high bits of its LHS or RHS.
Zhou Sheng01542f32007-03-29 02:26:30 +00001314 if (DemandedMask[BitWidth-1] == 0) {
Reid Spencer8cb68342007-03-12 17:25:59 +00001315 // Right fill the mask of bits for this SUB to demand the most
1316 // significant bit and all those below it.
Zhou Sheng4351c642007-04-02 08:20:41 +00001317 uint32_t NLZ = DemandedMask.countLeadingZeros();
Zhou Sheng01542f32007-03-29 02:26:30 +00001318 APInt DemandedFromOps(APInt::getLowBitsSet(BitWidth, BitWidth-NLZ));
Reid Spencer8cb68342007-03-12 17:25:59 +00001319 if (SimplifyDemandedBits(I->getOperand(0), DemandedFromOps,
1320 LHSKnownZero, LHSKnownOne, Depth+1))
1321 return true;
1322 if (SimplifyDemandedBits(I->getOperand(1), DemandedFromOps,
1323 LHSKnownZero, LHSKnownOne, Depth+1))
1324 return true;
1325 }
1326 break;
1327 case Instruction::Shl:
1328 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00001329 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
Zhou Sheng01542f32007-03-29 02:26:30 +00001330 APInt DemandedMaskIn(DemandedMask.lshr(ShiftAmt));
1331 if (SimplifyDemandedBits(I->getOperand(0), DemandedMaskIn,
Reid Spencer8cb68342007-03-12 17:25:59 +00001332 RHSKnownZero, RHSKnownOne, Depth+1))
1333 return true;
1334 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1335 "Bits known to be one AND zero?");
1336 RHSKnownZero <<= ShiftAmt;
1337 RHSKnownOne <<= ShiftAmt;
1338 // low bits known zero.
Zhou Shengadc14952007-03-14 09:07:33 +00001339 if (ShiftAmt)
Zhou Shenge9e03f62007-03-28 15:02:20 +00001340 RHSKnownZero |= APInt::getLowBitsSet(BitWidth, ShiftAmt);
Reid Spencer8cb68342007-03-12 17:25:59 +00001341 }
1342 break;
1343 case Instruction::LShr:
1344 // For a logical shift right
1345 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00001346 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
Reid Spencer8cb68342007-03-12 17:25:59 +00001347
Reid Spencer8cb68342007-03-12 17:25:59 +00001348 // Unsigned shift right.
Zhou Sheng01542f32007-03-29 02:26:30 +00001349 APInt DemandedMaskIn(DemandedMask.shl(ShiftAmt));
1350 if (SimplifyDemandedBits(I->getOperand(0), DemandedMaskIn,
Reid Spencer8cb68342007-03-12 17:25:59 +00001351 RHSKnownZero, RHSKnownOne, Depth+1))
1352 return true;
1353 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1354 "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +00001355 RHSKnownZero = APIntOps::lshr(RHSKnownZero, ShiftAmt);
1356 RHSKnownOne = APIntOps::lshr(RHSKnownOne, ShiftAmt);
Zhou Shengadc14952007-03-14 09:07:33 +00001357 if (ShiftAmt) {
1358 // Compute the new bits that are at the top now.
Zhou Sheng01542f32007-03-29 02:26:30 +00001359 APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
Zhou Shengadc14952007-03-14 09:07:33 +00001360 RHSKnownZero |= HighBits; // high bits known zero.
1361 }
Reid Spencer8cb68342007-03-12 17:25:59 +00001362 }
1363 break;
1364 case Instruction::AShr:
1365 // If this is an arithmetic shift right and only the low-bit is set, we can
1366 // always convert this into a logical shr, even if the shift amount is
1367 // variable. The low bit of the shift cannot be an input sign bit unless
1368 // the shift amount is >= the size of the datatype, which is undefined.
1369 if (DemandedMask == 1) {
1370 // Perform the logical shift right.
1371 Value *NewVal = BinaryOperator::createLShr(
1372 I->getOperand(0), I->getOperand(1), I->getName());
1373 InsertNewInstBefore(cast<Instruction>(NewVal), *I);
1374 return UpdateValueUsesWith(I, NewVal);
1375 }
Chris Lattner4241e4d2007-07-15 20:54:51 +00001376
1377 // If the sign bit is the only bit demanded by this ashr, then there is no
1378 // need to do it, the shift doesn't change the high bit.
1379 if (DemandedMask.isSignBit())
1380 return UpdateValueUsesWith(I, I->getOperand(0));
Reid Spencer8cb68342007-03-12 17:25:59 +00001381
1382 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
Zhou Sheng302748d2007-03-30 17:20:39 +00001383 uint32_t ShiftAmt = SA->getLimitedValue(BitWidth);
Reid Spencer8cb68342007-03-12 17:25:59 +00001384
Reid Spencer8cb68342007-03-12 17:25:59 +00001385 // Signed shift right.
Zhou Sheng01542f32007-03-29 02:26:30 +00001386 APInt DemandedMaskIn(DemandedMask.shl(ShiftAmt));
Lauro Ramos Venanciod0499af2007-06-06 17:08:48 +00001387 // If any of the "high bits" are demanded, we should set the sign bit as
1388 // demanded.
1389 if (DemandedMask.countLeadingZeros() <= ShiftAmt)
1390 DemandedMaskIn.set(BitWidth-1);
Reid Spencer8cb68342007-03-12 17:25:59 +00001391 if (SimplifyDemandedBits(I->getOperand(0),
Zhou Sheng01542f32007-03-29 02:26:30 +00001392 DemandedMaskIn,
Reid Spencer8cb68342007-03-12 17:25:59 +00001393 RHSKnownZero, RHSKnownOne, Depth+1))
1394 return true;
1395 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1396 "Bits known to be one AND zero?");
1397 // Compute the new bits that are at the top now.
Zhou Sheng01542f32007-03-29 02:26:30 +00001398 APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
Reid Spencer8cb68342007-03-12 17:25:59 +00001399 RHSKnownZero = APIntOps::lshr(RHSKnownZero, ShiftAmt);
1400 RHSKnownOne = APIntOps::lshr(RHSKnownOne, ShiftAmt);
1401
1402 // Handle the sign bits.
1403 APInt SignBit(APInt::getSignBit(BitWidth));
1404 // Adjust to where it is now in the mask.
1405 SignBit = APIntOps::lshr(SignBit, ShiftAmt);
1406
1407 // If the input sign bit is known to be zero, or if none of the top bits
1408 // are demanded, turn this into an unsigned shift right.
Zhou Sheng01542f32007-03-29 02:26:30 +00001409 if (RHSKnownZero[BitWidth-ShiftAmt-1] ||
Reid Spencer8cb68342007-03-12 17:25:59 +00001410 (HighBits & ~DemandedMask) == HighBits) {
1411 // Perform the logical shift right.
1412 Value *NewVal = BinaryOperator::createLShr(
1413 I->getOperand(0), SA, I->getName());
1414 InsertNewInstBefore(cast<Instruction>(NewVal), *I);
1415 return UpdateValueUsesWith(I, NewVal);
1416 } else if ((RHSKnownOne & SignBit) != 0) { // New bits are known one.
1417 RHSKnownOne |= HighBits;
1418 }
1419 }
1420 break;
1421 }
1422
1423 // If the client is only demanding bits that we know, return the known
1424 // constant.
1425 if ((DemandedMask & (RHSKnownZero|RHSKnownOne)) == DemandedMask)
1426 return UpdateValueUsesWith(I, ConstantInt::get(RHSKnownOne));
1427 return false;
1428}
1429
Chris Lattner867b99f2006-10-05 06:55:50 +00001430
1431/// SimplifyDemandedVectorElts - The specified value producecs a vector with
1432/// 64 or fewer elements. DemandedElts contains the set of elements that are
1433/// actually used by the caller. This method analyzes which elements of the
1434/// operand are undef and returns that information in UndefElts.
1435///
1436/// If the information about demanded elements can be used to simplify the
1437/// operation, the operation is simplified, then the resultant value is
1438/// returned. This returns null if no change was made.
1439Value *InstCombiner::SimplifyDemandedVectorElts(Value *V, uint64_t DemandedElts,
1440 uint64_t &UndefElts,
1441 unsigned Depth) {
Reid Spencer9d6565a2007-02-15 02:26:10 +00001442 unsigned VWidth = cast<VectorType>(V->getType())->getNumElements();
Chris Lattner867b99f2006-10-05 06:55:50 +00001443 assert(VWidth <= 64 && "Vector too wide to analyze!");
1444 uint64_t EltMask = ~0ULL >> (64-VWidth);
1445 assert(DemandedElts != EltMask && (DemandedElts & ~EltMask) == 0 &&
1446 "Invalid DemandedElts!");
1447
1448 if (isa<UndefValue>(V)) {
1449 // If the entire vector is undefined, just return this info.
1450 UndefElts = EltMask;
1451 return 0;
1452 } else if (DemandedElts == 0) { // If nothing is demanded, provide undef.
1453 UndefElts = EltMask;
1454 return UndefValue::get(V->getType());
1455 }
1456
1457 UndefElts = 0;
Reid Spencer9d6565a2007-02-15 02:26:10 +00001458 if (ConstantVector *CP = dyn_cast<ConstantVector>(V)) {
1459 const Type *EltTy = cast<VectorType>(V->getType())->getElementType();
Chris Lattner867b99f2006-10-05 06:55:50 +00001460 Constant *Undef = UndefValue::get(EltTy);
1461
1462 std::vector<Constant*> Elts;
1463 for (unsigned i = 0; i != VWidth; ++i)
1464 if (!(DemandedElts & (1ULL << i))) { // If not demanded, set to undef.
1465 Elts.push_back(Undef);
1466 UndefElts |= (1ULL << i);
1467 } else if (isa<UndefValue>(CP->getOperand(i))) { // Already undef.
1468 Elts.push_back(Undef);
1469 UndefElts |= (1ULL << i);
1470 } else { // Otherwise, defined.
1471 Elts.push_back(CP->getOperand(i));
1472 }
1473
1474 // If we changed the constant, return it.
Reid Spencer9d6565a2007-02-15 02:26:10 +00001475 Constant *NewCP = ConstantVector::get(Elts);
Chris Lattner867b99f2006-10-05 06:55:50 +00001476 return NewCP != CP ? NewCP : 0;
1477 } else if (isa<ConstantAggregateZero>(V)) {
Reid Spencer9d6565a2007-02-15 02:26:10 +00001478 // Simplify the CAZ to a ConstantVector where the non-demanded elements are
Chris Lattner867b99f2006-10-05 06:55:50 +00001479 // set to undef.
Reid Spencer9d6565a2007-02-15 02:26:10 +00001480 const Type *EltTy = cast<VectorType>(V->getType())->getElementType();
Chris Lattner867b99f2006-10-05 06:55:50 +00001481 Constant *Zero = Constant::getNullValue(EltTy);
1482 Constant *Undef = UndefValue::get(EltTy);
1483 std::vector<Constant*> Elts;
1484 for (unsigned i = 0; i != VWidth; ++i)
1485 Elts.push_back((DemandedElts & (1ULL << i)) ? Zero : Undef);
1486 UndefElts = DemandedElts ^ EltMask;
Reid Spencer9d6565a2007-02-15 02:26:10 +00001487 return ConstantVector::get(Elts);
Chris Lattner867b99f2006-10-05 06:55:50 +00001488 }
1489
1490 if (!V->hasOneUse()) { // Other users may use these bits.
1491 if (Depth != 0) { // Not at the root.
1492 // TODO: Just compute the UndefElts information recursively.
1493 return false;
1494 }
1495 return false;
1496 } else if (Depth == 10) { // Limit search depth.
1497 return false;
1498 }
1499
1500 Instruction *I = dyn_cast<Instruction>(V);
1501 if (!I) return false; // Only analyze instructions.
1502
1503 bool MadeChange = false;
1504 uint64_t UndefElts2;
1505 Value *TmpV;
1506 switch (I->getOpcode()) {
1507 default: break;
1508
1509 case Instruction::InsertElement: {
1510 // If this is a variable index, we don't know which element it overwrites.
1511 // demand exactly the same input as we produce.
Reid Spencerb83eb642006-10-20 07:07:24 +00001512 ConstantInt *Idx = dyn_cast<ConstantInt>(I->getOperand(2));
Chris Lattner867b99f2006-10-05 06:55:50 +00001513 if (Idx == 0) {
1514 // Note that we can't propagate undef elt info, because we don't know
1515 // which elt is getting updated.
1516 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1517 UndefElts2, Depth+1);
1518 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1519 break;
1520 }
1521
1522 // If this is inserting an element that isn't demanded, remove this
1523 // insertelement.
Reid Spencerb83eb642006-10-20 07:07:24 +00001524 unsigned IdxNo = Idx->getZExtValue();
Chris Lattner867b99f2006-10-05 06:55:50 +00001525 if (IdxNo >= VWidth || (DemandedElts & (1ULL << IdxNo)) == 0)
1526 return AddSoonDeadInstToWorklist(*I, 0);
1527
1528 // Otherwise, the element inserted overwrites whatever was there, so the
1529 // input demanded set is simpler than the output set.
1530 TmpV = SimplifyDemandedVectorElts(I->getOperand(0),
1531 DemandedElts & ~(1ULL << IdxNo),
1532 UndefElts, Depth+1);
1533 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1534
1535 // The inserted element is defined.
1536 UndefElts |= 1ULL << IdxNo;
1537 break;
1538 }
Chris Lattner69878332007-04-14 22:29:23 +00001539 case Instruction::BitCast: {
Dan Gohman07a96762007-07-16 14:29:03 +00001540 // Vector->vector casts only.
Chris Lattner69878332007-04-14 22:29:23 +00001541 const VectorType *VTy = dyn_cast<VectorType>(I->getOperand(0)->getType());
1542 if (!VTy) break;
1543 unsigned InVWidth = VTy->getNumElements();
1544 uint64_t InputDemandedElts = 0;
1545 unsigned Ratio;
1546
1547 if (VWidth == InVWidth) {
Dan Gohman07a96762007-07-16 14:29:03 +00001548 // If we are converting from <4 x i32> -> <4 x f32>, we demand the same
Chris Lattner69878332007-04-14 22:29:23 +00001549 // elements as are demanded of us.
1550 Ratio = 1;
1551 InputDemandedElts = DemandedElts;
1552 } else if (VWidth > InVWidth) {
1553 // Untested so far.
1554 break;
1555
1556 // If there are more elements in the result than there are in the source,
1557 // then an input element is live if any of the corresponding output
1558 // elements are live.
1559 Ratio = VWidth/InVWidth;
1560 for (unsigned OutIdx = 0; OutIdx != VWidth; ++OutIdx) {
1561 if (DemandedElts & (1ULL << OutIdx))
1562 InputDemandedElts |= 1ULL << (OutIdx/Ratio);
1563 }
1564 } else {
1565 // Untested so far.
1566 break;
1567
1568 // If there are more elements in the source than there are in the result,
1569 // then an input element is live if the corresponding output element is
1570 // live.
1571 Ratio = InVWidth/VWidth;
1572 for (unsigned InIdx = 0; InIdx != InVWidth; ++InIdx)
1573 if (DemandedElts & (1ULL << InIdx/Ratio))
1574 InputDemandedElts |= 1ULL << InIdx;
1575 }
Chris Lattner867b99f2006-10-05 06:55:50 +00001576
Chris Lattner69878332007-04-14 22:29:23 +00001577 // div/rem demand all inputs, because they don't want divide by zero.
1578 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), InputDemandedElts,
1579 UndefElts2, Depth+1);
1580 if (TmpV) {
1581 I->setOperand(0, TmpV);
1582 MadeChange = true;
1583 }
1584
1585 UndefElts = UndefElts2;
1586 if (VWidth > InVWidth) {
1587 assert(0 && "Unimp");
1588 // If there are more elements in the result than there are in the source,
1589 // then an output element is undef if the corresponding input element is
1590 // undef.
1591 for (unsigned OutIdx = 0; OutIdx != VWidth; ++OutIdx)
1592 if (UndefElts2 & (1ULL << (OutIdx/Ratio)))
1593 UndefElts |= 1ULL << OutIdx;
1594 } else if (VWidth < InVWidth) {
1595 assert(0 && "Unimp");
1596 // If there are more elements in the source than there are in the result,
1597 // then a result element is undef if all of the corresponding input
1598 // elements are undef.
1599 UndefElts = ~0ULL >> (64-VWidth); // Start out all undef.
1600 for (unsigned InIdx = 0; InIdx != InVWidth; ++InIdx)
1601 if ((UndefElts2 & (1ULL << InIdx)) == 0) // Not undef?
1602 UndefElts &= ~(1ULL << (InIdx/Ratio)); // Clear undef bit.
1603 }
1604 break;
1605 }
Chris Lattner867b99f2006-10-05 06:55:50 +00001606 case Instruction::And:
1607 case Instruction::Or:
1608 case Instruction::Xor:
1609 case Instruction::Add:
1610 case Instruction::Sub:
1611 case Instruction::Mul:
1612 // div/rem demand all inputs, because they don't want divide by zero.
1613 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1614 UndefElts, Depth+1);
1615 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1616 TmpV = SimplifyDemandedVectorElts(I->getOperand(1), DemandedElts,
1617 UndefElts2, Depth+1);
1618 if (TmpV) { I->setOperand(1, TmpV); MadeChange = true; }
1619
1620 // Output elements are undefined if both are undefined. Consider things
1621 // like undef&0. The result is known zero, not undef.
1622 UndefElts &= UndefElts2;
1623 break;
1624
1625 case Instruction::Call: {
1626 IntrinsicInst *II = dyn_cast<IntrinsicInst>(I);
1627 if (!II) break;
1628 switch (II->getIntrinsicID()) {
1629 default: break;
1630
1631 // Binary vector operations that work column-wise. A dest element is a
1632 // function of the corresponding input elements from the two inputs.
1633 case Intrinsic::x86_sse_sub_ss:
1634 case Intrinsic::x86_sse_mul_ss:
1635 case Intrinsic::x86_sse_min_ss:
1636 case Intrinsic::x86_sse_max_ss:
1637 case Intrinsic::x86_sse2_sub_sd:
1638 case Intrinsic::x86_sse2_mul_sd:
1639 case Intrinsic::x86_sse2_min_sd:
1640 case Intrinsic::x86_sse2_max_sd:
1641 TmpV = SimplifyDemandedVectorElts(II->getOperand(1), DemandedElts,
1642 UndefElts, Depth+1);
1643 if (TmpV) { II->setOperand(1, TmpV); MadeChange = true; }
1644 TmpV = SimplifyDemandedVectorElts(II->getOperand(2), DemandedElts,
1645 UndefElts2, Depth+1);
1646 if (TmpV) { II->setOperand(2, TmpV); MadeChange = true; }
1647
1648 // If only the low elt is demanded and this is a scalarizable intrinsic,
1649 // scalarize it now.
1650 if (DemandedElts == 1) {
1651 switch (II->getIntrinsicID()) {
1652 default: break;
1653 case Intrinsic::x86_sse_sub_ss:
1654 case Intrinsic::x86_sse_mul_ss:
1655 case Intrinsic::x86_sse2_sub_sd:
1656 case Intrinsic::x86_sse2_mul_sd:
1657 // TODO: Lower MIN/MAX/ABS/etc
1658 Value *LHS = II->getOperand(1);
1659 Value *RHS = II->getOperand(2);
1660 // Extract the element as scalars.
1661 LHS = InsertNewInstBefore(new ExtractElementInst(LHS, 0U,"tmp"), *II);
1662 RHS = InsertNewInstBefore(new ExtractElementInst(RHS, 0U,"tmp"), *II);
1663
1664 switch (II->getIntrinsicID()) {
1665 default: assert(0 && "Case stmts out of sync!");
1666 case Intrinsic::x86_sse_sub_ss:
1667 case Intrinsic::x86_sse2_sub_sd:
1668 TmpV = InsertNewInstBefore(BinaryOperator::createSub(LHS, RHS,
1669 II->getName()), *II);
1670 break;
1671 case Intrinsic::x86_sse_mul_ss:
1672 case Intrinsic::x86_sse2_mul_sd:
1673 TmpV = InsertNewInstBefore(BinaryOperator::createMul(LHS, RHS,
1674 II->getName()), *II);
1675 break;
1676 }
1677
1678 Instruction *New =
1679 new InsertElementInst(UndefValue::get(II->getType()), TmpV, 0U,
1680 II->getName());
1681 InsertNewInstBefore(New, *II);
1682 AddSoonDeadInstToWorklist(*II, 0);
1683 return New;
1684 }
1685 }
1686
1687 // Output elements are undefined if both are undefined. Consider things
1688 // like undef&0. The result is known zero, not undef.
1689 UndefElts &= UndefElts2;
1690 break;
1691 }
1692 break;
1693 }
1694 }
1695 return MadeChange ? I : 0;
1696}
1697
Nick Lewycky455e1762007-09-06 02:40:25 +00001698/// @returns true if the specified compare predicate is
Reid Spencere4d87aa2006-12-23 06:05:41 +00001699/// true when both operands are equal...
Nick Lewycky455e1762007-09-06 02:40:25 +00001700/// @brief Determine if the icmp Predicate is true when both operands are equal
1701static bool isTrueWhenEqual(ICmpInst::Predicate pred) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00001702 return pred == ICmpInst::ICMP_EQ || pred == ICmpInst::ICMP_UGE ||
1703 pred == ICmpInst::ICMP_SGE || pred == ICmpInst::ICMP_ULE ||
1704 pred == ICmpInst::ICMP_SLE;
1705}
1706
Nick Lewycky455e1762007-09-06 02:40:25 +00001707/// @returns true if the specified compare instruction is
1708/// true when both operands are equal...
1709/// @brief Determine if the ICmpInst returns true when both operands are equal
1710static bool isTrueWhenEqual(ICmpInst &ICI) {
1711 return isTrueWhenEqual(ICI.getPredicate());
1712}
1713
Chris Lattner564a7272003-08-13 19:01:45 +00001714/// AssociativeOpt - Perform an optimization on an associative operator. This
1715/// function is designed to check a chain of associative operators for a
1716/// potential to apply a certain optimization. Since the optimization may be
1717/// applicable if the expression was reassociated, this checks the chain, then
1718/// reassociates the expression as necessary to expose the optimization
1719/// opportunity. This makes use of a special Functor, which must define
1720/// 'shouldApply' and 'apply' methods.
1721///
1722template<typename Functor>
1723Instruction *AssociativeOpt(BinaryOperator &Root, const Functor &F) {
1724 unsigned Opcode = Root.getOpcode();
1725 Value *LHS = Root.getOperand(0);
1726
1727 // Quick check, see if the immediate LHS matches...
1728 if (F.shouldApply(LHS))
1729 return F.apply(Root);
1730
1731 // Otherwise, if the LHS is not of the same opcode as the root, return.
1732 Instruction *LHSI = dyn_cast<Instruction>(LHS);
Chris Lattnerfd059242003-10-15 16:48:29 +00001733 while (LHSI && LHSI->getOpcode() == Opcode && LHSI->hasOneUse()) {
Chris Lattner564a7272003-08-13 19:01:45 +00001734 // Should we apply this transform to the RHS?
1735 bool ShouldApply = F.shouldApply(LHSI->getOperand(1));
1736
1737 // If not to the RHS, check to see if we should apply to the LHS...
1738 if (!ShouldApply && F.shouldApply(LHSI->getOperand(0))) {
1739 cast<BinaryOperator>(LHSI)->swapOperands(); // Make the LHS the RHS
1740 ShouldApply = true;
1741 }
1742
1743 // If the functor wants to apply the optimization to the RHS of LHSI,
1744 // reassociate the expression from ((? op A) op B) to (? op (A op B))
1745 if (ShouldApply) {
1746 BasicBlock *BB = Root.getParent();
Misha Brukmanfd939082005-04-21 23:48:37 +00001747
Chris Lattner564a7272003-08-13 19:01:45 +00001748 // Now all of the instructions are in the current basic block, go ahead
1749 // and perform the reassociation.
1750 Instruction *TmpLHSI = cast<Instruction>(Root.getOperand(0));
1751
1752 // First move the selected RHS to the LHS of the root...
1753 Root.setOperand(0, LHSI->getOperand(1));
1754
1755 // Make what used to be the LHS of the root be the user of the root...
1756 Value *ExtraOperand = TmpLHSI->getOperand(1);
Chris Lattner65725312004-04-16 18:08:07 +00001757 if (&Root == TmpLHSI) {
Chris Lattner15a76c02004-04-05 02:10:19 +00001758 Root.replaceAllUsesWith(Constant::getNullValue(TmpLHSI->getType()));
1759 return 0;
1760 }
Chris Lattner65725312004-04-16 18:08:07 +00001761 Root.replaceAllUsesWith(TmpLHSI); // Users now use TmpLHSI
Chris Lattner564a7272003-08-13 19:01:45 +00001762 TmpLHSI->setOperand(1, &Root); // TmpLHSI now uses the root
Chris Lattner65725312004-04-16 18:08:07 +00001763 TmpLHSI->getParent()->getInstList().remove(TmpLHSI);
1764 BasicBlock::iterator ARI = &Root; ++ARI;
1765 BB->getInstList().insert(ARI, TmpLHSI); // Move TmpLHSI to after Root
1766 ARI = Root;
Chris Lattner564a7272003-08-13 19:01:45 +00001767
1768 // Now propagate the ExtraOperand down the chain of instructions until we
1769 // get to LHSI.
1770 while (TmpLHSI != LHSI) {
1771 Instruction *NextLHSI = cast<Instruction>(TmpLHSI->getOperand(0));
Chris Lattner65725312004-04-16 18:08:07 +00001772 // Move the instruction to immediately before the chain we are
1773 // constructing to avoid breaking dominance properties.
1774 NextLHSI->getParent()->getInstList().remove(NextLHSI);
1775 BB->getInstList().insert(ARI, NextLHSI);
1776 ARI = NextLHSI;
1777
Chris Lattner564a7272003-08-13 19:01:45 +00001778 Value *NextOp = NextLHSI->getOperand(1);
1779 NextLHSI->setOperand(1, ExtraOperand);
1780 TmpLHSI = NextLHSI;
1781 ExtraOperand = NextOp;
1782 }
Misha Brukmanfd939082005-04-21 23:48:37 +00001783
Chris Lattner564a7272003-08-13 19:01:45 +00001784 // Now that the instructions are reassociated, have the functor perform
1785 // the transformation...
1786 return F.apply(Root);
1787 }
Misha Brukmanfd939082005-04-21 23:48:37 +00001788
Chris Lattner564a7272003-08-13 19:01:45 +00001789 LHSI = dyn_cast<Instruction>(LHSI->getOperand(0));
1790 }
1791 return 0;
1792}
1793
1794
1795// AddRHS - Implements: X + X --> X << 1
1796struct AddRHS {
1797 Value *RHS;
1798 AddRHS(Value *rhs) : RHS(rhs) {}
1799 bool shouldApply(Value *LHS) const { return LHS == RHS; }
1800 Instruction *apply(BinaryOperator &Add) const {
Reid Spencercc46cdb2007-02-02 14:08:20 +00001801 return BinaryOperator::createShl(Add.getOperand(0),
Reid Spencer832254e2007-02-02 02:16:23 +00001802 ConstantInt::get(Add.getType(), 1));
Chris Lattner564a7272003-08-13 19:01:45 +00001803 }
1804};
1805
1806// AddMaskingAnd - Implements (A & C1)+(B & C2) --> (A & C1)|(B & C2)
1807// iff C1&C2 == 0
1808struct AddMaskingAnd {
1809 Constant *C2;
1810 AddMaskingAnd(Constant *c) : C2(c) {}
1811 bool shouldApply(Value *LHS) const {
Chris Lattneracd1f0f2004-07-30 07:50:03 +00001812 ConstantInt *C1;
Misha Brukmanfd939082005-04-21 23:48:37 +00001813 return match(LHS, m_And(m_Value(), m_ConstantInt(C1))) &&
Chris Lattneracd1f0f2004-07-30 07:50:03 +00001814 ConstantExpr::getAnd(C1, C2)->isNullValue();
Chris Lattner564a7272003-08-13 19:01:45 +00001815 }
1816 Instruction *apply(BinaryOperator &Add) const {
Chris Lattner48595f12004-06-10 02:07:29 +00001817 return BinaryOperator::createOr(Add.getOperand(0), Add.getOperand(1));
Chris Lattner564a7272003-08-13 19:01:45 +00001818 }
1819};
1820
Chris Lattner6e7ba452005-01-01 16:22:27 +00001821static Value *FoldOperationIntoSelectOperand(Instruction &I, Value *SO,
Chris Lattner2eefe512004-04-09 19:05:30 +00001822 InstCombiner *IC) {
Reid Spencer3da59db2006-11-27 01:05:10 +00001823 if (CastInst *CI = dyn_cast<CastInst>(&I)) {
Chris Lattner6e7ba452005-01-01 16:22:27 +00001824 if (Constant *SOC = dyn_cast<Constant>(SO))
Reid Spencer3da59db2006-11-27 01:05:10 +00001825 return ConstantExpr::getCast(CI->getOpcode(), SOC, I.getType());
Misha Brukmanfd939082005-04-21 23:48:37 +00001826
Reid Spencer3da59db2006-11-27 01:05:10 +00001827 return IC->InsertNewInstBefore(CastInst::create(
1828 CI->getOpcode(), SO, I.getType(), SO->getName() + ".cast"), I);
Chris Lattner6e7ba452005-01-01 16:22:27 +00001829 }
1830
Chris Lattner2eefe512004-04-09 19:05:30 +00001831 // Figure out if the constant is the left or the right argument.
Chris Lattner6e7ba452005-01-01 16:22:27 +00001832 bool ConstIsRHS = isa<Constant>(I.getOperand(1));
1833 Constant *ConstOperand = cast<Constant>(I.getOperand(ConstIsRHS));
Chris Lattner564a7272003-08-13 19:01:45 +00001834
Chris Lattner2eefe512004-04-09 19:05:30 +00001835 if (Constant *SOC = dyn_cast<Constant>(SO)) {
1836 if (ConstIsRHS)
Chris Lattner6e7ba452005-01-01 16:22:27 +00001837 return ConstantExpr::get(I.getOpcode(), SOC, ConstOperand);
1838 return ConstantExpr::get(I.getOpcode(), ConstOperand, SOC);
Chris Lattner2eefe512004-04-09 19:05:30 +00001839 }
1840
1841 Value *Op0 = SO, *Op1 = ConstOperand;
1842 if (!ConstIsRHS)
1843 std::swap(Op0, Op1);
1844 Instruction *New;
Chris Lattner6e7ba452005-01-01 16:22:27 +00001845 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
1846 New = BinaryOperator::create(BO->getOpcode(), Op0, Op1,SO->getName()+".op");
Reid Spencere4d87aa2006-12-23 06:05:41 +00001847 else if (CmpInst *CI = dyn_cast<CmpInst>(&I))
1848 New = CmpInst::create(CI->getOpcode(), CI->getPredicate(), Op0, Op1,
1849 SO->getName()+".cmp");
Chris Lattner326c0f32004-04-10 19:15:56 +00001850 else {
Chris Lattner2eefe512004-04-09 19:05:30 +00001851 assert(0 && "Unknown binary instruction type!");
Chris Lattner326c0f32004-04-10 19:15:56 +00001852 abort();
1853 }
Chris Lattner6e7ba452005-01-01 16:22:27 +00001854 return IC->InsertNewInstBefore(New, I);
1855}
1856
1857// FoldOpIntoSelect - Given an instruction with a select as one operand and a
1858// constant as the other operand, try to fold the binary operator into the
1859// select arguments. This also works for Cast instructions, which obviously do
1860// not have a second operand.
1861static Instruction *FoldOpIntoSelect(Instruction &Op, SelectInst *SI,
1862 InstCombiner *IC) {
1863 // Don't modify shared select instructions
1864 if (!SI->hasOneUse()) return 0;
1865 Value *TV = SI->getOperand(1);
1866 Value *FV = SI->getOperand(2);
1867
1868 if (isa<Constant>(TV) || isa<Constant>(FV)) {
Chris Lattner956db272005-04-21 05:43:13 +00001869 // Bool selects with constant operands can be folded to logical ops.
Reid Spencer4fe16d62007-01-11 18:21:29 +00001870 if (SI->getType() == Type::Int1Ty) return 0;
Chris Lattner956db272005-04-21 05:43:13 +00001871
Chris Lattner6e7ba452005-01-01 16:22:27 +00001872 Value *SelectTrueVal = FoldOperationIntoSelectOperand(Op, TV, IC);
1873 Value *SelectFalseVal = FoldOperationIntoSelectOperand(Op, FV, IC);
1874
1875 return new SelectInst(SI->getCondition(), SelectTrueVal,
1876 SelectFalseVal);
1877 }
1878 return 0;
Chris Lattner2eefe512004-04-09 19:05:30 +00001879}
1880
Chris Lattner4e998b22004-09-29 05:07:12 +00001881
1882/// FoldOpIntoPhi - Given a binary operator or cast instruction which has a PHI
1883/// node as operand #0, see if we can fold the instruction into the PHI (which
1884/// is only possible if all operands to the PHI are constants).
1885Instruction *InstCombiner::FoldOpIntoPhi(Instruction &I) {
1886 PHINode *PN = cast<PHINode>(I.getOperand(0));
Chris Lattnerbac32862004-11-14 19:13:23 +00001887 unsigned NumPHIValues = PN->getNumIncomingValues();
Chris Lattner2a86f3b2006-09-09 22:02:56 +00001888 if (!PN->hasOneUse() || NumPHIValues == 0) return 0;
Chris Lattner4e998b22004-09-29 05:07:12 +00001889
Chris Lattner2a86f3b2006-09-09 22:02:56 +00001890 // Check to see if all of the operands of the PHI are constants. If there is
1891 // one non-constant value, remember the BB it is. If there is more than one
Chris Lattnerb3036682007-02-24 01:03:45 +00001892 // or if *it* is a PHI, bail out.
Chris Lattner2a86f3b2006-09-09 22:02:56 +00001893 BasicBlock *NonConstBB = 0;
1894 for (unsigned i = 0; i != NumPHIValues; ++i)
1895 if (!isa<Constant>(PN->getIncomingValue(i))) {
1896 if (NonConstBB) return 0; // More than one non-const value.
Chris Lattnerb3036682007-02-24 01:03:45 +00001897 if (isa<PHINode>(PN->getIncomingValue(i))) return 0; // Itself a phi.
Chris Lattner2a86f3b2006-09-09 22:02:56 +00001898 NonConstBB = PN->getIncomingBlock(i);
1899
1900 // If the incoming non-constant value is in I's block, we have an infinite
1901 // loop.
1902 if (NonConstBB == I.getParent())
1903 return 0;
1904 }
1905
1906 // If there is exactly one non-constant value, we can insert a copy of the
1907 // operation in that block. However, if this is a critical edge, we would be
1908 // inserting the computation one some other paths (e.g. inside a loop). Only
1909 // do this if the pred block is unconditionally branching into the phi block.
1910 if (NonConstBB) {
1911 BranchInst *BI = dyn_cast<BranchInst>(NonConstBB->getTerminator());
1912 if (!BI || !BI->isUnconditional()) return 0;
1913 }
Chris Lattner4e998b22004-09-29 05:07:12 +00001914
1915 // Okay, we can do the transformation: create the new PHI node.
Chris Lattner6934a042007-02-11 01:23:03 +00001916 PHINode *NewPN = new PHINode(I.getType(), "");
Chris Lattner55517062005-01-29 00:39:08 +00001917 NewPN->reserveOperandSpace(PN->getNumOperands()/2);
Chris Lattner4e998b22004-09-29 05:07:12 +00001918 InsertNewInstBefore(NewPN, *PN);
Chris Lattner6934a042007-02-11 01:23:03 +00001919 NewPN->takeName(PN);
Chris Lattner4e998b22004-09-29 05:07:12 +00001920
1921 // Next, add all of the operands to the PHI.
1922 if (I.getNumOperands() == 2) {
1923 Constant *C = cast<Constant>(I.getOperand(1));
Chris Lattnerbac32862004-11-14 19:13:23 +00001924 for (unsigned i = 0; i != NumPHIValues; ++i) {
Chris Lattnera9ff5eb2007-08-05 08:47:58 +00001925 Value *InV = 0;
Chris Lattner2a86f3b2006-09-09 22:02:56 +00001926 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00001927 if (CmpInst *CI = dyn_cast<CmpInst>(&I))
1928 InV = ConstantExpr::getCompare(CI->getPredicate(), InC, C);
1929 else
1930 InV = ConstantExpr::get(I.getOpcode(), InC, C);
Chris Lattner2a86f3b2006-09-09 22:02:56 +00001931 } else {
1932 assert(PN->getIncomingBlock(i) == NonConstBB);
1933 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
1934 InV = BinaryOperator::create(BO->getOpcode(),
1935 PN->getIncomingValue(i), C, "phitmp",
1936 NonConstBB->getTerminator());
Reid Spencere4d87aa2006-12-23 06:05:41 +00001937 else if (CmpInst *CI = dyn_cast<CmpInst>(&I))
1938 InV = CmpInst::create(CI->getOpcode(),
1939 CI->getPredicate(),
1940 PN->getIncomingValue(i), C, "phitmp",
1941 NonConstBB->getTerminator());
Chris Lattner2a86f3b2006-09-09 22:02:56 +00001942 else
1943 assert(0 && "Unknown binop!");
1944
Chris Lattnerdbab3862007-03-02 21:28:56 +00001945 AddToWorkList(cast<Instruction>(InV));
Chris Lattner2a86f3b2006-09-09 22:02:56 +00001946 }
1947 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
Chris Lattner4e998b22004-09-29 05:07:12 +00001948 }
Reid Spencer3da59db2006-11-27 01:05:10 +00001949 } else {
1950 CastInst *CI = cast<CastInst>(&I);
1951 const Type *RetTy = CI->getType();
Chris Lattnerbac32862004-11-14 19:13:23 +00001952 for (unsigned i = 0; i != NumPHIValues; ++i) {
Chris Lattner2a86f3b2006-09-09 22:02:56 +00001953 Value *InV;
1954 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
Reid Spencer3da59db2006-11-27 01:05:10 +00001955 InV = ConstantExpr::getCast(CI->getOpcode(), InC, RetTy);
Chris Lattner2a86f3b2006-09-09 22:02:56 +00001956 } else {
1957 assert(PN->getIncomingBlock(i) == NonConstBB);
Reid Spencer3da59db2006-11-27 01:05:10 +00001958 InV = CastInst::create(CI->getOpcode(), PN->getIncomingValue(i),
1959 I.getType(), "phitmp",
1960 NonConstBB->getTerminator());
Chris Lattnerdbab3862007-03-02 21:28:56 +00001961 AddToWorkList(cast<Instruction>(InV));
Chris Lattner2a86f3b2006-09-09 22:02:56 +00001962 }
1963 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
Chris Lattner4e998b22004-09-29 05:07:12 +00001964 }
1965 }
1966 return ReplaceInstUsesWith(I, NewPN);
1967}
1968
Chris Lattner2454a2e2008-01-29 06:52:45 +00001969
1970/// CannotBeNegativeZero - Return true if we can prove that the specified FP
1971/// value is never equal to -0.0.
1972///
1973/// Note that this function will need to be revisited when we support nondefault
1974/// rounding modes!
1975///
1976static bool CannotBeNegativeZero(const Value *V) {
1977 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(V))
1978 return !CFP->getValueAPF().isNegZero();
1979
1980 // (add x, 0.0) is guaranteed to return +0.0, not -0.0.
1981 if (const Instruction *I = dyn_cast<Instruction>(V)) {
1982 if (I->getOpcode() == Instruction::Add &&
1983 isa<ConstantFP>(I->getOperand(1)) &&
1984 cast<ConstantFP>(I->getOperand(1))->isNullValue())
1985 return true;
1986
1987 if (const IntrinsicInst *II = dyn_cast<IntrinsicInst>(I))
1988 if (II->getIntrinsicID() == Intrinsic::sqrt)
1989 return CannotBeNegativeZero(II->getOperand(1));
1990
1991 if (const CallInst *CI = dyn_cast<CallInst>(I))
1992 if (const Function *F = CI->getCalledFunction()) {
1993 if (F->isDeclaration()) {
1994 switch (F->getNameLen()) {
1995 case 3: // abs(x) != -0.0
1996 if (!strcmp(F->getNameStart(), "abs")) return true;
1997 break;
1998 case 4: // abs[lf](x) != -0.0
1999 if (!strcmp(F->getNameStart(), "absf")) return true;
2000 if (!strcmp(F->getNameStart(), "absl")) return true;
2001 break;
2002 }
2003 }
2004 }
2005 }
2006
2007 return false;
2008}
2009
2010
Chris Lattner7e708292002-06-25 16:13:24 +00002011Instruction *InstCombiner::visitAdd(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00002012 bool Changed = SimplifyCommutative(I);
Chris Lattner7e708292002-06-25 16:13:24 +00002013 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
Chris Lattnerb35dde12002-05-06 16:49:18 +00002014
Chris Lattner66331a42004-04-10 22:01:55 +00002015 if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
Chris Lattnere87597f2004-10-16 18:11:37 +00002016 // X + undef -> undef
2017 if (isa<UndefValue>(RHS))
2018 return ReplaceInstUsesWith(I, RHS);
2019
Chris Lattner66331a42004-04-10 22:01:55 +00002020 // X + 0 --> X
Chris Lattner9919e3d2006-12-02 00:13:08 +00002021 if (!I.getType()->isFPOrFPVector()) { // NOTE: -0 + +0 = +0.
Chris Lattner5e678e02005-10-17 17:56:38 +00002022 if (RHSC->isNullValue())
2023 return ReplaceInstUsesWith(I, LHS);
Chris Lattner8532cf62005-10-17 20:18:38 +00002024 } else if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
Dale Johannesen9e3d3ab2007-09-14 22:26:36 +00002025 if (CFP->isExactlyValue(ConstantFP::getNegativeZero
2026 (I.getType())->getValueAPF()))
Chris Lattner8532cf62005-10-17 20:18:38 +00002027 return ReplaceInstUsesWith(I, LHS);
Chris Lattner5e678e02005-10-17 17:56:38 +00002028 }
Misha Brukmanfd939082005-04-21 23:48:37 +00002029
Chris Lattner66331a42004-04-10 22:01:55 +00002030 if (ConstantInt *CI = dyn_cast<ConstantInt>(RHSC)) {
Chris Lattnerb4a2f052006-11-09 05:12:27 +00002031 // X + (signbit) --> X ^ signbit
Zhou Sheng3a507fd2007-04-01 17:13:37 +00002032 const APInt& Val = CI->getValue();
Zhou Sheng4351c642007-04-02 08:20:41 +00002033 uint32_t BitWidth = Val.getBitWidth();
Reid Spencer2ec619a2007-03-23 21:24:59 +00002034 if (Val == APInt::getSignBit(BitWidth))
Chris Lattner48595f12004-06-10 02:07:29 +00002035 return BinaryOperator::createXor(LHS, RHS);
Chris Lattnerb4a2f052006-11-09 05:12:27 +00002036
2037 // See if SimplifyDemandedBits can simplify this. This handles stuff like
2038 // (X & 254)+1 -> (X&254)|1
Reid Spencer2ec619a2007-03-23 21:24:59 +00002039 if (!isa<VectorType>(I.getType())) {
2040 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
2041 if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(BitWidth),
2042 KnownZero, KnownOne))
2043 return &I;
2044 }
Chris Lattner66331a42004-04-10 22:01:55 +00002045 }
Chris Lattner4e998b22004-09-29 05:07:12 +00002046
2047 if (isa<PHINode>(LHS))
2048 if (Instruction *NV = FoldOpIntoPhi(I))
2049 return NV;
Chris Lattner5931c542005-09-24 23:43:33 +00002050
Chris Lattner4f637d42006-01-06 17:59:59 +00002051 ConstantInt *XorRHS = 0;
2052 Value *XorLHS = 0;
Chris Lattnerc5eff442007-01-30 22:32:46 +00002053 if (isa<ConstantInt>(RHSC) &&
2054 match(LHS, m_Xor(m_Value(XorLHS), m_ConstantInt(XorRHS)))) {
Zhou Sheng4351c642007-04-02 08:20:41 +00002055 uint32_t TySizeBits = I.getType()->getPrimitiveSizeInBits();
Zhou Sheng3a507fd2007-04-01 17:13:37 +00002056 const APInt& RHSVal = cast<ConstantInt>(RHSC)->getValue();
Chris Lattner5931c542005-09-24 23:43:33 +00002057
Zhou Sheng4351c642007-04-02 08:20:41 +00002058 uint32_t Size = TySizeBits / 2;
Reid Spencer2ec619a2007-03-23 21:24:59 +00002059 APInt C0080Val(APInt(TySizeBits, 1ULL).shl(Size - 1));
2060 APInt CFF80Val(-C0080Val);
Chris Lattner5931c542005-09-24 23:43:33 +00002061 do {
2062 if (TySizeBits > Size) {
Chris Lattner5931c542005-09-24 23:43:33 +00002063 // If we have ADD(XOR(AND(X, 0xFF), 0x80), 0xF..F80), it's a sext.
2064 // If we have ADD(XOR(AND(X, 0xFF), 0xF..F80), 0x80), it's a sext.
Reid Spencer2ec619a2007-03-23 21:24:59 +00002065 if ((RHSVal == CFF80Val && XorRHS->getValue() == C0080Val) ||
2066 (RHSVal == C0080Val && XorRHS->getValue() == CFF80Val)) {
Chris Lattner5931c542005-09-24 23:43:33 +00002067 // This is a sign extend if the top bits are known zero.
Zhou Sheng290bec52007-03-29 08:15:12 +00002068 if (!MaskedValueIsZero(XorLHS,
2069 APInt::getHighBitsSet(TySizeBits, TySizeBits - Size)))
Chris Lattner5931c542005-09-24 23:43:33 +00002070 Size = 0; // Not a sign ext, but can't be any others either.
Reid Spencer2ec619a2007-03-23 21:24:59 +00002071 break;
Chris Lattner5931c542005-09-24 23:43:33 +00002072 }
2073 }
2074 Size >>= 1;
Reid Spencer2ec619a2007-03-23 21:24:59 +00002075 C0080Val = APIntOps::lshr(C0080Val, Size);
2076 CFF80Val = APIntOps::ashr(CFF80Val, Size);
2077 } while (Size >= 1);
Chris Lattner5931c542005-09-24 23:43:33 +00002078
Reid Spencer35c38852007-03-28 01:36:16 +00002079 // FIXME: This shouldn't be necessary. When the backends can handle types
2080 // with funny bit widths then this whole cascade of if statements should
2081 // be removed. It is just here to get the size of the "middle" type back
2082 // up to something that the back ends can handle.
2083 const Type *MiddleType = 0;
2084 switch (Size) {
2085 default: break;
2086 case 32: MiddleType = Type::Int32Ty; break;
2087 case 16: MiddleType = Type::Int16Ty; break;
2088 case 8: MiddleType = Type::Int8Ty; break;
2089 }
2090 if (MiddleType) {
Reid Spencerd977d862006-12-12 23:36:14 +00002091 Instruction *NewTrunc = new TruncInst(XorLHS, MiddleType, "sext");
Chris Lattner5931c542005-09-24 23:43:33 +00002092 InsertNewInstBefore(NewTrunc, I);
Reid Spencer35c38852007-03-28 01:36:16 +00002093 return new SExtInst(NewTrunc, I.getType(), I.getName());
Chris Lattner5931c542005-09-24 23:43:33 +00002094 }
2095 }
Chris Lattner66331a42004-04-10 22:01:55 +00002096 }
Chris Lattnerb35dde12002-05-06 16:49:18 +00002097
Chris Lattner564a7272003-08-13 19:01:45 +00002098 // X + X --> X << 1
Chris Lattner42a75512007-01-15 02:27:26 +00002099 if (I.getType()->isInteger() && I.getType() != Type::Int1Ty) {
Chris Lattner564a7272003-08-13 19:01:45 +00002100 if (Instruction *Result = AssociativeOpt(I, AddRHS(RHS))) return Result;
Chris Lattner7edc8c22005-04-07 17:14:51 +00002101
2102 if (Instruction *RHSI = dyn_cast<Instruction>(RHS)) {
2103 if (RHSI->getOpcode() == Instruction::Sub)
2104 if (LHS == RHSI->getOperand(1)) // A + (B - A) --> B
2105 return ReplaceInstUsesWith(I, RHSI->getOperand(0));
2106 }
2107 if (Instruction *LHSI = dyn_cast<Instruction>(LHS)) {
2108 if (LHSI->getOpcode() == Instruction::Sub)
2109 if (RHS == LHSI->getOperand(1)) // (B - A) + A --> B
2110 return ReplaceInstUsesWith(I, LHSI->getOperand(0));
2111 }
Robert Bocchino71698282004-07-27 21:02:21 +00002112 }
Chris Lattnere92d2f42003-08-13 04:18:28 +00002113
Chris Lattner5c4afb92002-05-08 22:46:53 +00002114 // -A + B --> B - A
Chris Lattnerdd12f962008-02-17 21:03:36 +00002115 // -A + -B --> -(A + B)
2116 if (Value *LHSV = dyn_castNegVal(LHS)) {
Chris Lattnere10c0b92008-02-18 17:50:16 +00002117 if (LHS->getType()->isIntOrIntVector()) {
2118 if (Value *RHSV = dyn_castNegVal(RHS)) {
2119 Instruction *NewAdd = BinaryOperator::createAdd(LHSV, RHSV, "sum");
2120 InsertNewInstBefore(NewAdd, I);
2121 return BinaryOperator::createNeg(NewAdd);
2122 }
Chris Lattnerdd12f962008-02-17 21:03:36 +00002123 }
2124
2125 return BinaryOperator::createSub(RHS, LHSV);
2126 }
Chris Lattnerb35dde12002-05-06 16:49:18 +00002127
2128 // A + -B --> A - B
Chris Lattner8d969642003-03-10 23:06:50 +00002129 if (!isa<Constant>(RHS))
2130 if (Value *V = dyn_castNegVal(RHS))
Chris Lattner48595f12004-06-10 02:07:29 +00002131 return BinaryOperator::createSub(LHS, V);
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002132
Misha Brukmanfd939082005-04-21 23:48:37 +00002133
Chris Lattner50af16a2004-11-13 19:50:12 +00002134 ConstantInt *C2;
2135 if (Value *X = dyn_castFoldableMul(LHS, C2)) {
2136 if (X == RHS) // X*C + X --> X * (C+1)
2137 return BinaryOperator::createMul(RHS, AddOne(C2));
2138
2139 // X*C1 + X*C2 --> X * (C1+C2)
2140 ConstantInt *C1;
2141 if (X == dyn_castFoldableMul(RHS, C1))
Reid Spencer7177c3a2007-03-25 05:33:51 +00002142 return BinaryOperator::createMul(X, Add(C1, C2));
Chris Lattnerad3448c2003-02-18 19:57:07 +00002143 }
2144
2145 // X + X*C --> X * (C+1)
Chris Lattner50af16a2004-11-13 19:50:12 +00002146 if (dyn_castFoldableMul(RHS, C2) == LHS)
2147 return BinaryOperator::createMul(LHS, AddOne(C2));
2148
Chris Lattnere617c9e2007-01-05 02:17:46 +00002149 // X + ~X --> -1 since ~X = -X-1
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00002150 if (dyn_castNotVal(LHS) == RHS || dyn_castNotVal(RHS) == LHS)
2151 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Chris Lattnere617c9e2007-01-05 02:17:46 +00002152
Chris Lattnerad3448c2003-02-18 19:57:07 +00002153
Chris Lattner564a7272003-08-13 19:01:45 +00002154 // (A & C1)+(B & C2) --> (A & C1)|(B & C2) iff C1&C2 == 0
Chris Lattneracd1f0f2004-07-30 07:50:03 +00002155 if (match(RHS, m_And(m_Value(), m_ConstantInt(C2))))
Chris Lattnere617c9e2007-01-05 02:17:46 +00002156 if (Instruction *R = AssociativeOpt(I, AddMaskingAnd(C2)))
2157 return R;
Chris Lattnerc8802d22003-03-11 00:12:48 +00002158
Nick Lewyckyb6eabff2008-02-03 07:42:09 +00002159 // W*X + Y*Z --> W * (X+Z) iff W == Y
Nick Lewycky0c2c3f62008-02-03 08:19:11 +00002160 if (I.getType()->isIntOrIntVector()) {
Nick Lewyckyb6eabff2008-02-03 07:42:09 +00002161 Value *W, *X, *Y, *Z;
2162 if (match(LHS, m_Mul(m_Value(W), m_Value(X))) &&
2163 match(RHS, m_Mul(m_Value(Y), m_Value(Z)))) {
2164 if (W != Y) {
2165 if (W == Z) {
Bill Wendling587c01d2008-02-26 10:53:30 +00002166 std::swap(Y, Z);
Nick Lewyckyb6eabff2008-02-03 07:42:09 +00002167 } else if (Y == X) {
Bill Wendling587c01d2008-02-26 10:53:30 +00002168 std::swap(W, X);
2169 } else if (X == Z) {
Nick Lewyckyb6eabff2008-02-03 07:42:09 +00002170 std::swap(Y, Z);
2171 std::swap(W, X);
2172 }
2173 }
2174
2175 if (W == Y) {
2176 Value *NewAdd = InsertNewInstBefore(BinaryOperator::createAdd(X, Z,
2177 LHS->getName()), I);
2178 return BinaryOperator::createMul(W, NewAdd);
2179 }
2180 }
2181 }
2182
Chris Lattner6b032052003-10-02 15:11:26 +00002183 if (ConstantInt *CRHS = dyn_cast<ConstantInt>(RHS)) {
Chris Lattner4f637d42006-01-06 17:59:59 +00002184 Value *X = 0;
Reid Spencer7177c3a2007-03-25 05:33:51 +00002185 if (match(LHS, m_Not(m_Value(X)))) // ~X + C --> (C-1) - X
2186 return BinaryOperator::createSub(SubOne(CRHS), X);
Chris Lattneracd1f0f2004-07-30 07:50:03 +00002187
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002188 // (X & FF00) + xx00 -> (X+xx00) & FF00
2189 if (LHS->hasOneUse() && match(LHS, m_And(m_Value(X), m_ConstantInt(C2)))) {
Reid Spencer7177c3a2007-03-25 05:33:51 +00002190 Constant *Anded = And(CRHS, C2);
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002191 if (Anded == CRHS) {
2192 // See if all bits from the first bit set in the Add RHS up are included
2193 // in the mask. First, get the rightmost bit.
Zhou Sheng3a507fd2007-04-01 17:13:37 +00002194 const APInt& AddRHSV = CRHS->getValue();
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002195
2196 // Form a mask of all bits from the lowest bit added through the top.
Zhou Sheng3a507fd2007-04-01 17:13:37 +00002197 APInt AddRHSHighBits(~((AddRHSV & -AddRHSV)-1));
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002198
2199 // See if the and mask includes all of these bits.
Zhou Sheng3a507fd2007-04-01 17:13:37 +00002200 APInt AddRHSHighBitsAnd(AddRHSHighBits & C2->getValue());
Misha Brukmanfd939082005-04-21 23:48:37 +00002201
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002202 if (AddRHSHighBits == AddRHSHighBitsAnd) {
2203 // Okay, the xform is safe. Insert the new add pronto.
2204 Value *NewAdd = InsertNewInstBefore(BinaryOperator::createAdd(X, CRHS,
2205 LHS->getName()), I);
2206 return BinaryOperator::createAnd(NewAdd, C2);
2207 }
2208 }
2209 }
2210
Chris Lattneracd1f0f2004-07-30 07:50:03 +00002211 // Try to fold constant add into select arguments.
2212 if (SelectInst *SI = dyn_cast<SelectInst>(LHS))
Chris Lattner6e7ba452005-01-01 16:22:27 +00002213 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattneracd1f0f2004-07-30 07:50:03 +00002214 return R;
Chris Lattner6b032052003-10-02 15:11:26 +00002215 }
2216
Reid Spencer1628cec2006-10-26 06:15:43 +00002217 // add (cast *A to intptrtype) B ->
Chris Lattner42790482007-12-20 01:56:58 +00002218 // cast (GEP (cast *A to sbyte*) B) --> intptrtype
Andrew Lenharth16d79552006-09-19 18:24:51 +00002219 {
Reid Spencer3da59db2006-11-27 01:05:10 +00002220 CastInst *CI = dyn_cast<CastInst>(LHS);
2221 Value *Other = RHS;
Andrew Lenharth16d79552006-09-19 18:24:51 +00002222 if (!CI) {
2223 CI = dyn_cast<CastInst>(RHS);
2224 Other = LHS;
2225 }
Andrew Lenharth45633262006-09-20 15:37:57 +00002226 if (CI && CI->getType()->isSized() &&
Reid Spencerabaa8ca2007-01-08 16:32:00 +00002227 (CI->getType()->getPrimitiveSizeInBits() ==
2228 TD->getIntPtrType()->getPrimitiveSizeInBits())
Andrew Lenharth45633262006-09-20 15:37:57 +00002229 && isa<PointerType>(CI->getOperand(0)->getType())) {
Christopher Lamb43ad6b32007-12-17 01:12:55 +00002230 unsigned AS =
2231 cast<PointerType>(CI->getOperand(0)->getType())->getAddressSpace();
Chris Lattner6d0339d2008-01-13 22:23:22 +00002232 Value *I2 = InsertBitCastBefore(CI->getOperand(0),
2233 PointerType::get(Type::Int8Ty, AS), I);
Andrew Lenharth45633262006-09-20 15:37:57 +00002234 I2 = InsertNewInstBefore(new GetElementPtrInst(I2, Other, "ctg2"), I);
Reid Spencer3da59db2006-11-27 01:05:10 +00002235 return new PtrToIntInst(I2, CI->getType());
Andrew Lenharth16d79552006-09-19 18:24:51 +00002236 }
2237 }
Christopher Lamb30f017a2007-12-18 09:34:41 +00002238
Chris Lattner42790482007-12-20 01:56:58 +00002239 // add (select X 0 (sub n A)) A --> select X A n
Christopher Lamb30f017a2007-12-18 09:34:41 +00002240 {
2241 SelectInst *SI = dyn_cast<SelectInst>(LHS);
2242 Value *Other = RHS;
2243 if (!SI) {
2244 SI = dyn_cast<SelectInst>(RHS);
2245 Other = LHS;
2246 }
Chris Lattner42790482007-12-20 01:56:58 +00002247 if (SI && SI->hasOneUse()) {
Christopher Lamb30f017a2007-12-18 09:34:41 +00002248 Value *TV = SI->getTrueValue();
2249 Value *FV = SI->getFalseValue();
Chris Lattner42790482007-12-20 01:56:58 +00002250 Value *A, *N;
Christopher Lamb30f017a2007-12-18 09:34:41 +00002251
2252 // Can we fold the add into the argument of the select?
2253 // We check both true and false select arguments for a matching subtract.
Chris Lattner42790482007-12-20 01:56:58 +00002254 if (match(FV, m_Zero()) && match(TV, m_Sub(m_Value(N), m_Value(A))) &&
2255 A == Other) // Fold the add into the true select value.
2256 return new SelectInst(SI->getCondition(), N, A);
2257 if (match(TV, m_Zero()) && match(FV, m_Sub(m_Value(N), m_Value(A))) &&
2258 A == Other) // Fold the add into the false select value.
2259 return new SelectInst(SI->getCondition(), A, N);
Christopher Lamb30f017a2007-12-18 09:34:41 +00002260 }
2261 }
Chris Lattner2454a2e2008-01-29 06:52:45 +00002262
2263 // Check for X+0.0. Simplify it to X if we know X is not -0.0.
2264 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHS))
2265 if (CFP->getValueAPF().isPosZero() && CannotBeNegativeZero(LHS))
2266 return ReplaceInstUsesWith(I, LHS);
Andrew Lenharth16d79552006-09-19 18:24:51 +00002267
Chris Lattner7e708292002-06-25 16:13:24 +00002268 return Changed ? &I : 0;
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002269}
2270
Chris Lattner1ba5bcd2003-07-22 21:46:59 +00002271// isSignBit - Return true if the value represented by the constant only has the
2272// highest order bit set.
2273static bool isSignBit(ConstantInt *CI) {
Zhou Sheng4351c642007-04-02 08:20:41 +00002274 uint32_t NumBits = CI->getType()->getPrimitiveSizeInBits();
Reid Spencer5a1e3e12007-03-19 20:58:18 +00002275 return CI->getValue() == APInt::getSignBit(NumBits);
Chris Lattner1ba5bcd2003-07-22 21:46:59 +00002276}
2277
Chris Lattner7e708292002-06-25 16:13:24 +00002278Instruction *InstCombiner::visitSub(BinaryOperator &I) {
Chris Lattner7e708292002-06-25 16:13:24 +00002279 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00002280
Chris Lattner233f7dc2002-08-12 21:17:25 +00002281 if (Op0 == Op1) // sub X, X -> 0
2282 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002283
Chris Lattner233f7dc2002-08-12 21:17:25 +00002284 // If this is a 'B = x-(-A)', change to B = x+A...
Chris Lattner8d969642003-03-10 23:06:50 +00002285 if (Value *V = dyn_castNegVal(Op1))
Chris Lattner48595f12004-06-10 02:07:29 +00002286 return BinaryOperator::createAdd(Op0, V);
Chris Lattnerb35dde12002-05-06 16:49:18 +00002287
Chris Lattnere87597f2004-10-16 18:11:37 +00002288 if (isa<UndefValue>(Op0))
2289 return ReplaceInstUsesWith(I, Op0); // undef - X -> undef
2290 if (isa<UndefValue>(Op1))
2291 return ReplaceInstUsesWith(I, Op1); // X - undef -> undef
2292
Chris Lattnerd65460f2003-11-05 01:06:05 +00002293 if (ConstantInt *C = dyn_cast<ConstantInt>(Op0)) {
2294 // Replace (-1 - A) with (~A)...
Chris Lattnera2881962003-02-18 19:28:33 +00002295 if (C->isAllOnesValue())
2296 return BinaryOperator::createNot(Op1);
Chris Lattner40371712002-05-09 01:29:19 +00002297
Chris Lattnerd65460f2003-11-05 01:06:05 +00002298 // C - ~X == X + (1+C)
Reid Spencer4b828e62005-06-18 17:37:34 +00002299 Value *X = 0;
Chris Lattneracd1f0f2004-07-30 07:50:03 +00002300 if (match(Op1, m_Not(m_Value(X))))
Reid Spencer7177c3a2007-03-25 05:33:51 +00002301 return BinaryOperator::createAdd(X, AddOne(C));
2302
Chris Lattner76b7a062007-01-15 07:02:54 +00002303 // -(X >>u 31) -> (X >>s 31)
2304 // -(X >>s 31) -> (X >>u 31)
Zhou Sheng302748d2007-03-30 17:20:39 +00002305 if (C->isZero()) {
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00002306 if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op1)) {
Reid Spencer3822ff52006-11-08 06:47:33 +00002307 if (SI->getOpcode() == Instruction::LShr) {
Reid Spencerb83eb642006-10-20 07:07:24 +00002308 if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
Chris Lattner9c290672004-03-12 23:53:13 +00002309 // Check to see if we are shifting out everything but the sign bit.
Zhou Sheng302748d2007-03-30 17:20:39 +00002310 if (CU->getLimitedValue(SI->getType()->getPrimitiveSizeInBits()) ==
Reid Spencerb83eb642006-10-20 07:07:24 +00002311 SI->getType()->getPrimitiveSizeInBits()-1) {
Reid Spencer3822ff52006-11-08 06:47:33 +00002312 // Ok, the transformation is safe. Insert AShr.
Reid Spencer832254e2007-02-02 02:16:23 +00002313 return BinaryOperator::create(Instruction::AShr,
2314 SI->getOperand(0), CU, SI->getName());
Chris Lattner9c290672004-03-12 23:53:13 +00002315 }
2316 }
Reid Spencer3822ff52006-11-08 06:47:33 +00002317 }
2318 else if (SI->getOpcode() == Instruction::AShr) {
2319 if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
2320 // Check to see if we are shifting out everything but the sign bit.
Zhou Sheng302748d2007-03-30 17:20:39 +00002321 if (CU->getLimitedValue(SI->getType()->getPrimitiveSizeInBits()) ==
Reid Spencer3822ff52006-11-08 06:47:33 +00002322 SI->getType()->getPrimitiveSizeInBits()-1) {
Reid Spencerc5b206b2006-12-31 05:48:39 +00002323 // Ok, the transformation is safe. Insert LShr.
Reid Spencercc46cdb2007-02-02 14:08:20 +00002324 return BinaryOperator::createLShr(
Reid Spencer832254e2007-02-02 02:16:23 +00002325 SI->getOperand(0), CU, SI->getName());
Reid Spencer3822ff52006-11-08 06:47:33 +00002326 }
2327 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00002328 }
2329 }
Chris Lattnerbfe492b2004-03-13 00:11:49 +00002330 }
Chris Lattner2eefe512004-04-09 19:05:30 +00002331
2332 // Try to fold constant sub into select arguments.
2333 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
Chris Lattner6e7ba452005-01-01 16:22:27 +00002334 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00002335 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00002336
2337 if (isa<PHINode>(Op0))
2338 if (Instruction *NV = FoldOpIntoPhi(I))
2339 return NV;
Chris Lattnerd65460f2003-11-05 01:06:05 +00002340 }
2341
Chris Lattner43d84d62005-04-07 16:15:25 +00002342 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
2343 if (Op1I->getOpcode() == Instruction::Add &&
Chris Lattner9919e3d2006-12-02 00:13:08 +00002344 !Op0->getType()->isFPOrFPVector()) {
Chris Lattner08954a22005-04-07 16:28:01 +00002345 if (Op1I->getOperand(0) == Op0) // X-(X+Y) == -Y
Chris Lattner43d84d62005-04-07 16:15:25 +00002346 return BinaryOperator::createNeg(Op1I->getOperand(1), I.getName());
Chris Lattner08954a22005-04-07 16:28:01 +00002347 else if (Op1I->getOperand(1) == Op0) // X-(Y+X) == -Y
Chris Lattner43d84d62005-04-07 16:15:25 +00002348 return BinaryOperator::createNeg(Op1I->getOperand(0), I.getName());
Chris Lattner08954a22005-04-07 16:28:01 +00002349 else if (ConstantInt *CI1 = dyn_cast<ConstantInt>(I.getOperand(0))) {
2350 if (ConstantInt *CI2 = dyn_cast<ConstantInt>(Op1I->getOperand(1)))
2351 // C1-(X+C2) --> (C1-C2)-X
Reid Spencer7177c3a2007-03-25 05:33:51 +00002352 return BinaryOperator::createSub(Subtract(CI1, CI2),
Chris Lattner08954a22005-04-07 16:28:01 +00002353 Op1I->getOperand(0));
2354 }
Chris Lattner43d84d62005-04-07 16:15:25 +00002355 }
2356
Chris Lattnerfd059242003-10-15 16:48:29 +00002357 if (Op1I->hasOneUse()) {
Chris Lattnera2881962003-02-18 19:28:33 +00002358 // Replace (x - (y - z)) with (x + (z - y)) if the (y - z) subexpression
2359 // is not used by anyone else...
2360 //
Chris Lattner0517e722004-02-02 20:09:56 +00002361 if (Op1I->getOpcode() == Instruction::Sub &&
Chris Lattner9919e3d2006-12-02 00:13:08 +00002362 !Op1I->getType()->isFPOrFPVector()) {
Chris Lattnera2881962003-02-18 19:28:33 +00002363 // Swap the two operands of the subexpr...
2364 Value *IIOp0 = Op1I->getOperand(0), *IIOp1 = Op1I->getOperand(1);
2365 Op1I->setOperand(0, IIOp1);
2366 Op1I->setOperand(1, IIOp0);
Misha Brukmanfd939082005-04-21 23:48:37 +00002367
Chris Lattnera2881962003-02-18 19:28:33 +00002368 // Create the new top level add instruction...
Chris Lattner48595f12004-06-10 02:07:29 +00002369 return BinaryOperator::createAdd(Op0, Op1);
Chris Lattnera2881962003-02-18 19:28:33 +00002370 }
2371
2372 // Replace (A - (A & B)) with (A & ~B) if this is the only use of (A&B)...
2373 //
2374 if (Op1I->getOpcode() == Instruction::And &&
2375 (Op1I->getOperand(0) == Op0 || Op1I->getOperand(1) == Op0)) {
2376 Value *OtherOp = Op1I->getOperand(Op1I->getOperand(0) == Op0);
2377
Chris Lattnerf523d062004-06-09 05:08:07 +00002378 Value *NewNot =
2379 InsertNewInstBefore(BinaryOperator::createNot(OtherOp, "B.not"), I);
Chris Lattner48595f12004-06-10 02:07:29 +00002380 return BinaryOperator::createAnd(Op0, NewNot);
Chris Lattnera2881962003-02-18 19:28:33 +00002381 }
Chris Lattnerad3448c2003-02-18 19:57:07 +00002382
Reid Spencerac5209e2006-10-16 23:08:08 +00002383 // 0 - (X sdiv C) -> (X sdiv -C)
Reid Spencer1628cec2006-10-26 06:15:43 +00002384 if (Op1I->getOpcode() == Instruction::SDiv)
Reid Spencerb83eb642006-10-20 07:07:24 +00002385 if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
Zhou Sheng843f07672007-04-19 05:39:12 +00002386 if (CSI->isZero())
Chris Lattner91ccc152004-10-06 15:08:25 +00002387 if (Constant *DivRHS = dyn_cast<Constant>(Op1I->getOperand(1)))
Reid Spencer1628cec2006-10-26 06:15:43 +00002388 return BinaryOperator::createSDiv(Op1I->getOperand(0),
Chris Lattner91ccc152004-10-06 15:08:25 +00002389 ConstantExpr::getNeg(DivRHS));
2390
Chris Lattnerad3448c2003-02-18 19:57:07 +00002391 // X - X*C --> X * (1-C)
Reid Spencer4b828e62005-06-18 17:37:34 +00002392 ConstantInt *C2 = 0;
Chris Lattner50af16a2004-11-13 19:50:12 +00002393 if (dyn_castFoldableMul(Op1I, C2) == Op0) {
Reid Spencer7177c3a2007-03-25 05:33:51 +00002394 Constant *CP1 = Subtract(ConstantInt::get(I.getType(), 1), C2);
Chris Lattner48595f12004-06-10 02:07:29 +00002395 return BinaryOperator::createMul(Op0, CP1);
Chris Lattnerad3448c2003-02-18 19:57:07 +00002396 }
Dan Gohman5d066ff2007-09-17 17:31:57 +00002397
2398 // X - ((X / Y) * Y) --> X % Y
2399 if (Op1I->getOpcode() == Instruction::Mul)
2400 if (Instruction *I = dyn_cast<Instruction>(Op1I->getOperand(0)))
2401 if (Op0 == I->getOperand(0) &&
2402 Op1I->getOperand(1) == I->getOperand(1)) {
2403 if (I->getOpcode() == Instruction::SDiv)
2404 return BinaryOperator::createSRem(Op0, Op1I->getOperand(1));
2405 if (I->getOpcode() == Instruction::UDiv)
2406 return BinaryOperator::createURem(Op0, Op1I->getOperand(1));
2407 }
Chris Lattner40371712002-05-09 01:29:19 +00002408 }
Chris Lattner43d84d62005-04-07 16:15:25 +00002409 }
Chris Lattnera2881962003-02-18 19:28:33 +00002410
Chris Lattner9919e3d2006-12-02 00:13:08 +00002411 if (!Op0->getType()->isFPOrFPVector())
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00002412 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
Chris Lattner7edc8c22005-04-07 17:14:51 +00002413 if (Op0I->getOpcode() == Instruction::Add) {
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00002414 if (Op0I->getOperand(0) == Op1) // (Y+X)-Y == X
2415 return ReplaceInstUsesWith(I, Op0I->getOperand(1));
2416 else if (Op0I->getOperand(1) == Op1) // (X+Y)-Y == X
2417 return ReplaceInstUsesWith(I, Op0I->getOperand(0));
Chris Lattner7edc8c22005-04-07 17:14:51 +00002418 } else if (Op0I->getOpcode() == Instruction::Sub) {
2419 if (Op0I->getOperand(0) == Op1) // (X-Y)-X == -Y
2420 return BinaryOperator::createNeg(Op0I->getOperand(1), I.getName());
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00002421 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00002422 }
Misha Brukmanfd939082005-04-21 23:48:37 +00002423
Chris Lattner50af16a2004-11-13 19:50:12 +00002424 ConstantInt *C1;
2425 if (Value *X = dyn_castFoldableMul(Op0, C1)) {
Reid Spencer7177c3a2007-03-25 05:33:51 +00002426 if (X == Op1) // X*C - X --> X * (C-1)
2427 return BinaryOperator::createMul(Op1, SubOne(C1));
Chris Lattnerad3448c2003-02-18 19:57:07 +00002428
Chris Lattner50af16a2004-11-13 19:50:12 +00002429 ConstantInt *C2; // X*C1 - X*C2 -> X * (C1-C2)
2430 if (X == dyn_castFoldableMul(Op1, C2))
Zhou Sheng58d13af2008-02-22 10:00:35 +00002431 return BinaryOperator::createMul(X, Subtract(C1, C2));
Chris Lattner50af16a2004-11-13 19:50:12 +00002432 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00002433 return 0;
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002434}
2435
Chris Lattnera0141b92007-07-15 20:42:37 +00002436/// isSignBitCheck - Given an exploded icmp instruction, return true if the
2437/// comparison only checks the sign bit. If it only checks the sign bit, set
2438/// TrueIfSigned if the result of the comparison is true when the input value is
2439/// signed.
2440static bool isSignBitCheck(ICmpInst::Predicate pred, ConstantInt *RHS,
2441 bool &TrueIfSigned) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00002442 switch (pred) {
Chris Lattnera0141b92007-07-15 20:42:37 +00002443 case ICmpInst::ICMP_SLT: // True if LHS s< 0
2444 TrueIfSigned = true;
2445 return RHS->isZero();
Chris Lattnercb7122b2007-07-16 04:15:34 +00002446 case ICmpInst::ICMP_SLE: // True if LHS s<= RHS and RHS == -1
2447 TrueIfSigned = true;
2448 return RHS->isAllOnesValue();
Chris Lattnera0141b92007-07-15 20:42:37 +00002449 case ICmpInst::ICMP_SGT: // True if LHS s> -1
2450 TrueIfSigned = false;
2451 return RHS->isAllOnesValue();
Chris Lattnercb7122b2007-07-16 04:15:34 +00002452 case ICmpInst::ICMP_UGT:
2453 // True if LHS u> RHS and RHS == high-bit-mask - 1
2454 TrueIfSigned = true;
2455 return RHS->getValue() ==
2456 APInt::getSignedMaxValue(RHS->getType()->getPrimitiveSizeInBits());
2457 case ICmpInst::ICMP_UGE:
2458 // True if LHS u>= RHS and RHS == high-bit-mask (2^7, 2^15, 2^31, etc)
2459 TrueIfSigned = true;
2460 return RHS->getValue() ==
2461 APInt::getSignBit(RHS->getType()->getPrimitiveSizeInBits());
Chris Lattnera0141b92007-07-15 20:42:37 +00002462 default:
2463 return false;
Chris Lattner4cb170c2004-02-23 06:38:22 +00002464 }
Chris Lattner4cb170c2004-02-23 06:38:22 +00002465}
2466
Chris Lattner7e708292002-06-25 16:13:24 +00002467Instruction *InstCombiner::visitMul(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00002468 bool Changed = SimplifyCommutative(I);
Chris Lattnera2881962003-02-18 19:28:33 +00002469 Value *Op0 = I.getOperand(0);
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002470
Chris Lattnere87597f2004-10-16 18:11:37 +00002471 if (isa<UndefValue>(I.getOperand(1))) // undef * X -> 0
2472 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2473
Chris Lattner233f7dc2002-08-12 21:17:25 +00002474 // Simplify mul instructions with a constant RHS...
Chris Lattnera2881962003-02-18 19:28:33 +00002475 if (Constant *Op1 = dyn_cast<Constant>(I.getOperand(1))) {
2476 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Chris Lattnere92d2f42003-08-13 04:18:28 +00002477
2478 // ((X << C1)*C2) == (X * (C2 << C1))
Reid Spencer832254e2007-02-02 02:16:23 +00002479 if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op0))
Chris Lattnere92d2f42003-08-13 04:18:28 +00002480 if (SI->getOpcode() == Instruction::Shl)
2481 if (Constant *ShOp = dyn_cast<Constant>(SI->getOperand(1)))
Chris Lattner48595f12004-06-10 02:07:29 +00002482 return BinaryOperator::createMul(SI->getOperand(0),
2483 ConstantExpr::getShl(CI, ShOp));
Misha Brukmanfd939082005-04-21 23:48:37 +00002484
Zhou Sheng843f07672007-04-19 05:39:12 +00002485 if (CI->isZero())
Chris Lattner515c97c2003-09-11 22:24:54 +00002486 return ReplaceInstUsesWith(I, Op1); // X * 0 == 0
2487 if (CI->equalsInt(1)) // X * 1 == X
2488 return ReplaceInstUsesWith(I, Op0);
2489 if (CI->isAllOnesValue()) // X * -1 == 0 - X
Chris Lattner0af1fab2003-06-25 17:09:20 +00002490 return BinaryOperator::createNeg(Op0, I.getName());
Chris Lattner6c1ce212002-04-29 22:24:47 +00002491
Zhou Sheng97b52c22007-03-29 01:57:21 +00002492 const APInt& Val = cast<ConstantInt>(CI)->getValue();
Reid Spencerbca0e382007-03-23 20:05:17 +00002493 if (Val.isPowerOf2()) { // Replace X*(2^C) with X << C
Reid Spencercc46cdb2007-02-02 14:08:20 +00002494 return BinaryOperator::createShl(Op0,
Reid Spencerbca0e382007-03-23 20:05:17 +00002495 ConstantInt::get(Op0->getType(), Val.logBase2()));
Chris Lattnerbcd7db52005-08-02 19:16:58 +00002496 }
Robert Bocchino71698282004-07-27 21:02:21 +00002497 } else if (ConstantFP *Op1F = dyn_cast<ConstantFP>(Op1)) {
Chris Lattnera2881962003-02-18 19:28:33 +00002498 if (Op1F->isNullValue())
2499 return ReplaceInstUsesWith(I, Op1);
Chris Lattner6c1ce212002-04-29 22:24:47 +00002500
Chris Lattnera2881962003-02-18 19:28:33 +00002501 // "In IEEE floating point, x*1 is not equivalent to x for nans. However,
2502 // ANSI says we can drop signals, so we can do this anyway." (from GCC)
Dale Johannesen9e3d3ab2007-09-14 22:26:36 +00002503 // We need a better interface for long double here.
2504 if (Op1->getType() == Type::FloatTy || Op1->getType() == Type::DoubleTy)
2505 if (Op1F->isExactlyValue(1.0))
2506 return ReplaceInstUsesWith(I, Op0); // Eliminate 'mul double %X, 1.0'
Chris Lattnera2881962003-02-18 19:28:33 +00002507 }
Chris Lattnerab51f3f2006-03-04 06:04:02 +00002508
2509 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
2510 if (Op0I->getOpcode() == Instruction::Add && Op0I->hasOneUse() &&
2511 isa<ConstantInt>(Op0I->getOperand(1))) {
2512 // Canonicalize (X+C1)*C2 -> X*C2+C1*C2.
2513 Instruction *Add = BinaryOperator::createMul(Op0I->getOperand(0),
2514 Op1, "tmp");
2515 InsertNewInstBefore(Add, I);
2516 Value *C1C2 = ConstantExpr::getMul(Op1,
2517 cast<Constant>(Op0I->getOperand(1)));
2518 return BinaryOperator::createAdd(Add, C1C2);
2519
2520 }
Chris Lattner2eefe512004-04-09 19:05:30 +00002521
2522 // Try to fold constant mul into select arguments.
2523 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner6e7ba452005-01-01 16:22:27 +00002524 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00002525 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00002526
2527 if (isa<PHINode>(Op0))
2528 if (Instruction *NV = FoldOpIntoPhi(I))
2529 return NV;
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002530 }
2531
Chris Lattnera4f445b2003-03-10 23:23:04 +00002532 if (Value *Op0v = dyn_castNegVal(Op0)) // -X * -Y = X*Y
2533 if (Value *Op1v = dyn_castNegVal(I.getOperand(1)))
Chris Lattner48595f12004-06-10 02:07:29 +00002534 return BinaryOperator::createMul(Op0v, Op1v);
Chris Lattnera4f445b2003-03-10 23:23:04 +00002535
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002536 // If one of the operands of the multiply is a cast from a boolean value, then
2537 // we know the bool is either zero or one, so this is a 'masking' multiply.
2538 // See if we can simplify things based on how the boolean was originally
2539 // formed.
2540 CastInst *BoolCast = 0;
Reid Spencerc55b2432006-12-13 18:21:21 +00002541 if (ZExtInst *CI = dyn_cast<ZExtInst>(I.getOperand(0)))
Reid Spencer4fe16d62007-01-11 18:21:29 +00002542 if (CI->getOperand(0)->getType() == Type::Int1Ty)
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002543 BoolCast = CI;
2544 if (!BoolCast)
Reid Spencerc55b2432006-12-13 18:21:21 +00002545 if (ZExtInst *CI = dyn_cast<ZExtInst>(I.getOperand(1)))
Reid Spencer4fe16d62007-01-11 18:21:29 +00002546 if (CI->getOperand(0)->getType() == Type::Int1Ty)
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002547 BoolCast = CI;
2548 if (BoolCast) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00002549 if (ICmpInst *SCI = dyn_cast<ICmpInst>(BoolCast->getOperand(0))) {
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002550 Value *SCIOp0 = SCI->getOperand(0), *SCIOp1 = SCI->getOperand(1);
2551 const Type *SCOpTy = SCIOp0->getType();
Chris Lattnera0141b92007-07-15 20:42:37 +00002552 bool TIS = false;
2553
Reid Spencere4d87aa2006-12-23 06:05:41 +00002554 // If the icmp is true iff the sign bit of X is set, then convert this
Chris Lattner4cb170c2004-02-23 06:38:22 +00002555 // multiply into a shift/and combination.
2556 if (isa<ConstantInt>(SCIOp1) &&
Chris Lattnera0141b92007-07-15 20:42:37 +00002557 isSignBitCheck(SCI->getPredicate(), cast<ConstantInt>(SCIOp1), TIS) &&
2558 TIS) {
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002559 // Shift the X value right to turn it into "all signbits".
Reid Spencer832254e2007-02-02 02:16:23 +00002560 Constant *Amt = ConstantInt::get(SCIOp0->getType(),
Chris Lattner484d3cf2005-04-24 06:59:08 +00002561 SCOpTy->getPrimitiveSizeInBits()-1);
Chris Lattner4cb170c2004-02-23 06:38:22 +00002562 Value *V =
Reid Spencer832254e2007-02-02 02:16:23 +00002563 InsertNewInstBefore(
2564 BinaryOperator::create(Instruction::AShr, SCIOp0, Amt,
Chris Lattner4cb170c2004-02-23 06:38:22 +00002565 BoolCast->getOperand(0)->getName()+
2566 ".mask"), I);
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002567
2568 // If the multiply type is not the same as the source type, sign extend
2569 // or truncate to the multiply type.
Reid Spencer17212df2006-12-12 09:18:51 +00002570 if (I.getType() != V->getType()) {
Zhou Sheng4351c642007-04-02 08:20:41 +00002571 uint32_t SrcBits = V->getType()->getPrimitiveSizeInBits();
2572 uint32_t DstBits = I.getType()->getPrimitiveSizeInBits();
Reid Spencer17212df2006-12-12 09:18:51 +00002573 Instruction::CastOps opcode =
2574 (SrcBits == DstBits ? Instruction::BitCast :
2575 (SrcBits < DstBits ? Instruction::SExt : Instruction::Trunc));
2576 V = InsertCastBefore(opcode, V, I.getType(), I);
2577 }
Misha Brukmanfd939082005-04-21 23:48:37 +00002578
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002579 Value *OtherOp = Op0 == BoolCast ? I.getOperand(1) : Op0;
Chris Lattner48595f12004-06-10 02:07:29 +00002580 return BinaryOperator::createAnd(V, OtherOp);
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00002581 }
2582 }
2583 }
2584
Chris Lattner7e708292002-06-25 16:13:24 +00002585 return Changed ? &I : 0;
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002586}
2587
Reid Spencer1628cec2006-10-26 06:15:43 +00002588/// This function implements the transforms on div instructions that work
2589/// regardless of the kind of div instruction it is (udiv, sdiv, or fdiv). It is
2590/// used by the visitors to those instructions.
2591/// @brief Transforms common to all three div instructions
Reid Spencer3da59db2006-11-27 01:05:10 +00002592Instruction *InstCombiner::commonDivTransforms(BinaryOperator &I) {
Chris Lattner857e8cd2004-12-12 21:48:58 +00002593 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnere87597f2004-10-16 18:11:37 +00002594
Chris Lattner50b2ca42008-02-19 06:12:18 +00002595 // undef / X -> 0 for integer.
2596 // undef / X -> undef for FP (the undef could be a snan).
2597 if (isa<UndefValue>(Op0)) {
2598 if (Op0->getType()->isFPOrFPVector())
2599 return ReplaceInstUsesWith(I, Op0);
Chris Lattner857e8cd2004-12-12 21:48:58 +00002600 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner50b2ca42008-02-19 06:12:18 +00002601 }
Reid Spencer1628cec2006-10-26 06:15:43 +00002602
2603 // X / undef -> undef
Chris Lattner857e8cd2004-12-12 21:48:58 +00002604 if (isa<UndefValue>(Op1))
Reid Spencer1628cec2006-10-26 06:15:43 +00002605 return ReplaceInstUsesWith(I, Op1);
Chris Lattner857e8cd2004-12-12 21:48:58 +00002606
Chris Lattner25feae52008-01-28 00:58:18 +00002607 // Handle cases involving: [su]div X, (select Cond, Y, Z)
2608 // This does not apply for fdiv.
Chris Lattner8e49e082006-09-09 20:26:32 +00002609 if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
Chris Lattner25feae52008-01-28 00:58:18 +00002610 // [su]div X, (Cond ? 0 : Y) -> div X, Y. If the div and the select are in
2611 // the same basic block, then we replace the select with Y, and the
2612 // condition of the select with false (if the cond value is in the same BB).
2613 // If the select has uses other than the div, this allows them to be
2614 // simplified also. Note that div X, Y is just as good as div X, 0 (undef)
2615 if (ConstantInt *ST = dyn_cast<ConstantInt>(SI->getOperand(1)))
Chris Lattner8e49e082006-09-09 20:26:32 +00002616 if (ST->isNullValue()) {
2617 Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
2618 if (CondI && CondI->getParent() == I.getParent())
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00002619 UpdateValueUsesWith(CondI, ConstantInt::getFalse());
Chris Lattner8e49e082006-09-09 20:26:32 +00002620 else if (I.getParent() != SI->getParent() || SI->hasOneUse())
2621 I.setOperand(1, SI->getOperand(2));
2622 else
2623 UpdateValueUsesWith(SI, SI->getOperand(2));
2624 return &I;
2625 }
Reid Spencer1628cec2006-10-26 06:15:43 +00002626
Chris Lattner25feae52008-01-28 00:58:18 +00002627 // Likewise for: [su]div X, (Cond ? Y : 0) -> div X, Y
2628 if (ConstantInt *ST = dyn_cast<ConstantInt>(SI->getOperand(2)))
Chris Lattner8e49e082006-09-09 20:26:32 +00002629 if (ST->isNullValue()) {
2630 Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
2631 if (CondI && CondI->getParent() == I.getParent())
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00002632 UpdateValueUsesWith(CondI, ConstantInt::getTrue());
Chris Lattner8e49e082006-09-09 20:26:32 +00002633 else if (I.getParent() != SI->getParent() || SI->hasOneUse())
2634 I.setOperand(1, SI->getOperand(1));
2635 else
2636 UpdateValueUsesWith(SI, SI->getOperand(1));
2637 return &I;
2638 }
Reid Spencer1628cec2006-10-26 06:15:43 +00002639 }
Chris Lattner8e49e082006-09-09 20:26:32 +00002640
Reid Spencer1628cec2006-10-26 06:15:43 +00002641 return 0;
2642}
Misha Brukmanfd939082005-04-21 23:48:37 +00002643
Reid Spencer1628cec2006-10-26 06:15:43 +00002644/// This function implements the transforms common to both integer division
2645/// instructions (udiv and sdiv). It is called by the visitors to those integer
2646/// division instructions.
2647/// @brief Common integer divide transforms
Reid Spencer3da59db2006-11-27 01:05:10 +00002648Instruction *InstCombiner::commonIDivTransforms(BinaryOperator &I) {
Reid Spencer1628cec2006-10-26 06:15:43 +00002649 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2650
2651 if (Instruction *Common = commonDivTransforms(I))
2652 return Common;
2653
2654 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2655 // div X, 1 == X
2656 if (RHS->equalsInt(1))
2657 return ReplaceInstUsesWith(I, Op0);
2658
2659 // (X / C1) / C2 -> X / (C1*C2)
2660 if (Instruction *LHS = dyn_cast<Instruction>(Op0))
2661 if (Instruction::BinaryOps(LHS->getOpcode()) == I.getOpcode())
2662 if (ConstantInt *LHSRHS = dyn_cast<ConstantInt>(LHS->getOperand(1))) {
Nick Lewyckye0cfecf2008-02-18 22:48:05 +00002663 if (MultiplyOverflows(RHS, LHSRHS, I.getOpcode()==Instruction::SDiv))
2664 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2665 else
2666 return BinaryOperator::create(I.getOpcode(), LHS->getOperand(0),
2667 Multiply(RHS, LHSRHS));
Chris Lattnerbf70b832005-04-08 04:03:26 +00002668 }
Reid Spencer1628cec2006-10-26 06:15:43 +00002669
Reid Spencerbca0e382007-03-23 20:05:17 +00002670 if (!RHS->isZero()) { // avoid X udiv 0
Reid Spencer1628cec2006-10-26 06:15:43 +00002671 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2672 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2673 return R;
2674 if (isa<PHINode>(Op0))
2675 if (Instruction *NV = FoldOpIntoPhi(I))
2676 return NV;
2677 }
Chris Lattner8e49e082006-09-09 20:26:32 +00002678 }
Misha Brukmanfd939082005-04-21 23:48:37 +00002679
Chris Lattnera2881962003-02-18 19:28:33 +00002680 // 0 / X == 0, we don't need to preserve faults!
Chris Lattner857e8cd2004-12-12 21:48:58 +00002681 if (ConstantInt *LHS = dyn_cast<ConstantInt>(Op0))
Chris Lattnera2881962003-02-18 19:28:33 +00002682 if (LHS->equalsInt(0))
2683 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2684
Reid Spencer1628cec2006-10-26 06:15:43 +00002685 return 0;
2686}
2687
2688Instruction *InstCombiner::visitUDiv(BinaryOperator &I) {
2689 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2690
2691 // Handle the integer div common cases
2692 if (Instruction *Common = commonIDivTransforms(I))
2693 return Common;
2694
2695 // X udiv C^2 -> X >> C
2696 // Check to see if this is an unsigned division with an exact power of 2,
2697 // if so, convert to a right shift.
2698 if (ConstantInt *C = dyn_cast<ConstantInt>(Op1)) {
Reid Spencer6eb0d992007-03-26 23:58:26 +00002699 if (C->getValue().isPowerOf2()) // 0 not included in isPowerOf2
Reid Spencerbca0e382007-03-23 20:05:17 +00002700 return BinaryOperator::createLShr(Op0,
Zhou Sheng0fc50952007-03-25 05:01:29 +00002701 ConstantInt::get(Op0->getType(), C->getValue().logBase2()));
Reid Spencer1628cec2006-10-26 06:15:43 +00002702 }
2703
2704 // X udiv (C1 << N), where C1 is "1<<C2" --> X >> (N+C2)
Reid Spencer832254e2007-02-02 02:16:23 +00002705 if (BinaryOperator *RHSI = dyn_cast<BinaryOperator>(I.getOperand(1))) {
Reid Spencer1628cec2006-10-26 06:15:43 +00002706 if (RHSI->getOpcode() == Instruction::Shl &&
2707 isa<ConstantInt>(RHSI->getOperand(0))) {
Zhou Sheng3a507fd2007-04-01 17:13:37 +00002708 const APInt& C1 = cast<ConstantInt>(RHSI->getOperand(0))->getValue();
Reid Spencerbca0e382007-03-23 20:05:17 +00002709 if (C1.isPowerOf2()) {
Reid Spencer1628cec2006-10-26 06:15:43 +00002710 Value *N = RHSI->getOperand(1);
Reid Spencer3da59db2006-11-27 01:05:10 +00002711 const Type *NTy = N->getType();
Reid Spencer2ec619a2007-03-23 21:24:59 +00002712 if (uint32_t C2 = C1.logBase2()) {
Reid Spencer1628cec2006-10-26 06:15:43 +00002713 Constant *C2V = ConstantInt::get(NTy, C2);
2714 N = InsertNewInstBefore(BinaryOperator::createAdd(N, C2V, "tmp"), I);
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00002715 }
Reid Spencercc46cdb2007-02-02 14:08:20 +00002716 return BinaryOperator::createLShr(Op0, N);
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00002717 }
2718 }
Chris Lattnerc812e5d2005-11-05 07:40:31 +00002719 }
2720
Reid Spencer1628cec2006-10-26 06:15:43 +00002721 // udiv X, (Select Cond, C1, C2) --> Select Cond, (shr X, C1), (shr X, C2)
2722 // where C1&C2 are powers of two.
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00002723 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
Reid Spencer1628cec2006-10-26 06:15:43 +00002724 if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00002725 if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2))) {
Zhou Sheng3a507fd2007-04-01 17:13:37 +00002726 const APInt &TVA = STO->getValue(), &FVA = SFO->getValue();
Reid Spencerbca0e382007-03-23 20:05:17 +00002727 if (TVA.isPowerOf2() && FVA.isPowerOf2()) {
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00002728 // Compute the shift amounts
Reid Spencerbca0e382007-03-23 20:05:17 +00002729 uint32_t TSA = TVA.logBase2(), FSA = FVA.logBase2();
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00002730 // Construct the "on true" case of the select
2731 Constant *TC = ConstantInt::get(Op0->getType(), TSA);
2732 Instruction *TSI = BinaryOperator::createLShr(
2733 Op0, TC, SI->getName()+".t");
2734 TSI = InsertNewInstBefore(TSI, I);
2735
2736 // Construct the "on false" case of the select
2737 Constant *FC = ConstantInt::get(Op0->getType(), FSA);
2738 Instruction *FSI = BinaryOperator::createLShr(
2739 Op0, FC, SI->getName()+".f");
2740 FSI = InsertNewInstBefore(FSI, I);
Reid Spencer1628cec2006-10-26 06:15:43 +00002741
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00002742 // construct the select instruction and return it.
2743 return new SelectInst(SI->getOperand(0), TSI, FSI, SI->getName());
Reid Spencer1628cec2006-10-26 06:15:43 +00002744 }
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00002745 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00002746 return 0;
2747}
2748
Reid Spencer1628cec2006-10-26 06:15:43 +00002749Instruction *InstCombiner::visitSDiv(BinaryOperator &I) {
2750 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2751
2752 // Handle the integer div common cases
2753 if (Instruction *Common = commonIDivTransforms(I))
2754 return Common;
2755
2756 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2757 // sdiv X, -1 == -X
2758 if (RHS->isAllOnesValue())
2759 return BinaryOperator::createNeg(Op0);
2760
2761 // -X/C -> X/-C
2762 if (Value *LHSNeg = dyn_castNegVal(Op0))
2763 return BinaryOperator::createSDiv(LHSNeg, ConstantExpr::getNeg(RHS));
2764 }
2765
2766 // If the sign bits of both operands are zero (i.e. we can prove they are
2767 // unsigned inputs), turn this into a udiv.
Chris Lattner42a75512007-01-15 02:27:26 +00002768 if (I.getType()->isInteger()) {
Reid Spencerbca0e382007-03-23 20:05:17 +00002769 APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
Reid Spencer1628cec2006-10-26 06:15:43 +00002770 if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
Dan Gohmancff55092007-11-05 23:16:33 +00002771 // X sdiv Y -> X udiv Y, iff X and Y don't have sign bit set
Reid Spencer1628cec2006-10-26 06:15:43 +00002772 return BinaryOperator::createUDiv(Op0, Op1, I.getName());
2773 }
2774 }
2775
2776 return 0;
2777}
2778
2779Instruction *InstCombiner::visitFDiv(BinaryOperator &I) {
2780 return commonDivTransforms(I);
2781}
Chris Lattner3f5b8772002-05-06 16:14:14 +00002782
Chris Lattnerdb3f8732006-03-02 06:50:58 +00002783/// GetFactor - If we can prove that the specified value is at least a multiple
2784/// of some factor, return that factor.
2785static Constant *GetFactor(Value *V) {
2786 if (ConstantInt *CI = dyn_cast<ConstantInt>(V))
2787 return CI;
2788
2789 // Unless we can be tricky, we know this is a multiple of 1.
2790 Constant *Result = ConstantInt::get(V->getType(), 1);
2791
2792 Instruction *I = dyn_cast<Instruction>(V);
2793 if (!I) return Result;
2794
2795 if (I->getOpcode() == Instruction::Mul) {
2796 // Handle multiplies by a constant, etc.
2797 return ConstantExpr::getMul(GetFactor(I->getOperand(0)),
2798 GetFactor(I->getOperand(1)));
2799 } else if (I->getOpcode() == Instruction::Shl) {
2800 // (X<<C) -> X * (1 << C)
2801 if (Constant *ShRHS = dyn_cast<Constant>(I->getOperand(1))) {
2802 ShRHS = ConstantExpr::getShl(Result, ShRHS);
2803 return ConstantExpr::getMul(GetFactor(I->getOperand(0)), ShRHS);
2804 }
2805 } else if (I->getOpcode() == Instruction::And) {
2806 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
2807 // X & 0xFFF0 is known to be a multiple of 16.
Reid Spencerf2442522007-03-24 00:42:08 +00002808 uint32_t Zeros = RHS->getValue().countTrailingZeros();
Chris Lattner148083a2007-11-23 22:35:18 +00002809 if (Zeros != V->getType()->getPrimitiveSizeInBits())// don't shift by "32"
Chris Lattnerdb3f8732006-03-02 06:50:58 +00002810 return ConstantExpr::getShl(Result,
Reid Spencer832254e2007-02-02 02:16:23 +00002811 ConstantInt::get(Result->getType(), Zeros));
Chris Lattnerdb3f8732006-03-02 06:50:58 +00002812 }
Reid Spencer3da59db2006-11-27 01:05:10 +00002813 } else if (CastInst *CI = dyn_cast<CastInst>(I)) {
Chris Lattnerdb3f8732006-03-02 06:50:58 +00002814 // Only handle int->int casts.
Reid Spencer3da59db2006-11-27 01:05:10 +00002815 if (!CI->isIntegerCast())
2816 return Result;
2817 Value *Op = CI->getOperand(0);
2818 return ConstantExpr::getCast(CI->getOpcode(), GetFactor(Op), V->getType());
Chris Lattnerdb3f8732006-03-02 06:50:58 +00002819 }
2820 return Result;
2821}
2822
Reid Spencer0a783f72006-11-02 01:53:59 +00002823/// This function implements the transforms on rem instructions that work
2824/// regardless of the kind of rem instruction it is (urem, srem, or frem). It
2825/// is used by the visitors to those instructions.
2826/// @brief Transforms common to all three rem instructions
2827Instruction *InstCombiner::commonRemTransforms(BinaryOperator &I) {
Chris Lattner857e8cd2004-12-12 21:48:58 +00002828 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Reid Spencer0a783f72006-11-02 01:53:59 +00002829
Chris Lattner50b2ca42008-02-19 06:12:18 +00002830 // 0 % X == 0 for integer, we don't need to preserve faults!
Chris Lattner19ccd5c2006-02-28 05:30:45 +00002831 if (Constant *LHS = dyn_cast<Constant>(Op0))
2832 if (LHS->isNullValue())
2833 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2834
Chris Lattner50b2ca42008-02-19 06:12:18 +00002835 if (isa<UndefValue>(Op0)) { // undef % X -> 0
2836 if (I.getType()->isFPOrFPVector())
2837 return ReplaceInstUsesWith(I, Op0); // X % undef -> undef (could be SNaN)
Chris Lattner19ccd5c2006-02-28 05:30:45 +00002838 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner50b2ca42008-02-19 06:12:18 +00002839 }
Chris Lattner19ccd5c2006-02-28 05:30:45 +00002840 if (isa<UndefValue>(Op1))
2841 return ReplaceInstUsesWith(I, Op1); // X % undef -> undef
Reid Spencer0a783f72006-11-02 01:53:59 +00002842
2843 // Handle cases involving: rem X, (select Cond, Y, Z)
2844 if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
2845 // rem X, (Cond ? 0 : Y) -> rem X, Y. If the rem and the select are in
2846 // the same basic block, then we replace the select with Y, and the
2847 // condition of the select with false (if the cond value is in the same
2848 // BB). If the select has uses other than the div, this allows them to be
2849 // simplified also.
2850 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(1)))
2851 if (ST->isNullValue()) {
2852 Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
2853 if (CondI && CondI->getParent() == I.getParent())
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00002854 UpdateValueUsesWith(CondI, ConstantInt::getFalse());
Reid Spencer0a783f72006-11-02 01:53:59 +00002855 else if (I.getParent() != SI->getParent() || SI->hasOneUse())
2856 I.setOperand(1, SI->getOperand(2));
2857 else
2858 UpdateValueUsesWith(SI, SI->getOperand(2));
Chris Lattner5b73c082004-07-06 07:01:22 +00002859 return &I;
2860 }
Reid Spencer0a783f72006-11-02 01:53:59 +00002861 // Likewise for: rem X, (Cond ? Y : 0) -> rem X, Y
2862 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(2)))
2863 if (ST->isNullValue()) {
2864 Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
2865 if (CondI && CondI->getParent() == I.getParent())
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00002866 UpdateValueUsesWith(CondI, ConstantInt::getTrue());
Reid Spencer0a783f72006-11-02 01:53:59 +00002867 else if (I.getParent() != SI->getParent() || SI->hasOneUse())
2868 I.setOperand(1, SI->getOperand(1));
2869 else
2870 UpdateValueUsesWith(SI, SI->getOperand(1));
2871 return &I;
2872 }
Chris Lattner11a49f22005-11-05 07:28:37 +00002873 }
Chris Lattner5b73c082004-07-06 07:01:22 +00002874
Reid Spencer0a783f72006-11-02 01:53:59 +00002875 return 0;
2876}
2877
2878/// This function implements the transforms common to both integer remainder
2879/// instructions (urem and srem). It is called by the visitors to those integer
2880/// remainder instructions.
2881/// @brief Common integer remainder transforms
2882Instruction *InstCombiner::commonIRemTransforms(BinaryOperator &I) {
2883 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2884
2885 if (Instruction *common = commonRemTransforms(I))
2886 return common;
2887
Chris Lattner857e8cd2004-12-12 21:48:58 +00002888 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner19ccd5c2006-02-28 05:30:45 +00002889 // X % 0 == undef, we don't need to preserve faults!
2890 if (RHS->equalsInt(0))
2891 return ReplaceInstUsesWith(I, UndefValue::get(I.getType()));
2892
Chris Lattnera2881962003-02-18 19:28:33 +00002893 if (RHS->equalsInt(1)) // X % 1 == 0
2894 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2895
Chris Lattner97943922006-02-28 05:49:21 +00002896 if (Instruction *Op0I = dyn_cast<Instruction>(Op0)) {
2897 if (SelectInst *SI = dyn_cast<SelectInst>(Op0I)) {
2898 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2899 return R;
2900 } else if (isa<PHINode>(Op0I)) {
2901 if (Instruction *NV = FoldOpIntoPhi(I))
2902 return NV;
Chris Lattner97943922006-02-28 05:49:21 +00002903 }
Reid Spencer0a783f72006-11-02 01:53:59 +00002904 // (X * C1) % C2 --> 0 iff C1 % C2 == 0
2905 if (ConstantExpr::getSRem(GetFactor(Op0I), RHS)->isNullValue())
Chris Lattnerdb3f8732006-03-02 06:50:58 +00002906 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner97943922006-02-28 05:49:21 +00002907 }
Chris Lattnera2881962003-02-18 19:28:33 +00002908 }
2909
Reid Spencer0a783f72006-11-02 01:53:59 +00002910 return 0;
2911}
2912
2913Instruction *InstCombiner::visitURem(BinaryOperator &I) {
2914 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2915
2916 if (Instruction *common = commonIRemTransforms(I))
2917 return common;
2918
2919 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2920 // X urem C^2 -> X and C
2921 // Check to see if this is an unsigned remainder with an exact power of 2,
2922 // if so, convert to a bitwise and.
2923 if (ConstantInt *C = dyn_cast<ConstantInt>(RHS))
Reid Spencerbca0e382007-03-23 20:05:17 +00002924 if (C->getValue().isPowerOf2())
Reid Spencer0a783f72006-11-02 01:53:59 +00002925 return BinaryOperator::createAnd(Op0, SubOne(C));
2926 }
2927
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00002928 if (Instruction *RHSI = dyn_cast<Instruction>(I.getOperand(1))) {
Reid Spencer0a783f72006-11-02 01:53:59 +00002929 // Turn A % (C << N), where C is 2^k, into A & ((C << N)-1)
2930 if (RHSI->getOpcode() == Instruction::Shl &&
2931 isa<ConstantInt>(RHSI->getOperand(0))) {
Zhou Sheng0fc50952007-03-25 05:01:29 +00002932 if (cast<ConstantInt>(RHSI->getOperand(0))->getValue().isPowerOf2()) {
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00002933 Constant *N1 = ConstantInt::getAllOnesValue(I.getType());
2934 Value *Add = InsertNewInstBefore(BinaryOperator::createAdd(RHSI, N1,
2935 "tmp"), I);
2936 return BinaryOperator::createAnd(Op0, Add);
2937 }
2938 }
Reid Spencer0a783f72006-11-02 01:53:59 +00002939 }
Chris Lattner8e49e082006-09-09 20:26:32 +00002940
Reid Spencer0a783f72006-11-02 01:53:59 +00002941 // urem X, (select Cond, 2^C1, 2^C2) --> select Cond, (and X, C1), (and X, C2)
2942 // where C1&C2 are powers of two.
2943 if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
2944 if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
2945 if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2))) {
2946 // STO == 0 and SFO == 0 handled above.
Reid Spencerbca0e382007-03-23 20:05:17 +00002947 if ((STO->getValue().isPowerOf2()) &&
2948 (SFO->getValue().isPowerOf2())) {
Reid Spencer0a783f72006-11-02 01:53:59 +00002949 Value *TrueAnd = InsertNewInstBefore(
2950 BinaryOperator::createAnd(Op0, SubOne(STO), SI->getName()+".t"), I);
2951 Value *FalseAnd = InsertNewInstBefore(
2952 BinaryOperator::createAnd(Op0, SubOne(SFO), SI->getName()+".f"), I);
2953 return new SelectInst(SI->getOperand(0), TrueAnd, FalseAnd);
2954 }
2955 }
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00002956 }
2957
Chris Lattner3f5b8772002-05-06 16:14:14 +00002958 return 0;
2959}
2960
Reid Spencer0a783f72006-11-02 01:53:59 +00002961Instruction *InstCombiner::visitSRem(BinaryOperator &I) {
2962 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2963
Dan Gohmancff55092007-11-05 23:16:33 +00002964 // Handle the integer rem common cases
Reid Spencer0a783f72006-11-02 01:53:59 +00002965 if (Instruction *common = commonIRemTransforms(I))
2966 return common;
2967
2968 if (Value *RHSNeg = dyn_castNegVal(Op1))
2969 if (!isa<ConstantInt>(RHSNeg) ||
Zhou Sheng0fc50952007-03-25 05:01:29 +00002970 cast<ConstantInt>(RHSNeg)->getValue().isStrictlyPositive()) {
Reid Spencer0a783f72006-11-02 01:53:59 +00002971 // X % -Y -> X % Y
2972 AddUsesToWorkList(I);
2973 I.setOperand(1, RHSNeg);
2974 return &I;
2975 }
2976
Dan Gohmancff55092007-11-05 23:16:33 +00002977 // If the sign bits of both operands are zero (i.e. we can prove they are
Reid Spencer0a783f72006-11-02 01:53:59 +00002978 // unsigned inputs), turn this into a urem.
Dan Gohmancff55092007-11-05 23:16:33 +00002979 if (I.getType()->isInteger()) {
2980 APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
2981 if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
2982 // X srem Y -> X urem Y, iff X and Y don't have sign bit set
2983 return BinaryOperator::createURem(Op0, Op1, I.getName());
2984 }
Reid Spencer0a783f72006-11-02 01:53:59 +00002985 }
2986
2987 return 0;
2988}
2989
2990Instruction *InstCombiner::visitFRem(BinaryOperator &I) {
Reid Spencer0a783f72006-11-02 01:53:59 +00002991 return commonRemTransforms(I);
2992}
2993
Chris Lattner8b170942002-08-09 23:47:40 +00002994// isMaxValueMinusOne - return true if this is Max-1
Reid Spencere4d87aa2006-12-23 06:05:41 +00002995static bool isMaxValueMinusOne(const ConstantInt *C, bool isSigned) {
Reid Spencer3a2a9fb2007-03-19 21:10:28 +00002996 uint32_t TypeBits = C->getType()->getPrimitiveSizeInBits();
Chris Lattnera0141b92007-07-15 20:42:37 +00002997 if (!isSigned)
2998 return C->getValue() == APInt::getAllOnesValue(TypeBits) - 1;
2999 return C->getValue() == APInt::getSignedMaxValue(TypeBits)-1;
Chris Lattner8b170942002-08-09 23:47:40 +00003000}
3001
3002// isMinValuePlusOne - return true if this is Min+1
Reid Spencere4d87aa2006-12-23 06:05:41 +00003003static bool isMinValuePlusOne(const ConstantInt *C, bool isSigned) {
Chris Lattnera0141b92007-07-15 20:42:37 +00003004 if (!isSigned)
3005 return C->getValue() == 1; // unsigned
3006
3007 // Calculate 1111111111000000000000
3008 uint32_t TypeBits = C->getType()->getPrimitiveSizeInBits();
3009 return C->getValue() == APInt::getSignedMinValue(TypeBits)+1;
Chris Lattner8b170942002-08-09 23:47:40 +00003010}
3011
Chris Lattner457dd822004-06-09 07:59:58 +00003012// isOneBitSet - Return true if there is exactly one bit set in the specified
3013// constant.
3014static bool isOneBitSet(const ConstantInt *CI) {
Reid Spencer5f6a8952007-03-20 00:16:52 +00003015 return CI->getValue().isPowerOf2();
Chris Lattner457dd822004-06-09 07:59:58 +00003016}
3017
Chris Lattnerb20ba0a2004-09-23 21:46:38 +00003018// isHighOnes - Return true if the constant is of the form 1+0+.
3019// This is the same as lowones(~X).
3020static bool isHighOnes(const ConstantInt *CI) {
Zhou Sheng2cde46c2007-03-20 12:49:06 +00003021 return (~CI->getValue() + 1).isPowerOf2();
Chris Lattnerb20ba0a2004-09-23 21:46:38 +00003022}
3023
Reid Spencere4d87aa2006-12-23 06:05:41 +00003024/// getICmpCode - Encode a icmp predicate into a three bit mask. These bits
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003025/// are carefully arranged to allow folding of expressions such as:
3026///
3027/// (A < B) | (A > B) --> (A != B)
3028///
Reid Spencere4d87aa2006-12-23 06:05:41 +00003029/// Note that this is only valid if the first and second predicates have the
3030/// same sign. Is illegal to do: (A u< B) | (A s> B)
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003031///
Reid Spencere4d87aa2006-12-23 06:05:41 +00003032/// Three bits are used to represent the condition, as follows:
3033/// 0 A > B
3034/// 1 A == B
3035/// 2 A < B
3036///
3037/// <=> Value Definition
3038/// 000 0 Always false
3039/// 001 1 A > B
3040/// 010 2 A == B
3041/// 011 3 A >= B
3042/// 100 4 A < B
3043/// 101 5 A != B
3044/// 110 6 A <= B
3045/// 111 7 Always true
3046///
3047static unsigned getICmpCode(const ICmpInst *ICI) {
3048 switch (ICI->getPredicate()) {
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003049 // False -> 0
Reid Spencere4d87aa2006-12-23 06:05:41 +00003050 case ICmpInst::ICMP_UGT: return 1; // 001
3051 case ICmpInst::ICMP_SGT: return 1; // 001
3052 case ICmpInst::ICMP_EQ: return 2; // 010
3053 case ICmpInst::ICMP_UGE: return 3; // 011
3054 case ICmpInst::ICMP_SGE: return 3; // 011
3055 case ICmpInst::ICMP_ULT: return 4; // 100
3056 case ICmpInst::ICMP_SLT: return 4; // 100
3057 case ICmpInst::ICMP_NE: return 5; // 101
3058 case ICmpInst::ICMP_ULE: return 6; // 110
3059 case ICmpInst::ICMP_SLE: return 6; // 110
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003060 // True -> 7
3061 default:
Reid Spencere4d87aa2006-12-23 06:05:41 +00003062 assert(0 && "Invalid ICmp predicate!");
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003063 return 0;
3064 }
3065}
3066
Reid Spencere4d87aa2006-12-23 06:05:41 +00003067/// getICmpValue - This is the complement of getICmpCode, which turns an
3068/// opcode and two operands into either a constant true or false, or a brand
Dan Gohman5d066ff2007-09-17 17:31:57 +00003069/// new ICmp instruction. The sign is passed in to determine which kind
Reid Spencere4d87aa2006-12-23 06:05:41 +00003070/// of predicate to use in new icmp instructions.
3071static Value *getICmpValue(bool sign, unsigned code, Value *LHS, Value *RHS) {
3072 switch (code) {
3073 default: assert(0 && "Illegal ICmp code!");
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003074 case 0: return ConstantInt::getFalse();
Reid Spencere4d87aa2006-12-23 06:05:41 +00003075 case 1:
3076 if (sign)
3077 return new ICmpInst(ICmpInst::ICMP_SGT, LHS, RHS);
3078 else
3079 return new ICmpInst(ICmpInst::ICMP_UGT, LHS, RHS);
3080 case 2: return new ICmpInst(ICmpInst::ICMP_EQ, LHS, RHS);
3081 case 3:
3082 if (sign)
3083 return new ICmpInst(ICmpInst::ICMP_SGE, LHS, RHS);
3084 else
3085 return new ICmpInst(ICmpInst::ICMP_UGE, LHS, RHS);
3086 case 4:
3087 if (sign)
3088 return new ICmpInst(ICmpInst::ICMP_SLT, LHS, RHS);
3089 else
3090 return new ICmpInst(ICmpInst::ICMP_ULT, LHS, RHS);
3091 case 5: return new ICmpInst(ICmpInst::ICMP_NE, LHS, RHS);
3092 case 6:
3093 if (sign)
3094 return new ICmpInst(ICmpInst::ICMP_SLE, LHS, RHS);
3095 else
3096 return new ICmpInst(ICmpInst::ICMP_ULE, LHS, RHS);
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003097 case 7: return ConstantInt::getTrue();
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003098 }
3099}
3100
Reid Spencere4d87aa2006-12-23 06:05:41 +00003101static bool PredicatesFoldable(ICmpInst::Predicate p1, ICmpInst::Predicate p2) {
3102 return (ICmpInst::isSignedPredicate(p1) == ICmpInst::isSignedPredicate(p2)) ||
3103 (ICmpInst::isSignedPredicate(p1) &&
3104 (p2 == ICmpInst::ICMP_EQ || p2 == ICmpInst::ICMP_NE)) ||
3105 (ICmpInst::isSignedPredicate(p2) &&
3106 (p1 == ICmpInst::ICMP_EQ || p1 == ICmpInst::ICMP_NE));
3107}
3108
3109namespace {
3110// FoldICmpLogical - Implements (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
3111struct FoldICmpLogical {
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003112 InstCombiner &IC;
3113 Value *LHS, *RHS;
Reid Spencere4d87aa2006-12-23 06:05:41 +00003114 ICmpInst::Predicate pred;
3115 FoldICmpLogical(InstCombiner &ic, ICmpInst *ICI)
3116 : IC(ic), LHS(ICI->getOperand(0)), RHS(ICI->getOperand(1)),
3117 pred(ICI->getPredicate()) {}
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003118 bool shouldApply(Value *V) const {
Reid Spencere4d87aa2006-12-23 06:05:41 +00003119 if (ICmpInst *ICI = dyn_cast<ICmpInst>(V))
3120 if (PredicatesFoldable(pred, ICI->getPredicate()))
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00003121 return ((ICI->getOperand(0) == LHS && ICI->getOperand(1) == RHS) ||
3122 (ICI->getOperand(0) == RHS && ICI->getOperand(1) == LHS));
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003123 return false;
3124 }
Reid Spencere4d87aa2006-12-23 06:05:41 +00003125 Instruction *apply(Instruction &Log) const {
3126 ICmpInst *ICI = cast<ICmpInst>(Log.getOperand(0));
3127 if (ICI->getOperand(0) != LHS) {
3128 assert(ICI->getOperand(1) == LHS);
3129 ICI->swapOperands(); // Swap the LHS and RHS of the ICmp
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003130 }
3131
Chris Lattnerbc1dbfc2007-03-13 14:27:42 +00003132 ICmpInst *RHSICI = cast<ICmpInst>(Log.getOperand(1));
Reid Spencere4d87aa2006-12-23 06:05:41 +00003133 unsigned LHSCode = getICmpCode(ICI);
Chris Lattnerbc1dbfc2007-03-13 14:27:42 +00003134 unsigned RHSCode = getICmpCode(RHSICI);
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003135 unsigned Code;
3136 switch (Log.getOpcode()) {
3137 case Instruction::And: Code = LHSCode & RHSCode; break;
3138 case Instruction::Or: Code = LHSCode | RHSCode; break;
3139 case Instruction::Xor: Code = LHSCode ^ RHSCode; break;
Chris Lattner021c1902003-09-22 20:33:34 +00003140 default: assert(0 && "Illegal logical opcode!"); return 0;
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003141 }
3142
Chris Lattnerbc1dbfc2007-03-13 14:27:42 +00003143 bool isSigned = ICmpInst::isSignedPredicate(RHSICI->getPredicate()) ||
3144 ICmpInst::isSignedPredicate(ICI->getPredicate());
3145
3146 Value *RV = getICmpValue(isSigned, Code, LHS, RHS);
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003147 if (Instruction *I = dyn_cast<Instruction>(RV))
3148 return I;
3149 // Otherwise, it's a constant boolean value...
3150 return IC.ReplaceInstUsesWith(Log, RV);
3151 }
3152};
Chris Lattnerd23b5ba2006-11-15 04:53:24 +00003153} // end anonymous namespace
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003154
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003155// OptAndOp - This handles expressions of the form ((val OP C1) & C2). Where
3156// the Op parameter is 'OP', OpRHS is 'C1', and AndRHS is 'C2'. Op is
Reid Spencer832254e2007-02-02 02:16:23 +00003157// guaranteed to be a binary operator.
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003158Instruction *InstCombiner::OptAndOp(Instruction *Op,
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003159 ConstantInt *OpRHS,
3160 ConstantInt *AndRHS,
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003161 BinaryOperator &TheAnd) {
3162 Value *X = Op->getOperand(0);
Chris Lattner76f7fe22004-01-12 19:47:05 +00003163 Constant *Together = 0;
Reid Spencer832254e2007-02-02 02:16:23 +00003164 if (!Op->isShift())
Reid Spencer7177c3a2007-03-25 05:33:51 +00003165 Together = And(AndRHS, OpRHS);
Chris Lattner7c4049c2004-01-12 19:35:11 +00003166
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003167 switch (Op->getOpcode()) {
3168 case Instruction::Xor:
Chris Lattner6e7ba452005-01-01 16:22:27 +00003169 if (Op->hasOneUse()) {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003170 // (X ^ C1) & C2 --> (X & C2) ^ (C1&C2)
Chris Lattner6934a042007-02-11 01:23:03 +00003171 Instruction *And = BinaryOperator::createAnd(X, AndRHS);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003172 InsertNewInstBefore(And, TheAnd);
Chris Lattner6934a042007-02-11 01:23:03 +00003173 And->takeName(Op);
Chris Lattner48595f12004-06-10 02:07:29 +00003174 return BinaryOperator::createXor(And, Together);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003175 }
3176 break;
3177 case Instruction::Or:
Chris Lattner6e7ba452005-01-01 16:22:27 +00003178 if (Together == AndRHS) // (X | C) & C --> C
3179 return ReplaceInstUsesWith(TheAnd, AndRHS);
Misha Brukmanfd939082005-04-21 23:48:37 +00003180
Chris Lattner6e7ba452005-01-01 16:22:27 +00003181 if (Op->hasOneUse() && Together != OpRHS) {
3182 // (X | C1) & C2 --> (X | (C1&C2)) & C2
Chris Lattner6934a042007-02-11 01:23:03 +00003183 Instruction *Or = BinaryOperator::createOr(X, Together);
Chris Lattner6e7ba452005-01-01 16:22:27 +00003184 InsertNewInstBefore(Or, TheAnd);
Chris Lattner6934a042007-02-11 01:23:03 +00003185 Or->takeName(Op);
Chris Lattner6e7ba452005-01-01 16:22:27 +00003186 return BinaryOperator::createAnd(Or, AndRHS);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003187 }
3188 break;
3189 case Instruction::Add:
Chris Lattnerfd059242003-10-15 16:48:29 +00003190 if (Op->hasOneUse()) {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003191 // Adding a one to a single bit bit-field should be turned into an XOR
3192 // of the bit. First thing to check is to see if this AND is with a
3193 // single bit constant.
Zhou Sheng3a507fd2007-04-01 17:13:37 +00003194 const APInt& AndRHSV = cast<ConstantInt>(AndRHS)->getValue();
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003195
3196 // If there is only one bit set...
Chris Lattner457dd822004-06-09 07:59:58 +00003197 if (isOneBitSet(cast<ConstantInt>(AndRHS))) {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003198 // Ok, at this point, we know that we are masking the result of the
3199 // ADD down to exactly one bit. If the constant we are adding has
3200 // no bits set below this bit, then we can eliminate the ADD.
Zhou Sheng3a507fd2007-04-01 17:13:37 +00003201 const APInt& AddRHS = cast<ConstantInt>(OpRHS)->getValue();
Misha Brukmanfd939082005-04-21 23:48:37 +00003202
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003203 // Check to see if any bits below the one bit set in AndRHSV are set.
3204 if ((AddRHS & (AndRHSV-1)) == 0) {
3205 // If not, the only thing that can effect the output of the AND is
3206 // the bit specified by AndRHSV. If that bit is set, the effect of
3207 // the XOR is to toggle the bit. If it is clear, then the ADD has
3208 // no effect.
3209 if ((AddRHS & AndRHSV) == 0) { // Bit is not set, noop
3210 TheAnd.setOperand(0, X);
3211 return &TheAnd;
3212 } else {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003213 // Pull the XOR out of the AND.
Chris Lattner6934a042007-02-11 01:23:03 +00003214 Instruction *NewAnd = BinaryOperator::createAnd(X, AndRHS);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003215 InsertNewInstBefore(NewAnd, TheAnd);
Chris Lattner6934a042007-02-11 01:23:03 +00003216 NewAnd->takeName(Op);
Chris Lattner48595f12004-06-10 02:07:29 +00003217 return BinaryOperator::createXor(NewAnd, AndRHS);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003218 }
3219 }
3220 }
3221 }
3222 break;
Chris Lattner62a355c2003-09-19 19:05:02 +00003223
3224 case Instruction::Shl: {
3225 // We know that the AND will not produce any of the bits shifted in, so if
3226 // the anded constant includes them, clear them now!
3227 //
Zhou Sheng290bec52007-03-29 08:15:12 +00003228 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00003229 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
Zhou Sheng290bec52007-03-29 08:15:12 +00003230 APInt ShlMask(APInt::getHighBitsSet(BitWidth, BitWidth-OpRHSVal));
3231 ConstantInt *CI = ConstantInt::get(AndRHS->getValue() & ShlMask);
Misha Brukmanfd939082005-04-21 23:48:37 +00003232
Zhou Sheng290bec52007-03-29 08:15:12 +00003233 if (CI->getValue() == ShlMask) {
3234 // Masking out bits that the shift already masks
Chris Lattner0c967662004-09-24 15:21:34 +00003235 return ReplaceInstUsesWith(TheAnd, Op); // No need for the and.
3236 } else if (CI != AndRHS) { // Reducing bits set in and.
Chris Lattner62a355c2003-09-19 19:05:02 +00003237 TheAnd.setOperand(1, CI);
3238 return &TheAnd;
3239 }
3240 break;
Misha Brukmanfd939082005-04-21 23:48:37 +00003241 }
Reid Spencer3822ff52006-11-08 06:47:33 +00003242 case Instruction::LShr:
3243 {
Chris Lattner62a355c2003-09-19 19:05:02 +00003244 // We know that the AND will not produce any of the bits shifted in, so if
3245 // the anded constant includes them, clear them now! This only applies to
3246 // unsigned shifts, because a signed shr may bring in set bits!
3247 //
Zhou Sheng290bec52007-03-29 08:15:12 +00003248 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00003249 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
Zhou Sheng290bec52007-03-29 08:15:12 +00003250 APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
3251 ConstantInt *CI = ConstantInt::get(AndRHS->getValue() & ShrMask);
Chris Lattner0c967662004-09-24 15:21:34 +00003252
Zhou Sheng290bec52007-03-29 08:15:12 +00003253 if (CI->getValue() == ShrMask) {
3254 // Masking out bits that the shift already masks.
Reid Spencer3822ff52006-11-08 06:47:33 +00003255 return ReplaceInstUsesWith(TheAnd, Op);
3256 } else if (CI != AndRHS) {
3257 TheAnd.setOperand(1, CI); // Reduce bits set in and cst.
3258 return &TheAnd;
3259 }
3260 break;
3261 }
3262 case Instruction::AShr:
3263 // Signed shr.
3264 // See if this is shifting in some sign extension, then masking it out
3265 // with an and.
3266 if (Op->hasOneUse()) {
Zhou Sheng290bec52007-03-29 08:15:12 +00003267 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00003268 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
Zhou Sheng290bec52007-03-29 08:15:12 +00003269 APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
3270 Constant *C = ConstantInt::get(AndRHS->getValue() & ShrMask);
Reid Spencer7eb76382006-12-13 17:19:09 +00003271 if (C == AndRHS) { // Masking out bits shifted in.
Reid Spencer17212df2006-12-12 09:18:51 +00003272 // (Val ashr C1) & C2 -> (Val lshr C1) & C2
Reid Spencer3822ff52006-11-08 06:47:33 +00003273 // Make the argument unsigned.
3274 Value *ShVal = Op->getOperand(0);
Reid Spencer832254e2007-02-02 02:16:23 +00003275 ShVal = InsertNewInstBefore(
Reid Spencercc46cdb2007-02-02 14:08:20 +00003276 BinaryOperator::createLShr(ShVal, OpRHS,
Reid Spencer832254e2007-02-02 02:16:23 +00003277 Op->getName()), TheAnd);
Reid Spencer7eb76382006-12-13 17:19:09 +00003278 return BinaryOperator::createAnd(ShVal, AndRHS, TheAnd.getName());
Chris Lattner0c967662004-09-24 15:21:34 +00003279 }
Chris Lattner62a355c2003-09-19 19:05:02 +00003280 }
3281 break;
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003282 }
3283 return 0;
3284}
3285
Chris Lattner8b170942002-08-09 23:47:40 +00003286
Chris Lattnera96879a2004-09-29 17:40:11 +00003287/// InsertRangeTest - Emit a computation of: (V >= Lo && V < Hi) if Inside is
3288/// true, otherwise (V < Lo || V >= Hi). In pratice, we emit the more efficient
Reid Spencere4d87aa2006-12-23 06:05:41 +00003289/// (V-Lo) <u Hi-Lo. This method expects that Lo <= Hi. isSigned indicates
3290/// whether to treat the V, Lo and HI as signed or not. IB is the location to
Chris Lattnera96879a2004-09-29 17:40:11 +00003291/// insert new instructions.
3292Instruction *InstCombiner::InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
Reid Spencere4d87aa2006-12-23 06:05:41 +00003293 bool isSigned, bool Inside,
3294 Instruction &IB) {
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003295 assert(cast<ConstantInt>(ConstantExpr::getICmp((isSigned ?
Reid Spencer579dca12007-01-12 04:24:46 +00003296 ICmpInst::ICMP_SLE:ICmpInst::ICMP_ULE), Lo, Hi))->getZExtValue() &&
Chris Lattnera96879a2004-09-29 17:40:11 +00003297 "Lo is not <= Hi in range emission code!");
Reid Spencere4d87aa2006-12-23 06:05:41 +00003298
Chris Lattnera96879a2004-09-29 17:40:11 +00003299 if (Inside) {
3300 if (Lo == Hi) // Trivially false.
Reid Spencere4d87aa2006-12-23 06:05:41 +00003301 return new ICmpInst(ICmpInst::ICMP_NE, V, V);
Misha Brukmanfd939082005-04-21 23:48:37 +00003302
Reid Spencere4d87aa2006-12-23 06:05:41 +00003303 // V >= Min && V < Hi --> V < Hi
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003304 if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
Reid Spencere4e40032007-03-21 23:19:50 +00003305 ICmpInst::Predicate pred = (isSigned ?
Reid Spencere4d87aa2006-12-23 06:05:41 +00003306 ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT);
3307 return new ICmpInst(pred, V, Hi);
3308 }
3309
3310 // Emit V-Lo <u Hi-Lo
3311 Constant *NegLo = ConstantExpr::getNeg(Lo);
3312 Instruction *Add = BinaryOperator::createAdd(V, NegLo, V->getName()+".off");
Chris Lattnera96879a2004-09-29 17:40:11 +00003313 InsertNewInstBefore(Add, IB);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003314 Constant *UpperBound = ConstantExpr::getAdd(NegLo, Hi);
3315 return new ICmpInst(ICmpInst::ICMP_ULT, Add, UpperBound);
Chris Lattnera96879a2004-09-29 17:40:11 +00003316 }
3317
3318 if (Lo == Hi) // Trivially true.
Reid Spencere4d87aa2006-12-23 06:05:41 +00003319 return new ICmpInst(ICmpInst::ICMP_EQ, V, V);
Chris Lattnera96879a2004-09-29 17:40:11 +00003320
Reid Spencere4e40032007-03-21 23:19:50 +00003321 // V < Min || V >= Hi -> V > Hi-1
Chris Lattnera96879a2004-09-29 17:40:11 +00003322 Hi = SubOne(cast<ConstantInt>(Hi));
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003323 if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00003324 ICmpInst::Predicate pred = (isSigned ?
3325 ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT);
3326 return new ICmpInst(pred, V, Hi);
3327 }
Reid Spencerb83eb642006-10-20 07:07:24 +00003328
Reid Spencere4e40032007-03-21 23:19:50 +00003329 // Emit V-Lo >u Hi-1-Lo
3330 // Note that Hi has already had one subtracted from it, above.
3331 ConstantInt *NegLo = cast<ConstantInt>(ConstantExpr::getNeg(Lo));
Reid Spencere4d87aa2006-12-23 06:05:41 +00003332 Instruction *Add = BinaryOperator::createAdd(V, NegLo, V->getName()+".off");
Chris Lattnera96879a2004-09-29 17:40:11 +00003333 InsertNewInstBefore(Add, IB);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003334 Constant *LowerBound = ConstantExpr::getAdd(NegLo, Hi);
3335 return new ICmpInst(ICmpInst::ICMP_UGT, Add, LowerBound);
Chris Lattnera96879a2004-09-29 17:40:11 +00003336}
3337
Chris Lattner7203e152005-09-18 07:22:02 +00003338// isRunOfOnes - Returns true iff Val consists of one contiguous run of 1s with
3339// any number of 0s on either side. The 1s are allowed to wrap from LSB to
3340// MSB, so 0x000FFF0, 0x0000FFFF, and 0xFF0000FF are all runs. 0x0F0F0000 is
3341// not, since all 1s are not contiguous.
Zhou Sheng4351c642007-04-02 08:20:41 +00003342static bool isRunOfOnes(ConstantInt *Val, uint32_t &MB, uint32_t &ME) {
Zhou Sheng3a507fd2007-04-01 17:13:37 +00003343 const APInt& V = Val->getValue();
Reid Spencerf2442522007-03-24 00:42:08 +00003344 uint32_t BitWidth = Val->getType()->getBitWidth();
3345 if (!APIntOps::isShiftedMask(BitWidth, V)) return false;
Chris Lattner7203e152005-09-18 07:22:02 +00003346
3347 // look for the first zero bit after the run of ones
Reid Spencerf2442522007-03-24 00:42:08 +00003348 MB = BitWidth - ((V - 1) ^ V).countLeadingZeros();
Chris Lattner7203e152005-09-18 07:22:02 +00003349 // look for the first non-zero bit
Reid Spencerf2442522007-03-24 00:42:08 +00003350 ME = V.getActiveBits();
Chris Lattner7203e152005-09-18 07:22:02 +00003351 return true;
3352}
3353
Chris Lattner7203e152005-09-18 07:22:02 +00003354/// FoldLogicalPlusAnd - This is part of an expression (LHS +/- RHS) & Mask,
3355/// where isSub determines whether the operator is a sub. If we can fold one of
3356/// the following xforms:
Chris Lattnerc8e77562005-09-18 04:24:45 +00003357///
3358/// ((A & N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == Mask
3359/// ((A | N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
3360/// ((A ^ N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
3361///
3362/// return (A +/- B).
3363///
3364Value *InstCombiner::FoldLogicalPlusAnd(Value *LHS, Value *RHS,
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003365 ConstantInt *Mask, bool isSub,
Chris Lattnerc8e77562005-09-18 04:24:45 +00003366 Instruction &I) {
3367 Instruction *LHSI = dyn_cast<Instruction>(LHS);
3368 if (!LHSI || LHSI->getNumOperands() != 2 ||
3369 !isa<ConstantInt>(LHSI->getOperand(1))) return 0;
3370
3371 ConstantInt *N = cast<ConstantInt>(LHSI->getOperand(1));
3372
3373 switch (LHSI->getOpcode()) {
3374 default: return 0;
3375 case Instruction::And:
Reid Spencer7177c3a2007-03-25 05:33:51 +00003376 if (And(N, Mask) == Mask) {
Chris Lattner7203e152005-09-18 07:22:02 +00003377 // If the AndRHS is a power of two minus one (0+1+), this is simple.
Zhou Sheng00f436c2007-03-24 15:34:37 +00003378 if ((Mask->getValue().countLeadingZeros() +
3379 Mask->getValue().countPopulation()) ==
3380 Mask->getValue().getBitWidth())
Chris Lattner7203e152005-09-18 07:22:02 +00003381 break;
3382
3383 // Otherwise, if Mask is 0+1+0+, and if B is known to have the low 0+
3384 // part, we don't need any explicit masks to take them out of A. If that
3385 // is all N is, ignore it.
Zhou Sheng4351c642007-04-02 08:20:41 +00003386 uint32_t MB = 0, ME = 0;
Chris Lattner7203e152005-09-18 07:22:02 +00003387 if (isRunOfOnes(Mask, MB, ME)) { // begin/end bit of run, inclusive
Reid Spencerb35ae032007-03-23 18:46:34 +00003388 uint32_t BitWidth = cast<IntegerType>(RHS->getType())->getBitWidth();
Zhou Sheng290bec52007-03-29 08:15:12 +00003389 APInt Mask(APInt::getLowBitsSet(BitWidth, MB-1));
Chris Lattner3bedbd92006-02-07 07:27:52 +00003390 if (MaskedValueIsZero(RHS, Mask))
Chris Lattner7203e152005-09-18 07:22:02 +00003391 break;
3392 }
3393 }
Chris Lattnerc8e77562005-09-18 04:24:45 +00003394 return 0;
3395 case Instruction::Or:
3396 case Instruction::Xor:
Chris Lattner7203e152005-09-18 07:22:02 +00003397 // If the AndRHS is a power of two minus one (0+1+), and N&Mask == 0
Zhou Sheng00f436c2007-03-24 15:34:37 +00003398 if ((Mask->getValue().countLeadingZeros() +
3399 Mask->getValue().countPopulation()) == Mask->getValue().getBitWidth()
Reid Spencer6eb0d992007-03-26 23:58:26 +00003400 && And(N, Mask)->isZero())
Chris Lattnerc8e77562005-09-18 04:24:45 +00003401 break;
3402 return 0;
3403 }
3404
3405 Instruction *New;
3406 if (isSub)
3407 New = BinaryOperator::createSub(LHSI->getOperand(0), RHS, "fold");
3408 else
3409 New = BinaryOperator::createAdd(LHSI->getOperand(0), RHS, "fold");
3410 return InsertNewInstBefore(New, I);
3411}
3412
Chris Lattner7e708292002-06-25 16:13:24 +00003413Instruction *InstCombiner::visitAnd(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00003414 bool Changed = SimplifyCommutative(I);
Chris Lattner7e708292002-06-25 16:13:24 +00003415 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00003416
Chris Lattnere87597f2004-10-16 18:11:37 +00003417 if (isa<UndefValue>(Op1)) // X & undef -> 0
3418 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3419
Chris Lattner6e7ba452005-01-01 16:22:27 +00003420 // and X, X = X
3421 if (Op0 == Op1)
Chris Lattner233f7dc2002-08-12 21:17:25 +00003422 return ReplaceInstUsesWith(I, Op1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00003423
Chris Lattnerf8c36f52006-02-12 08:02:11 +00003424 // See if we can simplify any instructions used by the instruction whose sole
Chris Lattner9ca96412006-02-08 03:25:32 +00003425 // purpose is to compute bits we don't care about.
Reid Spencer9d6565a2007-02-15 02:26:10 +00003426 if (!isa<VectorType>(I.getType())) {
Reid Spencera03d45f2007-03-22 22:19:58 +00003427 uint32_t BitWidth = cast<IntegerType>(I.getType())->getBitWidth();
3428 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
3429 if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(BitWidth),
Chris Lattner696ee0a2007-01-18 22:16:33 +00003430 KnownZero, KnownOne))
Reid Spencer6eb0d992007-03-26 23:58:26 +00003431 return &I;
Chris Lattner696ee0a2007-01-18 22:16:33 +00003432 } else {
Reid Spencer9d6565a2007-02-15 02:26:10 +00003433 if (ConstantVector *CP = dyn_cast<ConstantVector>(Op1)) {
Chris Lattner041a6c92007-06-15 05:26:55 +00003434 if (CP->isAllOnesValue()) // X & <-1,-1> -> X
Chris Lattner696ee0a2007-01-18 22:16:33 +00003435 return ReplaceInstUsesWith(I, I.getOperand(0));
Chris Lattner041a6c92007-06-15 05:26:55 +00003436 } else if (isa<ConstantAggregateZero>(Op1)) {
3437 return ReplaceInstUsesWith(I, Op1); // X & <0,0> -> <0,0>
Chris Lattner696ee0a2007-01-18 22:16:33 +00003438 }
3439 }
Chris Lattner9ca96412006-02-08 03:25:32 +00003440
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003441 if (ConstantInt *AndRHS = dyn_cast<ConstantInt>(Op1)) {
Zhou Sheng3a507fd2007-04-01 17:13:37 +00003442 const APInt& AndRHSMask = AndRHS->getValue();
3443 APInt NotAndRHS(~AndRHSMask);
Chris Lattner6e7ba452005-01-01 16:22:27 +00003444
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003445 // Optimize a variety of ((val OP C1) & C2) combinations...
Reid Spencer832254e2007-02-02 02:16:23 +00003446 if (isa<BinaryOperator>(Op0)) {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003447 Instruction *Op0I = cast<Instruction>(Op0);
Chris Lattner6e7ba452005-01-01 16:22:27 +00003448 Value *Op0LHS = Op0I->getOperand(0);
3449 Value *Op0RHS = Op0I->getOperand(1);
3450 switch (Op0I->getOpcode()) {
3451 case Instruction::Xor:
3452 case Instruction::Or:
Chris Lattnerad1e3022005-01-23 20:26:55 +00003453 // If the mask is only needed on one incoming arm, push it up.
3454 if (Op0I->hasOneUse()) {
3455 if (MaskedValueIsZero(Op0LHS, NotAndRHS)) {
3456 // Not masking anything out for the LHS, move to RHS.
3457 Instruction *NewRHS = BinaryOperator::createAnd(Op0RHS, AndRHS,
3458 Op0RHS->getName()+".masked");
3459 InsertNewInstBefore(NewRHS, I);
3460 return BinaryOperator::create(
3461 cast<BinaryOperator>(Op0I)->getOpcode(), Op0LHS, NewRHS);
Misha Brukmanfd939082005-04-21 23:48:37 +00003462 }
Chris Lattner3bedbd92006-02-07 07:27:52 +00003463 if (!isa<Constant>(Op0RHS) &&
Chris Lattnerad1e3022005-01-23 20:26:55 +00003464 MaskedValueIsZero(Op0RHS, NotAndRHS)) {
3465 // Not masking anything out for the RHS, move to LHS.
3466 Instruction *NewLHS = BinaryOperator::createAnd(Op0LHS, AndRHS,
3467 Op0LHS->getName()+".masked");
3468 InsertNewInstBefore(NewLHS, I);
3469 return BinaryOperator::create(
3470 cast<BinaryOperator>(Op0I)->getOpcode(), NewLHS, Op0RHS);
3471 }
3472 }
3473
Chris Lattner6e7ba452005-01-01 16:22:27 +00003474 break;
Chris Lattnerc8e77562005-09-18 04:24:45 +00003475 case Instruction::Add:
Chris Lattner7203e152005-09-18 07:22:02 +00003476 // ((A & N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == AndRHS.
3477 // ((A | N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
3478 // ((A ^ N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
3479 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, false, I))
3480 return BinaryOperator::createAnd(V, AndRHS);
3481 if (Value *V = FoldLogicalPlusAnd(Op0RHS, Op0LHS, AndRHS, false, I))
3482 return BinaryOperator::createAnd(V, AndRHS); // Add commutes
Chris Lattnerc8e77562005-09-18 04:24:45 +00003483 break;
3484
3485 case Instruction::Sub:
Chris Lattner7203e152005-09-18 07:22:02 +00003486 // ((A & N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == AndRHS.
3487 // ((A | N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
3488 // ((A ^ N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
3489 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, true, I))
3490 return BinaryOperator::createAnd(V, AndRHS);
Chris Lattnerc8e77562005-09-18 04:24:45 +00003491 break;
Chris Lattner6e7ba452005-01-01 16:22:27 +00003492 }
3493
Chris Lattner58403262003-07-23 19:25:52 +00003494 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
Chris Lattner6e7ba452005-01-01 16:22:27 +00003495 if (Instruction *Res = OptAndOp(Op0I, Op0CI, AndRHS, I))
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003496 return Res;
Chris Lattner6e7ba452005-01-01 16:22:27 +00003497 } else if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
Chris Lattner2b83af22005-08-07 07:03:10 +00003498 // If this is an integer truncation or change from signed-to-unsigned, and
3499 // if the source is an and/or with immediate, transform it. This
3500 // frequently occurs for bitfield accesses.
3501 if (Instruction *CastOp = dyn_cast<Instruction>(CI->getOperand(0))) {
Reid Spencer3da59db2006-11-27 01:05:10 +00003502 if ((isa<TruncInst>(CI) || isa<BitCastInst>(CI)) &&
Chris Lattner2b83af22005-08-07 07:03:10 +00003503 CastOp->getNumOperands() == 2)
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00003504 if (ConstantInt *AndCI = dyn_cast<ConstantInt>(CastOp->getOperand(1))) {
Chris Lattner2b83af22005-08-07 07:03:10 +00003505 if (CastOp->getOpcode() == Instruction::And) {
3506 // Change: and (cast (and X, C1) to T), C2
Reid Spencer3da59db2006-11-27 01:05:10 +00003507 // into : and (cast X to T), trunc_or_bitcast(C1)&C2
3508 // This will fold the two constants together, which may allow
3509 // other simplifications.
Reid Spencerd977d862006-12-12 23:36:14 +00003510 Instruction *NewCast = CastInst::createTruncOrBitCast(
3511 CastOp->getOperand(0), I.getType(),
3512 CastOp->getName()+".shrunk");
Chris Lattner2b83af22005-08-07 07:03:10 +00003513 NewCast = InsertNewInstBefore(NewCast, I);
Reid Spencer3da59db2006-11-27 01:05:10 +00003514 // trunc_or_bitcast(C1)&C2
Reid Spencerd977d862006-12-12 23:36:14 +00003515 Constant *C3 = ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
Reid Spencer3da59db2006-11-27 01:05:10 +00003516 C3 = ConstantExpr::getAnd(C3, AndRHS);
Chris Lattner2b83af22005-08-07 07:03:10 +00003517 return BinaryOperator::createAnd(NewCast, C3);
3518 } else if (CastOp->getOpcode() == Instruction::Or) {
3519 // Change: and (cast (or X, C1) to T), C2
3520 // into : trunc(C1)&C2 iff trunc(C1)&C2 == C2
Chris Lattnerbb4e7b22006-12-12 19:11:20 +00003521 Constant *C3 = ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
Chris Lattner2b83af22005-08-07 07:03:10 +00003522 if (ConstantExpr::getAnd(C3, AndRHS) == AndRHS) // trunc(C1)&C2
3523 return ReplaceInstUsesWith(I, AndRHS);
3524 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00003525 }
Chris Lattner2b83af22005-08-07 07:03:10 +00003526 }
Chris Lattner06782f82003-07-23 19:36:21 +00003527 }
Chris Lattner2eefe512004-04-09 19:05:30 +00003528
3529 // Try to fold constant and into select arguments.
3530 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner6e7ba452005-01-01 16:22:27 +00003531 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00003532 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00003533 if (isa<PHINode>(Op0))
3534 if (Instruction *NV = FoldOpIntoPhi(I))
3535 return NV;
Chris Lattnerc6a8aff2003-07-23 17:57:01 +00003536 }
3537
Chris Lattner8d969642003-03-10 23:06:50 +00003538 Value *Op0NotVal = dyn_castNotVal(Op0);
3539 Value *Op1NotVal = dyn_castNotVal(Op1);
Chris Lattnera2881962003-02-18 19:28:33 +00003540
Chris Lattner5b62aa72004-06-18 06:07:51 +00003541 if (Op0NotVal == Op1 || Op1NotVal == Op0) // A & ~A == ~A & A == 0
3542 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3543
Misha Brukmancb6267b2004-07-30 12:50:08 +00003544 // (~A & ~B) == (~(A | B)) - De Morgan's Law
Chris Lattner8d969642003-03-10 23:06:50 +00003545 if (Op0NotVal && Op1NotVal && isOnlyUse(Op0) && isOnlyUse(Op1)) {
Chris Lattner48595f12004-06-10 02:07:29 +00003546 Instruction *Or = BinaryOperator::createOr(Op0NotVal, Op1NotVal,
3547 I.getName()+".demorgan");
Chris Lattnerc6a8aff2003-07-23 17:57:01 +00003548 InsertNewInstBefore(Or, I);
Chris Lattnera2881962003-02-18 19:28:33 +00003549 return BinaryOperator::createNot(Or);
3550 }
Chris Lattner2082ad92006-02-13 23:07:23 +00003551
3552 {
Chris Lattner003b6202007-06-15 05:58:24 +00003553 Value *A = 0, *B = 0, *C = 0, *D = 0;
3554 if (match(Op0, m_Or(m_Value(A), m_Value(B)))) {
Chris Lattner2082ad92006-02-13 23:07:23 +00003555 if (A == Op1 || B == Op1) // (A | ?) & A --> A
3556 return ReplaceInstUsesWith(I, Op1);
Chris Lattner003b6202007-06-15 05:58:24 +00003557
3558 // (A|B) & ~(A&B) -> A^B
3559 if (match(Op1, m_Not(m_And(m_Value(C), m_Value(D))))) {
3560 if ((A == C && B == D) || (A == D && B == C))
3561 return BinaryOperator::createXor(A, B);
3562 }
3563 }
3564
3565 if (match(Op1, m_Or(m_Value(A), m_Value(B)))) {
Chris Lattner2082ad92006-02-13 23:07:23 +00003566 if (A == Op0 || B == Op0) // A & (A | ?) --> A
3567 return ReplaceInstUsesWith(I, Op0);
Chris Lattner003b6202007-06-15 05:58:24 +00003568
3569 // ~(A&B) & (A|B) -> A^B
3570 if (match(Op0, m_Not(m_And(m_Value(C), m_Value(D))))) {
3571 if ((A == C && B == D) || (A == D && B == C))
3572 return BinaryOperator::createXor(A, B);
3573 }
3574 }
Chris Lattner64daab52006-04-01 08:03:55 +00003575
3576 if (Op0->hasOneUse() &&
3577 match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
3578 if (A == Op1) { // (A^B)&A -> A&(A^B)
3579 I.swapOperands(); // Simplify below
3580 std::swap(Op0, Op1);
3581 } else if (B == Op1) { // (A^B)&B -> B&(B^A)
3582 cast<BinaryOperator>(Op0)->swapOperands();
3583 I.swapOperands(); // Simplify below
3584 std::swap(Op0, Op1);
3585 }
3586 }
3587 if (Op1->hasOneUse() &&
3588 match(Op1, m_Xor(m_Value(A), m_Value(B)))) {
3589 if (B == Op0) { // B&(A^B) -> B&(B^A)
3590 cast<BinaryOperator>(Op1)->swapOperands();
3591 std::swap(A, B);
3592 }
3593 if (A == Op0) { // A&(A^B) -> A & ~B
3594 Instruction *NotB = BinaryOperator::createNot(B, "tmp");
3595 InsertNewInstBefore(NotB, I);
3596 return BinaryOperator::createAnd(A, NotB);
3597 }
3598 }
Chris Lattner2082ad92006-02-13 23:07:23 +00003599 }
3600
Reid Spencere4d87aa2006-12-23 06:05:41 +00003601 if (ICmpInst *RHS = dyn_cast<ICmpInst>(Op1)) {
3602 // (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
3603 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003604 return R;
3605
Chris Lattner955f3312004-09-28 21:48:02 +00003606 Value *LHSVal, *RHSVal;
3607 ConstantInt *LHSCst, *RHSCst;
Reid Spencere4d87aa2006-12-23 06:05:41 +00003608 ICmpInst::Predicate LHSCC, RHSCC;
3609 if (match(Op0, m_ICmp(LHSCC, m_Value(LHSVal), m_ConstantInt(LHSCst))))
3610 if (match(RHS, m_ICmp(RHSCC, m_Value(RHSVal), m_ConstantInt(RHSCst))))
3611 if (LHSVal == RHSVal && // Found (X icmp C1) & (X icmp C2)
3612 // ICMP_[GL]E X, CST is folded to ICMP_[GL]T elsewhere.
3613 LHSCC != ICmpInst::ICMP_UGE && LHSCC != ICmpInst::ICMP_ULE &&
3614 RHSCC != ICmpInst::ICMP_UGE && RHSCC != ICmpInst::ICMP_ULE &&
3615 LHSCC != ICmpInst::ICMP_SGE && LHSCC != ICmpInst::ICMP_SLE &&
Chris Lattnereec8b9a2007-11-22 23:47:13 +00003616 RHSCC != ICmpInst::ICMP_SGE && RHSCC != ICmpInst::ICMP_SLE &&
3617
3618 // Don't try to fold ICMP_SLT + ICMP_ULT.
3619 (ICmpInst::isEquality(LHSCC) || ICmpInst::isEquality(RHSCC) ||
3620 ICmpInst::isSignedPredicate(LHSCC) ==
3621 ICmpInst::isSignedPredicate(RHSCC))) {
Chris Lattner955f3312004-09-28 21:48:02 +00003622 // Ensure that the larger constant is on the RHS.
Chris Lattneree2b7a42008-01-13 20:59:02 +00003623 ICmpInst::Predicate GT;
3624 if (ICmpInst::isSignedPredicate(LHSCC) ||
3625 (ICmpInst::isEquality(LHSCC) &&
3626 ICmpInst::isSignedPredicate(RHSCC)))
3627 GT = ICmpInst::ICMP_SGT;
3628 else
3629 GT = ICmpInst::ICMP_UGT;
3630
Reid Spencere4d87aa2006-12-23 06:05:41 +00003631 Constant *Cmp = ConstantExpr::getICmp(GT, LHSCst, RHSCst);
3632 ICmpInst *LHS = cast<ICmpInst>(Op0);
Reid Spencer579dca12007-01-12 04:24:46 +00003633 if (cast<ConstantInt>(Cmp)->getZExtValue()) {
Chris Lattner955f3312004-09-28 21:48:02 +00003634 std::swap(LHS, RHS);
3635 std::swap(LHSCst, RHSCst);
3636 std::swap(LHSCC, RHSCC);
3637 }
3638
Reid Spencere4d87aa2006-12-23 06:05:41 +00003639 // At this point, we know we have have two icmp instructions
Chris Lattner955f3312004-09-28 21:48:02 +00003640 // comparing a value against two constants and and'ing the result
3641 // together. Because of the above check, we know that we only have
Reid Spencere4d87aa2006-12-23 06:05:41 +00003642 // icmp eq, icmp ne, icmp [su]lt, and icmp [SU]gt here. We also know
3643 // (from the FoldICmpLogical check above), that the two constants
3644 // are not equal and that the larger constant is on the RHS
Chris Lattner955f3312004-09-28 21:48:02 +00003645 assert(LHSCst != RHSCst && "Compares not folded above?");
3646
3647 switch (LHSCC) {
3648 default: assert(0 && "Unknown integer condition code!");
Reid Spencere4d87aa2006-12-23 06:05:41 +00003649 case ICmpInst::ICMP_EQ:
Chris Lattner955f3312004-09-28 21:48:02 +00003650 switch (RHSCC) {
3651 default: assert(0 && "Unknown integer condition code!");
Reid Spencere4d87aa2006-12-23 06:05:41 +00003652 case ICmpInst::ICMP_EQ: // (X == 13 & X == 15) -> false
3653 case ICmpInst::ICMP_UGT: // (X == 13 & X > 15) -> false
3654 case ICmpInst::ICMP_SGT: // (X == 13 & X > 15) -> false
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003655 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00003656 case ICmpInst::ICMP_NE: // (X == 13 & X != 15) -> X == 13
3657 case ICmpInst::ICMP_ULT: // (X == 13 & X < 15) -> X == 13
3658 case ICmpInst::ICMP_SLT: // (X == 13 & X < 15) -> X == 13
Chris Lattner955f3312004-09-28 21:48:02 +00003659 return ReplaceInstUsesWith(I, LHS);
3660 }
Reid Spencere4d87aa2006-12-23 06:05:41 +00003661 case ICmpInst::ICMP_NE:
Chris Lattner955f3312004-09-28 21:48:02 +00003662 switch (RHSCC) {
3663 default: assert(0 && "Unknown integer condition code!");
Reid Spencere4d87aa2006-12-23 06:05:41 +00003664 case ICmpInst::ICMP_ULT:
3665 if (LHSCst == SubOne(RHSCst)) // (X != 13 & X u< 14) -> X < 13
3666 return new ICmpInst(ICmpInst::ICMP_ULT, LHSVal, LHSCst);
3667 break; // (X != 13 & X u< 15) -> no change
3668 case ICmpInst::ICMP_SLT:
3669 if (LHSCst == SubOne(RHSCst)) // (X != 13 & X s< 14) -> X < 13
3670 return new ICmpInst(ICmpInst::ICMP_SLT, LHSVal, LHSCst);
3671 break; // (X != 13 & X s< 15) -> no change
3672 case ICmpInst::ICMP_EQ: // (X != 13 & X == 15) -> X == 15
3673 case ICmpInst::ICMP_UGT: // (X != 13 & X u> 15) -> X u> 15
3674 case ICmpInst::ICMP_SGT: // (X != 13 & X s> 15) -> X s> 15
Chris Lattner955f3312004-09-28 21:48:02 +00003675 return ReplaceInstUsesWith(I, RHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003676 case ICmpInst::ICMP_NE:
3677 if (LHSCst == SubOne(RHSCst)){// (X != 13 & X != 14) -> X-13 >u 1
Chris Lattner955f3312004-09-28 21:48:02 +00003678 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
3679 Instruction *Add = BinaryOperator::createAdd(LHSVal, AddCST,
3680 LHSVal->getName()+".off");
3681 InsertNewInstBefore(Add, I);
Chris Lattner424db022007-01-27 23:08:34 +00003682 return new ICmpInst(ICmpInst::ICMP_UGT, Add,
3683 ConstantInt::get(Add->getType(), 1));
Chris Lattner955f3312004-09-28 21:48:02 +00003684 }
3685 break; // (X != 13 & X != 15) -> no change
3686 }
3687 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00003688 case ICmpInst::ICMP_ULT:
Chris Lattner955f3312004-09-28 21:48:02 +00003689 switch (RHSCC) {
3690 default: assert(0 && "Unknown integer condition code!");
Reid Spencere4d87aa2006-12-23 06:05:41 +00003691 case ICmpInst::ICMP_EQ: // (X u< 13 & X == 15) -> false
3692 case ICmpInst::ICMP_UGT: // (X u< 13 & X u> 15) -> false
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003693 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00003694 case ICmpInst::ICMP_SGT: // (X u< 13 & X s> 15) -> no change
3695 break;
3696 case ICmpInst::ICMP_NE: // (X u< 13 & X != 15) -> X u< 13
3697 case ICmpInst::ICMP_ULT: // (X u< 13 & X u< 15) -> X u< 13
Chris Lattner955f3312004-09-28 21:48:02 +00003698 return ReplaceInstUsesWith(I, LHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003699 case ICmpInst::ICMP_SLT: // (X u< 13 & X s< 15) -> no change
3700 break;
Chris Lattner955f3312004-09-28 21:48:02 +00003701 }
Reid Spencere4d87aa2006-12-23 06:05:41 +00003702 break;
3703 case ICmpInst::ICMP_SLT:
Chris Lattner955f3312004-09-28 21:48:02 +00003704 switch (RHSCC) {
3705 default: assert(0 && "Unknown integer condition code!");
Reid Spencere4d87aa2006-12-23 06:05:41 +00003706 case ICmpInst::ICMP_EQ: // (X s< 13 & X == 15) -> false
3707 case ICmpInst::ICMP_SGT: // (X s< 13 & X s> 15) -> false
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003708 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00003709 case ICmpInst::ICMP_UGT: // (X s< 13 & X u> 15) -> no change
3710 break;
3711 case ICmpInst::ICMP_NE: // (X s< 13 & X != 15) -> X < 13
3712 case ICmpInst::ICMP_SLT: // (X s< 13 & X s< 15) -> X < 13
Chris Lattner955f3312004-09-28 21:48:02 +00003713 return ReplaceInstUsesWith(I, LHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003714 case ICmpInst::ICMP_ULT: // (X s< 13 & X u< 15) -> no change
3715 break;
Chris Lattner955f3312004-09-28 21:48:02 +00003716 }
Reid Spencere4d87aa2006-12-23 06:05:41 +00003717 break;
3718 case ICmpInst::ICMP_UGT:
3719 switch (RHSCC) {
3720 default: assert(0 && "Unknown integer condition code!");
3721 case ICmpInst::ICMP_EQ: // (X u> 13 & X == 15) -> X > 13
3722 return ReplaceInstUsesWith(I, LHS);
3723 case ICmpInst::ICMP_UGT: // (X u> 13 & X u> 15) -> X u> 15
3724 return ReplaceInstUsesWith(I, RHS);
3725 case ICmpInst::ICMP_SGT: // (X u> 13 & X s> 15) -> no change
3726 break;
3727 case ICmpInst::ICMP_NE:
3728 if (RHSCst == AddOne(LHSCst)) // (X u> 13 & X != 14) -> X u> 14
3729 return new ICmpInst(LHSCC, LHSVal, RHSCst);
3730 break; // (X u> 13 & X != 15) -> no change
3731 case ICmpInst::ICMP_ULT: // (X u> 13 & X u< 15) ->(X-14) <u 1
3732 return InsertRangeTest(LHSVal, AddOne(LHSCst), RHSCst, false,
3733 true, I);
3734 case ICmpInst::ICMP_SLT: // (X u> 13 & X s< 15) -> no change
3735 break;
3736 }
3737 break;
3738 case ICmpInst::ICMP_SGT:
3739 switch (RHSCC) {
3740 default: assert(0 && "Unknown integer condition code!");
Chris Lattnera7d1ab02007-11-16 06:04:17 +00003741 case ICmpInst::ICMP_EQ: // (X s> 13 & X == 15) -> X == 15
Reid Spencere4d87aa2006-12-23 06:05:41 +00003742 case ICmpInst::ICMP_SGT: // (X s> 13 & X s> 15) -> X s> 15
3743 return ReplaceInstUsesWith(I, RHS);
3744 case ICmpInst::ICMP_UGT: // (X s> 13 & X u> 15) -> no change
3745 break;
3746 case ICmpInst::ICMP_NE:
3747 if (RHSCst == AddOne(LHSCst)) // (X s> 13 & X != 14) -> X s> 14
3748 return new ICmpInst(LHSCC, LHSVal, RHSCst);
3749 break; // (X s> 13 & X != 15) -> no change
3750 case ICmpInst::ICMP_SLT: // (X s> 13 & X s< 15) ->(X-14) s< 1
3751 return InsertRangeTest(LHSVal, AddOne(LHSCst), RHSCst, true,
3752 true, I);
3753 case ICmpInst::ICMP_ULT: // (X s> 13 & X u< 15) -> no change
3754 break;
3755 }
3756 break;
Chris Lattner955f3312004-09-28 21:48:02 +00003757 }
3758 }
3759 }
3760
Chris Lattner6fc205f2006-05-05 06:39:07 +00003761 // fold (and (cast A), (cast B)) -> (cast (and A, B))
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00003762 if (CastInst *Op0C = dyn_cast<CastInst>(Op0))
3763 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
3764 if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind ?
3765 const Type *SrcTy = Op0C->getOperand(0)->getType();
Chris Lattner42a75512007-01-15 02:27:26 +00003766 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00003767 // Only do this if the casts both really cause code to be generated.
Reid Spencere4d87aa2006-12-23 06:05:41 +00003768 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
3769 I.getType(), TD) &&
3770 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
3771 I.getType(), TD)) {
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00003772 Instruction *NewOp = BinaryOperator::createAnd(Op0C->getOperand(0),
3773 Op1C->getOperand(0),
3774 I.getName());
3775 InsertNewInstBefore(NewOp, I);
3776 return CastInst::create(Op0C->getOpcode(), NewOp, I.getType());
3777 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00003778 }
Chris Lattnere511b742006-11-14 07:46:50 +00003779
3780 // (X >> Z) & (Y >> Z) -> (X&Y) >> Z for all shifts.
Reid Spencer832254e2007-02-02 02:16:23 +00003781 if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
3782 if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
3783 if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() &&
Chris Lattnere511b742006-11-14 07:46:50 +00003784 SI0->getOperand(1) == SI1->getOperand(1) &&
3785 (SI0->hasOneUse() || SI1->hasOneUse())) {
3786 Instruction *NewOp =
3787 InsertNewInstBefore(BinaryOperator::createAnd(SI0->getOperand(0),
3788 SI1->getOperand(0),
3789 SI0->getName()), I);
Reid Spencer832254e2007-02-02 02:16:23 +00003790 return BinaryOperator::create(SI1->getOpcode(), NewOp,
3791 SI1->getOperand(1));
Chris Lattnere511b742006-11-14 07:46:50 +00003792 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00003793 }
3794
Chris Lattner99c65742007-10-24 05:38:08 +00003795 // (fcmp ord x, c) & (fcmp ord y, c) -> (fcmp ord x, y)
3796 if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0))) {
3797 if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1))) {
3798 if (LHS->getPredicate() == FCmpInst::FCMP_ORD &&
3799 RHS->getPredicate() == FCmpInst::FCMP_ORD)
3800 if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
3801 if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
3802 // If either of the constants are nans, then the whole thing returns
3803 // false.
Chris Lattnerbe3e3482007-10-24 18:54:45 +00003804 if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
Chris Lattner99c65742007-10-24 05:38:08 +00003805 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
3806 return new FCmpInst(FCmpInst::FCMP_ORD, LHS->getOperand(0),
3807 RHS->getOperand(0));
3808 }
3809 }
3810 }
3811
Chris Lattner7e708292002-06-25 16:13:24 +00003812 return Changed ? &I : 0;
Chris Lattner3f5b8772002-05-06 16:14:14 +00003813}
3814
Chris Lattnerafe91a52006-06-15 19:07:26 +00003815/// CollectBSwapParts - Look to see if the specified value defines a single byte
3816/// in the result. If it does, and if the specified byte hasn't been filled in
3817/// yet, fill it in and return false.
Chris Lattner535014f2007-02-15 22:52:10 +00003818static bool CollectBSwapParts(Value *V, SmallVector<Value*, 8> &ByteValues) {
Chris Lattnerafe91a52006-06-15 19:07:26 +00003819 Instruction *I = dyn_cast<Instruction>(V);
3820 if (I == 0) return true;
3821
3822 // If this is an or instruction, it is an inner node of the bswap.
3823 if (I->getOpcode() == Instruction::Or)
3824 return CollectBSwapParts(I->getOperand(0), ByteValues) ||
3825 CollectBSwapParts(I->getOperand(1), ByteValues);
3826
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00003827 uint32_t BitWidth = I->getType()->getPrimitiveSizeInBits();
Chris Lattnerafe91a52006-06-15 19:07:26 +00003828 // If this is a shift by a constant int, and it is "24", then its operand
3829 // defines a byte. We only handle unsigned types here.
Reid Spencer832254e2007-02-02 02:16:23 +00003830 if (I->isShift() && isa<ConstantInt>(I->getOperand(1))) {
Chris Lattnerafe91a52006-06-15 19:07:26 +00003831 // Not shifting the entire input by N-1 bytes?
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00003832 if (cast<ConstantInt>(I->getOperand(1))->getLimitedValue(BitWidth) !=
Chris Lattnerafe91a52006-06-15 19:07:26 +00003833 8*(ByteValues.size()-1))
3834 return true;
3835
3836 unsigned DestNo;
3837 if (I->getOpcode() == Instruction::Shl) {
3838 // X << 24 defines the top byte with the lowest of the input bytes.
3839 DestNo = ByteValues.size()-1;
3840 } else {
3841 // X >>u 24 defines the low byte with the highest of the input bytes.
3842 DestNo = 0;
3843 }
3844
3845 // If the destination byte value is already defined, the values are or'd
3846 // together, which isn't a bswap (unless it's an or of the same bits).
3847 if (ByteValues[DestNo] && ByteValues[DestNo] != I->getOperand(0))
3848 return true;
3849 ByteValues[DestNo] = I->getOperand(0);
3850 return false;
3851 }
3852
3853 // Otherwise, we can only handle and(shift X, imm), imm). Bail out of if we
3854 // don't have this.
3855 Value *Shift = 0, *ShiftLHS = 0;
3856 ConstantInt *AndAmt = 0, *ShiftAmt = 0;
3857 if (!match(I, m_And(m_Value(Shift), m_ConstantInt(AndAmt))) ||
3858 !match(Shift, m_Shift(m_Value(ShiftLHS), m_ConstantInt(ShiftAmt))))
3859 return true;
3860 Instruction *SI = cast<Instruction>(Shift);
3861
3862 // Make sure that the shift amount is by a multiple of 8 and isn't too big.
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00003863 if (ShiftAmt->getLimitedValue(BitWidth) & 7 ||
3864 ShiftAmt->getLimitedValue(BitWidth) > 8*ByteValues.size())
Chris Lattnerafe91a52006-06-15 19:07:26 +00003865 return true;
3866
3867 // Turn 0xFF -> 0, 0xFF00 -> 1, 0xFF0000 -> 2, etc.
3868 unsigned DestByte;
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00003869 if (AndAmt->getValue().getActiveBits() > 64)
3870 return true;
3871 uint64_t AndAmtVal = AndAmt->getZExtValue();
Chris Lattnerafe91a52006-06-15 19:07:26 +00003872 for (DestByte = 0; DestByte != ByteValues.size(); ++DestByte)
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00003873 if (AndAmtVal == uint64_t(0xFF) << 8*DestByte)
Chris Lattnerafe91a52006-06-15 19:07:26 +00003874 break;
3875 // Unknown mask for bswap.
3876 if (DestByte == ByteValues.size()) return true;
3877
Reid Spencerb83eb642006-10-20 07:07:24 +00003878 unsigned ShiftBytes = ShiftAmt->getZExtValue()/8;
Chris Lattnerafe91a52006-06-15 19:07:26 +00003879 unsigned SrcByte;
3880 if (SI->getOpcode() == Instruction::Shl)
3881 SrcByte = DestByte - ShiftBytes;
3882 else
3883 SrcByte = DestByte + ShiftBytes;
3884
3885 // If the SrcByte isn't a bswapped value from the DestByte, reject it.
3886 if (SrcByte != ByteValues.size()-DestByte-1)
3887 return true;
3888
3889 // If the destination byte value is already defined, the values are or'd
3890 // together, which isn't a bswap (unless it's an or of the same bits).
3891 if (ByteValues[DestByte] && ByteValues[DestByte] != SI->getOperand(0))
3892 return true;
3893 ByteValues[DestByte] = SI->getOperand(0);
3894 return false;
3895}
3896
3897/// MatchBSwap - Given an OR instruction, check to see if this is a bswap idiom.
3898/// If so, insert the new bswap intrinsic and return it.
3899Instruction *InstCombiner::MatchBSwap(BinaryOperator &I) {
Chris Lattner55fc8c42007-04-01 20:57:36 +00003900 const IntegerType *ITy = dyn_cast<IntegerType>(I.getType());
3901 if (!ITy || ITy->getBitWidth() % 16)
3902 return 0; // Can only bswap pairs of bytes. Can't do vectors.
Chris Lattnerafe91a52006-06-15 19:07:26 +00003903
3904 /// ByteValues - For each byte of the result, we keep track of which value
3905 /// defines each byte.
Chris Lattner535014f2007-02-15 22:52:10 +00003906 SmallVector<Value*, 8> ByteValues;
Chris Lattner55fc8c42007-04-01 20:57:36 +00003907 ByteValues.resize(ITy->getBitWidth()/8);
Chris Lattnerafe91a52006-06-15 19:07:26 +00003908
3909 // Try to find all the pieces corresponding to the bswap.
3910 if (CollectBSwapParts(I.getOperand(0), ByteValues) ||
3911 CollectBSwapParts(I.getOperand(1), ByteValues))
3912 return 0;
3913
3914 // Check to see if all of the bytes come from the same value.
3915 Value *V = ByteValues[0];
3916 if (V == 0) return 0; // Didn't find a byte? Must be zero.
3917
3918 // Check to make sure that all of the bytes come from the same value.
3919 for (unsigned i = 1, e = ByteValues.size(); i != e; ++i)
3920 if (ByteValues[i] != V)
3921 return 0;
Chandler Carruth69940402007-08-04 01:51:18 +00003922 const Type *Tys[] = { ITy };
Chris Lattnerafe91a52006-06-15 19:07:26 +00003923 Module *M = I.getParent()->getParent()->getParent();
Chandler Carruth69940402007-08-04 01:51:18 +00003924 Function *F = Intrinsic::getDeclaration(M, Intrinsic::bswap, Tys, 1);
Chris Lattnerafe91a52006-06-15 19:07:26 +00003925 return new CallInst(F, V);
3926}
3927
3928
Chris Lattner7e708292002-06-25 16:13:24 +00003929Instruction *InstCombiner::visitOr(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00003930 bool Changed = SimplifyCommutative(I);
Chris Lattner7e708292002-06-25 16:13:24 +00003931 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00003932
Chris Lattner42593e62007-03-24 23:56:43 +00003933 if (isa<UndefValue>(Op1)) // X | undef -> -1
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00003934 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Chris Lattnere87597f2004-10-16 18:11:37 +00003935
Chris Lattnerf8c36f52006-02-12 08:02:11 +00003936 // or X, X = X
3937 if (Op0 == Op1)
Chris Lattner233f7dc2002-08-12 21:17:25 +00003938 return ReplaceInstUsesWith(I, Op0);
Chris Lattner3f5b8772002-05-06 16:14:14 +00003939
Chris Lattnerf8c36f52006-02-12 08:02:11 +00003940 // See if we can simplify any instructions used by the instruction whose sole
3941 // purpose is to compute bits we don't care about.
Chris Lattner42593e62007-03-24 23:56:43 +00003942 if (!isa<VectorType>(I.getType())) {
3943 uint32_t BitWidth = cast<IntegerType>(I.getType())->getBitWidth();
3944 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
3945 if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(BitWidth),
3946 KnownZero, KnownOne))
3947 return &I;
Chris Lattner041a6c92007-06-15 05:26:55 +00003948 } else if (isa<ConstantAggregateZero>(Op1)) {
3949 return ReplaceInstUsesWith(I, Op0); // X | <0,0> -> X
3950 } else if (ConstantVector *CP = dyn_cast<ConstantVector>(Op1)) {
3951 if (CP->isAllOnesValue()) // X | <-1,-1> -> <-1,-1>
3952 return ReplaceInstUsesWith(I, I.getOperand(1));
Chris Lattner42593e62007-03-24 23:56:43 +00003953 }
Chris Lattner041a6c92007-06-15 05:26:55 +00003954
3955
Chris Lattnerf8c36f52006-02-12 08:02:11 +00003956
Chris Lattner3f5b8772002-05-06 16:14:14 +00003957 // or X, -1 == -1
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003958 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner4f637d42006-01-06 17:59:59 +00003959 ConstantInt *C1 = 0; Value *X = 0;
Chris Lattneracd1f0f2004-07-30 07:50:03 +00003960 // (X & C1) | C2 --> (X | C2) & (C1|C2)
3961 if (match(Op0, m_And(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
Chris Lattner6934a042007-02-11 01:23:03 +00003962 Instruction *Or = BinaryOperator::createOr(X, RHS);
Chris Lattneracd1f0f2004-07-30 07:50:03 +00003963 InsertNewInstBefore(Or, I);
Chris Lattner6934a042007-02-11 01:23:03 +00003964 Or->takeName(Op0);
Zhou Sheng4a1822a2007-04-02 13:45:30 +00003965 return BinaryOperator::createAnd(Or,
3966 ConstantInt::get(RHS->getValue() | C1->getValue()));
Chris Lattneracd1f0f2004-07-30 07:50:03 +00003967 }
Chris Lattnerad44ebf2003-07-23 18:29:44 +00003968
Chris Lattneracd1f0f2004-07-30 07:50:03 +00003969 // (X ^ C1) | C2 --> (X | C2) ^ (C1&~C2)
3970 if (match(Op0, m_Xor(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
Chris Lattner6934a042007-02-11 01:23:03 +00003971 Instruction *Or = BinaryOperator::createOr(X, RHS);
Chris Lattneracd1f0f2004-07-30 07:50:03 +00003972 InsertNewInstBefore(Or, I);
Chris Lattner6934a042007-02-11 01:23:03 +00003973 Or->takeName(Op0);
Chris Lattneracd1f0f2004-07-30 07:50:03 +00003974 return BinaryOperator::createXor(Or,
Zhou Sheng4a1822a2007-04-02 13:45:30 +00003975 ConstantInt::get(C1->getValue() & ~RHS->getValue()));
Chris Lattnerad44ebf2003-07-23 18:29:44 +00003976 }
Chris Lattner2eefe512004-04-09 19:05:30 +00003977
3978 // Try to fold constant and into select arguments.
3979 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner6e7ba452005-01-01 16:22:27 +00003980 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00003981 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00003982 if (isa<PHINode>(Op0))
3983 if (Instruction *NV = FoldOpIntoPhi(I))
3984 return NV;
Chris Lattnerad44ebf2003-07-23 18:29:44 +00003985 }
3986
Chris Lattner4f637d42006-01-06 17:59:59 +00003987 Value *A = 0, *B = 0;
3988 ConstantInt *C1 = 0, *C2 = 0;
Chris Lattnerf4d4c872005-05-07 23:49:08 +00003989
3990 if (match(Op0, m_And(m_Value(A), m_Value(B))))
3991 if (A == Op1 || B == Op1) // (A & ?) | A --> A
3992 return ReplaceInstUsesWith(I, Op1);
3993 if (match(Op1, m_And(m_Value(A), m_Value(B))))
3994 if (A == Op0 || B == Op0) // A | (A & ?) --> A
3995 return ReplaceInstUsesWith(I, Op0);
3996
Chris Lattner6423d4c2006-07-10 20:25:24 +00003997 // (A | B) | C and A | (B | C) -> bswap if possible.
3998 // (A >> B) | (C << D) and (A << B) | (B >> C) -> bswap if possible.
Chris Lattnerafe91a52006-06-15 19:07:26 +00003999 if (match(Op0, m_Or(m_Value(), m_Value())) ||
Chris Lattner6423d4c2006-07-10 20:25:24 +00004000 match(Op1, m_Or(m_Value(), m_Value())) ||
4001 (match(Op0, m_Shift(m_Value(), m_Value())) &&
4002 match(Op1, m_Shift(m_Value(), m_Value())))) {
Chris Lattnerafe91a52006-06-15 19:07:26 +00004003 if (Instruction *BSwap = MatchBSwap(I))
4004 return BSwap;
4005 }
4006
Chris Lattner6e4c6492005-05-09 04:58:36 +00004007 // (X^C)|Y -> (X|Y)^C iff Y&C == 0
4008 if (Op0->hasOneUse() && match(Op0, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
Reid Spencera03d45f2007-03-22 22:19:58 +00004009 MaskedValueIsZero(Op1, C1->getValue())) {
Chris Lattner6934a042007-02-11 01:23:03 +00004010 Instruction *NOr = BinaryOperator::createOr(A, Op1);
4011 InsertNewInstBefore(NOr, I);
4012 NOr->takeName(Op0);
4013 return BinaryOperator::createXor(NOr, C1);
Chris Lattner6e4c6492005-05-09 04:58:36 +00004014 }
4015
4016 // Y|(X^C) -> (X|Y)^C iff Y&C == 0
4017 if (Op1->hasOneUse() && match(Op1, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
Reid Spencera03d45f2007-03-22 22:19:58 +00004018 MaskedValueIsZero(Op0, C1->getValue())) {
Chris Lattner6934a042007-02-11 01:23:03 +00004019 Instruction *NOr = BinaryOperator::createOr(A, Op0);
4020 InsertNewInstBefore(NOr, I);
4021 NOr->takeName(Op0);
4022 return BinaryOperator::createXor(NOr, C1);
Chris Lattner6e4c6492005-05-09 04:58:36 +00004023 }
4024
Chris Lattnerc5e7ea42007-04-08 07:47:01 +00004025 // (A & C)|(B & D)
Chris Lattner2384d7b2007-06-19 05:43:49 +00004026 Value *C = 0, *D = 0;
Chris Lattnerc5e7ea42007-04-08 07:47:01 +00004027 if (match(Op0, m_And(m_Value(A), m_Value(C))) &&
4028 match(Op1, m_And(m_Value(B), m_Value(D)))) {
Chris Lattner6cae0e02007-04-08 07:55:22 +00004029 Value *V1 = 0, *V2 = 0, *V3 = 0;
4030 C1 = dyn_cast<ConstantInt>(C);
4031 C2 = dyn_cast<ConstantInt>(D);
4032 if (C1 && C2) { // (A & C1)|(B & C2)
4033 // If we have: ((V + N) & C1) | (V & C2)
4034 // .. and C2 = ~C1 and C2 is 0+1+ and (N & C2) == 0
4035 // replace with V+N.
4036 if (C1->getValue() == ~C2->getValue()) {
4037 if ((C2->getValue() & (C2->getValue()+1)) == 0 && // C2 == 0+1+
4038 match(A, m_Add(m_Value(V1), m_Value(V2)))) {
4039 // Add commutes, try both ways.
4040 if (V1 == B && MaskedValueIsZero(V2, C2->getValue()))
4041 return ReplaceInstUsesWith(I, A);
4042 if (V2 == B && MaskedValueIsZero(V1, C2->getValue()))
4043 return ReplaceInstUsesWith(I, A);
4044 }
4045 // Or commutes, try both ways.
4046 if ((C1->getValue() & (C1->getValue()+1)) == 0 &&
4047 match(B, m_Add(m_Value(V1), m_Value(V2)))) {
4048 // Add commutes, try both ways.
4049 if (V1 == A && MaskedValueIsZero(V2, C1->getValue()))
4050 return ReplaceInstUsesWith(I, B);
4051 if (V2 == A && MaskedValueIsZero(V1, C1->getValue()))
4052 return ReplaceInstUsesWith(I, B);
4053 }
4054 }
Chris Lattner044e5332007-04-08 08:01:49 +00004055 V1 = 0; V2 = 0; V3 = 0;
Chris Lattner6cae0e02007-04-08 07:55:22 +00004056 }
4057
Chris Lattnerc5e7ea42007-04-08 07:47:01 +00004058 // Check to see if we have any common things being and'ed. If so, find the
4059 // terms for V1 & (V2|V3).
Chris Lattnerc5e7ea42007-04-08 07:47:01 +00004060 if (isOnlyUse(Op0) || isOnlyUse(Op1)) {
4061 if (A == B) // (A & C)|(A & D) == A & (C|D)
4062 V1 = A, V2 = C, V3 = D;
4063 else if (A == D) // (A & C)|(B & A) == A & (B|C)
4064 V1 = A, V2 = B, V3 = C;
4065 else if (C == B) // (A & C)|(C & D) == C & (A|D)
4066 V1 = C, V2 = A, V3 = D;
4067 else if (C == D) // (A & C)|(B & C) == C & (A|B)
4068 V1 = C, V2 = A, V3 = B;
4069
4070 if (V1) {
4071 Value *Or =
4072 InsertNewInstBefore(BinaryOperator::createOr(V2, V3, "tmp"), I);
4073 return BinaryOperator::createAnd(V1, Or);
Chris Lattner0b7c0bf2005-09-18 06:02:59 +00004074 }
Chris Lattnerc5e7ea42007-04-08 07:47:01 +00004075 }
Chris Lattnere9bed7d2005-09-18 03:42:07 +00004076 }
Chris Lattnere511b742006-11-14 07:46:50 +00004077
4078 // (X >> Z) | (Y >> Z) -> (X|Y) >> Z for all shifts.
Reid Spencer832254e2007-02-02 02:16:23 +00004079 if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
4080 if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
4081 if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() &&
Chris Lattnere511b742006-11-14 07:46:50 +00004082 SI0->getOperand(1) == SI1->getOperand(1) &&
4083 (SI0->hasOneUse() || SI1->hasOneUse())) {
4084 Instruction *NewOp =
4085 InsertNewInstBefore(BinaryOperator::createOr(SI0->getOperand(0),
4086 SI1->getOperand(0),
4087 SI0->getName()), I);
Reid Spencer832254e2007-02-02 02:16:23 +00004088 return BinaryOperator::create(SI1->getOpcode(), NewOp,
4089 SI1->getOperand(1));
Chris Lattnere511b742006-11-14 07:46:50 +00004090 }
4091 }
Chris Lattner67ca7682003-08-12 19:11:07 +00004092
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004093 if (match(Op0, m_Not(m_Value(A)))) { // ~A | Op1
4094 if (A == Op1) // ~A | A == -1
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00004095 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004096 } else {
4097 A = 0;
4098 }
Chris Lattnerf4d4c872005-05-07 23:49:08 +00004099 // Note, A is still live here!
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004100 if (match(Op1, m_Not(m_Value(B)))) { // Op0 | ~B
4101 if (Op0 == B)
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00004102 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Chris Lattnera27231a2003-03-10 23:13:59 +00004103
Misha Brukmancb6267b2004-07-30 12:50:08 +00004104 // (~A | ~B) == (~(A & B)) - De Morgan's Law
Chris Lattneracd1f0f2004-07-30 07:50:03 +00004105 if (A && isOnlyUse(Op0) && isOnlyUse(Op1)) {
4106 Value *And = InsertNewInstBefore(BinaryOperator::createAnd(A, B,
4107 I.getName()+".demorgan"), I);
4108 return BinaryOperator::createNot(And);
4109 }
Chris Lattnera27231a2003-03-10 23:13:59 +00004110 }
Chris Lattnera2881962003-02-18 19:28:33 +00004111
Reid Spencere4d87aa2006-12-23 06:05:41 +00004112 // (icmp1 A, B) | (icmp2 A, B) --> (icmp3 A, B)
4113 if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1))) {
4114 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
Chris Lattneraa9c1f12003-08-13 20:16:26 +00004115 return R;
4116
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004117 Value *LHSVal, *RHSVal;
4118 ConstantInt *LHSCst, *RHSCst;
Reid Spencere4d87aa2006-12-23 06:05:41 +00004119 ICmpInst::Predicate LHSCC, RHSCC;
4120 if (match(Op0, m_ICmp(LHSCC, m_Value(LHSVal), m_ConstantInt(LHSCst))))
4121 if (match(RHS, m_ICmp(RHSCC, m_Value(RHSVal), m_ConstantInt(RHSCst))))
4122 if (LHSVal == RHSVal && // Found (X icmp C1) | (X icmp C2)
4123 // icmp [us][gl]e x, cst is folded to icmp [us][gl]t elsewhere.
4124 LHSCC != ICmpInst::ICMP_UGE && LHSCC != ICmpInst::ICMP_ULE &&
4125 RHSCC != ICmpInst::ICMP_UGE && RHSCC != ICmpInst::ICMP_ULE &&
4126 LHSCC != ICmpInst::ICMP_SGE && LHSCC != ICmpInst::ICMP_SLE &&
Chris Lattner88858872007-05-11 05:55:56 +00004127 RHSCC != ICmpInst::ICMP_SGE && RHSCC != ICmpInst::ICMP_SLE &&
4128 // We can't fold (ugt x, C) | (sgt x, C2).
4129 PredicatesFoldable(LHSCC, RHSCC)) {
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004130 // Ensure that the larger constant is on the RHS.
Reid Spencere4d87aa2006-12-23 06:05:41 +00004131 ICmpInst *LHS = cast<ICmpInst>(Op0);
Chris Lattner88858872007-05-11 05:55:56 +00004132 bool NeedsSwap;
4133 if (ICmpInst::isSignedPredicate(LHSCC))
Chris Lattner3aea1bd2007-05-11 16:58:45 +00004134 NeedsSwap = LHSCst->getValue().sgt(RHSCst->getValue());
Chris Lattner88858872007-05-11 05:55:56 +00004135 else
Chris Lattner3aea1bd2007-05-11 16:58:45 +00004136 NeedsSwap = LHSCst->getValue().ugt(RHSCst->getValue());
Chris Lattner88858872007-05-11 05:55:56 +00004137
4138 if (NeedsSwap) {
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004139 std::swap(LHS, RHS);
4140 std::swap(LHSCst, RHSCst);
4141 std::swap(LHSCC, RHSCC);
4142 }
4143
Reid Spencere4d87aa2006-12-23 06:05:41 +00004144 // At this point, we know we have have two icmp instructions
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004145 // comparing a value against two constants and or'ing the result
4146 // together. Because of the above check, we know that we only have
Reid Spencere4d87aa2006-12-23 06:05:41 +00004147 // ICMP_EQ, ICMP_NE, ICMP_LT, and ICMP_GT here. We also know (from the
4148 // FoldICmpLogical check above), that the two constants are not
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004149 // equal.
4150 assert(LHSCst != RHSCst && "Compares not folded above?");
4151
4152 switch (LHSCC) {
4153 default: assert(0 && "Unknown integer condition code!");
Reid Spencere4d87aa2006-12-23 06:05:41 +00004154 case ICmpInst::ICMP_EQ:
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004155 switch (RHSCC) {
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 if (LHSCst == SubOne(RHSCst)) {// (X == 13 | X == 14) -> X-13 <u 2
4159 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
4160 Instruction *Add = BinaryOperator::createAdd(LHSVal, AddCST,
4161 LHSVal->getName()+".off");
4162 InsertNewInstBefore(Add, I);
Zhou Sheng4a1822a2007-04-02 13:45:30 +00004163 AddCST = Subtract(AddOne(RHSCst), LHSCst);
Reid Spencere4d87aa2006-12-23 06:05:41 +00004164 return new ICmpInst(ICmpInst::ICMP_ULT, Add, AddCST);
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004165 }
Reid Spencere4d87aa2006-12-23 06:05:41 +00004166 break; // (X == 13 | X == 15) -> no change
4167 case ICmpInst::ICMP_UGT: // (X == 13 | X u> 14) -> no change
4168 case ICmpInst::ICMP_SGT: // (X == 13 | X s> 14) -> no change
Chris Lattner240d6f42005-04-19 06:04:18 +00004169 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00004170 case ICmpInst::ICMP_NE: // (X == 13 | X != 15) -> X != 15
4171 case ICmpInst::ICMP_ULT: // (X == 13 | X u< 15) -> X u< 15
4172 case ICmpInst::ICMP_SLT: // (X == 13 | X s< 15) -> X s< 15
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004173 return ReplaceInstUsesWith(I, RHS);
4174 }
4175 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00004176 case ICmpInst::ICMP_NE:
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004177 switch (RHSCC) {
4178 default: assert(0 && "Unknown integer condition code!");
Reid Spencere4d87aa2006-12-23 06:05:41 +00004179 case ICmpInst::ICMP_EQ: // (X != 13 | X == 15) -> X != 13
4180 case ICmpInst::ICMP_UGT: // (X != 13 | X u> 15) -> X != 13
4181 case ICmpInst::ICMP_SGT: // (X != 13 | X s> 15) -> X != 13
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004182 return ReplaceInstUsesWith(I, LHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00004183 case ICmpInst::ICMP_NE: // (X != 13 | X != 15) -> true
4184 case ICmpInst::ICMP_ULT: // (X != 13 | X u< 15) -> true
4185 case ICmpInst::ICMP_SLT: // (X != 13 | X s< 15) -> true
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004186 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004187 }
4188 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00004189 case ICmpInst::ICMP_ULT:
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004190 switch (RHSCC) {
4191 default: assert(0 && "Unknown integer condition code!");
Reid Spencere4d87aa2006-12-23 06:05:41 +00004192 case ICmpInst::ICMP_EQ: // (X u< 13 | X == 14) -> no change
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004193 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00004194 case ICmpInst::ICMP_UGT: // (X u< 13 | X u> 15) ->(X-13) u> 2
Chris Lattner74e012a2007-11-01 02:18:41 +00004195 // If RHSCst is [us]MAXINT, it is always false. Not handling
4196 // this can cause overflow.
4197 if (RHSCst->isMaxValue(false))
4198 return ReplaceInstUsesWith(I, LHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00004199 return InsertRangeTest(LHSVal, LHSCst, AddOne(RHSCst), false,
4200 false, I);
4201 case ICmpInst::ICMP_SGT: // (X u< 13 | X s> 15) -> no change
4202 break;
4203 case ICmpInst::ICMP_NE: // (X u< 13 | X != 15) -> X != 15
4204 case ICmpInst::ICMP_ULT: // (X u< 13 | X u< 15) -> X u< 15
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004205 return ReplaceInstUsesWith(I, RHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00004206 case ICmpInst::ICMP_SLT: // (X u< 13 | X s< 15) -> no change
4207 break;
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004208 }
4209 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00004210 case ICmpInst::ICMP_SLT:
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004211 switch (RHSCC) {
4212 default: assert(0 && "Unknown integer condition code!");
Reid Spencere4d87aa2006-12-23 06:05:41 +00004213 case ICmpInst::ICMP_EQ: // (X s< 13 | X == 14) -> no change
4214 break;
4215 case ICmpInst::ICMP_SGT: // (X s< 13 | X s> 15) ->(X-13) s> 2
Chris Lattner74e012a2007-11-01 02:18:41 +00004216 // If RHSCst is [us]MAXINT, it is always false. Not handling
4217 // this can cause overflow.
4218 if (RHSCst->isMaxValue(true))
4219 return ReplaceInstUsesWith(I, LHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00004220 return InsertRangeTest(LHSVal, LHSCst, AddOne(RHSCst), true,
4221 false, I);
4222 case ICmpInst::ICMP_UGT: // (X s< 13 | X u> 15) -> no change
4223 break;
4224 case ICmpInst::ICMP_NE: // (X s< 13 | X != 15) -> X != 15
4225 case ICmpInst::ICMP_SLT: // (X s< 13 | X s< 15) -> X s< 15
4226 return ReplaceInstUsesWith(I, RHS);
4227 case ICmpInst::ICMP_ULT: // (X s< 13 | X u< 15) -> no change
4228 break;
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004229 }
Reid Spencere4d87aa2006-12-23 06:05:41 +00004230 break;
4231 case ICmpInst::ICMP_UGT:
4232 switch (RHSCC) {
4233 default: assert(0 && "Unknown integer condition code!");
4234 case ICmpInst::ICMP_EQ: // (X u> 13 | X == 15) -> X u> 13
4235 case ICmpInst::ICMP_UGT: // (X u> 13 | X u> 15) -> X u> 13
4236 return ReplaceInstUsesWith(I, LHS);
4237 case ICmpInst::ICMP_SGT: // (X u> 13 | X s> 15) -> no change
4238 break;
4239 case ICmpInst::ICMP_NE: // (X u> 13 | X != 15) -> true
4240 case ICmpInst::ICMP_ULT: // (X u> 13 | X u< 15) -> true
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004241 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencere4d87aa2006-12-23 06:05:41 +00004242 case ICmpInst::ICMP_SLT: // (X u> 13 | X s< 15) -> no change
4243 break;
4244 }
4245 break;
4246 case ICmpInst::ICMP_SGT:
4247 switch (RHSCC) {
4248 default: assert(0 && "Unknown integer condition code!");
4249 case ICmpInst::ICMP_EQ: // (X s> 13 | X == 15) -> X > 13
4250 case ICmpInst::ICMP_SGT: // (X s> 13 | X s> 15) -> X > 13
4251 return ReplaceInstUsesWith(I, LHS);
4252 case ICmpInst::ICMP_UGT: // (X s> 13 | X u> 15) -> no change
4253 break;
4254 case ICmpInst::ICMP_NE: // (X s> 13 | X != 15) -> true
4255 case ICmpInst::ICMP_SLT: // (X s> 13 | X s< 15) -> true
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004256 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencere4d87aa2006-12-23 06:05:41 +00004257 case ICmpInst::ICMP_ULT: // (X s> 13 | X u< 15) -> no change
4258 break;
4259 }
4260 break;
Chris Lattnerb4f40d22004-09-28 22:33:08 +00004261 }
4262 }
4263 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00004264
4265 // fold (or (cast A), (cast B)) -> (cast (or A, B))
Chris Lattner99c65742007-10-24 05:38:08 +00004266 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
Chris Lattner6fc205f2006-05-05 06:39:07 +00004267 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004268 if (Op0C->getOpcode() == Op1C->getOpcode()) {// same cast kind ?
4269 const Type *SrcTy = Op0C->getOperand(0)->getType();
Chris Lattner42a75512007-01-15 02:27:26 +00004270 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004271 // Only do this if the casts both really cause code to be generated.
Reid Spencere4d87aa2006-12-23 06:05:41 +00004272 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
4273 I.getType(), TD) &&
4274 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
4275 I.getType(), TD)) {
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004276 Instruction *NewOp = BinaryOperator::createOr(Op0C->getOperand(0),
4277 Op1C->getOperand(0),
4278 I.getName());
4279 InsertNewInstBefore(NewOp, I);
4280 return CastInst::create(Op0C->getOpcode(), NewOp, I.getType());
4281 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00004282 }
Chris Lattner99c65742007-10-24 05:38:08 +00004283 }
4284
4285
4286 // (fcmp uno x, c) | (fcmp uno y, c) -> (fcmp uno x, y)
4287 if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0))) {
4288 if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1))) {
4289 if (LHS->getPredicate() == FCmpInst::FCMP_UNO &&
Chris Lattner5ebd9362008-02-29 06:09:11 +00004290 RHS->getPredicate() == FCmpInst::FCMP_UNO &&
4291 LHS->getOperand(0)->getType() == RHS->getOperand(0)->getType())
Chris Lattner99c65742007-10-24 05:38:08 +00004292 if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
4293 if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
4294 // If either of the constants are nans, then the whole thing returns
4295 // true.
Chris Lattnerbe3e3482007-10-24 18:54:45 +00004296 if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
Chris Lattner99c65742007-10-24 05:38:08 +00004297 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4298
4299 // Otherwise, no need to compare the two constants, compare the
4300 // rest.
4301 return new FCmpInst(FCmpInst::FCMP_UNO, LHS->getOperand(0),
4302 RHS->getOperand(0));
4303 }
4304 }
4305 }
Chris Lattnere9bed7d2005-09-18 03:42:07 +00004306
Chris Lattner7e708292002-06-25 16:13:24 +00004307 return Changed ? &I : 0;
Chris Lattner3f5b8772002-05-06 16:14:14 +00004308}
4309
Chris Lattnerc317d392004-02-16 01:20:27 +00004310// XorSelf - Implements: X ^ X --> 0
4311struct XorSelf {
4312 Value *RHS;
4313 XorSelf(Value *rhs) : RHS(rhs) {}
4314 bool shouldApply(Value *LHS) const { return LHS == RHS; }
4315 Instruction *apply(BinaryOperator &Xor) const {
4316 return &Xor;
4317 }
4318};
Chris Lattner3f5b8772002-05-06 16:14:14 +00004319
4320
Chris Lattner7e708292002-06-25 16:13:24 +00004321Instruction *InstCombiner::visitXor(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00004322 bool Changed = SimplifyCommutative(I);
Chris Lattner7e708292002-06-25 16:13:24 +00004323 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00004324
Chris Lattnere87597f2004-10-16 18:11:37 +00004325 if (isa<UndefValue>(Op1))
4326 return ReplaceInstUsesWith(I, Op1); // X ^ undef -> undef
4327
Chris Lattnerc317d392004-02-16 01:20:27 +00004328 // xor X, X = 0, even if X is nested in a sequence of Xor's.
4329 if (Instruction *Result = AssociativeOpt(I, XorSelf(Op1))) {
Chris Lattnera9ff5eb2007-08-05 08:47:58 +00004330 assert(Result == &I && "AssociativeOpt didn't work?"); Result=Result;
Chris Lattner233f7dc2002-08-12 21:17:25 +00004331 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnerc317d392004-02-16 01:20:27 +00004332 }
Chris Lattnerf8c36f52006-02-12 08:02:11 +00004333
4334 // See if we can simplify any instructions used by the instruction whose sole
4335 // purpose is to compute bits we don't care about.
Reid Spencera03d45f2007-03-22 22:19:58 +00004336 if (!isa<VectorType>(I.getType())) {
4337 uint32_t BitWidth = cast<IntegerType>(I.getType())->getBitWidth();
4338 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
4339 if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(BitWidth),
4340 KnownZero, KnownOne))
4341 return &I;
Chris Lattner041a6c92007-06-15 05:26:55 +00004342 } else if (isa<ConstantAggregateZero>(Op1)) {
4343 return ReplaceInstUsesWith(I, Op0); // X ^ <0,0> -> X
Reid Spencera03d45f2007-03-22 22:19:58 +00004344 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00004345
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00004346 // Is this a ~ operation?
4347 if (Value *NotOp = dyn_castNotVal(&I)) {
4348 // ~(~X & Y) --> (X | ~Y) - De Morgan's Law
4349 // ~(~X | Y) === (X & ~Y) - De Morgan's Law
4350 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(NotOp)) {
4351 if (Op0I->getOpcode() == Instruction::And ||
4352 Op0I->getOpcode() == Instruction::Or) {
4353 if (dyn_castNotVal(Op0I->getOperand(1))) Op0I->swapOperands();
4354 if (Value *Op0NotVal = dyn_castNotVal(Op0I->getOperand(0))) {
4355 Instruction *NotY =
4356 BinaryOperator::createNot(Op0I->getOperand(1),
4357 Op0I->getOperand(1)->getName()+".not");
4358 InsertNewInstBefore(NotY, I);
4359 if (Op0I->getOpcode() == Instruction::And)
4360 return BinaryOperator::createOr(Op0NotVal, NotY);
4361 else
4362 return BinaryOperator::createAnd(Op0NotVal, NotY);
4363 }
4364 }
4365 }
4366 }
4367
4368
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004369 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Nick Lewyckyf947b3e2007-08-06 20:04:16 +00004370 // xor (cmp A, B), true = not (cmp A, B) = !cmp A, B
4371 if (RHS == ConstantInt::getTrue() && Op0->hasOneUse()) {
4372 if (ICmpInst *ICI = dyn_cast<ICmpInst>(Op0))
Reid Spencere4d87aa2006-12-23 06:05:41 +00004373 return new ICmpInst(ICI->getInversePredicate(),
4374 ICI->getOperand(0), ICI->getOperand(1));
Chris Lattnerad5b4fb2003-11-04 23:50:51 +00004375
Nick Lewyckyf947b3e2007-08-06 20:04:16 +00004376 if (FCmpInst *FCI = dyn_cast<FCmpInst>(Op0))
4377 return new FCmpInst(FCI->getInversePredicate(),
4378 FCI->getOperand(0), FCI->getOperand(1));
4379 }
4380
Reid Spencere4d87aa2006-12-23 06:05:41 +00004381 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
Chris Lattnerd65460f2003-11-05 01:06:05 +00004382 // ~(c-X) == X-c-1 == X+(-c-1)
Chris Lattner7c4049c2004-01-12 19:35:11 +00004383 if (Op0I->getOpcode() == Instruction::Sub && RHS->isAllOnesValue())
4384 if (Constant *Op0I0C = dyn_cast<Constant>(Op0I->getOperand(0))) {
Chris Lattner48595f12004-06-10 02:07:29 +00004385 Constant *NegOp0I0C = ConstantExpr::getNeg(Op0I0C);
4386 Constant *ConstantRHS = ConstantExpr::getSub(NegOp0I0C,
Chris Lattner7c4049c2004-01-12 19:35:11 +00004387 ConstantInt::get(I.getType(), 1));
Chris Lattner48595f12004-06-10 02:07:29 +00004388 return BinaryOperator::createAdd(Op0I->getOperand(1), ConstantRHS);
Chris Lattner7c4049c2004-01-12 19:35:11 +00004389 }
Chris Lattner5c6e2db2007-04-02 05:36:22 +00004390
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00004391 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
Chris Lattnerf8c36f52006-02-12 08:02:11 +00004392 if (Op0I->getOpcode() == Instruction::Add) {
Chris Lattner689d24b2003-11-04 23:37:10 +00004393 // ~(X-c) --> (-c-1)-X
Chris Lattner7c4049c2004-01-12 19:35:11 +00004394 if (RHS->isAllOnesValue()) {
Chris Lattner48595f12004-06-10 02:07:29 +00004395 Constant *NegOp0CI = ConstantExpr::getNeg(Op0CI);
4396 return BinaryOperator::createSub(
4397 ConstantExpr::getSub(NegOp0CI,
Chris Lattner7c4049c2004-01-12 19:35:11 +00004398 ConstantInt::get(I.getType(), 1)),
Chris Lattner689d24b2003-11-04 23:37:10 +00004399 Op0I->getOperand(0));
Chris Lattneracf4e072007-04-02 05:42:22 +00004400 } else if (RHS->getValue().isSignBit()) {
Chris Lattner5c6e2db2007-04-02 05:36:22 +00004401 // (X + C) ^ signbit -> (X + C + signbit)
4402 Constant *C = ConstantInt::get(RHS->getValue() + Op0CI->getValue());
4403 return BinaryOperator::createAdd(Op0I->getOperand(0), C);
Chris Lattnercd1d6d52007-04-02 05:48:58 +00004404
Chris Lattner7c4049c2004-01-12 19:35:11 +00004405 }
Chris Lattner02bd1b32006-02-26 19:57:54 +00004406 } else if (Op0I->getOpcode() == Instruction::Or) {
4407 // (X|C1)^C2 -> X^(C1|C2) iff X&~C1 == 0
Reid Spencera03d45f2007-03-22 22:19:58 +00004408 if (MaskedValueIsZero(Op0I->getOperand(0), Op0CI->getValue())) {
Chris Lattner02bd1b32006-02-26 19:57:54 +00004409 Constant *NewRHS = ConstantExpr::getOr(Op0CI, RHS);
4410 // Anything in both C1 and C2 is known to be zero, remove it from
4411 // NewRHS.
Zhou Sheng4a1822a2007-04-02 13:45:30 +00004412 Constant *CommonBits = And(Op0CI, RHS);
Chris Lattner02bd1b32006-02-26 19:57:54 +00004413 NewRHS = ConstantExpr::getAnd(NewRHS,
4414 ConstantExpr::getNot(CommonBits));
Chris Lattnerdbab3862007-03-02 21:28:56 +00004415 AddToWorkList(Op0I);
Chris Lattner02bd1b32006-02-26 19:57:54 +00004416 I.setOperand(0, Op0I->getOperand(0));
4417 I.setOperand(1, NewRHS);
4418 return &I;
4419 }
Chris Lattnereca0c5c2003-07-23 21:37:07 +00004420 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00004421 }
Chris Lattner05bd1b22002-08-20 18:24:26 +00004422 }
Chris Lattner2eefe512004-04-09 19:05:30 +00004423
4424 // Try to fold constant and into select arguments.
4425 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner6e7ba452005-01-01 16:22:27 +00004426 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00004427 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00004428 if (isa<PHINode>(Op0))
4429 if (Instruction *NV = FoldOpIntoPhi(I))
4430 return NV;
Chris Lattner3f5b8772002-05-06 16:14:14 +00004431 }
4432
Chris Lattner8d969642003-03-10 23:06:50 +00004433 if (Value *X = dyn_castNotVal(Op0)) // ~A ^ A == -1
Chris Lattnera2881962003-02-18 19:28:33 +00004434 if (X == Op1)
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00004435 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Chris Lattnera2881962003-02-18 19:28:33 +00004436
Chris Lattner8d969642003-03-10 23:06:50 +00004437 if (Value *X = dyn_castNotVal(Op1)) // A ^ ~A == -1
Chris Lattnera2881962003-02-18 19:28:33 +00004438 if (X == Op0)
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00004439 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Chris Lattnera2881962003-02-18 19:28:33 +00004440
Chris Lattner318bf792007-03-18 22:51:34 +00004441
4442 BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1);
4443 if (Op1I) {
4444 Value *A, *B;
4445 if (match(Op1I, m_Or(m_Value(A), m_Value(B)))) {
4446 if (A == Op0) { // B^(B|A) == (A|B)^B
Chris Lattner64daab52006-04-01 08:03:55 +00004447 Op1I->swapOperands();
Chris Lattnercb40a372003-03-10 18:24:17 +00004448 I.swapOperands();
4449 std::swap(Op0, Op1);
Chris Lattner318bf792007-03-18 22:51:34 +00004450 } else if (B == Op0) { // B^(A|B) == (A|B)^B
Chris Lattner64daab52006-04-01 08:03:55 +00004451 I.swapOperands(); // Simplified below.
Chris Lattnercb40a372003-03-10 18:24:17 +00004452 std::swap(Op0, Op1);
Misha Brukmanfd939082005-04-21 23:48:37 +00004453 }
Chris Lattner318bf792007-03-18 22:51:34 +00004454 } else if (match(Op1I, m_Xor(m_Value(A), m_Value(B)))) {
4455 if (Op0 == A) // A^(A^B) == B
4456 return ReplaceInstUsesWith(I, B);
4457 else if (Op0 == B) // A^(B^A) == B
4458 return ReplaceInstUsesWith(I, A);
4459 } else if (match(Op1I, m_And(m_Value(A), m_Value(B))) && Op1I->hasOneUse()){
Chris Lattner6abbdf92007-04-01 05:36:37 +00004460 if (A == Op0) { // A^(A&B) -> A^(B&A)
Chris Lattner64daab52006-04-01 08:03:55 +00004461 Op1I->swapOperands();
Chris Lattner6abbdf92007-04-01 05:36:37 +00004462 std::swap(A, B);
4463 }
Chris Lattner318bf792007-03-18 22:51:34 +00004464 if (B == Op0) { // A^(B&A) -> (B&A)^A
Chris Lattner64daab52006-04-01 08:03:55 +00004465 I.swapOperands(); // Simplified below.
4466 std::swap(Op0, Op1);
4467 }
Chris Lattner26ca7e12004-02-16 03:54:20 +00004468 }
Chris Lattner318bf792007-03-18 22:51:34 +00004469 }
4470
4471 BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0);
4472 if (Op0I) {
4473 Value *A, *B;
4474 if (match(Op0I, m_Or(m_Value(A), m_Value(B))) && Op0I->hasOneUse()) {
4475 if (A == Op1) // (B|A)^B == (A|B)^B
4476 std::swap(A, B);
4477 if (B == Op1) { // (A|B)^B == A & ~B
4478 Instruction *NotB =
4479 InsertNewInstBefore(BinaryOperator::createNot(Op1, "tmp"), I);
4480 return BinaryOperator::createAnd(A, NotB);
Chris Lattnercb40a372003-03-10 18:24:17 +00004481 }
Chris Lattner318bf792007-03-18 22:51:34 +00004482 } else if (match(Op0I, m_Xor(m_Value(A), m_Value(B)))) {
4483 if (Op1 == A) // (A^B)^A == B
4484 return ReplaceInstUsesWith(I, B);
4485 else if (Op1 == B) // (B^A)^A == B
4486 return ReplaceInstUsesWith(I, A);
4487 } else if (match(Op0I, m_And(m_Value(A), m_Value(B))) && Op0I->hasOneUse()){
4488 if (A == Op1) // (A&B)^A -> (B&A)^A
4489 std::swap(A, B);
4490 if (B == Op1 && // (B&A)^A == ~B & A
Chris Lattnerae1ab392006-04-01 22:05:01 +00004491 !isa<ConstantInt>(Op1)) { // Canonical form is (B&C)^C
Chris Lattner318bf792007-03-18 22:51:34 +00004492 Instruction *N =
4493 InsertNewInstBefore(BinaryOperator::createNot(A, "tmp"), I);
Chris Lattner64daab52006-04-01 08:03:55 +00004494 return BinaryOperator::createAnd(N, Op1);
4495 }
Chris Lattnercb40a372003-03-10 18:24:17 +00004496 }
Chris Lattner318bf792007-03-18 22:51:34 +00004497 }
4498
4499 // (X >> Z) ^ (Y >> Z) -> (X^Y) >> Z for all shifts.
4500 if (Op0I && Op1I && Op0I->isShift() &&
4501 Op0I->getOpcode() == Op1I->getOpcode() &&
4502 Op0I->getOperand(1) == Op1I->getOperand(1) &&
4503 (Op1I->hasOneUse() || Op1I->hasOneUse())) {
4504 Instruction *NewOp =
4505 InsertNewInstBefore(BinaryOperator::createXor(Op0I->getOperand(0),
4506 Op1I->getOperand(0),
4507 Op0I->getName()), I);
4508 return BinaryOperator::create(Op1I->getOpcode(), NewOp,
4509 Op1I->getOperand(1));
4510 }
4511
4512 if (Op0I && Op1I) {
4513 Value *A, *B, *C, *D;
4514 // (A & B)^(A | B) -> A ^ B
4515 if (match(Op0I, m_And(m_Value(A), m_Value(B))) &&
4516 match(Op1I, m_Or(m_Value(C), m_Value(D)))) {
4517 if ((A == C && B == D) || (A == D && B == C))
4518 return BinaryOperator::createXor(A, B);
4519 }
4520 // (A | B)^(A & B) -> A ^ B
4521 if (match(Op0I, m_Or(m_Value(A), m_Value(B))) &&
4522 match(Op1I, m_And(m_Value(C), m_Value(D)))) {
4523 if ((A == C && B == D) || (A == D && B == C))
4524 return BinaryOperator::createXor(A, B);
4525 }
4526
4527 // (A & B)^(C & D)
4528 if ((Op0I->hasOneUse() || Op1I->hasOneUse()) &&
4529 match(Op0I, m_And(m_Value(A), m_Value(B))) &&
4530 match(Op1I, m_And(m_Value(C), m_Value(D)))) {
4531 // (X & Y)^(X & Y) -> (Y^Z) & X
4532 Value *X = 0, *Y = 0, *Z = 0;
4533 if (A == C)
4534 X = A, Y = B, Z = D;
4535 else if (A == D)
4536 X = A, Y = B, Z = C;
4537 else if (B == C)
4538 X = B, Y = A, Z = D;
4539 else if (B == D)
4540 X = B, Y = A, Z = C;
4541
4542 if (X) {
4543 Instruction *NewOp =
4544 InsertNewInstBefore(BinaryOperator::createXor(Y, Z, Op0->getName()), I);
4545 return BinaryOperator::createAnd(NewOp, X);
4546 }
4547 }
4548 }
4549
Reid Spencere4d87aa2006-12-23 06:05:41 +00004550 // (icmp1 A, B) ^ (icmp2 A, B) --> (icmp3 A, B)
4551 if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1)))
4552 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
Chris Lattneraa9c1f12003-08-13 20:16:26 +00004553 return R;
4554
Chris Lattner6fc205f2006-05-05 06:39:07 +00004555 // fold (xor (cast A), (cast B)) -> (cast (xor A, B))
Chris Lattner99c65742007-10-24 05:38:08 +00004556 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
Chris Lattner6fc205f2006-05-05 06:39:07 +00004557 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004558 if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind?
4559 const Type *SrcTy = Op0C->getOperand(0)->getType();
Chris Lattner42a75512007-01-15 02:27:26 +00004560 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004561 // Only do this if the casts both really cause code to be generated.
Reid Spencere4d87aa2006-12-23 06:05:41 +00004562 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
4563 I.getType(), TD) &&
4564 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
4565 I.getType(), TD)) {
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004566 Instruction *NewOp = BinaryOperator::createXor(Op0C->getOperand(0),
4567 Op1C->getOperand(0),
4568 I.getName());
4569 InsertNewInstBefore(NewOp, I);
4570 return CastInst::create(Op0C->getOpcode(), NewOp, I.getType());
4571 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00004572 }
Chris Lattner99c65742007-10-24 05:38:08 +00004573 }
Chris Lattner7e708292002-06-25 16:13:24 +00004574 return Changed ? &I : 0;
Chris Lattner3f5b8772002-05-06 16:14:14 +00004575}
4576
Chris Lattnera96879a2004-09-29 17:40:11 +00004577/// AddWithOverflow - Compute Result = In1+In2, returning true if the result
4578/// overflowed for this type.
4579static bool AddWithOverflow(ConstantInt *&Result, ConstantInt *In1,
Reid Spencere4e40032007-03-21 23:19:50 +00004580 ConstantInt *In2, bool IsSigned = false) {
Zhou Sheng4a1822a2007-04-02 13:45:30 +00004581 Result = cast<ConstantInt>(Add(In1, In2));
Chris Lattnera96879a2004-09-29 17:40:11 +00004582
Reid Spencere4e40032007-03-21 23:19:50 +00004583 if (IsSigned)
4584 if (In2->getValue().isNegative())
4585 return Result->getValue().sgt(In1->getValue());
4586 else
4587 return Result->getValue().slt(In1->getValue());
4588 else
4589 return Result->getValue().ult(In1->getValue());
Chris Lattnera96879a2004-09-29 17:40:11 +00004590}
4591
Chris Lattner574da9b2005-01-13 20:14:25 +00004592/// EmitGEPOffset - Given a getelementptr instruction/constantexpr, emit the
4593/// code necessary to compute the offset from the base pointer (without adding
4594/// in the base pointer). Return the result as a signed integer of intptr size.
4595static Value *EmitGEPOffset(User *GEP, Instruction &I, InstCombiner &IC) {
4596 TargetData &TD = IC.getTargetData();
4597 gep_type_iterator GTI = gep_type_begin(GEP);
Reid Spencere4d87aa2006-12-23 06:05:41 +00004598 const Type *IntPtrTy = TD.getIntPtrType();
4599 Value *Result = Constant::getNullValue(IntPtrTy);
Chris Lattner574da9b2005-01-13 20:14:25 +00004600
4601 // Build a mask for high order bits.
Chris Lattnere62f0212007-04-28 04:52:43 +00004602 unsigned IntPtrWidth = TD.getPointerSize()*8;
4603 uint64_t PtrSizeMask = ~0ULL >> (64-IntPtrWidth);
Chris Lattner574da9b2005-01-13 20:14:25 +00004604
Chris Lattner574da9b2005-01-13 20:14:25 +00004605 for (unsigned i = 1, e = GEP->getNumOperands(); i != e; ++i, ++GTI) {
4606 Value *Op = GEP->getOperand(i);
Duncan Sands514ab342007-11-01 20:53:16 +00004607 uint64_t Size = TD.getABITypeSize(GTI.getIndexedType()) & PtrSizeMask;
Chris Lattnere62f0212007-04-28 04:52:43 +00004608 if (ConstantInt *OpC = dyn_cast<ConstantInt>(Op)) {
4609 if (OpC->isZero()) continue;
4610
4611 // Handle a struct index, which adds its field offset to the pointer.
4612 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
4613 Size = TD.getStructLayout(STy)->getElementOffset(OpC->getZExtValue());
4614
4615 if (ConstantInt *RC = dyn_cast<ConstantInt>(Result))
4616 Result = ConstantInt::get(RC->getValue() + APInt(IntPtrWidth, Size));
Chris Lattner9bc14642007-04-28 00:57:34 +00004617 else
Chris Lattnere62f0212007-04-28 04:52:43 +00004618 Result = IC.InsertNewInstBefore(
4619 BinaryOperator::createAdd(Result,
4620 ConstantInt::get(IntPtrTy, Size),
4621 GEP->getName()+".offs"), I);
4622 continue;
Chris Lattner9bc14642007-04-28 00:57:34 +00004623 }
Chris Lattnere62f0212007-04-28 04:52:43 +00004624
4625 Constant *Scale = ConstantInt::get(IntPtrTy, Size);
4626 Constant *OC = ConstantExpr::getIntegerCast(OpC, IntPtrTy, true /*SExt*/);
4627 Scale = ConstantExpr::getMul(OC, Scale);
4628 if (Constant *RC = dyn_cast<Constant>(Result))
4629 Result = ConstantExpr::getAdd(RC, Scale);
4630 else {
4631 // Emit an add instruction.
4632 Result = IC.InsertNewInstBefore(
4633 BinaryOperator::createAdd(Result, Scale,
4634 GEP->getName()+".offs"), I);
Chris Lattner9bc14642007-04-28 00:57:34 +00004635 }
Chris Lattnere62f0212007-04-28 04:52:43 +00004636 continue;
Chris Lattner574da9b2005-01-13 20:14:25 +00004637 }
Chris Lattnere62f0212007-04-28 04:52:43 +00004638 // Convert to correct type.
4639 if (Op->getType() != IntPtrTy) {
4640 if (Constant *OpC = dyn_cast<Constant>(Op))
4641 Op = ConstantExpr::getSExt(OpC, IntPtrTy);
4642 else
4643 Op = IC.InsertNewInstBefore(new SExtInst(Op, IntPtrTy,
4644 Op->getName()+".c"), I);
4645 }
4646 if (Size != 1) {
4647 Constant *Scale = ConstantInt::get(IntPtrTy, Size);
4648 if (Constant *OpC = dyn_cast<Constant>(Op))
4649 Op = ConstantExpr::getMul(OpC, Scale);
4650 else // We'll let instcombine(mul) convert this to a shl if possible.
4651 Op = IC.InsertNewInstBefore(BinaryOperator::createMul(Op, Scale,
4652 GEP->getName()+".idx"), I);
4653 }
4654
4655 // Emit an add instruction.
4656 if (isa<Constant>(Op) && isa<Constant>(Result))
4657 Result = ConstantExpr::getAdd(cast<Constant>(Op),
4658 cast<Constant>(Result));
4659 else
4660 Result = IC.InsertNewInstBefore(BinaryOperator::createAdd(Op, Result,
4661 GEP->getName()+".offs"), I);
Chris Lattner574da9b2005-01-13 20:14:25 +00004662 }
4663 return Result;
4664}
4665
Reid Spencere4d87aa2006-12-23 06:05:41 +00004666/// FoldGEPICmp - Fold comparisons between a GEP instruction and something
Chris Lattner574da9b2005-01-13 20:14:25 +00004667/// else. At this point we know that the GEP is on the LHS of the comparison.
Reid Spencere4d87aa2006-12-23 06:05:41 +00004668Instruction *InstCombiner::FoldGEPICmp(User *GEPLHS, Value *RHS,
4669 ICmpInst::Predicate Cond,
4670 Instruction &I) {
Chris Lattner574da9b2005-01-13 20:14:25 +00004671 assert(dyn_castGetElementPtr(GEPLHS) && "LHS is not a getelementptr!");
Chris Lattnere9d782b2005-01-13 22:25:21 +00004672
4673 if (CastInst *CI = dyn_cast<CastInst>(RHS))
4674 if (isa<PointerType>(CI->getOperand(0)->getType()))
4675 RHS = CI->getOperand(0);
4676
Chris Lattner574da9b2005-01-13 20:14:25 +00004677 Value *PtrBase = GEPLHS->getOperand(0);
4678 if (PtrBase == RHS) {
Chris Lattner7c95deb2008-02-05 04:45:32 +00004679 // ((gep Ptr, OFFSET) cmp Ptr) ---> (OFFSET cmp 0).
4680 // This transformation is valid because we know pointers can't overflow.
4681 Value *Offset = EmitGEPOffset(GEPLHS, I, *this);
4682 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), Offset,
4683 Constant::getNullValue(Offset->getType()));
Chris Lattner574da9b2005-01-13 20:14:25 +00004684 } else if (User *GEPRHS = dyn_castGetElementPtr(RHS)) {
Chris Lattnera70b66d2005-04-25 20:17:30 +00004685 // If the base pointers are different, but the indices are the same, just
4686 // compare the base pointer.
4687 if (PtrBase != GEPRHS->getOperand(0)) {
4688 bool IndicesTheSame = GEPLHS->getNumOperands()==GEPRHS->getNumOperands();
Jeff Cohen00b168892005-07-27 06:12:32 +00004689 IndicesTheSame &= GEPLHS->getOperand(0)->getType() ==
Chris Lattner93b94a62005-04-26 14:40:41 +00004690 GEPRHS->getOperand(0)->getType();
Chris Lattnera70b66d2005-04-25 20:17:30 +00004691 if (IndicesTheSame)
4692 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
4693 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
4694 IndicesTheSame = false;
4695 break;
4696 }
4697
4698 // If all indices are the same, just compare the base pointers.
4699 if (IndicesTheSame)
Reid Spencere4d87aa2006-12-23 06:05:41 +00004700 return new ICmpInst(ICmpInst::getSignedPredicate(Cond),
4701 GEPLHS->getOperand(0), GEPRHS->getOperand(0));
Chris Lattnera70b66d2005-04-25 20:17:30 +00004702
4703 // Otherwise, the base pointers are different and the indices are
4704 // different, bail out.
Chris Lattner574da9b2005-01-13 20:14:25 +00004705 return 0;
Chris Lattnera70b66d2005-04-25 20:17:30 +00004706 }
Chris Lattner574da9b2005-01-13 20:14:25 +00004707
Chris Lattnere9d782b2005-01-13 22:25:21 +00004708 // If one of the GEPs has all zero indices, recurse.
4709 bool AllZeros = true;
4710 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
4711 if (!isa<Constant>(GEPLHS->getOperand(i)) ||
4712 !cast<Constant>(GEPLHS->getOperand(i))->isNullValue()) {
4713 AllZeros = false;
4714 break;
4715 }
4716 if (AllZeros)
Reid Spencere4d87aa2006-12-23 06:05:41 +00004717 return FoldGEPICmp(GEPRHS, GEPLHS->getOperand(0),
4718 ICmpInst::getSwappedPredicate(Cond), I);
Chris Lattner4401c9c2005-01-14 00:20:05 +00004719
4720 // If the other GEP has all zero indices, recurse.
Chris Lattnere9d782b2005-01-13 22:25:21 +00004721 AllZeros = true;
4722 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
4723 if (!isa<Constant>(GEPRHS->getOperand(i)) ||
4724 !cast<Constant>(GEPRHS->getOperand(i))->isNullValue()) {
4725 AllZeros = false;
4726 break;
4727 }
4728 if (AllZeros)
Reid Spencere4d87aa2006-12-23 06:05:41 +00004729 return FoldGEPICmp(GEPLHS, GEPRHS->getOperand(0), Cond, I);
Chris Lattnere9d782b2005-01-13 22:25:21 +00004730
Chris Lattner4401c9c2005-01-14 00:20:05 +00004731 if (GEPLHS->getNumOperands() == GEPRHS->getNumOperands()) {
4732 // If the GEPs only differ by one index, compare it.
4733 unsigned NumDifferences = 0; // Keep track of # differences.
4734 unsigned DiffOperand = 0; // The operand that differs.
4735 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
4736 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
Chris Lattner484d3cf2005-04-24 06:59:08 +00004737 if (GEPLHS->getOperand(i)->getType()->getPrimitiveSizeInBits() !=
4738 GEPRHS->getOperand(i)->getType()->getPrimitiveSizeInBits()) {
Chris Lattner45f57b82005-01-21 23:06:49 +00004739 // Irreconcilable differences.
Chris Lattner4401c9c2005-01-14 00:20:05 +00004740 NumDifferences = 2;
4741 break;
4742 } else {
4743 if (NumDifferences++) break;
4744 DiffOperand = i;
4745 }
4746 }
4747
4748 if (NumDifferences == 0) // SAME GEP?
4749 return ReplaceInstUsesWith(I, // No comparison is needed here.
Nick Lewycky455e1762007-09-06 02:40:25 +00004750 ConstantInt::get(Type::Int1Ty,
4751 isTrueWhenEqual(Cond)));
4752
Chris Lattner4401c9c2005-01-14 00:20:05 +00004753 else if (NumDifferences == 1) {
Chris Lattner45f57b82005-01-21 23:06:49 +00004754 Value *LHSV = GEPLHS->getOperand(DiffOperand);
4755 Value *RHSV = GEPRHS->getOperand(DiffOperand);
Reid Spencere4d87aa2006-12-23 06:05:41 +00004756 // Make sure we do a signed comparison here.
4757 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), LHSV, RHSV);
Chris Lattner4401c9c2005-01-14 00:20:05 +00004758 }
4759 }
4760
Reid Spencere4d87aa2006-12-23 06:05:41 +00004761 // Only lower this if the icmp is the only user of the GEP or if we expect
Chris Lattner574da9b2005-01-13 20:14:25 +00004762 // the result to fold to a constant!
4763 if ((isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) &&
4764 (isa<ConstantExpr>(GEPRHS) || GEPRHS->hasOneUse())) {
4765 // ((gep Ptr, OFFSET1) cmp (gep Ptr, OFFSET2) ---> (OFFSET1 cmp OFFSET2)
4766 Value *L = EmitGEPOffset(GEPLHS, I, *this);
4767 Value *R = EmitGEPOffset(GEPRHS, I, *this);
Reid Spencere4d87aa2006-12-23 06:05:41 +00004768 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), L, R);
Chris Lattner574da9b2005-01-13 20:14:25 +00004769 }
4770 }
4771 return 0;
4772}
4773
Reid Spencere4d87aa2006-12-23 06:05:41 +00004774Instruction *InstCombiner::visitFCmpInst(FCmpInst &I) {
4775 bool Changed = SimplifyCompare(I);
Chris Lattner8b170942002-08-09 23:47:40 +00004776 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00004777
Chris Lattner58e97462007-01-14 19:42:17 +00004778 // Fold trivial predicates.
4779 if (I.getPredicate() == FCmpInst::FCMP_FALSE)
4780 return ReplaceInstUsesWith(I, Constant::getNullValue(Type::Int1Ty));
4781 if (I.getPredicate() == FCmpInst::FCMP_TRUE)
4782 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 1));
4783
4784 // Simplify 'fcmp pred X, X'
4785 if (Op0 == Op1) {
4786 switch (I.getPredicate()) {
4787 default: assert(0 && "Unknown predicate!");
4788 case FCmpInst::FCMP_UEQ: // True if unordered or equal
4789 case FCmpInst::FCMP_UGE: // True if unordered, greater than, or equal
4790 case FCmpInst::FCMP_ULE: // True if unordered, less than, or equal
4791 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 1));
4792 case FCmpInst::FCMP_OGT: // True if ordered and greater than
4793 case FCmpInst::FCMP_OLT: // True if ordered and less than
4794 case FCmpInst::FCMP_ONE: // True if ordered and operands are unequal
4795 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 0));
4796
4797 case FCmpInst::FCMP_UNO: // True if unordered: isnan(X) | isnan(Y)
4798 case FCmpInst::FCMP_ULT: // True if unordered or less than
4799 case FCmpInst::FCMP_UGT: // True if unordered or greater than
4800 case FCmpInst::FCMP_UNE: // True if unordered or not equal
4801 // Canonicalize these to be 'fcmp uno %X, 0.0'.
4802 I.setPredicate(FCmpInst::FCMP_UNO);
4803 I.setOperand(1, Constant::getNullValue(Op0->getType()));
4804 return &I;
4805
4806 case FCmpInst::FCMP_ORD: // True if ordered (no nans)
4807 case FCmpInst::FCMP_OEQ: // True if ordered and equal
4808 case FCmpInst::FCMP_OGE: // True if ordered and greater than or equal
4809 case FCmpInst::FCMP_OLE: // True if ordered and less than or equal
4810 // Canonicalize these to be 'fcmp ord %X, 0.0'.
4811 I.setPredicate(FCmpInst::FCMP_ORD);
4812 I.setOperand(1, Constant::getNullValue(Op0->getType()));
4813 return &I;
4814 }
4815 }
4816
Reid Spencere4d87aa2006-12-23 06:05:41 +00004817 if (isa<UndefValue>(Op1)) // fcmp pred X, undef -> undef
Reid Spencer4fe16d62007-01-11 18:21:29 +00004818 return ReplaceInstUsesWith(I, UndefValue::get(Type::Int1Ty));
Chris Lattnere87597f2004-10-16 18:11:37 +00004819
Reid Spencere4d87aa2006-12-23 06:05:41 +00004820 // Handle fcmp with constant RHS
4821 if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
4822 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
4823 switch (LHSI->getOpcode()) {
4824 case Instruction::PHI:
4825 if (Instruction *NV = FoldOpIntoPhi(I))
4826 return NV;
4827 break;
4828 case Instruction::Select:
4829 // If either operand of the select is a constant, we can fold the
4830 // comparison into the select arms, which will cause one to be
4831 // constant folded and the select turned into a bitwise or.
4832 Value *Op1 = 0, *Op2 = 0;
4833 if (LHSI->hasOneUse()) {
4834 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
4835 // Fold the known value into the constant operand.
4836 Op1 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
4837 // Insert a new FCmp of the other select operand.
4838 Op2 = InsertNewInstBefore(new FCmpInst(I.getPredicate(),
4839 LHSI->getOperand(2), RHSC,
4840 I.getName()), I);
4841 } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
4842 // Fold the known value into the constant operand.
4843 Op2 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
4844 // Insert a new FCmp of the other select operand.
4845 Op1 = InsertNewInstBefore(new FCmpInst(I.getPredicate(),
4846 LHSI->getOperand(1), RHSC,
4847 I.getName()), I);
4848 }
4849 }
4850
4851 if (Op1)
4852 return new SelectInst(LHSI->getOperand(0), Op1, Op2);
4853 break;
4854 }
4855 }
4856
4857 return Changed ? &I : 0;
4858}
4859
4860Instruction *InstCombiner::visitICmpInst(ICmpInst &I) {
4861 bool Changed = SimplifyCompare(I);
4862 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
4863 const Type *Ty = Op0->getType();
4864
4865 // icmp X, X
4866 if (Op0 == Op1)
Reid Spencer579dca12007-01-12 04:24:46 +00004867 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty,
4868 isTrueWhenEqual(I)));
Reid Spencere4d87aa2006-12-23 06:05:41 +00004869
4870 if (isa<UndefValue>(Op1)) // X icmp undef -> undef
Reid Spencer4fe16d62007-01-11 18:21:29 +00004871 return ReplaceInstUsesWith(I, UndefValue::get(Type::Int1Ty));
Christopher Lamb7a0678c2007-12-18 21:32:20 +00004872
Reid Spencere4d87aa2006-12-23 06:05:41 +00004873 // icmp <global/alloca*/null>, <global/alloca*/null> - Global/Stack value
Chris Lattner711b3402004-11-14 07:33:16 +00004874 // addresses never equal each other! We already know that Op0 != Op1.
Misha Brukmanfd939082005-04-21 23:48:37 +00004875 if ((isa<GlobalValue>(Op0) || isa<AllocaInst>(Op0) ||
4876 isa<ConstantPointerNull>(Op0)) &&
4877 (isa<GlobalValue>(Op1) || isa<AllocaInst>(Op1) ||
Chris Lattner711b3402004-11-14 07:33:16 +00004878 isa<ConstantPointerNull>(Op1)))
Reid Spencer579dca12007-01-12 04:24:46 +00004879 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty,
4880 !isTrueWhenEqual(I)));
Chris Lattner8b170942002-08-09 23:47:40 +00004881
Reid Spencere4d87aa2006-12-23 06:05:41 +00004882 // icmp's with boolean values can always be turned into bitwise operations
Reid Spencer4fe16d62007-01-11 18:21:29 +00004883 if (Ty == Type::Int1Ty) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00004884 switch (I.getPredicate()) {
4885 default: assert(0 && "Invalid icmp instruction!");
4886 case ICmpInst::ICMP_EQ: { // icmp eq bool %A, %B -> ~(A^B)
Chris Lattner48595f12004-06-10 02:07:29 +00004887 Instruction *Xor = BinaryOperator::createXor(Op0, Op1, I.getName()+"tmp");
Chris Lattner8b170942002-08-09 23:47:40 +00004888 InsertNewInstBefore(Xor, I);
Chris Lattnerde90b762003-11-03 04:25:02 +00004889 return BinaryOperator::createNot(Xor);
Chris Lattner8b170942002-08-09 23:47:40 +00004890 }
Reid Spencere4d87aa2006-12-23 06:05:41 +00004891 case ICmpInst::ICMP_NE: // icmp eq bool %A, %B -> A^B
Chris Lattner5dbef222004-08-11 00:50:51 +00004892 return BinaryOperator::createXor(Op0, Op1);
Chris Lattner8b170942002-08-09 23:47:40 +00004893
Reid Spencere4d87aa2006-12-23 06:05:41 +00004894 case ICmpInst::ICMP_UGT:
4895 case ICmpInst::ICMP_SGT:
4896 std::swap(Op0, Op1); // Change icmp gt -> icmp lt
Chris Lattner5dbef222004-08-11 00:50:51 +00004897 // FALL THROUGH
Reid Spencere4d87aa2006-12-23 06:05:41 +00004898 case ICmpInst::ICMP_ULT:
4899 case ICmpInst::ICMP_SLT: { // icmp lt bool A, B -> ~X & Y
Chris Lattner5dbef222004-08-11 00:50:51 +00004900 Instruction *Not = BinaryOperator::createNot(Op0, I.getName()+"tmp");
4901 InsertNewInstBefore(Not, I);
4902 return BinaryOperator::createAnd(Not, Op1);
4903 }
Reid Spencere4d87aa2006-12-23 06:05:41 +00004904 case ICmpInst::ICMP_UGE:
4905 case ICmpInst::ICMP_SGE:
4906 std::swap(Op0, Op1); // Change icmp ge -> icmp le
Chris Lattner5dbef222004-08-11 00:50:51 +00004907 // FALL THROUGH
Reid Spencere4d87aa2006-12-23 06:05:41 +00004908 case ICmpInst::ICMP_ULE:
4909 case ICmpInst::ICMP_SLE: { // icmp le bool %A, %B -> ~A | B
Chris Lattner5dbef222004-08-11 00:50:51 +00004910 Instruction *Not = BinaryOperator::createNot(Op0, I.getName()+"tmp");
4911 InsertNewInstBefore(Not, I);
4912 return BinaryOperator::createOr(Not, Op1);
4913 }
4914 }
Chris Lattner8b170942002-08-09 23:47:40 +00004915 }
4916
Chris Lattner2be51ae2004-06-09 04:24:29 +00004917 // See if we are doing a comparison between a constant and an instruction that
4918 // can be folded into the comparison.
Chris Lattner8b170942002-08-09 23:47:40 +00004919 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Christopher Lamb103e1a32007-12-20 07:21:11 +00004920 Value *A, *B;
4921
Chris Lattnerb6566012008-01-05 01:18:20 +00004922 // (icmp ne/eq (sub A B) 0) -> (icmp ne/eq A, B)
4923 if (I.isEquality() && CI->isNullValue() &&
4924 match(Op0, m_Sub(m_Value(A), m_Value(B)))) {
4925 // (icmp cond A B) if cond is equality
4926 return new ICmpInst(I.getPredicate(), A, B);
Owen Andersonf5783f82007-12-28 07:42:12 +00004927 }
Christopher Lamb103e1a32007-12-20 07:21:11 +00004928
Reid Spencere4d87aa2006-12-23 06:05:41 +00004929 switch (I.getPredicate()) {
4930 default: break;
4931 case ICmpInst::ICMP_ULT: // A <u MIN -> FALSE
4932 if (CI->isMinValue(false))
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004933 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00004934 if (CI->isMaxValue(false)) // A <u MAX -> A != MAX
4935 return new ICmpInst(ICmpInst::ICMP_NE, Op0,Op1);
4936 if (isMinValuePlusOne(CI,false)) // A <u MIN+1 -> A == MIN
4937 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, SubOne(CI));
Chris Lattnerba417832007-04-11 06:12:58 +00004938 // (x <u 2147483648) -> (x >s -1) -> true if sign bit clear
4939 if (CI->isMinValue(true))
4940 return new ICmpInst(ICmpInst::ICMP_SGT, Op0,
4941 ConstantInt::getAllOnesValue(Op0->getType()));
4942
Reid Spencere4d87aa2006-12-23 06:05:41 +00004943 break;
Chris Lattnera96879a2004-09-29 17:40:11 +00004944
Reid Spencere4d87aa2006-12-23 06:05:41 +00004945 case ICmpInst::ICMP_SLT:
4946 if (CI->isMinValue(true)) // A <s MIN -> FALSE
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004947 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00004948 if (CI->isMaxValue(true)) // A <s MAX -> A != MAX
4949 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
4950 if (isMinValuePlusOne(CI,true)) // A <s MIN+1 -> A == MIN
4951 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, SubOne(CI));
4952 break;
4953
4954 case ICmpInst::ICMP_UGT:
4955 if (CI->isMaxValue(false)) // A >u MAX -> FALSE
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004956 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00004957 if (CI->isMinValue(false)) // A >u MIN -> A != MIN
4958 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
4959 if (isMaxValueMinusOne(CI, false)) // A >u MAX-1 -> A == MAX
4960 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, AddOne(CI));
Chris Lattnerba417832007-04-11 06:12:58 +00004961
4962 // (x >u 2147483647) -> (x <s 0) -> true if sign bit set
4963 if (CI->isMaxValue(true))
4964 return new ICmpInst(ICmpInst::ICMP_SLT, Op0,
4965 ConstantInt::getNullValue(Op0->getType()));
Reid Spencere4d87aa2006-12-23 06:05:41 +00004966 break;
4967
4968 case ICmpInst::ICMP_SGT:
4969 if (CI->isMaxValue(true)) // A >s MAX -> FALSE
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004970 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00004971 if (CI->isMinValue(true)) // A >s MIN -> A != MIN
4972 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
4973 if (isMaxValueMinusOne(CI, true)) // A >s MAX-1 -> A == MAX
4974 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, AddOne(CI));
4975 break;
4976
4977 case ICmpInst::ICMP_ULE:
4978 if (CI->isMaxValue(false)) // A <=u MAX -> TRUE
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004979 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencere4d87aa2006-12-23 06:05:41 +00004980 if (CI->isMinValue(false)) // A <=u MIN -> A == MIN
4981 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
4982 if (isMaxValueMinusOne(CI,false)) // A <=u MAX-1 -> A != MAX
4983 return new ICmpInst(ICmpInst::ICMP_NE, Op0, AddOne(CI));
4984 break;
Chris Lattnera96879a2004-09-29 17:40:11 +00004985
Reid Spencere4d87aa2006-12-23 06:05:41 +00004986 case ICmpInst::ICMP_SLE:
4987 if (CI->isMaxValue(true)) // A <=s MAX -> TRUE
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004988 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencere4d87aa2006-12-23 06:05:41 +00004989 if (CI->isMinValue(true)) // A <=s MIN -> A == MIN
4990 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
4991 if (isMaxValueMinusOne(CI,true)) // A <=s MAX-1 -> A != MAX
4992 return new ICmpInst(ICmpInst::ICMP_NE, Op0, AddOne(CI));
4993 break;
Chris Lattnera96879a2004-09-29 17:40:11 +00004994
Reid Spencere4d87aa2006-12-23 06:05:41 +00004995 case ICmpInst::ICMP_UGE:
4996 if (CI->isMinValue(false)) // A >=u MIN -> TRUE
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004997 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencere4d87aa2006-12-23 06:05:41 +00004998 if (CI->isMaxValue(false)) // A >=u MAX -> A == MAX
4999 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
5000 if (isMinValuePlusOne(CI,false)) // A >=u MIN-1 -> A != MIN
5001 return new ICmpInst(ICmpInst::ICMP_NE, Op0, SubOne(CI));
5002 break;
5003
5004 case ICmpInst::ICMP_SGE:
5005 if (CI->isMinValue(true)) // A >=s MIN -> TRUE
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005006 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencere4d87aa2006-12-23 06:05:41 +00005007 if (CI->isMaxValue(true)) // A >=s MAX -> A == MAX
5008 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
5009 if (isMinValuePlusOne(CI,true)) // A >=s MIN-1 -> A != MIN
5010 return new ICmpInst(ICmpInst::ICMP_NE, Op0, SubOne(CI));
5011 break;
Chris Lattnera96879a2004-09-29 17:40:11 +00005012 }
5013
Reid Spencere4d87aa2006-12-23 06:05:41 +00005014 // If we still have a icmp le or icmp ge instruction, turn it into the
5015 // appropriate icmp lt or icmp gt instruction. Since the border cases have
Chris Lattnera96879a2004-09-29 17:40:11 +00005016 // already been handled above, this requires little checking.
5017 //
Reid Spencer2149a9d2007-03-25 19:55:33 +00005018 switch (I.getPredicate()) {
Chris Lattner4241e4d2007-07-15 20:54:51 +00005019 default: break;
5020 case ICmpInst::ICMP_ULE:
5021 return new ICmpInst(ICmpInst::ICMP_ULT, Op0, AddOne(CI));
5022 case ICmpInst::ICMP_SLE:
5023 return new ICmpInst(ICmpInst::ICMP_SLT, Op0, AddOne(CI));
5024 case ICmpInst::ICMP_UGE:
5025 return new ICmpInst( ICmpInst::ICMP_UGT, Op0, SubOne(CI));
5026 case ICmpInst::ICMP_SGE:
5027 return new ICmpInst(ICmpInst::ICMP_SGT, Op0, SubOne(CI));
Reid Spencer2149a9d2007-03-25 19:55:33 +00005028 }
Chris Lattnerbf5d8a82006-02-12 02:07:56 +00005029
5030 // See if we can fold the comparison based on bits known to be zero or one
Chris Lattner4241e4d2007-07-15 20:54:51 +00005031 // in the input. If this comparison is a normal comparison, it demands all
5032 // bits, if it is a sign bit comparison, it only demands the sign bit.
5033
5034 bool UnusedBit;
5035 bool isSignBit = isSignBitCheck(I.getPredicate(), CI, UnusedBit);
5036
Reid Spencer0460fb32007-03-22 20:36:03 +00005037 uint32_t BitWidth = cast<IntegerType>(Ty)->getBitWidth();
5038 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
Chris Lattner4241e4d2007-07-15 20:54:51 +00005039 if (SimplifyDemandedBits(Op0,
5040 isSignBit ? APInt::getSignBit(BitWidth)
5041 : APInt::getAllOnesValue(BitWidth),
Chris Lattnerbf5d8a82006-02-12 02:07:56 +00005042 KnownZero, KnownOne, 0))
5043 return &I;
5044
5045 // Given the known and unknown bits, compute a range that the LHS could be
5046 // in.
Reid Spencer0460fb32007-03-22 20:36:03 +00005047 if ((KnownOne | KnownZero) != 0) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00005048 // Compute the Min, Max and RHS values based on the known bits. For the
5049 // EQ and NE we use unsigned values.
Zhou Sheng3a507fd2007-04-01 17:13:37 +00005050 APInt Min(BitWidth, 0), Max(BitWidth, 0);
5051 const APInt& RHSVal = CI->getValue();
Reid Spencere4d87aa2006-12-23 06:05:41 +00005052 if (ICmpInst::isSignedPredicate(I.getPredicate())) {
Reid Spencer0460fb32007-03-22 20:36:03 +00005053 ComputeSignedMinMaxValuesFromKnownBits(Ty, KnownZero, KnownOne, Min,
5054 Max);
Reid Spencere4d87aa2006-12-23 06:05:41 +00005055 } else {
Reid Spencer0460fb32007-03-22 20:36:03 +00005056 ComputeUnsignedMinMaxValuesFromKnownBits(Ty, KnownZero, KnownOne, Min,
5057 Max);
Reid Spencere4d87aa2006-12-23 06:05:41 +00005058 }
5059 switch (I.getPredicate()) { // LE/GE have been folded already.
5060 default: assert(0 && "Unknown icmp opcode!");
5061 case ICmpInst::ICMP_EQ:
Reid Spencer0460fb32007-03-22 20:36:03 +00005062 if (Max.ult(RHSVal) || Min.ugt(RHSVal))
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005063 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00005064 break;
5065 case ICmpInst::ICMP_NE:
Reid Spencer0460fb32007-03-22 20:36:03 +00005066 if (Max.ult(RHSVal) || Min.ugt(RHSVal))
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005067 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencere4d87aa2006-12-23 06:05:41 +00005068 break;
5069 case ICmpInst::ICMP_ULT:
Reid Spencer0460fb32007-03-22 20:36:03 +00005070 if (Max.ult(RHSVal))
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005071 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Chris Lattner81973ef2007-04-09 23:52:13 +00005072 if (Min.uge(RHSVal))
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005073 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00005074 break;
5075 case ICmpInst::ICMP_UGT:
Reid Spencer0460fb32007-03-22 20:36:03 +00005076 if (Min.ugt(RHSVal))
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005077 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Chris Lattner81973ef2007-04-09 23:52:13 +00005078 if (Max.ule(RHSVal))
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005079 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00005080 break;
5081 case ICmpInst::ICMP_SLT:
Reid Spencer0460fb32007-03-22 20:36:03 +00005082 if (Max.slt(RHSVal))
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005083 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Reid Spencer0460fb32007-03-22 20:36:03 +00005084 if (Min.sgt(RHSVal))
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005085 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00005086 break;
5087 case ICmpInst::ICMP_SGT:
Reid Spencer0460fb32007-03-22 20:36:03 +00005088 if (Min.sgt(RHSVal))
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005089 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Chris Lattner81973ef2007-04-09 23:52:13 +00005090 if (Max.sle(RHSVal))
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005091 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00005092 break;
Chris Lattnerbf5d8a82006-02-12 02:07:56 +00005093 }
5094 }
5095
Reid Spencere4d87aa2006-12-23 06:05:41 +00005096 // Since the RHS is a ConstantInt (CI), if the left hand side is an
Reid Spencer1628cec2006-10-26 06:15:43 +00005097 // instruction, see if that instruction also has constants so that the
Reid Spencere4d87aa2006-12-23 06:05:41 +00005098 // instruction can be folded into the icmp
Chris Lattner3c6a0d42004-05-25 06:32:08 +00005099 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
Chris Lattner01deb9d2007-04-03 17:43:25 +00005100 if (Instruction *Res = visitICmpInstWithInstAndIntCst(I, LHSI, CI))
5101 return Res;
Chris Lattner3f5b8772002-05-06 16:14:14 +00005102 }
5103
Chris Lattner01deb9d2007-04-03 17:43:25 +00005104 // Handle icmp with constant (but not simple integer constant) RHS
Chris Lattner6970b662005-04-23 15:31:55 +00005105 if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
5106 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
5107 switch (LHSI->getOpcode()) {
Chris Lattner9fb25db2005-05-01 04:42:15 +00005108 case Instruction::GetElementPtr:
5109 if (RHSC->isNullValue()) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00005110 // icmp pred GEP (P, int 0, int 0, int 0), null -> icmp pred P, null
Chris Lattner9fb25db2005-05-01 04:42:15 +00005111 bool isAllZeros = true;
5112 for (unsigned i = 1, e = LHSI->getNumOperands(); i != e; ++i)
5113 if (!isa<Constant>(LHSI->getOperand(i)) ||
5114 !cast<Constant>(LHSI->getOperand(i))->isNullValue()) {
5115 isAllZeros = false;
5116 break;
5117 }
5118 if (isAllZeros)
Reid Spencere4d87aa2006-12-23 06:05:41 +00005119 return new ICmpInst(I.getPredicate(), LHSI->getOperand(0),
Chris Lattner9fb25db2005-05-01 04:42:15 +00005120 Constant::getNullValue(LHSI->getOperand(0)->getType()));
5121 }
5122 break;
5123
Chris Lattner6970b662005-04-23 15:31:55 +00005124 case Instruction::PHI:
5125 if (Instruction *NV = FoldOpIntoPhi(I))
5126 return NV;
5127 break;
Chris Lattner4802d902007-04-06 18:57:34 +00005128 case Instruction::Select: {
Chris Lattner6970b662005-04-23 15:31:55 +00005129 // 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.
Reid Spencere4d87aa2006-12-23 06:05:41 +00005136 Op1 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
5137 // Insert a new ICmp of the other select operand.
5138 Op2 = InsertNewInstBefore(new ICmpInst(I.getPredicate(),
5139 LHSI->getOperand(2), RHSC,
5140 I.getName()), I);
Chris Lattner6970b662005-04-23 15:31:55 +00005141 } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
5142 // Fold the known value into the constant operand.
Reid Spencere4d87aa2006-12-23 06:05:41 +00005143 Op2 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
5144 // Insert a new ICmp of the other select operand.
5145 Op1 = InsertNewInstBefore(new ICmpInst(I.getPredicate(),
5146 LHSI->getOperand(1), RHSC,
5147 I.getName()), I);
Chris Lattner6970b662005-04-23 15:31:55 +00005148 }
5149 }
Jeff Cohen9d809302005-04-23 21:38:35 +00005150
Chris Lattner6970b662005-04-23 15:31:55 +00005151 if (Op1)
5152 return new SelectInst(LHSI->getOperand(0), Op1, Op2);
5153 break;
5154 }
Chris Lattner4802d902007-04-06 18:57:34 +00005155 case Instruction::Malloc:
5156 // If we have (malloc != null), and if the malloc has a single use, we
5157 // can assume it is successful and remove the malloc.
5158 if (LHSI->hasOneUse() && isa<ConstantPointerNull>(RHSC)) {
5159 AddToWorkList(LHSI);
5160 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty,
5161 !isTrueWhenEqual(I)));
5162 }
5163 break;
5164 }
Chris Lattner6970b662005-04-23 15:31:55 +00005165 }
5166
Reid Spencere4d87aa2006-12-23 06:05:41 +00005167 // If we can optimize a 'icmp GEP, P' or 'icmp P, GEP', do so now.
Chris Lattner574da9b2005-01-13 20:14:25 +00005168 if (User *GEP = dyn_castGetElementPtr(Op0))
Reid Spencere4d87aa2006-12-23 06:05:41 +00005169 if (Instruction *NI = FoldGEPICmp(GEP, Op1, I.getPredicate(), I))
Chris Lattner574da9b2005-01-13 20:14:25 +00005170 return NI;
5171 if (User *GEP = dyn_castGetElementPtr(Op1))
Reid Spencere4d87aa2006-12-23 06:05:41 +00005172 if (Instruction *NI = FoldGEPICmp(GEP, Op0,
5173 ICmpInst::getSwappedPredicate(I.getPredicate()), I))
Chris Lattner574da9b2005-01-13 20:14:25 +00005174 return NI;
5175
Reid Spencere4d87aa2006-12-23 06:05:41 +00005176 // Test to see if the operands of the icmp are casted versions of other
Chris Lattner57d86372007-01-06 01:45:59 +00005177 // values. If the ptr->ptr cast can be stripped off both arguments, we do so
5178 // now.
5179 if (BitCastInst *CI = dyn_cast<BitCastInst>(Op0)) {
5180 if (isa<PointerType>(Op0->getType()) &&
5181 (isa<Constant>(Op1) || isa<BitCastInst>(Op1))) {
Chris Lattnerde90b762003-11-03 04:25:02 +00005182 // We keep moving the cast from the left operand over to the right
5183 // operand, where it can often be eliminated completely.
Chris Lattner57d86372007-01-06 01:45:59 +00005184 Op0 = CI->getOperand(0);
Misha Brukmanfd939082005-04-21 23:48:37 +00005185
Chris Lattner57d86372007-01-06 01:45:59 +00005186 // If operand #1 is a bitcast instruction, it must also be a ptr->ptr cast
5187 // so eliminate it as well.
5188 if (BitCastInst *CI2 = dyn_cast<BitCastInst>(Op1))
5189 Op1 = CI2->getOperand(0);
Misha Brukmanfd939082005-04-21 23:48:37 +00005190
Chris Lattnerde90b762003-11-03 04:25:02 +00005191 // If Op1 is a constant, we can fold the cast into the constant.
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00005192 if (Op0->getType() != Op1->getType()) {
Chris Lattnerde90b762003-11-03 04:25:02 +00005193 if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
Reid Spencerd977d862006-12-12 23:36:14 +00005194 Op1 = ConstantExpr::getBitCast(Op1C, Op0->getType());
Chris Lattnerde90b762003-11-03 04:25:02 +00005195 } else {
Reid Spencere4d87aa2006-12-23 06:05:41 +00005196 // Otherwise, cast the RHS right before the icmp
Chris Lattner6d0339d2008-01-13 22:23:22 +00005197 Op1 = InsertBitCastBefore(Op1, Op0->getType(), I);
Chris Lattnerde90b762003-11-03 04:25:02 +00005198 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00005199 }
Reid Spencere4d87aa2006-12-23 06:05:41 +00005200 return new ICmpInst(I.getPredicate(), Op0, Op1);
Chris Lattnerde90b762003-11-03 04:25:02 +00005201 }
Chris Lattner57d86372007-01-06 01:45:59 +00005202 }
5203
5204 if (isa<CastInst>(Op0)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00005205 // Handle the special case of: icmp (cast bool to X), <cst>
Chris Lattner68708052003-11-03 05:17:03 +00005206 // This comes up when you have code like
5207 // int X = A < B;
5208 // if (X) ...
5209 // For generality, we handle any zero-extension of any operand comparison
Chris Lattner484d3cf2005-04-24 06:59:08 +00005210 // with a constant or another cast from the same type.
5211 if (isa<ConstantInt>(Op1) || isa<CastInst>(Op1))
Reid Spencere4d87aa2006-12-23 06:05:41 +00005212 if (Instruction *R = visitICmpInstWithCastAndCast(I))
Chris Lattner484d3cf2005-04-24 06:59:08 +00005213 return R;
Chris Lattner68708052003-11-03 05:17:03 +00005214 }
Chris Lattner26ab9a92006-02-27 01:44:11 +00005215
Chris Lattner65b72ba2006-09-18 04:22:48 +00005216 if (I.isEquality()) {
Chris Lattner4f0e33d2007-01-05 03:04:57 +00005217 Value *A, *B, *C, *D;
5218 if (match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
5219 if (A == Op1 || B == Op1) { // (A^B) == A -> B == 0
5220 Value *OtherVal = A == Op1 ? B : A;
5221 return new ICmpInst(I.getPredicate(), OtherVal,
5222 Constant::getNullValue(A->getType()));
5223 }
5224
5225 if (match(Op1, m_Xor(m_Value(C), m_Value(D)))) {
5226 // A^c1 == C^c2 --> A == C^(c1^c2)
5227 if (ConstantInt *C1 = dyn_cast<ConstantInt>(B))
5228 if (ConstantInt *C2 = dyn_cast<ConstantInt>(D))
5229 if (Op1->hasOneUse()) {
Zhou Sheng4a1822a2007-04-02 13:45:30 +00005230 Constant *NC = ConstantInt::get(C1->getValue() ^ C2->getValue());
Chris Lattner4f0e33d2007-01-05 03:04:57 +00005231 Instruction *Xor = BinaryOperator::createXor(C, NC, "tmp");
5232 return new ICmpInst(I.getPredicate(), A,
5233 InsertNewInstBefore(Xor, I));
5234 }
5235
5236 // A^B == A^D -> B == D
5237 if (A == C) return new ICmpInst(I.getPredicate(), B, D);
5238 if (A == D) return new ICmpInst(I.getPredicate(), B, C);
5239 if (B == C) return new ICmpInst(I.getPredicate(), A, D);
5240 if (B == D) return new ICmpInst(I.getPredicate(), A, C);
5241 }
5242 }
5243
5244 if (match(Op1, m_Xor(m_Value(A), m_Value(B))) &&
5245 (A == Op0 || B == Op0)) {
Chris Lattner26ab9a92006-02-27 01:44:11 +00005246 // A == (A^B) -> B == 0
5247 Value *OtherVal = A == Op0 ? B : A;
Reid Spencere4d87aa2006-12-23 06:05:41 +00005248 return new ICmpInst(I.getPredicate(), OtherVal,
5249 Constant::getNullValue(A->getType()));
Chris Lattner4f0e33d2007-01-05 03:04:57 +00005250 }
5251 if (match(Op0, m_Sub(m_Value(A), m_Value(B))) && A == Op1) {
Chris Lattner26ab9a92006-02-27 01:44:11 +00005252 // (A-B) == A -> B == 0
Reid Spencere4d87aa2006-12-23 06:05:41 +00005253 return new ICmpInst(I.getPredicate(), B,
5254 Constant::getNullValue(B->getType()));
Chris Lattner4f0e33d2007-01-05 03:04:57 +00005255 }
5256 if (match(Op1, m_Sub(m_Value(A), m_Value(B))) && A == Op0) {
Chris Lattner26ab9a92006-02-27 01:44:11 +00005257 // A == (A-B) -> B == 0
Reid Spencere4d87aa2006-12-23 06:05:41 +00005258 return new ICmpInst(I.getPredicate(), B,
5259 Constant::getNullValue(B->getType()));
Chris Lattner26ab9a92006-02-27 01:44:11 +00005260 }
Chris Lattner9c2328e2006-11-14 06:06:06 +00005261
Chris Lattner9c2328e2006-11-14 06:06:06 +00005262 // (X&Z) == (Y&Z) -> (X^Y) & Z == 0
5263 if (Op0->hasOneUse() && Op1->hasOneUse() &&
5264 match(Op0, m_And(m_Value(A), m_Value(B))) &&
5265 match(Op1, m_And(m_Value(C), m_Value(D)))) {
5266 Value *X = 0, *Y = 0, *Z = 0;
5267
5268 if (A == C) {
5269 X = B; Y = D; Z = A;
5270 } else if (A == D) {
5271 X = B; Y = C; Z = A;
5272 } else if (B == C) {
5273 X = A; Y = D; Z = B;
5274 } else if (B == D) {
5275 X = A; Y = C; Z = B;
5276 }
5277
5278 if (X) { // Build (X^Y) & Z
5279 Op1 = InsertNewInstBefore(BinaryOperator::createXor(X, Y, "tmp"), I);
5280 Op1 = InsertNewInstBefore(BinaryOperator::createAnd(Op1, Z, "tmp"), I);
5281 I.setOperand(0, Op1);
5282 I.setOperand(1, Constant::getNullValue(Op1->getType()));
5283 return &I;
5284 }
5285 }
Chris Lattner26ab9a92006-02-27 01:44:11 +00005286 }
Chris Lattner7e708292002-06-25 16:13:24 +00005287 return Changed ? &I : 0;
Chris Lattner3f5b8772002-05-06 16:14:14 +00005288}
5289
Chris Lattner562ef782007-06-20 23:46:26 +00005290
5291/// FoldICmpDivCst - Fold "icmp pred, ([su]div X, DivRHS), CmpRHS" where DivRHS
5292/// and CmpRHS are both known to be integer constants.
5293Instruction *InstCombiner::FoldICmpDivCst(ICmpInst &ICI, BinaryOperator *DivI,
5294 ConstantInt *DivRHS) {
5295 ConstantInt *CmpRHS = cast<ConstantInt>(ICI.getOperand(1));
5296 const APInt &CmpRHSV = CmpRHS->getValue();
5297
5298 // FIXME: If the operand types don't match the type of the divide
5299 // then don't attempt this transform. The code below doesn't have the
5300 // logic to deal with a signed divide and an unsigned compare (and
5301 // vice versa). This is because (x /s C1) <s C2 produces different
5302 // results than (x /s C1) <u C2 or (x /u C1) <s C2 or even
5303 // (x /u C1) <u C2. Simply casting the operands and result won't
5304 // work. :( The if statement below tests that condition and bails
5305 // if it finds it.
5306 bool DivIsSigned = DivI->getOpcode() == Instruction::SDiv;
5307 if (!ICI.isEquality() && DivIsSigned != ICI.isSignedPredicate())
5308 return 0;
5309 if (DivRHS->isZero())
Chris Lattner1dbfd482007-06-21 18:11:19 +00005310 return 0; // The ProdOV computation fails on divide by zero.
Chris Lattner562ef782007-06-20 23:46:26 +00005311
5312 // Compute Prod = CI * DivRHS. We are essentially solving an equation
5313 // of form X/C1=C2. We solve for X by multiplying C1 (DivRHS) and
5314 // C2 (CI). By solving for X we can turn this into a range check
5315 // instead of computing a divide.
5316 ConstantInt *Prod = Multiply(CmpRHS, DivRHS);
5317
5318 // Determine if the product overflows by seeing if the product is
5319 // not equal to the divide. Make sure we do the same kind of divide
5320 // as in the LHS instruction that we're folding.
5321 bool ProdOV = (DivIsSigned ? ConstantExpr::getSDiv(Prod, DivRHS) :
5322 ConstantExpr::getUDiv(Prod, DivRHS)) != CmpRHS;
5323
5324 // Get the ICmp opcode
Chris Lattner1dbfd482007-06-21 18:11:19 +00005325 ICmpInst::Predicate Pred = ICI.getPredicate();
Chris Lattner562ef782007-06-20 23:46:26 +00005326
Chris Lattner1dbfd482007-06-21 18:11:19 +00005327 // Figure out the interval that is being checked. For example, a comparison
5328 // like "X /u 5 == 0" is really checking that X is in the interval [0, 5).
5329 // Compute this interval based on the constants involved and the signedness of
5330 // the compare/divide. This computes a half-open interval, keeping track of
5331 // whether either value in the interval overflows. After analysis each
5332 // overflow variable is set to 0 if it's corresponding bound variable is valid
5333 // -1 if overflowed off the bottom end, or +1 if overflowed off the top end.
5334 int LoOverflow = 0, HiOverflow = 0;
5335 ConstantInt *LoBound = 0, *HiBound = 0;
5336
5337
Chris Lattner562ef782007-06-20 23:46:26 +00005338 if (!DivIsSigned) { // udiv
Chris Lattner1dbfd482007-06-21 18:11:19 +00005339 // e.g. X/5 op 3 --> [15, 20)
Chris Lattner562ef782007-06-20 23:46:26 +00005340 LoBound = Prod;
Chris Lattner1dbfd482007-06-21 18:11:19 +00005341 HiOverflow = LoOverflow = ProdOV;
5342 if (!HiOverflow)
5343 HiOverflow = AddWithOverflow(HiBound, LoBound, DivRHS, false);
Dan Gohman76491272008-02-13 22:09:18 +00005344 } else if (DivRHS->getValue().isStrictlyPositive()) { // Divisor is > 0.
Chris Lattner562ef782007-06-20 23:46:26 +00005345 if (CmpRHSV == 0) { // (X / pos) op 0
Chris Lattner1dbfd482007-06-21 18:11:19 +00005346 // Can't overflow. e.g. X/2 op 0 --> [-1, 2)
Chris Lattner562ef782007-06-20 23:46:26 +00005347 LoBound = cast<ConstantInt>(ConstantExpr::getNeg(SubOne(DivRHS)));
5348 HiBound = DivRHS;
Dan Gohman76491272008-02-13 22:09:18 +00005349 } else if (CmpRHSV.isStrictlyPositive()) { // (X / pos) op pos
Chris Lattner1dbfd482007-06-21 18:11:19 +00005350 LoBound = Prod; // e.g. X/5 op 3 --> [15, 20)
5351 HiOverflow = LoOverflow = ProdOV;
5352 if (!HiOverflow)
5353 HiOverflow = AddWithOverflow(HiBound, Prod, DivRHS, true);
Chris Lattner562ef782007-06-20 23:46:26 +00005354 } else { // (X / pos) op neg
Chris Lattner1dbfd482007-06-21 18:11:19 +00005355 // e.g. X/5 op -3 --> [-15-4, -15+1) --> [-19, -14)
Chris Lattner562ef782007-06-20 23:46:26 +00005356 Constant *DivRHSH = ConstantExpr::getNeg(SubOne(DivRHS));
5357 LoOverflow = AddWithOverflow(LoBound, Prod,
Chris Lattner1dbfd482007-06-21 18:11:19 +00005358 cast<ConstantInt>(DivRHSH), true) ? -1 : 0;
Chris Lattner562ef782007-06-20 23:46:26 +00005359 HiBound = AddOne(Prod);
Chris Lattner1dbfd482007-06-21 18:11:19 +00005360 HiOverflow = ProdOV ? -1 : 0;
Chris Lattner562ef782007-06-20 23:46:26 +00005361 }
Dan Gohman76491272008-02-13 22:09:18 +00005362 } else if (DivRHS->getValue().isNegative()) { // Divisor is < 0.
Chris Lattner562ef782007-06-20 23:46:26 +00005363 if (CmpRHSV == 0) { // (X / neg) op 0
Chris Lattner1dbfd482007-06-21 18:11:19 +00005364 // e.g. X/-5 op 0 --> [-4, 5)
Chris Lattner562ef782007-06-20 23:46:26 +00005365 LoBound = AddOne(DivRHS);
5366 HiBound = cast<ConstantInt>(ConstantExpr::getNeg(DivRHS));
Chris Lattner1dbfd482007-06-21 18:11:19 +00005367 if (HiBound == DivRHS) { // -INTMIN = INTMIN
5368 HiOverflow = 1; // [INTMIN+1, overflow)
5369 HiBound = 0; // e.g. X/INTMIN = 0 --> X > INTMIN
5370 }
Dan Gohman76491272008-02-13 22:09:18 +00005371 } else if (CmpRHSV.isStrictlyPositive()) { // (X / neg) op pos
Chris Lattner1dbfd482007-06-21 18:11:19 +00005372 // e.g. X/-5 op 3 --> [-19, -14)
5373 HiOverflow = LoOverflow = ProdOV ? -1 : 0;
Chris Lattner562ef782007-06-20 23:46:26 +00005374 if (!LoOverflow)
Chris Lattner1dbfd482007-06-21 18:11:19 +00005375 LoOverflow = AddWithOverflow(LoBound, Prod, AddOne(DivRHS), true) ?-1:0;
Chris Lattner562ef782007-06-20 23:46:26 +00005376 HiBound = AddOne(Prod);
5377 } else { // (X / neg) op neg
Chris Lattner1dbfd482007-06-21 18:11:19 +00005378 // e.g. X/-5 op -3 --> [15, 20)
Chris Lattner562ef782007-06-20 23:46:26 +00005379 LoBound = Prod;
Chris Lattner1dbfd482007-06-21 18:11:19 +00005380 LoOverflow = HiOverflow = ProdOV ? 1 : 0;
Chris Lattner562ef782007-06-20 23:46:26 +00005381 HiBound = Subtract(Prod, DivRHS);
5382 }
5383
Chris Lattner1dbfd482007-06-21 18:11:19 +00005384 // Dividing by a negative swaps the condition. LT <-> GT
5385 Pred = ICmpInst::getSwappedPredicate(Pred);
Chris Lattner562ef782007-06-20 23:46:26 +00005386 }
5387
5388 Value *X = DivI->getOperand(0);
Chris Lattner1dbfd482007-06-21 18:11:19 +00005389 switch (Pred) {
Chris Lattner562ef782007-06-20 23:46:26 +00005390 default: assert(0 && "Unhandled icmp opcode!");
5391 case ICmpInst::ICMP_EQ:
5392 if (LoOverflow && HiOverflow)
5393 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
5394 else if (HiOverflow)
Chris Lattner1dbfd482007-06-21 18:11:19 +00005395 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE :
Chris Lattner562ef782007-06-20 23:46:26 +00005396 ICmpInst::ICMP_UGE, X, LoBound);
5397 else if (LoOverflow)
5398 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT :
5399 ICmpInst::ICMP_ULT, X, HiBound);
5400 else
Chris Lattner1dbfd482007-06-21 18:11:19 +00005401 return InsertRangeTest(X, LoBound, HiBound, DivIsSigned, true, ICI);
Chris Lattner562ef782007-06-20 23:46:26 +00005402 case ICmpInst::ICMP_NE:
5403 if (LoOverflow && HiOverflow)
5404 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
5405 else if (HiOverflow)
Chris Lattner1dbfd482007-06-21 18:11:19 +00005406 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT :
Chris Lattner562ef782007-06-20 23:46:26 +00005407 ICmpInst::ICMP_ULT, X, LoBound);
5408 else if (LoOverflow)
5409 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE :
5410 ICmpInst::ICMP_UGE, X, HiBound);
5411 else
Chris Lattner1dbfd482007-06-21 18:11:19 +00005412 return InsertRangeTest(X, LoBound, HiBound, DivIsSigned, false, ICI);
Chris Lattner562ef782007-06-20 23:46:26 +00005413 case ICmpInst::ICMP_ULT:
5414 case ICmpInst::ICMP_SLT:
Chris Lattner1dbfd482007-06-21 18:11:19 +00005415 if (LoOverflow == +1) // Low bound is greater than input range.
5416 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
5417 if (LoOverflow == -1) // Low bound is less than input range.
Chris Lattner562ef782007-06-20 23:46:26 +00005418 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
Chris Lattner1dbfd482007-06-21 18:11:19 +00005419 return new ICmpInst(Pred, X, LoBound);
Chris Lattner562ef782007-06-20 23:46:26 +00005420 case ICmpInst::ICMP_UGT:
5421 case ICmpInst::ICMP_SGT:
Chris Lattner1dbfd482007-06-21 18:11:19 +00005422 if (HiOverflow == +1) // High bound greater than input range.
Chris Lattner562ef782007-06-20 23:46:26 +00005423 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
Chris Lattner1dbfd482007-06-21 18:11:19 +00005424 else if (HiOverflow == -1) // High bound less than input range.
5425 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
5426 if (Pred == ICmpInst::ICMP_UGT)
Chris Lattner562ef782007-06-20 23:46:26 +00005427 return new ICmpInst(ICmpInst::ICMP_UGE, X, HiBound);
5428 else
5429 return new ICmpInst(ICmpInst::ICMP_SGE, X, HiBound);
5430 }
5431}
5432
5433
Chris Lattner01deb9d2007-04-03 17:43:25 +00005434/// visitICmpInstWithInstAndIntCst - Handle "icmp (instr, intcst)".
5435///
5436Instruction *InstCombiner::visitICmpInstWithInstAndIntCst(ICmpInst &ICI,
5437 Instruction *LHSI,
5438 ConstantInt *RHS) {
5439 const APInt &RHSV = RHS->getValue();
5440
5441 switch (LHSI->getOpcode()) {
Duncan Sands0091bf22007-04-04 06:42:45 +00005442 case Instruction::Xor: // (icmp pred (xor X, XorCST), CI)
Chris Lattner01deb9d2007-04-03 17:43:25 +00005443 if (ConstantInt *XorCST = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
5444 // If this is a comparison that tests the signbit (X < 0) or (x > -1),
5445 // fold the xor.
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00005446 if ((ICI.getPredicate() == ICmpInst::ICMP_SLT && RHSV == 0) ||
5447 (ICI.getPredicate() == ICmpInst::ICMP_SGT && RHSV.isAllOnesValue())) {
Chris Lattner01deb9d2007-04-03 17:43:25 +00005448 Value *CompareVal = LHSI->getOperand(0);
5449
5450 // If the sign bit of the XorCST is not set, there is no change to
5451 // the operation, just stop using the Xor.
5452 if (!XorCST->getValue().isNegative()) {
5453 ICI.setOperand(0, CompareVal);
5454 AddToWorkList(LHSI);
5455 return &ICI;
5456 }
5457
5458 // Was the old condition true if the operand is positive?
5459 bool isTrueIfPositive = ICI.getPredicate() == ICmpInst::ICMP_SGT;
5460
5461 // If so, the new one isn't.
5462 isTrueIfPositive ^= true;
5463
5464 if (isTrueIfPositive)
5465 return new ICmpInst(ICmpInst::ICMP_SGT, CompareVal, SubOne(RHS));
5466 else
5467 return new ICmpInst(ICmpInst::ICMP_SLT, CompareVal, AddOne(RHS));
5468 }
5469 }
5470 break;
5471 case Instruction::And: // (icmp pred (and X, AndCST), RHS)
5472 if (LHSI->hasOneUse() && isa<ConstantInt>(LHSI->getOperand(1)) &&
5473 LHSI->getOperand(0)->hasOneUse()) {
5474 ConstantInt *AndCST = cast<ConstantInt>(LHSI->getOperand(1));
5475
5476 // If the LHS is an AND of a truncating cast, we can widen the
5477 // and/compare to be the input width without changing the value
5478 // produced, eliminating a cast.
5479 if (TruncInst *Cast = dyn_cast<TruncInst>(LHSI->getOperand(0))) {
5480 // We can do this transformation if either the AND constant does not
5481 // have its sign bit set or if it is an equality comparison.
5482 // Extending a relational comparison when we're checking the sign
5483 // bit would not work.
5484 if (Cast->hasOneUse() &&
Anton Korobeynikov4aefd6b2008-02-20 12:07:57 +00005485 (ICI.isEquality() ||
5486 (AndCST->getValue().isNonNegative() && RHSV.isNonNegative()))) {
Chris Lattner01deb9d2007-04-03 17:43:25 +00005487 uint32_t BitWidth =
5488 cast<IntegerType>(Cast->getOperand(0)->getType())->getBitWidth();
5489 APInt NewCST = AndCST->getValue();
5490 NewCST.zext(BitWidth);
5491 APInt NewCI = RHSV;
5492 NewCI.zext(BitWidth);
5493 Instruction *NewAnd =
5494 BinaryOperator::createAnd(Cast->getOperand(0),
5495 ConstantInt::get(NewCST),LHSI->getName());
5496 InsertNewInstBefore(NewAnd, ICI);
5497 return new ICmpInst(ICI.getPredicate(), NewAnd,
5498 ConstantInt::get(NewCI));
5499 }
5500 }
5501
5502 // If this is: (X >> C1) & C2 != C3 (where any shift and any compare
5503 // could exist), turn it into (X & (C2 << C1)) != (C3 << C1). This
5504 // happens a LOT in code produced by the C front-end, for bitfield
5505 // access.
5506 BinaryOperator *Shift = dyn_cast<BinaryOperator>(LHSI->getOperand(0));
5507 if (Shift && !Shift->isShift())
5508 Shift = 0;
5509
5510 ConstantInt *ShAmt;
5511 ShAmt = Shift ? dyn_cast<ConstantInt>(Shift->getOperand(1)) : 0;
5512 const Type *Ty = Shift ? Shift->getType() : 0; // Type of the shift.
5513 const Type *AndTy = AndCST->getType(); // Type of the and.
5514
5515 // We can fold this as long as we can't shift unknown bits
5516 // into the mask. This can only happen with signed shift
5517 // rights, as they sign-extend.
5518 if (ShAmt) {
5519 bool CanFold = Shift->isLogicalShift();
5520 if (!CanFold) {
5521 // To test for the bad case of the signed shr, see if any
5522 // of the bits shifted in could be tested after the mask.
5523 uint32_t TyBits = Ty->getPrimitiveSizeInBits();
5524 int ShAmtVal = TyBits - ShAmt->getLimitedValue(TyBits);
5525
5526 uint32_t BitWidth = AndTy->getPrimitiveSizeInBits();
5527 if ((APInt::getHighBitsSet(BitWidth, BitWidth-ShAmtVal) &
5528 AndCST->getValue()) == 0)
5529 CanFold = true;
5530 }
5531
5532 if (CanFold) {
5533 Constant *NewCst;
5534 if (Shift->getOpcode() == Instruction::Shl)
5535 NewCst = ConstantExpr::getLShr(RHS, ShAmt);
5536 else
5537 NewCst = ConstantExpr::getShl(RHS, ShAmt);
5538
5539 // Check to see if we are shifting out any of the bits being
5540 // compared.
5541 if (ConstantExpr::get(Shift->getOpcode(), NewCst, ShAmt) != RHS) {
5542 // If we shifted bits out, the fold is not going to work out.
5543 // As a special case, check to see if this means that the
5544 // result is always true or false now.
5545 if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
5546 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
5547 if (ICI.getPredicate() == ICmpInst::ICMP_NE)
5548 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
5549 } else {
5550 ICI.setOperand(1, NewCst);
5551 Constant *NewAndCST;
5552 if (Shift->getOpcode() == Instruction::Shl)
5553 NewAndCST = ConstantExpr::getLShr(AndCST, ShAmt);
5554 else
5555 NewAndCST = ConstantExpr::getShl(AndCST, ShAmt);
5556 LHSI->setOperand(1, NewAndCST);
5557 LHSI->setOperand(0, Shift->getOperand(0));
5558 AddToWorkList(Shift); // Shift is dead.
5559 AddUsesToWorkList(ICI);
5560 return &ICI;
5561 }
5562 }
5563 }
5564
5565 // Turn ((X >> Y) & C) == 0 into (X & (C << Y)) == 0. The later is
5566 // preferable because it allows the C<<Y expression to be hoisted out
5567 // of a loop if Y is invariant and X is not.
5568 if (Shift && Shift->hasOneUse() && RHSV == 0 &&
5569 ICI.isEquality() && !Shift->isArithmeticShift() &&
5570 isa<Instruction>(Shift->getOperand(0))) {
5571 // Compute C << Y.
5572 Value *NS;
5573 if (Shift->getOpcode() == Instruction::LShr) {
5574 NS = BinaryOperator::createShl(AndCST,
5575 Shift->getOperand(1), "tmp");
5576 } else {
5577 // Insert a logical shift.
5578 NS = BinaryOperator::createLShr(AndCST,
5579 Shift->getOperand(1), "tmp");
5580 }
5581 InsertNewInstBefore(cast<Instruction>(NS), ICI);
5582
5583 // Compute X & (C << Y).
5584 Instruction *NewAnd =
5585 BinaryOperator::createAnd(Shift->getOperand(0), NS, LHSI->getName());
5586 InsertNewInstBefore(NewAnd, ICI);
5587
5588 ICI.setOperand(0, NewAnd);
5589 return &ICI;
5590 }
5591 }
5592 break;
5593
Chris Lattnera0141b92007-07-15 20:42:37 +00005594 case Instruction::Shl: { // (icmp pred (shl X, ShAmt), CI)
5595 ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1));
5596 if (!ShAmt) break;
5597
5598 uint32_t TypeBits = RHSV.getBitWidth();
5599
5600 // Check that the shift amount is in range. If not, don't perform
5601 // undefined shifts. When the shift is visited it will be
5602 // simplified.
5603 if (ShAmt->uge(TypeBits))
5604 break;
5605
5606 if (ICI.isEquality()) {
5607 // If we are comparing against bits always shifted out, the
5608 // comparison cannot succeed.
5609 Constant *Comp =
5610 ConstantExpr::getShl(ConstantExpr::getLShr(RHS, ShAmt), ShAmt);
5611 if (Comp != RHS) {// Comparing against a bit that we know is zero.
5612 bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
5613 Constant *Cst = ConstantInt::get(Type::Int1Ty, IsICMP_NE);
5614 return ReplaceInstUsesWith(ICI, Cst);
5615 }
5616
5617 if (LHSI->hasOneUse()) {
5618 // Otherwise strength reduce the shift into an and.
5619 uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
5620 Constant *Mask =
5621 ConstantInt::get(APInt::getLowBitsSet(TypeBits, TypeBits-ShAmtVal));
Chris Lattner01deb9d2007-04-03 17:43:25 +00005622
Chris Lattnera0141b92007-07-15 20:42:37 +00005623 Instruction *AndI =
5624 BinaryOperator::createAnd(LHSI->getOperand(0),
5625 Mask, LHSI->getName()+".mask");
5626 Value *And = InsertNewInstBefore(AndI, ICI);
5627 return new ICmpInst(ICI.getPredicate(), And,
5628 ConstantInt::get(RHSV.lshr(ShAmtVal)));
Chris Lattner01deb9d2007-04-03 17:43:25 +00005629 }
5630 }
Chris Lattnera0141b92007-07-15 20:42:37 +00005631
5632 // Otherwise, if this is a comparison of the sign bit, simplify to and/test.
5633 bool TrueIfSigned = false;
5634 if (LHSI->hasOneUse() &&
5635 isSignBitCheck(ICI.getPredicate(), RHS, TrueIfSigned)) {
5636 // (X << 31) <s 0 --> (X&1) != 0
5637 Constant *Mask = ConstantInt::get(APInt(TypeBits, 1) <<
5638 (TypeBits-ShAmt->getZExtValue()-1));
5639 Instruction *AndI =
5640 BinaryOperator::createAnd(LHSI->getOperand(0),
5641 Mask, LHSI->getName()+".mask");
5642 Value *And = InsertNewInstBefore(AndI, ICI);
5643
5644 return new ICmpInst(TrueIfSigned ? ICmpInst::ICMP_NE : ICmpInst::ICMP_EQ,
5645 And, Constant::getNullValue(And->getType()));
5646 }
Chris Lattner01deb9d2007-04-03 17:43:25 +00005647 break;
Chris Lattnera0141b92007-07-15 20:42:37 +00005648 }
Chris Lattner01deb9d2007-04-03 17:43:25 +00005649
5650 case Instruction::LShr: // (icmp pred (shr X, ShAmt), CI)
Chris Lattnera0141b92007-07-15 20:42:37 +00005651 case Instruction::AShr: {
5652 ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1));
5653 if (!ShAmt) break;
5654
5655 if (ICI.isEquality()) {
5656 // Check that the shift amount is in range. If not, don't perform
5657 // undefined shifts. When the shift is visited it will be
5658 // simplified.
5659 uint32_t TypeBits = RHSV.getBitWidth();
5660 if (ShAmt->uge(TypeBits))
5661 break;
5662 uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
5663
5664 // If we are comparing against bits always shifted out, the
5665 // comparison cannot succeed.
5666 APInt Comp = RHSV << ShAmtVal;
5667 if (LHSI->getOpcode() == Instruction::LShr)
5668 Comp = Comp.lshr(ShAmtVal);
5669 else
5670 Comp = Comp.ashr(ShAmtVal);
5671
5672 if (Comp != RHSV) { // Comparing against a bit that we know is zero.
5673 bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
5674 Constant *Cst = ConstantInt::get(Type::Int1Ty, IsICMP_NE);
5675 return ReplaceInstUsesWith(ICI, Cst);
5676 }
5677
5678 if (LHSI->hasOneUse() || RHSV == 0) {
5679 // Otherwise strength reduce the shift into an and.
5680 APInt Val(APInt::getHighBitsSet(TypeBits, TypeBits - ShAmtVal));
5681 Constant *Mask = ConstantInt::get(Val);
Chris Lattner01deb9d2007-04-03 17:43:25 +00005682
Chris Lattnera0141b92007-07-15 20:42:37 +00005683 Instruction *AndI =
5684 BinaryOperator::createAnd(LHSI->getOperand(0),
5685 Mask, LHSI->getName()+".mask");
5686 Value *And = InsertNewInstBefore(AndI, ICI);
5687 return new ICmpInst(ICI.getPredicate(), And,
5688 ConstantExpr::getShl(RHS, ShAmt));
Chris Lattner01deb9d2007-04-03 17:43:25 +00005689 }
5690 }
5691 break;
Chris Lattnera0141b92007-07-15 20:42:37 +00005692 }
Chris Lattner01deb9d2007-04-03 17:43:25 +00005693
5694 case Instruction::SDiv:
5695 case Instruction::UDiv:
5696 // Fold: icmp pred ([us]div X, C1), C2 -> range test
5697 // Fold this div into the comparison, producing a range check.
5698 // Determine, based on the divide type, what the range is being
5699 // checked. If there is an overflow on the low or high side, remember
5700 // it, otherwise compute the range [low, hi) bounding the new value.
5701 // See: InsertRangeTest above for the kinds of replacements possible.
Chris Lattner562ef782007-06-20 23:46:26 +00005702 if (ConstantInt *DivRHS = dyn_cast<ConstantInt>(LHSI->getOperand(1)))
5703 if (Instruction *R = FoldICmpDivCst(ICI, cast<BinaryOperator>(LHSI),
5704 DivRHS))
5705 return R;
Chris Lattner01deb9d2007-04-03 17:43:25 +00005706 break;
Nick Lewycky5be29202008-02-03 16:33:09 +00005707
5708 case Instruction::Add:
5709 // Fold: icmp pred (add, X, C1), C2
5710
5711 if (!ICI.isEquality()) {
5712 ConstantInt *LHSC = dyn_cast<ConstantInt>(LHSI->getOperand(1));
5713 if (!LHSC) break;
5714 const APInt &LHSV = LHSC->getValue();
5715
5716 ConstantRange CR = ICI.makeConstantRange(ICI.getPredicate(), RHSV)
5717 .subtract(LHSV);
5718
5719 if (ICI.isSignedPredicate()) {
5720 if (CR.getLower().isSignBit()) {
5721 return new ICmpInst(ICmpInst::ICMP_SLT, LHSI->getOperand(0),
5722 ConstantInt::get(CR.getUpper()));
5723 } else if (CR.getUpper().isSignBit()) {
5724 return new ICmpInst(ICmpInst::ICMP_SGE, LHSI->getOperand(0),
5725 ConstantInt::get(CR.getLower()));
5726 }
5727 } else {
5728 if (CR.getLower().isMinValue()) {
5729 return new ICmpInst(ICmpInst::ICMP_ULT, LHSI->getOperand(0),
5730 ConstantInt::get(CR.getUpper()));
5731 } else if (CR.getUpper().isMinValue()) {
5732 return new ICmpInst(ICmpInst::ICMP_UGE, LHSI->getOperand(0),
5733 ConstantInt::get(CR.getLower()));
5734 }
5735 }
5736 }
5737 break;
Chris Lattner01deb9d2007-04-03 17:43:25 +00005738 }
5739
5740 // Simplify icmp_eq and icmp_ne instructions with integer constant RHS.
5741 if (ICI.isEquality()) {
5742 bool isICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
5743
5744 // If the first operand is (add|sub|and|or|xor|rem) with a constant, and
5745 // the second operand is a constant, simplify a bit.
5746 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(LHSI)) {
5747 switch (BO->getOpcode()) {
5748 case Instruction::SRem:
5749 // If we have a signed (X % (2^c)) == 0, turn it into an unsigned one.
5750 if (RHSV == 0 && isa<ConstantInt>(BO->getOperand(1)) &&BO->hasOneUse()){
5751 const APInt &V = cast<ConstantInt>(BO->getOperand(1))->getValue();
5752 if (V.sgt(APInt(V.getBitWidth(), 1)) && V.isPowerOf2()) {
5753 Instruction *NewRem =
5754 BinaryOperator::createURem(BO->getOperand(0), BO->getOperand(1),
5755 BO->getName());
5756 InsertNewInstBefore(NewRem, ICI);
5757 return new ICmpInst(ICI.getPredicate(), NewRem,
5758 Constant::getNullValue(BO->getType()));
5759 }
5760 }
5761 break;
5762 case Instruction::Add:
5763 // Replace ((add A, B) != C) with (A != C-B) if B & C are constants.
5764 if (ConstantInt *BOp1C = dyn_cast<ConstantInt>(BO->getOperand(1))) {
5765 if (BO->hasOneUse())
5766 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
5767 Subtract(RHS, BOp1C));
5768 } else if (RHSV == 0) {
5769 // Replace ((add A, B) != 0) with (A != -B) if A or B is
5770 // efficiently invertible, or if the add has just this one use.
5771 Value *BOp0 = BO->getOperand(0), *BOp1 = BO->getOperand(1);
5772
5773 if (Value *NegVal = dyn_castNegVal(BOp1))
5774 return new ICmpInst(ICI.getPredicate(), BOp0, NegVal);
5775 else if (Value *NegVal = dyn_castNegVal(BOp0))
5776 return new ICmpInst(ICI.getPredicate(), NegVal, BOp1);
5777 else if (BO->hasOneUse()) {
5778 Instruction *Neg = BinaryOperator::createNeg(BOp1);
5779 InsertNewInstBefore(Neg, ICI);
5780 Neg->takeName(BO);
5781 return new ICmpInst(ICI.getPredicate(), BOp0, Neg);
5782 }
5783 }
5784 break;
5785 case Instruction::Xor:
5786 // For the xor case, we can xor two constants together, eliminating
5787 // the explicit xor.
5788 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1)))
5789 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
5790 ConstantExpr::getXor(RHS, BOC));
5791
5792 // FALLTHROUGH
5793 case Instruction::Sub:
5794 // Replace (([sub|xor] A, B) != 0) with (A != B)
5795 if (RHSV == 0)
5796 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
5797 BO->getOperand(1));
5798 break;
5799
5800 case Instruction::Or:
5801 // If bits are being or'd in that are not present in the constant we
5802 // are comparing against, then the comparison could never succeed!
5803 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1))) {
5804 Constant *NotCI = ConstantExpr::getNot(RHS);
5805 if (!ConstantExpr::getAnd(BOC, NotCI)->isNullValue())
5806 return ReplaceInstUsesWith(ICI, ConstantInt::get(Type::Int1Ty,
5807 isICMP_NE));
5808 }
5809 break;
5810
5811 case Instruction::And:
5812 if (ConstantInt *BOC = dyn_cast<ConstantInt>(BO->getOperand(1))) {
5813 // If bits are being compared against that are and'd out, then the
5814 // comparison can never succeed!
5815 if ((RHSV & ~BOC->getValue()) != 0)
5816 return ReplaceInstUsesWith(ICI, ConstantInt::get(Type::Int1Ty,
5817 isICMP_NE));
5818
5819 // If we have ((X & C) == C), turn it into ((X & C) != 0).
5820 if (RHS == BOC && RHSV.isPowerOf2())
5821 return new ICmpInst(isICMP_NE ? ICmpInst::ICMP_EQ :
5822 ICmpInst::ICMP_NE, LHSI,
5823 Constant::getNullValue(RHS->getType()));
5824
5825 // Replace (and X, (1 << size(X)-1) != 0) with x s< 0
5826 if (isSignBit(BOC)) {
5827 Value *X = BO->getOperand(0);
5828 Constant *Zero = Constant::getNullValue(X->getType());
5829 ICmpInst::Predicate pred = isICMP_NE ?
5830 ICmpInst::ICMP_SLT : ICmpInst::ICMP_SGE;
5831 return new ICmpInst(pred, X, Zero);
5832 }
5833
5834 // ((X & ~7) == 0) --> X < 8
5835 if (RHSV == 0 && isHighOnes(BOC)) {
5836 Value *X = BO->getOperand(0);
5837 Constant *NegX = ConstantExpr::getNeg(BOC);
5838 ICmpInst::Predicate pred = isICMP_NE ?
5839 ICmpInst::ICMP_UGE : ICmpInst::ICMP_ULT;
5840 return new ICmpInst(pred, X, NegX);
5841 }
5842 }
5843 default: break;
5844 }
5845 } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(LHSI)) {
5846 // Handle icmp {eq|ne} <intrinsic>, intcst.
5847 if (II->getIntrinsicID() == Intrinsic::bswap) {
5848 AddToWorkList(II);
5849 ICI.setOperand(0, II->getOperand(1));
5850 ICI.setOperand(1, ConstantInt::get(RHSV.byteSwap()));
5851 return &ICI;
5852 }
5853 }
5854 } else { // Not a ICMP_EQ/ICMP_NE
Chris Lattnere34e9a22007-04-14 23:32:02 +00005855 // If the LHS is a cast from an integral value of the same size,
5856 // then since we know the RHS is a constant, try to simlify.
Chris Lattner01deb9d2007-04-03 17:43:25 +00005857 if (CastInst *Cast = dyn_cast<CastInst>(LHSI)) {
5858 Value *CastOp = Cast->getOperand(0);
5859 const Type *SrcTy = CastOp->getType();
5860 uint32_t SrcTySize = SrcTy->getPrimitiveSizeInBits();
5861 if (SrcTy->isInteger() &&
5862 SrcTySize == Cast->getType()->getPrimitiveSizeInBits()) {
5863 // If this is an unsigned comparison, try to make the comparison use
5864 // smaller constant values.
5865 if (ICI.getPredicate() == ICmpInst::ICMP_ULT && RHSV.isSignBit()) {
5866 // X u< 128 => X s> -1
5867 return new ICmpInst(ICmpInst::ICMP_SGT, CastOp,
5868 ConstantInt::get(APInt::getAllOnesValue(SrcTySize)));
5869 } else if (ICI.getPredicate() == ICmpInst::ICMP_UGT &&
5870 RHSV == APInt::getSignedMaxValue(SrcTySize)) {
5871 // X u> 127 => X s< 0
5872 return new ICmpInst(ICmpInst::ICMP_SLT, CastOp,
5873 Constant::getNullValue(SrcTy));
5874 }
5875 }
5876 }
5877 }
5878 return 0;
5879}
5880
5881/// visitICmpInstWithCastAndCast - Handle icmp (cast x to y), (cast/cst).
5882/// We only handle extending casts so far.
5883///
Reid Spencere4d87aa2006-12-23 06:05:41 +00005884Instruction *InstCombiner::visitICmpInstWithCastAndCast(ICmpInst &ICI) {
5885 const CastInst *LHSCI = cast<CastInst>(ICI.getOperand(0));
Reid Spencer3da59db2006-11-27 01:05:10 +00005886 Value *LHSCIOp = LHSCI->getOperand(0);
5887 const Type *SrcTy = LHSCIOp->getType();
Reid Spencere4d87aa2006-12-23 06:05:41 +00005888 const Type *DestTy = LHSCI->getType();
Chris Lattner484d3cf2005-04-24 06:59:08 +00005889 Value *RHSCIOp;
5890
Chris Lattner8c756c12007-05-05 22:41:33 +00005891 // Turn icmp (ptrtoint x), (ptrtoint/c) into a compare of the input if the
5892 // integer type is the same size as the pointer type.
5893 if (LHSCI->getOpcode() == Instruction::PtrToInt &&
5894 getTargetData().getPointerSizeInBits() ==
5895 cast<IntegerType>(DestTy)->getBitWidth()) {
5896 Value *RHSOp = 0;
5897 if (Constant *RHSC = dyn_cast<Constant>(ICI.getOperand(1))) {
Chris Lattner6f6f5122007-05-06 07:24:03 +00005898 RHSOp = ConstantExpr::getIntToPtr(RHSC, SrcTy);
Chris Lattner8c756c12007-05-05 22:41:33 +00005899 } else if (PtrToIntInst *RHSC = dyn_cast<PtrToIntInst>(ICI.getOperand(1))) {
5900 RHSOp = RHSC->getOperand(0);
5901 // If the pointer types don't match, insert a bitcast.
5902 if (LHSCIOp->getType() != RHSOp->getType())
Chris Lattner6d0339d2008-01-13 22:23:22 +00005903 RHSOp = InsertBitCastBefore(RHSOp, LHSCIOp->getType(), ICI);
Chris Lattner8c756c12007-05-05 22:41:33 +00005904 }
5905
5906 if (RHSOp)
5907 return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSOp);
5908 }
5909
5910 // The code below only handles extension cast instructions, so far.
5911 // Enforce this.
Reid Spencere4d87aa2006-12-23 06:05:41 +00005912 if (LHSCI->getOpcode() != Instruction::ZExt &&
5913 LHSCI->getOpcode() != Instruction::SExt)
Chris Lattnerb352fa52005-01-17 03:20:02 +00005914 return 0;
5915
Reid Spencere4d87aa2006-12-23 06:05:41 +00005916 bool isSignedExt = LHSCI->getOpcode() == Instruction::SExt;
5917 bool isSignedCmp = ICI.isSignedPredicate();
Chris Lattner484d3cf2005-04-24 06:59:08 +00005918
Reid Spencere4d87aa2006-12-23 06:05:41 +00005919 if (CastInst *CI = dyn_cast<CastInst>(ICI.getOperand(1))) {
Chris Lattner484d3cf2005-04-24 06:59:08 +00005920 // Not an extension from the same type?
5921 RHSCIOp = CI->getOperand(0);
Reid Spencere4d87aa2006-12-23 06:05:41 +00005922 if (RHSCIOp->getType() != LHSCIOp->getType())
5923 return 0;
Chris Lattnera5c5e772007-01-13 23:11:38 +00005924
Nick Lewycky4189a532008-01-28 03:48:02 +00005925 // If the signedness of the two casts doesn't agree (i.e. one is a sext
Chris Lattnera5c5e772007-01-13 23:11:38 +00005926 // and the other is a zext), then we can't handle this.
5927 if (CI->getOpcode() != LHSCI->getOpcode())
5928 return 0;
5929
Nick Lewycky4189a532008-01-28 03:48:02 +00005930 // Deal with equality cases early.
5931 if (ICI.isEquality())
5932 return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSCIOp);
5933
5934 // A signed comparison of sign extended values simplifies into a
5935 // signed comparison.
5936 if (isSignedCmp && isSignedExt)
5937 return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSCIOp);
5938
5939 // The other three cases all fold into an unsigned comparison.
5940 return new ICmpInst(ICI.getUnsignedPredicate(), LHSCIOp, RHSCIOp);
Reid Spencer6731d5c2004-11-28 21:31:15 +00005941 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00005942
Reid Spencere4d87aa2006-12-23 06:05:41 +00005943 // If we aren't dealing with a constant on the RHS, exit early
5944 ConstantInt *CI = dyn_cast<ConstantInt>(ICI.getOperand(1));
5945 if (!CI)
5946 return 0;
5947
5948 // Compute the constant that would happen if we truncated to SrcTy then
5949 // reextended to DestTy.
5950 Constant *Res1 = ConstantExpr::getTrunc(CI, SrcTy);
5951 Constant *Res2 = ConstantExpr::getCast(LHSCI->getOpcode(), Res1, DestTy);
5952
5953 // If the re-extended constant didn't change...
5954 if (Res2 == CI) {
5955 // Make sure that sign of the Cmp and the sign of the Cast are the same.
5956 // For example, we might have:
5957 // %A = sext short %X to uint
5958 // %B = icmp ugt uint %A, 1330
5959 // It is incorrect to transform this into
5960 // %B = icmp ugt short %X, 1330
5961 // because %A may have negative value.
5962 //
5963 // However, it is OK if SrcTy is bool (See cast-set.ll testcase)
5964 // OR operation is EQ/NE.
Reid Spencer4fe16d62007-01-11 18:21:29 +00005965 if (isSignedExt == isSignedCmp || SrcTy == Type::Int1Ty || ICI.isEquality())
Reid Spencere4d87aa2006-12-23 06:05:41 +00005966 return new ICmpInst(ICI.getPredicate(), LHSCIOp, Res1);
5967 else
5968 return 0;
5969 }
5970
5971 // The re-extended constant changed so the constant cannot be represented
5972 // in the shorter type. Consequently, we cannot emit a simple comparison.
5973
5974 // First, handle some easy cases. We know the result cannot be equal at this
5975 // point so handle the ICI.isEquality() cases
5976 if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005977 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
Reid Spencere4d87aa2006-12-23 06:05:41 +00005978 if (ICI.getPredicate() == ICmpInst::ICMP_NE)
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005979 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
Reid Spencere4d87aa2006-12-23 06:05:41 +00005980
5981 // Evaluate the comparison for LT (we invert for GT below). LE and GE cases
5982 // should have been folded away previously and not enter in here.
5983 Value *Result;
5984 if (isSignedCmp) {
5985 // We're performing a signed comparison.
Reid Spencer0460fb32007-03-22 20:36:03 +00005986 if (cast<ConstantInt>(CI)->getValue().isNegative())
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005987 Result = ConstantInt::getFalse(); // X < (small) --> false
Reid Spencere4d87aa2006-12-23 06:05:41 +00005988 else
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005989 Result = ConstantInt::getTrue(); // X < (large) --> true
Reid Spencere4d87aa2006-12-23 06:05:41 +00005990 } else {
5991 // We're performing an unsigned comparison.
5992 if (isSignedExt) {
5993 // We're performing an unsigned comp with a sign extended value.
5994 // This is true if the input is >= 0. [aka >s -1]
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005995 Constant *NegOne = ConstantInt::getAllOnesValue(SrcTy);
Reid Spencere4d87aa2006-12-23 06:05:41 +00005996 Result = InsertNewInstBefore(new ICmpInst(ICmpInst::ICMP_SGT, LHSCIOp,
5997 NegOne, ICI.getName()), ICI);
5998 } else {
5999 // Unsigned extend & unsigned compare -> always true.
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00006000 Result = ConstantInt::getTrue();
Reid Spencere4d87aa2006-12-23 06:05:41 +00006001 }
6002 }
6003
6004 // Finally, return the value computed.
6005 if (ICI.getPredicate() == ICmpInst::ICMP_ULT ||
6006 ICI.getPredicate() == ICmpInst::ICMP_SLT) {
6007 return ReplaceInstUsesWith(ICI, Result);
6008 } else {
6009 assert((ICI.getPredicate()==ICmpInst::ICMP_UGT ||
6010 ICI.getPredicate()==ICmpInst::ICMP_SGT) &&
6011 "ICmp should be folded!");
6012 if (Constant *CI = dyn_cast<Constant>(Result))
6013 return ReplaceInstUsesWith(ICI, ConstantExpr::getNot(CI));
6014 else
6015 return BinaryOperator::createNot(Result);
6016 }
Chris Lattner484d3cf2005-04-24 06:59:08 +00006017}
Chris Lattner3f5b8772002-05-06 16:14:14 +00006018
Reid Spencer832254e2007-02-02 02:16:23 +00006019Instruction *InstCombiner::visitShl(BinaryOperator &I) {
6020 return commonShiftTransforms(I);
6021}
6022
6023Instruction *InstCombiner::visitLShr(BinaryOperator &I) {
6024 return commonShiftTransforms(I);
6025}
6026
6027Instruction *InstCombiner::visitAShr(BinaryOperator &I) {
Chris Lattner348f6652007-12-06 01:59:46 +00006028 if (Instruction *R = commonShiftTransforms(I))
6029 return R;
6030
6031 Value *Op0 = I.getOperand(0);
6032
6033 // ashr int -1, X = -1 (for any arithmetic shift rights of ~0)
6034 if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
6035 if (CSI->isAllOnesValue())
6036 return ReplaceInstUsesWith(I, CSI);
6037
6038 // See if we can turn a signed shr into an unsigned shr.
6039 if (MaskedValueIsZero(Op0,
6040 APInt::getSignBit(I.getType()->getPrimitiveSizeInBits())))
6041 return BinaryOperator::createLShr(Op0, I.getOperand(1));
6042
6043 return 0;
Reid Spencer832254e2007-02-02 02:16:23 +00006044}
6045
6046Instruction *InstCombiner::commonShiftTransforms(BinaryOperator &I) {
6047 assert(I.getOperand(1)->getType() == I.getOperand(0)->getType());
Chris Lattner7e708292002-06-25 16:13:24 +00006048 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00006049
6050 // shl X, 0 == X and shr X, 0 == X
6051 // shl 0, X == 0 and shr 0, X == 0
Reid Spencer832254e2007-02-02 02:16:23 +00006052 if (Op1 == Constant::getNullValue(Op1->getType()) ||
Chris Lattner233f7dc2002-08-12 21:17:25 +00006053 Op0 == Constant::getNullValue(Op0->getType()))
6054 return ReplaceInstUsesWith(I, Op0);
Chris Lattner8d6bbdb2006-02-12 08:07:37 +00006055
Reid Spencere4d87aa2006-12-23 06:05:41 +00006056 if (isa<UndefValue>(Op0)) {
6057 if (I.getOpcode() == Instruction::AShr) // undef >>s X -> undef
Chris Lattner79a564c2004-10-16 23:28:04 +00006058 return ReplaceInstUsesWith(I, Op0);
Reid Spencere4d87aa2006-12-23 06:05:41 +00006059 else // undef << X -> 0, undef >>u X -> 0
Chris Lattnere87597f2004-10-16 18:11:37 +00006060 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
6061 }
6062 if (isa<UndefValue>(Op1)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00006063 if (I.getOpcode() == Instruction::AShr) // X >>s undef -> X
6064 return ReplaceInstUsesWith(I, Op0);
6065 else // X << undef, X >>u undef -> 0
Chris Lattnere87597f2004-10-16 18:11:37 +00006066 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnere87597f2004-10-16 18:11:37 +00006067 }
6068
Chris Lattner2eefe512004-04-09 19:05:30 +00006069 // Try to fold constant and into select arguments.
6070 if (isa<Constant>(Op0))
6071 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
Chris Lattner6e7ba452005-01-01 16:22:27 +00006072 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00006073 return R;
6074
Reid Spencerb83eb642006-10-20 07:07:24 +00006075 if (ConstantInt *CUI = dyn_cast<ConstantInt>(Op1))
Reid Spencerc5b206b2006-12-31 05:48:39 +00006076 if (Instruction *Res = FoldShiftByConstant(Op0, CUI, I))
6077 return Res;
Chris Lattner4d5542c2006-01-06 07:12:35 +00006078 return 0;
6079}
6080
Reid Spencerb83eb642006-10-20 07:07:24 +00006081Instruction *InstCombiner::FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
Reid Spencer832254e2007-02-02 02:16:23 +00006082 BinaryOperator &I) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00006083 bool isLeftShift = I.getOpcode() == Instruction::Shl;
Chris Lattner4d5542c2006-01-06 07:12:35 +00006084
Chris Lattner8d6bbdb2006-02-12 08:07:37 +00006085 // See if we can simplify any instructions used by the instruction whose sole
6086 // purpose is to compute bits we don't care about.
Reid Spencerb35ae032007-03-23 18:46:34 +00006087 uint32_t TypeBits = Op0->getType()->getPrimitiveSizeInBits();
6088 APInt KnownZero(TypeBits, 0), KnownOne(TypeBits, 0);
6089 if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(TypeBits),
Chris Lattner8d6bbdb2006-02-12 08:07:37 +00006090 KnownZero, KnownOne))
6091 return &I;
6092
Chris Lattner4d5542c2006-01-06 07:12:35 +00006093 // shl uint X, 32 = 0 and shr ubyte Y, 9 = 0, ... just don't eliminate shr
6094 // of a signed value.
6095 //
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00006096 if (Op1->uge(TypeBits)) {
Chris Lattner0737c242007-02-02 05:29:55 +00006097 if (I.getOpcode() != Instruction::AShr)
Chris Lattner4d5542c2006-01-06 07:12:35 +00006098 return ReplaceInstUsesWith(I, Constant::getNullValue(Op0->getType()));
6099 else {
Chris Lattner0737c242007-02-02 05:29:55 +00006100 I.setOperand(1, ConstantInt::get(I.getType(), TypeBits-1));
Chris Lattner4d5542c2006-01-06 07:12:35 +00006101 return &I;
Chris Lattner8adac752004-02-23 20:30:06 +00006102 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00006103 }
6104
6105 // ((X*C1) << C2) == (X * (C1 << C2))
6106 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0))
6107 if (BO->getOpcode() == Instruction::Mul && isLeftShift)
6108 if (Constant *BOOp = dyn_cast<Constant>(BO->getOperand(1)))
6109 return BinaryOperator::createMul(BO->getOperand(0),
6110 ConstantExpr::getShl(BOOp, Op1));
6111
6112 // Try to fold constant and into select arguments.
6113 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
6114 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
6115 return R;
6116 if (isa<PHINode>(Op0))
6117 if (Instruction *NV = FoldOpIntoPhi(I))
6118 return NV;
6119
Chris Lattner8999dd32007-12-22 09:07:47 +00006120 // Fold shift2(trunc(shift1(x,c1)), c2) -> trunc(shift2(shift1(x,c1),c2))
6121 if (TruncInst *TI = dyn_cast<TruncInst>(Op0)) {
6122 Instruction *TrOp = dyn_cast<Instruction>(TI->getOperand(0));
6123 // If 'shift2' is an ashr, we would have to get the sign bit into a funny
6124 // place. Don't try to do this transformation in this case. Also, we
6125 // require that the input operand is a shift-by-constant so that we have
6126 // confidence that the shifts will get folded together. We could do this
6127 // xform in more cases, but it is unlikely to be profitable.
6128 if (TrOp && I.isLogicalShift() && TrOp->isShift() &&
6129 isa<ConstantInt>(TrOp->getOperand(1))) {
6130 // Okay, we'll do this xform. Make the shift of shift.
6131 Constant *ShAmt = ConstantExpr::getZExt(Op1, TrOp->getType());
6132 Instruction *NSh = BinaryOperator::create(I.getOpcode(), TrOp, ShAmt,
6133 I.getName());
6134 InsertNewInstBefore(NSh, I); // (shift2 (shift1 & 0x00FF), c2)
6135
6136 // For logical shifts, the truncation has the effect of making the high
6137 // part of the register be zeros. Emulate this by inserting an AND to
6138 // clear the top bits as needed. This 'and' will usually be zapped by
6139 // other xforms later if dead.
6140 unsigned SrcSize = TrOp->getType()->getPrimitiveSizeInBits();
6141 unsigned DstSize = TI->getType()->getPrimitiveSizeInBits();
6142 APInt MaskV(APInt::getLowBitsSet(SrcSize, DstSize));
6143
6144 // The mask we constructed says what the trunc would do if occurring
6145 // between the shifts. We want to know the effect *after* the second
6146 // shift. We know that it is a logical shift by a constant, so adjust the
6147 // mask as appropriate.
6148 if (I.getOpcode() == Instruction::Shl)
6149 MaskV <<= Op1->getZExtValue();
6150 else {
6151 assert(I.getOpcode() == Instruction::LShr && "Unknown logical shift");
6152 MaskV = MaskV.lshr(Op1->getZExtValue());
6153 }
6154
6155 Instruction *And = BinaryOperator::createAnd(NSh, ConstantInt::get(MaskV),
6156 TI->getName());
6157 InsertNewInstBefore(And, I); // shift1 & 0x00FF
6158
6159 // Return the value truncated to the interesting size.
6160 return new TruncInst(And, I.getType());
6161 }
6162 }
6163
Chris Lattner4d5542c2006-01-06 07:12:35 +00006164 if (Op0->hasOneUse()) {
Chris Lattner4d5542c2006-01-06 07:12:35 +00006165 if (BinaryOperator *Op0BO = dyn_cast<BinaryOperator>(Op0)) {
6166 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
6167 Value *V1, *V2;
6168 ConstantInt *CC;
6169 switch (Op0BO->getOpcode()) {
Chris Lattner11021cb2005-09-18 05:12:10 +00006170 default: break;
6171 case Instruction::Add:
6172 case Instruction::And:
6173 case Instruction::Or:
Reid Spencera07cb7d2007-02-02 14:41:37 +00006174 case Instruction::Xor: {
Chris Lattner11021cb2005-09-18 05:12:10 +00006175 // These operators commute.
6176 // Turn (Y + (X >> C)) << C -> (X + (Y << C)) & (~0 << C)
Chris Lattner150f12a2005-09-18 06:30:59 +00006177 if (isLeftShift && Op0BO->getOperand(1)->hasOneUse() &&
6178 match(Op0BO->getOperand(1),
Chris Lattner4d5542c2006-01-06 07:12:35 +00006179 m_Shr(m_Value(V1), m_ConstantInt(CC))) && CC == Op1) {
Reid Spencercc46cdb2007-02-02 14:08:20 +00006180 Instruction *YS = BinaryOperator::createShl(
Chris Lattner4d5542c2006-01-06 07:12:35 +00006181 Op0BO->getOperand(0), Op1,
Chris Lattner150f12a2005-09-18 06:30:59 +00006182 Op0BO->getName());
6183 InsertNewInstBefore(YS, I); // (Y << C)
Chris Lattner9a4cacb2006-02-09 07:41:14 +00006184 Instruction *X =
6185 BinaryOperator::create(Op0BO->getOpcode(), YS, V1,
6186 Op0BO->getOperand(1)->getName());
Chris Lattner150f12a2005-09-18 06:30:59 +00006187 InsertNewInstBefore(X, I); // (X + (Y << C))
Zhou Sheng302748d2007-03-30 17:20:39 +00006188 uint32_t Op1Val = Op1->getLimitedValue(TypeBits);
Zhou Sheng90b96812007-03-30 05:45:18 +00006189 return BinaryOperator::createAnd(X, ConstantInt::get(
6190 APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
Chris Lattner150f12a2005-09-18 06:30:59 +00006191 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00006192
Chris Lattner150f12a2005-09-18 06:30:59 +00006193 // Turn (Y + ((X >> C) & CC)) << C -> ((X & (CC << C)) + (Y << C))
Reid Spencera07cb7d2007-02-02 14:41:37 +00006194 Value *Op0BOOp1 = Op0BO->getOperand(1);
Chris Lattner3c698492007-03-05 00:11:19 +00006195 if (isLeftShift && Op0BOOp1->hasOneUse() &&
Reid Spencera07cb7d2007-02-02 14:41:37 +00006196 match(Op0BOOp1,
6197 m_And(m_Shr(m_Value(V1), m_Value(V2)),m_ConstantInt(CC))) &&
Chris Lattner3c698492007-03-05 00:11:19 +00006198 cast<BinaryOperator>(Op0BOOp1)->getOperand(0)->hasOneUse() &&
6199 V2 == Op1) {
Reid Spencercc46cdb2007-02-02 14:08:20 +00006200 Instruction *YS = BinaryOperator::createShl(
Reid Spencer832254e2007-02-02 02:16:23 +00006201 Op0BO->getOperand(0), Op1,
6202 Op0BO->getName());
Chris Lattner150f12a2005-09-18 06:30:59 +00006203 InsertNewInstBefore(YS, I); // (Y << C)
6204 Instruction *XM =
Chris Lattner4d5542c2006-01-06 07:12:35 +00006205 BinaryOperator::createAnd(V1, ConstantExpr::getShl(CC, Op1),
Chris Lattner150f12a2005-09-18 06:30:59 +00006206 V1->getName()+".mask");
6207 InsertNewInstBefore(XM, I); // X & (CC << C)
6208
6209 return BinaryOperator::create(Op0BO->getOpcode(), YS, XM);
6210 }
Reid Spencera07cb7d2007-02-02 14:41:37 +00006211 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00006212
Reid Spencera07cb7d2007-02-02 14:41:37 +00006213 // FALL THROUGH.
6214 case Instruction::Sub: {
Chris Lattner11021cb2005-09-18 05:12:10 +00006215 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
Chris Lattner150f12a2005-09-18 06:30:59 +00006216 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
6217 match(Op0BO->getOperand(0),
Chris Lattner4d5542c2006-01-06 07:12:35 +00006218 m_Shr(m_Value(V1), m_ConstantInt(CC))) && CC == Op1) {
Reid Spencercc46cdb2007-02-02 14:08:20 +00006219 Instruction *YS = BinaryOperator::createShl(
Reid Spencer832254e2007-02-02 02:16:23 +00006220 Op0BO->getOperand(1), Op1,
6221 Op0BO->getName());
Chris Lattner150f12a2005-09-18 06:30:59 +00006222 InsertNewInstBefore(YS, I); // (Y << C)
Chris Lattner9a4cacb2006-02-09 07:41:14 +00006223 Instruction *X =
Chris Lattner13d4ab42006-05-31 21:14:00 +00006224 BinaryOperator::create(Op0BO->getOpcode(), V1, YS,
Chris Lattner9a4cacb2006-02-09 07:41:14 +00006225 Op0BO->getOperand(0)->getName());
Chris Lattner150f12a2005-09-18 06:30:59 +00006226 InsertNewInstBefore(X, I); // (X + (Y << C))
Zhou Sheng302748d2007-03-30 17:20:39 +00006227 uint32_t Op1Val = Op1->getLimitedValue(TypeBits);
Zhou Sheng90b96812007-03-30 05:45:18 +00006228 return BinaryOperator::createAnd(X, ConstantInt::get(
6229 APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
Chris Lattner150f12a2005-09-18 06:30:59 +00006230 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00006231
Chris Lattner13d4ab42006-05-31 21:14:00 +00006232 // Turn (((X >> C)&CC) + Y) << C -> (X + (Y << C)) & (CC << C)
Chris Lattner150f12a2005-09-18 06:30:59 +00006233 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
6234 match(Op0BO->getOperand(0),
6235 m_And(m_Shr(m_Value(V1), m_Value(V2)),
Chris Lattner4d5542c2006-01-06 07:12:35 +00006236 m_ConstantInt(CC))) && V2 == Op1 &&
Chris Lattner9a4cacb2006-02-09 07:41:14 +00006237 cast<BinaryOperator>(Op0BO->getOperand(0))
6238 ->getOperand(0)->hasOneUse()) {
Reid Spencercc46cdb2007-02-02 14:08:20 +00006239 Instruction *YS = BinaryOperator::createShl(
Reid Spencer832254e2007-02-02 02:16:23 +00006240 Op0BO->getOperand(1), Op1,
6241 Op0BO->getName());
Chris Lattner150f12a2005-09-18 06:30:59 +00006242 InsertNewInstBefore(YS, I); // (Y << C)
6243 Instruction *XM =
Chris Lattner4d5542c2006-01-06 07:12:35 +00006244 BinaryOperator::createAnd(V1, ConstantExpr::getShl(CC, Op1),
Chris Lattner150f12a2005-09-18 06:30:59 +00006245 V1->getName()+".mask");
6246 InsertNewInstBefore(XM, I); // X & (CC << C)
6247
Chris Lattner13d4ab42006-05-31 21:14:00 +00006248 return BinaryOperator::create(Op0BO->getOpcode(), XM, YS);
Chris Lattner150f12a2005-09-18 06:30:59 +00006249 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00006250
Chris Lattner11021cb2005-09-18 05:12:10 +00006251 break;
Reid Spencera07cb7d2007-02-02 14:41:37 +00006252 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00006253 }
6254
6255
6256 // If the operand is an bitwise operator with a constant RHS, and the
6257 // shift is the only use, we can pull it out of the shift.
6258 if (ConstantInt *Op0C = dyn_cast<ConstantInt>(Op0BO->getOperand(1))) {
6259 bool isValid = true; // Valid only for And, Or, Xor
6260 bool highBitSet = false; // Transform if high bit of constant set?
6261
6262 switch (Op0BO->getOpcode()) {
Chris Lattnerdf17af12003-08-12 21:53:41 +00006263 default: isValid = false; break; // Do not perform transform!
Chris Lattner1f7e1602004-10-08 03:46:20 +00006264 case Instruction::Add:
6265 isValid = isLeftShift;
6266 break;
Chris Lattnerdf17af12003-08-12 21:53:41 +00006267 case Instruction::Or:
6268 case Instruction::Xor:
6269 highBitSet = false;
6270 break;
6271 case Instruction::And:
6272 highBitSet = true;
6273 break;
Chris Lattner4d5542c2006-01-06 07:12:35 +00006274 }
6275
6276 // If this is a signed shift right, and the high bit is modified
6277 // by the logical operation, do not perform the transformation.
6278 // The highBitSet boolean indicates the value of the high bit of
6279 // the constant which would cause it to be modified for this
6280 // operation.
6281 //
Chris Lattnerc95ba442007-12-06 06:25:04 +00006282 if (isValid && I.getOpcode() == Instruction::AShr)
Zhou Shenge9e03f62007-03-28 15:02:20 +00006283 isValid = Op0C->getValue()[TypeBits-1] == highBitSet;
Chris Lattner4d5542c2006-01-06 07:12:35 +00006284
6285 if (isValid) {
6286 Constant *NewRHS = ConstantExpr::get(I.getOpcode(), Op0C, Op1);
6287
6288 Instruction *NewShift =
Chris Lattner6934a042007-02-11 01:23:03 +00006289 BinaryOperator::create(I.getOpcode(), Op0BO->getOperand(0), Op1);
Chris Lattner4d5542c2006-01-06 07:12:35 +00006290 InsertNewInstBefore(NewShift, I);
Chris Lattner6934a042007-02-11 01:23:03 +00006291 NewShift->takeName(Op0BO);
Chris Lattner4d5542c2006-01-06 07:12:35 +00006292
6293 return BinaryOperator::create(Op0BO->getOpcode(), NewShift,
6294 NewRHS);
6295 }
6296 }
6297 }
6298 }
6299
Chris Lattnerad0124c2006-01-06 07:52:12 +00006300 // Find out if this is a shift of a shift by a constant.
Reid Spencer832254e2007-02-02 02:16:23 +00006301 BinaryOperator *ShiftOp = dyn_cast<BinaryOperator>(Op0);
6302 if (ShiftOp && !ShiftOp->isShift())
6303 ShiftOp = 0;
Chris Lattnerad0124c2006-01-06 07:52:12 +00006304
Reid Spencerb83eb642006-10-20 07:07:24 +00006305 if (ShiftOp && isa<ConstantInt>(ShiftOp->getOperand(1))) {
Reid Spencerb83eb642006-10-20 07:07:24 +00006306 ConstantInt *ShiftAmt1C = cast<ConstantInt>(ShiftOp->getOperand(1));
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00006307 uint32_t ShiftAmt1 = ShiftAmt1C->getLimitedValue(TypeBits);
6308 uint32_t ShiftAmt2 = Op1->getLimitedValue(TypeBits);
Chris Lattnerb87056f2007-02-05 00:57:54 +00006309 assert(ShiftAmt2 != 0 && "Should have been simplified earlier");
6310 if (ShiftAmt1 == 0) return 0; // Will be simplified in the future.
6311 Value *X = ShiftOp->getOperand(0);
Chris Lattnerad0124c2006-01-06 07:52:12 +00006312
Zhou Sheng4351c642007-04-02 08:20:41 +00006313 uint32_t AmtSum = ShiftAmt1+ShiftAmt2; // Fold into one big shift.
Reid Spencerb35ae032007-03-23 18:46:34 +00006314 if (AmtSum > TypeBits)
6315 AmtSum = TypeBits;
Chris Lattnerb87056f2007-02-05 00:57:54 +00006316
6317 const IntegerType *Ty = cast<IntegerType>(I.getType());
6318
6319 // Check for (X << c1) << c2 and (X >> c1) >> c2
Chris Lattner7f3da2d2007-02-03 23:28:07 +00006320 if (I.getOpcode() == ShiftOp->getOpcode()) {
Chris Lattnerb87056f2007-02-05 00:57:54 +00006321 return BinaryOperator::create(I.getOpcode(), X,
6322 ConstantInt::get(Ty, AmtSum));
6323 } else if (ShiftOp->getOpcode() == Instruction::LShr &&
6324 I.getOpcode() == Instruction::AShr) {
6325 // ((X >>u C1) >>s C2) -> (X >>u (C1+C2)) since C1 != 0.
6326 return BinaryOperator::createLShr(X, ConstantInt::get(Ty, AmtSum));
6327 } else if (ShiftOp->getOpcode() == Instruction::AShr &&
6328 I.getOpcode() == Instruction::LShr) {
6329 // ((X >>s C1) >>u C2) -> ((X >>s (C1+C2)) & mask) since C1 != 0.
6330 Instruction *Shift =
6331 BinaryOperator::createAShr(X, ConstantInt::get(Ty, AmtSum));
6332 InsertNewInstBefore(Shift, I);
6333
Zhou Shenge9e03f62007-03-28 15:02:20 +00006334 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
Reid Spencerb35ae032007-03-23 18:46:34 +00006335 return BinaryOperator::createAnd(Shift, ConstantInt::get(Mask));
Chris Lattnerad0124c2006-01-06 07:52:12 +00006336 }
6337
Chris Lattnerb87056f2007-02-05 00:57:54 +00006338 // Okay, if we get here, one shift must be left, and the other shift must be
6339 // right. See if the amounts are equal.
6340 if (ShiftAmt1 == ShiftAmt2) {
6341 // If we have ((X >>? C) << C), turn this into X & (-1 << C).
6342 if (I.getOpcode() == Instruction::Shl) {
Reid Spencer55702aa2007-03-25 21:11:44 +00006343 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt1));
Reid Spencerb35ae032007-03-23 18:46:34 +00006344 return BinaryOperator::createAnd(X, ConstantInt::get(Mask));
Chris Lattnerb87056f2007-02-05 00:57:54 +00006345 }
6346 // If we have ((X << C) >>u C), turn this into X & (-1 >>u C).
6347 if (I.getOpcode() == Instruction::LShr) {
Zhou Sheng3a507fd2007-04-01 17:13:37 +00006348 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt1));
Reid Spencerb35ae032007-03-23 18:46:34 +00006349 return BinaryOperator::createAnd(X, ConstantInt::get(Mask));
Chris Lattnerb87056f2007-02-05 00:57:54 +00006350 }
6351 // We can simplify ((X << C) >>s C) into a trunc + sext.
6352 // NOTE: we could do this for any C, but that would make 'unusual' integer
6353 // types. For now, just stick to ones well-supported by the code
6354 // generators.
6355 const Type *SExtType = 0;
6356 switch (Ty->getBitWidth() - ShiftAmt1) {
Zhou Shenge9e03f62007-03-28 15:02:20 +00006357 case 1 :
6358 case 8 :
6359 case 16 :
6360 case 32 :
6361 case 64 :
6362 case 128:
6363 SExtType = IntegerType::get(Ty->getBitWidth() - ShiftAmt1);
6364 break;
Chris Lattnerb87056f2007-02-05 00:57:54 +00006365 default: break;
6366 }
6367 if (SExtType) {
6368 Instruction *NewTrunc = new TruncInst(X, SExtType, "sext");
6369 InsertNewInstBefore(NewTrunc, I);
6370 return new SExtInst(NewTrunc, Ty);
6371 }
6372 // Otherwise, we can't handle it yet.
6373 } else if (ShiftAmt1 < ShiftAmt2) {
Zhou Sheng4351c642007-04-02 08:20:41 +00006374 uint32_t ShiftDiff = ShiftAmt2-ShiftAmt1;
Chris Lattnerad0124c2006-01-06 07:52:12 +00006375
Chris Lattnerb0b991a2007-02-05 05:57:49 +00006376 // (X >>? C1) << C2 --> X << (C2-C1) & (-1 << C2)
Chris Lattnerb87056f2007-02-05 00:57:54 +00006377 if (I.getOpcode() == Instruction::Shl) {
6378 assert(ShiftOp->getOpcode() == Instruction::LShr ||
6379 ShiftOp->getOpcode() == Instruction::AShr);
Chris Lattnere8d56c52006-01-07 01:32:28 +00006380 Instruction *Shift =
Chris Lattnerb87056f2007-02-05 00:57:54 +00006381 BinaryOperator::createShl(X, ConstantInt::get(Ty, ShiftDiff));
Chris Lattnere8d56c52006-01-07 01:32:28 +00006382 InsertNewInstBefore(Shift, I);
6383
Reid Spencer55702aa2007-03-25 21:11:44 +00006384 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
6385 return BinaryOperator::createAnd(Shift, ConstantInt::get(Mask));
Chris Lattnerad0124c2006-01-06 07:52:12 +00006386 }
Chris Lattnerb87056f2007-02-05 00:57:54 +00006387
Chris Lattnerb0b991a2007-02-05 05:57:49 +00006388 // (X << C1) >>u C2 --> X >>u (C2-C1) & (-1 >> C2)
Chris Lattnerb87056f2007-02-05 00:57:54 +00006389 if (I.getOpcode() == Instruction::LShr) {
6390 assert(ShiftOp->getOpcode() == Instruction::Shl);
6391 Instruction *Shift =
6392 BinaryOperator::createLShr(X, ConstantInt::get(Ty, ShiftDiff));
6393 InsertNewInstBefore(Shift, I);
Chris Lattnerad0124c2006-01-06 07:52:12 +00006394
Reid Spencerd5e30f02007-03-26 17:18:58 +00006395 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
Reid Spencerb35ae032007-03-23 18:46:34 +00006396 return BinaryOperator::createAnd(Shift, ConstantInt::get(Mask));
Chris Lattner11021cb2005-09-18 05:12:10 +00006397 }
Chris Lattnerb87056f2007-02-05 00:57:54 +00006398
6399 // We can't handle (X << C1) >>s C2, it shifts arbitrary bits in.
6400 } else {
6401 assert(ShiftAmt2 < ShiftAmt1);
Zhou Sheng4351c642007-04-02 08:20:41 +00006402 uint32_t ShiftDiff = ShiftAmt1-ShiftAmt2;
Chris Lattnerb87056f2007-02-05 00:57:54 +00006403
Chris Lattnerb0b991a2007-02-05 05:57:49 +00006404 // (X >>? C1) << C2 --> X >>? (C1-C2) & (-1 << C2)
Chris Lattnerb87056f2007-02-05 00:57:54 +00006405 if (I.getOpcode() == Instruction::Shl) {
6406 assert(ShiftOp->getOpcode() == Instruction::LShr ||
6407 ShiftOp->getOpcode() == Instruction::AShr);
6408 Instruction *Shift =
6409 BinaryOperator::create(ShiftOp->getOpcode(), X,
6410 ConstantInt::get(Ty, ShiftDiff));
6411 InsertNewInstBefore(Shift, I);
6412
Reid Spencer55702aa2007-03-25 21:11:44 +00006413 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
Reid Spencerb35ae032007-03-23 18:46:34 +00006414 return BinaryOperator::createAnd(Shift, ConstantInt::get(Mask));
Chris Lattnerb87056f2007-02-05 00:57:54 +00006415 }
6416
Chris Lattnerb0b991a2007-02-05 05:57:49 +00006417 // (X << C1) >>u C2 --> X << (C1-C2) & (-1 >> C2)
Chris Lattnerb87056f2007-02-05 00:57:54 +00006418 if (I.getOpcode() == Instruction::LShr) {
6419 assert(ShiftOp->getOpcode() == Instruction::Shl);
6420 Instruction *Shift =
6421 BinaryOperator::createShl(X, ConstantInt::get(Ty, ShiftDiff));
6422 InsertNewInstBefore(Shift, I);
6423
Reid Spencer68d27cf2007-03-26 23:45:51 +00006424 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
Reid Spencerb35ae032007-03-23 18:46:34 +00006425 return BinaryOperator::createAnd(Shift, ConstantInt::get(Mask));
Chris Lattnerb87056f2007-02-05 00:57:54 +00006426 }
6427
6428 // We can't handle (X << C1) >>a C2, it shifts arbitrary bits in.
Chris Lattner6e7ba452005-01-01 16:22:27 +00006429 }
Chris Lattnerad0124c2006-01-06 07:52:12 +00006430 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00006431 return 0;
6432}
6433
Chris Lattnera1be5662002-05-02 17:06:02 +00006434
Chris Lattnercfd65102005-10-29 04:36:15 +00006435/// DecomposeSimpleLinearExpr - Analyze 'Val', seeing if it is a simple linear
6436/// expression. If so, decompose it, returning some value X, such that Val is
6437/// X*Scale+Offset.
6438///
6439static Value *DecomposeSimpleLinearExpr(Value *Val, unsigned &Scale,
Jeff Cohen86796be2007-04-04 16:58:57 +00006440 int &Offset) {
Reid Spencerc5b206b2006-12-31 05:48:39 +00006441 assert(Val->getType() == Type::Int32Ty && "Unexpected allocation size type!");
Reid Spencerb83eb642006-10-20 07:07:24 +00006442 if (ConstantInt *CI = dyn_cast<ConstantInt>(Val)) {
Reid Spencerc5b206b2006-12-31 05:48:39 +00006443 Offset = CI->getZExtValue();
Chris Lattner6a94de22007-10-12 05:30:59 +00006444 Scale = 0;
Reid Spencerc5b206b2006-12-31 05:48:39 +00006445 return ConstantInt::get(Type::Int32Ty, 0);
Chris Lattner6a94de22007-10-12 05:30:59 +00006446 } else if (BinaryOperator *I = dyn_cast<BinaryOperator>(Val)) {
6447 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
6448 if (I->getOpcode() == Instruction::Shl) {
6449 // This is a value scaled by '1 << the shift amt'.
6450 Scale = 1U << RHS->getZExtValue();
6451 Offset = 0;
6452 return I->getOperand(0);
6453 } else if (I->getOpcode() == Instruction::Mul) {
6454 // This value is scaled by 'RHS'.
6455 Scale = RHS->getZExtValue();
6456 Offset = 0;
6457 return I->getOperand(0);
6458 } else if (I->getOpcode() == Instruction::Add) {
6459 // We have X+C. Check to see if we really have (X*C2)+C1,
6460 // where C1 is divisible by C2.
6461 unsigned SubScale;
6462 Value *SubVal =
6463 DecomposeSimpleLinearExpr(I->getOperand(0), SubScale, Offset);
6464 Offset += RHS->getZExtValue();
6465 Scale = SubScale;
6466 return SubVal;
Chris Lattnercfd65102005-10-29 04:36:15 +00006467 }
6468 }
6469 }
6470
6471 // Otherwise, we can't look past this.
6472 Scale = 1;
6473 Offset = 0;
6474 return Val;
6475}
6476
6477
Chris Lattnerb3f83972005-10-24 06:03:58 +00006478/// PromoteCastOfAllocation - If we find a cast of an allocation instruction,
6479/// try to eliminate the cast by moving the type information into the alloc.
Chris Lattnerd3e28342007-04-27 17:44:50 +00006480Instruction *InstCombiner::PromoteCastOfAllocation(BitCastInst &CI,
Chris Lattnerb3f83972005-10-24 06:03:58 +00006481 AllocationInst &AI) {
Chris Lattnerd3e28342007-04-27 17:44:50 +00006482 const PointerType *PTy = cast<PointerType>(CI.getType());
Chris Lattnerb3f83972005-10-24 06:03:58 +00006483
Chris Lattnerb53c2382005-10-24 06:22:12 +00006484 // Remove any uses of AI that are dead.
6485 assert(!CI.use_empty() && "Dead instructions should be removed earlier!");
Chris Lattner535014f2007-02-15 22:52:10 +00006486
Chris Lattnerb53c2382005-10-24 06:22:12 +00006487 for (Value::use_iterator UI = AI.use_begin(), E = AI.use_end(); UI != E; ) {
6488 Instruction *User = cast<Instruction>(*UI++);
6489 if (isInstructionTriviallyDead(User)) {
6490 while (UI != E && *UI == User)
6491 ++UI; // If this instruction uses AI more than once, don't break UI.
6492
Chris Lattnerb53c2382005-10-24 06:22:12 +00006493 ++NumDeadInst;
Bill Wendlingb7427032006-11-26 09:46:52 +00006494 DOUT << "IC: DCE: " << *User;
Chris Lattnerf22a5c62007-03-02 19:59:19 +00006495 EraseInstFromFunction(*User);
Chris Lattnerb53c2382005-10-24 06:22:12 +00006496 }
6497 }
6498
Chris Lattnerb3f83972005-10-24 06:03:58 +00006499 // Get the type really allocated and the type casted to.
6500 const Type *AllocElTy = AI.getAllocatedType();
6501 const Type *CastElTy = PTy->getElementType();
6502 if (!AllocElTy->isSized() || !CastElTy->isSized()) return 0;
Chris Lattner18e78bb2005-10-24 06:26:18 +00006503
Chris Lattnerd2b7cec2007-02-14 05:52:17 +00006504 unsigned AllocElTyAlign = TD->getABITypeAlignment(AllocElTy);
6505 unsigned CastElTyAlign = TD->getABITypeAlignment(CastElTy);
Chris Lattner18e78bb2005-10-24 06:26:18 +00006506 if (CastElTyAlign < AllocElTyAlign) return 0;
6507
Chris Lattner39387a52005-10-24 06:35:18 +00006508 // If the allocation has multiple uses, only promote it if we are strictly
6509 // increasing the alignment of the resultant allocation. If we keep it the
6510 // same, we open the door to infinite loops of various kinds.
6511 if (!AI.hasOneUse() && CastElTyAlign == AllocElTyAlign) return 0;
6512
Duncan Sands514ab342007-11-01 20:53:16 +00006513 uint64_t AllocElTySize = TD->getABITypeSize(AllocElTy);
6514 uint64_t CastElTySize = TD->getABITypeSize(CastElTy);
Chris Lattner0ddac2a2005-10-27 05:53:56 +00006515 if (CastElTySize == 0 || AllocElTySize == 0) return 0;
Chris Lattner18e78bb2005-10-24 06:26:18 +00006516
Chris Lattner455fcc82005-10-29 03:19:53 +00006517 // See if we can satisfy the modulus by pulling a scale out of the array
6518 // size argument.
Jeff Cohen86796be2007-04-04 16:58:57 +00006519 unsigned ArraySizeScale;
6520 int ArrayOffset;
Chris Lattnercfd65102005-10-29 04:36:15 +00006521 Value *NumElements = // See if the array size is a decomposable linear expr.
6522 DecomposeSimpleLinearExpr(AI.getOperand(0), ArraySizeScale, ArrayOffset);
6523
Chris Lattner455fcc82005-10-29 03:19:53 +00006524 // If we can now satisfy the modulus, by using a non-1 scale, we really can
6525 // do the xform.
Chris Lattnercfd65102005-10-29 04:36:15 +00006526 if ((AllocElTySize*ArraySizeScale) % CastElTySize != 0 ||
6527 (AllocElTySize*ArrayOffset ) % CastElTySize != 0) return 0;
Chris Lattner8142b0a2005-10-27 06:12:00 +00006528
Chris Lattner455fcc82005-10-29 03:19:53 +00006529 unsigned Scale = (AllocElTySize*ArraySizeScale)/CastElTySize;
6530 Value *Amt = 0;
6531 if (Scale == 1) {
6532 Amt = NumElements;
6533 } else {
Reid Spencerb83eb642006-10-20 07:07:24 +00006534 // If the allocation size is constant, form a constant mul expression
Reid Spencerc5b206b2006-12-31 05:48:39 +00006535 Amt = ConstantInt::get(Type::Int32Ty, Scale);
6536 if (isa<ConstantInt>(NumElements))
Zhou Sheng4a1822a2007-04-02 13:45:30 +00006537 Amt = Multiply(cast<ConstantInt>(NumElements), cast<ConstantInt>(Amt));
Reid Spencerb83eb642006-10-20 07:07:24 +00006538 // otherwise multiply the amount and the number of elements
Chris Lattner455fcc82005-10-29 03:19:53 +00006539 else if (Scale != 1) {
6540 Instruction *Tmp = BinaryOperator::createMul(Amt, NumElements, "tmp");
6541 Amt = InsertNewInstBefore(Tmp, AI);
Chris Lattner8142b0a2005-10-27 06:12:00 +00006542 }
Chris Lattner0ddac2a2005-10-27 05:53:56 +00006543 }
6544
Jeff Cohen86796be2007-04-04 16:58:57 +00006545 if (int Offset = (AllocElTySize*ArrayOffset)/CastElTySize) {
6546 Value *Off = ConstantInt::get(Type::Int32Ty, Offset, true);
Chris Lattnercfd65102005-10-29 04:36:15 +00006547 Instruction *Tmp = BinaryOperator::createAdd(Amt, Off, "tmp");
6548 Amt = InsertNewInstBefore(Tmp, AI);
6549 }
6550
Chris Lattnerb3f83972005-10-24 06:03:58 +00006551 AllocationInst *New;
6552 if (isa<MallocInst>(AI))
Chris Lattner6934a042007-02-11 01:23:03 +00006553 New = new MallocInst(CastElTy, Amt, AI.getAlignment());
Chris Lattnerb3f83972005-10-24 06:03:58 +00006554 else
Chris Lattner6934a042007-02-11 01:23:03 +00006555 New = new AllocaInst(CastElTy, Amt, AI.getAlignment());
Chris Lattnerb3f83972005-10-24 06:03:58 +00006556 InsertNewInstBefore(New, AI);
Chris Lattner6934a042007-02-11 01:23:03 +00006557 New->takeName(&AI);
Chris Lattner39387a52005-10-24 06:35:18 +00006558
6559 // If the allocation has multiple uses, insert a cast and change all things
6560 // that used it to use the new cast. This will also hack on CI, but it will
6561 // die soon.
6562 if (!AI.hasOneUse()) {
6563 AddUsesToWorkList(AI);
Reid Spencer3da59db2006-11-27 01:05:10 +00006564 // New is the allocation instruction, pointer typed. AI is the original
6565 // allocation instruction, also pointer typed. Thus, cast to use is BitCast.
6566 CastInst *NewCast = new BitCastInst(New, AI.getType(), "tmpcast");
Chris Lattner39387a52005-10-24 06:35:18 +00006567 InsertNewInstBefore(NewCast, AI);
6568 AI.replaceAllUsesWith(NewCast);
6569 }
Chris Lattnerb3f83972005-10-24 06:03:58 +00006570 return ReplaceInstUsesWith(CI, New);
6571}
6572
Chris Lattner70074e02006-05-13 02:06:03 +00006573/// CanEvaluateInDifferentType - Return true if we can take the specified value
Chris Lattnerc739cd62007-03-03 05:27:34 +00006574/// and return it as type Ty without inserting any new casts and without
6575/// changing the computed value. This is used by code that tries to decide
6576/// whether promoting or shrinking integer operations to wider or smaller types
6577/// will allow us to eliminate a truncate or extend.
6578///
6579/// This is a truncation operation if Ty is smaller than V->getType(), or an
6580/// extension operation if Ty is larger.
6581static bool CanEvaluateInDifferentType(Value *V, const IntegerType *Ty,
Chris Lattner951626b2007-08-02 06:11:14 +00006582 unsigned CastOpc, int &NumCastsRemoved) {
Chris Lattnerc739cd62007-03-03 05:27:34 +00006583 // We can always evaluate constants in another type.
6584 if (isa<ConstantInt>(V))
6585 return true;
Chris Lattner70074e02006-05-13 02:06:03 +00006586
6587 Instruction *I = dyn_cast<Instruction>(V);
Chris Lattnerc739cd62007-03-03 05:27:34 +00006588 if (!I) return false;
6589
6590 const IntegerType *OrigTy = cast<IntegerType>(V->getType());
Chris Lattner70074e02006-05-13 02:06:03 +00006591
Chris Lattner951626b2007-08-02 06:11:14 +00006592 // If this is an extension or truncate, we can often eliminate it.
6593 if (isa<TruncInst>(I) || isa<ZExtInst>(I) || isa<SExtInst>(I)) {
6594 // If this is a cast from the destination type, we can trivially eliminate
6595 // it, and this will remove a cast overall.
6596 if (I->getOperand(0)->getType() == Ty) {
6597 // If the first operand is itself a cast, and is eliminable, do not count
6598 // this as an eliminable cast. We would prefer to eliminate those two
6599 // casts first.
6600 if (!isa<CastInst>(I->getOperand(0)))
6601 ++NumCastsRemoved;
6602 return true;
6603 }
6604 }
6605
6606 // We can't extend or shrink something that has multiple uses: doing so would
6607 // require duplicating the instruction in general, which isn't profitable.
6608 if (!I->hasOneUse()) return false;
6609
Chris Lattner70074e02006-05-13 02:06:03 +00006610 switch (I->getOpcode()) {
Chris Lattnerc739cd62007-03-03 05:27:34 +00006611 case Instruction::Add:
6612 case Instruction::Sub:
Chris Lattner70074e02006-05-13 02:06:03 +00006613 case Instruction::And:
6614 case Instruction::Or:
6615 case Instruction::Xor:
6616 // These operators can all arbitrarily be extended or truncated.
Chris Lattner951626b2007-08-02 06:11:14 +00006617 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
6618 NumCastsRemoved) &&
6619 CanEvaluateInDifferentType(I->getOperand(1), Ty, CastOpc,
6620 NumCastsRemoved);
Chris Lattnerc739cd62007-03-03 05:27:34 +00006621
Nick Lewyckye6b0c002008-01-22 05:08:48 +00006622 case Instruction::Mul:
Nick Lewyckye6b0c002008-01-22 05:08:48 +00006623 // A multiply can be truncated by truncating its operands.
6624 return Ty->getBitWidth() < OrigTy->getBitWidth() &&
6625 CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
6626 NumCastsRemoved) &&
6627 CanEvaluateInDifferentType(I->getOperand(1), Ty, CastOpc,
6628 NumCastsRemoved);
6629
Chris Lattner46b96052006-11-29 07:18:39 +00006630 case Instruction::Shl:
Chris Lattnerc739cd62007-03-03 05:27:34 +00006631 // If we are truncating the result of this SHL, and if it's a shift of a
6632 // constant amount, we can always perform a SHL in a smaller type.
6633 if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
Zhou Sheng302748d2007-03-30 17:20:39 +00006634 uint32_t BitWidth = Ty->getBitWidth();
6635 if (BitWidth < OrigTy->getBitWidth() &&
6636 CI->getLimitedValue(BitWidth) < BitWidth)
Chris Lattner951626b2007-08-02 06:11:14 +00006637 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
6638 NumCastsRemoved);
Chris Lattnerc739cd62007-03-03 05:27:34 +00006639 }
6640 break;
6641 case Instruction::LShr:
Chris Lattnerc739cd62007-03-03 05:27:34 +00006642 // If this is a truncate of a logical shr, we can truncate it to a smaller
6643 // lshr iff we know that the bits we would otherwise be shifting in are
6644 // already zeros.
6645 if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
Zhou Sheng302748d2007-03-30 17:20:39 +00006646 uint32_t OrigBitWidth = OrigTy->getBitWidth();
6647 uint32_t BitWidth = Ty->getBitWidth();
6648 if (BitWidth < OrigBitWidth &&
Chris Lattnerc739cd62007-03-03 05:27:34 +00006649 MaskedValueIsZero(I->getOperand(0),
Zhou Sheng302748d2007-03-30 17:20:39 +00006650 APInt::getHighBitsSet(OrigBitWidth, OrigBitWidth-BitWidth)) &&
6651 CI->getLimitedValue(BitWidth) < BitWidth) {
Chris Lattner951626b2007-08-02 06:11:14 +00006652 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
6653 NumCastsRemoved);
Chris Lattnerc739cd62007-03-03 05:27:34 +00006654 }
6655 }
Chris Lattner46b96052006-11-29 07:18:39 +00006656 break;
Reid Spencer3da59db2006-11-27 01:05:10 +00006657 case Instruction::ZExt:
6658 case Instruction::SExt:
Chris Lattner951626b2007-08-02 06:11:14 +00006659 case Instruction::Trunc:
6660 // If this is the same kind of case as our original (e.g. zext+zext), we
Chris Lattner5543a852007-08-02 17:23:38 +00006661 // can safely replace it. Note that replacing it does not reduce the number
6662 // of casts in the input.
6663 if (I->getOpcode() == CastOpc)
Chris Lattner70074e02006-05-13 02:06:03 +00006664 return true;
Chris Lattner50d9d772007-09-10 23:46:29 +00006665
Reid Spencer3da59db2006-11-27 01:05:10 +00006666 break;
6667 default:
Chris Lattner70074e02006-05-13 02:06:03 +00006668 // TODO: Can handle more cases here.
6669 break;
6670 }
6671
6672 return false;
6673}
6674
6675/// EvaluateInDifferentType - Given an expression that
6676/// CanEvaluateInDifferentType returns true for, actually insert the code to
6677/// evaluate the expression.
Reid Spencerc55b2432006-12-13 18:21:21 +00006678Value *InstCombiner::EvaluateInDifferentType(Value *V, const Type *Ty,
Chris Lattnerc739cd62007-03-03 05:27:34 +00006679 bool isSigned) {
Chris Lattner70074e02006-05-13 02:06:03 +00006680 if (Constant *C = dyn_cast<Constant>(V))
Reid Spencerc55b2432006-12-13 18:21:21 +00006681 return ConstantExpr::getIntegerCast(C, Ty, isSigned /*Sext or ZExt*/);
Chris Lattner70074e02006-05-13 02:06:03 +00006682
6683 // Otherwise, it must be an instruction.
6684 Instruction *I = cast<Instruction>(V);
Chris Lattner01859e82006-05-20 23:14:03 +00006685 Instruction *Res = 0;
Chris Lattner70074e02006-05-13 02:06:03 +00006686 switch (I->getOpcode()) {
Chris Lattnerc739cd62007-03-03 05:27:34 +00006687 case Instruction::Add:
6688 case Instruction::Sub:
Nick Lewyckye6b0c002008-01-22 05:08:48 +00006689 case Instruction::Mul:
Chris Lattner70074e02006-05-13 02:06:03 +00006690 case Instruction::And:
6691 case Instruction::Or:
Chris Lattnerc739cd62007-03-03 05:27:34 +00006692 case Instruction::Xor:
Chris Lattner46b96052006-11-29 07:18:39 +00006693 case Instruction::AShr:
6694 case Instruction::LShr:
6695 case Instruction::Shl: {
Reid Spencerc55b2432006-12-13 18:21:21 +00006696 Value *LHS = EvaluateInDifferentType(I->getOperand(0), Ty, isSigned);
Chris Lattnerc739cd62007-03-03 05:27:34 +00006697 Value *RHS = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned);
6698 Res = BinaryOperator::create((Instruction::BinaryOps)I->getOpcode(),
6699 LHS, RHS, I->getName());
Chris Lattner46b96052006-11-29 07:18:39 +00006700 break;
6701 }
Reid Spencer3da59db2006-11-27 01:05:10 +00006702 case Instruction::Trunc:
6703 case Instruction::ZExt:
6704 case Instruction::SExt:
Reid Spencer3da59db2006-11-27 01:05:10 +00006705 // If the source type of the cast is the type we're trying for then we can
Chris Lattner951626b2007-08-02 06:11:14 +00006706 // just return the source. There's no need to insert it because it is not
6707 // new.
Chris Lattner70074e02006-05-13 02:06:03 +00006708 if (I->getOperand(0)->getType() == Ty)
6709 return I->getOperand(0);
6710
Chris Lattner951626b2007-08-02 06:11:14 +00006711 // Otherwise, must be the same type of case, so just reinsert a new one.
6712 Res = CastInst::create(cast<CastInst>(I)->getOpcode(), I->getOperand(0),
6713 Ty, I->getName());
6714 break;
Reid Spencer3da59db2006-11-27 01:05:10 +00006715 default:
Chris Lattner70074e02006-05-13 02:06:03 +00006716 // TODO: Can handle more cases here.
6717 assert(0 && "Unreachable!");
6718 break;
6719 }
6720
6721 return InsertNewInstBefore(Res, *I);
6722}
6723
Reid Spencer3da59db2006-11-27 01:05:10 +00006724/// @brief Implement the transforms common to all CastInst visitors.
6725Instruction *InstCombiner::commonCastTransforms(CastInst &CI) {
Chris Lattner79d35b32003-06-23 21:59:52 +00006726 Value *Src = CI.getOperand(0);
6727
Dan Gohman23d9d272007-05-11 21:10:54 +00006728 // Many cases of "cast of a cast" are eliminable. If it's eliminable we just
Reid Spencer3da59db2006-11-27 01:05:10 +00006729 // eliminate it now.
Chris Lattner6e7ba452005-01-01 16:22:27 +00006730 if (CastInst *CSrc = dyn_cast<CastInst>(Src)) { // A->B->C cast
Reid Spencer3da59db2006-11-27 01:05:10 +00006731 if (Instruction::CastOps opc =
6732 isEliminableCastPair(CSrc, CI.getOpcode(), CI.getType(), TD)) {
6733 // The first cast (CSrc) is eliminable so we need to fix up or replace
6734 // the second cast (CI). CSrc will then have a good chance of being dead.
6735 return CastInst::create(opc, CSrc->getOperand(0), CI.getType());
Chris Lattner8fd217c2002-08-02 20:00:25 +00006736 }
6737 }
Chris Lattnera710ddc2004-05-25 04:29:21 +00006738
Reid Spencer3da59db2006-11-27 01:05:10 +00006739 // If we are casting a select then fold the cast into the select
Chris Lattner6e7ba452005-01-01 16:22:27 +00006740 if (SelectInst *SI = dyn_cast<SelectInst>(Src))
6741 if (Instruction *NV = FoldOpIntoSelect(CI, SI, this))
6742 return NV;
Reid Spencer3da59db2006-11-27 01:05:10 +00006743
6744 // If we are casting a PHI then fold the cast into the PHI
Chris Lattner4e998b22004-09-29 05:07:12 +00006745 if (isa<PHINode>(Src))
6746 if (Instruction *NV = FoldOpIntoPhi(CI))
6747 return NV;
Chris Lattner9fb92132006-04-12 18:09:35 +00006748
Reid Spencer3da59db2006-11-27 01:05:10 +00006749 return 0;
6750}
6751
Chris Lattnerd3e28342007-04-27 17:44:50 +00006752/// @brief Implement the transforms for cast of pointer (bitcast/ptrtoint)
6753Instruction *InstCombiner::commonPointerCastTransforms(CastInst &CI) {
6754 Value *Src = CI.getOperand(0);
6755
Chris Lattnerd3e28342007-04-27 17:44:50 +00006756 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Src)) {
Chris Lattner9bc14642007-04-28 00:57:34 +00006757 // If casting the result of a getelementptr instruction with no offset, turn
6758 // this into a cast of the original pointer!
Chris Lattnerd3e28342007-04-27 17:44:50 +00006759 if (GEP->hasAllZeroIndices()) {
6760 // Changing the cast operand is usually not a good idea but it is safe
6761 // here because the pointer operand is being replaced with another
6762 // pointer operand so the opcode doesn't need to change.
Chris Lattner9bc14642007-04-28 00:57:34 +00006763 AddToWorkList(GEP);
Chris Lattnerd3e28342007-04-27 17:44:50 +00006764 CI.setOperand(0, GEP->getOperand(0));
6765 return &CI;
6766 }
Chris Lattner9bc14642007-04-28 00:57:34 +00006767
6768 // If the GEP has a single use, and the base pointer is a bitcast, and the
6769 // GEP computes a constant offset, see if we can convert these three
6770 // instructions into fewer. This typically happens with unions and other
6771 // non-type-safe code.
6772 if (GEP->hasOneUse() && isa<BitCastInst>(GEP->getOperand(0))) {
6773 if (GEP->hasAllConstantIndices()) {
6774 // We are guaranteed to get a constant from EmitGEPOffset.
6775 ConstantInt *OffsetV = cast<ConstantInt>(EmitGEPOffset(GEP, CI, *this));
6776 int64_t Offset = OffsetV->getSExtValue();
6777
6778 // Get the base pointer input of the bitcast, and the type it points to.
6779 Value *OrigBase = cast<BitCastInst>(GEP->getOperand(0))->getOperand(0);
6780 const Type *GEPIdxTy =
6781 cast<PointerType>(OrigBase->getType())->getElementType();
6782 if (GEPIdxTy->isSized()) {
6783 SmallVector<Value*, 8> NewIndices;
6784
Chris Lattnerc42e2262007-05-05 01:59:31 +00006785 // Start with the index over the outer type. Note that the type size
6786 // might be zero (even if the offset isn't zero) if the indexed type
6787 // is something like [0 x {int, int}]
Chris Lattner9bc14642007-04-28 00:57:34 +00006788 const Type *IntPtrTy = TD->getIntPtrType();
Chris Lattnerc42e2262007-05-05 01:59:31 +00006789 int64_t FirstIdx = 0;
Duncan Sands514ab342007-11-01 20:53:16 +00006790 if (int64_t TySize = TD->getABITypeSize(GEPIdxTy)) {
Chris Lattnerc42e2262007-05-05 01:59:31 +00006791 FirstIdx = Offset/TySize;
6792 Offset %= TySize;
Chris Lattner9bc14642007-04-28 00:57:34 +00006793
Chris Lattnerc42e2262007-05-05 01:59:31 +00006794 // Handle silly modulus not returning values values [0..TySize).
6795 if (Offset < 0) {
6796 --FirstIdx;
6797 Offset += TySize;
6798 assert(Offset >= 0);
6799 }
Chris Lattnerd717c182007-05-05 22:32:24 +00006800 assert((uint64_t)Offset < (uint64_t)TySize &&"Out of range offset");
Chris Lattner9bc14642007-04-28 00:57:34 +00006801 }
6802
6803 NewIndices.push_back(ConstantInt::get(IntPtrTy, FirstIdx));
Chris Lattner9bc14642007-04-28 00:57:34 +00006804
6805 // Index into the types. If we fail, set OrigBase to null.
6806 while (Offset) {
6807 if (const StructType *STy = dyn_cast<StructType>(GEPIdxTy)) {
6808 const StructLayout *SL = TD->getStructLayout(STy);
Chris Lattner6b6aef82007-05-15 00:16:00 +00006809 if (Offset < (int64_t)SL->getSizeInBytes()) {
6810 unsigned Elt = SL->getElementContainingOffset(Offset);
6811 NewIndices.push_back(ConstantInt::get(Type::Int32Ty, Elt));
Chris Lattner9bc14642007-04-28 00:57:34 +00006812
Chris Lattner6b6aef82007-05-15 00:16:00 +00006813 Offset -= SL->getElementOffset(Elt);
6814 GEPIdxTy = STy->getElementType(Elt);
6815 } else {
6816 // Otherwise, we can't index into this, bail out.
6817 Offset = 0;
6818 OrigBase = 0;
6819 }
Chris Lattner9bc14642007-04-28 00:57:34 +00006820 } else if (isa<ArrayType>(GEPIdxTy) || isa<VectorType>(GEPIdxTy)) {
6821 const SequentialType *STy = cast<SequentialType>(GEPIdxTy);
Duncan Sands514ab342007-11-01 20:53:16 +00006822 if (uint64_t EltSize = TD->getABITypeSize(STy->getElementType())){
Chris Lattner6b6aef82007-05-15 00:16:00 +00006823 NewIndices.push_back(ConstantInt::get(IntPtrTy,Offset/EltSize));
6824 Offset %= EltSize;
6825 } else {
6826 NewIndices.push_back(ConstantInt::get(IntPtrTy, 0));
6827 }
Chris Lattner9bc14642007-04-28 00:57:34 +00006828 GEPIdxTy = STy->getElementType();
6829 } else {
6830 // Otherwise, we can't index into this, bail out.
6831 Offset = 0;
6832 OrigBase = 0;
6833 }
6834 }
6835 if (OrigBase) {
6836 // If we were able to index down into an element, create the GEP
6837 // and bitcast the result. This eliminates one bitcast, potentially
6838 // two.
David Greeneb8f74792007-09-04 15:46:09 +00006839 Instruction *NGEP = new GetElementPtrInst(OrigBase,
6840 NewIndices.begin(),
6841 NewIndices.end(), "");
Chris Lattner9bc14642007-04-28 00:57:34 +00006842 InsertNewInstBefore(NGEP, CI);
6843 NGEP->takeName(GEP);
6844
Chris Lattner9bc14642007-04-28 00:57:34 +00006845 if (isa<BitCastInst>(CI))
6846 return new BitCastInst(NGEP, CI.getType());
6847 assert(isa<PtrToIntInst>(CI));
6848 return new PtrToIntInst(NGEP, CI.getType());
6849 }
6850 }
6851 }
6852 }
Chris Lattnerd3e28342007-04-27 17:44:50 +00006853 }
6854
6855 return commonCastTransforms(CI);
6856}
6857
6858
6859
Chris Lattnerc739cd62007-03-03 05:27:34 +00006860/// Only the TRUNC, ZEXT, SEXT, and BITCAST can both operand and result as
6861/// integer types. This function implements the common transforms for all those
Reid Spencer3da59db2006-11-27 01:05:10 +00006862/// cases.
6863/// @brief Implement the transforms common to CastInst with integer operands
6864Instruction *InstCombiner::commonIntCastTransforms(CastInst &CI) {
6865 if (Instruction *Result = commonCastTransforms(CI))
6866 return Result;
6867
6868 Value *Src = CI.getOperand(0);
6869 const Type *SrcTy = Src->getType();
6870 const Type *DestTy = CI.getType();
Zhou Sheng4351c642007-04-02 08:20:41 +00006871 uint32_t SrcBitSize = SrcTy->getPrimitiveSizeInBits();
6872 uint32_t DestBitSize = DestTy->getPrimitiveSizeInBits();
Reid Spencer3da59db2006-11-27 01:05:10 +00006873
Reid Spencer3da59db2006-11-27 01:05:10 +00006874 // See if we can simplify any instructions used by the LHS whose sole
6875 // purpose is to compute bits we don't care about.
Reid Spencerad6676e2007-03-22 20:56:53 +00006876 APInt KnownZero(DestBitSize, 0), KnownOne(DestBitSize, 0);
6877 if (SimplifyDemandedBits(&CI, APInt::getAllOnesValue(DestBitSize),
Reid Spencer3da59db2006-11-27 01:05:10 +00006878 KnownZero, KnownOne))
6879 return &CI;
6880
6881 // If the source isn't an instruction or has more than one use then we
6882 // can't do anything more.
Reid Spencere4d87aa2006-12-23 06:05:41 +00006883 Instruction *SrcI = dyn_cast<Instruction>(Src);
6884 if (!SrcI || !Src->hasOneUse())
Reid Spencer3da59db2006-11-27 01:05:10 +00006885 return 0;
6886
Chris Lattnerc739cd62007-03-03 05:27:34 +00006887 // Attempt to propagate the cast into the instruction for int->int casts.
Reid Spencer3da59db2006-11-27 01:05:10 +00006888 int NumCastsRemoved = 0;
Chris Lattnerc739cd62007-03-03 05:27:34 +00006889 if (!isa<BitCastInst>(CI) &&
6890 CanEvaluateInDifferentType(SrcI, cast<IntegerType>(DestTy),
Chris Lattner951626b2007-08-02 06:11:14 +00006891 CI.getOpcode(), NumCastsRemoved)) {
Reid Spencer3da59db2006-11-27 01:05:10 +00006892 // If this cast is a truncate, evaluting in a different type always
Chris Lattner951626b2007-08-02 06:11:14 +00006893 // eliminates the cast, so it is always a win. If this is a zero-extension,
6894 // we need to do an AND to maintain the clear top-part of the computation,
6895 // so we require that the input have eliminated at least one cast. If this
6896 // is a sign extension, we insert two new casts (to do the extension) so we
Reid Spencer3da59db2006-11-27 01:05:10 +00006897 // require that two casts have been eliminated.
Chris Lattnerc739cd62007-03-03 05:27:34 +00006898 bool DoXForm;
6899 switch (CI.getOpcode()) {
6900 default:
6901 // All the others use floating point so we shouldn't actually
6902 // get here because of the check above.
6903 assert(0 && "Unknown cast type");
6904 case Instruction::Trunc:
6905 DoXForm = true;
6906 break;
6907 case Instruction::ZExt:
6908 DoXForm = NumCastsRemoved >= 1;
6909 break;
6910 case Instruction::SExt:
6911 DoXForm = NumCastsRemoved >= 2;
6912 break;
Reid Spencer3da59db2006-11-27 01:05:10 +00006913 }
6914
6915 if (DoXForm) {
Reid Spencerc55b2432006-12-13 18:21:21 +00006916 Value *Res = EvaluateInDifferentType(SrcI, DestTy,
6917 CI.getOpcode() == Instruction::SExt);
Reid Spencer3da59db2006-11-27 01:05:10 +00006918 assert(Res->getType() == DestTy);
6919 switch (CI.getOpcode()) {
6920 default: assert(0 && "Unknown cast type!");
6921 case Instruction::Trunc:
6922 case Instruction::BitCast:
6923 // Just replace this cast with the result.
6924 return ReplaceInstUsesWith(CI, Res);
6925 case Instruction::ZExt: {
6926 // We need to emit an AND to clear the high bits.
6927 assert(SrcBitSize < DestBitSize && "Not a zext?");
Chris Lattnercd1d6d52007-04-02 05:48:58 +00006928 Constant *C = ConstantInt::get(APInt::getLowBitsSet(DestBitSize,
6929 SrcBitSize));
Reid Spencer3da59db2006-11-27 01:05:10 +00006930 return BinaryOperator::createAnd(Res, C);
6931 }
6932 case Instruction::SExt:
6933 // We need to emit a cast to truncate, then a cast to sext.
6934 return CastInst::create(Instruction::SExt,
Reid Spencer17212df2006-12-12 09:18:51 +00006935 InsertCastBefore(Instruction::Trunc, Res, Src->getType(),
6936 CI), DestTy);
Reid Spencer3da59db2006-11-27 01:05:10 +00006937 }
6938 }
6939 }
6940
6941 Value *Op0 = SrcI->getNumOperands() > 0 ? SrcI->getOperand(0) : 0;
6942 Value *Op1 = SrcI->getNumOperands() > 1 ? SrcI->getOperand(1) : 0;
6943
6944 switch (SrcI->getOpcode()) {
6945 case Instruction::Add:
6946 case Instruction::Mul:
6947 case Instruction::And:
6948 case Instruction::Or:
6949 case Instruction::Xor:
Chris Lattner01deb9d2007-04-03 17:43:25 +00006950 // If we are discarding information, rewrite.
Reid Spencer3da59db2006-11-27 01:05:10 +00006951 if (DestBitSize <= SrcBitSize && DestBitSize != 1) {
6952 // Don't insert two casts if they cannot be eliminated. We allow
6953 // two casts to be inserted if the sizes are the same. This could
6954 // only be converting signedness, which is a noop.
6955 if (DestBitSize == SrcBitSize ||
Reid Spencere4d87aa2006-12-23 06:05:41 +00006956 !ValueRequiresCast(CI.getOpcode(), Op1, DestTy,TD) ||
6957 !ValueRequiresCast(CI.getOpcode(), Op0, DestTy, TD)) {
Reid Spencer7eb76382006-12-13 17:19:09 +00006958 Instruction::CastOps opcode = CI.getOpcode();
Reid Spencer17212df2006-12-12 09:18:51 +00006959 Value *Op0c = InsertOperandCastBefore(opcode, Op0, DestTy, SrcI);
6960 Value *Op1c = InsertOperandCastBefore(opcode, Op1, DestTy, SrcI);
6961 return BinaryOperator::create(
6962 cast<BinaryOperator>(SrcI)->getOpcode(), Op0c, Op1c);
Reid Spencer3da59db2006-11-27 01:05:10 +00006963 }
6964 }
6965
6966 // cast (xor bool X, true) to int --> xor (cast bool X to int), 1
6967 if (isa<ZExtInst>(CI) && SrcBitSize == 1 &&
6968 SrcI->getOpcode() == Instruction::Xor &&
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00006969 Op1 == ConstantInt::getTrue() &&
Reid Spencere4d87aa2006-12-23 06:05:41 +00006970 (!Op0->hasOneUse() || !isa<CmpInst>(Op0))) {
Reid Spencer17212df2006-12-12 09:18:51 +00006971 Value *New = InsertOperandCastBefore(Instruction::ZExt, Op0, DestTy, &CI);
Reid Spencer3da59db2006-11-27 01:05:10 +00006972 return BinaryOperator::createXor(New, ConstantInt::get(CI.getType(), 1));
6973 }
6974 break;
6975 case Instruction::SDiv:
6976 case Instruction::UDiv:
6977 case Instruction::SRem:
6978 case Instruction::URem:
6979 // If we are just changing the sign, rewrite.
6980 if (DestBitSize == SrcBitSize) {
6981 // Don't insert two casts if they cannot be eliminated. We allow
6982 // two casts to be inserted if the sizes are the same. This could
6983 // only be converting signedness, which is a noop.
Reid Spencere4d87aa2006-12-23 06:05:41 +00006984 if (!ValueRequiresCast(CI.getOpcode(), Op1, DestTy, TD) ||
6985 !ValueRequiresCast(CI.getOpcode(), Op0, DestTy, TD)) {
Reid Spencer17212df2006-12-12 09:18:51 +00006986 Value *Op0c = InsertOperandCastBefore(Instruction::BitCast,
6987 Op0, DestTy, SrcI);
6988 Value *Op1c = InsertOperandCastBefore(Instruction::BitCast,
6989 Op1, DestTy, SrcI);
Reid Spencer3da59db2006-11-27 01:05:10 +00006990 return BinaryOperator::create(
6991 cast<BinaryOperator>(SrcI)->getOpcode(), Op0c, Op1c);
6992 }
6993 }
6994 break;
6995
6996 case Instruction::Shl:
6997 // Allow changing the sign of the source operand. Do not allow
6998 // changing the size of the shift, UNLESS the shift amount is a
6999 // constant. We must not change variable sized shifts to a smaller
7000 // size, because it is undefined to shift more bits out than exist
7001 // in the value.
7002 if (DestBitSize == SrcBitSize ||
7003 (DestBitSize < SrcBitSize && isa<Constant>(Op1))) {
Reid Spencer17212df2006-12-12 09:18:51 +00007004 Instruction::CastOps opcode = (DestBitSize == SrcBitSize ?
7005 Instruction::BitCast : Instruction::Trunc);
7006 Value *Op0c = InsertOperandCastBefore(opcode, Op0, DestTy, SrcI);
Reid Spencer832254e2007-02-02 02:16:23 +00007007 Value *Op1c = InsertOperandCastBefore(opcode, Op1, DestTy, SrcI);
Reid Spencercc46cdb2007-02-02 14:08:20 +00007008 return BinaryOperator::createShl(Op0c, Op1c);
Reid Spencer3da59db2006-11-27 01:05:10 +00007009 }
7010 break;
7011 case Instruction::AShr:
7012 // If this is a signed shr, and if all bits shifted in are about to be
7013 // truncated off, turn it into an unsigned shr to allow greater
7014 // simplifications.
7015 if (DestBitSize < SrcBitSize &&
7016 isa<ConstantInt>(Op1)) {
Zhou Sheng302748d2007-03-30 17:20:39 +00007017 uint32_t ShiftAmt = cast<ConstantInt>(Op1)->getLimitedValue(SrcBitSize);
Reid Spencer3da59db2006-11-27 01:05:10 +00007018 if (SrcBitSize > ShiftAmt && SrcBitSize-ShiftAmt >= DestBitSize) {
7019 // Insert the new logical shift right.
Reid Spencercc46cdb2007-02-02 14:08:20 +00007020 return BinaryOperator::createLShr(Op0, Op1);
Reid Spencer3da59db2006-11-27 01:05:10 +00007021 }
7022 }
7023 break;
Reid Spencer3da59db2006-11-27 01:05:10 +00007024 }
7025 return 0;
7026}
7027
Chris Lattner8a9f5712007-04-11 06:57:46 +00007028Instruction *InstCombiner::visitTrunc(TruncInst &CI) {
Chris Lattner6aa5eb12006-11-29 07:04:07 +00007029 if (Instruction *Result = commonIntCastTransforms(CI))
7030 return Result;
7031
7032 Value *Src = CI.getOperand(0);
7033 const Type *Ty = CI.getType();
Zhou Sheng4351c642007-04-02 08:20:41 +00007034 uint32_t DestBitWidth = Ty->getPrimitiveSizeInBits();
7035 uint32_t SrcBitWidth = cast<IntegerType>(Src->getType())->getBitWidth();
Chris Lattner6aa5eb12006-11-29 07:04:07 +00007036
7037 if (Instruction *SrcI = dyn_cast<Instruction>(Src)) {
7038 switch (SrcI->getOpcode()) {
7039 default: break;
7040 case Instruction::LShr:
7041 // We can shrink lshr to something smaller if we know the bits shifted in
7042 // are already zeros.
7043 if (ConstantInt *ShAmtV = dyn_cast<ConstantInt>(SrcI->getOperand(1))) {
Zhou Sheng302748d2007-03-30 17:20:39 +00007044 uint32_t ShAmt = ShAmtV->getLimitedValue(SrcBitWidth);
Chris Lattner6aa5eb12006-11-29 07:04:07 +00007045
7046 // Get a mask for the bits shifting in.
Zhou Shenge82fca02007-03-28 09:19:01 +00007047 APInt Mask(APInt::getLowBitsSet(SrcBitWidth, ShAmt).shl(DestBitWidth));
Reid Spencer17212df2006-12-12 09:18:51 +00007048 Value* SrcIOp0 = SrcI->getOperand(0);
7049 if (SrcI->hasOneUse() && MaskedValueIsZero(SrcIOp0, Mask)) {
Chris Lattner6aa5eb12006-11-29 07:04:07 +00007050 if (ShAmt >= DestBitWidth) // All zeros.
7051 return ReplaceInstUsesWith(CI, Constant::getNullValue(Ty));
7052
7053 // Okay, we can shrink this. Truncate the input, then return a new
7054 // shift.
Reid Spencer832254e2007-02-02 02:16:23 +00007055 Value *V1 = InsertCastBefore(Instruction::Trunc, SrcIOp0, Ty, CI);
7056 Value *V2 = InsertCastBefore(Instruction::Trunc, SrcI->getOperand(1),
7057 Ty, CI);
Reid Spencercc46cdb2007-02-02 14:08:20 +00007058 return BinaryOperator::createLShr(V1, V2);
Chris Lattner6aa5eb12006-11-29 07:04:07 +00007059 }
Chris Lattnere13ab2a2006-12-05 01:26:29 +00007060 } else { // This is a variable shr.
7061
7062 // Turn 'trunc (lshr X, Y) to bool' into '(X & (1 << Y)) != 0'. This is
7063 // more LLVM instructions, but allows '1 << Y' to be hoisted if
7064 // loop-invariant and CSE'd.
Reid Spencer4fe16d62007-01-11 18:21:29 +00007065 if (CI.getType() == Type::Int1Ty && SrcI->hasOneUse()) {
Chris Lattnere13ab2a2006-12-05 01:26:29 +00007066 Value *One = ConstantInt::get(SrcI->getType(), 1);
7067
Reid Spencer832254e2007-02-02 02:16:23 +00007068 Value *V = InsertNewInstBefore(
Reid Spencercc46cdb2007-02-02 14:08:20 +00007069 BinaryOperator::createShl(One, SrcI->getOperand(1),
Reid Spencer832254e2007-02-02 02:16:23 +00007070 "tmp"), CI);
Chris Lattnere13ab2a2006-12-05 01:26:29 +00007071 V = InsertNewInstBefore(BinaryOperator::createAnd(V,
7072 SrcI->getOperand(0),
7073 "tmp"), CI);
7074 Value *Zero = Constant::getNullValue(V->getType());
Reid Spencere4d87aa2006-12-23 06:05:41 +00007075 return new ICmpInst(ICmpInst::ICMP_NE, V, Zero);
Chris Lattnere13ab2a2006-12-05 01:26:29 +00007076 }
Chris Lattner6aa5eb12006-11-29 07:04:07 +00007077 }
7078 break;
7079 }
7080 }
7081
7082 return 0;
Reid Spencer3da59db2006-11-27 01:05:10 +00007083}
7084
Chris Lattner8a9f5712007-04-11 06:57:46 +00007085Instruction *InstCombiner::visitZExt(ZExtInst &CI) {
Reid Spencer3da59db2006-11-27 01:05:10 +00007086 // If one of the common conversion will work ..
7087 if (Instruction *Result = commonIntCastTransforms(CI))
7088 return Result;
7089
7090 Value *Src = CI.getOperand(0);
7091
7092 // If this is a cast of a cast
7093 if (CastInst *CSrc = dyn_cast<CastInst>(Src)) { // A->B->C cast
Reid Spencer3da59db2006-11-27 01:05:10 +00007094 // If this is a TRUNC followed by a ZEXT then we are dealing with integral
7095 // types and if the sizes are just right we can convert this into a logical
7096 // 'and' which will be much cheaper than the pair of casts.
7097 if (isa<TruncInst>(CSrc)) {
7098 // Get the sizes of the types involved
7099 Value *A = CSrc->getOperand(0);
Zhou Sheng4351c642007-04-02 08:20:41 +00007100 uint32_t SrcSize = A->getType()->getPrimitiveSizeInBits();
7101 uint32_t MidSize = CSrc->getType()->getPrimitiveSizeInBits();
7102 uint32_t DstSize = CI.getType()->getPrimitiveSizeInBits();
Reid Spencer3da59db2006-11-27 01:05:10 +00007103 // If we're actually extending zero bits and the trunc is a no-op
7104 if (MidSize < DstSize && SrcSize == DstSize) {
7105 // Replace both of the casts with an And of the type mask.
Zhou Shenge82fca02007-03-28 09:19:01 +00007106 APInt AndValue(APInt::getLowBitsSet(SrcSize, MidSize));
Reid Spencerad6676e2007-03-22 20:56:53 +00007107 Constant *AndConst = ConstantInt::get(AndValue);
Reid Spencer3da59db2006-11-27 01:05:10 +00007108 Instruction *And =
7109 BinaryOperator::createAnd(CSrc->getOperand(0), AndConst);
7110 // Unfortunately, if the type changed, we need to cast it back.
7111 if (And->getType() != CI.getType()) {
7112 And->setName(CSrc->getName()+".mask");
7113 InsertNewInstBefore(And, CI);
Reid Spencerd977d862006-12-12 23:36:14 +00007114 And = CastInst::createIntegerCast(And, CI.getType(), false/*ZExt*/);
Reid Spencer3da59db2006-11-27 01:05:10 +00007115 }
7116 return And;
7117 }
7118 }
7119 }
7120
Chris Lattner66bc3252007-04-11 05:45:39 +00007121 if (ICmpInst *ICI = dyn_cast<ICmpInst>(Src)) {
7122 // If we are just checking for a icmp eq of a single bit and zext'ing it
7123 // to an integer, then shift the bit to the appropriate place and then
7124 // cast to integer to avoid the comparison.
7125 if (ConstantInt *Op1C = dyn_cast<ConstantInt>(ICI->getOperand(1))) {
Chris Lattnerba417832007-04-11 06:12:58 +00007126 const APInt &Op1CV = Op1C->getValue();
Chris Lattnera2e2c9b2007-04-11 06:53:04 +00007127
7128 // zext (x <s 0) to i32 --> x>>u31 true if signbit set.
7129 // zext (x >s -1) to i32 --> (x>>u31)^1 true if signbit clear.
7130 if ((ICI->getPredicate() == ICmpInst::ICMP_SLT && Op1CV == 0) ||
7131 (ICI->getPredicate() == ICmpInst::ICMP_SGT &&Op1CV.isAllOnesValue())){
7132 Value *In = ICI->getOperand(0);
7133 Value *Sh = ConstantInt::get(In->getType(),
7134 In->getType()->getPrimitiveSizeInBits()-1);
7135 In = InsertNewInstBefore(BinaryOperator::createLShr(In, Sh,
Chris Lattnere34e9a22007-04-14 23:32:02 +00007136 In->getName()+".lobit"),
Chris Lattnera2e2c9b2007-04-11 06:53:04 +00007137 CI);
7138 if (In->getType() != CI.getType())
7139 In = CastInst::createIntegerCast(In, CI.getType(),
7140 false/*ZExt*/, "tmp", &CI);
7141
7142 if (ICI->getPredicate() == ICmpInst::ICMP_SGT) {
7143 Constant *One = ConstantInt::get(In->getType(), 1);
7144 In = InsertNewInstBefore(BinaryOperator::createXor(In, One,
Chris Lattnere34e9a22007-04-14 23:32:02 +00007145 In->getName()+".not"),
Chris Lattnera2e2c9b2007-04-11 06:53:04 +00007146 CI);
7147 }
7148
7149 return ReplaceInstUsesWith(CI, In);
7150 }
7151
7152
7153
Chris Lattnerba417832007-04-11 06:12:58 +00007154 // zext (X == 0) to i32 --> X^1 iff X has only the low bit set.
7155 // zext (X == 0) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
7156 // zext (X == 1) to i32 --> X iff X has only the low bit set.
7157 // zext (X == 2) to i32 --> X>>1 iff X has only the 2nd bit set.
7158 // zext (X != 0) to i32 --> X iff X has only the low bit set.
7159 // zext (X != 0) to i32 --> X>>1 iff X has only the 2nd bit set.
7160 // zext (X != 1) to i32 --> X^1 iff X has only the low bit set.
7161 // zext (X != 2) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
Chris Lattner66bc3252007-04-11 05:45:39 +00007162 if ((Op1CV == 0 || Op1CV.isPowerOf2()) &&
7163 // This only works for EQ and NE
7164 ICI->isEquality()) {
7165 // If Op1C some other power of two, convert:
7166 uint32_t BitWidth = Op1C->getType()->getBitWidth();
7167 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
7168 APInt TypeMask(APInt::getAllOnesValue(BitWidth));
7169 ComputeMaskedBits(ICI->getOperand(0), TypeMask, KnownZero, KnownOne);
7170
7171 APInt KnownZeroMask(~KnownZero);
7172 if (KnownZeroMask.isPowerOf2()) { // Exactly 1 possible 1?
7173 bool isNE = ICI->getPredicate() == ICmpInst::ICMP_NE;
7174 if (Op1CV != 0 && (Op1CV != KnownZeroMask)) {
7175 // (X&4) == 2 --> false
7176 // (X&4) != 2 --> true
7177 Constant *Res = ConstantInt::get(Type::Int1Ty, isNE);
7178 Res = ConstantExpr::getZExt(Res, CI.getType());
7179 return ReplaceInstUsesWith(CI, Res);
7180 }
7181
7182 uint32_t ShiftAmt = KnownZeroMask.logBase2();
7183 Value *In = ICI->getOperand(0);
7184 if (ShiftAmt) {
7185 // Perform a logical shr by shiftamt.
7186 // Insert the shift to put the result in the low bit.
7187 In = InsertNewInstBefore(
7188 BinaryOperator::createLShr(In,
7189 ConstantInt::get(In->getType(), ShiftAmt),
7190 In->getName()+".lobit"), CI);
7191 }
7192
7193 if ((Op1CV != 0) == isNE) { // Toggle the low bit.
7194 Constant *One = ConstantInt::get(In->getType(), 1);
7195 In = BinaryOperator::createXor(In, One, "tmp");
7196 InsertNewInstBefore(cast<Instruction>(In), CI);
7197 }
7198
7199 if (CI.getType() == In->getType())
7200 return ReplaceInstUsesWith(CI, In);
7201 else
7202 return CastInst::createIntegerCast(In, CI.getType(), false/*ZExt*/);
7203 }
7204 }
7205 }
7206 }
Reid Spencer3da59db2006-11-27 01:05:10 +00007207 return 0;
7208}
7209
Chris Lattner8a9f5712007-04-11 06:57:46 +00007210Instruction *InstCombiner::visitSExt(SExtInst &CI) {
Chris Lattnerba417832007-04-11 06:12:58 +00007211 if (Instruction *I = commonIntCastTransforms(CI))
7212 return I;
7213
Chris Lattner8a9f5712007-04-11 06:57:46 +00007214 Value *Src = CI.getOperand(0);
7215
7216 // sext (x <s 0) -> ashr x, 31 -> all ones if signed
7217 // sext (x >s -1) -> ashr x, 31 -> all ones if not signed
7218 if (ICmpInst *ICI = dyn_cast<ICmpInst>(Src)) {
7219 // If we are just checking for a icmp eq of a single bit and zext'ing it
7220 // to an integer, then shift the bit to the appropriate place and then
7221 // cast to integer to avoid the comparison.
7222 if (ConstantInt *Op1C = dyn_cast<ConstantInt>(ICI->getOperand(1))) {
7223 const APInt &Op1CV = Op1C->getValue();
7224
7225 // sext (x <s 0) to i32 --> x>>s31 true if signbit set.
7226 // sext (x >s -1) to i32 --> (x>>s31)^-1 true if signbit clear.
7227 if ((ICI->getPredicate() == ICmpInst::ICMP_SLT && Op1CV == 0) ||
7228 (ICI->getPredicate() == ICmpInst::ICMP_SGT &&Op1CV.isAllOnesValue())){
7229 Value *In = ICI->getOperand(0);
7230 Value *Sh = ConstantInt::get(In->getType(),
7231 In->getType()->getPrimitiveSizeInBits()-1);
7232 In = InsertNewInstBefore(BinaryOperator::createAShr(In, Sh,
Chris Lattnere34e9a22007-04-14 23:32:02 +00007233 In->getName()+".lobit"),
Chris Lattner8a9f5712007-04-11 06:57:46 +00007234 CI);
7235 if (In->getType() != CI.getType())
7236 In = CastInst::createIntegerCast(In, CI.getType(),
7237 true/*SExt*/, "tmp", &CI);
7238
7239 if (ICI->getPredicate() == ICmpInst::ICMP_SGT)
7240 In = InsertNewInstBefore(BinaryOperator::createNot(In,
7241 In->getName()+".not"), CI);
7242
7243 return ReplaceInstUsesWith(CI, In);
7244 }
7245 }
7246 }
7247
Chris Lattnerba417832007-04-11 06:12:58 +00007248 return 0;
Reid Spencer3da59db2006-11-27 01:05:10 +00007249}
7250
Chris Lattnerb7530652008-01-27 05:29:54 +00007251/// FitsInFPType - Return a Constant* for the specified FP constant if it fits
7252/// in the specified FP type without changing its value.
7253static Constant *FitsInFPType(ConstantFP *CFP, const Type *FPTy,
7254 const fltSemantics &Sem) {
7255 APFloat F = CFP->getValueAPF();
7256 if (F.convert(Sem, APFloat::rmNearestTiesToEven) == APFloat::opOK)
7257 return ConstantFP::get(FPTy, F);
7258 return 0;
7259}
7260
7261/// LookThroughFPExtensions - If this is an fp extension instruction, look
7262/// through it until we get the source value.
7263static Value *LookThroughFPExtensions(Value *V) {
7264 if (Instruction *I = dyn_cast<Instruction>(V))
7265 if (I->getOpcode() == Instruction::FPExt)
7266 return LookThroughFPExtensions(I->getOperand(0));
7267
7268 // If this value is a constant, return the constant in the smallest FP type
7269 // that can accurately represent it. This allows us to turn
7270 // (float)((double)X+2.0) into x+2.0f.
7271 if (ConstantFP *CFP = dyn_cast<ConstantFP>(V)) {
7272 if (CFP->getType() == Type::PPC_FP128Ty)
7273 return V; // No constant folding of this.
7274 // See if the value can be truncated to float and then reextended.
7275 if (Value *V = FitsInFPType(CFP, Type::FloatTy, APFloat::IEEEsingle))
7276 return V;
7277 if (CFP->getType() == Type::DoubleTy)
7278 return V; // Won't shrink.
7279 if (Value *V = FitsInFPType(CFP, Type::DoubleTy, APFloat::IEEEdouble))
7280 return V;
7281 // Don't try to shrink to various long double types.
7282 }
7283
7284 return V;
7285}
7286
7287Instruction *InstCombiner::visitFPTrunc(FPTruncInst &CI) {
7288 if (Instruction *I = commonCastTransforms(CI))
7289 return I;
7290
7291 // If we have fptrunc(add (fpextend x), (fpextend y)), where x and y are
7292 // smaller than the destination type, we can eliminate the truncate by doing
7293 // the add as the smaller type. This applies to add/sub/mul/div as well as
7294 // many builtins (sqrt, etc).
7295 BinaryOperator *OpI = dyn_cast<BinaryOperator>(CI.getOperand(0));
7296 if (OpI && OpI->hasOneUse()) {
7297 switch (OpI->getOpcode()) {
7298 default: break;
7299 case Instruction::Add:
7300 case Instruction::Sub:
7301 case Instruction::Mul:
7302 case Instruction::FDiv:
7303 case Instruction::FRem:
7304 const Type *SrcTy = OpI->getType();
7305 Value *LHSTrunc = LookThroughFPExtensions(OpI->getOperand(0));
7306 Value *RHSTrunc = LookThroughFPExtensions(OpI->getOperand(1));
7307 if (LHSTrunc->getType() != SrcTy &&
7308 RHSTrunc->getType() != SrcTy) {
7309 unsigned DstSize = CI.getType()->getPrimitiveSizeInBits();
7310 // If the source types were both smaller than the destination type of
7311 // the cast, do this xform.
7312 if (LHSTrunc->getType()->getPrimitiveSizeInBits() <= DstSize &&
7313 RHSTrunc->getType()->getPrimitiveSizeInBits() <= DstSize) {
7314 LHSTrunc = InsertCastBefore(Instruction::FPExt, LHSTrunc,
7315 CI.getType(), CI);
7316 RHSTrunc = InsertCastBefore(Instruction::FPExt, RHSTrunc,
7317 CI.getType(), CI);
7318 return BinaryOperator::create(OpI->getOpcode(), LHSTrunc, RHSTrunc);
7319 }
7320 }
7321 break;
7322 }
7323 }
7324 return 0;
Reid Spencer3da59db2006-11-27 01:05:10 +00007325}
7326
7327Instruction *InstCombiner::visitFPExt(CastInst &CI) {
7328 return commonCastTransforms(CI);
7329}
7330
7331Instruction *InstCombiner::visitFPToUI(CastInst &CI) {
Reid Spencer44c030a2006-11-30 23:13:36 +00007332 return commonCastTransforms(CI);
Reid Spencer3da59db2006-11-27 01:05:10 +00007333}
7334
7335Instruction *InstCombiner::visitFPToSI(CastInst &CI) {
Reid Spencer44c030a2006-11-30 23:13:36 +00007336 return commonCastTransforms(CI);
Reid Spencer3da59db2006-11-27 01:05:10 +00007337}
7338
7339Instruction *InstCombiner::visitUIToFP(CastInst &CI) {
7340 return commonCastTransforms(CI);
7341}
7342
7343Instruction *InstCombiner::visitSIToFP(CastInst &CI) {
7344 return commonCastTransforms(CI);
7345}
7346
7347Instruction *InstCombiner::visitPtrToInt(CastInst &CI) {
Chris Lattnerd3e28342007-04-27 17:44:50 +00007348 return commonPointerCastTransforms(CI);
Reid Spencer3da59db2006-11-27 01:05:10 +00007349}
7350
Chris Lattnerf9d9e452008-01-08 07:23:51 +00007351Instruction *InstCombiner::visitIntToPtr(IntToPtrInst &CI) {
7352 if (Instruction *I = commonCastTransforms(CI))
7353 return I;
7354
7355 const Type *DestPointee = cast<PointerType>(CI.getType())->getElementType();
7356 if (!DestPointee->isSized()) return 0;
7357
7358 // If this is inttoptr(add (ptrtoint x), cst), try to turn this into a GEP.
7359 ConstantInt *Cst;
7360 Value *X;
7361 if (match(CI.getOperand(0), m_Add(m_Cast<PtrToIntInst>(m_Value(X)),
7362 m_ConstantInt(Cst)))) {
7363 // If the source and destination operands have the same type, see if this
7364 // is a single-index GEP.
7365 if (X->getType() == CI.getType()) {
7366 // Get the size of the pointee type.
7367 uint64_t Size = TD->getABITypeSizeInBits(DestPointee);
7368
7369 // Convert the constant to intptr type.
7370 APInt Offset = Cst->getValue();
7371 Offset.sextOrTrunc(TD->getPointerSizeInBits());
7372
7373 // If Offset is evenly divisible by Size, we can do this xform.
7374 if (Size && !APIntOps::srem(Offset, APInt(Offset.getBitWidth(), Size))){
7375 Offset = APIntOps::sdiv(Offset, APInt(Offset.getBitWidth(), Size));
7376 return new GetElementPtrInst(X, ConstantInt::get(Offset));
7377 }
7378 }
7379 // TODO: Could handle other cases, e.g. where add is indexing into field of
7380 // struct etc.
7381 } else if (CI.getOperand(0)->hasOneUse() &&
7382 match(CI.getOperand(0), m_Add(m_Value(X), m_ConstantInt(Cst)))) {
7383 // Otherwise, if this is inttoptr(add x, cst), try to turn this into an
7384 // "inttoptr+GEP" instead of "add+intptr".
7385
7386 // Get the size of the pointee type.
7387 uint64_t Size = TD->getABITypeSize(DestPointee);
7388
7389 // Convert the constant to intptr type.
7390 APInt Offset = Cst->getValue();
7391 Offset.sextOrTrunc(TD->getPointerSizeInBits());
7392
7393 // If Offset is evenly divisible by Size, we can do this xform.
7394 if (Size && !APIntOps::srem(Offset, APInt(Offset.getBitWidth(), Size))){
7395 Offset = APIntOps::sdiv(Offset, APInt(Offset.getBitWidth(), Size));
7396
7397 Instruction *P = InsertNewInstBefore(new IntToPtrInst(X, CI.getType(),
7398 "tmp"), CI);
7399 return new GetElementPtrInst(P, ConstantInt::get(Offset), "tmp");
7400 }
7401 }
7402 return 0;
Reid Spencer3da59db2006-11-27 01:05:10 +00007403}
7404
Chris Lattnerd3e28342007-04-27 17:44:50 +00007405Instruction *InstCombiner::visitBitCast(BitCastInst &CI) {
Reid Spencer3da59db2006-11-27 01:05:10 +00007406 // If the operands are integer typed then apply the integer transforms,
7407 // otherwise just apply the common ones.
7408 Value *Src = CI.getOperand(0);
7409 const Type *SrcTy = Src->getType();
7410 const Type *DestTy = CI.getType();
7411
Chris Lattner42a75512007-01-15 02:27:26 +00007412 if (SrcTy->isInteger() && DestTy->isInteger()) {
Reid Spencer3da59db2006-11-27 01:05:10 +00007413 if (Instruction *Result = commonIntCastTransforms(CI))
7414 return Result;
Chris Lattnerd3e28342007-04-27 17:44:50 +00007415 } else if (isa<PointerType>(SrcTy)) {
7416 if (Instruction *I = commonPointerCastTransforms(CI))
7417 return I;
Reid Spencer3da59db2006-11-27 01:05:10 +00007418 } else {
7419 if (Instruction *Result = commonCastTransforms(CI))
7420 return Result;
7421 }
7422
7423
7424 // Get rid of casts from one type to the same type. These are useless and can
7425 // be replaced by the operand.
7426 if (DestTy == Src->getType())
7427 return ReplaceInstUsesWith(CI, Src);
7428
Reid Spencer3da59db2006-11-27 01:05:10 +00007429 if (const PointerType *DstPTy = dyn_cast<PointerType>(DestTy)) {
Chris Lattnerd3e28342007-04-27 17:44:50 +00007430 const PointerType *SrcPTy = cast<PointerType>(SrcTy);
7431 const Type *DstElTy = DstPTy->getElementType();
7432 const Type *SrcElTy = SrcPTy->getElementType();
7433
7434 // If we are casting a malloc or alloca to a pointer to a type of the same
7435 // size, rewrite the allocation instruction to allocate the "right" type.
7436 if (AllocationInst *AI = dyn_cast<AllocationInst>(Src))
7437 if (Instruction *V = PromoteCastOfAllocation(CI, *AI))
7438 return V;
7439
Chris Lattnerd717c182007-05-05 22:32:24 +00007440 // If the source and destination are pointers, and this cast is equivalent
7441 // to a getelementptr X, 0, 0, 0... turn it into the appropriate gep.
Chris Lattnerd3e28342007-04-27 17:44:50 +00007442 // This can enhance SROA and other transforms that want type-safe pointers.
7443 Constant *ZeroUInt = Constant::getNullValue(Type::Int32Ty);
7444 unsigned NumZeros = 0;
7445 while (SrcElTy != DstElTy &&
7446 isa<CompositeType>(SrcElTy) && !isa<PointerType>(SrcElTy) &&
7447 SrcElTy->getNumContainedTypes() /* not "{}" */) {
7448 SrcElTy = cast<CompositeType>(SrcElTy)->getTypeAtIndex(ZeroUInt);
7449 ++NumZeros;
7450 }
Chris Lattner4e998b22004-09-29 05:07:12 +00007451
Chris Lattnerd3e28342007-04-27 17:44:50 +00007452 // If we found a path from the src to dest, create the getelementptr now.
7453 if (SrcElTy == DstElTy) {
7454 SmallVector<Value*, 8> Idxs(NumZeros+1, ZeroUInt);
Chuck Rose IIIc331d302007-09-05 20:36:41 +00007455 return new GetElementPtrInst(Src, Idxs.begin(), Idxs.end(), "",
7456 ((Instruction*) NULL));
Chris Lattner9fb92132006-04-12 18:09:35 +00007457 }
Reid Spencer3da59db2006-11-27 01:05:10 +00007458 }
Chris Lattner24c8e382003-07-24 17:35:25 +00007459
Reid Spencer3da59db2006-11-27 01:05:10 +00007460 if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(Src)) {
7461 if (SVI->hasOneUse()) {
7462 // Okay, we have (bitconvert (shuffle ..)). Check to see if this is
7463 // a bitconvert to a vector with the same # elts.
Reid Spencer9d6565a2007-02-15 02:26:10 +00007464 if (isa<VectorType>(DestTy) &&
7465 cast<VectorType>(DestTy)->getNumElements() ==
Reid Spencer3da59db2006-11-27 01:05:10 +00007466 SVI->getType()->getNumElements()) {
7467 CastInst *Tmp;
7468 // If either of the operands is a cast from CI.getType(), then
7469 // evaluating the shuffle in the casted destination's type will allow
7470 // us to eliminate at least one cast.
7471 if (((Tmp = dyn_cast<CastInst>(SVI->getOperand(0))) &&
7472 Tmp->getOperand(0)->getType() == DestTy) ||
7473 ((Tmp = dyn_cast<CastInst>(SVI->getOperand(1))) &&
7474 Tmp->getOperand(0)->getType() == DestTy)) {
Reid Spencer17212df2006-12-12 09:18:51 +00007475 Value *LHS = InsertOperandCastBefore(Instruction::BitCast,
7476 SVI->getOperand(0), DestTy, &CI);
7477 Value *RHS = InsertOperandCastBefore(Instruction::BitCast,
7478 SVI->getOperand(1), DestTy, &CI);
Reid Spencer3da59db2006-11-27 01:05:10 +00007479 // Return a new shuffle vector. Use the same element ID's, as we
7480 // know the vector types match #elts.
7481 return new ShuffleVectorInst(LHS, RHS, SVI->getOperand(2));
Chris Lattner01575b72006-05-25 23:24:33 +00007482 }
7483 }
7484 }
7485 }
Chris Lattnerdd841ae2002-04-18 17:39:14 +00007486 return 0;
Chris Lattner8a2a3112001-12-14 16:52:21 +00007487}
7488
Chris Lattnere576b912004-04-09 23:46:01 +00007489/// GetSelectFoldableOperands - We want to turn code that looks like this:
7490/// %C = or %A, %B
7491/// %D = select %cond, %C, %A
7492/// into:
7493/// %C = select %cond, %B, 0
7494/// %D = or %A, %C
7495///
7496/// Assuming that the specified instruction is an operand to the select, return
7497/// a bitmask indicating which operands of this instruction are foldable if they
7498/// equal the other incoming value of the select.
7499///
7500static unsigned GetSelectFoldableOperands(Instruction *I) {
7501 switch (I->getOpcode()) {
7502 case Instruction::Add:
7503 case Instruction::Mul:
7504 case Instruction::And:
7505 case Instruction::Or:
7506 case Instruction::Xor:
7507 return 3; // Can fold through either operand.
7508 case Instruction::Sub: // Can only fold on the amount subtracted.
7509 case Instruction::Shl: // Can only fold on the shift amount.
Reid Spencer3822ff52006-11-08 06:47:33 +00007510 case Instruction::LShr:
7511 case Instruction::AShr:
Misha Brukmanfd939082005-04-21 23:48:37 +00007512 return 1;
Chris Lattnere576b912004-04-09 23:46:01 +00007513 default:
7514 return 0; // Cannot fold
7515 }
7516}
7517
7518/// GetSelectFoldableConstant - For the same transformation as the previous
7519/// function, return the identity constant that goes into the select.
7520static Constant *GetSelectFoldableConstant(Instruction *I) {
7521 switch (I->getOpcode()) {
7522 default: assert(0 && "This cannot happen!"); abort();
7523 case Instruction::Add:
7524 case Instruction::Sub:
7525 case Instruction::Or:
7526 case Instruction::Xor:
Chris Lattnere576b912004-04-09 23:46:01 +00007527 case Instruction::Shl:
Reid Spencer3822ff52006-11-08 06:47:33 +00007528 case Instruction::LShr:
7529 case Instruction::AShr:
Reid Spencer832254e2007-02-02 02:16:23 +00007530 return Constant::getNullValue(I->getType());
Chris Lattnere576b912004-04-09 23:46:01 +00007531 case Instruction::And:
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00007532 return Constant::getAllOnesValue(I->getType());
Chris Lattnere576b912004-04-09 23:46:01 +00007533 case Instruction::Mul:
7534 return ConstantInt::get(I->getType(), 1);
7535 }
7536}
7537
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00007538/// FoldSelectOpOp - Here we have (select c, TI, FI), and we know that TI and FI
7539/// have the same opcode and only one use each. Try to simplify this.
7540Instruction *InstCombiner::FoldSelectOpOp(SelectInst &SI, Instruction *TI,
7541 Instruction *FI) {
7542 if (TI->getNumOperands() == 1) {
7543 // If this is a non-volatile load or a cast from the same type,
7544 // merge.
Reid Spencer3da59db2006-11-27 01:05:10 +00007545 if (TI->isCast()) {
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00007546 if (TI->getOperand(0)->getType() != FI->getOperand(0)->getType())
7547 return 0;
7548 } else {
7549 return 0; // unknown unary op.
7550 }
Misha Brukmanfd939082005-04-21 23:48:37 +00007551
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00007552 // Fold this by inserting a select from the input values.
7553 SelectInst *NewSI = new SelectInst(SI.getCondition(), TI->getOperand(0),
7554 FI->getOperand(0), SI.getName()+".v");
7555 InsertNewInstBefore(NewSI, SI);
Reid Spencer3da59db2006-11-27 01:05:10 +00007556 return CastInst::create(Instruction::CastOps(TI->getOpcode()), NewSI,
7557 TI->getType());
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00007558 }
7559
Reid Spencer832254e2007-02-02 02:16:23 +00007560 // Only handle binary operators here.
7561 if (!isa<BinaryOperator>(TI))
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00007562 return 0;
7563
7564 // Figure out if the operations have any operands in common.
7565 Value *MatchOp, *OtherOpT, *OtherOpF;
7566 bool MatchIsOpZero;
7567 if (TI->getOperand(0) == FI->getOperand(0)) {
7568 MatchOp = TI->getOperand(0);
7569 OtherOpT = TI->getOperand(1);
7570 OtherOpF = FI->getOperand(1);
7571 MatchIsOpZero = true;
7572 } else if (TI->getOperand(1) == FI->getOperand(1)) {
7573 MatchOp = TI->getOperand(1);
7574 OtherOpT = TI->getOperand(0);
7575 OtherOpF = FI->getOperand(0);
7576 MatchIsOpZero = false;
7577 } else if (!TI->isCommutative()) {
7578 return 0;
7579 } else if (TI->getOperand(0) == FI->getOperand(1)) {
7580 MatchOp = TI->getOperand(0);
7581 OtherOpT = TI->getOperand(1);
7582 OtherOpF = FI->getOperand(0);
7583 MatchIsOpZero = true;
7584 } else if (TI->getOperand(1) == FI->getOperand(0)) {
7585 MatchOp = TI->getOperand(1);
7586 OtherOpT = TI->getOperand(0);
7587 OtherOpF = FI->getOperand(1);
7588 MatchIsOpZero = true;
7589 } else {
7590 return 0;
7591 }
7592
7593 // If we reach here, they do have operations in common.
7594 SelectInst *NewSI = new SelectInst(SI.getCondition(), OtherOpT,
7595 OtherOpF, SI.getName()+".v");
7596 InsertNewInstBefore(NewSI, SI);
7597
7598 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TI)) {
7599 if (MatchIsOpZero)
7600 return BinaryOperator::create(BO->getOpcode(), MatchOp, NewSI);
7601 else
7602 return BinaryOperator::create(BO->getOpcode(), NewSI, MatchOp);
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00007603 }
Reid Spencera07cb7d2007-02-02 14:41:37 +00007604 assert(0 && "Shouldn't get here");
7605 return 0;
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00007606}
7607
Chris Lattner3d69f462004-03-12 05:52:32 +00007608Instruction *InstCombiner::visitSelectInst(SelectInst &SI) {
Chris Lattnerc32b30a2004-03-30 19:37:13 +00007609 Value *CondVal = SI.getCondition();
7610 Value *TrueVal = SI.getTrueValue();
7611 Value *FalseVal = SI.getFalseValue();
7612
7613 // select true, X, Y -> X
7614 // select false, X, Y -> Y
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00007615 if (ConstantInt *C = dyn_cast<ConstantInt>(CondVal))
Reid Spencer579dca12007-01-12 04:24:46 +00007616 return ReplaceInstUsesWith(SI, C->getZExtValue() ? TrueVal : FalseVal);
Chris Lattnerc32b30a2004-03-30 19:37:13 +00007617
7618 // select C, X, X -> X
7619 if (TrueVal == FalseVal)
7620 return ReplaceInstUsesWith(SI, TrueVal);
7621
Chris Lattnere87597f2004-10-16 18:11:37 +00007622 if (isa<UndefValue>(TrueVal)) // select C, undef, X -> X
7623 return ReplaceInstUsesWith(SI, FalseVal);
7624 if (isa<UndefValue>(FalseVal)) // select C, X, undef -> X
7625 return ReplaceInstUsesWith(SI, TrueVal);
7626 if (isa<UndefValue>(CondVal)) { // select undef, X, Y -> X or Y
7627 if (isa<Constant>(TrueVal))
7628 return ReplaceInstUsesWith(SI, TrueVal);
7629 else
7630 return ReplaceInstUsesWith(SI, FalseVal);
7631 }
7632
Reid Spencer4fe16d62007-01-11 18:21:29 +00007633 if (SI.getType() == Type::Int1Ty) {
Reid Spencera54b7cb2007-01-12 07:05:14 +00007634 if (ConstantInt *C = dyn_cast<ConstantInt>(TrueVal)) {
Reid Spencer579dca12007-01-12 04:24:46 +00007635 if (C->getZExtValue()) {
Chris Lattner0c199a72004-04-08 04:43:23 +00007636 // Change: A = select B, true, C --> A = or B, C
Chris Lattner48595f12004-06-10 02:07:29 +00007637 return BinaryOperator::createOr(CondVal, FalseVal);
Chris Lattner0c199a72004-04-08 04:43:23 +00007638 } else {
7639 // Change: A = select B, false, C --> A = and !B, C
7640 Value *NotCond =
7641 InsertNewInstBefore(BinaryOperator::createNot(CondVal,
7642 "not."+CondVal->getName()), SI);
Chris Lattner48595f12004-06-10 02:07:29 +00007643 return BinaryOperator::createAnd(NotCond, FalseVal);
Chris Lattner0c199a72004-04-08 04:43:23 +00007644 }
Reid Spencera54b7cb2007-01-12 07:05:14 +00007645 } else if (ConstantInt *C = dyn_cast<ConstantInt>(FalseVal)) {
Reid Spencer579dca12007-01-12 04:24:46 +00007646 if (C->getZExtValue() == false) {
Chris Lattner0c199a72004-04-08 04:43:23 +00007647 // Change: A = select B, C, false --> A = and B, C
Chris Lattner48595f12004-06-10 02:07:29 +00007648 return BinaryOperator::createAnd(CondVal, TrueVal);
Chris Lattner0c199a72004-04-08 04:43:23 +00007649 } else {
7650 // Change: A = select B, C, true --> A = or !B, C
7651 Value *NotCond =
7652 InsertNewInstBefore(BinaryOperator::createNot(CondVal,
7653 "not."+CondVal->getName()), SI);
Chris Lattner48595f12004-06-10 02:07:29 +00007654 return BinaryOperator::createOr(NotCond, TrueVal);
Chris Lattner0c199a72004-04-08 04:43:23 +00007655 }
7656 }
Chris Lattnercfa59752007-11-25 21:27:53 +00007657
7658 // select a, b, a -> a&b
7659 // select a, a, b -> a|b
7660 if (CondVal == TrueVal)
7661 return BinaryOperator::createOr(CondVal, FalseVal);
7662 else if (CondVal == FalseVal)
7663 return BinaryOperator::createAnd(CondVal, TrueVal);
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00007664 }
Chris Lattner0c199a72004-04-08 04:43:23 +00007665
Chris Lattner2eefe512004-04-09 19:05:30 +00007666 // Selecting between two integer constants?
7667 if (ConstantInt *TrueValC = dyn_cast<ConstantInt>(TrueVal))
7668 if (ConstantInt *FalseValC = dyn_cast<ConstantInt>(FalseVal)) {
Chris Lattnerba417832007-04-11 06:12:58 +00007669 // select C, 1, 0 -> zext C to int
Reid Spencer2ec619a2007-03-23 21:24:59 +00007670 if (FalseValC->isZero() && TrueValC->getValue() == 1) {
Reid Spencer3da59db2006-11-27 01:05:10 +00007671 return CastInst::create(Instruction::ZExt, CondVal, SI.getType());
Reid Spencer2ec619a2007-03-23 21:24:59 +00007672 } else if (TrueValC->isZero() && FalseValC->getValue() == 1) {
Chris Lattnerba417832007-04-11 06:12:58 +00007673 // select C, 0, 1 -> zext !C to int
Chris Lattner2eefe512004-04-09 19:05:30 +00007674 Value *NotCond =
7675 InsertNewInstBefore(BinaryOperator::createNot(CondVal,
Chris Lattner82e14fe2004-04-09 18:19:44 +00007676 "not."+CondVal->getName()), SI);
Reid Spencer3da59db2006-11-27 01:05:10 +00007677 return CastInst::create(Instruction::ZExt, NotCond, SI.getType());
Chris Lattner82e14fe2004-04-09 18:19:44 +00007678 }
Chris Lattnerba417832007-04-11 06:12:58 +00007679
7680 // FIXME: Turn select 0/-1 and -1/0 into sext from condition!
Chris Lattner457dd822004-06-09 07:59:58 +00007681
Reid Spencere4d87aa2006-12-23 06:05:41 +00007682 if (ICmpInst *IC = dyn_cast<ICmpInst>(SI.getCondition())) {
Chris Lattnerb8456462006-09-20 04:44:59 +00007683
Reid Spencere4d87aa2006-12-23 06:05:41 +00007684 // (x <s 0) ? -1 : 0 -> ashr x, 31
Reid Spencer2ec619a2007-03-23 21:24:59 +00007685 if (TrueValC->isAllOnesValue() && FalseValC->isZero())
Chris Lattnerb8456462006-09-20 04:44:59 +00007686 if (ConstantInt *CmpCst = dyn_cast<ConstantInt>(IC->getOperand(1))) {
Chris Lattnerba417832007-04-11 06:12:58 +00007687 if (IC->getPredicate() == ICmpInst::ICMP_SLT && CmpCst->isZero()) {
Chris Lattnerb8456462006-09-20 04:44:59 +00007688 // The comparison constant and the result are not neccessarily the
Reid Spencer3da59db2006-11-27 01:05:10 +00007689 // same width. Make an all-ones value by inserting a AShr.
Chris Lattnerb8456462006-09-20 04:44:59 +00007690 Value *X = IC->getOperand(0);
Zhou Sheng4351c642007-04-02 08:20:41 +00007691 uint32_t Bits = X->getType()->getPrimitiveSizeInBits();
Reid Spencer832254e2007-02-02 02:16:23 +00007692 Constant *ShAmt = ConstantInt::get(X->getType(), Bits-1);
7693 Instruction *SRA = BinaryOperator::create(Instruction::AShr, X,
7694 ShAmt, "ones");
Chris Lattnerb8456462006-09-20 04:44:59 +00007695 InsertNewInstBefore(SRA, SI);
7696
Reid Spencer3da59db2006-11-27 01:05:10 +00007697 // Finally, convert to the type of the select RHS. We figure out
7698 // if this requires a SExt, Trunc or BitCast based on the sizes.
7699 Instruction::CastOps opc = Instruction::BitCast;
Zhou Sheng4351c642007-04-02 08:20:41 +00007700 uint32_t SRASize = SRA->getType()->getPrimitiveSizeInBits();
7701 uint32_t SISize = SI.getType()->getPrimitiveSizeInBits();
Reid Spencer3da59db2006-11-27 01:05:10 +00007702 if (SRASize < SISize)
7703 opc = Instruction::SExt;
7704 else if (SRASize > SISize)
7705 opc = Instruction::Trunc;
7706 return CastInst::create(opc, SRA, SI.getType());
Chris Lattnerb8456462006-09-20 04:44:59 +00007707 }
7708 }
7709
7710
7711 // If one of the constants is zero (we know they can't both be) and we
Chris Lattnerba417832007-04-11 06:12:58 +00007712 // have an icmp instruction with zero, and we have an 'and' with the
Chris Lattnerb8456462006-09-20 04:44:59 +00007713 // non-constant value, eliminate this whole mess. This corresponds to
7714 // cases like this: ((X & 27) ? 27 : 0)
Reid Spencer2ec619a2007-03-23 21:24:59 +00007715 if (TrueValC->isZero() || FalseValC->isZero())
Chris Lattner65b72ba2006-09-18 04:22:48 +00007716 if (IC->isEquality() && isa<ConstantInt>(IC->getOperand(1)) &&
Chris Lattner457dd822004-06-09 07:59:58 +00007717 cast<Constant>(IC->getOperand(1))->isNullValue())
7718 if (Instruction *ICA = dyn_cast<Instruction>(IC->getOperand(0)))
7719 if (ICA->getOpcode() == Instruction::And &&
Misha Brukmanfd939082005-04-21 23:48:37 +00007720 isa<ConstantInt>(ICA->getOperand(1)) &&
7721 (ICA->getOperand(1) == TrueValC ||
7722 ICA->getOperand(1) == FalseValC) &&
Chris Lattner457dd822004-06-09 07:59:58 +00007723 isOneBitSet(cast<ConstantInt>(ICA->getOperand(1)))) {
7724 // Okay, now we know that everything is set up, we just don't
Reid Spencere4d87aa2006-12-23 06:05:41 +00007725 // know whether we have a icmp_ne or icmp_eq and whether the
7726 // true or false val is the zero.
Reid Spencer2ec619a2007-03-23 21:24:59 +00007727 bool ShouldNotVal = !TrueValC->isZero();
Reid Spencere4d87aa2006-12-23 06:05:41 +00007728 ShouldNotVal ^= IC->getPredicate() == ICmpInst::ICMP_NE;
Chris Lattner457dd822004-06-09 07:59:58 +00007729 Value *V = ICA;
7730 if (ShouldNotVal)
7731 V = InsertNewInstBefore(BinaryOperator::create(
7732 Instruction::Xor, V, ICA->getOperand(1)), SI);
7733 return ReplaceInstUsesWith(SI, V);
7734 }
Chris Lattnerb8456462006-09-20 04:44:59 +00007735 }
Chris Lattnerc32b30a2004-03-30 19:37:13 +00007736 }
Chris Lattnerd76956d2004-04-10 22:21:27 +00007737
7738 // See if we are selecting two values based on a comparison of the two values.
Reid Spencere4d87aa2006-12-23 06:05:41 +00007739 if (FCmpInst *FCI = dyn_cast<FCmpInst>(CondVal)) {
7740 if (FCI->getOperand(0) == TrueVal && FCI->getOperand(1) == FalseVal) {
Chris Lattnerd76956d2004-04-10 22:21:27 +00007741 // Transform (X == Y) ? X : Y -> Y
Dale Johannesen5a2174f2007-10-03 17:45:27 +00007742 if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
7743 // This is not safe in general for floating point:
7744 // consider X== -0, Y== +0.
7745 // It becomes safe if either operand is a nonzero constant.
7746 ConstantFP *CFPt, *CFPf;
7747 if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
7748 !CFPt->getValueAPF().isZero()) ||
7749 ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
7750 !CFPf->getValueAPF().isZero()))
Chris Lattnerd76956d2004-04-10 22:21:27 +00007751 return ReplaceInstUsesWith(SI, FalseVal);
Dale Johannesen5a2174f2007-10-03 17:45:27 +00007752 }
Chris Lattnerd76956d2004-04-10 22:21:27 +00007753 // Transform (X != Y) ? X : Y -> X
Reid Spencere4d87aa2006-12-23 06:05:41 +00007754 if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
Chris Lattnerd76956d2004-04-10 22:21:27 +00007755 return ReplaceInstUsesWith(SI, TrueVal);
7756 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
7757
Reid Spencere4d87aa2006-12-23 06:05:41 +00007758 } else if (FCI->getOperand(0) == FalseVal && FCI->getOperand(1) == TrueVal){
Chris Lattnerd76956d2004-04-10 22:21:27 +00007759 // Transform (X == Y) ? Y : X -> X
Dale Johannesen5a2174f2007-10-03 17:45:27 +00007760 if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
7761 // This is not safe in general for floating point:
7762 // consider X== -0, Y== +0.
7763 // It becomes safe if either operand is a nonzero constant.
7764 ConstantFP *CFPt, *CFPf;
7765 if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
7766 !CFPt->getValueAPF().isZero()) ||
7767 ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
7768 !CFPf->getValueAPF().isZero()))
7769 return ReplaceInstUsesWith(SI, FalseVal);
7770 }
Chris Lattnerd76956d2004-04-10 22:21:27 +00007771 // Transform (X != Y) ? Y : X -> Y
Reid Spencere4d87aa2006-12-23 06:05:41 +00007772 if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
7773 return ReplaceInstUsesWith(SI, TrueVal);
7774 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
7775 }
7776 }
7777
7778 // See if we are selecting two values based on a comparison of the two values.
7779 if (ICmpInst *ICI = dyn_cast<ICmpInst>(CondVal)) {
7780 if (ICI->getOperand(0) == TrueVal && ICI->getOperand(1) == FalseVal) {
7781 // Transform (X == Y) ? X : Y -> Y
7782 if (ICI->getPredicate() == ICmpInst::ICMP_EQ)
7783 return ReplaceInstUsesWith(SI, FalseVal);
7784 // Transform (X != Y) ? X : Y -> X
7785 if (ICI->getPredicate() == ICmpInst::ICMP_NE)
7786 return ReplaceInstUsesWith(SI, TrueVal);
7787 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
7788
7789 } else if (ICI->getOperand(0) == FalseVal && ICI->getOperand(1) == TrueVal){
7790 // Transform (X == Y) ? Y : X -> X
7791 if (ICI->getPredicate() == ICmpInst::ICMP_EQ)
7792 return ReplaceInstUsesWith(SI, FalseVal);
7793 // Transform (X != Y) ? Y : X -> Y
7794 if (ICI->getPredicate() == ICmpInst::ICMP_NE)
Chris Lattnerfbede522004-04-11 01:39:19 +00007795 return ReplaceInstUsesWith(SI, TrueVal);
Chris Lattnerd76956d2004-04-10 22:21:27 +00007796 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
7797 }
7798 }
Misha Brukmanfd939082005-04-21 23:48:37 +00007799
Chris Lattner87875da2005-01-13 22:52:24 +00007800 if (Instruction *TI = dyn_cast<Instruction>(TrueVal))
7801 if (Instruction *FI = dyn_cast<Instruction>(FalseVal))
7802 if (TI->hasOneUse() && FI->hasOneUse()) {
Chris Lattner87875da2005-01-13 22:52:24 +00007803 Instruction *AddOp = 0, *SubOp = 0;
7804
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00007805 // Turn (select C, (op X, Y), (op X, Z)) -> (op X, (select C, Y, Z))
7806 if (TI->getOpcode() == FI->getOpcode())
7807 if (Instruction *IV = FoldSelectOpOp(SI, TI, FI))
7808 return IV;
7809
7810 // Turn select C, (X+Y), (X-Y) --> (X+(select C, Y, (-Y))). This is
7811 // even legal for FP.
Chris Lattner87875da2005-01-13 22:52:24 +00007812 if (TI->getOpcode() == Instruction::Sub &&
7813 FI->getOpcode() == Instruction::Add) {
7814 AddOp = FI; SubOp = TI;
7815 } else if (FI->getOpcode() == Instruction::Sub &&
7816 TI->getOpcode() == Instruction::Add) {
7817 AddOp = TI; SubOp = FI;
7818 }
7819
7820 if (AddOp) {
7821 Value *OtherAddOp = 0;
7822 if (SubOp->getOperand(0) == AddOp->getOperand(0)) {
7823 OtherAddOp = AddOp->getOperand(1);
7824 } else if (SubOp->getOperand(0) == AddOp->getOperand(1)) {
7825 OtherAddOp = AddOp->getOperand(0);
7826 }
7827
7828 if (OtherAddOp) {
Chris Lattner97f37a42006-02-24 18:05:58 +00007829 // So at this point we know we have (Y -> OtherAddOp):
7830 // select C, (add X, Y), (sub X, Z)
7831 Value *NegVal; // Compute -Z
7832 if (Constant *C = dyn_cast<Constant>(SubOp->getOperand(1))) {
7833 NegVal = ConstantExpr::getNeg(C);
7834 } else {
7835 NegVal = InsertNewInstBefore(
7836 BinaryOperator::createNeg(SubOp->getOperand(1), "tmp"), SI);
Chris Lattner87875da2005-01-13 22:52:24 +00007837 }
Chris Lattner97f37a42006-02-24 18:05:58 +00007838
7839 Value *NewTrueOp = OtherAddOp;
7840 Value *NewFalseOp = NegVal;
7841 if (AddOp != TI)
7842 std::swap(NewTrueOp, NewFalseOp);
7843 Instruction *NewSel =
7844 new SelectInst(CondVal, NewTrueOp,NewFalseOp,SI.getName()+".p");
7845
7846 NewSel = InsertNewInstBefore(NewSel, SI);
7847 return BinaryOperator::createAdd(SubOp->getOperand(0), NewSel);
Chris Lattner87875da2005-01-13 22:52:24 +00007848 }
7849 }
7850 }
Misha Brukmanfd939082005-04-21 23:48:37 +00007851
Chris Lattnere576b912004-04-09 23:46:01 +00007852 // See if we can fold the select into one of our operands.
Chris Lattner42a75512007-01-15 02:27:26 +00007853 if (SI.getType()->isInteger()) {
Chris Lattnere576b912004-04-09 23:46:01 +00007854 // See the comment above GetSelectFoldableOperands for a description of the
7855 // transformation we are doing here.
7856 if (Instruction *TVI = dyn_cast<Instruction>(TrueVal))
7857 if (TVI->hasOneUse() && TVI->getNumOperands() == 2 &&
7858 !isa<Constant>(FalseVal))
7859 if (unsigned SFO = GetSelectFoldableOperands(TVI)) {
7860 unsigned OpToFold = 0;
7861 if ((SFO & 1) && FalseVal == TVI->getOperand(0)) {
7862 OpToFold = 1;
7863 } else if ((SFO & 2) && FalseVal == TVI->getOperand(1)) {
7864 OpToFold = 2;
7865 }
7866
7867 if (OpToFold) {
7868 Constant *C = GetSelectFoldableConstant(TVI);
Chris Lattnere576b912004-04-09 23:46:01 +00007869 Instruction *NewSel =
Chris Lattner6934a042007-02-11 01:23:03 +00007870 new SelectInst(SI.getCondition(), TVI->getOperand(2-OpToFold), C);
Chris Lattnere576b912004-04-09 23:46:01 +00007871 InsertNewInstBefore(NewSel, SI);
Chris Lattner6934a042007-02-11 01:23:03 +00007872 NewSel->takeName(TVI);
Chris Lattnere576b912004-04-09 23:46:01 +00007873 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TVI))
7874 return BinaryOperator::create(BO->getOpcode(), FalseVal, NewSel);
Chris Lattnere576b912004-04-09 23:46:01 +00007875 else {
7876 assert(0 && "Unknown instruction!!");
7877 }
7878 }
7879 }
Chris Lattnera96879a2004-09-29 17:40:11 +00007880
Chris Lattnere576b912004-04-09 23:46:01 +00007881 if (Instruction *FVI = dyn_cast<Instruction>(FalseVal))
7882 if (FVI->hasOneUse() && FVI->getNumOperands() == 2 &&
7883 !isa<Constant>(TrueVal))
7884 if (unsigned SFO = GetSelectFoldableOperands(FVI)) {
7885 unsigned OpToFold = 0;
7886 if ((SFO & 1) && TrueVal == FVI->getOperand(0)) {
7887 OpToFold = 1;
7888 } else if ((SFO & 2) && TrueVal == FVI->getOperand(1)) {
7889 OpToFold = 2;
7890 }
7891
7892 if (OpToFold) {
7893 Constant *C = GetSelectFoldableConstant(FVI);
Chris Lattnere576b912004-04-09 23:46:01 +00007894 Instruction *NewSel =
Chris Lattner6934a042007-02-11 01:23:03 +00007895 new SelectInst(SI.getCondition(), C, FVI->getOperand(2-OpToFold));
Chris Lattnere576b912004-04-09 23:46:01 +00007896 InsertNewInstBefore(NewSel, SI);
Chris Lattner6934a042007-02-11 01:23:03 +00007897 NewSel->takeName(FVI);
Chris Lattnere576b912004-04-09 23:46:01 +00007898 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(FVI))
7899 return BinaryOperator::create(BO->getOpcode(), TrueVal, NewSel);
Reid Spencer832254e2007-02-02 02:16:23 +00007900 else
Chris Lattnere576b912004-04-09 23:46:01 +00007901 assert(0 && "Unknown instruction!!");
Chris Lattnere576b912004-04-09 23:46:01 +00007902 }
7903 }
7904 }
Chris Lattnera1df33c2005-04-24 07:30:14 +00007905
7906 if (BinaryOperator::isNot(CondVal)) {
7907 SI.setOperand(0, BinaryOperator::getNotArgument(CondVal));
7908 SI.setOperand(1, FalseVal);
7909 SI.setOperand(2, TrueVal);
7910 return &SI;
7911 }
7912
Chris Lattner3d69f462004-03-12 05:52:32 +00007913 return 0;
7914}
7915
Chris Lattnerf2369f22007-08-09 19:05:49 +00007916/// GetOrEnforceKnownAlignment - If the specified pointer has an alignment that
7917/// we can determine, return it, otherwise return 0. If PrefAlign is specified,
7918/// and it is more than the alignment of the ultimate object, see if we can
7919/// increase the alignment of the ultimate object, making this check succeed.
7920static unsigned GetOrEnforceKnownAlignment(Value *V, TargetData *TD,
7921 unsigned PrefAlign = 0) {
Chris Lattner95a959d2006-03-06 20:18:44 +00007922 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(V)) {
7923 unsigned Align = GV->getAlignment();
Andrew Lenharthb410df92007-11-08 18:45:15 +00007924 if (Align == 0 && TD && GV->getType()->getElementType()->isSized())
Chris Lattnerd2b7cec2007-02-14 05:52:17 +00007925 Align = TD->getPrefTypeAlignment(GV->getType()->getElementType());
Chris Lattnerf2369f22007-08-09 19:05:49 +00007926
7927 // If there is a large requested alignment and we can, bump up the alignment
7928 // of the global.
7929 if (PrefAlign > Align && GV->hasInitializer()) {
7930 GV->setAlignment(PrefAlign);
7931 Align = PrefAlign;
7932 }
Chris Lattner95a959d2006-03-06 20:18:44 +00007933 return Align;
7934 } else if (AllocationInst *AI = dyn_cast<AllocationInst>(V)) {
7935 unsigned Align = AI->getAlignment();
7936 if (Align == 0 && TD) {
7937 if (isa<AllocaInst>(AI))
Chris Lattnerd2b7cec2007-02-14 05:52:17 +00007938 Align = TD->getPrefTypeAlignment(AI->getType()->getElementType());
Chris Lattner95a959d2006-03-06 20:18:44 +00007939 else if (isa<MallocInst>(AI)) {
7940 // Malloc returns maximally aligned memory.
Chris Lattnerd2b7cec2007-02-14 05:52:17 +00007941 Align = TD->getABITypeAlignment(AI->getType()->getElementType());
Chris Lattner58092e32007-01-20 22:35:55 +00007942 Align =
7943 std::max(Align,
Chris Lattnerd2b7cec2007-02-14 05:52:17 +00007944 (unsigned)TD->getABITypeAlignment(Type::DoubleTy));
Chris Lattner58092e32007-01-20 22:35:55 +00007945 Align =
7946 std::max(Align,
Chris Lattnerd2b7cec2007-02-14 05:52:17 +00007947 (unsigned)TD->getABITypeAlignment(Type::Int64Ty));
Chris Lattner95a959d2006-03-06 20:18:44 +00007948 }
7949 }
Chris Lattnerf2369f22007-08-09 19:05:49 +00007950
7951 // If there is a requested alignment and if this is an alloca, round up. We
7952 // don't do this for malloc, because some systems can't respect the request.
7953 if (PrefAlign > Align && isa<AllocaInst>(AI)) {
7954 AI->setAlignment(PrefAlign);
7955 Align = PrefAlign;
7956 }
Chris Lattner95a959d2006-03-06 20:18:44 +00007957 return Align;
Reid Spencer3da59db2006-11-27 01:05:10 +00007958 } else if (isa<BitCastInst>(V) ||
Chris Lattner51c26e92006-03-07 01:28:57 +00007959 (isa<ConstantExpr>(V) &&
Reid Spencer3da59db2006-11-27 01:05:10 +00007960 cast<ConstantExpr>(V)->getOpcode() == Instruction::BitCast)) {
Chris Lattnerf2369f22007-08-09 19:05:49 +00007961 return GetOrEnforceKnownAlignment(cast<User>(V)->getOperand(0),
7962 TD, PrefAlign);
Chris Lattner9bc14642007-04-28 00:57:34 +00007963 } else if (User *GEPI = dyn_castGetElementPtr(V)) {
Chris Lattner95a959d2006-03-06 20:18:44 +00007964 // If all indexes are zero, it is just the alignment of the base pointer.
7965 bool AllZeroOperands = true;
7966 for (unsigned i = 1, e = GEPI->getNumOperands(); i != e; ++i)
7967 if (!isa<Constant>(GEPI->getOperand(i)) ||
7968 !cast<Constant>(GEPI->getOperand(i))->isNullValue()) {
7969 AllZeroOperands = false;
7970 break;
7971 }
Chris Lattnerf2369f22007-08-09 19:05:49 +00007972
7973 if (AllZeroOperands) {
7974 // Treat this like a bitcast.
7975 return GetOrEnforceKnownAlignment(GEPI->getOperand(0), TD, PrefAlign);
7976 }
7977
7978 unsigned BaseAlignment = GetOrEnforceKnownAlignment(GEPI->getOperand(0),TD);
7979 if (BaseAlignment == 0) return 0;
7980
Chris Lattner95a959d2006-03-06 20:18:44 +00007981 // Otherwise, if the base alignment is >= the alignment we expect for the
7982 // base pointer type, then we know that the resultant pointer is aligned at
7983 // least as much as its type requires.
7984 if (!TD) return 0;
7985
7986 const Type *BasePtrTy = GEPI->getOperand(0)->getType();
Chris Lattner58092e32007-01-20 22:35:55 +00007987 const PointerType *PtrTy = cast<PointerType>(BasePtrTy);
Lauro Ramos Venancioc7d11142007-07-31 20:13:21 +00007988 unsigned Align = TD->getABITypeAlignment(PtrTy->getElementType());
7989 if (Align <= BaseAlignment) {
Chris Lattner51c26e92006-03-07 01:28:57 +00007990 const Type *GEPTy = GEPI->getType();
Chris Lattner58092e32007-01-20 22:35:55 +00007991 const PointerType *GEPPtrTy = cast<PointerType>(GEPTy);
Lauro Ramos Venancioc7d11142007-07-31 20:13:21 +00007992 Align = std::min(Align, (unsigned)
7993 TD->getABITypeAlignment(GEPPtrTy->getElementType()));
7994 return Align;
Chris Lattner51c26e92006-03-07 01:28:57 +00007995 }
Chris Lattner95a959d2006-03-06 20:18:44 +00007996 return 0;
7997 }
7998 return 0;
7999}
8000
Chris Lattnerf497b022008-01-13 23:50:23 +00008001Instruction *InstCombiner::SimplifyMemTransfer(MemIntrinsic *MI) {
8002 unsigned DstAlign = GetOrEnforceKnownAlignment(MI->getOperand(1), TD);
8003 unsigned SrcAlign = GetOrEnforceKnownAlignment(MI->getOperand(2), TD);
8004 unsigned MinAlign = std::min(DstAlign, SrcAlign);
8005 unsigned CopyAlign = MI->getAlignment()->getZExtValue();
8006
8007 if (CopyAlign < MinAlign) {
8008 MI->setAlignment(ConstantInt::get(Type::Int32Ty, MinAlign));
8009 return MI;
8010 }
8011
8012 // If MemCpyInst length is 1/2/4/8 bytes then replace memcpy with
8013 // load/store.
8014 ConstantInt *MemOpLength = dyn_cast<ConstantInt>(MI->getOperand(3));
8015 if (MemOpLength == 0) return 0;
8016
Chris Lattner37ac6082008-01-14 00:28:35 +00008017 // Source and destination pointer types are always "i8*" for intrinsic. See
8018 // if the size is something we can handle with a single primitive load/store.
8019 // A single load+store correctly handles overlapping memory in the memmove
8020 // case.
Chris Lattnerf497b022008-01-13 23:50:23 +00008021 unsigned Size = MemOpLength->getZExtValue();
8022 if (Size == 0 || Size > 8 || (Size&(Size-1)))
Chris Lattner37ac6082008-01-14 00:28:35 +00008023 return 0; // If not 1/2/4/8 bytes, exit.
Chris Lattnerf497b022008-01-13 23:50:23 +00008024
Chris Lattner37ac6082008-01-14 00:28:35 +00008025 // Use an integer load+store unless we can find something better.
Chris Lattnerf497b022008-01-13 23:50:23 +00008026 Type *NewPtrTy = PointerType::getUnqual(IntegerType::get(Size<<3));
Chris Lattner37ac6082008-01-14 00:28:35 +00008027
8028 // Memcpy forces the use of i8* for the source and destination. That means
8029 // that if you're using memcpy to move one double around, you'll get a cast
8030 // from double* to i8*. We'd much rather use a double load+store rather than
8031 // an i64 load+store, here because this improves the odds that the source or
8032 // dest address will be promotable. See if we can find a better type than the
8033 // integer datatype.
8034 if (Value *Op = getBitCastOperand(MI->getOperand(1))) {
8035 const Type *SrcETy = cast<PointerType>(Op->getType())->getElementType();
8036 if (SrcETy->isSized() && TD->getTypeStoreSize(SrcETy) == Size) {
8037 // The SrcETy might be something like {{{double}}} or [1 x double]. Rip
8038 // down through these levels if so.
8039 while (!SrcETy->isFirstClassType()) {
8040 if (const StructType *STy = dyn_cast<StructType>(SrcETy)) {
8041 if (STy->getNumElements() == 1)
8042 SrcETy = STy->getElementType(0);
8043 else
8044 break;
8045 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(SrcETy)) {
8046 if (ATy->getNumElements() == 1)
8047 SrcETy = ATy->getElementType();
8048 else
8049 break;
8050 } else
8051 break;
8052 }
8053
8054 if (SrcETy->isFirstClassType())
8055 NewPtrTy = PointerType::getUnqual(SrcETy);
8056 }
8057 }
8058
8059
Chris Lattnerf497b022008-01-13 23:50:23 +00008060 // If the memcpy/memmove provides better alignment info than we can
8061 // infer, use it.
8062 SrcAlign = std::max(SrcAlign, CopyAlign);
8063 DstAlign = std::max(DstAlign, CopyAlign);
8064
8065 Value *Src = InsertBitCastBefore(MI->getOperand(2), NewPtrTy, *MI);
8066 Value *Dest = InsertBitCastBefore(MI->getOperand(1), NewPtrTy, *MI);
Chris Lattner37ac6082008-01-14 00:28:35 +00008067 Instruction *L = new LoadInst(Src, "tmp", false, SrcAlign);
8068 InsertNewInstBefore(L, *MI);
8069 InsertNewInstBefore(new StoreInst(L, Dest, false, DstAlign), *MI);
8070
8071 // Set the size of the copy to 0, it will be deleted on the next iteration.
8072 MI->setOperand(3, Constant::getNullValue(MemOpLength->getType()));
8073 return MI;
Chris Lattnerf497b022008-01-13 23:50:23 +00008074}
Chris Lattner3d69f462004-03-12 05:52:32 +00008075
Chris Lattner8b0ea312006-01-13 20:11:04 +00008076/// visitCallInst - CallInst simplification. This mostly only handles folding
8077/// of intrinsic instructions. For normal calls, it allows visitCallSite to do
8078/// the heavy lifting.
8079///
Chris Lattner9fe38862003-06-19 17:00:31 +00008080Instruction *InstCombiner::visitCallInst(CallInst &CI) {
Chris Lattner8b0ea312006-01-13 20:11:04 +00008081 IntrinsicInst *II = dyn_cast<IntrinsicInst>(&CI);
8082 if (!II) return visitCallSite(&CI);
8083
Chris Lattner7bcc0e72004-02-28 05:22:00 +00008084 // Intrinsics cannot occur in an invoke, so handle them here instead of in
8085 // visitCallSite.
Chris Lattner8b0ea312006-01-13 20:11:04 +00008086 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(II)) {
Chris Lattner35b9e482004-10-12 04:52:52 +00008087 bool Changed = false;
8088
8089 // memmove/cpy/set of zero bytes is a noop.
8090 if (Constant *NumBytes = dyn_cast<Constant>(MI->getLength())) {
8091 if (NumBytes->isNullValue()) return EraseInstFromFunction(CI);
8092
Chris Lattner35b9e482004-10-12 04:52:52 +00008093 if (ConstantInt *CI = dyn_cast<ConstantInt>(NumBytes))
Reid Spencerb83eb642006-10-20 07:07:24 +00008094 if (CI->getZExtValue() == 1) {
Chris Lattner35b9e482004-10-12 04:52:52 +00008095 // Replace the instruction with just byte operations. We would
8096 // transform other cases to loads/stores, but we don't know if
8097 // alignment is sufficient.
8098 }
Chris Lattner7bcc0e72004-02-28 05:22:00 +00008099 }
8100
Chris Lattner35b9e482004-10-12 04:52:52 +00008101 // If we have a memmove and the source operation is a constant global,
8102 // then the source and dest pointers can't alias, so we can change this
8103 // into a call to memcpy.
Chris Lattnerf497b022008-01-13 23:50:23 +00008104 if (MemMoveInst *MMI = dyn_cast<MemMoveInst>(MI)) {
Chris Lattner35b9e482004-10-12 04:52:52 +00008105 if (GlobalVariable *GVSrc = dyn_cast<GlobalVariable>(MMI->getSource()))
8106 if (GVSrc->isConstant()) {
8107 Module *M = CI.getParent()->getParent()->getParent();
Chris Lattner6d0339d2008-01-13 22:23:22 +00008108 Intrinsic::ID MemCpyID;
8109 if (CI.getOperand(3)->getType() == Type::Int32Ty)
8110 MemCpyID = Intrinsic::memcpy_i32;
Chris Lattner21959392006-03-03 01:34:17 +00008111 else
Chris Lattner6d0339d2008-01-13 22:23:22 +00008112 MemCpyID = Intrinsic::memcpy_i64;
8113 CI.setOperand(0, Intrinsic::getDeclaration(M, MemCpyID));
Chris Lattner35b9e482004-10-12 04:52:52 +00008114 Changed = true;
8115 }
Chris Lattner95a959d2006-03-06 20:18:44 +00008116 }
Chris Lattner35b9e482004-10-12 04:52:52 +00008117
Chris Lattner95a959d2006-03-06 20:18:44 +00008118 // If we can determine a pointer alignment that is bigger than currently
8119 // set, update the alignment.
8120 if (isa<MemCpyInst>(MI) || isa<MemMoveInst>(MI)) {
Chris Lattnerf497b022008-01-13 23:50:23 +00008121 if (Instruction *I = SimplifyMemTransfer(MI))
8122 return I;
Chris Lattner95a959d2006-03-06 20:18:44 +00008123 } else if (isa<MemSetInst>(MI)) {
Chris Lattnerf2369f22007-08-09 19:05:49 +00008124 unsigned Alignment = GetOrEnforceKnownAlignment(MI->getDest(), TD);
Reid Spencerb83eb642006-10-20 07:07:24 +00008125 if (MI->getAlignment()->getZExtValue() < Alignment) {
Reid Spencerc5b206b2006-12-31 05:48:39 +00008126 MI->setAlignment(ConstantInt::get(Type::Int32Ty, Alignment));
Chris Lattner95a959d2006-03-06 20:18:44 +00008127 Changed = true;
8128 }
8129 }
8130
Chris Lattner8b0ea312006-01-13 20:11:04 +00008131 if (Changed) return II;
Chris Lattnera728ddc2006-01-13 21:28:09 +00008132 } else {
8133 switch (II->getIntrinsicID()) {
8134 default: break;
Chris Lattner82ed58f2006-04-02 05:30:25 +00008135 case Intrinsic::ppc_altivec_lvx:
8136 case Intrinsic::ppc_altivec_lvxl:
Chris Lattnerfd6bdf02006-04-17 22:26:56 +00008137 case Intrinsic::x86_sse_loadu_ps:
8138 case Intrinsic::x86_sse2_loadu_pd:
8139 case Intrinsic::x86_sse2_loadu_dq:
8140 // Turn PPC lvx -> load if the pointer is known aligned.
8141 // Turn X86 loadups -> load if the pointer is known aligned.
Chris Lattnerf2369f22007-08-09 19:05:49 +00008142 if (GetOrEnforceKnownAlignment(II->getOperand(1), TD, 16) >= 16) {
Chris Lattner6d0339d2008-01-13 22:23:22 +00008143 Value *Ptr = InsertBitCastBefore(II->getOperand(1),
8144 PointerType::getUnqual(II->getType()),
8145 CI);
Chris Lattner82ed58f2006-04-02 05:30:25 +00008146 return new LoadInst(Ptr);
8147 }
8148 break;
8149 case Intrinsic::ppc_altivec_stvx:
8150 case Intrinsic::ppc_altivec_stvxl:
8151 // Turn stvx -> store if the pointer is known aligned.
Chris Lattnerf2369f22007-08-09 19:05:49 +00008152 if (GetOrEnforceKnownAlignment(II->getOperand(2), TD, 16) >= 16) {
Christopher Lamb43ad6b32007-12-17 01:12:55 +00008153 const Type *OpPtrTy =
8154 PointerType::getUnqual(II->getOperand(1)->getType());
Chris Lattner6d0339d2008-01-13 22:23:22 +00008155 Value *Ptr = InsertBitCastBefore(II->getOperand(2), OpPtrTy, CI);
Chris Lattner82ed58f2006-04-02 05:30:25 +00008156 return new StoreInst(II->getOperand(1), Ptr);
8157 }
8158 break;
Chris Lattnerfd6bdf02006-04-17 22:26:56 +00008159 case Intrinsic::x86_sse_storeu_ps:
8160 case Intrinsic::x86_sse2_storeu_pd:
8161 case Intrinsic::x86_sse2_storeu_dq:
8162 case Intrinsic::x86_sse2_storel_dq:
8163 // Turn X86 storeu -> store if the pointer is known aligned.
Chris Lattnerf2369f22007-08-09 19:05:49 +00008164 if (GetOrEnforceKnownAlignment(II->getOperand(1), TD, 16) >= 16) {
Christopher Lamb43ad6b32007-12-17 01:12:55 +00008165 const Type *OpPtrTy =
8166 PointerType::getUnqual(II->getOperand(2)->getType());
Chris Lattner6d0339d2008-01-13 22:23:22 +00008167 Value *Ptr = InsertBitCastBefore(II->getOperand(1), OpPtrTy, CI);
Chris Lattnerfd6bdf02006-04-17 22:26:56 +00008168 return new StoreInst(II->getOperand(2), Ptr);
8169 }
8170 break;
Chris Lattner867b99f2006-10-05 06:55:50 +00008171
8172 case Intrinsic::x86_sse_cvttss2si: {
8173 // These intrinsics only demands the 0th element of its input vector. If
8174 // we can simplify the input based on that, do so now.
8175 uint64_t UndefElts;
8176 if (Value *V = SimplifyDemandedVectorElts(II->getOperand(1), 1,
8177 UndefElts)) {
8178 II->setOperand(1, V);
8179 return II;
8180 }
8181 break;
8182 }
8183
Chris Lattnere2ed0572006-04-06 19:19:17 +00008184 case Intrinsic::ppc_altivec_vperm:
8185 // Turn vperm(V1,V2,mask) -> shuffle(V1,V2,mask) if mask is a constant.
Reid Spencer9d6565a2007-02-15 02:26:10 +00008186 if (ConstantVector *Mask = dyn_cast<ConstantVector>(II->getOperand(3))) {
Chris Lattnere2ed0572006-04-06 19:19:17 +00008187 assert(Mask->getNumOperands() == 16 && "Bad type for intrinsic!");
8188
8189 // Check that all of the elements are integer constants or undefs.
8190 bool AllEltsOk = true;
8191 for (unsigned i = 0; i != 16; ++i) {
8192 if (!isa<ConstantInt>(Mask->getOperand(i)) &&
8193 !isa<UndefValue>(Mask->getOperand(i))) {
8194 AllEltsOk = false;
8195 break;
8196 }
8197 }
8198
8199 if (AllEltsOk) {
8200 // Cast the input vectors to byte vectors.
Chris Lattner6d0339d2008-01-13 22:23:22 +00008201 Value *Op0 =InsertBitCastBefore(II->getOperand(1),Mask->getType(),CI);
8202 Value *Op1 =InsertBitCastBefore(II->getOperand(2),Mask->getType(),CI);
Chris Lattnere2ed0572006-04-06 19:19:17 +00008203 Value *Result = UndefValue::get(Op0->getType());
8204
8205 // Only extract each element once.
8206 Value *ExtractedElts[32];
8207 memset(ExtractedElts, 0, sizeof(ExtractedElts));
8208
8209 for (unsigned i = 0; i != 16; ++i) {
8210 if (isa<UndefValue>(Mask->getOperand(i)))
8211 continue;
Chris Lattnere34e9a22007-04-14 23:32:02 +00008212 unsigned Idx=cast<ConstantInt>(Mask->getOperand(i))->getZExtValue();
Chris Lattnere2ed0572006-04-06 19:19:17 +00008213 Idx &= 31; // Match the hardware behavior.
8214
8215 if (ExtractedElts[Idx] == 0) {
8216 Instruction *Elt =
Chris Lattner867b99f2006-10-05 06:55:50 +00008217 new ExtractElementInst(Idx < 16 ? Op0 : Op1, Idx&15, "tmp");
Chris Lattnere2ed0572006-04-06 19:19:17 +00008218 InsertNewInstBefore(Elt, CI);
8219 ExtractedElts[Idx] = Elt;
8220 }
8221
8222 // Insert this value into the result vector.
Chris Lattner867b99f2006-10-05 06:55:50 +00008223 Result = new InsertElementInst(Result, ExtractedElts[Idx], i,"tmp");
Chris Lattnere2ed0572006-04-06 19:19:17 +00008224 InsertNewInstBefore(cast<Instruction>(Result), CI);
8225 }
Reid Spencer3da59db2006-11-27 01:05:10 +00008226 return CastInst::create(Instruction::BitCast, Result, CI.getType());
Chris Lattnere2ed0572006-04-06 19:19:17 +00008227 }
8228 }
8229 break;
8230
Chris Lattnera728ddc2006-01-13 21:28:09 +00008231 case Intrinsic::stackrestore: {
8232 // If the save is right next to the restore, remove the restore. This can
8233 // happen when variable allocas are DCE'd.
8234 if (IntrinsicInst *SS = dyn_cast<IntrinsicInst>(II->getOperand(1))) {
8235 if (SS->getIntrinsicID() == Intrinsic::stacksave) {
8236 BasicBlock::iterator BI = SS;
8237 if (&*++BI == II)
8238 return EraseInstFromFunction(CI);
8239 }
8240 }
8241
Chris Lattnerbf1d8a72008-02-18 06:12:38 +00008242 // Scan down this block to see if there is another stack restore in the
8243 // same block without an intervening call/alloca.
8244 BasicBlock::iterator BI = II;
Chris Lattnera728ddc2006-01-13 21:28:09 +00008245 TerminatorInst *TI = II->getParent()->getTerminator();
Chris Lattnerbf1d8a72008-02-18 06:12:38 +00008246 bool CannotRemove = false;
8247 for (++BI; &*BI != TI; ++BI) {
8248 if (isa<AllocaInst>(BI)) {
8249 CannotRemove = true;
8250 break;
8251 }
8252 if (isa<CallInst>(BI)) {
8253 if (!isa<IntrinsicInst>(BI)) {
Chris Lattnera728ddc2006-01-13 21:28:09 +00008254 CannotRemove = true;
8255 break;
8256 }
Chris Lattnerbf1d8a72008-02-18 06:12:38 +00008257 // If there is a stackrestore below this one, remove this one.
Chris Lattnera728ddc2006-01-13 21:28:09 +00008258 return EraseInstFromFunction(CI);
Chris Lattnerbf1d8a72008-02-18 06:12:38 +00008259 }
Chris Lattnera728ddc2006-01-13 21:28:09 +00008260 }
Chris Lattnerbf1d8a72008-02-18 06:12:38 +00008261
8262 // If the stack restore is in a return/unwind block and if there are no
8263 // allocas or calls between the restore and the return, nuke the restore.
8264 if (!CannotRemove && (isa<ReturnInst>(TI) || isa<UnwindInst>(TI)))
8265 return EraseInstFromFunction(CI);
Chris Lattnera728ddc2006-01-13 21:28:09 +00008266 break;
8267 }
8268 }
Chris Lattner35b9e482004-10-12 04:52:52 +00008269 }
8270
Chris Lattner8b0ea312006-01-13 20:11:04 +00008271 return visitCallSite(II);
Chris Lattner9fe38862003-06-19 17:00:31 +00008272}
8273
8274// InvokeInst simplification
8275//
8276Instruction *InstCombiner::visitInvokeInst(InvokeInst &II) {
Chris Lattnera44d8a22003-10-07 22:32:43 +00008277 return visitCallSite(&II);
Chris Lattner9fe38862003-06-19 17:00:31 +00008278}
8279
Chris Lattnera44d8a22003-10-07 22:32:43 +00008280// visitCallSite - Improvements for call and invoke instructions.
8281//
8282Instruction *InstCombiner::visitCallSite(CallSite CS) {
Chris Lattner6c266db2003-10-07 22:54:13 +00008283 bool Changed = false;
8284
8285 // If the callee is a constexpr cast of a function, attempt to move the cast
8286 // to the arguments of the call/invoke.
Chris Lattnera44d8a22003-10-07 22:32:43 +00008287 if (transformConstExprCastCall(CS)) return 0;
8288
Chris Lattner6c266db2003-10-07 22:54:13 +00008289 Value *Callee = CS.getCalledValue();
Chris Lattnere87597f2004-10-16 18:11:37 +00008290
Chris Lattner08b22ec2005-05-13 07:09:09 +00008291 if (Function *CalleeF = dyn_cast<Function>(Callee))
8292 if (CalleeF->getCallingConv() != CS.getCallingConv()) {
8293 Instruction *OldCall = CS.getInstruction();
8294 // If the call and callee calling conventions don't match, this call must
8295 // be unreachable, as the call is undefined.
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00008296 new StoreInst(ConstantInt::getTrue(),
Christopher Lamb43ad6b32007-12-17 01:12:55 +00008297 UndefValue::get(PointerType::getUnqual(Type::Int1Ty)),
8298 OldCall);
Chris Lattner08b22ec2005-05-13 07:09:09 +00008299 if (!OldCall->use_empty())
8300 OldCall->replaceAllUsesWith(UndefValue::get(OldCall->getType()));
8301 if (isa<CallInst>(OldCall)) // Not worth removing an invoke here.
8302 return EraseInstFromFunction(*OldCall);
8303 return 0;
8304 }
8305
Chris Lattner17be6352004-10-18 02:59:09 +00008306 if (isa<ConstantPointerNull>(Callee) || isa<UndefValue>(Callee)) {
8307 // This instruction is not reachable, just remove it. We insert a store to
8308 // undef so that we know that this code is not reachable, despite the fact
8309 // that we can't modify the CFG here.
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00008310 new StoreInst(ConstantInt::getTrue(),
Christopher Lamb43ad6b32007-12-17 01:12:55 +00008311 UndefValue::get(PointerType::getUnqual(Type::Int1Ty)),
Chris Lattner17be6352004-10-18 02:59:09 +00008312 CS.getInstruction());
8313
8314 if (!CS.getInstruction()->use_empty())
8315 CS.getInstruction()->
8316 replaceAllUsesWith(UndefValue::get(CS.getInstruction()->getType()));
8317
8318 if (InvokeInst *II = dyn_cast<InvokeInst>(CS.getInstruction())) {
8319 // Don't break the CFG, insert a dummy cond branch.
8320 new BranchInst(II->getNormalDest(), II->getUnwindDest(),
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00008321 ConstantInt::getTrue(), II);
Chris Lattnere87597f2004-10-16 18:11:37 +00008322 }
Chris Lattner17be6352004-10-18 02:59:09 +00008323 return EraseInstFromFunction(*CS.getInstruction());
8324 }
Chris Lattnere87597f2004-10-16 18:11:37 +00008325
Duncan Sandscdb6d922007-09-17 10:26:40 +00008326 if (BitCastInst *BC = dyn_cast<BitCastInst>(Callee))
8327 if (IntrinsicInst *In = dyn_cast<IntrinsicInst>(BC->getOperand(0)))
8328 if (In->getIntrinsicID() == Intrinsic::init_trampoline)
8329 return transformCallThroughTrampoline(CS);
8330
Chris Lattner6c266db2003-10-07 22:54:13 +00008331 const PointerType *PTy = cast<PointerType>(Callee->getType());
8332 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
8333 if (FTy->isVarArg()) {
8334 // See if we can optimize any arguments passed through the varargs area of
8335 // the call.
8336 for (CallSite::arg_iterator I = CS.arg_begin()+FTy->getNumParams(),
8337 E = CS.arg_end(); I != E; ++I)
8338 if (CastInst *CI = dyn_cast<CastInst>(*I)) {
8339 // If this cast does not effect the value passed through the varargs
8340 // area, we can eliminate the use of the cast.
8341 Value *Op = CI->getOperand(0);
Reid Spencer3da59db2006-11-27 01:05:10 +00008342 if (CI->isLosslessCast()) {
Chris Lattner6c266db2003-10-07 22:54:13 +00008343 *I = Op;
8344 Changed = true;
8345 }
8346 }
8347 }
Misha Brukmanfd939082005-04-21 23:48:37 +00008348
Duncan Sandsf0c33542007-12-19 21:13:37 +00008349 if (isa<InlineAsm>(Callee) && !CS.doesNotThrow()) {
Duncan Sandsece2c042007-12-16 15:51:49 +00008350 // Inline asm calls cannot throw - mark them 'nounwind'.
Duncan Sandsf0c33542007-12-19 21:13:37 +00008351 CS.setDoesNotThrow();
Duncan Sandsece2c042007-12-16 15:51:49 +00008352 Changed = true;
8353 }
8354
Chris Lattner6c266db2003-10-07 22:54:13 +00008355 return Changed ? CS.getInstruction() : 0;
Chris Lattnera44d8a22003-10-07 22:32:43 +00008356}
8357
Chris Lattner9fe38862003-06-19 17:00:31 +00008358// transformConstExprCastCall - If the callee is a constexpr cast of a function,
8359// attempt to move the cast to the arguments of the call/invoke.
8360//
8361bool InstCombiner::transformConstExprCastCall(CallSite CS) {
8362 if (!isa<ConstantExpr>(CS.getCalledValue())) return false;
8363 ConstantExpr *CE = cast<ConstantExpr>(CS.getCalledValue());
Reid Spencer3da59db2006-11-27 01:05:10 +00008364 if (CE->getOpcode() != Instruction::BitCast ||
8365 !isa<Function>(CE->getOperand(0)))
Chris Lattner9fe38862003-06-19 17:00:31 +00008366 return false;
Reid Spencer8863f182004-07-18 00:38:32 +00008367 Function *Callee = cast<Function>(CE->getOperand(0));
Chris Lattner9fe38862003-06-19 17:00:31 +00008368 Instruction *Caller = CS.getInstruction();
Duncan Sandsad9a9e12008-01-06 18:27:01 +00008369 const ParamAttrsList* CallerPAL = CS.getParamAttrs();
Chris Lattner9fe38862003-06-19 17:00:31 +00008370
8371 // Okay, this is a cast from a function to a different type. Unless doing so
8372 // would cause a type conversion of one of our arguments, change this call to
8373 // be a direct call with arguments casted to the appropriate types.
8374 //
8375 const FunctionType *FT = Callee->getFunctionType();
8376 const Type *OldRetTy = Caller->getType();
8377
Chris Lattnerf78616b2004-01-14 06:06:08 +00008378 // Check to see if we are changing the return type...
8379 if (OldRetTy != FT->getReturnType()) {
Reid Spencer5cbf9852007-01-30 20:08:39 +00008380 if (Callee->isDeclaration() && !Caller->use_empty() &&
Chris Lattner46013f42007-01-06 19:53:32 +00008381 // Conversion is ok if changing from pointer to int of same size.
8382 !(isa<PointerType>(FT->getReturnType()) &&
8383 TD->getIntPtrType() == OldRetTy))
Chris Lattnerec479922007-01-06 02:09:32 +00008384 return false; // Cannot transform this return value.
Chris Lattnerf78616b2004-01-14 06:06:08 +00008385
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +00008386 if (!Caller->use_empty() &&
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +00008387 // void -> non-void is handled specially
Duncan Sandse1e520f2008-01-13 08:02:44 +00008388 FT->getReturnType() != Type::VoidTy &&
8389 !CastInst::isCastable(FT->getReturnType(), OldRetTy))
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +00008390 return false; // Cannot transform this return value.
8391
Duncan Sands6c3470e2008-01-07 17:16:06 +00008392 if (CallerPAL && !Caller->use_empty()) {
Dale Johannesen0d51e7e2008-02-19 21:38:47 +00008393 ParameterAttributes RAttrs = CallerPAL->getParamAttrs(0);
Duncan Sands6c3470e2008-01-07 17:16:06 +00008394 if (RAttrs & ParamAttr::typeIncompatible(FT->getReturnType()))
8395 return false; // Attribute not compatible with transformed value.
8396 }
Duncan Sandsad9a9e12008-01-06 18:27:01 +00008397
Chris Lattnerf78616b2004-01-14 06:06:08 +00008398 // If the callsite is an invoke instruction, and the return value is used by
8399 // a PHI node in a successor, we cannot change the return type of the call
8400 // because there is no place to put the cast instruction (without breaking
8401 // the critical edge). Bail out in this case.
8402 if (!Caller->use_empty())
8403 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller))
8404 for (Value::use_iterator UI = II->use_begin(), E = II->use_end();
8405 UI != E; ++UI)
8406 if (PHINode *PN = dyn_cast<PHINode>(*UI))
8407 if (PN->getParent() == II->getNormalDest() ||
Chris Lattneraeb2a1d2004-02-08 21:44:31 +00008408 PN->getParent() == II->getUnwindDest())
Chris Lattnerf78616b2004-01-14 06:06:08 +00008409 return false;
8410 }
Chris Lattner9fe38862003-06-19 17:00:31 +00008411
8412 unsigned NumActualArgs = unsigned(CS.arg_end()-CS.arg_begin());
8413 unsigned NumCommonArgs = std::min(FT->getNumParams(), NumActualArgs);
Misha Brukmanfd939082005-04-21 23:48:37 +00008414
Chris Lattner9fe38862003-06-19 17:00:31 +00008415 CallSite::arg_iterator AI = CS.arg_begin();
8416 for (unsigned i = 0, e = NumCommonArgs; i != e; ++i, ++AI) {
8417 const Type *ParamTy = FT->getParamType(i);
Andrew Lenharthb8e604c2006-06-28 01:01:52 +00008418 const Type *ActTy = (*AI)->getType();
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +00008419
8420 if (!CastInst::isCastable(ActTy, ParamTy))
Duncan Sandsad9a9e12008-01-06 18:27:01 +00008421 return false; // Cannot transform this parameter value.
8422
Duncan Sands6c3470e2008-01-07 17:16:06 +00008423 if (CallerPAL) {
Dale Johannesen0d51e7e2008-02-19 21:38:47 +00008424 ParameterAttributes PAttrs = CallerPAL->getParamAttrs(i + 1);
Duncan Sands6c3470e2008-01-07 17:16:06 +00008425 if (PAttrs & ParamAttr::typeIncompatible(ParamTy))
8426 return false; // Attribute not compatible with transformed value.
8427 }
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +00008428
Reid Spencer3da59db2006-11-27 01:05:10 +00008429 ConstantInt *c = dyn_cast<ConstantInt>(*AI);
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +00008430 // Some conversions are safe even if we do not have a body.
8431 // Either we can cast directly, or we can upconvert the argument
Chris Lattnerec479922007-01-06 02:09:32 +00008432 bool isConvertible = ActTy == ParamTy ||
Chris Lattner46013f42007-01-06 19:53:32 +00008433 (isa<PointerType>(ParamTy) && isa<PointerType>(ActTy)) ||
Chris Lattner42a75512007-01-15 02:27:26 +00008434 (ParamTy->isInteger() && ActTy->isInteger() &&
Reid Spencerabaa8ca2007-01-08 16:32:00 +00008435 ParamTy->getPrimitiveSizeInBits() >= ActTy->getPrimitiveSizeInBits()) ||
8436 (c && ParamTy->getPrimitiveSizeInBits() >= ActTy->getPrimitiveSizeInBits()
Zhou Sheng0fc50952007-03-25 05:01:29 +00008437 && c->getValue().isStrictlyPositive());
Reid Spencer5cbf9852007-01-30 20:08:39 +00008438 if (Callee->isDeclaration() && !isConvertible) return false;
Chris Lattner9fe38862003-06-19 17:00:31 +00008439 }
8440
8441 if (FT->getNumParams() < NumActualArgs && !FT->isVarArg() &&
Reid Spencer5cbf9852007-01-30 20:08:39 +00008442 Callee->isDeclaration())
Chris Lattner9fe38862003-06-19 17:00:31 +00008443 return false; // Do not delete arguments unless we have a function body...
8444
Duncan Sandse1e520f2008-01-13 08:02:44 +00008445 if (FT->getNumParams() < NumActualArgs && FT->isVarArg() && CallerPAL)
Duncan Sandsad9a9e12008-01-06 18:27:01 +00008446 // In this case we have more arguments than the new function type, but we
Duncan Sandse1e520f2008-01-13 08:02:44 +00008447 // won't be dropping them. Check that these extra arguments have attributes
8448 // that are compatible with being a vararg call argument.
8449 for (unsigned i = CallerPAL->size(); i; --i) {
8450 if (CallerPAL->getParamIndex(i - 1) <= FT->getNumParams())
8451 break;
Dale Johannesen0d51e7e2008-02-19 21:38:47 +00008452 ParameterAttributes PAttrs = CallerPAL->getParamAttrsAtIndex(i - 1);
Duncan Sandse1e520f2008-01-13 08:02:44 +00008453 if (PAttrs & ParamAttr::VarArgsIncompatible)
8454 return false;
8455 }
Duncan Sandsad9a9e12008-01-06 18:27:01 +00008456
Chris Lattner9fe38862003-06-19 17:00:31 +00008457 // Okay, we decided that this is a safe thing to do: go ahead and start
8458 // inserting cast instructions as necessary...
8459 std::vector<Value*> Args;
8460 Args.reserve(NumActualArgs);
Duncan Sandsad9a9e12008-01-06 18:27:01 +00008461 ParamAttrsVector attrVec;
8462 attrVec.reserve(NumCommonArgs);
8463
8464 // Get any return attributes.
Dale Johannesen0d51e7e2008-02-19 21:38:47 +00008465 ParameterAttributes RAttrs = CallerPAL ? CallerPAL->getParamAttrs(0) :
8466 ParamAttr::None;
Duncan Sandsad9a9e12008-01-06 18:27:01 +00008467
8468 // If the return value is not being used, the type may not be compatible
8469 // with the existing attributes. Wipe out any problematic attributes.
Duncan Sands6c3470e2008-01-07 17:16:06 +00008470 RAttrs &= ~ParamAttr::typeIncompatible(FT->getReturnType());
Duncan Sandsad9a9e12008-01-06 18:27:01 +00008471
8472 // Add the new return attributes.
8473 if (RAttrs)
8474 attrVec.push_back(ParamAttrsWithIndex::get(0, RAttrs));
Chris Lattner9fe38862003-06-19 17:00:31 +00008475
8476 AI = CS.arg_begin();
8477 for (unsigned i = 0; i != NumCommonArgs; ++i, ++AI) {
8478 const Type *ParamTy = FT->getParamType(i);
8479 if ((*AI)->getType() == ParamTy) {
8480 Args.push_back(*AI);
8481 } else {
Reid Spencer8a903db2006-12-18 08:47:13 +00008482 Instruction::CastOps opcode = CastInst::getCastOpcode(*AI,
Reid Spencerc5b206b2006-12-31 05:48:39 +00008483 false, ParamTy, false);
Reid Spencer8a903db2006-12-18 08:47:13 +00008484 CastInst *NewCast = CastInst::create(opcode, *AI, ParamTy, "tmp");
Reid Spencer3da59db2006-11-27 01:05:10 +00008485 Args.push_back(InsertNewInstBefore(NewCast, *Caller));
Chris Lattner9fe38862003-06-19 17:00:31 +00008486 }
Duncan Sandsad9a9e12008-01-06 18:27:01 +00008487
8488 // Add any parameter attributes.
Dale Johannesen0d51e7e2008-02-19 21:38:47 +00008489 ParameterAttributes PAttrs = CallerPAL ? CallerPAL->getParamAttrs(i + 1) :
8490 ParamAttr::None;
Duncan Sandsad9a9e12008-01-06 18:27:01 +00008491 if (PAttrs)
8492 attrVec.push_back(ParamAttrsWithIndex::get(i + 1, PAttrs));
Chris Lattner9fe38862003-06-19 17:00:31 +00008493 }
8494
8495 // If the function takes more arguments than the call was taking, add them
8496 // now...
8497 for (unsigned i = NumCommonArgs; i != FT->getNumParams(); ++i)
8498 Args.push_back(Constant::getNullValue(FT->getParamType(i)));
8499
8500 // If we are removing arguments to the function, emit an obnoxious warning...
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00008501 if (FT->getNumParams() < NumActualArgs) {
Chris Lattner9fe38862003-06-19 17:00:31 +00008502 if (!FT->isVarArg()) {
Bill Wendlinge8156192006-12-07 01:30:32 +00008503 cerr << "WARNING: While resolving call to function '"
8504 << Callee->getName() << "' arguments were dropped!\n";
Chris Lattner9fe38862003-06-19 17:00:31 +00008505 } else {
8506 // Add all of the arguments in their promoted form to the arg list...
8507 for (unsigned i = FT->getNumParams(); i != NumActualArgs; ++i, ++AI) {
8508 const Type *PTy = getPromotedType((*AI)->getType());
8509 if (PTy != (*AI)->getType()) {
8510 // Must promote to pass through va_arg area!
Reid Spencerc5b206b2006-12-31 05:48:39 +00008511 Instruction::CastOps opcode = CastInst::getCastOpcode(*AI, false,
8512 PTy, false);
Reid Spencer8a903db2006-12-18 08:47:13 +00008513 Instruction *Cast = CastInst::create(opcode, *AI, PTy, "tmp");
Chris Lattner9fe38862003-06-19 17:00:31 +00008514 InsertNewInstBefore(Cast, *Caller);
8515 Args.push_back(Cast);
8516 } else {
8517 Args.push_back(*AI);
8518 }
Duncan Sandsad9a9e12008-01-06 18:27:01 +00008519
Duncan Sandse1e520f2008-01-13 08:02:44 +00008520 // Add any parameter attributes.
Dale Johannesen0d51e7e2008-02-19 21:38:47 +00008521 ParameterAttributes PAttrs = CallerPAL ?
8522 CallerPAL->getParamAttrs(i + 1) :
8523 ParamAttr::None;
Duncan Sandse1e520f2008-01-13 08:02:44 +00008524 if (PAttrs)
8525 attrVec.push_back(ParamAttrsWithIndex::get(i + 1, PAttrs));
8526 }
Chris Lattner9fe38862003-06-19 17:00:31 +00008527 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00008528 }
Chris Lattner9fe38862003-06-19 17:00:31 +00008529
8530 if (FT->getReturnType() == Type::VoidTy)
Chris Lattner6934a042007-02-11 01:23:03 +00008531 Caller->setName(""); // Void type should not have a name.
Chris Lattner9fe38862003-06-19 17:00:31 +00008532
Duncan Sandsad9a9e12008-01-06 18:27:01 +00008533 const ParamAttrsList* NewCallerPAL = ParamAttrsList::get(attrVec);
8534
Chris Lattner9fe38862003-06-19 17:00:31 +00008535 Instruction *NC;
8536 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Chris Lattneraeb2a1d2004-02-08 21:44:31 +00008537 NC = new InvokeInst(Callee, II->getNormalDest(), II->getUnwindDest(),
David Greenef1355a52007-08-27 19:04:21 +00008538 Args.begin(), Args.end(), Caller->getName(), Caller);
Reid Spencered3fa852007-07-30 19:53:57 +00008539 cast<InvokeInst>(NC)->setCallingConv(II->getCallingConv());
Duncan Sandsad9a9e12008-01-06 18:27:01 +00008540 cast<InvokeInst>(NC)->setParamAttrs(NewCallerPAL);
Chris Lattner9fe38862003-06-19 17:00:31 +00008541 } else {
Chris Lattner684b22d2007-08-02 16:53:43 +00008542 NC = new CallInst(Callee, Args.begin(), Args.end(),
8543 Caller->getName(), Caller);
Duncan Sandsdc024672007-11-27 13:23:08 +00008544 CallInst *CI = cast<CallInst>(Caller);
8545 if (CI->isTailCall())
Chris Lattnera9e92112005-05-06 06:48:21 +00008546 cast<CallInst>(NC)->setTailCall();
Duncan Sandsdc024672007-11-27 13:23:08 +00008547 cast<CallInst>(NC)->setCallingConv(CI->getCallingConv());
Duncan Sandsad9a9e12008-01-06 18:27:01 +00008548 cast<CallInst>(NC)->setParamAttrs(NewCallerPAL);
Chris Lattner9fe38862003-06-19 17:00:31 +00008549 }
8550
Chris Lattner6934a042007-02-11 01:23:03 +00008551 // Insert a cast of the return type as necessary.
Chris Lattner9fe38862003-06-19 17:00:31 +00008552 Value *NV = NC;
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +00008553 if (OldRetTy != NV->getType() && !Caller->use_empty()) {
Chris Lattner9fe38862003-06-19 17:00:31 +00008554 if (NV->getType() != Type::VoidTy) {
Reid Spencerc5b206b2006-12-31 05:48:39 +00008555 Instruction::CastOps opcode = CastInst::getCastOpcode(NC, false,
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +00008556 OldRetTy, false);
8557 NV = NC = CastInst::create(opcode, NC, OldRetTy, "tmp");
Chris Lattnerbb609042003-10-30 00:46:41 +00008558
8559 // If this is an invoke instruction, we should insert it after the first
8560 // non-phi, instruction in the normal successor block.
8561 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
8562 BasicBlock::iterator I = II->getNormalDest()->begin();
8563 while (isa<PHINode>(I)) ++I;
8564 InsertNewInstBefore(NC, *I);
8565 } else {
8566 // Otherwise, it's a call, just insert cast right after the call instr
8567 InsertNewInstBefore(NC, *Caller);
8568 }
Chris Lattner7bcc0e72004-02-28 05:22:00 +00008569 AddUsersToWorkList(*Caller);
Chris Lattner9fe38862003-06-19 17:00:31 +00008570 } else {
Chris Lattnerc30bda72004-10-17 21:22:38 +00008571 NV = UndefValue::get(Caller->getType());
Chris Lattner9fe38862003-06-19 17:00:31 +00008572 }
8573 }
8574
8575 if (Caller->getType() != Type::VoidTy && !Caller->use_empty())
8576 Caller->replaceAllUsesWith(NV);
Chris Lattnerf22a5c62007-03-02 19:59:19 +00008577 Caller->eraseFromParent();
Chris Lattnerdbab3862007-03-02 21:28:56 +00008578 RemoveFromWorkList(Caller);
Chris Lattner9fe38862003-06-19 17:00:31 +00008579 return true;
8580}
8581
Duncan Sandscdb6d922007-09-17 10:26:40 +00008582// transformCallThroughTrampoline - Turn a call to a function created by the
8583// init_trampoline intrinsic into a direct call to the underlying function.
8584//
8585Instruction *InstCombiner::transformCallThroughTrampoline(CallSite CS) {
8586 Value *Callee = CS.getCalledValue();
8587 const PointerType *PTy = cast<PointerType>(Callee->getType());
8588 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
Duncan Sandsb0c9b932008-01-14 19:52:09 +00008589 const ParamAttrsList *Attrs = CS.getParamAttrs();
8590
8591 // If the call already has the 'nest' attribute somewhere then give up -
8592 // otherwise 'nest' would occur twice after splicing in the chain.
8593 if (Attrs && Attrs->hasAttrSomewhere(ParamAttr::Nest))
8594 return 0;
Duncan Sandscdb6d922007-09-17 10:26:40 +00008595
8596 IntrinsicInst *Tramp =
8597 cast<IntrinsicInst>(cast<BitCastInst>(Callee)->getOperand(0));
8598
8599 Function *NestF =
8600 cast<Function>(IntrinsicInst::StripPointerCasts(Tramp->getOperand(2)));
8601 const PointerType *NestFPTy = cast<PointerType>(NestF->getType());
8602 const FunctionType *NestFTy = cast<FunctionType>(NestFPTy->getElementType());
8603
Duncan Sandsdc024672007-11-27 13:23:08 +00008604 if (const ParamAttrsList *NestAttrs = NestF->getParamAttrs()) {
Duncan Sandscdb6d922007-09-17 10:26:40 +00008605 unsigned NestIdx = 1;
8606 const Type *NestTy = 0;
Dale Johannesen0d51e7e2008-02-19 21:38:47 +00008607 ParameterAttributes NestAttr = ParamAttr::None;
Duncan Sandscdb6d922007-09-17 10:26:40 +00008608
8609 // Look for a parameter marked with the 'nest' attribute.
8610 for (FunctionType::param_iterator I = NestFTy->param_begin(),
8611 E = NestFTy->param_end(); I != E; ++NestIdx, ++I)
8612 if (NestAttrs->paramHasAttr(NestIdx, ParamAttr::Nest)) {
8613 // Record the parameter type and any other attributes.
8614 NestTy = *I;
8615 NestAttr = NestAttrs->getParamAttrs(NestIdx);
8616 break;
8617 }
8618
8619 if (NestTy) {
8620 Instruction *Caller = CS.getInstruction();
8621 std::vector<Value*> NewArgs;
8622 NewArgs.reserve(unsigned(CS.arg_end()-CS.arg_begin())+1);
8623
Duncan Sandsb0c9b932008-01-14 19:52:09 +00008624 ParamAttrsVector NewAttrs;
8625 NewAttrs.reserve(Attrs ? Attrs->size() + 1 : 1);
8626
Duncan Sandscdb6d922007-09-17 10:26:40 +00008627 // Insert the nest argument into the call argument list, which may
Duncan Sandsb0c9b932008-01-14 19:52:09 +00008628 // mean appending it. Likewise for attributes.
8629
8630 // Add any function result attributes.
Dale Johannesen0d51e7e2008-02-19 21:38:47 +00008631 ParameterAttributes Attr = Attrs ? Attrs->getParamAttrs(0) :
8632 ParamAttr::None;
Duncan Sandsb0c9b932008-01-14 19:52:09 +00008633 if (Attr)
8634 NewAttrs.push_back (ParamAttrsWithIndex::get(0, Attr));
8635
Duncan Sandscdb6d922007-09-17 10:26:40 +00008636 {
8637 unsigned Idx = 1;
8638 CallSite::arg_iterator I = CS.arg_begin(), E = CS.arg_end();
8639 do {
8640 if (Idx == NestIdx) {
Duncan Sandsb0c9b932008-01-14 19:52:09 +00008641 // Add the chain argument and attributes.
Duncan Sandscdb6d922007-09-17 10:26:40 +00008642 Value *NestVal = Tramp->getOperand(3);
8643 if (NestVal->getType() != NestTy)
8644 NestVal = new BitCastInst(NestVal, NestTy, "nest", Caller);
8645 NewArgs.push_back(NestVal);
Duncan Sandsb0c9b932008-01-14 19:52:09 +00008646 NewAttrs.push_back(ParamAttrsWithIndex::get(NestIdx, NestAttr));
Duncan Sandscdb6d922007-09-17 10:26:40 +00008647 }
8648
8649 if (I == E)
8650 break;
8651
Duncan Sandsb0c9b932008-01-14 19:52:09 +00008652 // Add the original argument and attributes.
Duncan Sandscdb6d922007-09-17 10:26:40 +00008653 NewArgs.push_back(*I);
Duncan Sandsb0c9b932008-01-14 19:52:09 +00008654 Attr = Attrs ? Attrs->getParamAttrs(Idx) : 0;
8655 if (Attr)
8656 NewAttrs.push_back
8657 (ParamAttrsWithIndex::get(Idx + (Idx >= NestIdx), Attr));
Duncan Sandscdb6d922007-09-17 10:26:40 +00008658
8659 ++Idx, ++I;
8660 } while (1);
8661 }
8662
8663 // The trampoline may have been bitcast to a bogus type (FTy).
8664 // Handle this by synthesizing a new function type, equal to FTy
Duncan Sandsb0c9b932008-01-14 19:52:09 +00008665 // with the chain parameter inserted.
Duncan Sandscdb6d922007-09-17 10:26:40 +00008666
Duncan Sandscdb6d922007-09-17 10:26:40 +00008667 std::vector<const Type*> NewTypes;
Duncan Sandscdb6d922007-09-17 10:26:40 +00008668 NewTypes.reserve(FTy->getNumParams()+1);
8669
Duncan Sandscdb6d922007-09-17 10:26:40 +00008670 // Insert the chain's type into the list of parameter types, which may
Duncan Sandsb0c9b932008-01-14 19:52:09 +00008671 // mean appending it.
Duncan Sandscdb6d922007-09-17 10:26:40 +00008672 {
8673 unsigned Idx = 1;
8674 FunctionType::param_iterator I = FTy->param_begin(),
8675 E = FTy->param_end();
8676
8677 do {
Duncan Sandsb0c9b932008-01-14 19:52:09 +00008678 if (Idx == NestIdx)
8679 // Add the chain's type.
Duncan Sandscdb6d922007-09-17 10:26:40 +00008680 NewTypes.push_back(NestTy);
Duncan Sandscdb6d922007-09-17 10:26:40 +00008681
8682 if (I == E)
8683 break;
8684
Duncan Sandsb0c9b932008-01-14 19:52:09 +00008685 // Add the original type.
Duncan Sandscdb6d922007-09-17 10:26:40 +00008686 NewTypes.push_back(*I);
Duncan Sandscdb6d922007-09-17 10:26:40 +00008687
8688 ++Idx, ++I;
8689 } while (1);
8690 }
8691
8692 // Replace the trampoline call with a direct call. Let the generic
8693 // code sort out any function type mismatches.
8694 FunctionType *NewFTy =
Duncan Sandsdc024672007-11-27 13:23:08 +00008695 FunctionType::get(FTy->getReturnType(), NewTypes, FTy->isVarArg());
Christopher Lamb43ad6b32007-12-17 01:12:55 +00008696 Constant *NewCallee = NestF->getType() == PointerType::getUnqual(NewFTy) ?
8697 NestF : ConstantExpr::getBitCast(NestF, PointerType::getUnqual(NewFTy));
Duncan Sandsdc024672007-11-27 13:23:08 +00008698 const ParamAttrsList *NewPAL = ParamAttrsList::get(NewAttrs);
Duncan Sandscdb6d922007-09-17 10:26:40 +00008699
8700 Instruction *NewCaller;
8701 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
8702 NewCaller = new InvokeInst(NewCallee,
8703 II->getNormalDest(), II->getUnwindDest(),
8704 NewArgs.begin(), NewArgs.end(),
8705 Caller->getName(), Caller);
8706 cast<InvokeInst>(NewCaller)->setCallingConv(II->getCallingConv());
Duncan Sandsdc024672007-11-27 13:23:08 +00008707 cast<InvokeInst>(NewCaller)->setParamAttrs(NewPAL);
Duncan Sandscdb6d922007-09-17 10:26:40 +00008708 } else {
8709 NewCaller = new CallInst(NewCallee, NewArgs.begin(), NewArgs.end(),
8710 Caller->getName(), Caller);
8711 if (cast<CallInst>(Caller)->isTailCall())
8712 cast<CallInst>(NewCaller)->setTailCall();
8713 cast<CallInst>(NewCaller)->
8714 setCallingConv(cast<CallInst>(Caller)->getCallingConv());
Duncan Sandsdc024672007-11-27 13:23:08 +00008715 cast<CallInst>(NewCaller)->setParamAttrs(NewPAL);
Duncan Sandscdb6d922007-09-17 10:26:40 +00008716 }
8717 if (Caller->getType() != Type::VoidTy && !Caller->use_empty())
8718 Caller->replaceAllUsesWith(NewCaller);
8719 Caller->eraseFromParent();
8720 RemoveFromWorkList(Caller);
8721 return 0;
8722 }
8723 }
8724
8725 // Replace the trampoline call with a direct call. Since there is no 'nest'
8726 // parameter, there is no need to adjust the argument list. Let the generic
8727 // code sort out any function type mismatches.
8728 Constant *NewCallee =
8729 NestF->getType() == PTy ? NestF : ConstantExpr::getBitCast(NestF, PTy);
8730 CS.setCalledFunction(NewCallee);
8731 return CS.getInstruction();
8732}
8733
Chris Lattner7da52b22006-11-01 04:51:18 +00008734/// FoldPHIArgBinOpIntoPHI - If we have something like phi [add (a,b), add(c,d)]
8735/// and if a/b/c/d and the add's all have a single use, turn this into two phi's
8736/// and a single binop.
8737Instruction *InstCombiner::FoldPHIArgBinOpIntoPHI(PHINode &PN) {
8738 Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
Reid Spencer832254e2007-02-02 02:16:23 +00008739 assert(isa<BinaryOperator>(FirstInst) || isa<GetElementPtrInst>(FirstInst) ||
8740 isa<CmpInst>(FirstInst));
Chris Lattner7da52b22006-11-01 04:51:18 +00008741 unsigned Opc = FirstInst->getOpcode();
Chris Lattnerf6fd94d2006-11-08 19:29:23 +00008742 Value *LHSVal = FirstInst->getOperand(0);
8743 Value *RHSVal = FirstInst->getOperand(1);
8744
8745 const Type *LHSType = LHSVal->getType();
8746 const Type *RHSType = RHSVal->getType();
Chris Lattner7da52b22006-11-01 04:51:18 +00008747
8748 // Scan to see if all operands are the same opcode, all have one use, and all
8749 // kill their operands (i.e. the operands have one use).
Chris Lattnera90a24c2006-11-01 04:55:47 +00008750 for (unsigned i = 0; i != PN.getNumIncomingValues(); ++i) {
Chris Lattner7da52b22006-11-01 04:51:18 +00008751 Instruction *I = dyn_cast<Instruction>(PN.getIncomingValue(i));
Chris Lattnera90a24c2006-11-01 04:55:47 +00008752 if (!I || I->getOpcode() != Opc || !I->hasOneUse() ||
Reid Spencere4d87aa2006-12-23 06:05:41 +00008753 // Verify type of the LHS matches so we don't fold cmp's of different
Chris Lattner9c080502006-11-01 07:43:41 +00008754 // types or GEP's with different index types.
8755 I->getOperand(0)->getType() != LHSType ||
8756 I->getOperand(1)->getType() != RHSType)
Chris Lattner7da52b22006-11-01 04:51:18 +00008757 return 0;
Reid Spencere4d87aa2006-12-23 06:05:41 +00008758
8759 // If they are CmpInst instructions, check their predicates
8760 if (Opc == Instruction::ICmp || Opc == Instruction::FCmp)
8761 if (cast<CmpInst>(I)->getPredicate() !=
8762 cast<CmpInst>(FirstInst)->getPredicate())
8763 return 0;
Chris Lattnerf6fd94d2006-11-08 19:29:23 +00008764
8765 // Keep track of which operand needs a phi node.
8766 if (I->getOperand(0) != LHSVal) LHSVal = 0;
8767 if (I->getOperand(1) != RHSVal) RHSVal = 0;
Chris Lattner7da52b22006-11-01 04:51:18 +00008768 }
8769
Chris Lattner53738a42006-11-08 19:42:28 +00008770 // Otherwise, this is safe to transform, determine if it is profitable.
8771
8772 // If this is a GEP, and if the index (not the pointer) needs a PHI, bail out.
8773 // Indexes are often folded into load/store instructions, so we don't want to
8774 // hide them behind a phi.
8775 if (isa<GetElementPtrInst>(FirstInst) && RHSVal == 0)
8776 return 0;
8777
Chris Lattner7da52b22006-11-01 04:51:18 +00008778 Value *InLHS = FirstInst->getOperand(0);
Chris Lattner7da52b22006-11-01 04:51:18 +00008779 Value *InRHS = FirstInst->getOperand(1);
Chris Lattner53738a42006-11-08 19:42:28 +00008780 PHINode *NewLHS = 0, *NewRHS = 0;
Chris Lattnerf6fd94d2006-11-08 19:29:23 +00008781 if (LHSVal == 0) {
8782 NewLHS = new PHINode(LHSType, FirstInst->getOperand(0)->getName()+".pn");
8783 NewLHS->reserveOperandSpace(PN.getNumOperands()/2);
8784 NewLHS->addIncoming(InLHS, PN.getIncomingBlock(0));
Chris Lattner9c080502006-11-01 07:43:41 +00008785 InsertNewInstBefore(NewLHS, PN);
8786 LHSVal = NewLHS;
8787 }
Chris Lattnerf6fd94d2006-11-08 19:29:23 +00008788
8789 if (RHSVal == 0) {
8790 NewRHS = new PHINode(RHSType, FirstInst->getOperand(1)->getName()+".pn");
8791 NewRHS->reserveOperandSpace(PN.getNumOperands()/2);
8792 NewRHS->addIncoming(InRHS, PN.getIncomingBlock(0));
Chris Lattner9c080502006-11-01 07:43:41 +00008793 InsertNewInstBefore(NewRHS, PN);
8794 RHSVal = NewRHS;
8795 }
8796
Chris Lattnerf6fd94d2006-11-08 19:29:23 +00008797 // Add all operands to the new PHIs.
8798 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
8799 if (NewLHS) {
8800 Value *NewInLHS =cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
8801 NewLHS->addIncoming(NewInLHS, PN.getIncomingBlock(i));
8802 }
8803 if (NewRHS) {
8804 Value *NewInRHS =cast<Instruction>(PN.getIncomingValue(i))->getOperand(1);
8805 NewRHS->addIncoming(NewInRHS, PN.getIncomingBlock(i));
8806 }
8807 }
8808
Chris Lattner7da52b22006-11-01 04:51:18 +00008809 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
Chris Lattner9c080502006-11-01 07:43:41 +00008810 return BinaryOperator::create(BinOp->getOpcode(), LHSVal, RHSVal);
Reid Spencere4d87aa2006-12-23 06:05:41 +00008811 else if (CmpInst *CIOp = dyn_cast<CmpInst>(FirstInst))
8812 return CmpInst::create(CIOp->getOpcode(), CIOp->getPredicate(), LHSVal,
8813 RHSVal);
Chris Lattner9c080502006-11-01 07:43:41 +00008814 else {
8815 assert(isa<GetElementPtrInst>(FirstInst));
8816 return new GetElementPtrInst(LHSVal, RHSVal);
8817 }
Chris Lattner7da52b22006-11-01 04:51:18 +00008818}
8819
Chris Lattner76c73142006-11-01 07:13:54 +00008820/// isSafeToSinkLoad - Return true if we know that it is safe sink the load out
8821/// of the block that defines it. This means that it must be obvious the value
8822/// of the load is not changed from the point of the load to the end of the
8823/// block it is in.
Chris Lattnerfd905ca2007-02-01 22:30:07 +00008824///
8825/// Finally, it is safe, but not profitable, to sink a load targetting a
8826/// non-address-taken alloca. Doing so will cause us to not promote the alloca
8827/// to a register.
Chris Lattner76c73142006-11-01 07:13:54 +00008828static bool isSafeToSinkLoad(LoadInst *L) {
8829 BasicBlock::iterator BBI = L, E = L->getParent()->end();
8830
8831 for (++BBI; BBI != E; ++BBI)
8832 if (BBI->mayWriteToMemory())
8833 return false;
Chris Lattnerfd905ca2007-02-01 22:30:07 +00008834
8835 // Check for non-address taken alloca. If not address-taken already, it isn't
8836 // profitable to do this xform.
8837 if (AllocaInst *AI = dyn_cast<AllocaInst>(L->getOperand(0))) {
8838 bool isAddressTaken = false;
8839 for (Value::use_iterator UI = AI->use_begin(), E = AI->use_end();
8840 UI != E; ++UI) {
8841 if (isa<LoadInst>(UI)) continue;
8842 if (StoreInst *SI = dyn_cast<StoreInst>(*UI)) {
8843 // If storing TO the alloca, then the address isn't taken.
8844 if (SI->getOperand(1) == AI) continue;
8845 }
8846 isAddressTaken = true;
8847 break;
8848 }
8849
8850 if (!isAddressTaken)
8851 return false;
8852 }
8853
Chris Lattner76c73142006-11-01 07:13:54 +00008854 return true;
8855}
8856
Chris Lattner9fe38862003-06-19 17:00:31 +00008857
Chris Lattnerbac32862004-11-14 19:13:23 +00008858// FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
8859// operator and they all are only used by the PHI, PHI together their
8860// inputs, and do the operation once, to the result of the PHI.
8861Instruction *InstCombiner::FoldPHIArgOpIntoPHI(PHINode &PN) {
8862 Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
8863
8864 // Scan the instruction, looking for input operations that can be folded away.
8865 // If all input operands to the phi are the same instruction (e.g. a cast from
8866 // the same type or "+42") we can pull the operation through the PHI, reducing
8867 // code size and simplifying code.
8868 Constant *ConstantOp = 0;
8869 const Type *CastSrcTy = 0;
Chris Lattner76c73142006-11-01 07:13:54 +00008870 bool isVolatile = false;
Chris Lattnerbac32862004-11-14 19:13:23 +00008871 if (isa<CastInst>(FirstInst)) {
8872 CastSrcTy = FirstInst->getOperand(0)->getType();
Reid Spencer832254e2007-02-02 02:16:23 +00008873 } else if (isa<BinaryOperator>(FirstInst) || isa<CmpInst>(FirstInst)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00008874 // Can fold binop, compare or shift here if the RHS is a constant,
8875 // otherwise call FoldPHIArgBinOpIntoPHI.
Chris Lattnerbac32862004-11-14 19:13:23 +00008876 ConstantOp = dyn_cast<Constant>(FirstInst->getOperand(1));
Chris Lattner7da52b22006-11-01 04:51:18 +00008877 if (ConstantOp == 0)
8878 return FoldPHIArgBinOpIntoPHI(PN);
Chris Lattner76c73142006-11-01 07:13:54 +00008879 } else if (LoadInst *LI = dyn_cast<LoadInst>(FirstInst)) {
8880 isVolatile = LI->isVolatile();
8881 // We can't sink the load if the loaded value could be modified between the
8882 // load and the PHI.
8883 if (LI->getParent() != PN.getIncomingBlock(0) ||
8884 !isSafeToSinkLoad(LI))
8885 return 0;
Chris Lattner9c080502006-11-01 07:43:41 +00008886 } else if (isa<GetElementPtrInst>(FirstInst)) {
Chris Lattner53738a42006-11-08 19:42:28 +00008887 if (FirstInst->getNumOperands() == 2)
Chris Lattner9c080502006-11-01 07:43:41 +00008888 return FoldPHIArgBinOpIntoPHI(PN);
8889 // Can't handle general GEPs yet.
8890 return 0;
Chris Lattnerbac32862004-11-14 19:13:23 +00008891 } else {
8892 return 0; // Cannot fold this operation.
8893 }
8894
8895 // Check to see if all arguments are the same operation.
8896 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
8897 if (!isa<Instruction>(PN.getIncomingValue(i))) return 0;
8898 Instruction *I = cast<Instruction>(PN.getIncomingValue(i));
Reid Spencere4d87aa2006-12-23 06:05:41 +00008899 if (!I->hasOneUse() || !I->isSameOperationAs(FirstInst))
Chris Lattnerbac32862004-11-14 19:13:23 +00008900 return 0;
8901 if (CastSrcTy) {
8902 if (I->getOperand(0)->getType() != CastSrcTy)
8903 return 0; // Cast operation must match.
Chris Lattner76c73142006-11-01 07:13:54 +00008904 } else if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00008905 // We can't sink the load if the loaded value could be modified between
8906 // the load and the PHI.
Chris Lattner76c73142006-11-01 07:13:54 +00008907 if (LI->isVolatile() != isVolatile ||
8908 LI->getParent() != PN.getIncomingBlock(i) ||
8909 !isSafeToSinkLoad(LI))
8910 return 0;
Chris Lattnerbac32862004-11-14 19:13:23 +00008911 } else if (I->getOperand(1) != ConstantOp) {
8912 return 0;
8913 }
8914 }
8915
8916 // Okay, they are all the same operation. Create a new PHI node of the
8917 // correct type, and PHI together all of the LHS's of the instructions.
8918 PHINode *NewPN = new PHINode(FirstInst->getOperand(0)->getType(),
8919 PN.getName()+".in");
Chris Lattner55517062005-01-29 00:39:08 +00008920 NewPN->reserveOperandSpace(PN.getNumOperands()/2);
Chris Lattnerb5893442004-11-14 19:29:34 +00008921
8922 Value *InVal = FirstInst->getOperand(0);
8923 NewPN->addIncoming(InVal, PN.getIncomingBlock(0));
Chris Lattnerbac32862004-11-14 19:13:23 +00008924
8925 // Add all operands to the new PHI.
Chris Lattnerb5893442004-11-14 19:29:34 +00008926 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
8927 Value *NewInVal = cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
8928 if (NewInVal != InVal)
8929 InVal = 0;
8930 NewPN->addIncoming(NewInVal, PN.getIncomingBlock(i));
8931 }
8932
8933 Value *PhiVal;
8934 if (InVal) {
8935 // The new PHI unions all of the same values together. This is really
8936 // common, so we handle it intelligently here for compile-time speed.
8937 PhiVal = InVal;
8938 delete NewPN;
8939 } else {
8940 InsertNewInstBefore(NewPN, PN);
8941 PhiVal = NewPN;
8942 }
Misha Brukmanfd939082005-04-21 23:48:37 +00008943
Chris Lattnerbac32862004-11-14 19:13:23 +00008944 // Insert and return the new operation.
Reid Spencer3da59db2006-11-27 01:05:10 +00008945 if (CastInst* FirstCI = dyn_cast<CastInst>(FirstInst))
8946 return CastInst::create(FirstCI->getOpcode(), PhiVal, PN.getType());
Reid Spencer3ed469c2006-11-02 20:25:50 +00008947 else if (isa<LoadInst>(FirstInst))
Chris Lattner76c73142006-11-01 07:13:54 +00008948 return new LoadInst(PhiVal, "", isVolatile);
Chris Lattnerbac32862004-11-14 19:13:23 +00008949 else if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
Chris Lattnerb5893442004-11-14 19:29:34 +00008950 return BinaryOperator::create(BinOp->getOpcode(), PhiVal, ConstantOp);
Reid Spencere4d87aa2006-12-23 06:05:41 +00008951 else if (CmpInst *CIOp = dyn_cast<CmpInst>(FirstInst))
8952 return CmpInst::create(CIOp->getOpcode(), CIOp->getPredicate(),
8953 PhiVal, ConstantOp);
Chris Lattnerbac32862004-11-14 19:13:23 +00008954 else
Reid Spencer832254e2007-02-02 02:16:23 +00008955 assert(0 && "Unknown operation");
Jeff Cohenca5183d2007-03-05 00:00:42 +00008956 return 0;
Chris Lattnerbac32862004-11-14 19:13:23 +00008957}
Chris Lattnera1be5662002-05-02 17:06:02 +00008958
Chris Lattnera3fd1c52005-01-17 05:10:15 +00008959/// DeadPHICycle - Return true if this PHI node is only used by a PHI node cycle
8960/// that is dead.
Chris Lattner0e5444b2007-03-26 20:40:50 +00008961static bool DeadPHICycle(PHINode *PN,
8962 SmallPtrSet<PHINode*, 16> &PotentiallyDeadPHIs) {
Chris Lattnera3fd1c52005-01-17 05:10:15 +00008963 if (PN->use_empty()) return true;
8964 if (!PN->hasOneUse()) return false;
8965
8966 // Remember this node, and if we find the cycle, return.
Chris Lattner0e5444b2007-03-26 20:40:50 +00008967 if (!PotentiallyDeadPHIs.insert(PN))
Chris Lattnera3fd1c52005-01-17 05:10:15 +00008968 return true;
Chris Lattner92103de2007-08-28 04:23:55 +00008969
8970 // Don't scan crazily complex things.
8971 if (PotentiallyDeadPHIs.size() == 16)
8972 return false;
Chris Lattnera3fd1c52005-01-17 05:10:15 +00008973
8974 if (PHINode *PU = dyn_cast<PHINode>(PN->use_back()))
8975 return DeadPHICycle(PU, PotentiallyDeadPHIs);
Misha Brukmanfd939082005-04-21 23:48:37 +00008976
Chris Lattnera3fd1c52005-01-17 05:10:15 +00008977 return false;
8978}
8979
Chris Lattnercf5008a2007-11-06 21:52:06 +00008980/// PHIsEqualValue - Return true if this phi node is always equal to
8981/// NonPhiInVal. This happens with mutually cyclic phi nodes like:
8982/// z = some value; x = phi (y, z); y = phi (x, z)
8983static bool PHIsEqualValue(PHINode *PN, Value *NonPhiInVal,
8984 SmallPtrSet<PHINode*, 16> &ValueEqualPHIs) {
8985 // See if we already saw this PHI node.
8986 if (!ValueEqualPHIs.insert(PN))
8987 return true;
8988
8989 // Don't scan crazily complex things.
8990 if (ValueEqualPHIs.size() == 16)
8991 return false;
8992
8993 // Scan the operands to see if they are either phi nodes or are equal to
8994 // the value.
8995 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
8996 Value *Op = PN->getIncomingValue(i);
8997 if (PHINode *OpPN = dyn_cast<PHINode>(Op)) {
8998 if (!PHIsEqualValue(OpPN, NonPhiInVal, ValueEqualPHIs))
8999 return false;
9000 } else if (Op != NonPhiInVal)
9001 return false;
9002 }
9003
9004 return true;
9005}
9006
9007
Chris Lattner473945d2002-05-06 18:06:38 +00009008// PHINode simplification
9009//
Chris Lattner7e708292002-06-25 16:13:24 +00009010Instruction *InstCombiner::visitPHINode(PHINode &PN) {
Owen Andersonb64ab872006-07-10 22:15:25 +00009011 // If LCSSA is around, don't mess with Phi nodes
Chris Lattnerf964f322007-03-04 04:27:24 +00009012 if (MustPreserveLCSSA) return 0;
Owen Andersond1b78a12006-07-10 19:03:49 +00009013
Owen Anderson7e057142006-07-10 22:03:18 +00009014 if (Value *V = PN.hasConstantValue())
9015 return ReplaceInstUsesWith(PN, V);
9016
Owen Anderson7e057142006-07-10 22:03:18 +00009017 // If all PHI operands are the same operation, pull them through the PHI,
9018 // reducing code size.
9019 if (isa<Instruction>(PN.getIncomingValue(0)) &&
9020 PN.getIncomingValue(0)->hasOneUse())
9021 if (Instruction *Result = FoldPHIArgOpIntoPHI(PN))
9022 return Result;
9023
9024 // If this is a trivial cycle in the PHI node graph, remove it. Basically, if
9025 // this PHI only has a single use (a PHI), and if that PHI only has one use (a
9026 // PHI)... break the cycle.
Chris Lattnerff9f13a2007-01-15 07:30:06 +00009027 if (PN.hasOneUse()) {
9028 Instruction *PHIUser = cast<Instruction>(PN.use_back());
9029 if (PHINode *PU = dyn_cast<PHINode>(PHIUser)) {
Chris Lattner0e5444b2007-03-26 20:40:50 +00009030 SmallPtrSet<PHINode*, 16> PotentiallyDeadPHIs;
Owen Anderson7e057142006-07-10 22:03:18 +00009031 PotentiallyDeadPHIs.insert(&PN);
9032 if (DeadPHICycle(PU, PotentiallyDeadPHIs))
9033 return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
9034 }
Chris Lattnerff9f13a2007-01-15 07:30:06 +00009035
9036 // If this phi has a single use, and if that use just computes a value for
9037 // the next iteration of a loop, delete the phi. This occurs with unused
9038 // induction variables, e.g. "for (int j = 0; ; ++j);". Detecting this
9039 // common case here is good because the only other things that catch this
9040 // are induction variable analysis (sometimes) and ADCE, which is only run
9041 // late.
9042 if (PHIUser->hasOneUse() &&
9043 (isa<BinaryOperator>(PHIUser) || isa<GetElementPtrInst>(PHIUser)) &&
9044 PHIUser->use_back() == &PN) {
9045 return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
9046 }
9047 }
Owen Anderson7e057142006-07-10 22:03:18 +00009048
Chris Lattnercf5008a2007-11-06 21:52:06 +00009049 // We sometimes end up with phi cycles that non-obviously end up being the
9050 // same value, for example:
9051 // z = some value; x = phi (y, z); y = phi (x, z)
9052 // where the phi nodes don't necessarily need to be in the same block. Do a
9053 // quick check to see if the PHI node only contains a single non-phi value, if
9054 // so, scan to see if the phi cycle is actually equal to that value.
9055 {
9056 unsigned InValNo = 0, NumOperandVals = PN.getNumIncomingValues();
9057 // Scan for the first non-phi operand.
9058 while (InValNo != NumOperandVals &&
9059 isa<PHINode>(PN.getIncomingValue(InValNo)))
9060 ++InValNo;
9061
9062 if (InValNo != NumOperandVals) {
9063 Value *NonPhiInVal = PN.getOperand(InValNo);
9064
9065 // Scan the rest of the operands to see if there are any conflicts, if so
9066 // there is no need to recursively scan other phis.
9067 for (++InValNo; InValNo != NumOperandVals; ++InValNo) {
9068 Value *OpVal = PN.getIncomingValue(InValNo);
9069 if (OpVal != NonPhiInVal && !isa<PHINode>(OpVal))
9070 break;
9071 }
9072
9073 // If we scanned over all operands, then we have one unique value plus
9074 // phi values. Scan PHI nodes to see if they all merge in each other or
9075 // the value.
9076 if (InValNo == NumOperandVals) {
9077 SmallPtrSet<PHINode*, 16> ValueEqualPHIs;
9078 if (PHIsEqualValue(&PN, NonPhiInVal, ValueEqualPHIs))
9079 return ReplaceInstUsesWith(PN, NonPhiInVal);
9080 }
9081 }
9082 }
Chris Lattner60921c92003-12-19 05:58:40 +00009083 return 0;
Chris Lattner473945d2002-05-06 18:06:38 +00009084}
9085
Reid Spencer17212df2006-12-12 09:18:51 +00009086static Value *InsertCastToIntPtrTy(Value *V, const Type *DTy,
9087 Instruction *InsertPoint,
9088 InstCombiner *IC) {
Reid Spencerabaa8ca2007-01-08 16:32:00 +00009089 unsigned PtrSize = DTy->getPrimitiveSizeInBits();
9090 unsigned VTySize = V->getType()->getPrimitiveSizeInBits();
Reid Spencer17212df2006-12-12 09:18:51 +00009091 // We must cast correctly to the pointer type. Ensure that we
9092 // sign extend the integer value if it is smaller as this is
9093 // used for address computation.
9094 Instruction::CastOps opcode =
9095 (VTySize < PtrSize ? Instruction::SExt :
9096 (VTySize == PtrSize ? Instruction::BitCast : Instruction::Trunc));
9097 return IC->InsertCastBefore(opcode, V, DTy, *InsertPoint);
Chris Lattner28977af2004-04-05 01:30:19 +00009098}
9099
Chris Lattnera1be5662002-05-02 17:06:02 +00009100
Chris Lattner7e708292002-06-25 16:13:24 +00009101Instruction *InstCombiner::visitGetElementPtrInst(GetElementPtrInst &GEP) {
Chris Lattner620ce142004-05-07 22:09:22 +00009102 Value *PtrOp = GEP.getOperand(0);
Chris Lattner9bc14642007-04-28 00:57:34 +00009103 // Is it 'getelementptr %P, i32 0' or 'getelementptr %P'
Chris Lattner7e708292002-06-25 16:13:24 +00009104 // If so, eliminate the noop.
Chris Lattnerc6bd1952004-02-22 05:25:17 +00009105 if (GEP.getNumOperands() == 1)
Chris Lattner620ce142004-05-07 22:09:22 +00009106 return ReplaceInstUsesWith(GEP, PtrOp);
Chris Lattnerc6bd1952004-02-22 05:25:17 +00009107
Chris Lattnere87597f2004-10-16 18:11:37 +00009108 if (isa<UndefValue>(GEP.getOperand(0)))
9109 return ReplaceInstUsesWith(GEP, UndefValue::get(GEP.getType()));
9110
Chris Lattnerc6bd1952004-02-22 05:25:17 +00009111 bool HasZeroPointerIndex = false;
9112 if (Constant *C = dyn_cast<Constant>(GEP.getOperand(1)))
9113 HasZeroPointerIndex = C->isNullValue();
9114
9115 if (GEP.getNumOperands() == 2 && HasZeroPointerIndex)
Chris Lattner620ce142004-05-07 22:09:22 +00009116 return ReplaceInstUsesWith(GEP, PtrOp);
Chris Lattnera1be5662002-05-02 17:06:02 +00009117
Chris Lattner28977af2004-04-05 01:30:19 +00009118 // Eliminate unneeded casts for indices.
9119 bool MadeChange = false;
Chris Lattnerdb9654e2007-03-25 20:43:09 +00009120
Chris Lattnercb69a4e2004-04-07 18:38:20 +00009121 gep_type_iterator GTI = gep_type_begin(GEP);
Chris Lattnerdb9654e2007-03-25 20:43:09 +00009122 for (unsigned i = 1, e = GEP.getNumOperands(); i != e; ++i, ++GTI) {
Chris Lattnercb69a4e2004-04-07 18:38:20 +00009123 if (isa<SequentialType>(*GTI)) {
9124 if (CastInst *CI = dyn_cast<CastInst>(GEP.getOperand(i))) {
Chris Lattner76b7a062007-01-15 07:02:54 +00009125 if (CI->getOpcode() == Instruction::ZExt ||
9126 CI->getOpcode() == Instruction::SExt) {
9127 const Type *SrcTy = CI->getOperand(0)->getType();
9128 // We can eliminate a cast from i32 to i64 iff the target
9129 // is a 32-bit pointer target.
9130 if (SrcTy->getPrimitiveSizeInBits() >= TD->getPointerSizeInBits()) {
9131 MadeChange = true;
9132 GEP.setOperand(i, CI->getOperand(0));
Chris Lattner28977af2004-04-05 01:30:19 +00009133 }
9134 }
9135 }
Chris Lattnercb69a4e2004-04-07 18:38:20 +00009136 // If we are using a wider index than needed for this platform, shrink it
9137 // to what we need. If the incoming value needs a cast instruction,
9138 // insert it. This explicit cast can make subsequent optimizations more
9139 // obvious.
9140 Value *Op = GEP.getOperand(i);
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00009141 if (TD->getTypeSizeInBits(Op->getType()) > TD->getPointerSizeInBits()) {
Chris Lattner4f1134e2004-04-17 18:16:10 +00009142 if (Constant *C = dyn_cast<Constant>(Op)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00009143 GEP.setOperand(i, ConstantExpr::getTrunc(C, TD->getIntPtrType()));
Chris Lattner4f1134e2004-04-17 18:16:10 +00009144 MadeChange = true;
9145 } else {
Reid Spencer17212df2006-12-12 09:18:51 +00009146 Op = InsertCastBefore(Instruction::Trunc, Op, TD->getIntPtrType(),
9147 GEP);
Chris Lattnercb69a4e2004-04-07 18:38:20 +00009148 GEP.setOperand(i, Op);
9149 MadeChange = true;
9150 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00009151 }
Chris Lattner28977af2004-04-05 01:30:19 +00009152 }
Chris Lattnerdb9654e2007-03-25 20:43:09 +00009153 }
Chris Lattner28977af2004-04-05 01:30:19 +00009154 if (MadeChange) return &GEP;
9155
Chris Lattnerdb9654e2007-03-25 20:43:09 +00009156 // If this GEP instruction doesn't move the pointer, and if the input operand
9157 // is a bitcast of another pointer, just replace the GEP with a bitcast of the
9158 // real input to the dest type.
Chris Lattner6a94de22007-10-12 05:30:59 +00009159 if (GEP.hasAllZeroIndices()) {
9160 if (BitCastInst *BCI = dyn_cast<BitCastInst>(GEP.getOperand(0))) {
9161 // If the bitcast is of an allocation, and the allocation will be
9162 // converted to match the type of the cast, don't touch this.
9163 if (isa<AllocationInst>(BCI->getOperand(0))) {
9164 // See if the bitcast simplifies, if so, don't nuke this GEP yet.
Chris Lattnera79dd432007-10-12 18:05:47 +00009165 if (Instruction *I = visitBitCast(*BCI)) {
9166 if (I != BCI) {
9167 I->takeName(BCI);
9168 BCI->getParent()->getInstList().insert(BCI, I);
9169 ReplaceInstUsesWith(*BCI, I);
9170 }
Chris Lattner6a94de22007-10-12 05:30:59 +00009171 return &GEP;
Chris Lattnera79dd432007-10-12 18:05:47 +00009172 }
Chris Lattner6a94de22007-10-12 05:30:59 +00009173 }
9174 return new BitCastInst(BCI->getOperand(0), GEP.getType());
9175 }
9176 }
9177
Chris Lattner90ac28c2002-08-02 19:29:35 +00009178 // Combine Indices - If the source pointer to this getelementptr instruction
9179 // is a getelementptr instruction, combine the indices of the two
9180 // getelementptr instructions into a single instruction.
9181 //
Chris Lattner72588fc2007-02-15 22:48:32 +00009182 SmallVector<Value*, 8> SrcGEPOperands;
Chris Lattner574da9b2005-01-13 20:14:25 +00009183 if (User *Src = dyn_castGetElementPtr(PtrOp))
Chris Lattner72588fc2007-02-15 22:48:32 +00009184 SrcGEPOperands.append(Src->op_begin(), Src->op_end());
Chris Lattnerebd985c2004-03-25 22:59:29 +00009185
9186 if (!SrcGEPOperands.empty()) {
Chris Lattner620ce142004-05-07 22:09:22 +00009187 // Note that if our source is a gep chain itself that we wait for that
9188 // chain to be resolved before we perform this transformation. This
9189 // avoids us creating a TON of code in some cases.
9190 //
9191 if (isa<GetElementPtrInst>(SrcGEPOperands[0]) &&
9192 cast<Instruction>(SrcGEPOperands[0])->getNumOperands() == 2)
9193 return 0; // Wait until our source is folded to completion.
9194
Chris Lattner72588fc2007-02-15 22:48:32 +00009195 SmallVector<Value*, 8> Indices;
Chris Lattner620ce142004-05-07 22:09:22 +00009196
9197 // Find out whether the last index in the source GEP is a sequential idx.
9198 bool EndsWithSequential = false;
9199 for (gep_type_iterator I = gep_type_begin(*cast<User>(PtrOp)),
9200 E = gep_type_end(*cast<User>(PtrOp)); I != E; ++I)
Chris Lattnerbe97b4e2004-05-08 22:41:42 +00009201 EndsWithSequential = !isa<StructType>(*I);
Misha Brukmanfd939082005-04-21 23:48:37 +00009202
Chris Lattner90ac28c2002-08-02 19:29:35 +00009203 // Can we combine the two pointer arithmetics offsets?
Chris Lattner620ce142004-05-07 22:09:22 +00009204 if (EndsWithSequential) {
Chris Lattnerdecd0812003-03-05 22:33:14 +00009205 // Replace: gep (gep %P, long B), long A, ...
9206 // With: T = long A+B; gep %P, T, ...
9207 //
Chris Lattner620ce142004-05-07 22:09:22 +00009208 Value *Sum, *SO1 = SrcGEPOperands.back(), *GO1 = GEP.getOperand(1);
Chris Lattner28977af2004-04-05 01:30:19 +00009209 if (SO1 == Constant::getNullValue(SO1->getType())) {
9210 Sum = GO1;
9211 } else if (GO1 == Constant::getNullValue(GO1->getType())) {
9212 Sum = SO1;
9213 } else {
9214 // If they aren't the same type, convert both to an integer of the
9215 // target's pointer size.
9216 if (SO1->getType() != GO1->getType()) {
9217 if (Constant *SO1C = dyn_cast<Constant>(SO1)) {
Reid Spencer17212df2006-12-12 09:18:51 +00009218 SO1 = ConstantExpr::getIntegerCast(SO1C, GO1->getType(), true);
Chris Lattner28977af2004-04-05 01:30:19 +00009219 } else if (Constant *GO1C = dyn_cast<Constant>(GO1)) {
Reid Spencer17212df2006-12-12 09:18:51 +00009220 GO1 = ConstantExpr::getIntegerCast(GO1C, SO1->getType(), true);
Chris Lattner28977af2004-04-05 01:30:19 +00009221 } else {
Duncan Sands514ab342007-11-01 20:53:16 +00009222 unsigned PS = TD->getPointerSizeInBits();
9223 if (TD->getTypeSizeInBits(SO1->getType()) == PS) {
Chris Lattner28977af2004-04-05 01:30:19 +00009224 // Convert GO1 to SO1's type.
Reid Spencer17212df2006-12-12 09:18:51 +00009225 GO1 = InsertCastToIntPtrTy(GO1, SO1->getType(), &GEP, this);
Chris Lattner28977af2004-04-05 01:30:19 +00009226
Duncan Sands514ab342007-11-01 20:53:16 +00009227 } else if (TD->getTypeSizeInBits(GO1->getType()) == PS) {
Chris Lattner28977af2004-04-05 01:30:19 +00009228 // Convert SO1 to GO1's type.
Reid Spencer17212df2006-12-12 09:18:51 +00009229 SO1 = InsertCastToIntPtrTy(SO1, GO1->getType(), &GEP, this);
Chris Lattner28977af2004-04-05 01:30:19 +00009230 } else {
9231 const Type *PT = TD->getIntPtrType();
Reid Spencer17212df2006-12-12 09:18:51 +00009232 SO1 = InsertCastToIntPtrTy(SO1, PT, &GEP, this);
9233 GO1 = InsertCastToIntPtrTy(GO1, PT, &GEP, this);
Chris Lattner28977af2004-04-05 01:30:19 +00009234 }
9235 }
9236 }
Chris Lattner620ce142004-05-07 22:09:22 +00009237 if (isa<Constant>(SO1) && isa<Constant>(GO1))
9238 Sum = ConstantExpr::getAdd(cast<Constant>(SO1), cast<Constant>(GO1));
9239 else {
Chris Lattner48595f12004-06-10 02:07:29 +00009240 Sum = BinaryOperator::createAdd(SO1, GO1, PtrOp->getName()+".sum");
9241 InsertNewInstBefore(cast<Instruction>(Sum), GEP);
Chris Lattner620ce142004-05-07 22:09:22 +00009242 }
Chris Lattner28977af2004-04-05 01:30:19 +00009243 }
Chris Lattner620ce142004-05-07 22:09:22 +00009244
9245 // Recycle the GEP we already have if possible.
9246 if (SrcGEPOperands.size() == 2) {
9247 GEP.setOperand(0, SrcGEPOperands[0]);
9248 GEP.setOperand(1, Sum);
9249 return &GEP;
9250 } else {
9251 Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
9252 SrcGEPOperands.end()-1);
9253 Indices.push_back(Sum);
9254 Indices.insert(Indices.end(), GEP.op_begin()+2, GEP.op_end());
9255 }
Misha Brukmanfd939082005-04-21 23:48:37 +00009256 } else if (isa<Constant>(*GEP.idx_begin()) &&
Chris Lattner28977af2004-04-05 01:30:19 +00009257 cast<Constant>(*GEP.idx_begin())->isNullValue() &&
Misha Brukmanfd939082005-04-21 23:48:37 +00009258 SrcGEPOperands.size() != 1) {
Chris Lattner90ac28c2002-08-02 19:29:35 +00009259 // Otherwise we can do the fold if the first index of the GEP is a zero
Chris Lattnerebd985c2004-03-25 22:59:29 +00009260 Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
9261 SrcGEPOperands.end());
Chris Lattner90ac28c2002-08-02 19:29:35 +00009262 Indices.insert(Indices.end(), GEP.idx_begin()+1, GEP.idx_end());
9263 }
9264
9265 if (!Indices.empty())
David Greeneb8f74792007-09-04 15:46:09 +00009266 return new GetElementPtrInst(SrcGEPOperands[0], Indices.begin(),
9267 Indices.end(), GEP.getName());
Chris Lattner9b761232002-08-17 22:21:59 +00009268
Chris Lattner620ce142004-05-07 22:09:22 +00009269 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(PtrOp)) {
Chris Lattner9b761232002-08-17 22:21:59 +00009270 // GEP of global variable. If all of the indices for this GEP are
9271 // constants, we can promote this to a constexpr instead of an instruction.
9272
9273 // Scan for nonconstants...
Chris Lattner55eb1c42007-01-31 04:40:53 +00009274 SmallVector<Constant*, 8> Indices;
Chris Lattner9b761232002-08-17 22:21:59 +00009275 User::op_iterator I = GEP.idx_begin(), E = GEP.idx_end();
9276 for (; I != E && isa<Constant>(*I); ++I)
9277 Indices.push_back(cast<Constant>(*I));
9278
9279 if (I == E) { // If they are all constants...
Chris Lattner55eb1c42007-01-31 04:40:53 +00009280 Constant *CE = ConstantExpr::getGetElementPtr(GV,
9281 &Indices[0],Indices.size());
Chris Lattner9b761232002-08-17 22:21:59 +00009282
9283 // Replace all uses of the GEP with the new constexpr...
9284 return ReplaceInstUsesWith(GEP, CE);
9285 }
Reid Spencer3da59db2006-11-27 01:05:10 +00009286 } else if (Value *X = getBitCastOperand(PtrOp)) { // Is the operand a cast?
Chris Lattnereed48272005-09-13 00:40:14 +00009287 if (!isa<PointerType>(X->getType())) {
9288 // Not interesting. Source pointer must be a cast from pointer.
9289 } else if (HasZeroPointerIndex) {
Wojciech Matyjewiczed223252007-12-12 15:21:32 +00009290 // transform: GEP (bitcast [10 x i8]* X to [0 x i8]*), i32 0, ...
9291 // into : GEP [10 x i8]* X, i32 0, ...
Chris Lattnereed48272005-09-13 00:40:14 +00009292 //
9293 // This occurs when the program declares an array extern like "int X[];"
9294 //
9295 const PointerType *CPTy = cast<PointerType>(PtrOp->getType());
9296 const PointerType *XTy = cast<PointerType>(X->getType());
9297 if (const ArrayType *XATy =
9298 dyn_cast<ArrayType>(XTy->getElementType()))
9299 if (const ArrayType *CATy =
9300 dyn_cast<ArrayType>(CPTy->getElementType()))
9301 if (CATy->getElementType() == XATy->getElementType()) {
9302 // At this point, we know that the cast source type is a pointer
9303 // to an array of the same type as the destination pointer
9304 // array. Because the array type is never stepped over (there
9305 // is a leading zero) we can fold the cast into this GEP.
9306 GEP.setOperand(0, X);
9307 return &GEP;
9308 }
9309 } else if (GEP.getNumOperands() == 2) {
9310 // Transform things like:
Wojciech Matyjewiczed223252007-12-12 15:21:32 +00009311 // %t = getelementptr i32* bitcast ([2 x i32]* %str to i32*), i32 %V
9312 // into: %t1 = getelementptr [2 x i32]* %str, i32 0, i32 %V; bitcast
Chris Lattnereed48272005-09-13 00:40:14 +00009313 const Type *SrcElTy = cast<PointerType>(X->getType())->getElementType();
9314 const Type *ResElTy=cast<PointerType>(PtrOp->getType())->getElementType();
9315 if (isa<ArrayType>(SrcElTy) &&
Duncan Sands514ab342007-11-01 20:53:16 +00009316 TD->getABITypeSize(cast<ArrayType>(SrcElTy)->getElementType()) ==
9317 TD->getABITypeSize(ResElTy)) {
David Greeneb8f74792007-09-04 15:46:09 +00009318 Value *Idx[2];
9319 Idx[0] = Constant::getNullValue(Type::Int32Ty);
9320 Idx[1] = GEP.getOperand(1);
Chris Lattnereed48272005-09-13 00:40:14 +00009321 Value *V = InsertNewInstBefore(
David Greeneb8f74792007-09-04 15:46:09 +00009322 new GetElementPtrInst(X, Idx, Idx + 2, GEP.getName()), GEP);
Reid Spencer3da59db2006-11-27 01:05:10 +00009323 // V and GEP are both pointer types --> BitCast
9324 return new BitCastInst(V, GEP.getType());
Chris Lattnerc6bd1952004-02-22 05:25:17 +00009325 }
Chris Lattner7835cdd2005-09-13 18:36:04 +00009326
9327 // Transform things like:
Wojciech Matyjewiczed223252007-12-12 15:21:32 +00009328 // getelementptr i8* bitcast ([100 x double]* X to i8*), i32 %tmp
Chris Lattner7835cdd2005-09-13 18:36:04 +00009329 // (where tmp = 8*tmp2) into:
Wojciech Matyjewiczed223252007-12-12 15:21:32 +00009330 // getelementptr [100 x double]* %arr, i32 0, i32 %tmp2; bitcast
Chris Lattner7835cdd2005-09-13 18:36:04 +00009331
Wojciech Matyjewiczed223252007-12-12 15:21:32 +00009332 if (isa<ArrayType>(SrcElTy) && ResElTy == Type::Int8Ty) {
Chris Lattner7835cdd2005-09-13 18:36:04 +00009333 uint64_t ArrayEltSize =
Duncan Sands514ab342007-11-01 20:53:16 +00009334 TD->getABITypeSize(cast<ArrayType>(SrcElTy)->getElementType());
Chris Lattner7835cdd2005-09-13 18:36:04 +00009335
9336 // Check to see if "tmp" is a scale by a multiple of ArrayEltSize. We
9337 // allow either a mul, shift, or constant here.
9338 Value *NewIdx = 0;
9339 ConstantInt *Scale = 0;
9340 if (ArrayEltSize == 1) {
9341 NewIdx = GEP.getOperand(1);
9342 Scale = ConstantInt::get(NewIdx->getType(), 1);
9343 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP.getOperand(1))) {
Chris Lattner6e2f8432005-09-14 17:32:56 +00009344 NewIdx = ConstantInt::get(CI->getType(), 1);
Chris Lattner7835cdd2005-09-13 18:36:04 +00009345 Scale = CI;
9346 } else if (Instruction *Inst =dyn_cast<Instruction>(GEP.getOperand(1))){
9347 if (Inst->getOpcode() == Instruction::Shl &&
9348 isa<ConstantInt>(Inst->getOperand(1))) {
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00009349 ConstantInt *ShAmt = cast<ConstantInt>(Inst->getOperand(1));
9350 uint32_t ShAmtVal = ShAmt->getLimitedValue(64);
9351 Scale = ConstantInt::get(Inst->getType(), 1ULL << ShAmtVal);
Chris Lattner7835cdd2005-09-13 18:36:04 +00009352 NewIdx = Inst->getOperand(0);
9353 } else if (Inst->getOpcode() == Instruction::Mul &&
9354 isa<ConstantInt>(Inst->getOperand(1))) {
9355 Scale = cast<ConstantInt>(Inst->getOperand(1));
9356 NewIdx = Inst->getOperand(0);
9357 }
9358 }
Wojciech Matyjewiczed223252007-12-12 15:21:32 +00009359
Chris Lattner7835cdd2005-09-13 18:36:04 +00009360 // If the index will be to exactly the right offset with the scale taken
Wojciech Matyjewiczed223252007-12-12 15:21:32 +00009361 // out, perform the transformation. Note, we don't know whether Scale is
9362 // signed or not. We'll use unsigned version of division/modulo
9363 // operation after making sure Scale doesn't have the sign bit set.
9364 if (Scale && Scale->getSExtValue() >= 0LL &&
9365 Scale->getZExtValue() % ArrayEltSize == 0) {
9366 Scale = ConstantInt::get(Scale->getType(),
9367 Scale->getZExtValue() / ArrayEltSize);
Reid Spencerb83eb642006-10-20 07:07:24 +00009368 if (Scale->getZExtValue() != 1) {
Reid Spencer17212df2006-12-12 09:18:51 +00009369 Constant *C = ConstantExpr::getIntegerCast(Scale, NewIdx->getType(),
Wojciech Matyjewiczed223252007-12-12 15:21:32 +00009370 false /*ZExt*/);
Chris Lattner7835cdd2005-09-13 18:36:04 +00009371 Instruction *Sc = BinaryOperator::createMul(NewIdx, C, "idxscale");
9372 NewIdx = InsertNewInstBefore(Sc, GEP);
9373 }
9374
9375 // Insert the new GEP instruction.
David Greeneb8f74792007-09-04 15:46:09 +00009376 Value *Idx[2];
9377 Idx[0] = Constant::getNullValue(Type::Int32Ty);
9378 Idx[1] = NewIdx;
Reid Spencer3da59db2006-11-27 01:05:10 +00009379 Instruction *NewGEP =
David Greeneb8f74792007-09-04 15:46:09 +00009380 new GetElementPtrInst(X, Idx, Idx + 2, GEP.getName());
Reid Spencer3da59db2006-11-27 01:05:10 +00009381 NewGEP = InsertNewInstBefore(NewGEP, GEP);
9382 // The NewGEP must be pointer typed, so must the old one -> BitCast
9383 return new BitCastInst(NewGEP, GEP.getType());
Chris Lattner7835cdd2005-09-13 18:36:04 +00009384 }
9385 }
Chris Lattnerc6bd1952004-02-22 05:25:17 +00009386 }
Chris Lattner8a2a3112001-12-14 16:52:21 +00009387 }
9388
Chris Lattner8a2a3112001-12-14 16:52:21 +00009389 return 0;
9390}
9391
Chris Lattner0864acf2002-11-04 16:18:53 +00009392Instruction *InstCombiner::visitAllocationInst(AllocationInst &AI) {
9393 // Convert: malloc Ty, C - where C is a constant != 1 into: malloc [C x Ty], 1
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00009394 if (AI.isArrayAllocation()) { // Check C != 1
Reid Spencerb83eb642006-10-20 07:07:24 +00009395 if (const ConstantInt *C = dyn_cast<ConstantInt>(AI.getArraySize())) {
9396 const Type *NewTy =
9397 ArrayType::get(AI.getAllocatedType(), C->getZExtValue());
Chris Lattner0006bd72002-11-09 00:49:43 +00009398 AllocationInst *New = 0;
Chris Lattner0864acf2002-11-04 16:18:53 +00009399
9400 // Create and insert the replacement instruction...
9401 if (isa<MallocInst>(AI))
Nate Begeman14b05292005-11-05 09:21:28 +00009402 New = new MallocInst(NewTy, 0, AI.getAlignment(), AI.getName());
Chris Lattner0006bd72002-11-09 00:49:43 +00009403 else {
9404 assert(isa<AllocaInst>(AI) && "Unknown type of allocation inst!");
Nate Begeman14b05292005-11-05 09:21:28 +00009405 New = new AllocaInst(NewTy, 0, AI.getAlignment(), AI.getName());
Chris Lattner0006bd72002-11-09 00:49:43 +00009406 }
Chris Lattner7c881df2004-03-19 06:08:10 +00009407
9408 InsertNewInstBefore(New, AI);
Misha Brukmanfd939082005-04-21 23:48:37 +00009409
Chris Lattner0864acf2002-11-04 16:18:53 +00009410 // Scan to the end of the allocation instructions, to skip over a block of
9411 // allocas if possible...
9412 //
9413 BasicBlock::iterator It = New;
9414 while (isa<AllocationInst>(*It)) ++It;
9415
9416 // Now that I is pointing to the first non-allocation-inst in the block,
9417 // insert our getelementptr instruction...
9418 //
Reid Spencerc5b206b2006-12-31 05:48:39 +00009419 Value *NullIdx = Constant::getNullValue(Type::Int32Ty);
David Greeneb8f74792007-09-04 15:46:09 +00009420 Value *Idx[2];
9421 Idx[0] = NullIdx;
9422 Idx[1] = NullIdx;
9423 Value *V = new GetElementPtrInst(New, Idx, Idx + 2,
Chris Lattner693787a2005-05-04 19:10:26 +00009424 New->getName()+".sub", It);
Chris Lattner0864acf2002-11-04 16:18:53 +00009425
9426 // Now make everything use the getelementptr instead of the original
9427 // allocation.
Chris Lattner7c881df2004-03-19 06:08:10 +00009428 return ReplaceInstUsesWith(AI, V);
Chris Lattnere87597f2004-10-16 18:11:37 +00009429 } else if (isa<UndefValue>(AI.getArraySize())) {
9430 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
Chris Lattner0864acf2002-11-04 16:18:53 +00009431 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00009432 }
Chris Lattner7c881df2004-03-19 06:08:10 +00009433
9434 // If alloca'ing a zero byte object, replace the alloca with a null pointer.
9435 // Note that we only do this for alloca's, because malloc should allocate and
9436 // return a unique pointer, even for a zero byte allocation.
Misha Brukmanfd939082005-04-21 23:48:37 +00009437 if (isa<AllocaInst>(AI) && AI.getAllocatedType()->isSized() &&
Duncan Sands514ab342007-11-01 20:53:16 +00009438 TD->getABITypeSize(AI.getAllocatedType()) == 0)
Chris Lattner7c881df2004-03-19 06:08:10 +00009439 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
9440
Chris Lattner0864acf2002-11-04 16:18:53 +00009441 return 0;
9442}
9443
Chris Lattner67b1e1b2003-12-07 01:24:23 +00009444Instruction *InstCombiner::visitFreeInst(FreeInst &FI) {
9445 Value *Op = FI.getOperand(0);
9446
Chris Lattner17be6352004-10-18 02:59:09 +00009447 // free undef -> unreachable.
9448 if (isa<UndefValue>(Op)) {
9449 // Insert a new store to null because we cannot modify the CFG here.
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00009450 new StoreInst(ConstantInt::getTrue(),
Christopher Lamb43ad6b32007-12-17 01:12:55 +00009451 UndefValue::get(PointerType::getUnqual(Type::Int1Ty)), &FI);
Chris Lattner17be6352004-10-18 02:59:09 +00009452 return EraseInstFromFunction(FI);
9453 }
Chris Lattner6fe55412007-04-14 00:20:02 +00009454
Chris Lattner6160e852004-02-28 04:57:37 +00009455 // If we have 'free null' delete the instruction. This can happen in stl code
9456 // when lots of inlining happens.
Chris Lattner17be6352004-10-18 02:59:09 +00009457 if (isa<ConstantPointerNull>(Op))
Chris Lattner7bcc0e72004-02-28 05:22:00 +00009458 return EraseInstFromFunction(FI);
Chris Lattner6fe55412007-04-14 00:20:02 +00009459
9460 // Change free <ty>* (cast <ty2>* X to <ty>*) into free <ty2>* X
9461 if (BitCastInst *CI = dyn_cast<BitCastInst>(Op)) {
9462 FI.setOperand(0, CI->getOperand(0));
9463 return &FI;
9464 }
9465
9466 // Change free (gep X, 0,0,0,0) into free(X)
9467 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op)) {
9468 if (GEPI->hasAllZeroIndices()) {
9469 AddToWorkList(GEPI);
9470 FI.setOperand(0, GEPI->getOperand(0));
9471 return &FI;
9472 }
9473 }
9474
9475 // Change free(malloc) into nothing, if the malloc has a single use.
9476 if (MallocInst *MI = dyn_cast<MallocInst>(Op))
9477 if (MI->hasOneUse()) {
9478 EraseInstFromFunction(FI);
9479 return EraseInstFromFunction(*MI);
9480 }
Chris Lattner6160e852004-02-28 04:57:37 +00009481
Chris Lattner67b1e1b2003-12-07 01:24:23 +00009482 return 0;
9483}
9484
9485
Chris Lattnerfcfe33a2005-01-31 05:51:45 +00009486/// InstCombineLoadCast - Fold 'load (cast P)' -> cast (load P)' when possible.
Devang Patel99db6ad2007-10-18 19:52:32 +00009487static Instruction *InstCombineLoadCast(InstCombiner &IC, LoadInst &LI,
Bill Wendling587c01d2008-02-26 10:53:30 +00009488 const TargetData *TD) {
Chris Lattnerb89e0712004-07-13 01:49:43 +00009489 User *CI = cast<User>(LI.getOperand(0));
Chris Lattnerf9527852005-01-31 04:50:46 +00009490 Value *CastOp = CI->getOperand(0);
Chris Lattnerb89e0712004-07-13 01:49:43 +00009491
Devang Patel99db6ad2007-10-18 19:52:32 +00009492 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(CI)) {
9493 // Instead of loading constant c string, use corresponding integer value
9494 // directly if string length is small enough.
9495 const std::string &Str = CE->getOperand(0)->getStringValue();
9496 if (!Str.empty()) {
9497 unsigned len = Str.length();
9498 const Type *Ty = cast<PointerType>(CE->getType())->getElementType();
9499 unsigned numBits = Ty->getPrimitiveSizeInBits();
9500 // Replace LI with immediate integer store.
9501 if ((numBits >> 3) == len + 1) {
Bill Wendling587c01d2008-02-26 10:53:30 +00009502 APInt StrVal(numBits, 0);
9503 APInt SingleChar(numBits, 0);
9504 if (TD->isLittleEndian()) {
9505 for (signed i = len-1; i >= 0; i--) {
9506 SingleChar = (uint64_t) Str[i];
9507 StrVal = (StrVal << 8) | SingleChar;
9508 }
9509 } else {
9510 for (unsigned i = 0; i < len; i++) {
9511 SingleChar = (uint64_t) Str[i];
9512 StrVal = (StrVal << 8) | SingleChar;
9513 }
9514 // Append NULL at the end.
9515 SingleChar = 0;
9516 StrVal = (StrVal << 8) | SingleChar;
9517 }
9518 Value *NL = ConstantInt::get(StrVal);
9519 return IC.ReplaceInstUsesWith(LI, NL);
Devang Patel99db6ad2007-10-18 19:52:32 +00009520 }
9521 }
9522 }
9523
Chris Lattnerb89e0712004-07-13 01:49:43 +00009524 const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
Chris Lattnerf9527852005-01-31 04:50:46 +00009525 if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
Chris Lattnerb89e0712004-07-13 01:49:43 +00009526 const Type *SrcPTy = SrcTy->getElementType();
Chris Lattnerf9527852005-01-31 04:50:46 +00009527
Reid Spencer42230162007-01-22 05:51:25 +00009528 if (DestPTy->isInteger() || isa<PointerType>(DestPTy) ||
Reid Spencer9d6565a2007-02-15 02:26:10 +00009529 isa<VectorType>(DestPTy)) {
Chris Lattnerf9527852005-01-31 04:50:46 +00009530 // If the source is an array, the code below will not succeed. Check to
9531 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
9532 // constants.
9533 if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
9534 if (Constant *CSrc = dyn_cast<Constant>(CastOp))
9535 if (ASrcTy->getNumElements() != 0) {
Chris Lattner55eb1c42007-01-31 04:40:53 +00009536 Value *Idxs[2];
9537 Idxs[0] = Idxs[1] = Constant::getNullValue(Type::Int32Ty);
9538 CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs, 2);
Chris Lattnerf9527852005-01-31 04:50:46 +00009539 SrcTy = cast<PointerType>(CastOp->getType());
9540 SrcPTy = SrcTy->getElementType();
9541 }
9542
Reid Spencer42230162007-01-22 05:51:25 +00009543 if ((SrcPTy->isInteger() || isa<PointerType>(SrcPTy) ||
Reid Spencer9d6565a2007-02-15 02:26:10 +00009544 isa<VectorType>(SrcPTy)) &&
Chris Lattnerb1515fe2005-03-29 06:37:47 +00009545 // Do not allow turning this into a load of an integer, which is then
9546 // casted to a pointer, this pessimizes pointer analysis a lot.
9547 (isa<PointerType>(SrcPTy) == isa<PointerType>(LI.getType())) &&
Reid Spencer42230162007-01-22 05:51:25 +00009548 IC.getTargetData().getTypeSizeInBits(SrcPTy) ==
9549 IC.getTargetData().getTypeSizeInBits(DestPTy)) {
Misha Brukmanfd939082005-04-21 23:48:37 +00009550
Chris Lattnerf9527852005-01-31 04:50:46 +00009551 // Okay, we are casting from one integer or pointer type to another of
9552 // the same size. Instead of casting the pointer before the load, cast
9553 // the result of the loaded value.
9554 Value *NewLoad = IC.InsertNewInstBefore(new LoadInst(CastOp,
9555 CI->getName(),
9556 LI.isVolatile()),LI);
9557 // Now cast the result of the load.
Reid Spencerd977d862006-12-12 23:36:14 +00009558 return new BitCastInst(NewLoad, LI.getType());
Chris Lattnerf9527852005-01-31 04:50:46 +00009559 }
Chris Lattnerb89e0712004-07-13 01:49:43 +00009560 }
9561 }
9562 return 0;
9563}
9564
Chris Lattnerc10aced2004-09-19 18:43:46 +00009565/// isSafeToLoadUnconditionally - Return true if we know that executing a load
Chris Lattner8a375202004-09-19 19:18:10 +00009566/// from this value cannot trap. If it is not obviously safe to load from the
9567/// specified pointer, we do a quick local scan of the basic block containing
9568/// ScanFrom, to determine if the address is already accessed.
9569static bool isSafeToLoadUnconditionally(Value *V, Instruction *ScanFrom) {
Duncan Sands892c7e42007-09-19 10:10:31 +00009570 // If it is an alloca it is always safe to load from.
9571 if (isa<AllocaInst>(V)) return true;
9572
Duncan Sands46318cd2007-09-19 10:25:38 +00009573 // If it is a global variable it is mostly safe to load from.
Duncan Sands892c7e42007-09-19 10:10:31 +00009574 if (const GlobalValue *GV = dyn_cast<GlobalVariable>(V))
Duncan Sands46318cd2007-09-19 10:25:38 +00009575 // Don't try to evaluate aliases. External weak GV can be null.
Duncan Sands892c7e42007-09-19 10:10:31 +00009576 return !isa<GlobalAlias>(GV) && !GV->hasExternalWeakLinkage();
Chris Lattner8a375202004-09-19 19:18:10 +00009577
9578 // Otherwise, be a little bit agressive by scanning the local block where we
9579 // want to check to see if the pointer is already being loaded or stored
Alkis Evlogimenos7b6ec602004-09-20 06:42:58 +00009580 // from/to. If so, the previous load or store would have already trapped,
9581 // so there is no harm doing an extra load (also, CSE will later eliminate
9582 // the load entirely).
Chris Lattner8a375202004-09-19 19:18:10 +00009583 BasicBlock::iterator BBI = ScanFrom, E = ScanFrom->getParent()->begin();
9584
Alkis Evlogimenos7b6ec602004-09-20 06:42:58 +00009585 while (BBI != E) {
Chris Lattner8a375202004-09-19 19:18:10 +00009586 --BBI;
9587
9588 if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
9589 if (LI->getOperand(0) == V) return true;
9590 } else if (StoreInst *SI = dyn_cast<StoreInst>(BBI))
9591 if (SI->getOperand(1) == V) return true;
Misha Brukmanfd939082005-04-21 23:48:37 +00009592
Alkis Evlogimenos7b6ec602004-09-20 06:42:58 +00009593 }
Chris Lattner8a375202004-09-19 19:18:10 +00009594 return false;
Chris Lattnerc10aced2004-09-19 18:43:46 +00009595}
9596
Chris Lattner8d2e8882007-08-11 18:48:48 +00009597/// GetUnderlyingObject - Trace through a series of getelementptrs and bitcasts
9598/// until we find the underlying object a pointer is referring to or something
9599/// we don't understand. Note that the returned pointer may be offset from the
9600/// input, because we ignore GEP indices.
9601static Value *GetUnderlyingObject(Value *Ptr) {
9602 while (1) {
9603 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr)) {
9604 if (CE->getOpcode() == Instruction::BitCast ||
9605 CE->getOpcode() == Instruction::GetElementPtr)
9606 Ptr = CE->getOperand(0);
9607 else
9608 return Ptr;
9609 } else if (BitCastInst *BCI = dyn_cast<BitCastInst>(Ptr)) {
9610 Ptr = BCI->getOperand(0);
9611 } else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr)) {
9612 Ptr = GEP->getOperand(0);
9613 } else {
9614 return Ptr;
9615 }
9616 }
9617}
9618
Chris Lattner833b8a42003-06-26 05:06:25 +00009619Instruction *InstCombiner::visitLoadInst(LoadInst &LI) {
9620 Value *Op = LI.getOperand(0);
Chris Lattner5f16a132004-01-12 04:13:56 +00009621
Dan Gohman9941f742007-07-20 16:34:21 +00009622 // Attempt to improve the alignment.
Chris Lattnerf2369f22007-08-09 19:05:49 +00009623 unsigned KnownAlign = GetOrEnforceKnownAlignment(Op, TD);
Dan Gohman9941f742007-07-20 16:34:21 +00009624 if (KnownAlign > LI.getAlignment())
9625 LI.setAlignment(KnownAlign);
9626
Chris Lattner37366c12005-05-01 04:24:53 +00009627 // load (cast X) --> cast (load X) iff safe
Reid Spencer3ed469c2006-11-02 20:25:50 +00009628 if (isa<CastInst>(Op))
Devang Patel99db6ad2007-10-18 19:52:32 +00009629 if (Instruction *Res = InstCombineLoadCast(*this, LI, TD))
Chris Lattner37366c12005-05-01 04:24:53 +00009630 return Res;
9631
9632 // None of the following transforms are legal for volatile loads.
9633 if (LI.isVolatile()) return 0;
Chris Lattner62f254d2005-09-12 22:00:15 +00009634
Chris Lattner62f254d2005-09-12 22:00:15 +00009635 if (&LI.getParent()->front() != &LI) {
9636 BasicBlock::iterator BBI = &LI; --BBI;
Chris Lattner9c1f0fd2005-09-12 22:21:03 +00009637 // If the instruction immediately before this is a store to the same
9638 // address, do a simple form of store->load forwarding.
Chris Lattner62f254d2005-09-12 22:00:15 +00009639 if (StoreInst *SI = dyn_cast<StoreInst>(BBI))
9640 if (SI->getOperand(1) == LI.getOperand(0))
9641 return ReplaceInstUsesWith(LI, SI->getOperand(0));
Chris Lattner9c1f0fd2005-09-12 22:21:03 +00009642 if (LoadInst *LIB = dyn_cast<LoadInst>(BBI))
9643 if (LIB->getOperand(0) == LI.getOperand(0))
9644 return ReplaceInstUsesWith(LI, LIB);
Chris Lattner62f254d2005-09-12 22:00:15 +00009645 }
Chris Lattner37366c12005-05-01 04:24:53 +00009646
Christopher Lambb15147e2007-12-29 07:56:53 +00009647 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op)) {
9648 const Value *GEPI0 = GEPI->getOperand(0);
9649 // TODO: Consider a target hook for valid address spaces for this xform.
9650 if (isa<ConstantPointerNull>(GEPI0) &&
9651 cast<PointerType>(GEPI0->getType())->getAddressSpace() == 0) {
Chris Lattner37366c12005-05-01 04:24:53 +00009652 // Insert a new store to null instruction before the load to indicate
9653 // that this code is not reachable. We do this instead of inserting
9654 // an unreachable instruction directly because we cannot modify the
9655 // CFG.
9656 new StoreInst(UndefValue::get(LI.getType()),
9657 Constant::getNullValue(Op->getType()), &LI);
9658 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
9659 }
Christopher Lambb15147e2007-12-29 07:56:53 +00009660 }
Chris Lattner37366c12005-05-01 04:24:53 +00009661
Chris Lattnere87597f2004-10-16 18:11:37 +00009662 if (Constant *C = dyn_cast<Constant>(Op)) {
Chris Lattner37366c12005-05-01 04:24:53 +00009663 // load null/undef -> undef
Christopher Lambb15147e2007-12-29 07:56:53 +00009664 // TODO: Consider a target hook for valid address spaces for this xform.
9665 if (isa<UndefValue>(C) || (C->isNullValue() &&
9666 cast<PointerType>(Op->getType())->getAddressSpace() == 0)) {
Chris Lattner17be6352004-10-18 02:59:09 +00009667 // Insert a new store to null instruction before the load to indicate that
9668 // this code is not reachable. We do this instead of inserting an
9669 // unreachable instruction directly because we cannot modify the CFG.
Chris Lattner37366c12005-05-01 04:24:53 +00009670 new StoreInst(UndefValue::get(LI.getType()),
9671 Constant::getNullValue(Op->getType()), &LI);
Chris Lattnere87597f2004-10-16 18:11:37 +00009672 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
Chris Lattner17be6352004-10-18 02:59:09 +00009673 }
Chris Lattner833b8a42003-06-26 05:06:25 +00009674
Chris Lattnere87597f2004-10-16 18:11:37 +00009675 // Instcombine load (constant global) into the value loaded.
9676 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Op))
Reid Spencer5cbf9852007-01-30 20:08:39 +00009677 if (GV->isConstant() && !GV->isDeclaration())
Chris Lattnere87597f2004-10-16 18:11:37 +00009678 return ReplaceInstUsesWith(LI, GV->getInitializer());
Misha Brukmanfd939082005-04-21 23:48:37 +00009679
Chris Lattnere87597f2004-10-16 18:11:37 +00009680 // Instcombine load (constantexpr_GEP global, 0, ...) into the value loaded.
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00009681 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Op)) {
Chris Lattnere87597f2004-10-16 18:11:37 +00009682 if (CE->getOpcode() == Instruction::GetElementPtr) {
9683 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(CE->getOperand(0)))
Reid Spencer5cbf9852007-01-30 20:08:39 +00009684 if (GV->isConstant() && !GV->isDeclaration())
Chris Lattner363f2a22005-09-26 05:28:06 +00009685 if (Constant *V =
9686 ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE))
Chris Lattnere87597f2004-10-16 18:11:37 +00009687 return ReplaceInstUsesWith(LI, V);
Chris Lattner37366c12005-05-01 04:24:53 +00009688 if (CE->getOperand(0)->isNullValue()) {
9689 // Insert a new store to null instruction before the load to indicate
9690 // that this code is not reachable. We do this instead of inserting
9691 // an unreachable instruction directly because we cannot modify the
9692 // CFG.
9693 new StoreInst(UndefValue::get(LI.getType()),
9694 Constant::getNullValue(Op->getType()), &LI);
9695 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
9696 }
9697
Reid Spencer3da59db2006-11-27 01:05:10 +00009698 } else if (CE->isCast()) {
Devang Patel99db6ad2007-10-18 19:52:32 +00009699 if (Instruction *Res = InstCombineLoadCast(*this, LI, TD))
Chris Lattnere87597f2004-10-16 18:11:37 +00009700 return Res;
9701 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00009702 }
Chris Lattnere87597f2004-10-16 18:11:37 +00009703 }
Chris Lattner8d2e8882007-08-11 18:48:48 +00009704
9705 // If this load comes from anywhere in a constant global, and if the global
9706 // is all undef or zero, we know what it loads.
9707 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(GetUnderlyingObject(Op))) {
9708 if (GV->isConstant() && GV->hasInitializer()) {
9709 if (GV->getInitializer()->isNullValue())
9710 return ReplaceInstUsesWith(LI, Constant::getNullValue(LI.getType()));
9711 else if (isa<UndefValue>(GV->getInitializer()))
9712 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
9713 }
9714 }
Chris Lattnerf499eac2004-04-08 20:39:49 +00009715
Chris Lattner37366c12005-05-01 04:24:53 +00009716 if (Op->hasOneUse()) {
Chris Lattnerc10aced2004-09-19 18:43:46 +00009717 // Change select and PHI nodes to select values instead of addresses: this
9718 // helps alias analysis out a lot, allows many others simplifications, and
9719 // exposes redundancy in the code.
9720 //
9721 // Note that we cannot do the transformation unless we know that the
9722 // introduced loads cannot trap! Something like this is valid as long as
9723 // the condition is always false: load (select bool %C, int* null, int* %G),
9724 // but it would not be valid if we transformed it to load from null
9725 // unconditionally.
9726 //
9727 if (SelectInst *SI = dyn_cast<SelectInst>(Op)) {
9728 // load (select (Cond, &V1, &V2)) --> select(Cond, load &V1, load &V2).
Chris Lattner8a375202004-09-19 19:18:10 +00009729 if (isSafeToLoadUnconditionally(SI->getOperand(1), SI) &&
9730 isSafeToLoadUnconditionally(SI->getOperand(2), SI)) {
Chris Lattnerc10aced2004-09-19 18:43:46 +00009731 Value *V1 = InsertNewInstBefore(new LoadInst(SI->getOperand(1),
Chris Lattner79f0c8e2004-09-20 10:15:10 +00009732 SI->getOperand(1)->getName()+".val"), LI);
Chris Lattnerc10aced2004-09-19 18:43:46 +00009733 Value *V2 = InsertNewInstBefore(new LoadInst(SI->getOperand(2),
Chris Lattner79f0c8e2004-09-20 10:15:10 +00009734 SI->getOperand(2)->getName()+".val"), LI);
Chris Lattnerc10aced2004-09-19 18:43:46 +00009735 return new SelectInst(SI->getCondition(), V1, V2);
9736 }
9737
Chris Lattner684fe212004-09-23 15:46:00 +00009738 // load (select (cond, null, P)) -> load P
9739 if (Constant *C = dyn_cast<Constant>(SI->getOperand(1)))
9740 if (C->isNullValue()) {
9741 LI.setOperand(0, SI->getOperand(2));
9742 return &LI;
9743 }
9744
9745 // load (select (cond, P, null)) -> load P
9746 if (Constant *C = dyn_cast<Constant>(SI->getOperand(2)))
9747 if (C->isNullValue()) {
9748 LI.setOperand(0, SI->getOperand(1));
9749 return &LI;
9750 }
Chris Lattnerc10aced2004-09-19 18:43:46 +00009751 }
9752 }
Chris Lattner833b8a42003-06-26 05:06:25 +00009753 return 0;
9754}
9755
Reid Spencer55af2b52007-01-19 21:20:31 +00009756/// InstCombineStoreToCast - Fold store V, (cast P) -> store (cast V), P
Chris Lattnerfcfe33a2005-01-31 05:51:45 +00009757/// when possible.
9758static Instruction *InstCombineStoreToCast(InstCombiner &IC, StoreInst &SI) {
9759 User *CI = cast<User>(SI.getOperand(1));
9760 Value *CastOp = CI->getOperand(0);
9761
9762 const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
9763 if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
9764 const Type *SrcPTy = SrcTy->getElementType();
9765
Reid Spencer42230162007-01-22 05:51:25 +00009766 if (DestPTy->isInteger() || isa<PointerType>(DestPTy)) {
Chris Lattnerfcfe33a2005-01-31 05:51:45 +00009767 // If the source is an array, the code below will not succeed. Check to
9768 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
9769 // constants.
9770 if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
9771 if (Constant *CSrc = dyn_cast<Constant>(CastOp))
9772 if (ASrcTy->getNumElements() != 0) {
Chris Lattner55eb1c42007-01-31 04:40:53 +00009773 Value* Idxs[2];
9774 Idxs[0] = Idxs[1] = Constant::getNullValue(Type::Int32Ty);
9775 CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs, 2);
Chris Lattnerfcfe33a2005-01-31 05:51:45 +00009776 SrcTy = cast<PointerType>(CastOp->getType());
9777 SrcPTy = SrcTy->getElementType();
9778 }
9779
Reid Spencer67f827c2007-01-20 23:35:48 +00009780 if ((SrcPTy->isInteger() || isa<PointerType>(SrcPTy)) &&
9781 IC.getTargetData().getTypeSizeInBits(SrcPTy) ==
9782 IC.getTargetData().getTypeSizeInBits(DestPTy)) {
Chris Lattnerfcfe33a2005-01-31 05:51:45 +00009783
9784 // Okay, we are casting from one integer or pointer type to another of
Reid Spencer75153962007-01-18 18:54:33 +00009785 // the same size. Instead of casting the pointer before
9786 // the store, cast the value to be stored.
Chris Lattnerfcfe33a2005-01-31 05:51:45 +00009787 Value *NewCast;
Reid Spencerd977d862006-12-12 23:36:14 +00009788 Value *SIOp0 = SI.getOperand(0);
Reid Spencer75153962007-01-18 18:54:33 +00009789 Instruction::CastOps opcode = Instruction::BitCast;
9790 const Type* CastSrcTy = SIOp0->getType();
9791 const Type* CastDstTy = SrcPTy;
9792 if (isa<PointerType>(CastDstTy)) {
9793 if (CastSrcTy->isInteger())
Reid Spencerd977d862006-12-12 23:36:14 +00009794 opcode = Instruction::IntToPtr;
Reid Spencer67f827c2007-01-20 23:35:48 +00009795 } else if (isa<IntegerType>(CastDstTy)) {
Reid Spencerc55b2432006-12-13 18:21:21 +00009796 if (isa<PointerType>(SIOp0->getType()))
Reid Spencerd977d862006-12-12 23:36:14 +00009797 opcode = Instruction::PtrToInt;
9798 }
9799 if (Constant *C = dyn_cast<Constant>(SIOp0))
Reid Spencer75153962007-01-18 18:54:33 +00009800 NewCast = ConstantExpr::getCast(opcode, C, CastDstTy);
Chris Lattnerfcfe33a2005-01-31 05:51:45 +00009801 else
Reid Spencer3da59db2006-11-27 01:05:10 +00009802 NewCast = IC.InsertNewInstBefore(
Reid Spencer75153962007-01-18 18:54:33 +00009803 CastInst::create(opcode, SIOp0, CastDstTy, SIOp0->getName()+".c"),
9804 SI);
Chris Lattnerfcfe33a2005-01-31 05:51:45 +00009805 return new StoreInst(NewCast, CastOp);
9806 }
9807 }
9808 }
9809 return 0;
9810}
9811
Chris Lattner2f503e62005-01-31 05:36:43 +00009812Instruction *InstCombiner::visitStoreInst(StoreInst &SI) {
9813 Value *Val = SI.getOperand(0);
9814 Value *Ptr = SI.getOperand(1);
9815
9816 if (isa<UndefValue>(Ptr)) { // store X, undef -> noop (even if volatile)
Chris Lattner9ca96412006-02-08 03:25:32 +00009817 EraseInstFromFunction(SI);
Chris Lattner2f503e62005-01-31 05:36:43 +00009818 ++NumCombined;
9819 return 0;
9820 }
Chris Lattner836692d2007-01-15 06:51:56 +00009821
9822 // If the RHS is an alloca with a single use, zapify the store, making the
9823 // alloca dead.
9824 if (Ptr->hasOneUse()) {
9825 if (isa<AllocaInst>(Ptr)) {
9826 EraseInstFromFunction(SI);
9827 ++NumCombined;
9828 return 0;
9829 }
9830
9831 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr))
9832 if (isa<AllocaInst>(GEP->getOperand(0)) &&
9833 GEP->getOperand(0)->hasOneUse()) {
9834 EraseInstFromFunction(SI);
9835 ++NumCombined;
9836 return 0;
9837 }
9838 }
Chris Lattner2f503e62005-01-31 05:36:43 +00009839
Dan Gohman9941f742007-07-20 16:34:21 +00009840 // Attempt to improve the alignment.
Chris Lattnerf2369f22007-08-09 19:05:49 +00009841 unsigned KnownAlign = GetOrEnforceKnownAlignment(Ptr, TD);
Dan Gohman9941f742007-07-20 16:34:21 +00009842 if (KnownAlign > SI.getAlignment())
9843 SI.setAlignment(KnownAlign);
9844
Chris Lattner9ca96412006-02-08 03:25:32 +00009845 // Do really simple DSE, to catch cases where there are several consequtive
9846 // stores to the same location, separated by a few arithmetic operations. This
9847 // situation often occurs with bitfield accesses.
9848 BasicBlock::iterator BBI = &SI;
9849 for (unsigned ScanInsts = 6; BBI != SI.getParent()->begin() && ScanInsts;
9850 --ScanInsts) {
9851 --BBI;
9852
9853 if (StoreInst *PrevSI = dyn_cast<StoreInst>(BBI)) {
9854 // Prev store isn't volatile, and stores to the same location?
9855 if (!PrevSI->isVolatile() && PrevSI->getOperand(1) == SI.getOperand(1)) {
9856 ++NumDeadStore;
9857 ++BBI;
9858 EraseInstFromFunction(*PrevSI);
9859 continue;
9860 }
9861 break;
9862 }
9863
Chris Lattnerb4db97f2006-05-26 19:19:20 +00009864 // If this is a load, we have to stop. However, if the loaded value is from
9865 // the pointer we're loading and is producing the pointer we're storing,
9866 // then *this* store is dead (X = load P; store X -> P).
9867 if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
Chris Lattnera54c7eb2007-09-07 05:33:03 +00009868 if (LI == Val && LI->getOperand(0) == Ptr && !SI.isVolatile()) {
Chris Lattnerb4db97f2006-05-26 19:19:20 +00009869 EraseInstFromFunction(SI);
9870 ++NumCombined;
9871 return 0;
9872 }
9873 // Otherwise, this is a load from some other location. Stores before it
9874 // may not be dead.
9875 break;
9876 }
9877
Chris Lattner9ca96412006-02-08 03:25:32 +00009878 // Don't skip over loads or things that can modify memory.
Chris Lattnerb4db97f2006-05-26 19:19:20 +00009879 if (BBI->mayWriteToMemory())
Chris Lattner9ca96412006-02-08 03:25:32 +00009880 break;
9881 }
9882
9883
9884 if (SI.isVolatile()) return 0; // Don't hack volatile stores.
Chris Lattner2f503e62005-01-31 05:36:43 +00009885
9886 // store X, null -> turns into 'unreachable' in SimplifyCFG
9887 if (isa<ConstantPointerNull>(Ptr)) {
9888 if (!isa<UndefValue>(Val)) {
9889 SI.setOperand(0, UndefValue::get(Val->getType()));
9890 if (Instruction *U = dyn_cast<Instruction>(Val))
Chris Lattnerdbab3862007-03-02 21:28:56 +00009891 AddToWorkList(U); // Dropped a use.
Chris Lattner2f503e62005-01-31 05:36:43 +00009892 ++NumCombined;
9893 }
9894 return 0; // Do not modify these!
9895 }
9896
9897 // store undef, Ptr -> noop
9898 if (isa<UndefValue>(Val)) {
Chris Lattner9ca96412006-02-08 03:25:32 +00009899 EraseInstFromFunction(SI);
Chris Lattner2f503e62005-01-31 05:36:43 +00009900 ++NumCombined;
9901 return 0;
9902 }
9903
Chris Lattnerfcfe33a2005-01-31 05:51:45 +00009904 // If the pointer destination is a cast, see if we can fold the cast into the
9905 // source instead.
Reid Spencer3ed469c2006-11-02 20:25:50 +00009906 if (isa<CastInst>(Ptr))
Chris Lattnerfcfe33a2005-01-31 05:51:45 +00009907 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
9908 return Res;
9909 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr))
Reid Spencer3da59db2006-11-27 01:05:10 +00009910 if (CE->isCast())
Chris Lattnerfcfe33a2005-01-31 05:51:45 +00009911 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
9912 return Res;
9913
Chris Lattner408902b2005-09-12 23:23:25 +00009914
9915 // If this store is the last instruction in the basic block, and if the block
9916 // ends with an unconditional branch, try to move it to the successor block.
Chris Lattner9ca96412006-02-08 03:25:32 +00009917 BBI = &SI; ++BBI;
Chris Lattner408902b2005-09-12 23:23:25 +00009918 if (BranchInst *BI = dyn_cast<BranchInst>(BBI))
Chris Lattner3284d1f2007-04-15 00:07:55 +00009919 if (BI->isUnconditional())
9920 if (SimplifyStoreAtEndOfBlock(SI))
9921 return 0; // xform done!
Chris Lattner408902b2005-09-12 23:23:25 +00009922
Chris Lattner2f503e62005-01-31 05:36:43 +00009923 return 0;
9924}
9925
Chris Lattner3284d1f2007-04-15 00:07:55 +00009926/// SimplifyStoreAtEndOfBlock - Turn things like:
9927/// if () { *P = v1; } else { *P = v2 }
9928/// into a phi node with a store in the successor.
9929///
Chris Lattner31755a02007-04-15 01:02:18 +00009930/// Simplify things like:
9931/// *P = v1; if () { *P = v2; }
9932/// into a phi node with a store in the successor.
9933///
Chris Lattner3284d1f2007-04-15 00:07:55 +00009934bool InstCombiner::SimplifyStoreAtEndOfBlock(StoreInst &SI) {
9935 BasicBlock *StoreBB = SI.getParent();
9936
9937 // Check to see if the successor block has exactly two incoming edges. If
9938 // so, see if the other predecessor contains a store to the same location.
9939 // if so, insert a PHI node (if needed) and move the stores down.
Chris Lattner31755a02007-04-15 01:02:18 +00009940 BasicBlock *DestBB = StoreBB->getTerminator()->getSuccessor(0);
Chris Lattner3284d1f2007-04-15 00:07:55 +00009941
9942 // Determine whether Dest has exactly two predecessors and, if so, compute
9943 // the other predecessor.
Chris Lattner31755a02007-04-15 01:02:18 +00009944 pred_iterator PI = pred_begin(DestBB);
9945 BasicBlock *OtherBB = 0;
Chris Lattner3284d1f2007-04-15 00:07:55 +00009946 if (*PI != StoreBB)
Chris Lattner31755a02007-04-15 01:02:18 +00009947 OtherBB = *PI;
Chris Lattner3284d1f2007-04-15 00:07:55 +00009948 ++PI;
Chris Lattner31755a02007-04-15 01:02:18 +00009949 if (PI == pred_end(DestBB))
Chris Lattner3284d1f2007-04-15 00:07:55 +00009950 return false;
9951
9952 if (*PI != StoreBB) {
Chris Lattner31755a02007-04-15 01:02:18 +00009953 if (OtherBB)
Chris Lattner3284d1f2007-04-15 00:07:55 +00009954 return false;
Chris Lattner31755a02007-04-15 01:02:18 +00009955 OtherBB = *PI;
Chris Lattner3284d1f2007-04-15 00:07:55 +00009956 }
Chris Lattner31755a02007-04-15 01:02:18 +00009957 if (++PI != pred_end(DestBB))
Chris Lattner3284d1f2007-04-15 00:07:55 +00009958 return false;
9959
9960
Chris Lattner31755a02007-04-15 01:02:18 +00009961 // Verify that the other block ends in a branch and is not otherwise empty.
9962 BasicBlock::iterator BBI = OtherBB->getTerminator();
Chris Lattner3284d1f2007-04-15 00:07:55 +00009963 BranchInst *OtherBr = dyn_cast<BranchInst>(BBI);
Chris Lattner31755a02007-04-15 01:02:18 +00009964 if (!OtherBr || BBI == OtherBB->begin())
Chris Lattner3284d1f2007-04-15 00:07:55 +00009965 return false;
9966
Chris Lattner31755a02007-04-15 01:02:18 +00009967 // If the other block ends in an unconditional branch, check for the 'if then
9968 // else' case. there is an instruction before the branch.
9969 StoreInst *OtherStore = 0;
9970 if (OtherBr->isUnconditional()) {
9971 // If this isn't a store, or isn't a store to the same location, bail out.
9972 --BBI;
9973 OtherStore = dyn_cast<StoreInst>(BBI);
9974 if (!OtherStore || OtherStore->getOperand(1) != SI.getOperand(1))
9975 return false;
9976 } else {
Chris Lattnerd717c182007-05-05 22:32:24 +00009977 // Otherwise, the other block ended with a conditional branch. If one of the
Chris Lattner31755a02007-04-15 01:02:18 +00009978 // destinations is StoreBB, then we have the if/then case.
9979 if (OtherBr->getSuccessor(0) != StoreBB &&
9980 OtherBr->getSuccessor(1) != StoreBB)
9981 return false;
9982
9983 // Okay, we know that OtherBr now goes to Dest and StoreBB, so this is an
Chris Lattnerd717c182007-05-05 22:32:24 +00009984 // if/then triangle. See if there is a store to the same ptr as SI that
9985 // lives in OtherBB.
Chris Lattner31755a02007-04-15 01:02:18 +00009986 for (;; --BBI) {
9987 // Check to see if we find the matching store.
9988 if ((OtherStore = dyn_cast<StoreInst>(BBI))) {
9989 if (OtherStore->getOperand(1) != SI.getOperand(1))
9990 return false;
9991 break;
9992 }
Chris Lattnerd717c182007-05-05 22:32:24 +00009993 // If we find something that may be using the stored value, or if we run
9994 // out of instructions, we can't do the xform.
Chris Lattner31755a02007-04-15 01:02:18 +00009995 if (isa<LoadInst>(BBI) || BBI->mayWriteToMemory() ||
9996 BBI == OtherBB->begin())
9997 return false;
9998 }
9999
10000 // In order to eliminate the store in OtherBr, we have to
10001 // make sure nothing reads the stored value in StoreBB.
10002 for (BasicBlock::iterator I = StoreBB->begin(); &*I != &SI; ++I) {
10003 // FIXME: This should really be AA driven.
10004 if (isa<LoadInst>(I) || I->mayWriteToMemory())
10005 return false;
10006 }
10007 }
Chris Lattner3284d1f2007-04-15 00:07:55 +000010008
Chris Lattner31755a02007-04-15 01:02:18 +000010009 // Insert a PHI node now if we need it.
Chris Lattner3284d1f2007-04-15 00:07:55 +000010010 Value *MergedVal = OtherStore->getOperand(0);
10011 if (MergedVal != SI.getOperand(0)) {
10012 PHINode *PN = new PHINode(MergedVal->getType(), "storemerge");
10013 PN->reserveOperandSpace(2);
10014 PN->addIncoming(SI.getOperand(0), SI.getParent());
Chris Lattner31755a02007-04-15 01:02:18 +000010015 PN->addIncoming(OtherStore->getOperand(0), OtherBB);
10016 MergedVal = InsertNewInstBefore(PN, DestBB->front());
Chris Lattner3284d1f2007-04-15 00:07:55 +000010017 }
10018
10019 // Advance to a place where it is safe to insert the new store and
10020 // insert it.
Chris Lattner31755a02007-04-15 01:02:18 +000010021 BBI = DestBB->begin();
Chris Lattner3284d1f2007-04-15 00:07:55 +000010022 while (isa<PHINode>(BBI)) ++BBI;
10023 InsertNewInstBefore(new StoreInst(MergedVal, SI.getOperand(1),
10024 OtherStore->isVolatile()), *BBI);
10025
10026 // Nuke the old stores.
10027 EraseInstFromFunction(SI);
10028 EraseInstFromFunction(*OtherStore);
10029 ++NumCombined;
10030 return true;
10031}
10032
Chris Lattner2f503e62005-01-31 05:36:43 +000010033
Chris Lattnerc4d10eb2003-06-04 04:46:00 +000010034Instruction *InstCombiner::visitBranchInst(BranchInst &BI) {
10035 // Change br (not X), label True, label False to: br X, label False, True
Reid Spencer4b828e62005-06-18 17:37:34 +000010036 Value *X = 0;
Chris Lattneracd1f0f2004-07-30 07:50:03 +000010037 BasicBlock *TrueDest;
10038 BasicBlock *FalseDest;
10039 if (match(&BI, m_Br(m_Not(m_Value(X)), TrueDest, FalseDest)) &&
10040 !isa<Constant>(X)) {
10041 // Swap Destinations and condition...
10042 BI.setCondition(X);
10043 BI.setSuccessor(0, FalseDest);
10044 BI.setSuccessor(1, TrueDest);
10045 return &BI;
10046 }
10047
Reid Spencere4d87aa2006-12-23 06:05:41 +000010048 // Cannonicalize fcmp_one -> fcmp_oeq
10049 FCmpInst::Predicate FPred; Value *Y;
10050 if (match(&BI, m_Br(m_FCmp(FPred, m_Value(X), m_Value(Y)),
10051 TrueDest, FalseDest)))
10052 if ((FPred == FCmpInst::FCMP_ONE || FPred == FCmpInst::FCMP_OLE ||
10053 FPred == FCmpInst::FCMP_OGE) && BI.getCondition()->hasOneUse()) {
10054 FCmpInst *I = cast<FCmpInst>(BI.getCondition());
Reid Spencere4d87aa2006-12-23 06:05:41 +000010055 FCmpInst::Predicate NewPred = FCmpInst::getInversePredicate(FPred);
Chris Lattner6934a042007-02-11 01:23:03 +000010056 Instruction *NewSCC = new FCmpInst(NewPred, X, Y, "", I);
10057 NewSCC->takeName(I);
Reid Spencere4d87aa2006-12-23 06:05:41 +000010058 // Swap Destinations and condition...
10059 BI.setCondition(NewSCC);
10060 BI.setSuccessor(0, FalseDest);
10061 BI.setSuccessor(1, TrueDest);
Chris Lattnerdbab3862007-03-02 21:28:56 +000010062 RemoveFromWorkList(I);
Chris Lattner6934a042007-02-11 01:23:03 +000010063 I->eraseFromParent();
Chris Lattnerdbab3862007-03-02 21:28:56 +000010064 AddToWorkList(NewSCC);
Reid Spencere4d87aa2006-12-23 06:05:41 +000010065 return &BI;
10066 }
10067
10068 // Cannonicalize icmp_ne -> icmp_eq
10069 ICmpInst::Predicate IPred;
10070 if (match(&BI, m_Br(m_ICmp(IPred, m_Value(X), m_Value(Y)),
10071 TrueDest, FalseDest)))
10072 if ((IPred == ICmpInst::ICMP_NE || IPred == ICmpInst::ICMP_ULE ||
10073 IPred == ICmpInst::ICMP_SLE || IPred == ICmpInst::ICMP_UGE ||
10074 IPred == ICmpInst::ICMP_SGE) && BI.getCondition()->hasOneUse()) {
10075 ICmpInst *I = cast<ICmpInst>(BI.getCondition());
Reid Spencere4d87aa2006-12-23 06:05:41 +000010076 ICmpInst::Predicate NewPred = ICmpInst::getInversePredicate(IPred);
Chris Lattner6934a042007-02-11 01:23:03 +000010077 Instruction *NewSCC = new ICmpInst(NewPred, X, Y, "", I);
10078 NewSCC->takeName(I);
Chris Lattner40f5d702003-06-04 05:10:11 +000010079 // Swap Destinations and condition...
Chris Lattneracd1f0f2004-07-30 07:50:03 +000010080 BI.setCondition(NewSCC);
Chris Lattner40f5d702003-06-04 05:10:11 +000010081 BI.setSuccessor(0, FalseDest);
10082 BI.setSuccessor(1, TrueDest);
Chris Lattnerdbab3862007-03-02 21:28:56 +000010083 RemoveFromWorkList(I);
Chris Lattner6934a042007-02-11 01:23:03 +000010084 I->eraseFromParent();;
Chris Lattnerdbab3862007-03-02 21:28:56 +000010085 AddToWorkList(NewSCC);
Chris Lattner40f5d702003-06-04 05:10:11 +000010086 return &BI;
10087 }
Misha Brukmanfd939082005-04-21 23:48:37 +000010088
Chris Lattnerc4d10eb2003-06-04 04:46:00 +000010089 return 0;
10090}
Chris Lattner0864acf2002-11-04 16:18:53 +000010091
Chris Lattner46238a62004-07-03 00:26:11 +000010092Instruction *InstCombiner::visitSwitchInst(SwitchInst &SI) {
10093 Value *Cond = SI.getCondition();
10094 if (Instruction *I = dyn_cast<Instruction>(Cond)) {
10095 if (I->getOpcode() == Instruction::Add)
10096 if (ConstantInt *AddRHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
10097 // change 'switch (X+4) case 1:' into 'switch (X) case -3'
10098 for (unsigned i = 2, e = SI.getNumOperands(); i != e; i += 2)
Chris Lattnere87597f2004-10-16 18:11:37 +000010099 SI.setOperand(i,ConstantExpr::getSub(cast<Constant>(SI.getOperand(i)),
Chris Lattner46238a62004-07-03 00:26:11 +000010100 AddRHS));
10101 SI.setOperand(0, I->getOperand(0));
Chris Lattnerdbab3862007-03-02 21:28:56 +000010102 AddToWorkList(I);
Chris Lattner46238a62004-07-03 00:26:11 +000010103 return &SI;
10104 }
10105 }
10106 return 0;
10107}
10108
Chris Lattner220b0cf2006-03-05 00:22:33 +000010109/// CheapToScalarize - Return true if the value is cheaper to scalarize than it
10110/// is to leave as a vector operation.
10111static bool CheapToScalarize(Value *V, bool isConstant) {
10112 if (isa<ConstantAggregateZero>(V))
10113 return true;
Reid Spencer9d6565a2007-02-15 02:26:10 +000010114 if (ConstantVector *C = dyn_cast<ConstantVector>(V)) {
Chris Lattner220b0cf2006-03-05 00:22:33 +000010115 if (isConstant) return true;
10116 // If all elts are the same, we can extract.
10117 Constant *Op0 = C->getOperand(0);
10118 for (unsigned i = 1; i < C->getNumOperands(); ++i)
10119 if (C->getOperand(i) != Op0)
10120 return false;
10121 return true;
10122 }
10123 Instruction *I = dyn_cast<Instruction>(V);
10124 if (!I) return false;
10125
10126 // Insert element gets simplified to the inserted element or is deleted if
10127 // this is constant idx extract element and its a constant idx insertelt.
10128 if (I->getOpcode() == Instruction::InsertElement && isConstant &&
10129 isa<ConstantInt>(I->getOperand(2)))
10130 return true;
10131 if (I->getOpcode() == Instruction::Load && I->hasOneUse())
10132 return true;
10133 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I))
10134 if (BO->hasOneUse() &&
10135 (CheapToScalarize(BO->getOperand(0), isConstant) ||
10136 CheapToScalarize(BO->getOperand(1), isConstant)))
10137 return true;
Reid Spencere4d87aa2006-12-23 06:05:41 +000010138 if (CmpInst *CI = dyn_cast<CmpInst>(I))
10139 if (CI->hasOneUse() &&
10140 (CheapToScalarize(CI->getOperand(0), isConstant) ||
10141 CheapToScalarize(CI->getOperand(1), isConstant)))
10142 return true;
Chris Lattner220b0cf2006-03-05 00:22:33 +000010143
10144 return false;
10145}
10146
Chris Lattnerd2b7cec2007-02-14 05:52:17 +000010147/// Read and decode a shufflevector mask.
10148///
10149/// It turns undef elements into values that are larger than the number of
10150/// elements in the input.
Chris Lattner863bcff2006-05-25 23:48:38 +000010151static std::vector<unsigned> getShuffleMask(const ShuffleVectorInst *SVI) {
10152 unsigned NElts = SVI->getType()->getNumElements();
10153 if (isa<ConstantAggregateZero>(SVI->getOperand(2)))
10154 return std::vector<unsigned>(NElts, 0);
10155 if (isa<UndefValue>(SVI->getOperand(2)))
10156 return std::vector<unsigned>(NElts, 2*NElts);
10157
10158 std::vector<unsigned> Result;
Reid Spencer9d6565a2007-02-15 02:26:10 +000010159 const ConstantVector *CP = cast<ConstantVector>(SVI->getOperand(2));
Chris Lattner863bcff2006-05-25 23:48:38 +000010160 for (unsigned i = 0, e = CP->getNumOperands(); i != e; ++i)
10161 if (isa<UndefValue>(CP->getOperand(i)))
10162 Result.push_back(NElts*2); // undef -> 8
10163 else
Reid Spencerb83eb642006-10-20 07:07:24 +000010164 Result.push_back(cast<ConstantInt>(CP->getOperand(i))->getZExtValue());
Chris Lattner863bcff2006-05-25 23:48:38 +000010165 return Result;
10166}
10167
Chris Lattner6e6b0da2006-03-31 23:01:56 +000010168/// FindScalarElement - Given a vector and an element number, see if the scalar
10169/// value is already around as a register, for example if it were inserted then
10170/// extracted from the vector.
10171static Value *FindScalarElement(Value *V, unsigned EltNo) {
Reid Spencer9d6565a2007-02-15 02:26:10 +000010172 assert(isa<VectorType>(V->getType()) && "Not looking at a vector?");
10173 const VectorType *PTy = cast<VectorType>(V->getType());
Chris Lattner389a6f52006-04-10 23:06:36 +000010174 unsigned Width = PTy->getNumElements();
10175 if (EltNo >= Width) // Out of range access.
Chris Lattner6e6b0da2006-03-31 23:01:56 +000010176 return UndefValue::get(PTy->getElementType());
10177
10178 if (isa<UndefValue>(V))
10179 return UndefValue::get(PTy->getElementType());
10180 else if (isa<ConstantAggregateZero>(V))
10181 return Constant::getNullValue(PTy->getElementType());
Reid Spencer9d6565a2007-02-15 02:26:10 +000010182 else if (ConstantVector *CP = dyn_cast<ConstantVector>(V))
Chris Lattner6e6b0da2006-03-31 23:01:56 +000010183 return CP->getOperand(EltNo);
10184 else if (InsertElementInst *III = dyn_cast<InsertElementInst>(V)) {
10185 // If this is an insert to a variable element, we don't know what it is.
Reid Spencerb83eb642006-10-20 07:07:24 +000010186 if (!isa<ConstantInt>(III->getOperand(2)))
10187 return 0;
10188 unsigned IIElt = cast<ConstantInt>(III->getOperand(2))->getZExtValue();
Chris Lattner6e6b0da2006-03-31 23:01:56 +000010189
10190 // If this is an insert to the element we are looking for, return the
10191 // inserted value.
Reid Spencerb83eb642006-10-20 07:07:24 +000010192 if (EltNo == IIElt)
10193 return III->getOperand(1);
Chris Lattner6e6b0da2006-03-31 23:01:56 +000010194
10195 // Otherwise, the insertelement doesn't modify the value, recurse on its
10196 // vector input.
10197 return FindScalarElement(III->getOperand(0), EltNo);
Chris Lattner389a6f52006-04-10 23:06:36 +000010198 } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(V)) {
Chris Lattner863bcff2006-05-25 23:48:38 +000010199 unsigned InEl = getShuffleMask(SVI)[EltNo];
10200 if (InEl < Width)
10201 return FindScalarElement(SVI->getOperand(0), InEl);
10202 else if (InEl < Width*2)
10203 return FindScalarElement(SVI->getOperand(1), InEl - Width);
10204 else
10205 return UndefValue::get(PTy->getElementType());
Chris Lattner6e6b0da2006-03-31 23:01:56 +000010206 }
10207
10208 // Otherwise, we don't know.
10209 return 0;
10210}
10211
Robert Bocchino1d7456d2006-01-13 22:48:06 +000010212Instruction *InstCombiner::visitExtractElementInst(ExtractElementInst &EI) {
Chris Lattner6e6b0da2006-03-31 23:01:56 +000010213
Dan Gohman07a96762007-07-16 14:29:03 +000010214 // If vector val is undef, replace extract with scalar undef.
Chris Lattner1f13c882006-03-31 18:25:14 +000010215 if (isa<UndefValue>(EI.getOperand(0)))
10216 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
10217
Dan Gohman07a96762007-07-16 14:29:03 +000010218 // If vector val is constant 0, replace extract with scalar 0.
Chris Lattner1f13c882006-03-31 18:25:14 +000010219 if (isa<ConstantAggregateZero>(EI.getOperand(0)))
10220 return ReplaceInstUsesWith(EI, Constant::getNullValue(EI.getType()));
10221
Reid Spencer9d6565a2007-02-15 02:26:10 +000010222 if (ConstantVector *C = dyn_cast<ConstantVector>(EI.getOperand(0))) {
Dan Gohman07a96762007-07-16 14:29:03 +000010223 // If vector val is constant with uniform operands, replace EI
Robert Bocchino1d7456d2006-01-13 22:48:06 +000010224 // with that operand
Chris Lattner220b0cf2006-03-05 00:22:33 +000010225 Constant *op0 = C->getOperand(0);
Robert Bocchino1d7456d2006-01-13 22:48:06 +000010226 for (unsigned i = 1; i < C->getNumOperands(); ++i)
Chris Lattner220b0cf2006-03-05 00:22:33 +000010227 if (C->getOperand(i) != op0) {
10228 op0 = 0;
10229 break;
10230 }
10231 if (op0)
10232 return ReplaceInstUsesWith(EI, op0);
Robert Bocchino1d7456d2006-01-13 22:48:06 +000010233 }
Chris Lattner220b0cf2006-03-05 00:22:33 +000010234
Chris Lattner6e6b0da2006-03-31 23:01:56 +000010235 // If extracting a specified index from the vector, see if we can recursively
10236 // find a previously computed scalar that was inserted into the vector.
Reid Spencerb83eb642006-10-20 07:07:24 +000010237 if (ConstantInt *IdxC = dyn_cast<ConstantInt>(EI.getOperand(1))) {
Chris Lattner85464092007-04-09 01:37:55 +000010238 unsigned IndexVal = IdxC->getZExtValue();
10239 unsigned VectorWidth =
10240 cast<VectorType>(EI.getOperand(0)->getType())->getNumElements();
10241
10242 // If this is extracting an invalid index, turn this into undef, to avoid
10243 // crashing the code below.
10244 if (IndexVal >= VectorWidth)
10245 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
10246
Chris Lattner867b99f2006-10-05 06:55:50 +000010247 // This instruction only demands the single element from the input vector.
10248 // If the input vector has a single use, simplify it based on this use
10249 // property.
Chris Lattner85464092007-04-09 01:37:55 +000010250 if (EI.getOperand(0)->hasOneUse() && VectorWidth != 1) {
Chris Lattner867b99f2006-10-05 06:55:50 +000010251 uint64_t UndefElts;
10252 if (Value *V = SimplifyDemandedVectorElts(EI.getOperand(0),
Reid Spencerb83eb642006-10-20 07:07:24 +000010253 1 << IndexVal,
Chris Lattner867b99f2006-10-05 06:55:50 +000010254 UndefElts)) {
10255 EI.setOperand(0, V);
10256 return &EI;
10257 }
10258 }
10259
Reid Spencerb83eb642006-10-20 07:07:24 +000010260 if (Value *Elt = FindScalarElement(EI.getOperand(0), IndexVal))
Chris Lattner6e6b0da2006-03-31 23:01:56 +000010261 return ReplaceInstUsesWith(EI, Elt);
Chris Lattnerb7300fa2007-04-14 23:02:14 +000010262
10263 // If the this extractelement is directly using a bitcast from a vector of
10264 // the same number of elements, see if we can find the source element from
10265 // it. In this case, we will end up needing to bitcast the scalars.
10266 if (BitCastInst *BCI = dyn_cast<BitCastInst>(EI.getOperand(0))) {
10267 if (const VectorType *VT =
10268 dyn_cast<VectorType>(BCI->getOperand(0)->getType()))
10269 if (VT->getNumElements() == VectorWidth)
10270 if (Value *Elt = FindScalarElement(BCI->getOperand(0), IndexVal))
10271 return new BitCastInst(Elt, EI.getType());
10272 }
Chris Lattner389a6f52006-04-10 23:06:36 +000010273 }
Chris Lattner6e6b0da2006-03-31 23:01:56 +000010274
Chris Lattner73fa49d2006-05-25 22:53:38 +000010275 if (Instruction *I = dyn_cast<Instruction>(EI.getOperand(0))) {
Robert Bocchino1d7456d2006-01-13 22:48:06 +000010276 if (I->hasOneUse()) {
10277 // Push extractelement into predecessor operation if legal and
10278 // profitable to do so
10279 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) {
Chris Lattner220b0cf2006-03-05 00:22:33 +000010280 bool isConstantElt = isa<ConstantInt>(EI.getOperand(1));
10281 if (CheapToScalarize(BO, isConstantElt)) {
10282 ExtractElementInst *newEI0 =
10283 new ExtractElementInst(BO->getOperand(0), EI.getOperand(1),
10284 EI.getName()+".lhs");
10285 ExtractElementInst *newEI1 =
10286 new ExtractElementInst(BO->getOperand(1), EI.getOperand(1),
10287 EI.getName()+".rhs");
10288 InsertNewInstBefore(newEI0, EI);
10289 InsertNewInstBefore(newEI1, EI);
10290 return BinaryOperator::create(BO->getOpcode(), newEI0, newEI1);
10291 }
Reid Spencer3ed469c2006-11-02 20:25:50 +000010292 } else if (isa<LoadInst>(I)) {
Christopher Lamb43ad6b32007-12-17 01:12:55 +000010293 unsigned AS =
10294 cast<PointerType>(I->getOperand(0)->getType())->getAddressSpace();
Chris Lattner6d0339d2008-01-13 22:23:22 +000010295 Value *Ptr = InsertBitCastBefore(I->getOperand(0),
10296 PointerType::get(EI.getType(), AS),EI);
Robert Bocchino1d7456d2006-01-13 22:48:06 +000010297 GetElementPtrInst *GEP =
Reid Spencerde331242006-11-29 01:11:01 +000010298 new GetElementPtrInst(Ptr, EI.getOperand(1), I->getName() + ".gep");
Robert Bocchino1d7456d2006-01-13 22:48:06 +000010299 InsertNewInstBefore(GEP, EI);
10300 return new LoadInst(GEP);
Chris Lattner73fa49d2006-05-25 22:53:38 +000010301 }
10302 }
10303 if (InsertElementInst *IE = dyn_cast<InsertElementInst>(I)) {
10304 // Extracting the inserted element?
10305 if (IE->getOperand(2) == EI.getOperand(1))
10306 return ReplaceInstUsesWith(EI, IE->getOperand(1));
10307 // If the inserted and extracted elements are constants, they must not
10308 // be the same value, extract from the pre-inserted value instead.
10309 if (isa<Constant>(IE->getOperand(2)) &&
10310 isa<Constant>(EI.getOperand(1))) {
10311 AddUsesToWorkList(EI);
10312 EI.setOperand(0, IE->getOperand(0));
10313 return &EI;
10314 }
10315 } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(I)) {
10316 // If this is extracting an element from a shufflevector, figure out where
10317 // it came from and extract from the appropriate input element instead.
Reid Spencerb83eb642006-10-20 07:07:24 +000010318 if (ConstantInt *Elt = dyn_cast<ConstantInt>(EI.getOperand(1))) {
10319 unsigned SrcIdx = getShuffleMask(SVI)[Elt->getZExtValue()];
Chris Lattner863bcff2006-05-25 23:48:38 +000010320 Value *Src;
10321 if (SrcIdx < SVI->getType()->getNumElements())
10322 Src = SVI->getOperand(0);
10323 else if (SrcIdx < SVI->getType()->getNumElements()*2) {
10324 SrcIdx -= SVI->getType()->getNumElements();
10325 Src = SVI->getOperand(1);
10326 } else {
10327 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
Chris Lattnerdf084ff2006-03-30 22:02:40 +000010328 }
Chris Lattner867b99f2006-10-05 06:55:50 +000010329 return new ExtractElementInst(Src, SrcIdx);
Robert Bocchino1d7456d2006-01-13 22:48:06 +000010330 }
10331 }
Chris Lattner73fa49d2006-05-25 22:53:38 +000010332 }
Robert Bocchino1d7456d2006-01-13 22:48:06 +000010333 return 0;
10334}
10335
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000010336/// CollectSingleShuffleElements - If V is a shuffle of values that ONLY returns
10337/// elements from either LHS or RHS, return the shuffle mask and true.
10338/// Otherwise, return false.
10339static bool CollectSingleShuffleElements(Value *V, Value *LHS, Value *RHS,
10340 std::vector<Constant*> &Mask) {
10341 assert(V->getType() == LHS->getType() && V->getType() == RHS->getType() &&
10342 "Invalid CollectSingleShuffleElements");
Reid Spencer9d6565a2007-02-15 02:26:10 +000010343 unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000010344
10345 if (isa<UndefValue>(V)) {
Reid Spencerc5b206b2006-12-31 05:48:39 +000010346 Mask.assign(NumElts, UndefValue::get(Type::Int32Ty));
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000010347 return true;
10348 } else if (V == LHS) {
10349 for (unsigned i = 0; i != NumElts; ++i)
Reid Spencerc5b206b2006-12-31 05:48:39 +000010350 Mask.push_back(ConstantInt::get(Type::Int32Ty, i));
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000010351 return true;
10352 } else if (V == RHS) {
10353 for (unsigned i = 0; i != NumElts; ++i)
Reid Spencerc5b206b2006-12-31 05:48:39 +000010354 Mask.push_back(ConstantInt::get(Type::Int32Ty, i+NumElts));
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000010355 return true;
10356 } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
10357 // If this is an insert of an extract from some other vector, include it.
10358 Value *VecOp = IEI->getOperand(0);
10359 Value *ScalarOp = IEI->getOperand(1);
10360 Value *IdxOp = IEI->getOperand(2);
10361
Chris Lattnerd929f062006-04-27 21:14:21 +000010362 if (!isa<ConstantInt>(IdxOp))
10363 return false;
Reid Spencerb83eb642006-10-20 07:07:24 +000010364 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
Chris Lattnerd929f062006-04-27 21:14:21 +000010365
10366 if (isa<UndefValue>(ScalarOp)) { // inserting undef into vector.
10367 // Okay, we can handle this if the vector we are insertinting into is
10368 // transitively ok.
10369 if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask)) {
10370 // If so, update the mask to reflect the inserted undef.
Reid Spencerc5b206b2006-12-31 05:48:39 +000010371 Mask[InsertedIdx] = UndefValue::get(Type::Int32Ty);
Chris Lattnerd929f062006-04-27 21:14:21 +000010372 return true;
10373 }
10374 } else if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)){
10375 if (isa<ConstantInt>(EI->getOperand(1)) &&
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000010376 EI->getOperand(0)->getType() == V->getType()) {
10377 unsigned ExtractedIdx =
Reid Spencerb83eb642006-10-20 07:07:24 +000010378 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000010379
10380 // This must be extracting from either LHS or RHS.
10381 if (EI->getOperand(0) == LHS || EI->getOperand(0) == RHS) {
10382 // Okay, we can handle this if the vector we are insertinting into is
10383 // transitively ok.
10384 if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask)) {
10385 // If so, update the mask to reflect the inserted value.
10386 if (EI->getOperand(0) == LHS) {
10387 Mask[InsertedIdx & (NumElts-1)] =
Reid Spencerc5b206b2006-12-31 05:48:39 +000010388 ConstantInt::get(Type::Int32Ty, ExtractedIdx);
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000010389 } else {
10390 assert(EI->getOperand(0) == RHS);
10391 Mask[InsertedIdx & (NumElts-1)] =
Reid Spencerc5b206b2006-12-31 05:48:39 +000010392 ConstantInt::get(Type::Int32Ty, ExtractedIdx+NumElts);
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000010393
10394 }
10395 return true;
10396 }
10397 }
10398 }
10399 }
10400 }
10401 // TODO: Handle shufflevector here!
10402
10403 return false;
10404}
10405
10406/// CollectShuffleElements - We are building a shuffle of V, using RHS as the
10407/// RHS of the shuffle instruction, if it is not null. Return a shuffle mask
10408/// that computes V and the LHS value of the shuffle.
Chris Lattnerefb47352006-04-15 01:39:45 +000010409static Value *CollectShuffleElements(Value *V, std::vector<Constant*> &Mask,
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000010410 Value *&RHS) {
Reid Spencer9d6565a2007-02-15 02:26:10 +000010411 assert(isa<VectorType>(V->getType()) &&
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000010412 (RHS == 0 || V->getType() == RHS->getType()) &&
Chris Lattnerefb47352006-04-15 01:39:45 +000010413 "Invalid shuffle!");
Reid Spencer9d6565a2007-02-15 02:26:10 +000010414 unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
Chris Lattnerefb47352006-04-15 01:39:45 +000010415
10416 if (isa<UndefValue>(V)) {
Reid Spencerc5b206b2006-12-31 05:48:39 +000010417 Mask.assign(NumElts, UndefValue::get(Type::Int32Ty));
Chris Lattnerefb47352006-04-15 01:39:45 +000010418 return V;
10419 } else if (isa<ConstantAggregateZero>(V)) {
Reid Spencerc5b206b2006-12-31 05:48:39 +000010420 Mask.assign(NumElts, ConstantInt::get(Type::Int32Ty, 0));
Chris Lattnerefb47352006-04-15 01:39:45 +000010421 return V;
10422 } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
10423 // If this is an insert of an extract from some other vector, include it.
10424 Value *VecOp = IEI->getOperand(0);
10425 Value *ScalarOp = IEI->getOperand(1);
10426 Value *IdxOp = IEI->getOperand(2);
10427
10428 if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
10429 if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
10430 EI->getOperand(0)->getType() == V->getType()) {
10431 unsigned ExtractedIdx =
Reid Spencerb83eb642006-10-20 07:07:24 +000010432 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
10433 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
Chris Lattnerefb47352006-04-15 01:39:45 +000010434
10435 // Either the extracted from or inserted into vector must be RHSVec,
10436 // otherwise we'd end up with a shuffle of three inputs.
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000010437 if (EI->getOperand(0) == RHS || RHS == 0) {
10438 RHS = EI->getOperand(0);
10439 Value *V = CollectShuffleElements(VecOp, Mask, RHS);
Chris Lattnerefb47352006-04-15 01:39:45 +000010440 Mask[InsertedIdx & (NumElts-1)] =
Reid Spencerc5b206b2006-12-31 05:48:39 +000010441 ConstantInt::get(Type::Int32Ty, NumElts+ExtractedIdx);
Chris Lattnerefb47352006-04-15 01:39:45 +000010442 return V;
10443 }
10444
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000010445 if (VecOp == RHS) {
10446 Value *V = CollectShuffleElements(EI->getOperand(0), Mask, RHS);
Chris Lattnerefb47352006-04-15 01:39:45 +000010447 // Everything but the extracted element is replaced with the RHS.
10448 for (unsigned i = 0; i != NumElts; ++i) {
10449 if (i != InsertedIdx)
Reid Spencerc5b206b2006-12-31 05:48:39 +000010450 Mask[i] = ConstantInt::get(Type::Int32Ty, NumElts+i);
Chris Lattnerefb47352006-04-15 01:39:45 +000010451 }
10452 return V;
10453 }
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000010454
10455 // If this insertelement is a chain that comes from exactly these two
10456 // vectors, return the vector and the effective shuffle.
10457 if (CollectSingleShuffleElements(IEI, EI->getOperand(0), RHS, Mask))
10458 return EI->getOperand(0);
10459
Chris Lattnerefb47352006-04-15 01:39:45 +000010460 }
10461 }
10462 }
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000010463 // TODO: Handle shufflevector here!
Chris Lattnerefb47352006-04-15 01:39:45 +000010464
10465 // Otherwise, can't do anything fancy. Return an identity vector.
10466 for (unsigned i = 0; i != NumElts; ++i)
Reid Spencerc5b206b2006-12-31 05:48:39 +000010467 Mask.push_back(ConstantInt::get(Type::Int32Ty, i));
Chris Lattnerefb47352006-04-15 01:39:45 +000010468 return V;
10469}
10470
10471Instruction *InstCombiner::visitInsertElementInst(InsertElementInst &IE) {
10472 Value *VecOp = IE.getOperand(0);
10473 Value *ScalarOp = IE.getOperand(1);
10474 Value *IdxOp = IE.getOperand(2);
10475
Chris Lattner599ded12007-04-09 01:11:16 +000010476 // Inserting an undef or into an undefined place, remove this.
10477 if (isa<UndefValue>(ScalarOp) || isa<UndefValue>(IdxOp))
10478 ReplaceInstUsesWith(IE, VecOp);
10479
Chris Lattnerefb47352006-04-15 01:39:45 +000010480 // If the inserted element was extracted from some other vector, and if the
10481 // indexes are constant, try to turn this into a shufflevector operation.
10482 if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
10483 if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
10484 EI->getOperand(0)->getType() == IE.getType()) {
10485 unsigned NumVectorElts = IE.getType()->getNumElements();
Chris Lattnere34e9a22007-04-14 23:32:02 +000010486 unsigned ExtractedIdx =
10487 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
Reid Spencerb83eb642006-10-20 07:07:24 +000010488 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
Chris Lattnerefb47352006-04-15 01:39:45 +000010489
10490 if (ExtractedIdx >= NumVectorElts) // Out of range extract.
10491 return ReplaceInstUsesWith(IE, VecOp);
10492
10493 if (InsertedIdx >= NumVectorElts) // Out of range insert.
10494 return ReplaceInstUsesWith(IE, UndefValue::get(IE.getType()));
10495
10496 // If we are extracting a value from a vector, then inserting it right
10497 // back into the same place, just use the input vector.
10498 if (EI->getOperand(0) == VecOp && ExtractedIdx == InsertedIdx)
10499 return ReplaceInstUsesWith(IE, VecOp);
10500
10501 // We could theoretically do this for ANY input. However, doing so could
10502 // turn chains of insertelement instructions into a chain of shufflevector
10503 // instructions, and right now we do not merge shufflevectors. As such,
10504 // only do this in a situation where it is clear that there is benefit.
10505 if (isa<UndefValue>(VecOp) || isa<ConstantAggregateZero>(VecOp)) {
10506 // Turn this into shuffle(EIOp0, VecOp, Mask). The result has all of
10507 // the values of VecOp, except then one read from EIOp0.
10508 // Build a new shuffle mask.
10509 std::vector<Constant*> Mask;
10510 if (isa<UndefValue>(VecOp))
Reid Spencerc5b206b2006-12-31 05:48:39 +000010511 Mask.assign(NumVectorElts, UndefValue::get(Type::Int32Ty));
Chris Lattnerefb47352006-04-15 01:39:45 +000010512 else {
10513 assert(isa<ConstantAggregateZero>(VecOp) && "Unknown thing");
Reid Spencerc5b206b2006-12-31 05:48:39 +000010514 Mask.assign(NumVectorElts, ConstantInt::get(Type::Int32Ty,
Chris Lattnerefb47352006-04-15 01:39:45 +000010515 NumVectorElts));
10516 }
Reid Spencerc5b206b2006-12-31 05:48:39 +000010517 Mask[InsertedIdx] = ConstantInt::get(Type::Int32Ty, ExtractedIdx);
Chris Lattnerefb47352006-04-15 01:39:45 +000010518 return new ShuffleVectorInst(EI->getOperand(0), VecOp,
Reid Spencer9d6565a2007-02-15 02:26:10 +000010519 ConstantVector::get(Mask));
Chris Lattnerefb47352006-04-15 01:39:45 +000010520 }
10521
10522 // If this insertelement isn't used by some other insertelement, turn it
10523 // (and any insertelements it points to), into one big shuffle.
10524 if (!IE.hasOneUse() || !isa<InsertElementInst>(IE.use_back())) {
10525 std::vector<Constant*> Mask;
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000010526 Value *RHS = 0;
10527 Value *LHS = CollectShuffleElements(&IE, Mask, RHS);
10528 if (RHS == 0) RHS = UndefValue::get(LHS->getType());
10529 // We now have a shuffle of LHS, RHS, Mask.
Reid Spencer9d6565a2007-02-15 02:26:10 +000010530 return new ShuffleVectorInst(LHS, RHS, ConstantVector::get(Mask));
Chris Lattnerefb47352006-04-15 01:39:45 +000010531 }
10532 }
10533 }
10534
10535 return 0;
10536}
10537
10538
Chris Lattnera844fc4c2006-04-10 22:45:52 +000010539Instruction *InstCombiner::visitShuffleVectorInst(ShuffleVectorInst &SVI) {
10540 Value *LHS = SVI.getOperand(0);
10541 Value *RHS = SVI.getOperand(1);
Chris Lattner863bcff2006-05-25 23:48:38 +000010542 std::vector<unsigned> Mask = getShuffleMask(&SVI);
Chris Lattnera844fc4c2006-04-10 22:45:52 +000010543
10544 bool MadeChange = false;
10545
Chris Lattner867b99f2006-10-05 06:55:50 +000010546 // Undefined shuffle mask -> undefined value.
Chris Lattner863bcff2006-05-25 23:48:38 +000010547 if (isa<UndefValue>(SVI.getOperand(2)))
Chris Lattnera844fc4c2006-04-10 22:45:52 +000010548 return ReplaceInstUsesWith(SVI, UndefValue::get(SVI.getType()));
10549
Chris Lattnere4929dd2007-01-05 07:36:08 +000010550 // If we have shuffle(x, undef, mask) and any elements of mask refer to
Chris Lattnerefb47352006-04-15 01:39:45 +000010551 // the undef, change them to undefs.
Chris Lattnere4929dd2007-01-05 07:36:08 +000010552 if (isa<UndefValue>(SVI.getOperand(1))) {
10553 // Scan to see if there are any references to the RHS. If so, replace them
10554 // with undef element refs and set MadeChange to true.
10555 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
10556 if (Mask[i] >= e && Mask[i] != 2*e) {
10557 Mask[i] = 2*e;
10558 MadeChange = true;
10559 }
10560 }
10561
10562 if (MadeChange) {
10563 // Remap any references to RHS to use LHS.
10564 std::vector<Constant*> Elts;
10565 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
10566 if (Mask[i] == 2*e)
10567 Elts.push_back(UndefValue::get(Type::Int32Ty));
10568 else
10569 Elts.push_back(ConstantInt::get(Type::Int32Ty, Mask[i]));
10570 }
Reid Spencer9d6565a2007-02-15 02:26:10 +000010571 SVI.setOperand(2, ConstantVector::get(Elts));
Chris Lattnere4929dd2007-01-05 07:36:08 +000010572 }
10573 }
Chris Lattnerefb47352006-04-15 01:39:45 +000010574
Chris Lattner863bcff2006-05-25 23:48:38 +000010575 // Canonicalize shuffle(x ,x,mask) -> shuffle(x, undef,mask')
10576 // Canonicalize shuffle(undef,x,mask) -> shuffle(x, undef,mask').
10577 if (LHS == RHS || isa<UndefValue>(LHS)) {
10578 if (isa<UndefValue>(LHS) && LHS == RHS) {
Chris Lattnera844fc4c2006-04-10 22:45:52 +000010579 // shuffle(undef,undef,mask) -> undef.
10580 return ReplaceInstUsesWith(SVI, LHS);
10581 }
10582
Chris Lattner863bcff2006-05-25 23:48:38 +000010583 // Remap any references to RHS to use LHS.
10584 std::vector<Constant*> Elts;
10585 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
Chris Lattner7b2e27922006-05-26 00:29:06 +000010586 if (Mask[i] >= 2*e)
Reid Spencerc5b206b2006-12-31 05:48:39 +000010587 Elts.push_back(UndefValue::get(Type::Int32Ty));
Chris Lattner7b2e27922006-05-26 00:29:06 +000010588 else {
10589 if ((Mask[i] >= e && isa<UndefValue>(RHS)) ||
10590 (Mask[i] < e && isa<UndefValue>(LHS)))
10591 Mask[i] = 2*e; // Turn into undef.
10592 else
10593 Mask[i] &= (e-1); // Force to LHS.
Reid Spencerc5b206b2006-12-31 05:48:39 +000010594 Elts.push_back(ConstantInt::get(Type::Int32Ty, Mask[i]));
Chris Lattner7b2e27922006-05-26 00:29:06 +000010595 }
Chris Lattnera844fc4c2006-04-10 22:45:52 +000010596 }
Chris Lattner863bcff2006-05-25 23:48:38 +000010597 SVI.setOperand(0, SVI.getOperand(1));
Chris Lattnera844fc4c2006-04-10 22:45:52 +000010598 SVI.setOperand(1, UndefValue::get(RHS->getType()));
Reid Spencer9d6565a2007-02-15 02:26:10 +000010599 SVI.setOperand(2, ConstantVector::get(Elts));
Chris Lattner7b2e27922006-05-26 00:29:06 +000010600 LHS = SVI.getOperand(0);
10601 RHS = SVI.getOperand(1);
Chris Lattnera844fc4c2006-04-10 22:45:52 +000010602 MadeChange = true;
10603 }
10604
Chris Lattner7b2e27922006-05-26 00:29:06 +000010605 // Analyze the shuffle, are the LHS or RHS and identity shuffles?
Chris Lattner863bcff2006-05-25 23:48:38 +000010606 bool isLHSID = true, isRHSID = true;
Chris Lattner706126d2006-04-16 00:03:56 +000010607
Chris Lattner863bcff2006-05-25 23:48:38 +000010608 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
10609 if (Mask[i] >= e*2) continue; // Ignore undef values.
10610 // Is this an identity shuffle of the LHS value?
10611 isLHSID &= (Mask[i] == i);
10612
10613 // Is this an identity shuffle of the RHS value?
10614 isRHSID &= (Mask[i]-e == i);
Chris Lattner706126d2006-04-16 00:03:56 +000010615 }
Chris Lattnera844fc4c2006-04-10 22:45:52 +000010616
Chris Lattner863bcff2006-05-25 23:48:38 +000010617 // Eliminate identity shuffles.
10618 if (isLHSID) return ReplaceInstUsesWith(SVI, LHS);
10619 if (isRHSID) return ReplaceInstUsesWith(SVI, RHS);
Chris Lattnera844fc4c2006-04-10 22:45:52 +000010620
Chris Lattner7b2e27922006-05-26 00:29:06 +000010621 // If the LHS is a shufflevector itself, see if we can combine it with this
10622 // one without producing an unusual shuffle. Here we are really conservative:
10623 // we are absolutely afraid of producing a shuffle mask not in the input
10624 // program, because the code gen may not be smart enough to turn a merged
10625 // shuffle into two specific shuffles: it may produce worse code. As such,
10626 // we only merge two shuffles if the result is one of the two input shuffle
10627 // masks. In this case, merging the shuffles just removes one instruction,
10628 // which we know is safe. This is good for things like turning:
10629 // (splat(splat)) -> splat.
10630 if (ShuffleVectorInst *LHSSVI = dyn_cast<ShuffleVectorInst>(LHS)) {
10631 if (isa<UndefValue>(RHS)) {
10632 std::vector<unsigned> LHSMask = getShuffleMask(LHSSVI);
10633
10634 std::vector<unsigned> NewMask;
10635 for (unsigned i = 0, e = Mask.size(); i != e; ++i)
10636 if (Mask[i] >= 2*e)
10637 NewMask.push_back(2*e);
10638 else
10639 NewMask.push_back(LHSMask[Mask[i]]);
10640
10641 // If the result mask is equal to the src shuffle or this shuffle mask, do
10642 // the replacement.
10643 if (NewMask == LHSMask || NewMask == Mask) {
10644 std::vector<Constant*> Elts;
10645 for (unsigned i = 0, e = NewMask.size(); i != e; ++i) {
10646 if (NewMask[i] >= e*2) {
Reid Spencerc5b206b2006-12-31 05:48:39 +000010647 Elts.push_back(UndefValue::get(Type::Int32Ty));
Chris Lattner7b2e27922006-05-26 00:29:06 +000010648 } else {
Reid Spencerc5b206b2006-12-31 05:48:39 +000010649 Elts.push_back(ConstantInt::get(Type::Int32Ty, NewMask[i]));
Chris Lattner7b2e27922006-05-26 00:29:06 +000010650 }
10651 }
10652 return new ShuffleVectorInst(LHSSVI->getOperand(0),
10653 LHSSVI->getOperand(1),
Reid Spencer9d6565a2007-02-15 02:26:10 +000010654 ConstantVector::get(Elts));
Chris Lattner7b2e27922006-05-26 00:29:06 +000010655 }
10656 }
10657 }
Chris Lattnerc5eff442007-01-30 22:32:46 +000010658
Chris Lattnera844fc4c2006-04-10 22:45:52 +000010659 return MadeChange ? &SVI : 0;
10660}
10661
10662
Robert Bocchino1d7456d2006-01-13 22:48:06 +000010663
Chris Lattnerea1c4542004-12-08 23:43:58 +000010664
10665/// TryToSinkInstruction - Try to move the specified instruction from its
10666/// current block into the beginning of DestBlock, which can only happen if it's
10667/// safe to move the instruction past all of the instructions between it and the
10668/// end of its block.
10669static bool TryToSinkInstruction(Instruction *I, BasicBlock *DestBlock) {
10670 assert(I->hasOneUse() && "Invariants didn't hold!");
10671
Chris Lattner108e9022005-10-27 17:13:11 +000010672 // Cannot move control-flow-involving, volatile loads, vaarg, etc.
10673 if (isa<PHINode>(I) || I->mayWriteToMemory()) return false;
Misha Brukmanfd939082005-04-21 23:48:37 +000010674
Chris Lattnerea1c4542004-12-08 23:43:58 +000010675 // Do not sink alloca instructions out of the entry block.
Dan Gohmanecb7a772007-03-22 16:38:57 +000010676 if (isa<AllocaInst>(I) && I->getParent() ==
10677 &DestBlock->getParent()->getEntryBlock())
Chris Lattnerea1c4542004-12-08 23:43:58 +000010678 return false;
10679
Chris Lattner96a52a62004-12-09 07:14:34 +000010680 // We can only sink load instructions if there is nothing between the load and
10681 // the end of block that could change the value.
10682 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
Chris Lattner96a52a62004-12-09 07:14:34 +000010683 for (BasicBlock::iterator Scan = LI, E = LI->getParent()->end();
10684 Scan != E; ++Scan)
10685 if (Scan->mayWriteToMemory())
10686 return false;
Chris Lattner96a52a62004-12-09 07:14:34 +000010687 }
Chris Lattnerea1c4542004-12-08 23:43:58 +000010688
10689 BasicBlock::iterator InsertPos = DestBlock->begin();
10690 while (isa<PHINode>(InsertPos)) ++InsertPos;
10691
Chris Lattner4bc5f802005-08-08 19:11:57 +000010692 I->moveBefore(InsertPos);
Chris Lattnerea1c4542004-12-08 23:43:58 +000010693 ++NumSunkInst;
10694 return true;
10695}
10696
Chris Lattnerf4f5a772006-05-10 19:00:36 +000010697
10698/// AddReachableCodeToWorklist - Walk the function in depth-first order, adding
10699/// all reachable code to the worklist.
10700///
10701/// This has a couple of tricks to make the code faster and more powerful. In
10702/// particular, we constant fold and DCE instructions as we go, to avoid adding
10703/// them to the worklist (this significantly speeds up instcombine on code where
10704/// many instructions are dead or constant). Additionally, if we find a branch
10705/// whose condition is a known constant, we only visit the reachable successors.
10706///
10707static void AddReachableCodeToWorklist(BasicBlock *BB,
Chris Lattner1f87a582007-02-15 19:41:52 +000010708 SmallPtrSet<BasicBlock*, 64> &Visited,
Chris Lattnerdbab3862007-03-02 21:28:56 +000010709 InstCombiner &IC,
Chris Lattner8c8c66a2006-05-11 17:11:52 +000010710 const TargetData *TD) {
Chris Lattner2c7718a2007-03-23 19:17:18 +000010711 std::vector<BasicBlock*> Worklist;
10712 Worklist.push_back(BB);
Chris Lattnerf4f5a772006-05-10 19:00:36 +000010713
Chris Lattner2c7718a2007-03-23 19:17:18 +000010714 while (!Worklist.empty()) {
10715 BB = Worklist.back();
10716 Worklist.pop_back();
10717
10718 // We have now visited this block! If we've already been here, ignore it.
10719 if (!Visited.insert(BB)) continue;
10720
10721 for (BasicBlock::iterator BBI = BB->begin(), E = BB->end(); BBI != E; ) {
10722 Instruction *Inst = BBI++;
Chris Lattnerf4f5a772006-05-10 19:00:36 +000010723
Chris Lattner2c7718a2007-03-23 19:17:18 +000010724 // DCE instruction if trivially dead.
10725 if (isInstructionTriviallyDead(Inst)) {
10726 ++NumDeadInst;
10727 DOUT << "IC: DCE: " << *Inst;
10728 Inst->eraseFromParent();
10729 continue;
10730 }
10731
10732 // ConstantProp instruction if trivially constant.
10733 if (Constant *C = ConstantFoldInstruction(Inst, TD)) {
10734 DOUT << "IC: ConstFold to: " << *C << " from: " << *Inst;
10735 Inst->replaceAllUsesWith(C);
10736 ++NumConstProp;
10737 Inst->eraseFromParent();
10738 continue;
10739 }
Chris Lattner3ccc6bc2007-07-20 22:06:41 +000010740
Chris Lattner2c7718a2007-03-23 19:17:18 +000010741 IC.AddToWorkList(Inst);
Chris Lattnerf4f5a772006-05-10 19:00:36 +000010742 }
Chris Lattner2c7718a2007-03-23 19:17:18 +000010743
10744 // Recursively visit successors. If this is a branch or switch on a
10745 // constant, only visit the reachable successor.
10746 TerminatorInst *TI = BB->getTerminator();
10747 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
10748 if (BI->isConditional() && isa<ConstantInt>(BI->getCondition())) {
10749 bool CondVal = cast<ConstantInt>(BI->getCondition())->getZExtValue();
10750 Worklist.push_back(BI->getSuccessor(!CondVal));
10751 continue;
10752 }
10753 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
10754 if (ConstantInt *Cond = dyn_cast<ConstantInt>(SI->getCondition())) {
10755 // See if this is an explicit destination.
10756 for (unsigned i = 1, e = SI->getNumSuccessors(); i != e; ++i)
10757 if (SI->getCaseValue(i) == Cond) {
10758 Worklist.push_back(SI->getSuccessor(i));
10759 continue;
10760 }
10761
10762 // Otherwise it is the default destination.
10763 Worklist.push_back(SI->getSuccessor(0));
10764 continue;
10765 }
10766 }
10767
10768 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
10769 Worklist.push_back(TI->getSuccessor(i));
Chris Lattnerf4f5a772006-05-10 19:00:36 +000010770 }
Chris Lattnerf4f5a772006-05-10 19:00:36 +000010771}
10772
Chris Lattnerec9c3582007-03-03 02:04:50 +000010773bool InstCombiner::DoOneIteration(Function &F, unsigned Iteration) {
Chris Lattnerdd841ae2002-04-18 17:39:14 +000010774 bool Changed = false;
Chris Lattnerbc61e662003-11-02 05:57:39 +000010775 TD = &getAnalysis<TargetData>();
Chris Lattnerec9c3582007-03-03 02:04:50 +000010776
10777 DEBUG(DOUT << "\n\nINSTCOMBINE ITERATION #" << Iteration << " on "
10778 << F.getNameStr() << "\n");
Chris Lattner8a2a3112001-12-14 16:52:21 +000010779
Chris Lattnerb3d59702005-07-07 20:40:38 +000010780 {
Chris Lattnerf4f5a772006-05-10 19:00:36 +000010781 // Do a depth-first traversal of the function, populate the worklist with
10782 // the reachable instructions. Ignore blocks that are not reachable. Keep
10783 // track of which blocks we visit.
Chris Lattner1f87a582007-02-15 19:41:52 +000010784 SmallPtrSet<BasicBlock*, 64> Visited;
Chris Lattnerdbab3862007-03-02 21:28:56 +000010785 AddReachableCodeToWorklist(F.begin(), Visited, *this, TD);
Jeff Cohen00b168892005-07-27 06:12:32 +000010786
Chris Lattnerb3d59702005-07-07 20:40:38 +000010787 // Do a quick scan over the function. If we find any blocks that are
10788 // unreachable, remove any instructions inside of them. This prevents
10789 // the instcombine code from having to deal with some bad special cases.
10790 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
10791 if (!Visited.count(BB)) {
10792 Instruction *Term = BB->getTerminator();
10793 while (Term != BB->begin()) { // Remove instrs bottom-up
10794 BasicBlock::iterator I = Term; --I;
Chris Lattner6ffe5512004-04-27 15:13:33 +000010795
Bill Wendlingb7427032006-11-26 09:46:52 +000010796 DOUT << "IC: DCE: " << *I;
Chris Lattnerb3d59702005-07-07 20:40:38 +000010797 ++NumDeadInst;
10798
10799 if (!I->use_empty())
10800 I->replaceAllUsesWith(UndefValue::get(I->getType()));
10801 I->eraseFromParent();
10802 }
10803 }
10804 }
Chris Lattner8a2a3112001-12-14 16:52:21 +000010805
Chris Lattnerdbab3862007-03-02 21:28:56 +000010806 while (!Worklist.empty()) {
10807 Instruction *I = RemoveOneFromWorkList();
10808 if (I == 0) continue; // skip null values.
Chris Lattner8a2a3112001-12-14 16:52:21 +000010809
Chris Lattner8c8c66a2006-05-11 17:11:52 +000010810 // Check to see if we can DCE the instruction.
Chris Lattner62b14df2002-09-02 04:59:56 +000010811 if (isInstructionTriviallyDead(I)) {
Chris Lattner8c8c66a2006-05-11 17:11:52 +000010812 // Add operands to the worklist.
Chris Lattner4bb7c022003-10-06 17:11:01 +000010813 if (I->getNumOperands() < 4)
Chris Lattner7bcc0e72004-02-28 05:22:00 +000010814 AddUsesToWorkList(*I);
Chris Lattner62b14df2002-09-02 04:59:56 +000010815 ++NumDeadInst;
Chris Lattner4bb7c022003-10-06 17:11:01 +000010816
Bill Wendlingb7427032006-11-26 09:46:52 +000010817 DOUT << "IC: DCE: " << *I;
Chris Lattnerad5fec12005-01-28 19:32:01 +000010818
10819 I->eraseFromParent();
Chris Lattnerdbab3862007-03-02 21:28:56 +000010820 RemoveFromWorkList(I);
Chris Lattner4bb7c022003-10-06 17:11:01 +000010821 continue;
10822 }
Chris Lattner62b14df2002-09-02 04:59:56 +000010823
Chris Lattner8c8c66a2006-05-11 17:11:52 +000010824 // Instruction isn't dead, see if we can constant propagate it.
Chris Lattner0a19ffa2007-01-30 23:16:15 +000010825 if (Constant *C = ConstantFoldInstruction(I, TD)) {
Bill Wendlingb7427032006-11-26 09:46:52 +000010826 DOUT << "IC: ConstFold to: " << *C << " from: " << *I;
Chris Lattnerad5fec12005-01-28 19:32:01 +000010827
Chris Lattner8c8c66a2006-05-11 17:11:52 +000010828 // Add operands to the worklist.
Chris Lattner7bcc0e72004-02-28 05:22:00 +000010829 AddUsesToWorkList(*I);
Chris Lattnerc736d562002-12-05 22:41:53 +000010830 ReplaceInstUsesWith(*I, C);
10831
Chris Lattner62b14df2002-09-02 04:59:56 +000010832 ++NumConstProp;
Chris Lattnerf4f5a772006-05-10 19:00:36 +000010833 I->eraseFromParent();
Chris Lattnerdbab3862007-03-02 21:28:56 +000010834 RemoveFromWorkList(I);
Chris Lattner4bb7c022003-10-06 17:11:01 +000010835 continue;
Chris Lattner62b14df2002-09-02 04:59:56 +000010836 }
Chris Lattner4bb7c022003-10-06 17:11:01 +000010837
Chris Lattnerea1c4542004-12-08 23:43:58 +000010838 // See if we can trivially sink this instruction to a successor basic block.
10839 if (I->hasOneUse()) {
10840 BasicBlock *BB = I->getParent();
10841 BasicBlock *UserParent = cast<Instruction>(I->use_back())->getParent();
10842 if (UserParent != BB) {
10843 bool UserIsSuccessor = false;
10844 // See if the user is one of our successors.
10845 for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI)
10846 if (*SI == UserParent) {
10847 UserIsSuccessor = true;
10848 break;
10849 }
10850
10851 // If the user is one of our immediate successors, and if that successor
10852 // only has us as a predecessors (we'd have to split the critical edge
10853 // otherwise), we can keep going.
10854 if (UserIsSuccessor && !isa<PHINode>(I->use_back()) &&
10855 next(pred_begin(UserParent)) == pred_end(UserParent))
10856 // Okay, the CFG is simple enough, try to sink this instruction.
10857 Changed |= TryToSinkInstruction(I, UserParent);
10858 }
10859 }
10860
Chris Lattner8a2a3112001-12-14 16:52:21 +000010861 // Now that we have an instruction, try combining it to simplify it...
Reid Spencera9b81012007-03-26 17:44:01 +000010862#ifndef NDEBUG
10863 std::string OrigI;
10864#endif
10865 DEBUG(std::ostringstream SS; I->print(SS); OrigI = SS.str(););
Chris Lattner90ac28c2002-08-02 19:29:35 +000010866 if (Instruction *Result = visit(*I)) {
Chris Lattner3dec1f22002-05-10 15:38:35 +000010867 ++NumCombined;
Chris Lattnerdd841ae2002-04-18 17:39:14 +000010868 // Should we replace the old instruction with a new one?
Chris Lattnerb3bc8fa2002-05-14 15:24:07 +000010869 if (Result != I) {
Bill Wendlingb7427032006-11-26 09:46:52 +000010870 DOUT << "IC: Old = " << *I
10871 << " New = " << *Result;
Chris Lattner0cea42a2004-03-13 23:54:27 +000010872
Chris Lattnerf523d062004-06-09 05:08:07 +000010873 // Everything uses the new instruction now.
10874 I->replaceAllUsesWith(Result);
10875
10876 // Push the new instruction and any users onto the worklist.
Chris Lattnerdbab3862007-03-02 21:28:56 +000010877 AddToWorkList(Result);
Chris Lattnerf523d062004-06-09 05:08:07 +000010878 AddUsersToWorkList(*Result);
Chris Lattner4bb7c022003-10-06 17:11:01 +000010879
Chris Lattner6934a042007-02-11 01:23:03 +000010880 // Move the name to the new instruction first.
10881 Result->takeName(I);
Chris Lattner4bb7c022003-10-06 17:11:01 +000010882
10883 // Insert the new instruction into the basic block...
10884 BasicBlock *InstParent = I->getParent();
Chris Lattnerbac32862004-11-14 19:13:23 +000010885 BasicBlock::iterator InsertPos = I;
10886
10887 if (!isa<PHINode>(Result)) // If combining a PHI, don't insert
10888 while (isa<PHINode>(InsertPos)) // middle of a block of PHIs.
10889 ++InsertPos;
10890
10891 InstParent->getInstList().insert(InsertPos, Result);
Chris Lattner4bb7c022003-10-06 17:11:01 +000010892
Chris Lattner00d51312004-05-01 23:27:23 +000010893 // Make sure that we reprocess all operands now that we reduced their
10894 // use counts.
Chris Lattnerdbab3862007-03-02 21:28:56 +000010895 AddUsesToWorkList(*I);
Chris Lattner216d4d82004-05-01 23:19:52 +000010896
Chris Lattnerf523d062004-06-09 05:08:07 +000010897 // Instructions can end up on the worklist more than once. Make sure
10898 // we do not process an instruction that has been deleted.
Chris Lattnerdbab3862007-03-02 21:28:56 +000010899 RemoveFromWorkList(I);
Chris Lattner4bb7c022003-10-06 17:11:01 +000010900
10901 // Erase the old instruction.
10902 InstParent->getInstList().erase(I);
Chris Lattner7e708292002-06-25 16:13:24 +000010903 } else {
Evan Chengc7baf682007-03-27 16:44:48 +000010904#ifndef NDEBUG
Reid Spencera9b81012007-03-26 17:44:01 +000010905 DOUT << "IC: Mod = " << OrigI
10906 << " New = " << *I;
Evan Chengc7baf682007-03-27 16:44:48 +000010907#endif
Chris Lattner0cea42a2004-03-13 23:54:27 +000010908
Chris Lattner90ac28c2002-08-02 19:29:35 +000010909 // If the instruction was modified, it's possible that it is now dead.
10910 // if so, remove it.
Chris Lattner00d51312004-05-01 23:27:23 +000010911 if (isInstructionTriviallyDead(I)) {
10912 // Make sure we process all operands now that we are reducing their
10913 // use counts.
Chris Lattnerec9c3582007-03-03 02:04:50 +000010914 AddUsesToWorkList(*I);
Misha Brukmanfd939082005-04-21 23:48:37 +000010915
Chris Lattner00d51312004-05-01 23:27:23 +000010916 // Instructions may end up in the worklist more than once. Erase all
Robert Bocchino1d7456d2006-01-13 22:48:06 +000010917 // occurrences of this instruction.
Chris Lattnerdbab3862007-03-02 21:28:56 +000010918 RemoveFromWorkList(I);
Chris Lattner2f503e62005-01-31 05:36:43 +000010919 I->eraseFromParent();
Chris Lattnerf523d062004-06-09 05:08:07 +000010920 } else {
Chris Lattnerec9c3582007-03-03 02:04:50 +000010921 AddToWorkList(I);
10922 AddUsersToWorkList(*I);
Chris Lattner90ac28c2002-08-02 19:29:35 +000010923 }
Chris Lattnerb3bc8fa2002-05-14 15:24:07 +000010924 }
Chris Lattnerdd841ae2002-04-18 17:39:14 +000010925 Changed = true;
Chris Lattner8a2a3112001-12-14 16:52:21 +000010926 }
10927 }
10928
Chris Lattnerec9c3582007-03-03 02:04:50 +000010929 assert(WorklistMap.empty() && "Worklist empty, but map not?");
Chris Lattnera9ff5eb2007-08-05 08:47:58 +000010930
10931 // Do an explicit clear, this shrinks the map if needed.
10932 WorklistMap.clear();
Chris Lattnerdd841ae2002-04-18 17:39:14 +000010933 return Changed;
Chris Lattnerbd0ef772002-02-26 21:46:54 +000010934}
10935
Chris Lattnerec9c3582007-03-03 02:04:50 +000010936
10937bool InstCombiner::runOnFunction(Function &F) {
Chris Lattnerf964f322007-03-04 04:27:24 +000010938 MustPreserveLCSSA = mustPreserveAnalysisID(LCSSAID);
10939
Chris Lattnerec9c3582007-03-03 02:04:50 +000010940 bool EverMadeChange = false;
10941
10942 // Iterate while there is work to do.
10943 unsigned Iteration = 0;
10944 while (DoOneIteration(F, Iteration++))
10945 EverMadeChange = true;
10946 return EverMadeChange;
10947}
10948
Brian Gaeke96d4bf72004-07-27 17:43:21 +000010949FunctionPass *llvm::createInstructionCombiningPass() {
Chris Lattnerdd841ae2002-04-18 17:39:14 +000010950 return new InstCombiner();
Chris Lattnerbd0ef772002-02-26 21:46:54 +000010951}
Brian Gaeked0fde302003-11-11 22:41:34 +000010952