blob: 8b46a243a9119f5bbb3c6e4e08d8c74a16eacf5c [file] [log] [blame]
Chris Lattner233f7dc2002-08-12 21:17:25 +00001//===- InstructionCombining.cpp - Combine multiple instructions -----------===//
Misha Brukmanfd939082005-04-21 23:48:37 +00002//
John Criswellb576c942003-10-20 19:43:21 +00003// The LLVM Compiler Infrastructure
4//
Chris Lattner4ee451d2007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Misha Brukmanfd939082005-04-21 23:48:37 +00007//
John Criswellb576c942003-10-20 19:43:21 +00008//===----------------------------------------------------------------------===//
Chris Lattner8a2a3112001-12-14 16:52:21 +00009//
10// InstructionCombining - Combine instructions to form fewer, simple
Dan Gohman844731a2008-05-13 00:00:25 +000011// instructions. This pass does not modify the CFG. This pass is where
12// algebraic simplification happens.
Chris Lattner8a2a3112001-12-14 16:52:21 +000013//
14// This pass combines things like:
Chris Lattner318bf792007-03-18 22:51:34 +000015// %Y = add i32 %X, 1
16// %Z = add i32 %Y, 1
Chris Lattner8a2a3112001-12-14 16:52:21 +000017// into:
Chris Lattner318bf792007-03-18 22:51:34 +000018// %Z = add i32 %X, 2
Chris Lattner8a2a3112001-12-14 16:52:21 +000019//
20// This is a simple worklist driven algorithm.
21//
Chris Lattner065a6162003-09-10 05:29:43 +000022// This pass guarantees that the following canonicalizations are performed on
Chris Lattner2cd91962003-07-23 21:41:57 +000023// the program:
24// 1. If a binary operator has a constant operand, it is moved to the RHS
Chris Lattnerdf17af12003-08-12 21:53:41 +000025// 2. Bitwise operators with constant operands are always grouped so that
26// shifts are performed first, then or's, then and's, then xor's.
Reid Spencere4d87aa2006-12-23 06:05:41 +000027// 3. Compare instructions are converted from <,>,<=,>= to ==,!= if possible
28// 4. All cmp instructions on boolean values are replaced with logical ops
Chris Lattnere92d2f42003-08-13 04:18:28 +000029// 5. add X, X is represented as (X*2) => (X << 1)
30// 6. Multiplies with a power-of-two constant argument are transformed into
31// shifts.
Chris Lattnerbac32862004-11-14 19:13:23 +000032// ... etc.
Chris Lattner2cd91962003-07-23 21:41:57 +000033//
Chris Lattner8a2a3112001-12-14 16:52:21 +000034//===----------------------------------------------------------------------===//
35
Chris Lattner0cea42a2004-03-13 23:54:27 +000036#define DEBUG_TYPE "instcombine"
Chris Lattner022103b2002-05-07 20:03:00 +000037#include "llvm/Transforms/Scalar.h"
Chris Lattner3df5c6f2010-01-04 06:30:00 +000038#include "InstCombineWorklist.h"
Chris Lattner35b9e482004-10-12 04:52:52 +000039#include "llvm/IntrinsicInst.h"
Owen Andersond672ecb2009-07-03 00:17:18 +000040#include "llvm/LLVMContext.h"
Chris Lattnerbd0ef772002-02-26 21:46:54 +000041#include "llvm/Pass.h"
Chris Lattner0864acf2002-11-04 16:18:53 +000042#include "llvm/DerivedTypes.h"
Chris Lattner833b8a42003-06-26 05:06:25 +000043#include "llvm/GlobalVariable.h"
Dan Gohmanca178902009-07-17 20:47:02 +000044#include "llvm/Operator.h"
Chris Lattner79066fa2007-01-30 23:46:24 +000045#include "llvm/Analysis/ConstantFolding.h"
Chris Lattner9dbb4292009-11-09 23:28:39 +000046#include "llvm/Analysis/InstructionSimplify.h"
Victor Hernandezf006b182009-10-27 20:05:49 +000047#include "llvm/Analysis/MemoryBuiltins.h"
Chris Lattner173234a2008-06-02 01:18:21 +000048#include "llvm/Analysis/ValueTracking.h"
Chris Lattnerbc61e662003-11-02 05:57:39 +000049#include "llvm/Target/TargetData.h"
50#include "llvm/Transforms/Utils/BasicBlockUtils.h"
51#include "llvm/Transforms/Utils/Local.h"
Chris Lattner28977af2004-04-05 01:30:19 +000052#include "llvm/Support/CallSite.h"
Nick Lewycky5be29202008-02-03 16:33:09 +000053#include "llvm/Support/ConstantRange.h"
Chris Lattnerea1c4542004-12-08 23:43:58 +000054#include "llvm/Support/Debug.h"
Torok Edwin7d696d82009-07-11 13:10:19 +000055#include "llvm/Support/ErrorHandling.h"
Chris Lattner28977af2004-04-05 01:30:19 +000056#include "llvm/Support/GetElementPtrTypeIterator.h"
Chris Lattnerdd841ae2002-04-18 17:39:14 +000057#include "llvm/Support/InstVisitor.h"
Chris Lattner74381062009-08-30 07:44:24 +000058#include "llvm/Support/IRBuilder.h"
Chris Lattnerbcd7db52005-08-02 19:16:58 +000059#include "llvm/Support/MathExtras.h"
Chris Lattneracd1f0f2004-07-30 07:50:03 +000060#include "llvm/Support/PatternMatch.h"
Chris Lattnere2cc1ad2009-10-15 04:13:44 +000061#include "llvm/Support/TargetFolder.h"
Daniel Dunbarce63ffb2009-07-25 00:23:56 +000062#include "llvm/Support/raw_ostream.h"
Chris Lattnerdbab3862007-03-02 21:28:56 +000063#include "llvm/ADT/DenseMap.h"
Chris Lattner55eb1c42007-01-31 04:40:53 +000064#include "llvm/ADT/SmallVector.h"
Chris Lattner1f87a582007-02-15 19:41:52 +000065#include "llvm/ADT/SmallPtrSet.h"
Reid Spencer551ccae2004-09-01 22:55:40 +000066#include "llvm/ADT/Statistic.h"
Chris Lattnerea1c4542004-12-08 23:43:58 +000067#include "llvm/ADT/STLExtras.h"
Chris Lattnerb3bc8fa2002-05-14 15:24:07 +000068#include <algorithm>
Torok Edwin3eaee312008-04-20 08:33:11 +000069#include <climits>
Chris Lattner67b1e1b2003-12-07 01:24:23 +000070using namespace llvm;
Chris Lattneracd1f0f2004-07-30 07:50:03 +000071using namespace llvm::PatternMatch;
Brian Gaeked0fde302003-11-11 22:41:34 +000072
Chris Lattner0e5f4992006-12-19 21:40:18 +000073STATISTIC(NumCombined , "Number of insts combined");
74STATISTIC(NumConstProp, "Number of constant folds");
75STATISTIC(NumDeadInst , "Number of dead inst eliminated");
76STATISTIC(NumDeadStore, "Number of dead stores eliminated");
77STATISTIC(NumSunkInst , "Number of instructions sunk");
Chris Lattnera92f6962002-10-01 22:38:41 +000078
Chris Lattnerb109b5c2009-12-21 06:03:05 +000079/// SelectPatternFlavor - We can match a variety of different patterns for
80/// select operations.
81enum SelectPatternFlavor {
82 SPF_UNKNOWN = 0,
83 SPF_SMIN, SPF_UMIN,
84 SPF_SMAX, SPF_UMAX
85 //SPF_ABS - TODO.
86};
87
Chris Lattner873ff012009-08-30 05:55:36 +000088
89namespace {
Chris Lattner74381062009-08-30 07:44:24 +000090 /// InstCombineIRInserter - This is an IRBuilder insertion helper that works
91 /// just like the normal insertion helper, but also adds any new instructions
92 /// to the instcombine worklist.
93 class InstCombineIRInserter : public IRBuilderDefaultInserter<true> {
94 InstCombineWorklist &Worklist;
95 public:
96 InstCombineIRInserter(InstCombineWorklist &WL) : Worklist(WL) {}
97
98 void InsertHelper(Instruction *I, const Twine &Name,
99 BasicBlock *BB, BasicBlock::iterator InsertPt) const {
100 IRBuilderDefaultInserter<true>::InsertHelper(I, Name, BB, InsertPt);
101 Worklist.Add(I);
102 }
103 };
104} // end anonymous namespace
105
106
107namespace {
Chris Lattner3e8b6632009-09-02 06:11:42 +0000108 class InstCombiner : public FunctionPass,
109 public InstVisitor<InstCombiner, Instruction*> {
Chris Lattnerbc61e662003-11-02 05:57:39 +0000110 TargetData *TD;
Chris Lattnerf964f322007-03-04 04:27:24 +0000111 bool MustPreserveLCSSA;
Chris Lattnerb0b822c2009-08-31 06:57:37 +0000112 bool MadeIRChange;
Chris Lattnerdbab3862007-03-02 21:28:56 +0000113 public:
Chris Lattner75551f72009-08-30 17:53:59 +0000114 /// Worklist - All of the instructions that need to be simplified.
Chris Lattner7a1e9242009-08-30 06:13:40 +0000115 InstCombineWorklist Worklist;
116
Chris Lattner74381062009-08-30 07:44:24 +0000117 /// Builder - This is an IRBuilder that automatically inserts new
118 /// instructions into the worklist when they are created.
Chris Lattnere2cc1ad2009-10-15 04:13:44 +0000119 typedef IRBuilder<true, TargetFolder, InstCombineIRInserter> BuilderTy;
Chris Lattnerf925cbd2009-08-30 18:50:58 +0000120 BuilderTy *Builder;
Chris Lattner74381062009-08-30 07:44:24 +0000121
Nick Lewyckyecd94c82007-05-06 13:37:16 +0000122 static char ID; // Pass identification, replacement for typeid
Chris Lattner74381062009-08-30 07:44:24 +0000123 InstCombiner() : FunctionPass(&ID), TD(0), Builder(0) {}
Devang Patel794fd752007-05-01 21:15:47 +0000124
Owen Andersone922c022009-07-22 00:24:57 +0000125 LLVMContext *Context;
126 LLVMContext *getContext() const { return Context; }
Owen Andersond672ecb2009-07-03 00:17:18 +0000127
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000128 public:
Chris Lattner7e708292002-06-25 16:13:24 +0000129 virtual bool runOnFunction(Function &F);
Chris Lattnerec9c3582007-03-03 02:04:50 +0000130
131 bool DoOneIteration(Function &F, unsigned ItNum);
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000132
Chris Lattner97e52e42002-04-28 21:27:06 +0000133 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
Owen Andersond1b78a12006-07-10 19:03:49 +0000134 AU.addPreservedID(LCSSAID);
Chris Lattnercb2610e2002-10-21 20:00:28 +0000135 AU.setPreservesCFG();
Chris Lattner97e52e42002-04-28 21:27:06 +0000136 }
137
Dan Gohmance9fe9f2009-07-21 23:21:54 +0000138 TargetData *getTargetData() const { return TD; }
Chris Lattner28977af2004-04-05 01:30:19 +0000139
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000140 // Visitation implementation - Implement instruction combining for different
141 // instruction types. The semantics are as follows:
142 // Return Value:
143 // null - No change was made
Chris Lattner233f7dc2002-08-12 21:17:25 +0000144 // I - Change was made, I is still valid, I may be dead though
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000145 // otherwise - Change was made, replace I with returned instruction
Misha Brukmanfd939082005-04-21 23:48:37 +0000146 //
Chris Lattner7e708292002-06-25 16:13:24 +0000147 Instruction *visitAdd(BinaryOperator &I);
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000148 Instruction *visitFAdd(BinaryOperator &I);
Chris Lattner092543c2009-11-04 08:05:20 +0000149 Value *OptimizePointerDifference(Value *LHS, Value *RHS, const Type *Ty);
Chris Lattner7e708292002-06-25 16:13:24 +0000150 Instruction *visitSub(BinaryOperator &I);
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000151 Instruction *visitFSub(BinaryOperator &I);
Chris Lattner7e708292002-06-25 16:13:24 +0000152 Instruction *visitMul(BinaryOperator &I);
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000153 Instruction *visitFMul(BinaryOperator &I);
Reid Spencer0a783f72006-11-02 01:53:59 +0000154 Instruction *visitURem(BinaryOperator &I);
155 Instruction *visitSRem(BinaryOperator &I);
156 Instruction *visitFRem(BinaryOperator &I);
Chris Lattnerfdb19e52008-07-14 00:15:52 +0000157 bool SimplifyDivRemOfSelect(BinaryOperator &I);
Reid Spencer0a783f72006-11-02 01:53:59 +0000158 Instruction *commonRemTransforms(BinaryOperator &I);
159 Instruction *commonIRemTransforms(BinaryOperator &I);
Reid Spencer1628cec2006-10-26 06:15:43 +0000160 Instruction *commonDivTransforms(BinaryOperator &I);
161 Instruction *commonIDivTransforms(BinaryOperator &I);
162 Instruction *visitUDiv(BinaryOperator &I);
163 Instruction *visitSDiv(BinaryOperator &I);
164 Instruction *visitFDiv(BinaryOperator &I);
Chris Lattner29cd5ba2008-11-16 05:06:21 +0000165 Instruction *FoldAndOfICmps(Instruction &I, ICmpInst *LHS, ICmpInst *RHS);
Chris Lattner42d1be02009-07-23 05:14:02 +0000166 Instruction *FoldAndOfFCmps(Instruction &I, FCmpInst *LHS, FCmpInst *RHS);
Chris Lattner7e708292002-06-25 16:13:24 +0000167 Instruction *visitAnd(BinaryOperator &I);
Chris Lattner69d4ced2008-11-16 05:20:07 +0000168 Instruction *FoldOrOfICmps(Instruction &I, ICmpInst *LHS, ICmpInst *RHS);
Chris Lattner5414cc52009-07-23 05:46:22 +0000169 Instruction *FoldOrOfFCmps(Instruction &I, FCmpInst *LHS, FCmpInst *RHS);
Bill Wendlingd54d8602008-12-01 08:32:40 +0000170 Instruction *FoldOrWithConstants(BinaryOperator &I, Value *Op,
Bill Wendlinga698a472008-12-01 08:23:25 +0000171 Value *A, Value *B, Value *C);
Chris Lattner7e708292002-06-25 16:13:24 +0000172 Instruction *visitOr (BinaryOperator &I);
173 Instruction *visitXor(BinaryOperator &I);
Reid Spencer832254e2007-02-02 02:16:23 +0000174 Instruction *visitShl(BinaryOperator &I);
175 Instruction *visitAShr(BinaryOperator &I);
176 Instruction *visitLShr(BinaryOperator &I);
177 Instruction *commonShiftTransforms(BinaryOperator &I);
Chris Lattnera5406232008-05-19 20:18:56 +0000178 Instruction *FoldFCmp_IntToFP_Cst(FCmpInst &I, Instruction *LHSI,
179 Constant *RHSC);
Chris Lattner1f12e442010-01-02 08:12:04 +0000180 Instruction *FoldCmpLoadFromIndexedGlobal(GetElementPtrInst *GEP,
Chris Lattnerdf3d63b2010-01-02 22:08:28 +0000181 GlobalVariable *GV, CmpInst &ICI,
182 ConstantInt *AndCst = 0);
Reid Spencere4d87aa2006-12-23 06:05:41 +0000183 Instruction *visitFCmpInst(FCmpInst &I);
184 Instruction *visitICmpInst(ICmpInst &I);
185 Instruction *visitICmpInstWithCastAndCast(ICmpInst &ICI);
Chris Lattner01deb9d2007-04-03 17:43:25 +0000186 Instruction *visitICmpInstWithInstAndIntCst(ICmpInst &ICI,
187 Instruction *LHS,
188 ConstantInt *RHS);
Chris Lattner562ef782007-06-20 23:46:26 +0000189 Instruction *FoldICmpDivCst(ICmpInst &ICI, BinaryOperator *DivI,
190 ConstantInt *DivRHS);
Chris Lattner2799baf2009-12-21 03:19:28 +0000191 Instruction *FoldICmpAddOpCst(ICmpInst &ICI, Value *X, ConstantInt *CI,
Chris Lattner3bf68152009-12-21 04:04:05 +0000192 ICmpInst::Predicate Pred, Value *TheAdd);
Dan Gohmand6aa02d2009-07-28 01:40:03 +0000193 Instruction *FoldGEPICmp(GEPOperator *GEPLHS, Value *RHS,
Reid Spencere4d87aa2006-12-23 06:05:41 +0000194 ICmpInst::Predicate Cond, Instruction &I);
Reid Spencerb83eb642006-10-20 07:07:24 +0000195 Instruction *FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
Reid Spencer832254e2007-02-02 02:16:23 +0000196 BinaryOperator &I);
Reid Spencer3da59db2006-11-27 01:05:10 +0000197 Instruction *commonCastTransforms(CastInst &CI);
198 Instruction *commonIntCastTransforms(CastInst &CI);
Chris Lattnerd3e28342007-04-27 17:44:50 +0000199 Instruction *commonPointerCastTransforms(CastInst &CI);
Chris Lattner8a9f5712007-04-11 06:57:46 +0000200 Instruction *visitTrunc(TruncInst &CI);
201 Instruction *visitZExt(ZExtInst &CI);
202 Instruction *visitSExt(SExtInst &CI);
Chris Lattnerb7530652008-01-27 05:29:54 +0000203 Instruction *visitFPTrunc(FPTruncInst &CI);
Reid Spencer3da59db2006-11-27 01:05:10 +0000204 Instruction *visitFPExt(CastInst &CI);
Chris Lattner0c7a9a02008-05-19 20:25:04 +0000205 Instruction *visitFPToUI(FPToUIInst &FI);
206 Instruction *visitFPToSI(FPToSIInst &FI);
Reid Spencer3da59db2006-11-27 01:05:10 +0000207 Instruction *visitUIToFP(CastInst &CI);
208 Instruction *visitSIToFP(CastInst &CI);
Chris Lattnera0e69692009-03-24 18:35:40 +0000209 Instruction *visitPtrToInt(PtrToIntInst &CI);
Chris Lattnerf9d9e452008-01-08 07:23:51 +0000210 Instruction *visitIntToPtr(IntToPtrInst &CI);
Chris Lattnerd3e28342007-04-27 17:44:50 +0000211 Instruction *visitBitCast(BitCastInst &CI);
Chris Lattner6fb5a4a2005-01-19 21:50:18 +0000212 Instruction *FoldSelectOpOp(SelectInst &SI, Instruction *TI,
213 Instruction *FI);
Evan Chengde621922009-03-31 20:42:45 +0000214 Instruction *FoldSelectIntoOp(SelectInst &SI, Value*, Value*);
Chris Lattnerb109b5c2009-12-21 06:03:05 +0000215 Instruction *FoldSPFofSPF(Instruction *Inner, SelectPatternFlavor SPF1,
216 Value *A, Value *B, Instruction &Outer,
217 SelectPatternFlavor SPF2, Value *C);
Dan Gohman81b28ce2008-09-16 18:46:06 +0000218 Instruction *visitSelectInst(SelectInst &SI);
219 Instruction *visitSelectInstWithICmp(SelectInst &SI, ICmpInst *ICI);
Chris Lattner9fe38862003-06-19 17:00:31 +0000220 Instruction *visitCallInst(CallInst &CI);
221 Instruction *visitInvokeInst(InvokeInst &II);
Chris Lattner9956c052009-11-08 19:23:30 +0000222
223 Instruction *SliceUpIllegalIntegerPHI(PHINode &PN);
Chris Lattner7e708292002-06-25 16:13:24 +0000224 Instruction *visitPHINode(PHINode &PN);
225 Instruction *visitGetElementPtrInst(GetElementPtrInst &GEP);
Victor Hernandez7b929da2009-10-23 21:09:37 +0000226 Instruction *visitAllocaInst(AllocaInst &AI);
Victor Hernandez66284e02009-10-24 04:23:03 +0000227 Instruction *visitFree(Instruction &FI);
Chris Lattner833b8a42003-06-26 05:06:25 +0000228 Instruction *visitLoadInst(LoadInst &LI);
Chris Lattner2f503e62005-01-31 05:36:43 +0000229 Instruction *visitStoreInst(StoreInst &SI);
Chris Lattnerc4d10eb2003-06-04 04:46:00 +0000230 Instruction *visitBranchInst(BranchInst &BI);
Chris Lattner46238a62004-07-03 00:26:11 +0000231 Instruction *visitSwitchInst(SwitchInst &SI);
Chris Lattnerefb47352006-04-15 01:39:45 +0000232 Instruction *visitInsertElementInst(InsertElementInst &IE);
Robert Bocchino1d7456d2006-01-13 22:48:06 +0000233 Instruction *visitExtractElementInst(ExtractElementInst &EI);
Chris Lattnera844fc4c2006-04-10 22:45:52 +0000234 Instruction *visitShuffleVectorInst(ShuffleVectorInst &SVI);
Matthijs Kooijmana9012ec2008-06-11 14:05:05 +0000235 Instruction *visitExtractValueInst(ExtractValueInst &EV);
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000236
237 // visitInstruction - Specify what to return for unhandled instructions...
Chris Lattner7e708292002-06-25 16:13:24 +0000238 Instruction *visitInstruction(Instruction &I) { return 0; }
Chris Lattner8b170942002-08-09 23:47:40 +0000239
Chris Lattner9fe38862003-06-19 17:00:31 +0000240 private:
Chris Lattnera44d8a22003-10-07 22:32:43 +0000241 Instruction *visitCallSite(CallSite CS);
Chris Lattner9fe38862003-06-19 17:00:31 +0000242 bool transformConstExprCastCall(CallSite CS);
Duncan Sandscdb6d922007-09-17 10:26:40 +0000243 Instruction *transformCallThroughTrampoline(CallSite CS);
Evan Chengb98a10e2008-03-24 00:21:34 +0000244 Instruction *transformZExtICmp(ICmpInst *ICI, Instruction &CI,
245 bool DoXform = true);
Chris Lattner3d28b1b2008-05-20 05:46:13 +0000246 bool WillNotOverflowSignedAdd(Value *LHS, Value *RHS);
Dale Johannesen4945c652009-03-03 21:26:39 +0000247 DbgDeclareInst *hasOneUsePlusDeclare(Value *V);
248
Chris Lattner9fe38862003-06-19 17:00:31 +0000249
Chris Lattner28977af2004-04-05 01:30:19 +0000250 public:
Chris Lattner8b170942002-08-09 23:47:40 +0000251 // InsertNewInstBefore - insert an instruction New before instruction Old
252 // in the program. Add the new instruction to the worklist.
253 //
Chris Lattner955f3312004-09-28 21:48:02 +0000254 Instruction *InsertNewInstBefore(Instruction *New, Instruction &Old) {
Chris Lattnere6f9a912002-08-23 18:32:43 +0000255 assert(New && New->getParent() == 0 &&
256 "New instruction already inserted into a basic block!");
Chris Lattner8b170942002-08-09 23:47:40 +0000257 BasicBlock *BB = Old.getParent();
258 BB->getInstList().insert(&Old, New); // Insert inst
Chris Lattner7a1e9242009-08-30 06:13:40 +0000259 Worklist.Add(New);
Chris Lattner4cb170c2004-02-23 06:38:22 +0000260 return New;
Chris Lattner8b170942002-08-09 23:47:40 +0000261 }
Chris Lattner6d0339d2008-01-13 22:23:22 +0000262
Chris Lattner8b170942002-08-09 23:47:40 +0000263 // ReplaceInstUsesWith - This method is to be used when an instruction is
264 // found to be dead, replacable with another preexisting expression. Here
265 // we add all uses of I to the worklist, replace all uses of I with the new
266 // value, then return I, so that the inst combiner will know that I was
267 // modified.
268 //
269 Instruction *ReplaceInstUsesWith(Instruction &I, Value *V) {
Chris Lattnere5ecdb52009-08-30 06:22:51 +0000270 Worklist.AddUsersToWorkList(I); // Add all modified instrs to worklist.
Chris Lattner7a1e9242009-08-30 06:13:40 +0000271
272 // If we are replacing the instruction with itself, this must be in a
273 // segment of unreachable code, so just clobber the instruction.
274 if (&I == V)
275 V = UndefValue::get(I.getType());
276
277 I.replaceAllUsesWith(V);
278 return &I;
Chris Lattner8b170942002-08-09 23:47:40 +0000279 }
Chris Lattner7bcc0e72004-02-28 05:22:00 +0000280
281 // EraseInstFromFunction - When dealing with an instruction that has side
282 // effects or produces a void value, we can't rely on DCE to delete the
283 // instruction. Instead, visit methods should return the value returned by
284 // this function.
285 Instruction *EraseInstFromFunction(Instruction &I) {
Victor Hernandez83d63912009-09-18 22:35:49 +0000286 DEBUG(errs() << "IC: ERASE " << I << '\n');
Chris Lattner931f8f32009-08-31 05:17:58 +0000287
Chris Lattner7bcc0e72004-02-28 05:22:00 +0000288 assert(I.use_empty() && "Cannot erase instruction that is used!");
Chris Lattner7a1e9242009-08-30 06:13:40 +0000289 // Make sure that we reprocess all operands now that we reduced their
290 // use counts.
Chris Lattner3c4e38e2009-08-30 06:27:41 +0000291 if (I.getNumOperands() < 8) {
292 for (User::op_iterator i = I.op_begin(), e = I.op_end(); i != e; ++i)
293 if (Instruction *Op = dyn_cast<Instruction>(*i))
294 Worklist.Add(Op);
295 }
Chris Lattner7a1e9242009-08-30 06:13:40 +0000296 Worklist.Remove(&I);
Chris Lattner954f66a2004-11-18 21:41:39 +0000297 I.eraseFromParent();
Chris Lattnerb0b822c2009-08-31 06:57:37 +0000298 MadeIRChange = true;
Chris Lattner7bcc0e72004-02-28 05:22:00 +0000299 return 0; // Don't do anything with FI
300 }
Chris Lattner173234a2008-06-02 01:18:21 +0000301
302 void ComputeMaskedBits(Value *V, const APInt &Mask, APInt &KnownZero,
303 APInt &KnownOne, unsigned Depth = 0) const {
304 return llvm::ComputeMaskedBits(V, Mask, KnownZero, KnownOne, TD, Depth);
305 }
306
307 bool MaskedValueIsZero(Value *V, const APInt &Mask,
308 unsigned Depth = 0) const {
309 return llvm::MaskedValueIsZero(V, Mask, TD, Depth);
310 }
311 unsigned ComputeNumSignBits(Value *Op, unsigned Depth = 0) const {
312 return llvm::ComputeNumSignBits(Op, TD, Depth);
313 }
Chris Lattner7bcc0e72004-02-28 05:22:00 +0000314
Chris Lattneraa9c1f12003-08-13 20:16:26 +0000315 private:
Chris Lattner24c8e382003-07-24 17:35:25 +0000316
Reid Spencere4d87aa2006-12-23 06:05:41 +0000317 /// SimplifyCommutative - This performs a few simplifications for
318 /// commutative operators.
Chris Lattnerc8802d22003-03-11 00:12:48 +0000319 bool SimplifyCommutative(BinaryOperator &I);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +0000320
Chris Lattner886ab6c2009-01-31 08:15:18 +0000321 /// SimplifyDemandedUseBits - Attempts to replace V with a simpler value
322 /// based on the demanded bits.
323 Value *SimplifyDemandedUseBits(Value *V, APInt DemandedMask,
324 APInt& KnownZero, APInt& KnownOne,
325 unsigned Depth);
326 bool SimplifyDemandedBits(Use &U, APInt DemandedMask,
Reid Spencer8cb68342007-03-12 17:25:59 +0000327 APInt& KnownZero, APInt& KnownOne,
Chris Lattner886ab6c2009-01-31 08:15:18 +0000328 unsigned Depth=0);
329
330 /// SimplifyDemandedInstructionBits - Inst is an integer instruction that
331 /// SimplifyDemandedBits knows about. See if the instruction has any
332 /// properties that allow us to simplify its operands.
333 bool SimplifyDemandedInstructionBits(Instruction &Inst);
334
Evan Cheng388df622009-02-03 10:05:09 +0000335 Value *SimplifyDemandedVectorElts(Value *V, APInt DemandedElts,
336 APInt& UndefElts, unsigned Depth = 0);
Chris Lattner867b99f2006-10-05 06:55:50 +0000337
Chris Lattner5d1704d2009-09-27 19:57:57 +0000338 // FoldOpIntoPhi - Given a binary operator, cast instruction, or select
339 // which has a PHI node as operand #0, see if we can fold the instruction
340 // into the PHI (which is only possible if all operands to the PHI are
341 // constants).
Chris Lattner213cd612009-09-27 20:46:36 +0000342 //
343 // If AllowAggressive is true, FoldOpIntoPhi will allow certain transforms
344 // that would normally be unprofitable because they strongly encourage jump
345 // threading.
346 Instruction *FoldOpIntoPhi(Instruction &I, bool AllowAggressive = false);
Chris Lattner4e998b22004-09-29 05:07:12 +0000347
Chris Lattnerbac32862004-11-14 19:13:23 +0000348 // FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
349 // operator and they all are only used by the PHI, PHI together their
350 // inputs, and do the operation once, to the result of the PHI.
351 Instruction *FoldPHIArgOpIntoPHI(PHINode &PN);
Chris Lattner7da52b22006-11-01 04:51:18 +0000352 Instruction *FoldPHIArgBinOpIntoPHI(PHINode &PN);
Chris Lattner05f18922008-12-01 02:34:36 +0000353 Instruction *FoldPHIArgGEPIntoPHI(PHINode &PN);
Chris Lattner751a3622009-11-01 20:04:24 +0000354 Instruction *FoldPHIArgLoadIntoPHI(PHINode &PN);
Chris Lattner05f18922008-12-01 02:34:36 +0000355
Chris Lattner7da52b22006-11-01 04:51:18 +0000356
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +0000357 Instruction *OptAndOp(Instruction *Op, ConstantInt *OpRHS,
358 ConstantInt *AndRHS, BinaryOperator &TheAnd);
Chris Lattnerc8e77562005-09-18 04:24:45 +0000359
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +0000360 Value *FoldLogicalPlusAnd(Value *LHS, Value *RHS, ConstantInt *Mask,
Chris Lattnerc8e77562005-09-18 04:24:45 +0000361 bool isSub, Instruction &I);
Chris Lattnera96879a2004-09-29 17:40:11 +0000362 Instruction *InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
Reid Spencere4d87aa2006-12-23 06:05:41 +0000363 bool isSigned, bool Inside, Instruction &IB);
Victor Hernandez7b929da2009-10-23 21:09:37 +0000364 Instruction *PromoteCastOfAllocation(BitCastInst &CI, AllocaInst &AI);
Chris Lattnerafe91a52006-06-15 19:07:26 +0000365 Instruction *MatchBSwap(BinaryOperator &I);
Chris Lattner3284d1f2007-04-15 00:07:55 +0000366 bool SimplifyStoreAtEndOfBlock(StoreInst &SI);
Chris Lattnerf497b022008-01-13 23:50:23 +0000367 Instruction *SimplifyMemTransfer(MemIntrinsic *MI);
Chris Lattner69ea9d22008-04-30 06:39:11 +0000368 Instruction *SimplifyMemSet(MemSetInst *MI);
Chris Lattnerf497b022008-01-13 23:50:23 +0000369
Chris Lattnerafe91a52006-06-15 19:07:26 +0000370
Reid Spencerc55b2432006-12-13 18:21:21 +0000371 Value *EvaluateInDifferentType(Value *V, const Type *Ty, bool isSigned);
Dan Gohmaneee962e2008-04-10 18:43:06 +0000372
Dan Gohman6de29f82009-06-15 22:12:54 +0000373 bool CanEvaluateInDifferentType(Value *V, const Type *Ty,
Evan Cheng4e56ab22009-01-16 02:11:43 +0000374 unsigned CastOpc, int &NumCastsRemoved);
Dan Gohmaneee962e2008-04-10 18:43:06 +0000375 unsigned GetOrEnforceKnownAlignment(Value *V,
376 unsigned PrefAlign = 0);
Matthijs Kooijmana9012ec2008-06-11 14:05:05 +0000377
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000378 };
Chris Lattner873ff012009-08-30 05:55:36 +0000379} // end anonymous namespace
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000380
Dan Gohman844731a2008-05-13 00:00:25 +0000381char InstCombiner::ID = 0;
382static RegisterPass<InstCombiner>
383X("instcombine", "Combine redundant instructions");
384
Chris Lattner4f98c562003-03-10 21:43:22 +0000385// getComplexity: Assign a complexity or rank value to LLVM Values...
Chris Lattnere87597f2004-10-16 18:11:37 +0000386// 0 -> undef, 1 -> Const, 2 -> Other, 3 -> Arg, 3 -> Unary, 4 -> OtherInst
Dan Gohman14ef4f02009-08-29 23:39:38 +0000387static unsigned getComplexity(Value *V) {
Chris Lattner4f98c562003-03-10 21:43:22 +0000388 if (isa<Instruction>(V)) {
Owen Andersonfa82b6e2009-07-13 22:18:28 +0000389 if (BinaryOperator::isNeg(V) ||
390 BinaryOperator::isFNeg(V) ||
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000391 BinaryOperator::isNot(V))
Chris Lattnere87597f2004-10-16 18:11:37 +0000392 return 3;
393 return 4;
Chris Lattner4f98c562003-03-10 21:43:22 +0000394 }
Chris Lattnere87597f2004-10-16 18:11:37 +0000395 if (isa<Argument>(V)) return 3;
396 return isa<Constant>(V) ? (isa<UndefValue>(V) ? 0 : 1) : 2;
Chris Lattner4f98c562003-03-10 21:43:22 +0000397}
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000398
Chris Lattnerc8802d22003-03-11 00:12:48 +0000399// isOnlyUse - Return true if this instruction will be deleted if we stop using
400// it.
401static bool isOnlyUse(Value *V) {
Chris Lattnerfd059242003-10-15 16:48:29 +0000402 return V->hasOneUse() || isa<Constant>(V);
Chris Lattnerc8802d22003-03-11 00:12:48 +0000403}
404
Chris Lattner4cb170c2004-02-23 06:38:22 +0000405// getPromotedType - Return the specified type promoted as it would be to pass
406// though a va_arg area...
407static const Type *getPromotedType(const Type *Ty) {
Reid Spencera54b7cb2007-01-12 07:05:14 +0000408 if (const IntegerType* ITy = dyn_cast<IntegerType>(Ty)) {
409 if (ITy->getBitWidth() < 32)
Owen Anderson1d0be152009-08-13 21:58:54 +0000410 return Type::getInt32Ty(Ty->getContext());
Chris Lattner2b7e0ad2007-05-23 01:17:04 +0000411 }
Reid Spencera54b7cb2007-01-12 07:05:14 +0000412 return Ty;
Chris Lattner4cb170c2004-02-23 06:38:22 +0000413}
414
Chris Lattnerc22d4d12009-11-10 07:23:37 +0000415/// ShouldChangeType - Return true if it is desirable to convert a computation
416/// from 'From' to 'To'. We don't want to convert from a legal to an illegal
417/// type for example, or from a smaller to a larger illegal type.
418static bool ShouldChangeType(const Type *From, const Type *To,
419 const TargetData *TD) {
420 assert(isa<IntegerType>(From) && isa<IntegerType>(To));
421
422 // If we don't have TD, we don't know if the source/dest are legal.
423 if (!TD) return false;
424
425 unsigned FromWidth = From->getPrimitiveSizeInBits();
426 unsigned ToWidth = To->getPrimitiveSizeInBits();
427 bool FromLegal = TD->isLegalInteger(FromWidth);
428 bool ToLegal = TD->isLegalInteger(ToWidth);
429
430 // If this is a legal integer from type, and the result would be an illegal
431 // type, don't do the transformation.
432 if (FromLegal && !ToLegal)
433 return false;
434
435 // Otherwise, if both are illegal, do not increase the size of the result. We
436 // do allow things like i160 -> i64, but not i64 -> i160.
437 if (!FromLegal && !ToLegal && ToWidth > FromWidth)
438 return false;
439
440 return true;
441}
442
Matthijs Kooijman7e6d9b92008-10-13 15:17:01 +0000443/// getBitCastOperand - If the specified operand is a CastInst, a constant
444/// expression bitcast, or a GetElementPtrInst with all zero indices, return the
445/// operand value, otherwise return null.
Reid Spencer3da59db2006-11-27 01:05:10 +0000446static Value *getBitCastOperand(Value *V) {
Dan Gohman016de812009-07-17 23:55:56 +0000447 if (Operator *O = dyn_cast<Operator>(V)) {
448 if (O->getOpcode() == Instruction::BitCast)
449 return O->getOperand(0);
450 if (GEPOperator *GEP = dyn_cast<GEPOperator>(V))
451 if (GEP->hasAllZeroIndices())
452 return GEP->getPointerOperand();
Matthijs Kooijman7e6d9b92008-10-13 15:17:01 +0000453 }
Chris Lattnereed48272005-09-13 00:40:14 +0000454 return 0;
455}
456
Reid Spencer3da59db2006-11-27 01:05:10 +0000457/// This function is a wrapper around CastInst::isEliminableCastPair. It
458/// simply extracts arguments and returns what that function returns.
Reid Spencer3da59db2006-11-27 01:05:10 +0000459static Instruction::CastOps
460isEliminableCastPair(
461 const CastInst *CI, ///< The first cast instruction
462 unsigned opcode, ///< The opcode of the second cast instruction
463 const Type *DstTy, ///< The target type for the second cast instruction
464 TargetData *TD ///< The target data for pointer size
465) {
Dan Gohmance9fe9f2009-07-21 23:21:54 +0000466
Reid Spencer3da59db2006-11-27 01:05:10 +0000467 const Type *SrcTy = CI->getOperand(0)->getType(); // A from above
468 const Type *MidTy = CI->getType(); // B from above
Chris Lattner33a61132006-05-06 09:00:16 +0000469
Reid Spencer3da59db2006-11-27 01:05:10 +0000470 // Get the opcodes of the two Cast instructions
471 Instruction::CastOps firstOp = Instruction::CastOps(CI->getOpcode());
472 Instruction::CastOps secondOp = Instruction::CastOps(opcode);
Chris Lattner33a61132006-05-06 09:00:16 +0000473
Chris Lattnera0e69692009-03-24 18:35:40 +0000474 unsigned Res = CastInst::isEliminableCastPair(firstOp, secondOp, SrcTy, MidTy,
Dan Gohmance9fe9f2009-07-21 23:21:54 +0000475 DstTy,
Owen Anderson1d0be152009-08-13 21:58:54 +0000476 TD ? TD->getIntPtrType(CI->getContext()) : 0);
Chris Lattnera0e69692009-03-24 18:35:40 +0000477
478 // We don't want to form an inttoptr or ptrtoint that converts to an integer
479 // type that differs from the pointer size.
Owen Anderson1d0be152009-08-13 21:58:54 +0000480 if ((Res == Instruction::IntToPtr &&
Dan Gohman5e9bb732009-08-19 23:38:22 +0000481 (!TD || SrcTy != TD->getIntPtrType(CI->getContext()))) ||
Owen Anderson1d0be152009-08-13 21:58:54 +0000482 (Res == Instruction::PtrToInt &&
Dan Gohman5e9bb732009-08-19 23:38:22 +0000483 (!TD || DstTy != TD->getIntPtrType(CI->getContext()))))
Chris Lattnera0e69692009-03-24 18:35:40 +0000484 Res = 0;
485
486 return Instruction::CastOps(Res);
Chris Lattner33a61132006-05-06 09:00:16 +0000487}
488
489/// ValueRequiresCast - Return true if the cast from "V to Ty" actually results
490/// in any code being generated. It does not require codegen if V is simple
491/// enough or if the cast can be folded into other casts.
Reid Spencere4d87aa2006-12-23 06:05:41 +0000492static bool ValueRequiresCast(Instruction::CastOps opcode, const Value *V,
493 const Type *Ty, TargetData *TD) {
Chris Lattner33a61132006-05-06 09:00:16 +0000494 if (V->getType() == Ty || isa<Constant>(V)) return false;
495
Chris Lattner01575b72006-05-25 23:24:33 +0000496 // If this is another cast that can be eliminated, it isn't codegen either.
Chris Lattner33a61132006-05-06 09:00:16 +0000497 if (const CastInst *CI = dyn_cast<CastInst>(V))
Dan Gohmance9fe9f2009-07-21 23:21:54 +0000498 if (isEliminableCastPair(CI, opcode, Ty, TD))
Chris Lattner33a61132006-05-06 09:00:16 +0000499 return false;
500 return true;
501}
502
Chris Lattner4f98c562003-03-10 21:43:22 +0000503// SimplifyCommutative - This performs a few simplifications for commutative
504// operators:
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000505//
Chris Lattner4f98c562003-03-10 21:43:22 +0000506// 1. Order operands such that they are listed from right (least complex) to
507// left (most complex). This puts constants before unary operators before
508// binary operators.
509//
Chris Lattnerc8802d22003-03-11 00:12:48 +0000510// 2. Transform: (op (op V, C1), C2) ==> (op V, (op C1, C2))
511// 3. Transform: (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
Chris Lattner4f98c562003-03-10 21:43:22 +0000512//
Chris Lattnerc8802d22003-03-11 00:12:48 +0000513bool InstCombiner::SimplifyCommutative(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +0000514 bool Changed = false;
Dan Gohman14ef4f02009-08-29 23:39:38 +0000515 if (getComplexity(I.getOperand(0)) < getComplexity(I.getOperand(1)))
Chris Lattner4f98c562003-03-10 21:43:22 +0000516 Changed = !I.swapOperands();
Misha Brukmanfd939082005-04-21 23:48:37 +0000517
Chris Lattner4f98c562003-03-10 21:43:22 +0000518 if (!I.isAssociative()) return Changed;
519 Instruction::BinaryOps Opcode = I.getOpcode();
Chris Lattnerc8802d22003-03-11 00:12:48 +0000520 if (BinaryOperator *Op = dyn_cast<BinaryOperator>(I.getOperand(0)))
521 if (Op->getOpcode() == Opcode && isa<Constant>(Op->getOperand(1))) {
522 if (isa<Constant>(I.getOperand(1))) {
Owen Andersonbaf3c402009-07-29 18:55:55 +0000523 Constant *Folded = ConstantExpr::get(I.getOpcode(),
Chris Lattner2a9c8472003-05-27 16:40:51 +0000524 cast<Constant>(I.getOperand(1)),
525 cast<Constant>(Op->getOperand(1)));
Chris Lattnerc8802d22003-03-11 00:12:48 +0000526 I.setOperand(0, Op->getOperand(0));
527 I.setOperand(1, Folded);
528 return true;
529 } else if (BinaryOperator *Op1=dyn_cast<BinaryOperator>(I.getOperand(1)))
530 if (Op1->getOpcode() == Opcode && isa<Constant>(Op1->getOperand(1)) &&
531 isOnlyUse(Op) && isOnlyUse(Op1)) {
532 Constant *C1 = cast<Constant>(Op->getOperand(1));
533 Constant *C2 = cast<Constant>(Op1->getOperand(1));
534
535 // Fold (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
Owen Andersonbaf3c402009-07-29 18:55:55 +0000536 Constant *Folded = ConstantExpr::get(I.getOpcode(), C1, C2);
Gabor Greif7cbd8a32008-05-16 19:29:10 +0000537 Instruction *New = BinaryOperator::Create(Opcode, Op->getOperand(0),
Chris Lattnerc8802d22003-03-11 00:12:48 +0000538 Op1->getOperand(0),
539 Op1->getName(), &I);
Chris Lattner7a1e9242009-08-30 06:13:40 +0000540 Worklist.Add(New);
Chris Lattnerc8802d22003-03-11 00:12:48 +0000541 I.setOperand(0, New);
542 I.setOperand(1, Folded);
543 return true;
Misha Brukmanfd939082005-04-21 23:48:37 +0000544 }
Chris Lattner4f98c562003-03-10 21:43:22 +0000545 }
Chris Lattner4f98c562003-03-10 21:43:22 +0000546 return Changed;
Chris Lattnerdd841ae2002-04-18 17:39:14 +0000547}
Chris Lattner8a2a3112001-12-14 16:52:21 +0000548
Chris Lattner8d969642003-03-10 23:06:50 +0000549// dyn_castNegVal - Given a 'sub' instruction, return the RHS of the instruction
550// if the LHS is a constant zero (which is the 'negate' form).
Chris Lattnerb35dde12002-05-06 16:49:18 +0000551//
Dan Gohman186a6362009-08-12 16:04:34 +0000552static inline Value *dyn_castNegVal(Value *V) {
Owen Andersonfa82b6e2009-07-13 22:18:28 +0000553 if (BinaryOperator::isNeg(V))
Chris Lattnera1df33c2005-04-24 07:30:14 +0000554 return BinaryOperator::getNegArgument(V);
Chris Lattner8d969642003-03-10 23:06:50 +0000555
Chris Lattner0ce85802004-12-14 20:08:06 +0000556 // Constants can be considered to be negated values if they can be folded.
557 if (ConstantInt *C = dyn_cast<ConstantInt>(V))
Owen Andersonbaf3c402009-07-29 18:55:55 +0000558 return ConstantExpr::getNeg(C);
Nick Lewycky18b3da62008-05-23 04:54:45 +0000559
560 if (ConstantVector *C = dyn_cast<ConstantVector>(V))
561 if (C->getType()->getElementType()->isInteger())
Owen Andersonbaf3c402009-07-29 18:55:55 +0000562 return ConstantExpr::getNeg(C);
Nick Lewycky18b3da62008-05-23 04:54:45 +0000563
Chris Lattner8d969642003-03-10 23:06:50 +0000564 return 0;
Chris Lattnerb35dde12002-05-06 16:49:18 +0000565}
566
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000567// dyn_castFNegVal - Given a 'fsub' instruction, return the RHS of the
568// instruction if the LHS is a constant negative zero (which is the 'negate'
569// form).
570//
Dan Gohman186a6362009-08-12 16:04:34 +0000571static inline Value *dyn_castFNegVal(Value *V) {
Owen Andersonfa82b6e2009-07-13 22:18:28 +0000572 if (BinaryOperator::isFNeg(V))
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000573 return BinaryOperator::getFNegArgument(V);
574
575 // Constants can be considered to be negated values if they can be folded.
576 if (ConstantFP *C = dyn_cast<ConstantFP>(V))
Owen Andersonbaf3c402009-07-29 18:55:55 +0000577 return ConstantExpr::getFNeg(C);
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000578
579 if (ConstantVector *C = dyn_cast<ConstantVector>(V))
580 if (C->getType()->getElementType()->isFloatingPoint())
Owen Andersonbaf3c402009-07-29 18:55:55 +0000581 return ConstantExpr::getFNeg(C);
Dan Gohmanae3a0be2009-06-04 22:49:04 +0000582
583 return 0;
584}
585
Chris Lattnerb109b5c2009-12-21 06:03:05 +0000586/// MatchSelectPattern - Pattern match integer [SU]MIN, [SU]MAX, and ABS idioms,
587/// returning the kind and providing the out parameter results if we
588/// successfully match.
589static SelectPatternFlavor
590MatchSelectPattern(Value *V, Value *&LHS, Value *&RHS) {
591 SelectInst *SI = dyn_cast<SelectInst>(V);
592 if (SI == 0) return SPF_UNKNOWN;
593
594 ICmpInst *ICI = dyn_cast<ICmpInst>(SI->getCondition());
595 if (ICI == 0) return SPF_UNKNOWN;
596
597 LHS = ICI->getOperand(0);
598 RHS = ICI->getOperand(1);
599
600 // (icmp X, Y) ? X : Y
601 if (SI->getTrueValue() == ICI->getOperand(0) &&
602 SI->getFalseValue() == ICI->getOperand(1)) {
603 switch (ICI->getPredicate()) {
604 default: return SPF_UNKNOWN; // Equality.
605 case ICmpInst::ICMP_UGT:
606 case ICmpInst::ICMP_UGE: return SPF_UMAX;
607 case ICmpInst::ICMP_SGT:
608 case ICmpInst::ICMP_SGE: return SPF_SMAX;
609 case ICmpInst::ICMP_ULT:
610 case ICmpInst::ICMP_ULE: return SPF_UMIN;
611 case ICmpInst::ICMP_SLT:
612 case ICmpInst::ICMP_SLE: return SPF_SMIN;
613 }
614 }
615
616 // (icmp X, Y) ? Y : X
617 if (SI->getTrueValue() == ICI->getOperand(1) &&
618 SI->getFalseValue() == ICI->getOperand(0)) {
619 switch (ICI->getPredicate()) {
620 default: return SPF_UNKNOWN; // Equality.
621 case ICmpInst::ICMP_UGT:
622 case ICmpInst::ICMP_UGE: return SPF_UMIN;
623 case ICmpInst::ICMP_SGT:
624 case ICmpInst::ICMP_SGE: return SPF_SMIN;
625 case ICmpInst::ICMP_ULT:
626 case ICmpInst::ICMP_ULE: return SPF_UMAX;
627 case ICmpInst::ICMP_SLT:
628 case ICmpInst::ICMP_SLE: return SPF_SMAX;
629 }
630 }
631
632 // TODO: (X > 4) ? X : 5 --> (X >= 5) ? X : 5 --> MAX(X, 5)
633
634 return SPF_UNKNOWN;
635}
636
Chris Lattner48b59ec2009-10-26 15:40:07 +0000637/// isFreeToInvert - Return true if the specified value is free to invert (apply
638/// ~ to). This happens in cases where the ~ can be eliminated.
639static inline bool isFreeToInvert(Value *V) {
640 // ~(~(X)) -> X.
Evan Cheng85def162009-10-26 03:51:32 +0000641 if (BinaryOperator::isNot(V))
Chris Lattner48b59ec2009-10-26 15:40:07 +0000642 return true;
643
644 // Constants can be considered to be not'ed values.
645 if (isa<ConstantInt>(V))
646 return true;
647
648 // Compares can be inverted if they have a single use.
649 if (CmpInst *CI = dyn_cast<CmpInst>(V))
650 return CI->hasOneUse();
651
652 return false;
653}
654
655static inline Value *dyn_castNotVal(Value *V) {
656 // If this is not(not(x)) don't return that this is a not: we want the two
657 // not's to be folded first.
658 if (BinaryOperator::isNot(V)) {
659 Value *Operand = BinaryOperator::getNotArgument(V);
660 if (!isFreeToInvert(Operand))
661 return Operand;
662 }
Chris Lattner8d969642003-03-10 23:06:50 +0000663
664 // Constants can be considered to be not'ed values...
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +0000665 if (ConstantInt *C = dyn_cast<ConstantInt>(V))
Dan Gohman186a6362009-08-12 16:04:34 +0000666 return ConstantInt::get(C->getType(), ~C->getValue());
Chris Lattner8d969642003-03-10 23:06:50 +0000667 return 0;
668}
669
Chris Lattner48b59ec2009-10-26 15:40:07 +0000670
671
Chris Lattnerc8802d22003-03-11 00:12:48 +0000672// dyn_castFoldableMul - If this value is a multiply that can be folded into
673// other computations (because it has a constant operand), return the
Chris Lattner50af16a2004-11-13 19:50:12 +0000674// non-constant operand of the multiply, and set CST to point to the multiplier.
675// Otherwise, return null.
Chris Lattnerc8802d22003-03-11 00:12:48 +0000676//
Dan Gohman186a6362009-08-12 16:04:34 +0000677static inline Value *dyn_castFoldableMul(Value *V, ConstantInt *&CST) {
Chris Lattner42a75512007-01-15 02:27:26 +0000678 if (V->hasOneUse() && V->getType()->isInteger())
Chris Lattner50af16a2004-11-13 19:50:12 +0000679 if (Instruction *I = dyn_cast<Instruction>(V)) {
Chris Lattnerc8802d22003-03-11 00:12:48 +0000680 if (I->getOpcode() == Instruction::Mul)
Chris Lattner50e60c72004-11-15 05:54:07 +0000681 if ((CST = dyn_cast<ConstantInt>(I->getOperand(1))))
Chris Lattnerc8802d22003-03-11 00:12:48 +0000682 return I->getOperand(0);
Chris Lattner50af16a2004-11-13 19:50:12 +0000683 if (I->getOpcode() == Instruction::Shl)
Chris Lattner50e60c72004-11-15 05:54:07 +0000684 if ((CST = dyn_cast<ConstantInt>(I->getOperand(1)))) {
Chris Lattner50af16a2004-11-13 19:50:12 +0000685 // The multiplier is really 1 << CST.
Zhou Sheng97b52c22007-03-29 01:57:21 +0000686 uint32_t BitWidth = cast<IntegerType>(V->getType())->getBitWidth();
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +0000687 uint32_t CSTVal = CST->getLimitedValue(BitWidth);
Dan Gohman186a6362009-08-12 16:04:34 +0000688 CST = ConstantInt::get(V->getType()->getContext(),
689 APInt(BitWidth, 1).shl(CSTVal));
Chris Lattner50af16a2004-11-13 19:50:12 +0000690 return I->getOperand(0);
691 }
692 }
Chris Lattnerc8802d22003-03-11 00:12:48 +0000693 return 0;
Chris Lattnera2881962003-02-18 19:28:33 +0000694}
Chris Lattneraf2930e2002-08-14 17:51:49 +0000695
Reid Spencer7177c3a2007-03-25 05:33:51 +0000696/// AddOne - Add one to a ConstantInt
Dan Gohman186a6362009-08-12 16:04:34 +0000697static Constant *AddOne(Constant *C) {
Owen Andersonbaf3c402009-07-29 18:55:55 +0000698 return ConstantExpr::getAdd(C,
Owen Andersoneed707b2009-07-24 23:12:02 +0000699 ConstantInt::get(C->getType(), 1));
Chris Lattner955f3312004-09-28 21:48:02 +0000700}
Reid Spencer7177c3a2007-03-25 05:33:51 +0000701/// SubOne - Subtract one from a ConstantInt
Dan Gohman186a6362009-08-12 16:04:34 +0000702static Constant *SubOne(ConstantInt *C) {
Owen Andersonbaf3c402009-07-29 18:55:55 +0000703 return ConstantExpr::getSub(C,
Owen Andersoneed707b2009-07-24 23:12:02 +0000704 ConstantInt::get(C->getType(), 1));
Chris Lattner955f3312004-09-28 21:48:02 +0000705}
Nick Lewyckye0cfecf2008-02-18 22:48:05 +0000706/// MultiplyOverflows - True if the multiply can not be expressed in an int
707/// this size.
Dan Gohman186a6362009-08-12 16:04:34 +0000708static bool MultiplyOverflows(ConstantInt *C1, ConstantInt *C2, bool sign) {
Nick Lewyckye0cfecf2008-02-18 22:48:05 +0000709 uint32_t W = C1->getBitWidth();
710 APInt LHSExt = C1->getValue(), RHSExt = C2->getValue();
711 if (sign) {
712 LHSExt.sext(W * 2);
713 RHSExt.sext(W * 2);
714 } else {
715 LHSExt.zext(W * 2);
716 RHSExt.zext(W * 2);
717 }
718
719 APInt MulExt = LHSExt * RHSExt;
720
Chris Lattnerb109b5c2009-12-21 06:03:05 +0000721 if (!sign)
Nick Lewyckye0cfecf2008-02-18 22:48:05 +0000722 return MulExt.ugt(APInt::getLowBitsSet(W * 2, W));
Chris Lattnerb109b5c2009-12-21 06:03:05 +0000723
724 APInt Min = APInt::getSignedMinValue(W).sext(W * 2);
725 APInt Max = APInt::getSignedMaxValue(W).sext(W * 2);
726 return MulExt.slt(Min) || MulExt.sgt(Max);
Nick Lewyckye0cfecf2008-02-18 22:48:05 +0000727}
Chris Lattner955f3312004-09-28 21:48:02 +0000728
Reid Spencere7816b52007-03-08 01:52:58 +0000729
Chris Lattner255d8912006-02-11 09:31:47 +0000730/// ShrinkDemandedConstant - Check to see if the specified operand of the
731/// specified instruction is a constant integer. If so, check to see if there
732/// are any bits set in the constant that are not demanded. If so, shrink the
733/// constant and return true.
734static bool ShrinkDemandedConstant(Instruction *I, unsigned OpNo,
Dan Gohman186a6362009-08-12 16:04:34 +0000735 APInt Demanded) {
Reid Spencer6b79e2d2007-03-12 17:15:10 +0000736 assert(I && "No instruction?");
737 assert(OpNo < I->getNumOperands() && "Operand index too large");
738
739 // If the operand is not a constant integer, nothing to do.
740 ConstantInt *OpC = dyn_cast<ConstantInt>(I->getOperand(OpNo));
741 if (!OpC) return false;
742
743 // If there are no bits set that aren't demanded, nothing to do.
744 Demanded.zextOrTrunc(OpC->getValue().getBitWidth());
745 if ((~Demanded & OpC->getValue()) == 0)
746 return false;
747
748 // This instruction is producing bits that are not demanded. Shrink the RHS.
749 Demanded &= OpC->getValue();
Dan Gohman186a6362009-08-12 16:04:34 +0000750 I->setOperand(OpNo, ConstantInt::get(OpC->getType(), Demanded));
Reid Spencer6b79e2d2007-03-12 17:15:10 +0000751 return true;
752}
753
Chris Lattnerbf5d8a82006-02-12 02:07:56 +0000754// ComputeSignedMinMaxValuesFromKnownBits - Given a signed integer type and a
755// set of known zero and one bits, compute the maximum and minimum values that
756// could have the specified known zero and known one bits, returning them in
757// min/max.
Dan Gohman1c8491e2009-04-25 17:12:48 +0000758static void ComputeSignedMinMaxValuesFromKnownBits(const APInt& KnownZero,
Reid Spencer0460fb32007-03-22 20:36:03 +0000759 const APInt& KnownOne,
760 APInt& Min, APInt& Max) {
Dan Gohman1c8491e2009-04-25 17:12:48 +0000761 assert(KnownZero.getBitWidth() == KnownOne.getBitWidth() &&
762 KnownZero.getBitWidth() == Min.getBitWidth() &&
763 KnownZero.getBitWidth() == Max.getBitWidth() &&
764 "KnownZero, KnownOne and Min, Max must have equal bitwidth.");
Reid Spencer2f549172007-03-25 04:26:16 +0000765 APInt UnknownBits = ~(KnownZero|KnownOne);
Chris Lattnerbf5d8a82006-02-12 02:07:56 +0000766
Chris Lattnerbf5d8a82006-02-12 02:07:56 +0000767 // The minimum value is when all unknown bits are zeros, EXCEPT for the sign
768 // bit if it is unknown.
769 Min = KnownOne;
770 Max = KnownOne|UnknownBits;
771
Dan Gohman1c8491e2009-04-25 17:12:48 +0000772 if (UnknownBits.isNegative()) { // Sign bit is unknown
773 Min.set(Min.getBitWidth()-1);
774 Max.clear(Max.getBitWidth()-1);
Chris Lattnerbf5d8a82006-02-12 02:07:56 +0000775 }
Chris Lattnerbf5d8a82006-02-12 02:07:56 +0000776}
777
778// ComputeUnsignedMinMaxValuesFromKnownBits - Given an unsigned integer type and
779// a set of known zero and one bits, compute the maximum and minimum values that
780// could have the specified known zero and known one bits, returning them in
781// min/max.
Dan Gohman1c8491e2009-04-25 17:12:48 +0000782static void ComputeUnsignedMinMaxValuesFromKnownBits(const APInt &KnownZero,
Chris Lattnera9ff5eb2007-08-05 08:47:58 +0000783 const APInt &KnownOne,
784 APInt &Min, APInt &Max) {
Dan Gohman1c8491e2009-04-25 17:12:48 +0000785 assert(KnownZero.getBitWidth() == KnownOne.getBitWidth() &&
786 KnownZero.getBitWidth() == Min.getBitWidth() &&
787 KnownZero.getBitWidth() == Max.getBitWidth() &&
Reid Spencer0460fb32007-03-22 20:36:03 +0000788 "Ty, KnownZero, KnownOne and Min, Max must have equal bitwidth.");
Reid Spencer2f549172007-03-25 04:26:16 +0000789 APInt UnknownBits = ~(KnownZero|KnownOne);
Chris Lattnerbf5d8a82006-02-12 02:07:56 +0000790
791 // The minimum value is when the unknown bits are all zeros.
792 Min = KnownOne;
793 // The maximum value is when the unknown bits are all ones.
794 Max = KnownOne|UnknownBits;
795}
Chris Lattner255d8912006-02-11 09:31:47 +0000796
Chris Lattner886ab6c2009-01-31 08:15:18 +0000797/// SimplifyDemandedInstructionBits - Inst is an integer instruction that
798/// SimplifyDemandedBits knows about. See if the instruction has any
799/// properties that allow us to simplify its operands.
800bool InstCombiner::SimplifyDemandedInstructionBits(Instruction &Inst) {
Dan Gohman6de29f82009-06-15 22:12:54 +0000801 unsigned BitWidth = Inst.getType()->getScalarSizeInBits();
Chris Lattner886ab6c2009-01-31 08:15:18 +0000802 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
803 APInt DemandedMask(APInt::getAllOnesValue(BitWidth));
804
805 Value *V = SimplifyDemandedUseBits(&Inst, DemandedMask,
806 KnownZero, KnownOne, 0);
807 if (V == 0) return false;
808 if (V == &Inst) return true;
809 ReplaceInstUsesWith(Inst, V);
810 return true;
811}
812
813/// SimplifyDemandedBits - This form of SimplifyDemandedBits simplifies the
814/// specified instruction operand if possible, updating it in place. It returns
815/// true if it made any change and false otherwise.
816bool InstCombiner::SimplifyDemandedBits(Use &U, APInt DemandedMask,
817 APInt &KnownZero, APInt &KnownOne,
818 unsigned Depth) {
819 Value *NewVal = SimplifyDemandedUseBits(U.get(), DemandedMask,
820 KnownZero, KnownOne, Depth);
821 if (NewVal == 0) return false;
Dan Gohmane41a1152009-10-05 16:31:55 +0000822 U = NewVal;
Chris Lattner886ab6c2009-01-31 08:15:18 +0000823 return true;
824}
825
826
827/// SimplifyDemandedUseBits - This function attempts to replace V with a simpler
828/// value based on the demanded bits. When this function is called, it is known
Reid Spencer8cb68342007-03-12 17:25:59 +0000829/// that only the bits set in DemandedMask of the result of V are ever used
830/// downstream. Consequently, depending on the mask and V, it may be possible
831/// to replace V with a constant or one of its operands. In such cases, this
832/// function does the replacement and returns true. In all other cases, it
833/// returns false after analyzing the expression and setting KnownOne and known
Chris Lattner886ab6c2009-01-31 08:15:18 +0000834/// to be one in the expression. KnownZero contains all the bits that are known
Reid Spencer8cb68342007-03-12 17:25:59 +0000835/// to be zero in the expression. These are provided to potentially allow the
836/// caller (which might recursively be SimplifyDemandedBits itself) to simplify
837/// the expression. KnownOne and KnownZero always follow the invariant that
838/// KnownOne & KnownZero == 0. That is, a bit can't be both 1 and 0. Note that
839/// the bits in KnownOne and KnownZero may only be accurate for those bits set
840/// in DemandedMask. Note also that the bitwidth of V, DemandedMask, KnownZero
841/// and KnownOne must all be the same.
Chris Lattner886ab6c2009-01-31 08:15:18 +0000842///
843/// This returns null if it did not change anything and it permits no
844/// simplification. This returns V itself if it did some simplification of V's
845/// operands based on the information about what bits are demanded. This returns
846/// some other non-null value if it found out that V is equal to another value
847/// in the context where the specified bits are demanded, but not for all users.
848Value *InstCombiner::SimplifyDemandedUseBits(Value *V, APInt DemandedMask,
849 APInt &KnownZero, APInt &KnownOne,
850 unsigned Depth) {
Reid Spencer8cb68342007-03-12 17:25:59 +0000851 assert(V != 0 && "Null pointer of Value???");
852 assert(Depth <= 6 && "Limit Search Depth");
853 uint32_t BitWidth = DemandedMask.getBitWidth();
Dan Gohman1c8491e2009-04-25 17:12:48 +0000854 const Type *VTy = V->getType();
855 assert((TD || !isa<PointerType>(VTy)) &&
856 "SimplifyDemandedBits needs to know bit widths!");
Dan Gohman6de29f82009-06-15 22:12:54 +0000857 assert((!TD || TD->getTypeSizeInBits(VTy->getScalarType()) == BitWidth) &&
858 (!VTy->isIntOrIntVector() ||
859 VTy->getScalarSizeInBits() == BitWidth) &&
Dan Gohman1c8491e2009-04-25 17:12:48 +0000860 KnownZero.getBitWidth() == BitWidth &&
Reid Spencer8cb68342007-03-12 17:25:59 +0000861 KnownOne.getBitWidth() == BitWidth &&
Dan Gohman6de29f82009-06-15 22:12:54 +0000862 "Value *V, DemandedMask, KnownZero and KnownOne "
863 "must have same BitWidth");
Reid Spencer8cb68342007-03-12 17:25:59 +0000864 if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
865 // We know all of the bits for a constant!
866 KnownOne = CI->getValue() & DemandedMask;
867 KnownZero = ~KnownOne & DemandedMask;
Chris Lattner886ab6c2009-01-31 08:15:18 +0000868 return 0;
Reid Spencer8cb68342007-03-12 17:25:59 +0000869 }
Dan Gohman1c8491e2009-04-25 17:12:48 +0000870 if (isa<ConstantPointerNull>(V)) {
871 // We know all of the bits for a constant!
872 KnownOne.clear();
873 KnownZero = DemandedMask;
874 return 0;
875 }
876
Chris Lattner08d2cc72009-01-31 07:26:06 +0000877 KnownZero.clear();
Zhou Sheng96704452007-03-14 03:21:24 +0000878 KnownOne.clear();
Chris Lattner886ab6c2009-01-31 08:15:18 +0000879 if (DemandedMask == 0) { // Not demanding any bits from V.
880 if (isa<UndefValue>(V))
881 return 0;
Owen Anderson9e9a0d52009-07-30 23:03:37 +0000882 return UndefValue::get(VTy);
Reid Spencer8cb68342007-03-12 17:25:59 +0000883 }
884
Chris Lattner4598c942009-01-31 08:24:16 +0000885 if (Depth == 6) // Limit search depth.
886 return 0;
887
Chris Lattnerd1b5e3f2009-01-31 08:40:03 +0000888 APInt LHSKnownZero(BitWidth, 0), LHSKnownOne(BitWidth, 0);
889 APInt &RHSKnownZero = KnownZero, &RHSKnownOne = KnownOne;
890
Dan Gohman1c8491e2009-04-25 17:12:48 +0000891 Instruction *I = dyn_cast<Instruction>(V);
892 if (!I) {
893 ComputeMaskedBits(V, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
894 return 0; // Only analyze instructions.
895 }
896
Chris Lattner4598c942009-01-31 08:24:16 +0000897 // If there are multiple uses of this value and we aren't at the root, then
898 // we can't do any simplifications of the operands, because DemandedMask
899 // only reflects the bits demanded by *one* of the users.
900 if (Depth != 0 && !I->hasOneUse()) {
Chris Lattnerd1b5e3f2009-01-31 08:40:03 +0000901 // Despite the fact that we can't simplify this instruction in all User's
902 // context, we can at least compute the knownzero/knownone bits, and we can
903 // do simplifications that apply to *just* the one user if we know that
904 // this instruction has a simpler value in that context.
905 if (I->getOpcode() == Instruction::And) {
906 // If either the LHS or the RHS are Zero, the result is zero.
907 ComputeMaskedBits(I->getOperand(1), DemandedMask,
908 RHSKnownZero, RHSKnownOne, Depth+1);
909 ComputeMaskedBits(I->getOperand(0), DemandedMask & ~RHSKnownZero,
910 LHSKnownZero, LHSKnownOne, Depth+1);
911
912 // If all of the demanded bits are known 1 on one side, return the other.
913 // These bits cannot contribute to the result of the 'and' in this
914 // context.
915 if ((DemandedMask & ~LHSKnownZero & RHSKnownOne) ==
916 (DemandedMask & ~LHSKnownZero))
917 return I->getOperand(0);
918 if ((DemandedMask & ~RHSKnownZero & LHSKnownOne) ==
919 (DemandedMask & ~RHSKnownZero))
920 return I->getOperand(1);
921
922 // If all of the demanded bits in the inputs are known zeros, return zero.
923 if ((DemandedMask & (RHSKnownZero|LHSKnownZero)) == DemandedMask)
Owen Andersona7235ea2009-07-31 20:28:14 +0000924 return Constant::getNullValue(VTy);
Chris Lattnerd1b5e3f2009-01-31 08:40:03 +0000925
926 } else if (I->getOpcode() == Instruction::Or) {
927 // We can simplify (X|Y) -> X or Y in the user's context if we know that
928 // only bits from X or Y are demanded.
929
930 // If either the LHS or the RHS are One, the result is One.
931 ComputeMaskedBits(I->getOperand(1), DemandedMask,
932 RHSKnownZero, RHSKnownOne, Depth+1);
933 ComputeMaskedBits(I->getOperand(0), DemandedMask & ~RHSKnownOne,
934 LHSKnownZero, LHSKnownOne, Depth+1);
935
936 // If all of the demanded bits are known zero on one side, return the
937 // other. These bits cannot contribute to the result of the 'or' in this
938 // context.
939 if ((DemandedMask & ~LHSKnownOne & RHSKnownZero) ==
940 (DemandedMask & ~LHSKnownOne))
941 return I->getOperand(0);
942 if ((DemandedMask & ~RHSKnownOne & LHSKnownZero) ==
943 (DemandedMask & ~RHSKnownOne))
944 return I->getOperand(1);
945
946 // If all of the potentially set bits on one side are known to be set on
947 // the other side, just use the 'other' side.
948 if ((DemandedMask & (~RHSKnownZero) & LHSKnownOne) ==
949 (DemandedMask & (~RHSKnownZero)))
950 return I->getOperand(0);
951 if ((DemandedMask & (~LHSKnownZero) & RHSKnownOne) ==
952 (DemandedMask & (~LHSKnownZero)))
953 return I->getOperand(1);
954 }
955
Chris Lattner4598c942009-01-31 08:24:16 +0000956 // Compute the KnownZero/KnownOne bits to simplify things downstream.
957 ComputeMaskedBits(I, DemandedMask, KnownZero, KnownOne, Depth);
958 return 0;
959 }
960
961 // If this is the root being simplified, allow it to have multiple uses,
962 // just set the DemandedMask to all bits so that we can try to simplify the
963 // operands. This allows visitTruncInst (for example) to simplify the
964 // operand of a trunc without duplicating all the logic below.
965 if (Depth == 0 && !V->hasOneUse())
966 DemandedMask = APInt::getAllOnesValue(BitWidth);
967
Reid Spencer8cb68342007-03-12 17:25:59 +0000968 switch (I->getOpcode()) {
Dan Gohman23e8b712008-04-28 17:02:21 +0000969 default:
Chris Lattner886ab6c2009-01-31 08:15:18 +0000970 ComputeMaskedBits(I, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
Dan Gohman23e8b712008-04-28 17:02:21 +0000971 break;
Reid Spencer8cb68342007-03-12 17:25:59 +0000972 case Instruction::And:
973 // If either the LHS or the RHS are Zero, the result is zero.
Chris Lattner886ab6c2009-01-31 08:15:18 +0000974 if (SimplifyDemandedBits(I->getOperandUse(1), DemandedMask,
975 RHSKnownZero, RHSKnownOne, Depth+1) ||
976 SimplifyDemandedBits(I->getOperandUse(0), DemandedMask & ~RHSKnownZero,
Reid Spencer8cb68342007-03-12 17:25:59 +0000977 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +0000978 return I;
979 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
980 assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +0000981
982 // If all of the demanded bits are known 1 on one side, return the other.
983 // These bits cannot contribute to the result of the 'and'.
984 if ((DemandedMask & ~LHSKnownZero & RHSKnownOne) ==
985 (DemandedMask & ~LHSKnownZero))
Chris Lattner886ab6c2009-01-31 08:15:18 +0000986 return I->getOperand(0);
Reid Spencer8cb68342007-03-12 17:25:59 +0000987 if ((DemandedMask & ~RHSKnownZero & LHSKnownOne) ==
988 (DemandedMask & ~RHSKnownZero))
Chris Lattner886ab6c2009-01-31 08:15:18 +0000989 return I->getOperand(1);
Reid Spencer8cb68342007-03-12 17:25:59 +0000990
991 // If all of the demanded bits in the inputs are known zeros, return zero.
992 if ((DemandedMask & (RHSKnownZero|LHSKnownZero)) == DemandedMask)
Owen Andersona7235ea2009-07-31 20:28:14 +0000993 return Constant::getNullValue(VTy);
Reid Spencer8cb68342007-03-12 17:25:59 +0000994
995 // If the RHS is a constant, see if we can simplify it.
Dan Gohman186a6362009-08-12 16:04:34 +0000996 if (ShrinkDemandedConstant(I, 1, DemandedMask & ~LHSKnownZero))
Chris Lattner886ab6c2009-01-31 08:15:18 +0000997 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +0000998
999 // Output known-1 bits are only known if set in both the LHS & RHS.
1000 RHSKnownOne &= LHSKnownOne;
1001 // Output known-0 are known to be clear if zero in either the LHS | RHS.
1002 RHSKnownZero |= LHSKnownZero;
1003 break;
1004 case Instruction::Or:
1005 // If either the LHS or the RHS are One, the result is One.
Chris Lattner886ab6c2009-01-31 08:15:18 +00001006 if (SimplifyDemandedBits(I->getOperandUse(1), DemandedMask,
1007 RHSKnownZero, RHSKnownOne, Depth+1) ||
1008 SimplifyDemandedBits(I->getOperandUse(0), DemandedMask & ~RHSKnownOne,
Reid Spencer8cb68342007-03-12 17:25:59 +00001009 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001010 return I;
1011 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
1012 assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +00001013
1014 // If all of the demanded bits are known zero on one side, return the other.
1015 // These bits cannot contribute to the result of the 'or'.
1016 if ((DemandedMask & ~LHSKnownOne & RHSKnownZero) ==
1017 (DemandedMask & ~LHSKnownOne))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001018 return I->getOperand(0);
Reid Spencer8cb68342007-03-12 17:25:59 +00001019 if ((DemandedMask & ~RHSKnownOne & LHSKnownZero) ==
1020 (DemandedMask & ~RHSKnownOne))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001021 return I->getOperand(1);
Reid Spencer8cb68342007-03-12 17:25:59 +00001022
1023 // If all of the potentially set bits on one side are known to be set on
1024 // the other side, just use the 'other' side.
1025 if ((DemandedMask & (~RHSKnownZero) & LHSKnownOne) ==
1026 (DemandedMask & (~RHSKnownZero)))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001027 return I->getOperand(0);
Reid Spencer8cb68342007-03-12 17:25:59 +00001028 if ((DemandedMask & (~LHSKnownZero) & RHSKnownOne) ==
1029 (DemandedMask & (~LHSKnownZero)))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001030 return I->getOperand(1);
Reid Spencer8cb68342007-03-12 17:25:59 +00001031
1032 // If the RHS is a constant, see if we can simplify it.
Dan Gohman186a6362009-08-12 16:04:34 +00001033 if (ShrinkDemandedConstant(I, 1, DemandedMask))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001034 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +00001035
1036 // Output known-0 bits are only known if clear in both the LHS & RHS.
1037 RHSKnownZero &= LHSKnownZero;
1038 // Output known-1 are known to be set if set in either the LHS | RHS.
1039 RHSKnownOne |= LHSKnownOne;
1040 break;
1041 case Instruction::Xor: {
Chris Lattner886ab6c2009-01-31 08:15:18 +00001042 if (SimplifyDemandedBits(I->getOperandUse(1), DemandedMask,
1043 RHSKnownZero, RHSKnownOne, Depth+1) ||
1044 SimplifyDemandedBits(I->getOperandUse(0), DemandedMask,
Reid Spencer8cb68342007-03-12 17:25:59 +00001045 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001046 return I;
1047 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
1048 assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +00001049
1050 // If all of the demanded bits are known zero on one side, return the other.
1051 // These bits cannot contribute to the result of the 'xor'.
1052 if ((DemandedMask & RHSKnownZero) == DemandedMask)
Chris Lattner886ab6c2009-01-31 08:15:18 +00001053 return I->getOperand(0);
Reid Spencer8cb68342007-03-12 17:25:59 +00001054 if ((DemandedMask & LHSKnownZero) == DemandedMask)
Chris Lattner886ab6c2009-01-31 08:15:18 +00001055 return I->getOperand(1);
Reid Spencer8cb68342007-03-12 17:25:59 +00001056
1057 // Output known-0 bits are known if clear or set in both the LHS & RHS.
1058 APInt KnownZeroOut = (RHSKnownZero & LHSKnownZero) |
1059 (RHSKnownOne & LHSKnownOne);
1060 // Output known-1 are known to be set if set in only one of the LHS, RHS.
1061 APInt KnownOneOut = (RHSKnownZero & LHSKnownOne) |
1062 (RHSKnownOne & LHSKnownZero);
1063
1064 // If all of the demanded bits are known to be zero on one side or the
1065 // other, turn this into an *inclusive* or.
1066 // e.g. (A & C1)^(B & C2) -> (A & C1)|(B & C2) iff C1&C2 == 0
Chris Lattner95afdfe2009-08-31 04:36:22 +00001067 if ((DemandedMask & ~RHSKnownZero & ~LHSKnownZero) == 0) {
1068 Instruction *Or =
1069 BinaryOperator::CreateOr(I->getOperand(0), I->getOperand(1),
1070 I->getName());
1071 return InsertNewInstBefore(Or, *I);
1072 }
Reid Spencer8cb68342007-03-12 17:25:59 +00001073
1074 // If all of the demanded bits on one side are known, and all of the set
1075 // bits on that side are also known to be set on the other side, turn this
1076 // into an AND, as we know the bits will be cleared.
1077 // e.g. (X | C1) ^ C2 --> (X | C1) & ~C2 iff (C1&C2) == C2
1078 if ((DemandedMask & (RHSKnownZero|RHSKnownOne)) == DemandedMask) {
1079 // all known
1080 if ((RHSKnownOne & LHSKnownOne) == RHSKnownOne) {
Dan Gohman43ee5f72009-08-03 22:07:33 +00001081 Constant *AndC = Constant::getIntegerValue(VTy,
1082 ~RHSKnownOne & DemandedMask);
Reid Spencer8cb68342007-03-12 17:25:59 +00001083 Instruction *And =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001084 BinaryOperator::CreateAnd(I->getOperand(0), AndC, "tmp");
Chris Lattner886ab6c2009-01-31 08:15:18 +00001085 return InsertNewInstBefore(And, *I);
Reid Spencer8cb68342007-03-12 17:25:59 +00001086 }
1087 }
1088
1089 // If the RHS is a constant, see if we can simplify it.
1090 // FIXME: for XOR, we prefer to force bits to 1 if they will make a -1.
Dan Gohman186a6362009-08-12 16:04:34 +00001091 if (ShrinkDemandedConstant(I, 1, DemandedMask))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001092 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +00001093
Chris Lattnerd0883142009-10-11 22:22:13 +00001094 // If our LHS is an 'and' and if it has one use, and if any of the bits we
1095 // are flipping are known to be set, then the xor is just resetting those
1096 // bits to zero. We can just knock out bits from the 'and' and the 'xor',
1097 // simplifying both of them.
1098 if (Instruction *LHSInst = dyn_cast<Instruction>(I->getOperand(0)))
1099 if (LHSInst->getOpcode() == Instruction::And && LHSInst->hasOneUse() &&
1100 isa<ConstantInt>(I->getOperand(1)) &&
1101 isa<ConstantInt>(LHSInst->getOperand(1)) &&
1102 (LHSKnownOne & RHSKnownOne & DemandedMask) != 0) {
1103 ConstantInt *AndRHS = cast<ConstantInt>(LHSInst->getOperand(1));
1104 ConstantInt *XorRHS = cast<ConstantInt>(I->getOperand(1));
1105 APInt NewMask = ~(LHSKnownOne & RHSKnownOne & DemandedMask);
1106
1107 Constant *AndC =
1108 ConstantInt::get(I->getType(), NewMask & AndRHS->getValue());
1109 Instruction *NewAnd =
1110 BinaryOperator::CreateAnd(I->getOperand(0), AndC, "tmp");
1111 InsertNewInstBefore(NewAnd, *I);
1112
1113 Constant *XorC =
1114 ConstantInt::get(I->getType(), NewMask & XorRHS->getValue());
1115 Instruction *NewXor =
1116 BinaryOperator::CreateXor(NewAnd, XorC, "tmp");
1117 return InsertNewInstBefore(NewXor, *I);
1118 }
1119
1120
Reid Spencer8cb68342007-03-12 17:25:59 +00001121 RHSKnownZero = KnownZeroOut;
1122 RHSKnownOne = KnownOneOut;
1123 break;
1124 }
1125 case Instruction::Select:
Chris Lattner886ab6c2009-01-31 08:15:18 +00001126 if (SimplifyDemandedBits(I->getOperandUse(2), DemandedMask,
1127 RHSKnownZero, RHSKnownOne, Depth+1) ||
1128 SimplifyDemandedBits(I->getOperandUse(1), DemandedMask,
Reid Spencer8cb68342007-03-12 17:25:59 +00001129 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001130 return I;
1131 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
1132 assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +00001133
1134 // If the operands are constants, see if we can simplify them.
Dan Gohman186a6362009-08-12 16:04:34 +00001135 if (ShrinkDemandedConstant(I, 1, DemandedMask) ||
1136 ShrinkDemandedConstant(I, 2, DemandedMask))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001137 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +00001138
1139 // Only known if known in both the LHS and RHS.
1140 RHSKnownOne &= LHSKnownOne;
1141 RHSKnownZero &= LHSKnownZero;
1142 break;
1143 case Instruction::Trunc: {
Dan Gohman6de29f82009-06-15 22:12:54 +00001144 unsigned truncBf = I->getOperand(0)->getType()->getScalarSizeInBits();
Zhou Sheng01542f32007-03-29 02:26:30 +00001145 DemandedMask.zext(truncBf);
1146 RHSKnownZero.zext(truncBf);
1147 RHSKnownOne.zext(truncBf);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001148 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMask,
Zhou Sheng01542f32007-03-29 02:26:30 +00001149 RHSKnownZero, RHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001150 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +00001151 DemandedMask.trunc(BitWidth);
1152 RHSKnownZero.trunc(BitWidth);
1153 RHSKnownOne.trunc(BitWidth);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001154 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +00001155 break;
1156 }
1157 case Instruction::BitCast:
Dan Gohman6cc18fe2009-07-01 21:38:46 +00001158 if (!I->getOperand(0)->getType()->isIntOrIntVector())
Chris Lattner886ab6c2009-01-31 08:15:18 +00001159 return false; // vector->int or fp->int?
Dan Gohman6cc18fe2009-07-01 21:38:46 +00001160
1161 if (const VectorType *DstVTy = dyn_cast<VectorType>(I->getType())) {
1162 if (const VectorType *SrcVTy =
1163 dyn_cast<VectorType>(I->getOperand(0)->getType())) {
1164 if (DstVTy->getNumElements() != SrcVTy->getNumElements())
1165 // Don't touch a bitcast between vectors of different element counts.
1166 return false;
1167 } else
1168 // Don't touch a scalar-to-vector bitcast.
1169 return false;
1170 } else if (isa<VectorType>(I->getOperand(0)->getType()))
1171 // Don't touch a vector-to-scalar bitcast.
1172 return false;
1173
Chris Lattner886ab6c2009-01-31 08:15:18 +00001174 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMask,
Reid Spencer8cb68342007-03-12 17:25:59 +00001175 RHSKnownZero, RHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001176 return I;
1177 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +00001178 break;
1179 case Instruction::ZExt: {
1180 // Compute the bits in the result that are not present in the input.
Dan Gohman6de29f82009-06-15 22:12:54 +00001181 unsigned SrcBitWidth =I->getOperand(0)->getType()->getScalarSizeInBits();
Reid Spencer8cb68342007-03-12 17:25:59 +00001182
Zhou Shengd48653a2007-03-29 04:45:55 +00001183 DemandedMask.trunc(SrcBitWidth);
1184 RHSKnownZero.trunc(SrcBitWidth);
1185 RHSKnownOne.trunc(SrcBitWidth);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001186 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMask,
Zhou Sheng01542f32007-03-29 02:26:30 +00001187 RHSKnownZero, RHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001188 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +00001189 DemandedMask.zext(BitWidth);
1190 RHSKnownZero.zext(BitWidth);
1191 RHSKnownOne.zext(BitWidth);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001192 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +00001193 // The top bits are known to be zero.
Zhou Sheng01542f32007-03-29 02:26:30 +00001194 RHSKnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
Reid Spencer8cb68342007-03-12 17:25:59 +00001195 break;
1196 }
1197 case Instruction::SExt: {
1198 // Compute the bits in the result that are not present in the input.
Dan Gohman6de29f82009-06-15 22:12:54 +00001199 unsigned SrcBitWidth =I->getOperand(0)->getType()->getScalarSizeInBits();
Reid Spencer8cb68342007-03-12 17:25:59 +00001200
Reid Spencer8cb68342007-03-12 17:25:59 +00001201 APInt InputDemandedBits = DemandedMask &
Zhou Sheng01542f32007-03-29 02:26:30 +00001202 APInt::getLowBitsSet(BitWidth, SrcBitWidth);
Reid Spencer8cb68342007-03-12 17:25:59 +00001203
Zhou Sheng01542f32007-03-29 02:26:30 +00001204 APInt NewBits(APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth));
Reid Spencer8cb68342007-03-12 17:25:59 +00001205 // If any of the sign extended bits are demanded, we know that the sign
1206 // bit is demanded.
1207 if ((NewBits & DemandedMask) != 0)
Zhou Sheng4a1822a2007-04-02 13:45:30 +00001208 InputDemandedBits.set(SrcBitWidth-1);
Reid Spencer8cb68342007-03-12 17:25:59 +00001209
Zhou Shengd48653a2007-03-29 04:45:55 +00001210 InputDemandedBits.trunc(SrcBitWidth);
1211 RHSKnownZero.trunc(SrcBitWidth);
1212 RHSKnownOne.trunc(SrcBitWidth);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001213 if (SimplifyDemandedBits(I->getOperandUse(0), InputDemandedBits,
Zhou Sheng01542f32007-03-29 02:26:30 +00001214 RHSKnownZero, RHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001215 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +00001216 InputDemandedBits.zext(BitWidth);
1217 RHSKnownZero.zext(BitWidth);
1218 RHSKnownOne.zext(BitWidth);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001219 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +00001220
1221 // If the sign bit of the input is known set or clear, then we know the
1222 // top bits of the result.
1223
1224 // If the input sign bit is known zero, or if the NewBits are not demanded
1225 // convert this into a zero extension.
Chris Lattner886ab6c2009-01-31 08:15:18 +00001226 if (RHSKnownZero[SrcBitWidth-1] || (NewBits & ~DemandedMask) == NewBits) {
Reid Spencer8cb68342007-03-12 17:25:59 +00001227 // Convert to ZExt cast
Chris Lattner886ab6c2009-01-31 08:15:18 +00001228 CastInst *NewCast = new ZExtInst(I->getOperand(0), VTy, I->getName());
1229 return InsertNewInstBefore(NewCast, *I);
Zhou Sheng01542f32007-03-29 02:26:30 +00001230 } else if (RHSKnownOne[SrcBitWidth-1]) { // Input sign bit known set
Reid Spencer8cb68342007-03-12 17:25:59 +00001231 RHSKnownOne |= NewBits;
Reid Spencer8cb68342007-03-12 17:25:59 +00001232 }
1233 break;
1234 }
1235 case Instruction::Add: {
1236 // Figure out what the input bits are. If the top bits of the and result
1237 // are not demanded, then the add doesn't demand them from its input
1238 // either.
Chris Lattner886ab6c2009-01-31 08:15:18 +00001239 unsigned NLZ = DemandedMask.countLeadingZeros();
Reid Spencer8cb68342007-03-12 17:25:59 +00001240
1241 // If there is a constant on the RHS, there are a variety of xformations
1242 // we can do.
1243 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
1244 // If null, this should be simplified elsewhere. Some of the xforms here
1245 // won't work if the RHS is zero.
1246 if (RHS->isZero())
1247 break;
1248
1249 // If the top bit of the output is demanded, demand everything from the
1250 // input. Otherwise, we demand all the input bits except NLZ top bits.
Zhou Sheng01542f32007-03-29 02:26:30 +00001251 APInt InDemandedBits(APInt::getLowBitsSet(BitWidth, BitWidth - NLZ));
Reid Spencer8cb68342007-03-12 17:25:59 +00001252
1253 // Find information about known zero/one bits in the input.
Chris Lattner886ab6c2009-01-31 08:15:18 +00001254 if (SimplifyDemandedBits(I->getOperandUse(0), InDemandedBits,
Reid Spencer8cb68342007-03-12 17:25:59 +00001255 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001256 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +00001257
1258 // If the RHS of the add has bits set that can't affect the input, reduce
1259 // the constant.
Dan Gohman186a6362009-08-12 16:04:34 +00001260 if (ShrinkDemandedConstant(I, 1, InDemandedBits))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001261 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +00001262
1263 // Avoid excess work.
1264 if (LHSKnownZero == 0 && LHSKnownOne == 0)
1265 break;
1266
1267 // Turn it into OR if input bits are zero.
1268 if ((LHSKnownZero & RHS->getValue()) == RHS->getValue()) {
1269 Instruction *Or =
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001270 BinaryOperator::CreateOr(I->getOperand(0), I->getOperand(1),
Reid Spencer8cb68342007-03-12 17:25:59 +00001271 I->getName());
Chris Lattner886ab6c2009-01-31 08:15:18 +00001272 return InsertNewInstBefore(Or, *I);
Reid Spencer8cb68342007-03-12 17:25:59 +00001273 }
1274
1275 // We can say something about the output known-zero and known-one bits,
1276 // depending on potential carries from the input constant and the
1277 // unknowns. For example if the LHS is known to have at most the 0x0F0F0
1278 // bits set and the RHS constant is 0x01001, then we know we have a known
1279 // one mask of 0x00001 and a known zero mask of 0xE0F0E.
1280
1281 // To compute this, we first compute the potential carry bits. These are
1282 // the bits which may be modified. I'm not aware of a better way to do
1283 // this scan.
Chris Lattner886ab6c2009-01-31 08:15:18 +00001284 const APInt &RHSVal = RHS->getValue();
Zhou Shengb9cb95f2007-03-31 02:38:39 +00001285 APInt CarryBits((~LHSKnownZero + RHSVal) ^ (~LHSKnownZero ^ RHSVal));
Reid Spencer8cb68342007-03-12 17:25:59 +00001286
1287 // Now that we know which bits have carries, compute the known-1/0 sets.
1288
1289 // Bits are known one if they are known zero in one operand and one in the
1290 // other, and there is no input carry.
1291 RHSKnownOne = ((LHSKnownZero & RHSVal) |
1292 (LHSKnownOne & ~RHSVal)) & ~CarryBits;
1293
1294 // Bits are known zero if they are known zero in both operands and there
1295 // is no input carry.
1296 RHSKnownZero = LHSKnownZero & ~RHSVal & ~CarryBits;
1297 } else {
1298 // If the high-bits of this ADD are not demanded, then it does not demand
1299 // the high bits of its LHS or RHS.
Zhou Sheng01542f32007-03-29 02:26:30 +00001300 if (DemandedMask[BitWidth-1] == 0) {
Reid Spencer8cb68342007-03-12 17:25:59 +00001301 // Right fill the mask of bits for this ADD to demand the most
1302 // significant bit and all those below it.
Zhou Sheng01542f32007-03-29 02:26:30 +00001303 APInt DemandedFromOps(APInt::getLowBitsSet(BitWidth, BitWidth-NLZ));
Chris Lattner886ab6c2009-01-31 08:15:18 +00001304 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedFromOps,
1305 LHSKnownZero, LHSKnownOne, Depth+1) ||
1306 SimplifyDemandedBits(I->getOperandUse(1), DemandedFromOps,
Reid Spencer8cb68342007-03-12 17:25:59 +00001307 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001308 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +00001309 }
1310 }
1311 break;
1312 }
1313 case Instruction::Sub:
1314 // If the high-bits of this SUB are not demanded, then it does not demand
1315 // the high bits of its LHS or RHS.
Zhou Sheng01542f32007-03-29 02:26:30 +00001316 if (DemandedMask[BitWidth-1] == 0) {
Reid Spencer8cb68342007-03-12 17:25:59 +00001317 // Right fill the mask of bits for this SUB to demand the most
1318 // significant bit and all those below it.
Zhou Sheng4351c642007-04-02 08:20:41 +00001319 uint32_t NLZ = DemandedMask.countLeadingZeros();
Zhou Sheng01542f32007-03-29 02:26:30 +00001320 APInt DemandedFromOps(APInt::getLowBitsSet(BitWidth, BitWidth-NLZ));
Chris Lattner886ab6c2009-01-31 08:15:18 +00001321 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedFromOps,
1322 LHSKnownZero, LHSKnownOne, Depth+1) ||
1323 SimplifyDemandedBits(I->getOperandUse(1), DemandedFromOps,
Reid Spencer8cb68342007-03-12 17:25:59 +00001324 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001325 return I;
Reid Spencer8cb68342007-03-12 17:25:59 +00001326 }
Dan Gohman23e8b712008-04-28 17:02:21 +00001327 // Otherwise just hand the sub off to ComputeMaskedBits to fill in
1328 // the known zeros and ones.
1329 ComputeMaskedBits(V, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
Reid Spencer8cb68342007-03-12 17:25:59 +00001330 break;
1331 case Instruction::Shl:
1332 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00001333 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
Zhou Sheng01542f32007-03-29 02:26:30 +00001334 APInt DemandedMaskIn(DemandedMask.lshr(ShiftAmt));
Chris Lattner886ab6c2009-01-31 08:15:18 +00001335 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMaskIn,
Reid Spencer8cb68342007-03-12 17:25:59 +00001336 RHSKnownZero, RHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001337 return I;
1338 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +00001339 RHSKnownZero <<= ShiftAmt;
1340 RHSKnownOne <<= ShiftAmt;
1341 // low bits known zero.
Zhou Shengadc14952007-03-14 09:07:33 +00001342 if (ShiftAmt)
Zhou Shenge9e03f62007-03-28 15:02:20 +00001343 RHSKnownZero |= APInt::getLowBitsSet(BitWidth, ShiftAmt);
Reid Spencer8cb68342007-03-12 17:25:59 +00001344 }
1345 break;
1346 case Instruction::LShr:
1347 // For a logical shift right
1348 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00001349 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
Reid Spencer8cb68342007-03-12 17:25:59 +00001350
Reid Spencer8cb68342007-03-12 17:25:59 +00001351 // Unsigned shift right.
Zhou Sheng01542f32007-03-29 02:26:30 +00001352 APInt DemandedMaskIn(DemandedMask.shl(ShiftAmt));
Chris Lattner886ab6c2009-01-31 08:15:18 +00001353 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMaskIn,
Reid Spencer8cb68342007-03-12 17:25:59 +00001354 RHSKnownZero, RHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001355 return I;
1356 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +00001357 RHSKnownZero = APIntOps::lshr(RHSKnownZero, ShiftAmt);
1358 RHSKnownOne = APIntOps::lshr(RHSKnownOne, ShiftAmt);
Zhou Shengadc14952007-03-14 09:07:33 +00001359 if (ShiftAmt) {
1360 // Compute the new bits that are at the top now.
Zhou Sheng01542f32007-03-29 02:26:30 +00001361 APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
Zhou Shengadc14952007-03-14 09:07:33 +00001362 RHSKnownZero |= HighBits; // high bits known zero.
1363 }
Reid Spencer8cb68342007-03-12 17:25:59 +00001364 }
1365 break;
1366 case Instruction::AShr:
1367 // If this is an arithmetic shift right and only the low-bit is set, we can
1368 // always convert this into a logical shr, even if the shift amount is
1369 // variable. The low bit of the shift cannot be an input sign bit unless
1370 // the shift amount is >= the size of the datatype, which is undefined.
1371 if (DemandedMask == 1) {
1372 // Perform the logical shift right.
Chris Lattner886ab6c2009-01-31 08:15:18 +00001373 Instruction *NewVal = BinaryOperator::CreateLShr(
Reid Spencer8cb68342007-03-12 17:25:59 +00001374 I->getOperand(0), I->getOperand(1), I->getName());
Chris Lattner886ab6c2009-01-31 08:15:18 +00001375 return InsertNewInstBefore(NewVal, *I);
Reid Spencer8cb68342007-03-12 17:25:59 +00001376 }
Chris Lattner4241e4d2007-07-15 20:54:51 +00001377
1378 // If the sign bit is the only bit demanded by this ashr, then there is no
1379 // need to do it, the shift doesn't change the high bit.
1380 if (DemandedMask.isSignBit())
Chris Lattner886ab6c2009-01-31 08:15:18 +00001381 return I->getOperand(0);
Reid Spencer8cb68342007-03-12 17:25:59 +00001382
1383 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
Zhou Sheng302748d2007-03-30 17:20:39 +00001384 uint32_t ShiftAmt = SA->getLimitedValue(BitWidth);
Reid Spencer8cb68342007-03-12 17:25:59 +00001385
Reid Spencer8cb68342007-03-12 17:25:59 +00001386 // Signed shift right.
Zhou Sheng01542f32007-03-29 02:26:30 +00001387 APInt DemandedMaskIn(DemandedMask.shl(ShiftAmt));
Lauro Ramos Venanciod0499af2007-06-06 17:08:48 +00001388 // If any of the "high bits" are demanded, we should set the sign bit as
1389 // demanded.
1390 if (DemandedMask.countLeadingZeros() <= ShiftAmt)
1391 DemandedMaskIn.set(BitWidth-1);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001392 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMaskIn,
Reid Spencer8cb68342007-03-12 17:25:59 +00001393 RHSKnownZero, RHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001394 return I;
1395 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
Reid Spencer8cb68342007-03-12 17:25:59 +00001396 // Compute the new bits that are at the top now.
Zhou Sheng01542f32007-03-29 02:26:30 +00001397 APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
Reid Spencer8cb68342007-03-12 17:25:59 +00001398 RHSKnownZero = APIntOps::lshr(RHSKnownZero, ShiftAmt);
1399 RHSKnownOne = APIntOps::lshr(RHSKnownOne, ShiftAmt);
1400
1401 // Handle the sign bits.
1402 APInt SignBit(APInt::getSignBit(BitWidth));
1403 // Adjust to where it is now in the mask.
1404 SignBit = APIntOps::lshr(SignBit, ShiftAmt);
1405
1406 // If the input sign bit is known to be zero, or if none of the top bits
1407 // are demanded, turn this into an unsigned shift right.
Zhou Shengcc419402008-06-06 08:32:05 +00001408 if (BitWidth <= ShiftAmt || RHSKnownZero[BitWidth-ShiftAmt-1] ||
Reid Spencer8cb68342007-03-12 17:25:59 +00001409 (HighBits & ~DemandedMask) == HighBits) {
1410 // Perform the logical shift right.
Chris Lattner886ab6c2009-01-31 08:15:18 +00001411 Instruction *NewVal = BinaryOperator::CreateLShr(
Reid Spencer8cb68342007-03-12 17:25:59 +00001412 I->getOperand(0), SA, I->getName());
Chris Lattner886ab6c2009-01-31 08:15:18 +00001413 return InsertNewInstBefore(NewVal, *I);
Reid Spencer8cb68342007-03-12 17:25:59 +00001414 } else if ((RHSKnownOne & SignBit) != 0) { // New bits are known one.
1415 RHSKnownOne |= HighBits;
1416 }
1417 }
1418 break;
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001419 case Instruction::SRem:
1420 if (ConstantInt *Rem = dyn_cast<ConstantInt>(I->getOperand(1))) {
Nick Lewycky8e394322008-11-02 02:41:50 +00001421 APInt RA = Rem->getValue().abs();
1422 if (RA.isPowerOf2()) {
Eli Friedmana999a512009-06-17 02:57:36 +00001423 if (DemandedMask.ult(RA)) // srem won't affect demanded bits
Chris Lattner886ab6c2009-01-31 08:15:18 +00001424 return I->getOperand(0);
Nick Lewycky3ac9e102008-07-12 05:04:38 +00001425
Nick Lewycky8e394322008-11-02 02:41:50 +00001426 APInt LowBits = RA - 1;
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001427 APInt Mask2 = LowBits | APInt::getSignBit(BitWidth);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001428 if (SimplifyDemandedBits(I->getOperandUse(0), Mask2,
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001429 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001430 return I;
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001431
1432 if (LHSKnownZero[BitWidth-1] || ((LHSKnownZero & LowBits) == LowBits))
1433 LHSKnownZero |= ~LowBits;
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001434
1435 KnownZero |= LHSKnownZero & DemandedMask;
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001436
Chris Lattner886ab6c2009-01-31 08:15:18 +00001437 assert(!(KnownZero & KnownOne) && "Bits known to be one AND zero?");
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001438 }
1439 }
1440 break;
Dan Gohman23e8b712008-04-28 17:02:21 +00001441 case Instruction::URem: {
Dan Gohman23e8b712008-04-28 17:02:21 +00001442 APInt KnownZero2(BitWidth, 0), KnownOne2(BitWidth, 0);
1443 APInt AllOnes = APInt::getAllOnesValue(BitWidth);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001444 if (SimplifyDemandedBits(I->getOperandUse(0), AllOnes,
1445 KnownZero2, KnownOne2, Depth+1) ||
1446 SimplifyDemandedBits(I->getOperandUse(1), AllOnes,
Dan Gohmane85b7582008-05-01 19:13:24 +00001447 KnownZero2, KnownOne2, Depth+1))
Chris Lattner886ab6c2009-01-31 08:15:18 +00001448 return I;
Dan Gohmane85b7582008-05-01 19:13:24 +00001449
Chris Lattner455e9ab2009-01-21 18:09:24 +00001450 unsigned Leaders = KnownZero2.countLeadingOnes();
Dan Gohman23e8b712008-04-28 17:02:21 +00001451 Leaders = std::max(Leaders,
1452 KnownZero2.countLeadingOnes());
1453 KnownZero = APInt::getHighBitsSet(BitWidth, Leaders) & DemandedMask;
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00001454 break;
Reid Spencer8cb68342007-03-12 17:25:59 +00001455 }
Chris Lattner0521e3c2008-06-18 04:33:20 +00001456 case Instruction::Call:
1457 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
1458 switch (II->getIntrinsicID()) {
1459 default: break;
1460 case Intrinsic::bswap: {
1461 // If the only bits demanded come from one byte of the bswap result,
1462 // just shift the input byte into position to eliminate the bswap.
1463 unsigned NLZ = DemandedMask.countLeadingZeros();
1464 unsigned NTZ = DemandedMask.countTrailingZeros();
1465
1466 // Round NTZ down to the next byte. If we have 11 trailing zeros, then
1467 // we need all the bits down to bit 8. Likewise, round NLZ. If we
1468 // have 14 leading zeros, round to 8.
1469 NLZ &= ~7;
1470 NTZ &= ~7;
1471 // If we need exactly one byte, we can do this transformation.
1472 if (BitWidth-NLZ-NTZ == 8) {
1473 unsigned ResultBit = NTZ;
1474 unsigned InputBit = BitWidth-NTZ-8;
1475
1476 // Replace this with either a left or right shift to get the byte into
1477 // the right place.
1478 Instruction *NewVal;
1479 if (InputBit > ResultBit)
1480 NewVal = BinaryOperator::CreateLShr(I->getOperand(1),
Owen Andersoneed707b2009-07-24 23:12:02 +00001481 ConstantInt::get(I->getType(), InputBit-ResultBit));
Chris Lattner0521e3c2008-06-18 04:33:20 +00001482 else
1483 NewVal = BinaryOperator::CreateShl(I->getOperand(1),
Owen Andersoneed707b2009-07-24 23:12:02 +00001484 ConstantInt::get(I->getType(), ResultBit-InputBit));
Chris Lattner0521e3c2008-06-18 04:33:20 +00001485 NewVal->takeName(I);
Chris Lattner886ab6c2009-01-31 08:15:18 +00001486 return InsertNewInstBefore(NewVal, *I);
Chris Lattner0521e3c2008-06-18 04:33:20 +00001487 }
1488
1489 // TODO: Could compute known zero/one bits based on the input.
1490 break;
1491 }
1492 }
1493 }
Chris Lattner6c3bfba2008-06-18 18:11:55 +00001494 ComputeMaskedBits(V, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
Chris Lattner0521e3c2008-06-18 04:33:20 +00001495 break;
Dan Gohman23e8b712008-04-28 17:02:21 +00001496 }
Reid Spencer8cb68342007-03-12 17:25:59 +00001497
1498 // If the client is only demanding bits that we know, return the known
1499 // constant.
Dan Gohman43ee5f72009-08-03 22:07:33 +00001500 if ((DemandedMask & (RHSKnownZero|RHSKnownOne)) == DemandedMask)
1501 return Constant::getIntegerValue(VTy, RHSKnownOne);
Reid Spencer8cb68342007-03-12 17:25:59 +00001502 return false;
1503}
1504
Chris Lattner867b99f2006-10-05 06:55:50 +00001505
Mon P Wangaeb06d22008-11-10 04:46:22 +00001506/// SimplifyDemandedVectorElts - The specified value produces a vector with
Evan Cheng388df622009-02-03 10:05:09 +00001507/// any number of elements. DemandedElts contains the set of elements that are
Chris Lattner867b99f2006-10-05 06:55:50 +00001508/// actually used by the caller. This method analyzes which elements of the
1509/// operand are undef and returns that information in UndefElts.
1510///
1511/// If the information about demanded elements can be used to simplify the
1512/// operation, the operation is simplified, then the resultant value is
1513/// returned. This returns null if no change was made.
Evan Cheng388df622009-02-03 10:05:09 +00001514Value *InstCombiner::SimplifyDemandedVectorElts(Value *V, APInt DemandedElts,
1515 APInt& UndefElts,
Chris Lattner867b99f2006-10-05 06:55:50 +00001516 unsigned Depth) {
Reid Spencer9d6565a2007-02-15 02:26:10 +00001517 unsigned VWidth = cast<VectorType>(V->getType())->getNumElements();
Evan Cheng388df622009-02-03 10:05:09 +00001518 APInt EltMask(APInt::getAllOnesValue(VWidth));
Dan Gohman488fbfc2008-09-09 18:11:14 +00001519 assert((DemandedElts & ~EltMask) == 0 && "Invalid DemandedElts!");
Chris Lattner867b99f2006-10-05 06:55:50 +00001520
1521 if (isa<UndefValue>(V)) {
1522 // If the entire vector is undefined, just return this info.
1523 UndefElts = EltMask;
1524 return 0;
1525 } else if (DemandedElts == 0) { // If nothing is demanded, provide undef.
1526 UndefElts = EltMask;
Owen Anderson9e9a0d52009-07-30 23:03:37 +00001527 return UndefValue::get(V->getType());
Chris Lattner867b99f2006-10-05 06:55:50 +00001528 }
Mon P Wangaeb06d22008-11-10 04:46:22 +00001529
Chris Lattner867b99f2006-10-05 06:55:50 +00001530 UndefElts = 0;
Reid Spencer9d6565a2007-02-15 02:26:10 +00001531 if (ConstantVector *CP = dyn_cast<ConstantVector>(V)) {
1532 const Type *EltTy = cast<VectorType>(V->getType())->getElementType();
Owen Anderson9e9a0d52009-07-30 23:03:37 +00001533 Constant *Undef = UndefValue::get(EltTy);
Chris Lattner867b99f2006-10-05 06:55:50 +00001534
1535 std::vector<Constant*> Elts;
1536 for (unsigned i = 0; i != VWidth; ++i)
Evan Cheng388df622009-02-03 10:05:09 +00001537 if (!DemandedElts[i]) { // If not demanded, set to undef.
Chris Lattner867b99f2006-10-05 06:55:50 +00001538 Elts.push_back(Undef);
Evan Cheng388df622009-02-03 10:05:09 +00001539 UndefElts.set(i);
Chris Lattner867b99f2006-10-05 06:55:50 +00001540 } else if (isa<UndefValue>(CP->getOperand(i))) { // Already undef.
1541 Elts.push_back(Undef);
Evan Cheng388df622009-02-03 10:05:09 +00001542 UndefElts.set(i);
Chris Lattner867b99f2006-10-05 06:55:50 +00001543 } else { // Otherwise, defined.
1544 Elts.push_back(CP->getOperand(i));
1545 }
Mon P Wangaeb06d22008-11-10 04:46:22 +00001546
Chris Lattner867b99f2006-10-05 06:55:50 +00001547 // If we changed the constant, return it.
Owen Andersonaf7ec972009-07-28 21:19:26 +00001548 Constant *NewCP = ConstantVector::get(Elts);
Chris Lattner867b99f2006-10-05 06:55:50 +00001549 return NewCP != CP ? NewCP : 0;
1550 } else if (isa<ConstantAggregateZero>(V)) {
Reid Spencer9d6565a2007-02-15 02:26:10 +00001551 // Simplify the CAZ to a ConstantVector where the non-demanded elements are
Chris Lattner867b99f2006-10-05 06:55:50 +00001552 // set to undef.
Mon P Wange0b436a2008-11-06 22:52:21 +00001553
1554 // Check if this is identity. If so, return 0 since we are not simplifying
1555 // anything.
1556 if (DemandedElts == ((1ULL << VWidth) -1))
1557 return 0;
1558
Reid Spencer9d6565a2007-02-15 02:26:10 +00001559 const Type *EltTy = cast<VectorType>(V->getType())->getElementType();
Owen Andersona7235ea2009-07-31 20:28:14 +00001560 Constant *Zero = Constant::getNullValue(EltTy);
Owen Anderson9e9a0d52009-07-30 23:03:37 +00001561 Constant *Undef = UndefValue::get(EltTy);
Chris Lattner867b99f2006-10-05 06:55:50 +00001562 std::vector<Constant*> Elts;
Evan Cheng388df622009-02-03 10:05:09 +00001563 for (unsigned i = 0; i != VWidth; ++i) {
1564 Constant *Elt = DemandedElts[i] ? Zero : Undef;
1565 Elts.push_back(Elt);
1566 }
Chris Lattner867b99f2006-10-05 06:55:50 +00001567 UndefElts = DemandedElts ^ EltMask;
Owen Andersonaf7ec972009-07-28 21:19:26 +00001568 return ConstantVector::get(Elts);
Chris Lattner867b99f2006-10-05 06:55:50 +00001569 }
1570
Dan Gohman488fbfc2008-09-09 18:11:14 +00001571 // Limit search depth.
1572 if (Depth == 10)
Dan Gohman2fe4d0a2009-04-25 17:28:45 +00001573 return 0;
Dan Gohman488fbfc2008-09-09 18:11:14 +00001574
1575 // If multiple users are using the root value, procede with
1576 // simplification conservatively assuming that all elements
1577 // are needed.
1578 if (!V->hasOneUse()) {
1579 // Quit if we find multiple users of a non-root value though.
1580 // They'll be handled when it's their turn to be visited by
1581 // the main instcombine process.
1582 if (Depth != 0)
Chris Lattner867b99f2006-10-05 06:55:50 +00001583 // TODO: Just compute the UndefElts information recursively.
Dan Gohman2fe4d0a2009-04-25 17:28:45 +00001584 return 0;
Dan Gohman488fbfc2008-09-09 18:11:14 +00001585
1586 // Conservatively assume that all elements are needed.
1587 DemandedElts = EltMask;
Chris Lattner867b99f2006-10-05 06:55:50 +00001588 }
1589
1590 Instruction *I = dyn_cast<Instruction>(V);
Dan Gohman2fe4d0a2009-04-25 17:28:45 +00001591 if (!I) return 0; // Only analyze instructions.
Chris Lattner867b99f2006-10-05 06:55:50 +00001592
1593 bool MadeChange = false;
Evan Cheng388df622009-02-03 10:05:09 +00001594 APInt UndefElts2(VWidth, 0);
Chris Lattner867b99f2006-10-05 06:55:50 +00001595 Value *TmpV;
1596 switch (I->getOpcode()) {
1597 default: break;
1598
1599 case Instruction::InsertElement: {
1600 // If this is a variable index, we don't know which element it overwrites.
1601 // demand exactly the same input as we produce.
Reid Spencerb83eb642006-10-20 07:07:24 +00001602 ConstantInt *Idx = dyn_cast<ConstantInt>(I->getOperand(2));
Chris Lattner867b99f2006-10-05 06:55:50 +00001603 if (Idx == 0) {
1604 // Note that we can't propagate undef elt info, because we don't know
1605 // which elt is getting updated.
1606 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1607 UndefElts2, Depth+1);
1608 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1609 break;
1610 }
1611
1612 // If this is inserting an element that isn't demanded, remove this
1613 // insertelement.
Reid Spencerb83eb642006-10-20 07:07:24 +00001614 unsigned IdxNo = Idx->getZExtValue();
Chris Lattnerc3a3e362009-08-30 06:20:05 +00001615 if (IdxNo >= VWidth || !DemandedElts[IdxNo]) {
1616 Worklist.Add(I);
1617 return I->getOperand(0);
1618 }
Chris Lattner867b99f2006-10-05 06:55:50 +00001619
1620 // Otherwise, the element inserted overwrites whatever was there, so the
1621 // input demanded set is simpler than the output set.
Evan Cheng388df622009-02-03 10:05:09 +00001622 APInt DemandedElts2 = DemandedElts;
1623 DemandedElts2.clear(IdxNo);
1624 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts2,
Chris Lattner867b99f2006-10-05 06:55:50 +00001625 UndefElts, Depth+1);
1626 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1627
1628 // The inserted element is defined.
Evan Cheng388df622009-02-03 10:05:09 +00001629 UndefElts.clear(IdxNo);
Dan Gohman488fbfc2008-09-09 18:11:14 +00001630 break;
1631 }
1632 case Instruction::ShuffleVector: {
1633 ShuffleVectorInst *Shuffle = cast<ShuffleVectorInst>(I);
Mon P Wangaeb06d22008-11-10 04:46:22 +00001634 uint64_t LHSVWidth =
1635 cast<VectorType>(Shuffle->getOperand(0)->getType())->getNumElements();
Evan Cheng388df622009-02-03 10:05:09 +00001636 APInt LeftDemanded(LHSVWidth, 0), RightDemanded(LHSVWidth, 0);
Dan Gohman488fbfc2008-09-09 18:11:14 +00001637 for (unsigned i = 0; i < VWidth; i++) {
Evan Cheng388df622009-02-03 10:05:09 +00001638 if (DemandedElts[i]) {
Dan Gohman488fbfc2008-09-09 18:11:14 +00001639 unsigned MaskVal = Shuffle->getMaskValue(i);
1640 if (MaskVal != -1u) {
Mon P Wangaeb06d22008-11-10 04:46:22 +00001641 assert(MaskVal < LHSVWidth * 2 &&
Dan Gohman488fbfc2008-09-09 18:11:14 +00001642 "shufflevector mask index out of range!");
Mon P Wangaeb06d22008-11-10 04:46:22 +00001643 if (MaskVal < LHSVWidth)
Evan Cheng388df622009-02-03 10:05:09 +00001644 LeftDemanded.set(MaskVal);
Dan Gohman488fbfc2008-09-09 18:11:14 +00001645 else
Evan Cheng388df622009-02-03 10:05:09 +00001646 RightDemanded.set(MaskVal - LHSVWidth);
Dan Gohman488fbfc2008-09-09 18:11:14 +00001647 }
1648 }
1649 }
1650
Nate Begeman7b254672009-02-11 22:36:25 +00001651 APInt UndefElts4(LHSVWidth, 0);
Dan Gohman488fbfc2008-09-09 18:11:14 +00001652 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), LeftDemanded,
Nate Begeman7b254672009-02-11 22:36:25 +00001653 UndefElts4, Depth+1);
Dan Gohman488fbfc2008-09-09 18:11:14 +00001654 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1655
Nate Begeman7b254672009-02-11 22:36:25 +00001656 APInt UndefElts3(LHSVWidth, 0);
Dan Gohman488fbfc2008-09-09 18:11:14 +00001657 TmpV = SimplifyDemandedVectorElts(I->getOperand(1), RightDemanded,
1658 UndefElts3, Depth+1);
1659 if (TmpV) { I->setOperand(1, TmpV); MadeChange = true; }
1660
1661 bool NewUndefElts = false;
1662 for (unsigned i = 0; i < VWidth; i++) {
1663 unsigned MaskVal = Shuffle->getMaskValue(i);
Dan Gohmancb893092008-09-10 01:09:32 +00001664 if (MaskVal == -1u) {
Evan Cheng388df622009-02-03 10:05:09 +00001665 UndefElts.set(i);
Mon P Wangaeb06d22008-11-10 04:46:22 +00001666 } else if (MaskVal < LHSVWidth) {
Nate Begeman7b254672009-02-11 22:36:25 +00001667 if (UndefElts4[MaskVal]) {
Evan Cheng388df622009-02-03 10:05:09 +00001668 NewUndefElts = true;
1669 UndefElts.set(i);
1670 }
Dan Gohman488fbfc2008-09-09 18:11:14 +00001671 } else {
Evan Cheng388df622009-02-03 10:05:09 +00001672 if (UndefElts3[MaskVal - LHSVWidth]) {
1673 NewUndefElts = true;
1674 UndefElts.set(i);
1675 }
Dan Gohman488fbfc2008-09-09 18:11:14 +00001676 }
1677 }
1678
1679 if (NewUndefElts) {
1680 // Add additional discovered undefs.
1681 std::vector<Constant*> Elts;
1682 for (unsigned i = 0; i < VWidth; ++i) {
Evan Cheng388df622009-02-03 10:05:09 +00001683 if (UndefElts[i])
Owen Anderson1d0be152009-08-13 21:58:54 +00001684 Elts.push_back(UndefValue::get(Type::getInt32Ty(*Context)));
Dan Gohman488fbfc2008-09-09 18:11:14 +00001685 else
Owen Anderson1d0be152009-08-13 21:58:54 +00001686 Elts.push_back(ConstantInt::get(Type::getInt32Ty(*Context),
Dan Gohman488fbfc2008-09-09 18:11:14 +00001687 Shuffle->getMaskValue(i)));
1688 }
Owen Andersonaf7ec972009-07-28 21:19:26 +00001689 I->setOperand(2, ConstantVector::get(Elts));
Dan Gohman488fbfc2008-09-09 18:11:14 +00001690 MadeChange = true;
1691 }
Chris Lattner867b99f2006-10-05 06:55:50 +00001692 break;
1693 }
Chris Lattner69878332007-04-14 22:29:23 +00001694 case Instruction::BitCast: {
Dan Gohman07a96762007-07-16 14:29:03 +00001695 // Vector->vector casts only.
Chris Lattner69878332007-04-14 22:29:23 +00001696 const VectorType *VTy = dyn_cast<VectorType>(I->getOperand(0)->getType());
1697 if (!VTy) break;
1698 unsigned InVWidth = VTy->getNumElements();
Evan Cheng388df622009-02-03 10:05:09 +00001699 APInt InputDemandedElts(InVWidth, 0);
Chris Lattner69878332007-04-14 22:29:23 +00001700 unsigned Ratio;
1701
1702 if (VWidth == InVWidth) {
Dan Gohman07a96762007-07-16 14:29:03 +00001703 // If we are converting from <4 x i32> -> <4 x f32>, we demand the same
Chris Lattner69878332007-04-14 22:29:23 +00001704 // elements as are demanded of us.
1705 Ratio = 1;
1706 InputDemandedElts = DemandedElts;
1707 } else if (VWidth > InVWidth) {
1708 // Untested so far.
1709 break;
1710
1711 // If there are more elements in the result than there are in the source,
1712 // then an input element is live if any of the corresponding output
1713 // elements are live.
1714 Ratio = VWidth/InVWidth;
1715 for (unsigned OutIdx = 0; OutIdx != VWidth; ++OutIdx) {
Evan Cheng388df622009-02-03 10:05:09 +00001716 if (DemandedElts[OutIdx])
1717 InputDemandedElts.set(OutIdx/Ratio);
Chris Lattner69878332007-04-14 22:29:23 +00001718 }
1719 } else {
1720 // Untested so far.
1721 break;
1722
1723 // If there are more elements in the source than there are in the result,
1724 // then an input element is live if the corresponding output element is
1725 // live.
1726 Ratio = InVWidth/VWidth;
1727 for (unsigned InIdx = 0; InIdx != InVWidth; ++InIdx)
Evan Cheng388df622009-02-03 10:05:09 +00001728 if (DemandedElts[InIdx/Ratio])
1729 InputDemandedElts.set(InIdx);
Chris Lattner69878332007-04-14 22:29:23 +00001730 }
Chris Lattner867b99f2006-10-05 06:55:50 +00001731
Chris Lattner69878332007-04-14 22:29:23 +00001732 // div/rem demand all inputs, because they don't want divide by zero.
1733 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), InputDemandedElts,
1734 UndefElts2, Depth+1);
1735 if (TmpV) {
1736 I->setOperand(0, TmpV);
1737 MadeChange = true;
1738 }
1739
1740 UndefElts = UndefElts2;
1741 if (VWidth > InVWidth) {
Torok Edwinc23197a2009-07-14 16:55:14 +00001742 llvm_unreachable("Unimp");
Chris Lattner69878332007-04-14 22:29:23 +00001743 // If there are more elements in the result than there are in the source,
1744 // then an output element is undef if the corresponding input element is
1745 // undef.
1746 for (unsigned OutIdx = 0; OutIdx != VWidth; ++OutIdx)
Evan Cheng388df622009-02-03 10:05:09 +00001747 if (UndefElts2[OutIdx/Ratio])
1748 UndefElts.set(OutIdx);
Chris Lattner69878332007-04-14 22:29:23 +00001749 } else if (VWidth < InVWidth) {
Torok Edwinc23197a2009-07-14 16:55:14 +00001750 llvm_unreachable("Unimp");
Chris Lattner69878332007-04-14 22:29:23 +00001751 // If there are more elements in the source than there are in the result,
1752 // then a result element is undef if all of the corresponding input
1753 // elements are undef.
1754 UndefElts = ~0ULL >> (64-VWidth); // Start out all undef.
1755 for (unsigned InIdx = 0; InIdx != InVWidth; ++InIdx)
Evan Cheng388df622009-02-03 10:05:09 +00001756 if (!UndefElts2[InIdx]) // Not undef?
1757 UndefElts.clear(InIdx/Ratio); // Clear undef bit.
Chris Lattner69878332007-04-14 22:29:23 +00001758 }
1759 break;
1760 }
Chris Lattner867b99f2006-10-05 06:55:50 +00001761 case Instruction::And:
1762 case Instruction::Or:
1763 case Instruction::Xor:
1764 case Instruction::Add:
1765 case Instruction::Sub:
1766 case Instruction::Mul:
1767 // div/rem demand all inputs, because they don't want divide by zero.
1768 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1769 UndefElts, Depth+1);
1770 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1771 TmpV = SimplifyDemandedVectorElts(I->getOperand(1), DemandedElts,
1772 UndefElts2, Depth+1);
1773 if (TmpV) { I->setOperand(1, TmpV); MadeChange = true; }
1774
1775 // Output elements are undefined if both are undefined. Consider things
1776 // like undef&0. The result is known zero, not undef.
1777 UndefElts &= UndefElts2;
1778 break;
1779
1780 case Instruction::Call: {
1781 IntrinsicInst *II = dyn_cast<IntrinsicInst>(I);
1782 if (!II) break;
1783 switch (II->getIntrinsicID()) {
1784 default: break;
1785
1786 // Binary vector operations that work column-wise. A dest element is a
1787 // function of the corresponding input elements from the two inputs.
1788 case Intrinsic::x86_sse_sub_ss:
1789 case Intrinsic::x86_sse_mul_ss:
1790 case Intrinsic::x86_sse_min_ss:
1791 case Intrinsic::x86_sse_max_ss:
1792 case Intrinsic::x86_sse2_sub_sd:
1793 case Intrinsic::x86_sse2_mul_sd:
1794 case Intrinsic::x86_sse2_min_sd:
1795 case Intrinsic::x86_sse2_max_sd:
1796 TmpV = SimplifyDemandedVectorElts(II->getOperand(1), DemandedElts,
1797 UndefElts, Depth+1);
1798 if (TmpV) { II->setOperand(1, TmpV); MadeChange = true; }
1799 TmpV = SimplifyDemandedVectorElts(II->getOperand(2), DemandedElts,
1800 UndefElts2, Depth+1);
1801 if (TmpV) { II->setOperand(2, TmpV); MadeChange = true; }
1802
1803 // If only the low elt is demanded and this is a scalarizable intrinsic,
1804 // scalarize it now.
1805 if (DemandedElts == 1) {
1806 switch (II->getIntrinsicID()) {
1807 default: break;
1808 case Intrinsic::x86_sse_sub_ss:
1809 case Intrinsic::x86_sse_mul_ss:
1810 case Intrinsic::x86_sse2_sub_sd:
1811 case Intrinsic::x86_sse2_mul_sd:
1812 // TODO: Lower MIN/MAX/ABS/etc
1813 Value *LHS = II->getOperand(1);
1814 Value *RHS = II->getOperand(2);
1815 // Extract the element as scalars.
Eric Christophera3500da2009-07-25 02:28:41 +00001816 LHS = InsertNewInstBefore(ExtractElementInst::Create(LHS,
Owen Anderson1d0be152009-08-13 21:58:54 +00001817 ConstantInt::get(Type::getInt32Ty(*Context), 0U, false), "tmp"), *II);
Eric Christophera3500da2009-07-25 02:28:41 +00001818 RHS = InsertNewInstBefore(ExtractElementInst::Create(RHS,
Owen Anderson1d0be152009-08-13 21:58:54 +00001819 ConstantInt::get(Type::getInt32Ty(*Context), 0U, false), "tmp"), *II);
Chris Lattner867b99f2006-10-05 06:55:50 +00001820
1821 switch (II->getIntrinsicID()) {
Torok Edwinc23197a2009-07-14 16:55:14 +00001822 default: llvm_unreachable("Case stmts out of sync!");
Chris Lattner867b99f2006-10-05 06:55:50 +00001823 case Intrinsic::x86_sse_sub_ss:
1824 case Intrinsic::x86_sse2_sub_sd:
Dan Gohmanae3a0be2009-06-04 22:49:04 +00001825 TmpV = InsertNewInstBefore(BinaryOperator::CreateFSub(LHS, RHS,
Chris Lattner867b99f2006-10-05 06:55:50 +00001826 II->getName()), *II);
1827 break;
1828 case Intrinsic::x86_sse_mul_ss:
1829 case Intrinsic::x86_sse2_mul_sd:
Dan Gohmanae3a0be2009-06-04 22:49:04 +00001830 TmpV = InsertNewInstBefore(BinaryOperator::CreateFMul(LHS, RHS,
Chris Lattner867b99f2006-10-05 06:55:50 +00001831 II->getName()), *II);
1832 break;
1833 }
1834
1835 Instruction *New =
Owen Andersond672ecb2009-07-03 00:17:18 +00001836 InsertElementInst::Create(
Owen Anderson9e9a0d52009-07-30 23:03:37 +00001837 UndefValue::get(II->getType()), TmpV,
Owen Anderson1d0be152009-08-13 21:58:54 +00001838 ConstantInt::get(Type::getInt32Ty(*Context), 0U, false), II->getName());
Chris Lattner867b99f2006-10-05 06:55:50 +00001839 InsertNewInstBefore(New, *II);
Chris Lattner867b99f2006-10-05 06:55:50 +00001840 return New;
1841 }
1842 }
1843
1844 // Output elements are undefined if both are undefined. Consider things
1845 // like undef&0. The result is known zero, not undef.
1846 UndefElts &= UndefElts2;
1847 break;
1848 }
1849 break;
1850 }
1851 }
1852 return MadeChange ? I : 0;
1853}
1854
Dan Gohman45b4e482008-05-19 22:14:15 +00001855
Chris Lattner564a7272003-08-13 19:01:45 +00001856/// AssociativeOpt - Perform an optimization on an associative operator. This
1857/// function is designed to check a chain of associative operators for a
1858/// potential to apply a certain optimization. Since the optimization may be
1859/// applicable if the expression was reassociated, this checks the chain, then
1860/// reassociates the expression as necessary to expose the optimization
1861/// opportunity. This makes use of a special Functor, which must define
1862/// 'shouldApply' and 'apply' methods.
1863///
1864template<typename Functor>
Dan Gohman186a6362009-08-12 16:04:34 +00001865static Instruction *AssociativeOpt(BinaryOperator &Root, const Functor &F) {
Chris Lattner564a7272003-08-13 19:01:45 +00001866 unsigned Opcode = Root.getOpcode();
1867 Value *LHS = Root.getOperand(0);
1868
1869 // Quick check, see if the immediate LHS matches...
1870 if (F.shouldApply(LHS))
1871 return F.apply(Root);
1872
1873 // Otherwise, if the LHS is not of the same opcode as the root, return.
1874 Instruction *LHSI = dyn_cast<Instruction>(LHS);
Chris Lattnerfd059242003-10-15 16:48:29 +00001875 while (LHSI && LHSI->getOpcode() == Opcode && LHSI->hasOneUse()) {
Chris Lattner564a7272003-08-13 19:01:45 +00001876 // Should we apply this transform to the RHS?
1877 bool ShouldApply = F.shouldApply(LHSI->getOperand(1));
1878
1879 // If not to the RHS, check to see if we should apply to the LHS...
1880 if (!ShouldApply && F.shouldApply(LHSI->getOperand(0))) {
1881 cast<BinaryOperator>(LHSI)->swapOperands(); // Make the LHS the RHS
1882 ShouldApply = true;
1883 }
1884
1885 // If the functor wants to apply the optimization to the RHS of LHSI,
1886 // reassociate the expression from ((? op A) op B) to (? op (A op B))
1887 if (ShouldApply) {
Chris Lattner564a7272003-08-13 19:01:45 +00001888 // Now all of the instructions are in the current basic block, go ahead
1889 // and perform the reassociation.
1890 Instruction *TmpLHSI = cast<Instruction>(Root.getOperand(0));
1891
1892 // First move the selected RHS to the LHS of the root...
1893 Root.setOperand(0, LHSI->getOperand(1));
1894
1895 // Make what used to be the LHS of the root be the user of the root...
1896 Value *ExtraOperand = TmpLHSI->getOperand(1);
Chris Lattner65725312004-04-16 18:08:07 +00001897 if (&Root == TmpLHSI) {
Owen Andersona7235ea2009-07-31 20:28:14 +00001898 Root.replaceAllUsesWith(Constant::getNullValue(TmpLHSI->getType()));
Chris Lattner15a76c02004-04-05 02:10:19 +00001899 return 0;
1900 }
Chris Lattner65725312004-04-16 18:08:07 +00001901 Root.replaceAllUsesWith(TmpLHSI); // Users now use TmpLHSI
Chris Lattner564a7272003-08-13 19:01:45 +00001902 TmpLHSI->setOperand(1, &Root); // TmpLHSI now uses the root
Chris Lattner65725312004-04-16 18:08:07 +00001903 BasicBlock::iterator ARI = &Root; ++ARI;
Dan Gohmand02d9172008-06-19 17:47:47 +00001904 TmpLHSI->moveBefore(ARI); // Move TmpLHSI to after Root
Chris Lattner65725312004-04-16 18:08:07 +00001905 ARI = Root;
Chris Lattner564a7272003-08-13 19:01:45 +00001906
1907 // Now propagate the ExtraOperand down the chain of instructions until we
1908 // get to LHSI.
1909 while (TmpLHSI != LHSI) {
1910 Instruction *NextLHSI = cast<Instruction>(TmpLHSI->getOperand(0));
Chris Lattner65725312004-04-16 18:08:07 +00001911 // Move the instruction to immediately before the chain we are
1912 // constructing to avoid breaking dominance properties.
Dan Gohmand02d9172008-06-19 17:47:47 +00001913 NextLHSI->moveBefore(ARI);
Chris Lattner65725312004-04-16 18:08:07 +00001914 ARI = NextLHSI;
1915
Chris Lattner564a7272003-08-13 19:01:45 +00001916 Value *NextOp = NextLHSI->getOperand(1);
1917 NextLHSI->setOperand(1, ExtraOperand);
1918 TmpLHSI = NextLHSI;
1919 ExtraOperand = NextOp;
1920 }
Misha Brukmanfd939082005-04-21 23:48:37 +00001921
Chris Lattner564a7272003-08-13 19:01:45 +00001922 // Now that the instructions are reassociated, have the functor perform
1923 // the transformation...
1924 return F.apply(Root);
1925 }
Misha Brukmanfd939082005-04-21 23:48:37 +00001926
Chris Lattner564a7272003-08-13 19:01:45 +00001927 LHSI = dyn_cast<Instruction>(LHSI->getOperand(0));
1928 }
1929 return 0;
1930}
1931
Dan Gohman844731a2008-05-13 00:00:25 +00001932namespace {
Chris Lattner564a7272003-08-13 19:01:45 +00001933
Nick Lewycky02d639f2008-05-23 04:34:58 +00001934// AddRHS - Implements: X + X --> X << 1
Chris Lattner564a7272003-08-13 19:01:45 +00001935struct AddRHS {
1936 Value *RHS;
Dan Gohman4ae51262009-08-12 16:23:25 +00001937 explicit AddRHS(Value *rhs) : RHS(rhs) {}
Chris Lattner564a7272003-08-13 19:01:45 +00001938 bool shouldApply(Value *LHS) const { return LHS == RHS; }
1939 Instruction *apply(BinaryOperator &Add) const {
Nick Lewycky02d639f2008-05-23 04:34:58 +00001940 return BinaryOperator::CreateShl(Add.getOperand(0),
Owen Andersoneed707b2009-07-24 23:12:02 +00001941 ConstantInt::get(Add.getType(), 1));
Chris Lattner564a7272003-08-13 19:01:45 +00001942 }
1943};
1944
1945// AddMaskingAnd - Implements (A & C1)+(B & C2) --> (A & C1)|(B & C2)
1946// iff C1&C2 == 0
1947struct AddMaskingAnd {
1948 Constant *C2;
Dan Gohman4ae51262009-08-12 16:23:25 +00001949 explicit AddMaskingAnd(Constant *c) : C2(c) {}
Chris Lattner564a7272003-08-13 19:01:45 +00001950 bool shouldApply(Value *LHS) const {
Chris Lattneracd1f0f2004-07-30 07:50:03 +00001951 ConstantInt *C1;
Dan Gohman4ae51262009-08-12 16:23:25 +00001952 return match(LHS, m_And(m_Value(), m_ConstantInt(C1))) &&
Owen Andersonbaf3c402009-07-29 18:55:55 +00001953 ConstantExpr::getAnd(C1, C2)->isNullValue();
Chris Lattner564a7272003-08-13 19:01:45 +00001954 }
1955 Instruction *apply(BinaryOperator &Add) const {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00001956 return BinaryOperator::CreateOr(Add.getOperand(0), Add.getOperand(1));
Chris Lattner564a7272003-08-13 19:01:45 +00001957 }
1958};
1959
Dan Gohman844731a2008-05-13 00:00:25 +00001960}
1961
Chris Lattner6e7ba452005-01-01 16:22:27 +00001962static Value *FoldOperationIntoSelectOperand(Instruction &I, Value *SO,
Chris Lattner2eefe512004-04-09 19:05:30 +00001963 InstCombiner *IC) {
Chris Lattner08142f22009-08-30 19:47:22 +00001964 if (CastInst *CI = dyn_cast<CastInst>(&I))
Chris Lattner2345d1d2009-08-30 20:01:10 +00001965 return IC->Builder->CreateCast(CI->getOpcode(), SO, I.getType());
Chris Lattner6e7ba452005-01-01 16:22:27 +00001966
Chris Lattner2eefe512004-04-09 19:05:30 +00001967 // Figure out if the constant is the left or the right argument.
Chris Lattner6e7ba452005-01-01 16:22:27 +00001968 bool ConstIsRHS = isa<Constant>(I.getOperand(1));
1969 Constant *ConstOperand = cast<Constant>(I.getOperand(ConstIsRHS));
Chris Lattner564a7272003-08-13 19:01:45 +00001970
Chris Lattner2eefe512004-04-09 19:05:30 +00001971 if (Constant *SOC = dyn_cast<Constant>(SO)) {
1972 if (ConstIsRHS)
Owen Andersonbaf3c402009-07-29 18:55:55 +00001973 return ConstantExpr::get(I.getOpcode(), SOC, ConstOperand);
1974 return ConstantExpr::get(I.getOpcode(), ConstOperand, SOC);
Chris Lattner2eefe512004-04-09 19:05:30 +00001975 }
1976
1977 Value *Op0 = SO, *Op1 = ConstOperand;
1978 if (!ConstIsRHS)
1979 std::swap(Op0, Op1);
Chris Lattner74381062009-08-30 07:44:24 +00001980
Chris Lattner6e7ba452005-01-01 16:22:27 +00001981 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
Chris Lattner74381062009-08-30 07:44:24 +00001982 return IC->Builder->CreateBinOp(BO->getOpcode(), Op0, Op1,
1983 SO->getName()+".op");
1984 if (ICmpInst *CI = dyn_cast<ICmpInst>(&I))
1985 return IC->Builder->CreateICmp(CI->getPredicate(), Op0, Op1,
1986 SO->getName()+".cmp");
1987 if (FCmpInst *CI = dyn_cast<FCmpInst>(&I))
1988 return IC->Builder->CreateICmp(CI->getPredicate(), Op0, Op1,
1989 SO->getName()+".cmp");
1990 llvm_unreachable("Unknown binary instruction type!");
Chris Lattner6e7ba452005-01-01 16:22:27 +00001991}
1992
1993// FoldOpIntoSelect - Given an instruction with a select as one operand and a
1994// constant as the other operand, try to fold the binary operator into the
1995// select arguments. This also works for Cast instructions, which obviously do
1996// not have a second operand.
1997static Instruction *FoldOpIntoSelect(Instruction &Op, SelectInst *SI,
1998 InstCombiner *IC) {
1999 // Don't modify shared select instructions
2000 if (!SI->hasOneUse()) return 0;
2001 Value *TV = SI->getOperand(1);
2002 Value *FV = SI->getOperand(2);
2003
2004 if (isa<Constant>(TV) || isa<Constant>(FV)) {
Chris Lattner956db272005-04-21 05:43:13 +00002005 // Bool selects with constant operands can be folded to logical ops.
Owen Anderson1d0be152009-08-13 21:58:54 +00002006 if (SI->getType() == Type::getInt1Ty(*IC->getContext())) return 0;
Chris Lattner956db272005-04-21 05:43:13 +00002007
Chris Lattner6e7ba452005-01-01 16:22:27 +00002008 Value *SelectTrueVal = FoldOperationIntoSelectOperand(Op, TV, IC);
2009 Value *SelectFalseVal = FoldOperationIntoSelectOperand(Op, FV, IC);
2010
Gabor Greif051a9502008-04-06 20:25:17 +00002011 return SelectInst::Create(SI->getCondition(), SelectTrueVal,
2012 SelectFalseVal);
Chris Lattner6e7ba452005-01-01 16:22:27 +00002013 }
2014 return 0;
Chris Lattner2eefe512004-04-09 19:05:30 +00002015}
2016
Chris Lattner4e998b22004-09-29 05:07:12 +00002017
Chris Lattner5d1704d2009-09-27 19:57:57 +00002018/// FoldOpIntoPhi - Given a binary operator, cast instruction, or select which
2019/// has a PHI node as operand #0, see if we can fold the instruction into the
2020/// PHI (which is only possible if all operands to the PHI are constants).
Chris Lattner213cd612009-09-27 20:46:36 +00002021///
2022/// If AllowAggressive is true, FoldOpIntoPhi will allow certain transforms
2023/// that would normally be unprofitable because they strongly encourage jump
2024/// threading.
2025Instruction *InstCombiner::FoldOpIntoPhi(Instruction &I,
2026 bool AllowAggressive) {
2027 AllowAggressive = false;
Chris Lattner4e998b22004-09-29 05:07:12 +00002028 PHINode *PN = cast<PHINode>(I.getOperand(0));
Chris Lattnerbac32862004-11-14 19:13:23 +00002029 unsigned NumPHIValues = PN->getNumIncomingValues();
Chris Lattner213cd612009-09-27 20:46:36 +00002030 if (NumPHIValues == 0 ||
2031 // We normally only transform phis with a single use, unless we're trying
2032 // hard to make jump threading happen.
2033 (!PN->hasOneUse() && !AllowAggressive))
2034 return 0;
2035
2036
Chris Lattner5d1704d2009-09-27 19:57:57 +00002037 // Check to see if all of the operands of the PHI are simple constants
2038 // (constantint/constantfp/undef). If there is one non-constant value,
Chris Lattnerc6df8f42009-09-27 20:18:49 +00002039 // remember the BB it is in. If there is more than one or if *it* is a PHI,
2040 // bail out. We don't do arbitrary constant expressions here because moving
2041 // their computation can be expensive without a cost model.
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002042 BasicBlock *NonConstBB = 0;
2043 for (unsigned i = 0; i != NumPHIValues; ++i)
Chris Lattner5d1704d2009-09-27 19:57:57 +00002044 if (!isa<Constant>(PN->getIncomingValue(i)) ||
2045 isa<ConstantExpr>(PN->getIncomingValue(i))) {
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002046 if (NonConstBB) return 0; // More than one non-const value.
Chris Lattnerb3036682007-02-24 01:03:45 +00002047 if (isa<PHINode>(PN->getIncomingValue(i))) return 0; // Itself a phi.
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002048 NonConstBB = PN->getIncomingBlock(i);
2049
2050 // If the incoming non-constant value is in I's block, we have an infinite
2051 // loop.
2052 if (NonConstBB == I.getParent())
2053 return 0;
2054 }
2055
2056 // If there is exactly one non-constant value, we can insert a copy of the
2057 // operation in that block. However, if this is a critical edge, we would be
2058 // inserting the computation one some other paths (e.g. inside a loop). Only
2059 // do this if the pred block is unconditionally branching into the phi block.
Chris Lattner213cd612009-09-27 20:46:36 +00002060 if (NonConstBB != 0 && !AllowAggressive) {
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002061 BranchInst *BI = dyn_cast<BranchInst>(NonConstBB->getTerminator());
2062 if (!BI || !BI->isUnconditional()) return 0;
2063 }
Chris Lattner4e998b22004-09-29 05:07:12 +00002064
2065 // Okay, we can do the transformation: create the new PHI node.
Gabor Greif051a9502008-04-06 20:25:17 +00002066 PHINode *NewPN = PHINode::Create(I.getType(), "");
Chris Lattner55517062005-01-29 00:39:08 +00002067 NewPN->reserveOperandSpace(PN->getNumOperands()/2);
Chris Lattner857eb572009-10-21 23:41:58 +00002068 InsertNewInstBefore(NewPN, *PN);
2069 NewPN->takeName(PN);
Chris Lattner4e998b22004-09-29 05:07:12 +00002070
2071 // Next, add all of the operands to the PHI.
Chris Lattner5d1704d2009-09-27 19:57:57 +00002072 if (SelectInst *SI = dyn_cast<SelectInst>(&I)) {
2073 // We only currently try to fold the condition of a select when it is a phi,
2074 // not the true/false values.
Chris Lattnerc6df8f42009-09-27 20:18:49 +00002075 Value *TrueV = SI->getTrueValue();
2076 Value *FalseV = SI->getFalseValue();
Chris Lattner3ddfb212009-09-28 06:49:44 +00002077 BasicBlock *PhiTransBB = PN->getParent();
Chris Lattner5d1704d2009-09-27 19:57:57 +00002078 for (unsigned i = 0; i != NumPHIValues; ++i) {
Chris Lattnerc6df8f42009-09-27 20:18:49 +00002079 BasicBlock *ThisBB = PN->getIncomingBlock(i);
Chris Lattner3ddfb212009-09-28 06:49:44 +00002080 Value *TrueVInPred = TrueV->DoPHITranslation(PhiTransBB, ThisBB);
2081 Value *FalseVInPred = FalseV->DoPHITranslation(PhiTransBB, ThisBB);
Chris Lattner5d1704d2009-09-27 19:57:57 +00002082 Value *InV = 0;
2083 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
Chris Lattnerc6df8f42009-09-27 20:18:49 +00002084 InV = InC->isNullValue() ? FalseVInPred : TrueVInPred;
Chris Lattner5d1704d2009-09-27 19:57:57 +00002085 } else {
2086 assert(PN->getIncomingBlock(i) == NonConstBB);
Chris Lattnerc6df8f42009-09-27 20:18:49 +00002087 InV = SelectInst::Create(PN->getIncomingValue(i), TrueVInPred,
2088 FalseVInPred,
Chris Lattner5d1704d2009-09-27 19:57:57 +00002089 "phitmp", NonConstBB->getTerminator());
Chris Lattner857eb572009-10-21 23:41:58 +00002090 Worklist.Add(cast<Instruction>(InV));
Chris Lattner5d1704d2009-09-27 19:57:57 +00002091 }
Chris Lattnerc6df8f42009-09-27 20:18:49 +00002092 NewPN->addIncoming(InV, ThisBB);
Chris Lattner5d1704d2009-09-27 19:57:57 +00002093 }
2094 } else if (I.getNumOperands() == 2) {
Chris Lattner4e998b22004-09-29 05:07:12 +00002095 Constant *C = cast<Constant>(I.getOperand(1));
Chris Lattnerbac32862004-11-14 19:13:23 +00002096 for (unsigned i = 0; i != NumPHIValues; ++i) {
Chris Lattnera9ff5eb2007-08-05 08:47:58 +00002097 Value *InV = 0;
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002098 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00002099 if (CmpInst *CI = dyn_cast<CmpInst>(&I))
Owen Andersonbaf3c402009-07-29 18:55:55 +00002100 InV = ConstantExpr::getCompare(CI->getPredicate(), InC, C);
Reid Spencere4d87aa2006-12-23 06:05:41 +00002101 else
Owen Andersonbaf3c402009-07-29 18:55:55 +00002102 InV = ConstantExpr::get(I.getOpcode(), InC, C);
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002103 } else {
2104 assert(PN->getIncomingBlock(i) == NonConstBB);
2105 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002106 InV = BinaryOperator::Create(BO->getOpcode(),
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002107 PN->getIncomingValue(i), C, "phitmp",
2108 NonConstBB->getTerminator());
Reid Spencere4d87aa2006-12-23 06:05:41 +00002109 else if (CmpInst *CI = dyn_cast<CmpInst>(&I))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00002110 InV = CmpInst::Create(CI->getOpcode(),
Reid Spencere4d87aa2006-12-23 06:05:41 +00002111 CI->getPredicate(),
2112 PN->getIncomingValue(i), C, "phitmp",
2113 NonConstBB->getTerminator());
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002114 else
Torok Edwinc23197a2009-07-14 16:55:14 +00002115 llvm_unreachable("Unknown binop!");
Chris Lattner857eb572009-10-21 23:41:58 +00002116
2117 Worklist.Add(cast<Instruction>(InV));
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002118 }
2119 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
Chris Lattner4e998b22004-09-29 05:07:12 +00002120 }
Reid Spencer3da59db2006-11-27 01:05:10 +00002121 } else {
2122 CastInst *CI = cast<CastInst>(&I);
2123 const Type *RetTy = CI->getType();
Chris Lattnerbac32862004-11-14 19:13:23 +00002124 for (unsigned i = 0; i != NumPHIValues; ++i) {
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002125 Value *InV;
2126 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00002127 InV = ConstantExpr::getCast(CI->getOpcode(), InC, RetTy);
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002128 } else {
2129 assert(PN->getIncomingBlock(i) == NonConstBB);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002130 InV = CastInst::Create(CI->getOpcode(), PN->getIncomingValue(i),
Reid Spencer3da59db2006-11-27 01:05:10 +00002131 I.getType(), "phitmp",
2132 NonConstBB->getTerminator());
Chris Lattner857eb572009-10-21 23:41:58 +00002133 Worklist.Add(cast<Instruction>(InV));
Chris Lattner2a86f3b2006-09-09 22:02:56 +00002134 }
2135 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
Chris Lattner4e998b22004-09-29 05:07:12 +00002136 }
2137 }
2138 return ReplaceInstUsesWith(I, NewPN);
2139}
2140
Chris Lattner2454a2e2008-01-29 06:52:45 +00002141
Chris Lattner3d28b1b2008-05-20 05:46:13 +00002142/// WillNotOverflowSignedAdd - Return true if we can prove that:
2143/// (sext (add LHS, RHS)) === (add (sext LHS), (sext RHS))
2144/// This basically requires proving that the add in the original type would not
2145/// overflow to change the sign bit or have a carry out.
2146bool InstCombiner::WillNotOverflowSignedAdd(Value *LHS, Value *RHS) {
2147 // There are different heuristics we can use for this. Here are some simple
2148 // ones.
2149
2150 // Add has the property that adding any two 2's complement numbers can only
2151 // have one carry bit which can change a sign. As such, if LHS and RHS each
Chris Lattner8aee8ef2009-11-27 17:42:22 +00002152 // have at least two sign bits, we know that the addition of the two values
2153 // will sign extend fine.
Chris Lattner3d28b1b2008-05-20 05:46:13 +00002154 if (ComputeNumSignBits(LHS) > 1 && ComputeNumSignBits(RHS) > 1)
2155 return true;
2156
2157
2158 // If one of the operands only has one non-zero bit, and if the other operand
2159 // has a known-zero bit in a more significant place than it (not including the
2160 // sign bit) the ripple may go up to and fill the zero, but won't change the
2161 // sign. For example, (X & ~4) + 1.
2162
2163 // TODO: Implement.
2164
2165 return false;
2166}
2167
Chris Lattner2454a2e2008-01-29 06:52:45 +00002168
Chris Lattner7e708292002-06-25 16:13:24 +00002169Instruction *InstCombiner::visitAdd(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00002170 bool Changed = SimplifyCommutative(I);
Chris Lattner7e708292002-06-25 16:13:24 +00002171 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
Chris Lattnerb35dde12002-05-06 16:49:18 +00002172
Chris Lattner8aee8ef2009-11-27 17:42:22 +00002173 if (Value *V = SimplifyAddInst(LHS, RHS, I.hasNoSignedWrap(),
2174 I.hasNoUnsignedWrap(), TD))
2175 return ReplaceInstUsesWith(I, V);
2176
2177
Chris Lattner66331a42004-04-10 22:01:55 +00002178 if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
Chris Lattner66331a42004-04-10 22:01:55 +00002179 if (ConstantInt *CI = dyn_cast<ConstantInt>(RHSC)) {
Chris Lattnerb4a2f052006-11-09 05:12:27 +00002180 // X + (signbit) --> X ^ signbit
Zhou Sheng3a507fd2007-04-01 17:13:37 +00002181 const APInt& Val = CI->getValue();
Zhou Sheng4351c642007-04-02 08:20:41 +00002182 uint32_t BitWidth = Val.getBitWidth();
Reid Spencer2ec619a2007-03-23 21:24:59 +00002183 if (Val == APInt::getSignBit(BitWidth))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002184 return BinaryOperator::CreateXor(LHS, RHS);
Chris Lattnerb4a2f052006-11-09 05:12:27 +00002185
2186 // See if SimplifyDemandedBits can simplify this. This handles stuff like
2187 // (X & 254)+1 -> (X&254)|1
Dan Gohman6de29f82009-06-15 22:12:54 +00002188 if (SimplifyDemandedInstructionBits(I))
Chris Lattner886ab6c2009-01-31 08:15:18 +00002189 return &I;
Dan Gohman1975d032008-10-30 20:40:10 +00002190
Eli Friedman709b33d2009-07-13 22:27:52 +00002191 // zext(bool) + C -> bool ? C + 1 : C
Dan Gohman1975d032008-10-30 20:40:10 +00002192 if (ZExtInst *ZI = dyn_cast<ZExtInst>(LHS))
Owen Anderson1d0be152009-08-13 21:58:54 +00002193 if (ZI->getSrcTy() == Type::getInt1Ty(*Context))
Dan Gohman186a6362009-08-12 16:04:34 +00002194 return SelectInst::Create(ZI->getOperand(0), AddOne(CI), CI);
Chris Lattner66331a42004-04-10 22:01:55 +00002195 }
Chris Lattner4e998b22004-09-29 05:07:12 +00002196
2197 if (isa<PHINode>(LHS))
2198 if (Instruction *NV = FoldOpIntoPhi(I))
2199 return NV;
Chris Lattner5931c542005-09-24 23:43:33 +00002200
Chris Lattner4f637d42006-01-06 17:59:59 +00002201 ConstantInt *XorRHS = 0;
2202 Value *XorLHS = 0;
Chris Lattnerc5eff442007-01-30 22:32:46 +00002203 if (isa<ConstantInt>(RHSC) &&
Dan Gohman4ae51262009-08-12 16:23:25 +00002204 match(LHS, m_Xor(m_Value(XorLHS), m_ConstantInt(XorRHS)))) {
Dan Gohman6de29f82009-06-15 22:12:54 +00002205 uint32_t TySizeBits = I.getType()->getScalarSizeInBits();
Zhou Sheng3a507fd2007-04-01 17:13:37 +00002206 const APInt& RHSVal = cast<ConstantInt>(RHSC)->getValue();
Chris Lattner5931c542005-09-24 23:43:33 +00002207
Zhou Sheng4351c642007-04-02 08:20:41 +00002208 uint32_t Size = TySizeBits / 2;
Reid Spencer2ec619a2007-03-23 21:24:59 +00002209 APInt C0080Val(APInt(TySizeBits, 1ULL).shl(Size - 1));
2210 APInt CFF80Val(-C0080Val);
Chris Lattner5931c542005-09-24 23:43:33 +00002211 do {
2212 if (TySizeBits > Size) {
Chris Lattner5931c542005-09-24 23:43:33 +00002213 // If we have ADD(XOR(AND(X, 0xFF), 0x80), 0xF..F80), it's a sext.
2214 // If we have ADD(XOR(AND(X, 0xFF), 0xF..F80), 0x80), it's a sext.
Reid Spencer2ec619a2007-03-23 21:24:59 +00002215 if ((RHSVal == CFF80Val && XorRHS->getValue() == C0080Val) ||
2216 (RHSVal == C0080Val && XorRHS->getValue() == CFF80Val)) {
Chris Lattner5931c542005-09-24 23:43:33 +00002217 // This is a sign extend if the top bits are known zero.
Zhou Sheng290bec52007-03-29 08:15:12 +00002218 if (!MaskedValueIsZero(XorLHS,
2219 APInt::getHighBitsSet(TySizeBits, TySizeBits - Size)))
Chris Lattner5931c542005-09-24 23:43:33 +00002220 Size = 0; // Not a sign ext, but can't be any others either.
Reid Spencer2ec619a2007-03-23 21:24:59 +00002221 break;
Chris Lattner5931c542005-09-24 23:43:33 +00002222 }
2223 }
2224 Size >>= 1;
Reid Spencer2ec619a2007-03-23 21:24:59 +00002225 C0080Val = APIntOps::lshr(C0080Val, Size);
2226 CFF80Val = APIntOps::ashr(CFF80Val, Size);
2227 } while (Size >= 1);
Chris Lattner5931c542005-09-24 23:43:33 +00002228
Reid Spencer35c38852007-03-28 01:36:16 +00002229 // FIXME: This shouldn't be necessary. When the backends can handle types
Chris Lattner0c7a9a02008-05-19 20:25:04 +00002230 // with funny bit widths then this switch statement should be removed. It
2231 // is just here to get the size of the "middle" type back up to something
2232 // that the back ends can handle.
Reid Spencer35c38852007-03-28 01:36:16 +00002233 const Type *MiddleType = 0;
2234 switch (Size) {
2235 default: break;
Owen Anderson1d0be152009-08-13 21:58:54 +00002236 case 32: MiddleType = Type::getInt32Ty(*Context); break;
2237 case 16: MiddleType = Type::getInt16Ty(*Context); break;
2238 case 8: MiddleType = Type::getInt8Ty(*Context); break;
Reid Spencer35c38852007-03-28 01:36:16 +00002239 }
2240 if (MiddleType) {
Chris Lattner74381062009-08-30 07:44:24 +00002241 Value *NewTrunc = Builder->CreateTrunc(XorLHS, MiddleType, "sext");
Reid Spencer35c38852007-03-28 01:36:16 +00002242 return new SExtInst(NewTrunc, I.getType(), I.getName());
Chris Lattner5931c542005-09-24 23:43:33 +00002243 }
2244 }
Chris Lattner66331a42004-04-10 22:01:55 +00002245 }
Chris Lattnerb35dde12002-05-06 16:49:18 +00002246
Owen Anderson1d0be152009-08-13 21:58:54 +00002247 if (I.getType() == Type::getInt1Ty(*Context))
Nick Lewycky9419ddb2008-05-31 17:59:52 +00002248 return BinaryOperator::CreateXor(LHS, RHS);
2249
Nick Lewycky7d26bd82008-05-23 04:39:38 +00002250 // X + X --> X << 1
Nick Lewycky9419ddb2008-05-31 17:59:52 +00002251 if (I.getType()->isInteger()) {
Dan Gohman4ae51262009-08-12 16:23:25 +00002252 if (Instruction *Result = AssociativeOpt(I, AddRHS(RHS)))
Owen Andersond672ecb2009-07-03 00:17:18 +00002253 return Result;
Chris Lattner7edc8c22005-04-07 17:14:51 +00002254
2255 if (Instruction *RHSI = dyn_cast<Instruction>(RHS)) {
2256 if (RHSI->getOpcode() == Instruction::Sub)
2257 if (LHS == RHSI->getOperand(1)) // A + (B - A) --> B
2258 return ReplaceInstUsesWith(I, RHSI->getOperand(0));
2259 }
2260 if (Instruction *LHSI = dyn_cast<Instruction>(LHS)) {
2261 if (LHSI->getOpcode() == Instruction::Sub)
2262 if (RHS == LHSI->getOperand(1)) // (B - A) + A --> B
2263 return ReplaceInstUsesWith(I, LHSI->getOperand(0));
2264 }
Robert Bocchino71698282004-07-27 21:02:21 +00002265 }
Chris Lattnere92d2f42003-08-13 04:18:28 +00002266
Chris Lattner5c4afb92002-05-08 22:46:53 +00002267 // -A + B --> B - A
Chris Lattnerdd12f962008-02-17 21:03:36 +00002268 // -A + -B --> -(A + B)
Dan Gohman186a6362009-08-12 16:04:34 +00002269 if (Value *LHSV = dyn_castNegVal(LHS)) {
Chris Lattnere10c0b92008-02-18 17:50:16 +00002270 if (LHS->getType()->isIntOrIntVector()) {
Dan Gohman186a6362009-08-12 16:04:34 +00002271 if (Value *RHSV = dyn_castNegVal(RHS)) {
Chris Lattner74381062009-08-30 07:44:24 +00002272 Value *NewAdd = Builder->CreateAdd(LHSV, RHSV, "sum");
Dan Gohman4ae51262009-08-12 16:23:25 +00002273 return BinaryOperator::CreateNeg(NewAdd);
Chris Lattnere10c0b92008-02-18 17:50:16 +00002274 }
Chris Lattnerdd12f962008-02-17 21:03:36 +00002275 }
2276
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002277 return BinaryOperator::CreateSub(RHS, LHSV);
Chris Lattnerdd12f962008-02-17 21:03:36 +00002278 }
Chris Lattnerb35dde12002-05-06 16:49:18 +00002279
2280 // A + -B --> A - B
Chris Lattner8d969642003-03-10 23:06:50 +00002281 if (!isa<Constant>(RHS))
Dan Gohman186a6362009-08-12 16:04:34 +00002282 if (Value *V = dyn_castNegVal(RHS))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002283 return BinaryOperator::CreateSub(LHS, V);
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002284
Misha Brukmanfd939082005-04-21 23:48:37 +00002285
Chris Lattner50af16a2004-11-13 19:50:12 +00002286 ConstantInt *C2;
Dan Gohman186a6362009-08-12 16:04:34 +00002287 if (Value *X = dyn_castFoldableMul(LHS, C2)) {
Chris Lattner50af16a2004-11-13 19:50:12 +00002288 if (X == RHS) // X*C + X --> X * (C+1)
Dan Gohman186a6362009-08-12 16:04:34 +00002289 return BinaryOperator::CreateMul(RHS, AddOne(C2));
Chris Lattner50af16a2004-11-13 19:50:12 +00002290
2291 // X*C1 + X*C2 --> X * (C1+C2)
2292 ConstantInt *C1;
Dan Gohman186a6362009-08-12 16:04:34 +00002293 if (X == dyn_castFoldableMul(RHS, C1))
Owen Andersonbaf3c402009-07-29 18:55:55 +00002294 return BinaryOperator::CreateMul(X, ConstantExpr::getAdd(C1, C2));
Chris Lattnerad3448c2003-02-18 19:57:07 +00002295 }
2296
2297 // X + X*C --> X * (C+1)
Dan Gohman186a6362009-08-12 16:04:34 +00002298 if (dyn_castFoldableMul(RHS, C2) == LHS)
2299 return BinaryOperator::CreateMul(LHS, AddOne(C2));
Chris Lattner50af16a2004-11-13 19:50:12 +00002300
Chris Lattnere617c9e2007-01-05 02:17:46 +00002301 // X + ~X --> -1 since ~X = -X-1
Dan Gohman186a6362009-08-12 16:04:34 +00002302 if (dyn_castNotVal(LHS) == RHS ||
2303 dyn_castNotVal(RHS) == LHS)
Owen Andersona7235ea2009-07-31 20:28:14 +00002304 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Chris Lattnere617c9e2007-01-05 02:17:46 +00002305
Chris Lattnerad3448c2003-02-18 19:57:07 +00002306
Chris Lattner564a7272003-08-13 19:01:45 +00002307 // (A & C1)+(B & C2) --> (A & C1)|(B & C2) iff C1&C2 == 0
Dan Gohman4ae51262009-08-12 16:23:25 +00002308 if (match(RHS, m_And(m_Value(), m_ConstantInt(C2))))
2309 if (Instruction *R = AssociativeOpt(I, AddMaskingAnd(C2)))
Chris Lattnere617c9e2007-01-05 02:17:46 +00002310 return R;
Chris Lattner5e0d7182008-05-19 20:01:56 +00002311
2312 // A+B --> A|B iff A and B have no bits set in common.
2313 if (const IntegerType *IT = dyn_cast<IntegerType>(I.getType())) {
2314 APInt Mask = APInt::getAllOnesValue(IT->getBitWidth());
2315 APInt LHSKnownOne(IT->getBitWidth(), 0);
2316 APInt LHSKnownZero(IT->getBitWidth(), 0);
2317 ComputeMaskedBits(LHS, Mask, LHSKnownZero, LHSKnownOne);
2318 if (LHSKnownZero != 0) {
2319 APInt RHSKnownOne(IT->getBitWidth(), 0);
2320 APInt RHSKnownZero(IT->getBitWidth(), 0);
2321 ComputeMaskedBits(RHS, Mask, RHSKnownZero, RHSKnownOne);
2322
2323 // No bits in common -> bitwise or.
Chris Lattner9d60ba92008-05-19 20:03:53 +00002324 if ((LHSKnownZero|RHSKnownZero).isAllOnesValue())
Chris Lattner5e0d7182008-05-19 20:01:56 +00002325 return BinaryOperator::CreateOr(LHS, RHS);
Chris Lattner5e0d7182008-05-19 20:01:56 +00002326 }
2327 }
Chris Lattnerc8802d22003-03-11 00:12:48 +00002328
Nick Lewyckyb6eabff2008-02-03 07:42:09 +00002329 // W*X + Y*Z --> W * (X+Z) iff W == Y
Nick Lewycky0c2c3f62008-02-03 08:19:11 +00002330 if (I.getType()->isIntOrIntVector()) {
Nick Lewyckyb6eabff2008-02-03 07:42:09 +00002331 Value *W, *X, *Y, *Z;
Dan Gohman4ae51262009-08-12 16:23:25 +00002332 if (match(LHS, m_Mul(m_Value(W), m_Value(X))) &&
2333 match(RHS, m_Mul(m_Value(Y), m_Value(Z)))) {
Nick Lewyckyb6eabff2008-02-03 07:42:09 +00002334 if (W != Y) {
2335 if (W == Z) {
Bill Wendling587c01d2008-02-26 10:53:30 +00002336 std::swap(Y, Z);
Nick Lewyckyb6eabff2008-02-03 07:42:09 +00002337 } else if (Y == X) {
Bill Wendling587c01d2008-02-26 10:53:30 +00002338 std::swap(W, X);
2339 } else if (X == Z) {
Nick Lewyckyb6eabff2008-02-03 07:42:09 +00002340 std::swap(Y, Z);
2341 std::swap(W, X);
2342 }
2343 }
2344
2345 if (W == Y) {
Chris Lattner74381062009-08-30 07:44:24 +00002346 Value *NewAdd = Builder->CreateAdd(X, Z, LHS->getName());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002347 return BinaryOperator::CreateMul(W, NewAdd);
Nick Lewyckyb6eabff2008-02-03 07:42:09 +00002348 }
2349 }
2350 }
2351
Chris Lattner6b032052003-10-02 15:11:26 +00002352 if (ConstantInt *CRHS = dyn_cast<ConstantInt>(RHS)) {
Chris Lattner4f637d42006-01-06 17:59:59 +00002353 Value *X = 0;
Dan Gohman4ae51262009-08-12 16:23:25 +00002354 if (match(LHS, m_Not(m_Value(X)))) // ~X + C --> (C-1) - X
Dan Gohman186a6362009-08-12 16:04:34 +00002355 return BinaryOperator::CreateSub(SubOne(CRHS), X);
Chris Lattneracd1f0f2004-07-30 07:50:03 +00002356
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002357 // (X & FF00) + xx00 -> (X+xx00) & FF00
Owen Andersonc7d2ce72009-07-10 17:35:01 +00002358 if (LHS->hasOneUse() &&
Dan Gohman4ae51262009-08-12 16:23:25 +00002359 match(LHS, m_And(m_Value(X), m_ConstantInt(C2)))) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00002360 Constant *Anded = ConstantExpr::getAnd(CRHS, C2);
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002361 if (Anded == CRHS) {
2362 // See if all bits from the first bit set in the Add RHS up are included
2363 // in the mask. First, get the rightmost bit.
Zhou Sheng3a507fd2007-04-01 17:13:37 +00002364 const APInt& AddRHSV = CRHS->getValue();
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002365
2366 // Form a mask of all bits from the lowest bit added through the top.
Zhou Sheng3a507fd2007-04-01 17:13:37 +00002367 APInt AddRHSHighBits(~((AddRHSV & -AddRHSV)-1));
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002368
2369 // See if the and mask includes all of these bits.
Zhou Sheng3a507fd2007-04-01 17:13:37 +00002370 APInt AddRHSHighBitsAnd(AddRHSHighBits & C2->getValue());
Misha Brukmanfd939082005-04-21 23:48:37 +00002371
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002372 if (AddRHSHighBits == AddRHSHighBitsAnd) {
2373 // Okay, the xform is safe. Insert the new add pronto.
Chris Lattner74381062009-08-30 07:44:24 +00002374 Value *NewAdd = Builder->CreateAdd(X, CRHS, LHS->getName());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002375 return BinaryOperator::CreateAnd(NewAdd, C2);
Chris Lattnerb99d6b12004-10-08 05:07:56 +00002376 }
2377 }
2378 }
2379
Chris Lattneracd1f0f2004-07-30 07:50:03 +00002380 // Try to fold constant add into select arguments.
2381 if (SelectInst *SI = dyn_cast<SelectInst>(LHS))
Chris Lattner6e7ba452005-01-01 16:22:27 +00002382 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattneracd1f0f2004-07-30 07:50:03 +00002383 return R;
Chris Lattner6b032052003-10-02 15:11:26 +00002384 }
2385
Chris Lattner42790482007-12-20 01:56:58 +00002386 // add (select X 0 (sub n A)) A --> select X A n
Christopher Lamb30f017a2007-12-18 09:34:41 +00002387 {
2388 SelectInst *SI = dyn_cast<SelectInst>(LHS);
Chris Lattner6046fb72008-11-16 04:46:19 +00002389 Value *A = RHS;
Christopher Lamb30f017a2007-12-18 09:34:41 +00002390 if (!SI) {
2391 SI = dyn_cast<SelectInst>(RHS);
Chris Lattner6046fb72008-11-16 04:46:19 +00002392 A = LHS;
Christopher Lamb30f017a2007-12-18 09:34:41 +00002393 }
Chris Lattner42790482007-12-20 01:56:58 +00002394 if (SI && SI->hasOneUse()) {
Christopher Lamb30f017a2007-12-18 09:34:41 +00002395 Value *TV = SI->getTrueValue();
2396 Value *FV = SI->getFalseValue();
Chris Lattner6046fb72008-11-16 04:46:19 +00002397 Value *N;
Christopher Lamb30f017a2007-12-18 09:34:41 +00002398
2399 // Can we fold the add into the argument of the select?
2400 // We check both true and false select arguments for a matching subtract.
Dan Gohman4ae51262009-08-12 16:23:25 +00002401 if (match(FV, m_Zero()) &&
2402 match(TV, m_Sub(m_Value(N), m_Specific(A))))
Chris Lattner6046fb72008-11-16 04:46:19 +00002403 // Fold the add into the true select value.
Gabor Greif051a9502008-04-06 20:25:17 +00002404 return SelectInst::Create(SI->getCondition(), N, A);
Dan Gohman4ae51262009-08-12 16:23:25 +00002405 if (match(TV, m_Zero()) &&
2406 match(FV, m_Sub(m_Value(N), m_Specific(A))))
Chris Lattner6046fb72008-11-16 04:46:19 +00002407 // Fold the add into the false select value.
Gabor Greif051a9502008-04-06 20:25:17 +00002408 return SelectInst::Create(SI->getCondition(), A, N);
Christopher Lamb30f017a2007-12-18 09:34:41 +00002409 }
2410 }
Andrew Lenharth16d79552006-09-19 18:24:51 +00002411
Chris Lattner3d28b1b2008-05-20 05:46:13 +00002412 // Check for (add (sext x), y), see if we can merge this into an
2413 // integer add followed by a sext.
2414 if (SExtInst *LHSConv = dyn_cast<SExtInst>(LHS)) {
2415 // (add (sext x), cst) --> (sext (add x, cst'))
2416 if (ConstantInt *RHSC = dyn_cast<ConstantInt>(RHS)) {
2417 Constant *CI =
Owen Andersonbaf3c402009-07-29 18:55:55 +00002418 ConstantExpr::getTrunc(RHSC, LHSConv->getOperand(0)->getType());
Chris Lattner3d28b1b2008-05-20 05:46:13 +00002419 if (LHSConv->hasOneUse() &&
Owen Andersonbaf3c402009-07-29 18:55:55 +00002420 ConstantExpr::getSExt(CI, I.getType()) == RHSC &&
Chris Lattner3d28b1b2008-05-20 05:46:13 +00002421 WillNotOverflowSignedAdd(LHSConv->getOperand(0), CI)) {
2422 // Insert the new, smaller add.
Dan Gohmanfe359552009-10-26 22:14:22 +00002423 Value *NewAdd = Builder->CreateNSWAdd(LHSConv->getOperand(0),
2424 CI, "addconv");
Chris Lattner3d28b1b2008-05-20 05:46:13 +00002425 return new SExtInst(NewAdd, I.getType());
2426 }
2427 }
2428
2429 // (add (sext x), (sext y)) --> (sext (add int x, y))
2430 if (SExtInst *RHSConv = dyn_cast<SExtInst>(RHS)) {
2431 // Only do this if x/y have the same type, if at last one of them has a
2432 // single use (so we don't increase the number of sexts), and if the
2433 // integer add will not overflow.
2434 if (LHSConv->getOperand(0)->getType()==RHSConv->getOperand(0)->getType()&&
2435 (LHSConv->hasOneUse() || RHSConv->hasOneUse()) &&
2436 WillNotOverflowSignedAdd(LHSConv->getOperand(0),
2437 RHSConv->getOperand(0))) {
2438 // Insert the new integer add.
Dan Gohmanfe359552009-10-26 22:14:22 +00002439 Value *NewAdd = Builder->CreateNSWAdd(LHSConv->getOperand(0),
2440 RHSConv->getOperand(0), "addconv");
Chris Lattner3d28b1b2008-05-20 05:46:13 +00002441 return new SExtInst(NewAdd, I.getType());
2442 }
2443 }
2444 }
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002445
2446 return Changed ? &I : 0;
2447}
2448
2449Instruction *InstCombiner::visitFAdd(BinaryOperator &I) {
2450 bool Changed = SimplifyCommutative(I);
2451 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
2452
2453 if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
2454 // X + 0 --> X
2455 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
Owen Anderson6f83c9c2009-07-27 20:59:43 +00002456 if (CFP->isExactlyValue(ConstantFP::getNegativeZero
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002457 (I.getType())->getValueAPF()))
2458 return ReplaceInstUsesWith(I, LHS);
2459 }
2460
2461 if (isa<PHINode>(LHS))
2462 if (Instruction *NV = FoldOpIntoPhi(I))
2463 return NV;
2464 }
2465
2466 // -A + B --> B - A
2467 // -A + -B --> -(A + B)
Dan Gohman186a6362009-08-12 16:04:34 +00002468 if (Value *LHSV = dyn_castFNegVal(LHS))
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002469 return BinaryOperator::CreateFSub(RHS, LHSV);
2470
2471 // A + -B --> A - B
2472 if (!isa<Constant>(RHS))
Dan Gohman186a6362009-08-12 16:04:34 +00002473 if (Value *V = dyn_castFNegVal(RHS))
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002474 return BinaryOperator::CreateFSub(LHS, V);
2475
2476 // Check for X+0.0. Simplify it to X if we know X is not -0.0.
2477 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHS))
2478 if (CFP->getValueAPF().isPosZero() && CannotBeNegativeZero(LHS))
2479 return ReplaceInstUsesWith(I, LHS);
2480
Chris Lattner3d28b1b2008-05-20 05:46:13 +00002481 // Check for (add double (sitofp x), y), see if we can merge this into an
2482 // integer add followed by a promotion.
2483 if (SIToFPInst *LHSConv = dyn_cast<SIToFPInst>(LHS)) {
2484 // (add double (sitofp x), fpcst) --> (sitofp (add int x, intcst))
2485 // ... if the constant fits in the integer value. This is useful for things
2486 // like (double)(x & 1234) + 4.0 -> (double)((X & 1234)+4) which no longer
2487 // requires a constant pool load, and generally allows the add to be better
2488 // instcombined.
2489 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHS)) {
2490 Constant *CI =
Owen Andersonbaf3c402009-07-29 18:55:55 +00002491 ConstantExpr::getFPToSI(CFP, LHSConv->getOperand(0)->getType());
Chris Lattner3d28b1b2008-05-20 05:46:13 +00002492 if (LHSConv->hasOneUse() &&
Owen Andersonbaf3c402009-07-29 18:55:55 +00002493 ConstantExpr::getSIToFP(CI, I.getType()) == CFP &&
Chris Lattner3d28b1b2008-05-20 05:46:13 +00002494 WillNotOverflowSignedAdd(LHSConv->getOperand(0), CI)) {
2495 // Insert the new integer add.
Dan Gohmanfe359552009-10-26 22:14:22 +00002496 Value *NewAdd = Builder->CreateNSWAdd(LHSConv->getOperand(0),
2497 CI, "addconv");
Chris Lattner3d28b1b2008-05-20 05:46:13 +00002498 return new SIToFPInst(NewAdd, I.getType());
2499 }
2500 }
2501
2502 // (add double (sitofp x), (sitofp y)) --> (sitofp (add int x, y))
2503 if (SIToFPInst *RHSConv = dyn_cast<SIToFPInst>(RHS)) {
2504 // Only do this if x/y have the same type, if at last one of them has a
2505 // single use (so we don't increase the number of int->fp conversions),
2506 // and if the integer add will not overflow.
2507 if (LHSConv->getOperand(0)->getType()==RHSConv->getOperand(0)->getType()&&
2508 (LHSConv->hasOneUse() || RHSConv->hasOneUse()) &&
2509 WillNotOverflowSignedAdd(LHSConv->getOperand(0),
2510 RHSConv->getOperand(0))) {
2511 // Insert the new integer add.
Dan Gohmanfe359552009-10-26 22:14:22 +00002512 Value *NewAdd = Builder->CreateNSWAdd(LHSConv->getOperand(0),
Chris Lattner092543c2009-11-04 08:05:20 +00002513 RHSConv->getOperand(0),"addconv");
Chris Lattner3d28b1b2008-05-20 05:46:13 +00002514 return new SIToFPInst(NewAdd, I.getType());
2515 }
2516 }
2517 }
2518
Chris Lattner7e708292002-06-25 16:13:24 +00002519 return Changed ? &I : 0;
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002520}
2521
Chris Lattner092543c2009-11-04 08:05:20 +00002522
2523/// EmitGEPOffset - Given a getelementptr instruction/constantexpr, emit the
2524/// code necessary to compute the offset from the base pointer (without adding
2525/// in the base pointer). Return the result as a signed integer of intptr size.
2526static Value *EmitGEPOffset(User *GEP, InstCombiner &IC) {
2527 TargetData &TD = *IC.getTargetData();
2528 gep_type_iterator GTI = gep_type_begin(GEP);
2529 const Type *IntPtrTy = TD.getIntPtrType(GEP->getContext());
2530 Value *Result = Constant::getNullValue(IntPtrTy);
2531
2532 // Build a mask for high order bits.
2533 unsigned IntPtrWidth = TD.getPointerSizeInBits();
2534 uint64_t PtrSizeMask = ~0ULL >> (64-IntPtrWidth);
2535
2536 for (User::op_iterator i = GEP->op_begin() + 1, e = GEP->op_end(); i != e;
2537 ++i, ++GTI) {
2538 Value *Op = *i;
2539 uint64_t Size = TD.getTypeAllocSize(GTI.getIndexedType()) & PtrSizeMask;
2540 if (ConstantInt *OpC = dyn_cast<ConstantInt>(Op)) {
2541 if (OpC->isZero()) continue;
2542
2543 // Handle a struct index, which adds its field offset to the pointer.
2544 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
2545 Size = TD.getStructLayout(STy)->getElementOffset(OpC->getZExtValue());
2546
2547 Result = IC.Builder->CreateAdd(Result,
2548 ConstantInt::get(IntPtrTy, Size),
2549 GEP->getName()+".offs");
2550 continue;
2551 }
2552
2553 Constant *Scale = ConstantInt::get(IntPtrTy, Size);
2554 Constant *OC =
2555 ConstantExpr::getIntegerCast(OpC, IntPtrTy, true /*SExt*/);
2556 Scale = ConstantExpr::getMul(OC, Scale);
2557 // Emit an add instruction.
2558 Result = IC.Builder->CreateAdd(Result, Scale, GEP->getName()+".offs");
2559 continue;
2560 }
2561 // Convert to correct type.
2562 if (Op->getType() != IntPtrTy)
2563 Op = IC.Builder->CreateIntCast(Op, IntPtrTy, true, Op->getName()+".c");
2564 if (Size != 1) {
2565 Constant *Scale = ConstantInt::get(IntPtrTy, Size);
2566 // We'll let instcombine(mul) convert this to a shl if possible.
2567 Op = IC.Builder->CreateMul(Op, Scale, GEP->getName()+".idx");
2568 }
2569
2570 // Emit an add instruction.
2571 Result = IC.Builder->CreateAdd(Op, Result, GEP->getName()+".offs");
2572 }
2573 return Result;
2574}
2575
2576
2577/// EvaluateGEPOffsetExpression - Return a value that can be used to compare
2578/// the *offset* implied by a GEP to zero. For example, if we have &A[i], we
2579/// want to return 'i' for "icmp ne i, 0". Note that, in general, indices can
2580/// be complex, and scales are involved. The above expression would also be
2581/// legal to codegen as "icmp ne (i*4), 0" (assuming A is a pointer to i32).
2582/// This later form is less amenable to optimization though, and we are allowed
2583/// to generate the first by knowing that pointer arithmetic doesn't overflow.
2584///
2585/// If we can't emit an optimized form for this expression, this returns null.
2586///
2587static Value *EvaluateGEPOffsetExpression(User *GEP, Instruction &I,
2588 InstCombiner &IC) {
2589 TargetData &TD = *IC.getTargetData();
2590 gep_type_iterator GTI = gep_type_begin(GEP);
2591
2592 // Check to see if this gep only has a single variable index. If so, and if
2593 // any constant indices are a multiple of its scale, then we can compute this
2594 // in terms of the scale of the variable index. For example, if the GEP
2595 // implies an offset of "12 + i*4", then we can codegen this as "3 + i",
2596 // because the expression will cross zero at the same point.
2597 unsigned i, e = GEP->getNumOperands();
2598 int64_t Offset = 0;
2599 for (i = 1; i != e; ++i, ++GTI) {
2600 if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i))) {
2601 // Compute the aggregate offset of constant indices.
2602 if (CI->isZero()) continue;
2603
2604 // Handle a struct index, which adds its field offset to the pointer.
2605 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
2606 Offset += TD.getStructLayout(STy)->getElementOffset(CI->getZExtValue());
2607 } else {
2608 uint64_t Size = TD.getTypeAllocSize(GTI.getIndexedType());
2609 Offset += Size*CI->getSExtValue();
2610 }
2611 } else {
2612 // Found our variable index.
2613 break;
2614 }
2615 }
2616
2617 // If there are no variable indices, we must have a constant offset, just
2618 // evaluate it the general way.
2619 if (i == e) return 0;
2620
2621 Value *VariableIdx = GEP->getOperand(i);
2622 // Determine the scale factor of the variable element. For example, this is
2623 // 4 if the variable index is into an array of i32.
2624 uint64_t VariableScale = TD.getTypeAllocSize(GTI.getIndexedType());
2625
2626 // Verify that there are no other variable indices. If so, emit the hard way.
2627 for (++i, ++GTI; i != e; ++i, ++GTI) {
2628 ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i));
2629 if (!CI) return 0;
2630
2631 // Compute the aggregate offset of constant indices.
2632 if (CI->isZero()) continue;
2633
2634 // Handle a struct index, which adds its field offset to the pointer.
2635 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
2636 Offset += TD.getStructLayout(STy)->getElementOffset(CI->getZExtValue());
2637 } else {
2638 uint64_t Size = TD.getTypeAllocSize(GTI.getIndexedType());
2639 Offset += Size*CI->getSExtValue();
2640 }
2641 }
2642
2643 // Okay, we know we have a single variable index, which must be a
2644 // pointer/array/vector index. If there is no offset, life is simple, return
2645 // the index.
2646 unsigned IntPtrWidth = TD.getPointerSizeInBits();
2647 if (Offset == 0) {
2648 // Cast to intptrty in case a truncation occurs. If an extension is needed,
2649 // we don't need to bother extending: the extension won't affect where the
2650 // computation crosses zero.
2651 if (VariableIdx->getType()->getPrimitiveSizeInBits() > IntPtrWidth)
2652 VariableIdx = new TruncInst(VariableIdx,
2653 TD.getIntPtrType(VariableIdx->getContext()),
2654 VariableIdx->getName(), &I);
2655 return VariableIdx;
2656 }
2657
2658 // Otherwise, there is an index. The computation we will do will be modulo
2659 // the pointer size, so get it.
2660 uint64_t PtrSizeMask = ~0ULL >> (64-IntPtrWidth);
2661
2662 Offset &= PtrSizeMask;
2663 VariableScale &= PtrSizeMask;
2664
2665 // To do this transformation, any constant index must be a multiple of the
2666 // variable scale factor. For example, we can evaluate "12 + 4*i" as "3 + i",
2667 // but we can't evaluate "10 + 3*i" in terms of i. Check that the offset is a
2668 // multiple of the variable scale.
2669 int64_t NewOffs = Offset / (int64_t)VariableScale;
2670 if (Offset != NewOffs*(int64_t)VariableScale)
2671 return 0;
2672
2673 // Okay, we can do this evaluation. Start by converting the index to intptr.
2674 const Type *IntPtrTy = TD.getIntPtrType(VariableIdx->getContext());
2675 if (VariableIdx->getType() != IntPtrTy)
2676 VariableIdx = CastInst::CreateIntegerCast(VariableIdx, IntPtrTy,
2677 true /*SExt*/,
2678 VariableIdx->getName(), &I);
2679 Constant *OffsetVal = ConstantInt::get(IntPtrTy, NewOffs);
2680 return BinaryOperator::CreateAdd(VariableIdx, OffsetVal, "offset", &I);
2681}
2682
2683
2684/// Optimize pointer differences into the same array into a size. Consider:
2685/// &A[10] - &A[0]: we should compile this to "10". LHS/RHS are the pointer
2686/// operands to the ptrtoint instructions for the LHS/RHS of the subtract.
2687///
2688Value *InstCombiner::OptimizePointerDifference(Value *LHS, Value *RHS,
2689 const Type *Ty) {
2690 assert(TD && "Must have target data info for this");
2691
2692 // If LHS is a gep based on RHS or RHS is a gep based on LHS, we can optimize
2693 // this.
2694 bool Swapped;
Chris Lattner85c1c962010-01-01 22:42:29 +00002695 GetElementPtrInst *GEP = 0;
2696 ConstantExpr *CstGEP = 0;
Chris Lattner092543c2009-11-04 08:05:20 +00002697
Chris Lattner85c1c962010-01-01 22:42:29 +00002698 // TODO: Could also optimize &A[i] - &A[j] -> "i-j", and "&A.foo[i] - &A.foo".
2699 // For now we require one side to be the base pointer "A" or a constant
2700 // expression derived from it.
2701 if (GetElementPtrInst *LHSGEP = dyn_cast<GetElementPtrInst>(LHS)) {
2702 // (gep X, ...) - X
2703 if (LHSGEP->getOperand(0) == RHS) {
2704 GEP = LHSGEP;
2705 Swapped = false;
2706 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(RHS)) {
2707 // (gep X, ...) - (ce_gep X, ...)
2708 if (CE->getOpcode() == Instruction::GetElementPtr &&
2709 LHSGEP->getOperand(0) == CE->getOperand(0)) {
2710 CstGEP = CE;
2711 GEP = LHSGEP;
2712 Swapped = false;
2713 }
2714 }
2715 }
2716
2717 if (GetElementPtrInst *RHSGEP = dyn_cast<GetElementPtrInst>(RHS)) {
2718 // X - (gep X, ...)
2719 if (RHSGEP->getOperand(0) == LHS) {
2720 GEP = RHSGEP;
2721 Swapped = true;
2722 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(LHS)) {
2723 // (ce_gep X, ...) - (gep X, ...)
2724 if (CE->getOpcode() == Instruction::GetElementPtr &&
2725 RHSGEP->getOperand(0) == CE->getOperand(0)) {
2726 CstGEP = CE;
2727 GEP = RHSGEP;
2728 Swapped = true;
2729 }
2730 }
2731 }
2732
2733 if (GEP == 0)
Chris Lattner092543c2009-11-04 08:05:20 +00002734 return 0;
2735
Chris Lattner092543c2009-11-04 08:05:20 +00002736 // Emit the offset of the GEP and an intptr_t.
2737 Value *Result = EmitGEPOffset(GEP, *this);
Chris Lattner85c1c962010-01-01 22:42:29 +00002738
2739 // If we had a constant expression GEP on the other side offsetting the
2740 // pointer, subtract it from the offset we have.
2741 if (CstGEP) {
2742 Value *CstOffset = EmitGEPOffset(CstGEP, *this);
2743 Result = Builder->CreateSub(Result, CstOffset);
2744 }
2745
Chris Lattner092543c2009-11-04 08:05:20 +00002746
2747 // If we have p - gep(p, ...) then we have to negate the result.
2748 if (Swapped)
2749 Result = Builder->CreateNeg(Result, "diff.neg");
2750
2751 return Builder->CreateIntCast(Result, Ty, true);
2752}
2753
2754
Chris Lattner7e708292002-06-25 16:13:24 +00002755Instruction *InstCombiner::visitSub(BinaryOperator &I) {
Chris Lattner7e708292002-06-25 16:13:24 +00002756 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00002757
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002758 if (Op0 == Op1) // sub X, X -> 0
Owen Andersona7235ea2009-07-31 20:28:14 +00002759 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002760
Chris Lattner3bf68152009-12-21 04:04:05 +00002761 // If this is a 'B = x-(-A)', change to B = x+A. This preserves NSW/NUW.
2762 if (Value *V = dyn_castNegVal(Op1)) {
2763 BinaryOperator *Res = BinaryOperator::CreateAdd(Op0, V);
2764 Res->setHasNoSignedWrap(I.hasNoSignedWrap());
2765 Res->setHasNoUnsignedWrap(I.hasNoUnsignedWrap());
2766 return Res;
2767 }
Chris Lattnerb35dde12002-05-06 16:49:18 +00002768
Chris Lattnere87597f2004-10-16 18:11:37 +00002769 if (isa<UndefValue>(Op0))
2770 return ReplaceInstUsesWith(I, Op0); // undef - X -> undef
2771 if (isa<UndefValue>(Op1))
2772 return ReplaceInstUsesWith(I, Op1); // X - undef -> undef
Chris Lattner092543c2009-11-04 08:05:20 +00002773 if (I.getType() == Type::getInt1Ty(*Context))
2774 return BinaryOperator::CreateXor(Op0, Op1);
2775
Chris Lattnerd65460f2003-11-05 01:06:05 +00002776 if (ConstantInt *C = dyn_cast<ConstantInt>(Op0)) {
Chris Lattner092543c2009-11-04 08:05:20 +00002777 // Replace (-1 - A) with (~A).
Chris Lattnera2881962003-02-18 19:28:33 +00002778 if (C->isAllOnesValue())
Dan Gohman4ae51262009-08-12 16:23:25 +00002779 return BinaryOperator::CreateNot(Op1);
Chris Lattner40371712002-05-09 01:29:19 +00002780
Chris Lattnerd65460f2003-11-05 01:06:05 +00002781 // C - ~X == X + (1+C)
Reid Spencer4b828e62005-06-18 17:37:34 +00002782 Value *X = 0;
Dan Gohman4ae51262009-08-12 16:23:25 +00002783 if (match(Op1, m_Not(m_Value(X))))
Dan Gohman186a6362009-08-12 16:04:34 +00002784 return BinaryOperator::CreateAdd(X, AddOne(C));
Reid Spencer7177c3a2007-03-25 05:33:51 +00002785
Chris Lattner76b7a062007-01-15 07:02:54 +00002786 // -(X >>u 31) -> (X >>s 31)
2787 // -(X >>s 31) -> (X >>u 31)
Zhou Sheng302748d2007-03-30 17:20:39 +00002788 if (C->isZero()) {
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00002789 if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op1)) {
Reid Spencer3822ff52006-11-08 06:47:33 +00002790 if (SI->getOpcode() == Instruction::LShr) {
Reid Spencerb83eb642006-10-20 07:07:24 +00002791 if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
Chris Lattner9c290672004-03-12 23:53:13 +00002792 // Check to see if we are shifting out everything but the sign bit.
Zhou Sheng302748d2007-03-30 17:20:39 +00002793 if (CU->getLimitedValue(SI->getType()->getPrimitiveSizeInBits()) ==
Reid Spencerb83eb642006-10-20 07:07:24 +00002794 SI->getType()->getPrimitiveSizeInBits()-1) {
Reid Spencer3822ff52006-11-08 06:47:33 +00002795 // Ok, the transformation is safe. Insert AShr.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002796 return BinaryOperator::Create(Instruction::AShr,
Reid Spencer832254e2007-02-02 02:16:23 +00002797 SI->getOperand(0), CU, SI->getName());
Chris Lattner9c290672004-03-12 23:53:13 +00002798 }
2799 }
Chris Lattner092543c2009-11-04 08:05:20 +00002800 } else if (SI->getOpcode() == Instruction::AShr) {
Reid Spencer3822ff52006-11-08 06:47:33 +00002801 if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
2802 // Check to see if we are shifting out everything but the sign bit.
Zhou Sheng302748d2007-03-30 17:20:39 +00002803 if (CU->getLimitedValue(SI->getType()->getPrimitiveSizeInBits()) ==
Reid Spencer3822ff52006-11-08 06:47:33 +00002804 SI->getType()->getPrimitiveSizeInBits()-1) {
Reid Spencerc5b206b2006-12-31 05:48:39 +00002805 // Ok, the transformation is safe. Insert LShr.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002806 return BinaryOperator::CreateLShr(
Reid Spencer832254e2007-02-02 02:16:23 +00002807 SI->getOperand(0), CU, SI->getName());
Reid Spencer3822ff52006-11-08 06:47:33 +00002808 }
2809 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00002810 }
2811 }
Chris Lattnerbfe492b2004-03-13 00:11:49 +00002812 }
Chris Lattner2eefe512004-04-09 19:05:30 +00002813
2814 // Try to fold constant sub into select arguments.
2815 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
Chris Lattner6e7ba452005-01-01 16:22:27 +00002816 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00002817 return R;
Eli Friedman709b33d2009-07-13 22:27:52 +00002818
2819 // C - zext(bool) -> bool ? C - 1 : C
2820 if (ZExtInst *ZI = dyn_cast<ZExtInst>(Op1))
Owen Anderson1d0be152009-08-13 21:58:54 +00002821 if (ZI->getSrcTy() == Type::getInt1Ty(*Context))
Dan Gohman186a6362009-08-12 16:04:34 +00002822 return SelectInst::Create(ZI->getOperand(0), SubOne(C), C);
Chris Lattnerd65460f2003-11-05 01:06:05 +00002823 }
2824
Chris Lattner43d84d62005-04-07 16:15:25 +00002825 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002826 if (Op1I->getOpcode() == Instruction::Add) {
Chris Lattner08954a22005-04-07 16:28:01 +00002827 if (Op1I->getOperand(0) == Op0) // X-(X+Y) == -Y
Dan Gohman4ae51262009-08-12 16:23:25 +00002828 return BinaryOperator::CreateNeg(Op1I->getOperand(1),
Owen Anderson0a5372e2009-07-13 04:09:18 +00002829 I.getName());
Chris Lattner08954a22005-04-07 16:28:01 +00002830 else if (Op1I->getOperand(1) == Op0) // X-(Y+X) == -Y
Dan Gohman4ae51262009-08-12 16:23:25 +00002831 return BinaryOperator::CreateNeg(Op1I->getOperand(0),
Owen Anderson0a5372e2009-07-13 04:09:18 +00002832 I.getName());
Chris Lattner08954a22005-04-07 16:28:01 +00002833 else if (ConstantInt *CI1 = dyn_cast<ConstantInt>(I.getOperand(0))) {
2834 if (ConstantInt *CI2 = dyn_cast<ConstantInt>(Op1I->getOperand(1)))
2835 // C1-(X+C2) --> (C1-C2)-X
Owen Andersond672ecb2009-07-03 00:17:18 +00002836 return BinaryOperator::CreateSub(
Owen Andersonbaf3c402009-07-29 18:55:55 +00002837 ConstantExpr::getSub(CI1, CI2), Op1I->getOperand(0));
Chris Lattner08954a22005-04-07 16:28:01 +00002838 }
Chris Lattner43d84d62005-04-07 16:15:25 +00002839 }
2840
Chris Lattnerfd059242003-10-15 16:48:29 +00002841 if (Op1I->hasOneUse()) {
Chris Lattnera2881962003-02-18 19:28:33 +00002842 // Replace (x - (y - z)) with (x + (z - y)) if the (y - z) subexpression
2843 // is not used by anyone else...
2844 //
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002845 if (Op1I->getOpcode() == Instruction::Sub) {
Chris Lattnera2881962003-02-18 19:28:33 +00002846 // Swap the two operands of the subexpr...
2847 Value *IIOp0 = Op1I->getOperand(0), *IIOp1 = Op1I->getOperand(1);
2848 Op1I->setOperand(0, IIOp1);
2849 Op1I->setOperand(1, IIOp0);
Misha Brukmanfd939082005-04-21 23:48:37 +00002850
Chris Lattnera2881962003-02-18 19:28:33 +00002851 // Create the new top level add instruction...
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002852 return BinaryOperator::CreateAdd(Op0, Op1);
Chris Lattnera2881962003-02-18 19:28:33 +00002853 }
2854
2855 // Replace (A - (A & B)) with (A & ~B) if this is the only use of (A&B)...
2856 //
2857 if (Op1I->getOpcode() == Instruction::And &&
2858 (Op1I->getOperand(0) == Op0 || Op1I->getOperand(1) == Op0)) {
2859 Value *OtherOp = Op1I->getOperand(Op1I->getOperand(0) == Op0);
2860
Chris Lattner74381062009-08-30 07:44:24 +00002861 Value *NewNot = Builder->CreateNot(OtherOp, "B.not");
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002862 return BinaryOperator::CreateAnd(Op0, NewNot);
Chris Lattnera2881962003-02-18 19:28:33 +00002863 }
Chris Lattnerad3448c2003-02-18 19:57:07 +00002864
Reid Spencerac5209e2006-10-16 23:08:08 +00002865 // 0 - (X sdiv C) -> (X sdiv -C)
Reid Spencer1628cec2006-10-26 06:15:43 +00002866 if (Op1I->getOpcode() == Instruction::SDiv)
Reid Spencerb83eb642006-10-20 07:07:24 +00002867 if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
Zhou Sheng843f07672007-04-19 05:39:12 +00002868 if (CSI->isZero())
Chris Lattner91ccc152004-10-06 15:08:25 +00002869 if (Constant *DivRHS = dyn_cast<Constant>(Op1I->getOperand(1)))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002870 return BinaryOperator::CreateSDiv(Op1I->getOperand(0),
Owen Andersonbaf3c402009-07-29 18:55:55 +00002871 ConstantExpr::getNeg(DivRHS));
Chris Lattner91ccc152004-10-06 15:08:25 +00002872
Chris Lattnerad3448c2003-02-18 19:57:07 +00002873 // X - X*C --> X * (1-C)
Reid Spencer4b828e62005-06-18 17:37:34 +00002874 ConstantInt *C2 = 0;
Dan Gohman186a6362009-08-12 16:04:34 +00002875 if (dyn_castFoldableMul(Op1I, C2) == Op0) {
Owen Andersond672ecb2009-07-03 00:17:18 +00002876 Constant *CP1 =
Owen Andersonbaf3c402009-07-29 18:55:55 +00002877 ConstantExpr::getSub(ConstantInt::get(I.getType(), 1),
Dan Gohman6de29f82009-06-15 22:12:54 +00002878 C2);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002879 return BinaryOperator::CreateMul(Op0, CP1);
Chris Lattnerad3448c2003-02-18 19:57:07 +00002880 }
Chris Lattner40371712002-05-09 01:29:19 +00002881 }
Chris Lattner43d84d62005-04-07 16:15:25 +00002882 }
Chris Lattnera2881962003-02-18 19:28:33 +00002883
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002884 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
2885 if (Op0I->getOpcode() == Instruction::Add) {
2886 if (Op0I->getOperand(0) == Op1) // (Y+X)-Y == X
2887 return ReplaceInstUsesWith(I, Op0I->getOperand(1));
2888 else if (Op0I->getOperand(1) == Op1) // (X+Y)-Y == X
2889 return ReplaceInstUsesWith(I, Op0I->getOperand(0));
2890 } else if (Op0I->getOpcode() == Instruction::Sub) {
2891 if (Op0I->getOperand(0) == Op1) // (X-Y)-X == -Y
Dan Gohman4ae51262009-08-12 16:23:25 +00002892 return BinaryOperator::CreateNeg(Op0I->getOperand(1),
Owen Anderson0a5372e2009-07-13 04:09:18 +00002893 I.getName());
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00002894 }
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002895 }
Misha Brukmanfd939082005-04-21 23:48:37 +00002896
Chris Lattner50af16a2004-11-13 19:50:12 +00002897 ConstantInt *C1;
Dan Gohman186a6362009-08-12 16:04:34 +00002898 if (Value *X = dyn_castFoldableMul(Op0, C1)) {
Reid Spencer7177c3a2007-03-25 05:33:51 +00002899 if (X == Op1) // X*C - X --> X * (C-1)
Dan Gohman186a6362009-08-12 16:04:34 +00002900 return BinaryOperator::CreateMul(Op1, SubOne(C1));
Chris Lattnerad3448c2003-02-18 19:57:07 +00002901
Chris Lattner50af16a2004-11-13 19:50:12 +00002902 ConstantInt *C2; // X*C1 - X*C2 -> X * (C1-C2)
Dan Gohman186a6362009-08-12 16:04:34 +00002903 if (X == dyn_castFoldableMul(Op1, C2))
Owen Andersonbaf3c402009-07-29 18:55:55 +00002904 return BinaryOperator::CreateMul(X, ConstantExpr::getSub(C1, C2));
Chris Lattner50af16a2004-11-13 19:50:12 +00002905 }
Chris Lattner092543c2009-11-04 08:05:20 +00002906
2907 // Optimize pointer differences into the same array into a size. Consider:
2908 // &A[10] - &A[0]: we should compile this to "10".
2909 if (TD) {
Chris Lattner33767182010-01-01 22:12:03 +00002910 Value *LHSOp, *RHSOp;
Chris Lattnerf2ebc682010-01-01 22:29:12 +00002911 if (match(Op0, m_PtrToInt(m_Value(LHSOp))) &&
2912 match(Op1, m_PtrToInt(m_Value(RHSOp))))
Chris Lattner33767182010-01-01 22:12:03 +00002913 if (Value *Res = OptimizePointerDifference(LHSOp, RHSOp, I.getType()))
2914 return ReplaceInstUsesWith(I, Res);
Chris Lattner092543c2009-11-04 08:05:20 +00002915
2916 // trunc(p)-trunc(q) -> trunc(p-q)
Chris Lattnerf2ebc682010-01-01 22:29:12 +00002917 if (match(Op0, m_Trunc(m_PtrToInt(m_Value(LHSOp)))) &&
2918 match(Op1, m_Trunc(m_PtrToInt(m_Value(RHSOp)))))
2919 if (Value *Res = OptimizePointerDifference(LHSOp, RHSOp, I.getType()))
2920 return ReplaceInstUsesWith(I, Res);
Chris Lattner092543c2009-11-04 08:05:20 +00002921 }
2922
Chris Lattner3f5b8772002-05-06 16:14:14 +00002923 return 0;
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002924}
2925
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002926Instruction *InstCombiner::visitFSub(BinaryOperator &I) {
2927 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2928
2929 // If this is a 'B = x-(-A)', change to B = x+A...
Dan Gohman186a6362009-08-12 16:04:34 +00002930 if (Value *V = dyn_castFNegVal(Op1))
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002931 return BinaryOperator::CreateFAdd(Op0, V);
2932
2933 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
2934 if (Op1I->getOpcode() == Instruction::FAdd) {
2935 if (Op1I->getOperand(0) == Op0) // X-(X+Y) == -Y
Dan Gohman4ae51262009-08-12 16:23:25 +00002936 return BinaryOperator::CreateFNeg(Op1I->getOperand(1),
Owen Anderson0a5372e2009-07-13 04:09:18 +00002937 I.getName());
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002938 else if (Op1I->getOperand(1) == Op0) // X-(Y+X) == -Y
Dan Gohman4ae51262009-08-12 16:23:25 +00002939 return BinaryOperator::CreateFNeg(Op1I->getOperand(0),
Owen Anderson0a5372e2009-07-13 04:09:18 +00002940 I.getName());
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002941 }
Dan Gohmanae3a0be2009-06-04 22:49:04 +00002942 }
2943
2944 return 0;
2945}
2946
Chris Lattnera0141b92007-07-15 20:42:37 +00002947/// isSignBitCheck - Given an exploded icmp instruction, return true if the
2948/// comparison only checks the sign bit. If it only checks the sign bit, set
2949/// TrueIfSigned if the result of the comparison is true when the input value is
2950/// signed.
2951static bool isSignBitCheck(ICmpInst::Predicate pred, ConstantInt *RHS,
2952 bool &TrueIfSigned) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00002953 switch (pred) {
Chris Lattnera0141b92007-07-15 20:42:37 +00002954 case ICmpInst::ICMP_SLT: // True if LHS s< 0
2955 TrueIfSigned = true;
2956 return RHS->isZero();
Chris Lattnercb7122b2007-07-16 04:15:34 +00002957 case ICmpInst::ICMP_SLE: // True if LHS s<= RHS and RHS == -1
2958 TrueIfSigned = true;
2959 return RHS->isAllOnesValue();
Chris Lattnera0141b92007-07-15 20:42:37 +00002960 case ICmpInst::ICMP_SGT: // True if LHS s> -1
2961 TrueIfSigned = false;
2962 return RHS->isAllOnesValue();
Chris Lattnercb7122b2007-07-16 04:15:34 +00002963 case ICmpInst::ICMP_UGT:
2964 // True if LHS u> RHS and RHS == high-bit-mask - 1
2965 TrueIfSigned = true;
2966 return RHS->getValue() ==
2967 APInt::getSignedMaxValue(RHS->getType()->getPrimitiveSizeInBits());
2968 case ICmpInst::ICMP_UGE:
2969 // True if LHS u>= RHS and RHS == high-bit-mask (2^7, 2^15, 2^31, etc)
2970 TrueIfSigned = true;
Chris Lattner833f25d2008-06-02 01:29:46 +00002971 return RHS->getValue().isSignBit();
Chris Lattnera0141b92007-07-15 20:42:37 +00002972 default:
2973 return false;
Chris Lattner4cb170c2004-02-23 06:38:22 +00002974 }
Chris Lattner4cb170c2004-02-23 06:38:22 +00002975}
2976
Chris Lattner7e708292002-06-25 16:13:24 +00002977Instruction *InstCombiner::visitMul(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00002978 bool Changed = SimplifyCommutative(I);
Chris Lattnera2498472009-10-11 21:36:10 +00002979 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnerdd841ae2002-04-18 17:39:14 +00002980
Chris Lattnera2498472009-10-11 21:36:10 +00002981 if (isa<UndefValue>(Op1)) // undef * X -> 0
Owen Andersona7235ea2009-07-31 20:28:14 +00002982 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnere87597f2004-10-16 18:11:37 +00002983
Chris Lattner8af304a2009-10-11 07:53:15 +00002984 // Simplify mul instructions with a constant RHS.
Chris Lattnera2498472009-10-11 21:36:10 +00002985 if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
2986 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1C)) {
Chris Lattnere92d2f42003-08-13 04:18:28 +00002987
2988 // ((X << C1)*C2) == (X * (C2 << C1))
Reid Spencer832254e2007-02-02 02:16:23 +00002989 if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op0))
Chris Lattnere92d2f42003-08-13 04:18:28 +00002990 if (SI->getOpcode() == Instruction::Shl)
2991 if (Constant *ShOp = dyn_cast<Constant>(SI->getOperand(1)))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00002992 return BinaryOperator::CreateMul(SI->getOperand(0),
Owen Andersonbaf3c402009-07-29 18:55:55 +00002993 ConstantExpr::getShl(CI, ShOp));
Misha Brukmanfd939082005-04-21 23:48:37 +00002994
Zhou Sheng843f07672007-04-19 05:39:12 +00002995 if (CI->isZero())
Chris Lattnera2498472009-10-11 21:36:10 +00002996 return ReplaceInstUsesWith(I, Op1C); // X * 0 == 0
Chris Lattner515c97c2003-09-11 22:24:54 +00002997 if (CI->equalsInt(1)) // X * 1 == X
2998 return ReplaceInstUsesWith(I, Op0);
2999 if (CI->isAllOnesValue()) // X * -1 == 0 - X
Dan Gohman4ae51262009-08-12 16:23:25 +00003000 return BinaryOperator::CreateNeg(Op0, I.getName());
Chris Lattner6c1ce212002-04-29 22:24:47 +00003001
Zhou Sheng97b52c22007-03-29 01:57:21 +00003002 const APInt& Val = cast<ConstantInt>(CI)->getValue();
Reid Spencerbca0e382007-03-23 20:05:17 +00003003 if (Val.isPowerOf2()) { // Replace X*(2^C) with X << C
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003004 return BinaryOperator::CreateShl(Op0,
Owen Andersoneed707b2009-07-24 23:12:02 +00003005 ConstantInt::get(Op0->getType(), Val.logBase2()));
Chris Lattnerbcd7db52005-08-02 19:16:58 +00003006 }
Chris Lattnera2498472009-10-11 21:36:10 +00003007 } else if (isa<VectorType>(Op1C->getType())) {
3008 if (Op1C->isNullValue())
3009 return ReplaceInstUsesWith(I, Op1C);
Nick Lewycky895f0852008-11-27 20:21:08 +00003010
Chris Lattnera2498472009-10-11 21:36:10 +00003011 if (ConstantVector *Op1V = dyn_cast<ConstantVector>(Op1C)) {
Nick Lewycky895f0852008-11-27 20:21:08 +00003012 if (Op1V->isAllOnesValue()) // X * -1 == 0 - X
Dan Gohman4ae51262009-08-12 16:23:25 +00003013 return BinaryOperator::CreateNeg(Op0, I.getName());
Nick Lewycky895f0852008-11-27 20:21:08 +00003014
3015 // As above, vector X*splat(1.0) -> X in all defined cases.
3016 if (Constant *Splat = Op1V->getSplatValue()) {
Nick Lewycky895f0852008-11-27 20:21:08 +00003017 if (ConstantInt *CI = dyn_cast<ConstantInt>(Splat))
3018 if (CI->equalsInt(1))
3019 return ReplaceInstUsesWith(I, Op0);
3020 }
3021 }
Chris Lattnera2881962003-02-18 19:28:33 +00003022 }
Chris Lattnerab51f3f2006-03-04 06:04:02 +00003023
3024 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
3025 if (Op0I->getOpcode() == Instruction::Add && Op0I->hasOneUse() &&
Chris Lattnera2498472009-10-11 21:36:10 +00003026 isa<ConstantInt>(Op0I->getOperand(1)) && isa<ConstantInt>(Op1C)) {
Chris Lattnerab51f3f2006-03-04 06:04:02 +00003027 // Canonicalize (X+C1)*C2 -> X*C2+C1*C2.
Chris Lattnera2498472009-10-11 21:36:10 +00003028 Value *Add = Builder->CreateMul(Op0I->getOperand(0), Op1C, "tmp");
3029 Value *C1C2 = Builder->CreateMul(Op1C, Op0I->getOperand(1));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003030 return BinaryOperator::CreateAdd(Add, C1C2);
Chris Lattnerab51f3f2006-03-04 06:04:02 +00003031
3032 }
Chris Lattner2eefe512004-04-09 19:05:30 +00003033
3034 // Try to fold constant mul into select arguments.
3035 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner6e7ba452005-01-01 16:22:27 +00003036 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00003037 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00003038
3039 if (isa<PHINode>(Op0))
3040 if (Instruction *NV = FoldOpIntoPhi(I))
3041 return NV;
Chris Lattnerdd841ae2002-04-18 17:39:14 +00003042 }
3043
Dan Gohman186a6362009-08-12 16:04:34 +00003044 if (Value *Op0v = dyn_castNegVal(Op0)) // -X * -Y = X*Y
Chris Lattnera2498472009-10-11 21:36:10 +00003045 if (Value *Op1v = dyn_castNegVal(Op1))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003046 return BinaryOperator::CreateMul(Op0v, Op1v);
Chris Lattnera4f445b2003-03-10 23:23:04 +00003047
Nick Lewycky0c730792008-11-21 07:33:58 +00003048 // (X / Y) * Y = X - (X % Y)
3049 // (X / Y) * -Y = (X % Y) - X
3050 {
Chris Lattnera2498472009-10-11 21:36:10 +00003051 Value *Op1C = Op1;
Nick Lewycky0c730792008-11-21 07:33:58 +00003052 BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0);
3053 if (!BO ||
3054 (BO->getOpcode() != Instruction::UDiv &&
3055 BO->getOpcode() != Instruction::SDiv)) {
Chris Lattnera2498472009-10-11 21:36:10 +00003056 Op1C = Op0;
3057 BO = dyn_cast<BinaryOperator>(Op1);
Nick Lewycky0c730792008-11-21 07:33:58 +00003058 }
Chris Lattnera2498472009-10-11 21:36:10 +00003059 Value *Neg = dyn_castNegVal(Op1C);
Nick Lewycky0c730792008-11-21 07:33:58 +00003060 if (BO && BO->hasOneUse() &&
Chris Lattnera2498472009-10-11 21:36:10 +00003061 (BO->getOperand(1) == Op1C || BO->getOperand(1) == Neg) &&
Nick Lewycky0c730792008-11-21 07:33:58 +00003062 (BO->getOpcode() == Instruction::UDiv ||
3063 BO->getOpcode() == Instruction::SDiv)) {
3064 Value *Op0BO = BO->getOperand(0), *Op1BO = BO->getOperand(1);
3065
Dan Gohmanfa94b942009-08-12 16:33:09 +00003066 // If the division is exact, X % Y is zero.
3067 if (SDivOperator *SDiv = dyn_cast<SDivOperator>(BO))
3068 if (SDiv->isExact()) {
Chris Lattnera2498472009-10-11 21:36:10 +00003069 if (Op1BO == Op1C)
Dan Gohmanfa94b942009-08-12 16:33:09 +00003070 return ReplaceInstUsesWith(I, Op0BO);
Chris Lattnera2498472009-10-11 21:36:10 +00003071 return BinaryOperator::CreateNeg(Op0BO);
Dan Gohmanfa94b942009-08-12 16:33:09 +00003072 }
3073
Chris Lattner74381062009-08-30 07:44:24 +00003074 Value *Rem;
Nick Lewycky0c730792008-11-21 07:33:58 +00003075 if (BO->getOpcode() == Instruction::UDiv)
Chris Lattner74381062009-08-30 07:44:24 +00003076 Rem = Builder->CreateURem(Op0BO, Op1BO);
Nick Lewycky0c730792008-11-21 07:33:58 +00003077 else
Chris Lattner74381062009-08-30 07:44:24 +00003078 Rem = Builder->CreateSRem(Op0BO, Op1BO);
Nick Lewycky0c730792008-11-21 07:33:58 +00003079 Rem->takeName(BO);
3080
Chris Lattnera2498472009-10-11 21:36:10 +00003081 if (Op1BO == Op1C)
Nick Lewycky0c730792008-11-21 07:33:58 +00003082 return BinaryOperator::CreateSub(Op0BO, Rem);
Chris Lattner74381062009-08-30 07:44:24 +00003083 return BinaryOperator::CreateSub(Rem, Op0BO);
Nick Lewycky0c730792008-11-21 07:33:58 +00003084 }
3085 }
3086
Chris Lattner8af304a2009-10-11 07:53:15 +00003087 /// i1 mul -> i1 and.
Owen Anderson1d0be152009-08-13 21:58:54 +00003088 if (I.getType() == Type::getInt1Ty(*Context))
Chris Lattnera2498472009-10-11 21:36:10 +00003089 return BinaryOperator::CreateAnd(Op0, Op1);
Nick Lewycky9419ddb2008-05-31 17:59:52 +00003090
Chris Lattner8af304a2009-10-11 07:53:15 +00003091 // X*(1 << Y) --> X << Y
3092 // (1 << Y)*X --> X << Y
3093 {
3094 Value *Y;
3095 if (match(Op0, m_Shl(m_One(), m_Value(Y))))
Chris Lattnera2498472009-10-11 21:36:10 +00003096 return BinaryOperator::CreateShl(Op1, Y);
3097 if (match(Op1, m_Shl(m_One(), m_Value(Y))))
Chris Lattner8af304a2009-10-11 07:53:15 +00003098 return BinaryOperator::CreateShl(Op0, Y);
3099 }
3100
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00003101 // If one of the operands of the multiply is a cast from a boolean value, then
3102 // we know the bool is either zero or one, so this is a 'masking' multiply.
Chris Lattnerd2c58362009-10-11 21:29:45 +00003103 // X * Y (where Y is 0 or 1) -> X & (0-Y)
3104 if (!isa<VectorType>(I.getType())) {
3105 // -2 is "-1 << 1" so it is all bits set except the low one.
Dale Johannesenc1deda52009-10-12 18:45:32 +00003106 APInt Negative2(I.getType()->getPrimitiveSizeInBits(), (uint64_t)-2, true);
Chris Lattner0036e3a2009-10-11 21:22:21 +00003107
Chris Lattnerd2c58362009-10-11 21:29:45 +00003108 Value *BoolCast = 0, *OtherOp = 0;
3109 if (MaskedValueIsZero(Op0, Negative2))
Chris Lattnera2498472009-10-11 21:36:10 +00003110 BoolCast = Op0, OtherOp = Op1;
3111 else if (MaskedValueIsZero(Op1, Negative2))
3112 BoolCast = Op1, OtherOp = Op0;
Chris Lattnerd2c58362009-10-11 21:29:45 +00003113
Chris Lattner0036e3a2009-10-11 21:22:21 +00003114 if (BoolCast) {
Chris Lattner0036e3a2009-10-11 21:22:21 +00003115 Value *V = Builder->CreateSub(Constant::getNullValue(I.getType()),
3116 BoolCast, "tmp");
3117 return BinaryOperator::CreateAnd(V, OtherOp);
Chris Lattnerfb54b2b2004-02-23 05:39:21 +00003118 }
3119 }
3120
Chris Lattner7e708292002-06-25 16:13:24 +00003121 return Changed ? &I : 0;
Chris Lattnerdd841ae2002-04-18 17:39:14 +00003122}
3123
Dan Gohmanae3a0be2009-06-04 22:49:04 +00003124Instruction *InstCombiner::visitFMul(BinaryOperator &I) {
3125 bool Changed = SimplifyCommutative(I);
Chris Lattnera2498472009-10-11 21:36:10 +00003126 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Dan Gohmanae3a0be2009-06-04 22:49:04 +00003127
3128 // Simplify mul instructions with a constant RHS...
Chris Lattnera2498472009-10-11 21:36:10 +00003129 if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
3130 if (ConstantFP *Op1F = dyn_cast<ConstantFP>(Op1C)) {
Dan Gohmanae3a0be2009-06-04 22:49:04 +00003131 // "In IEEE floating point, x*1 is not equivalent to x for nans. However,
3132 // ANSI says we can drop signals, so we can do this anyway." (from GCC)
3133 if (Op1F->isExactlyValue(1.0))
3134 return ReplaceInstUsesWith(I, Op0); // Eliminate 'mul double %X, 1.0'
Chris Lattnera2498472009-10-11 21:36:10 +00003135 } else if (isa<VectorType>(Op1C->getType())) {
3136 if (ConstantVector *Op1V = dyn_cast<ConstantVector>(Op1C)) {
Dan Gohmanae3a0be2009-06-04 22:49:04 +00003137 // As above, vector X*splat(1.0) -> X in all defined cases.
3138 if (Constant *Splat = Op1V->getSplatValue()) {
3139 if (ConstantFP *F = dyn_cast<ConstantFP>(Splat))
3140 if (F->isExactlyValue(1.0))
3141 return ReplaceInstUsesWith(I, Op0);
3142 }
3143 }
3144 }
3145
3146 // Try to fold constant mul into select arguments.
3147 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
3148 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
3149 return R;
3150
3151 if (isa<PHINode>(Op0))
3152 if (Instruction *NV = FoldOpIntoPhi(I))
3153 return NV;
3154 }
3155
Dan Gohman186a6362009-08-12 16:04:34 +00003156 if (Value *Op0v = dyn_castFNegVal(Op0)) // -X * -Y = X*Y
Chris Lattnera2498472009-10-11 21:36:10 +00003157 if (Value *Op1v = dyn_castFNegVal(Op1))
Dan Gohmanae3a0be2009-06-04 22:49:04 +00003158 return BinaryOperator::CreateFMul(Op0v, Op1v);
3159
3160 return Changed ? &I : 0;
3161}
3162
Chris Lattnerfdb19e52008-07-14 00:15:52 +00003163/// SimplifyDivRemOfSelect - Try to fold a divide or remainder of a select
3164/// instruction.
3165bool InstCombiner::SimplifyDivRemOfSelect(BinaryOperator &I) {
3166 SelectInst *SI = cast<SelectInst>(I.getOperand(1));
3167
3168 // div/rem X, (Cond ? 0 : Y) -> div/rem X, Y
3169 int NonNullOperand = -1;
3170 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(1)))
3171 if (ST->isNullValue())
3172 NonNullOperand = 2;
3173 // div/rem X, (Cond ? Y : 0) -> div/rem X, Y
3174 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(2)))
3175 if (ST->isNullValue())
3176 NonNullOperand = 1;
3177
3178 if (NonNullOperand == -1)
3179 return false;
3180
3181 Value *SelectCond = SI->getOperand(0);
3182
3183 // Change the div/rem to use 'Y' instead of the select.
3184 I.setOperand(1, SI->getOperand(NonNullOperand));
3185
3186 // Okay, we know we replace the operand of the div/rem with 'Y' with no
3187 // problem. However, the select, or the condition of the select may have
3188 // multiple uses. Based on our knowledge that the operand must be non-zero,
3189 // propagate the known value for the select into other uses of it, and
3190 // propagate a known value of the condition into its other users.
3191
3192 // If the select and condition only have a single use, don't bother with this,
3193 // early exit.
3194 if (SI->use_empty() && SelectCond->hasOneUse())
3195 return true;
3196
3197 // Scan the current block backward, looking for other uses of SI.
3198 BasicBlock::iterator BBI = &I, BBFront = I.getParent()->begin();
3199
3200 while (BBI != BBFront) {
3201 --BBI;
3202 // If we found a call to a function, we can't assume it will return, so
3203 // information from below it cannot be propagated above it.
3204 if (isa<CallInst>(BBI) && !isa<IntrinsicInst>(BBI))
3205 break;
3206
3207 // Replace uses of the select or its condition with the known values.
3208 for (Instruction::op_iterator I = BBI->op_begin(), E = BBI->op_end();
3209 I != E; ++I) {
3210 if (*I == SI) {
3211 *I = SI->getOperand(NonNullOperand);
Chris Lattner7a1e9242009-08-30 06:13:40 +00003212 Worklist.Add(BBI);
Chris Lattnerfdb19e52008-07-14 00:15:52 +00003213 } else if (*I == SelectCond) {
Owen Anderson5defacc2009-07-31 17:39:07 +00003214 *I = NonNullOperand == 1 ? ConstantInt::getTrue(*Context) :
3215 ConstantInt::getFalse(*Context);
Chris Lattner7a1e9242009-08-30 06:13:40 +00003216 Worklist.Add(BBI);
Chris Lattnerfdb19e52008-07-14 00:15:52 +00003217 }
3218 }
3219
3220 // If we past the instruction, quit looking for it.
3221 if (&*BBI == SI)
3222 SI = 0;
3223 if (&*BBI == SelectCond)
3224 SelectCond = 0;
3225
3226 // If we ran out of things to eliminate, break out of the loop.
3227 if (SelectCond == 0 && SI == 0)
3228 break;
3229
3230 }
3231 return true;
3232}
3233
3234
Reid Spencer1628cec2006-10-26 06:15:43 +00003235/// This function implements the transforms on div instructions that work
3236/// regardless of the kind of div instruction it is (udiv, sdiv, or fdiv). It is
3237/// used by the visitors to those instructions.
3238/// @brief Transforms common to all three div instructions
Reid Spencer3da59db2006-11-27 01:05:10 +00003239Instruction *InstCombiner::commonDivTransforms(BinaryOperator &I) {
Chris Lattner857e8cd2004-12-12 21:48:58 +00003240 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattnere87597f2004-10-16 18:11:37 +00003241
Chris Lattner50b2ca42008-02-19 06:12:18 +00003242 // undef / X -> 0 for integer.
3243 // undef / X -> undef for FP (the undef could be a snan).
3244 if (isa<UndefValue>(Op0)) {
3245 if (Op0->getType()->isFPOrFPVector())
3246 return ReplaceInstUsesWith(I, Op0);
Owen Andersona7235ea2009-07-31 20:28:14 +00003247 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner50b2ca42008-02-19 06:12:18 +00003248 }
Reid Spencer1628cec2006-10-26 06:15:43 +00003249
3250 // X / undef -> undef
Chris Lattner857e8cd2004-12-12 21:48:58 +00003251 if (isa<UndefValue>(Op1))
Reid Spencer1628cec2006-10-26 06:15:43 +00003252 return ReplaceInstUsesWith(I, Op1);
Chris Lattner857e8cd2004-12-12 21:48:58 +00003253
Reid Spencer1628cec2006-10-26 06:15:43 +00003254 return 0;
3255}
Misha Brukmanfd939082005-04-21 23:48:37 +00003256
Reid Spencer1628cec2006-10-26 06:15:43 +00003257/// This function implements the transforms common to both integer division
3258/// instructions (udiv and sdiv). It is called by the visitors to those integer
3259/// division instructions.
3260/// @brief Common integer divide transforms
Reid Spencer3da59db2006-11-27 01:05:10 +00003261Instruction *InstCombiner::commonIDivTransforms(BinaryOperator &I) {
Reid Spencer1628cec2006-10-26 06:15:43 +00003262 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3263
Chris Lattnerb2ae9e32008-05-16 02:59:42 +00003264 // (sdiv X, X) --> 1 (udiv X, X) --> 1
Nick Lewycky39ac3b52008-05-23 03:26:47 +00003265 if (Op0 == Op1) {
3266 if (const VectorType *Ty = dyn_cast<VectorType>(I.getType())) {
Owen Andersoneed707b2009-07-24 23:12:02 +00003267 Constant *CI = ConstantInt::get(Ty->getElementType(), 1);
Nick Lewycky39ac3b52008-05-23 03:26:47 +00003268 std::vector<Constant*> Elts(Ty->getNumElements(), CI);
Owen Andersonaf7ec972009-07-28 21:19:26 +00003269 return ReplaceInstUsesWith(I, ConstantVector::get(Elts));
Nick Lewycky39ac3b52008-05-23 03:26:47 +00003270 }
3271
Owen Andersoneed707b2009-07-24 23:12:02 +00003272 Constant *CI = ConstantInt::get(I.getType(), 1);
Nick Lewycky39ac3b52008-05-23 03:26:47 +00003273 return ReplaceInstUsesWith(I, CI);
3274 }
Chris Lattnerb2ae9e32008-05-16 02:59:42 +00003275
Reid Spencer1628cec2006-10-26 06:15:43 +00003276 if (Instruction *Common = commonDivTransforms(I))
3277 return Common;
Chris Lattnerfdb19e52008-07-14 00:15:52 +00003278
3279 // Handle cases involving: [su]div X, (select Cond, Y, Z)
3280 // This does not apply for fdiv.
3281 if (isa<SelectInst>(Op1) && SimplifyDivRemOfSelect(I))
3282 return &I;
Reid Spencer1628cec2006-10-26 06:15:43 +00003283
3284 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3285 // div X, 1 == X
3286 if (RHS->equalsInt(1))
3287 return ReplaceInstUsesWith(I, Op0);
3288
3289 // (X / C1) / C2 -> X / (C1*C2)
3290 if (Instruction *LHS = dyn_cast<Instruction>(Op0))
3291 if (Instruction::BinaryOps(LHS->getOpcode()) == I.getOpcode())
3292 if (ConstantInt *LHSRHS = dyn_cast<ConstantInt>(LHS->getOperand(1))) {
Owen Andersond672ecb2009-07-03 00:17:18 +00003293 if (MultiplyOverflows(RHS, LHSRHS,
Dan Gohman186a6362009-08-12 16:04:34 +00003294 I.getOpcode()==Instruction::SDiv))
Owen Andersona7235ea2009-07-31 20:28:14 +00003295 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Nick Lewyckye0cfecf2008-02-18 22:48:05 +00003296 else
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003297 return BinaryOperator::Create(I.getOpcode(), LHS->getOperand(0),
Owen Andersonbaf3c402009-07-29 18:55:55 +00003298 ConstantExpr::getMul(RHS, LHSRHS));
Chris Lattnerbf70b832005-04-08 04:03:26 +00003299 }
Reid Spencer1628cec2006-10-26 06:15:43 +00003300
Reid Spencerbca0e382007-03-23 20:05:17 +00003301 if (!RHS->isZero()) { // avoid X udiv 0
Reid Spencer1628cec2006-10-26 06:15:43 +00003302 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
3303 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
3304 return R;
3305 if (isa<PHINode>(Op0))
3306 if (Instruction *NV = FoldOpIntoPhi(I))
3307 return NV;
3308 }
Chris Lattner8e49e082006-09-09 20:26:32 +00003309 }
Misha Brukmanfd939082005-04-21 23:48:37 +00003310
Chris Lattnera2881962003-02-18 19:28:33 +00003311 // 0 / X == 0, we don't need to preserve faults!
Chris Lattner857e8cd2004-12-12 21:48:58 +00003312 if (ConstantInt *LHS = dyn_cast<ConstantInt>(Op0))
Chris Lattnera2881962003-02-18 19:28:33 +00003313 if (LHS->equalsInt(0))
Owen Andersona7235ea2009-07-31 20:28:14 +00003314 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnera2881962003-02-18 19:28:33 +00003315
Nick Lewycky9419ddb2008-05-31 17:59:52 +00003316 // It can't be division by zero, hence it must be division by one.
Owen Anderson1d0be152009-08-13 21:58:54 +00003317 if (I.getType() == Type::getInt1Ty(*Context))
Nick Lewycky9419ddb2008-05-31 17:59:52 +00003318 return ReplaceInstUsesWith(I, Op0);
3319
Nick Lewycky895f0852008-11-27 20:21:08 +00003320 if (ConstantVector *Op1V = dyn_cast<ConstantVector>(Op1)) {
3321 if (ConstantInt *X = cast_or_null<ConstantInt>(Op1V->getSplatValue()))
3322 // div X, 1 == X
3323 if (X->isOne())
3324 return ReplaceInstUsesWith(I, Op0);
3325 }
3326
Reid Spencer1628cec2006-10-26 06:15:43 +00003327 return 0;
3328}
3329
3330Instruction *InstCombiner::visitUDiv(BinaryOperator &I) {
3331 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3332
3333 // Handle the integer div common cases
3334 if (Instruction *Common = commonIDivTransforms(I))
3335 return Common;
3336
Reid Spencer1628cec2006-10-26 06:15:43 +00003337 if (ConstantInt *C = dyn_cast<ConstantInt>(Op1)) {
Nick Lewycky8ca52482008-11-27 22:41:10 +00003338 // X udiv C^2 -> X >> C
3339 // Check to see if this is an unsigned division with an exact power of 2,
3340 // if so, convert to a right shift.
Reid Spencer6eb0d992007-03-26 23:58:26 +00003341 if (C->getValue().isPowerOf2()) // 0 not included in isPowerOf2
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003342 return BinaryOperator::CreateLShr(Op0,
Owen Andersoneed707b2009-07-24 23:12:02 +00003343 ConstantInt::get(Op0->getType(), C->getValue().logBase2()));
Nick Lewycky8ca52482008-11-27 22:41:10 +00003344
3345 // X udiv C, where C >= signbit
3346 if (C->getValue().isNegative()) {
Chris Lattner74381062009-08-30 07:44:24 +00003347 Value *IC = Builder->CreateICmpULT( Op0, C);
Owen Andersona7235ea2009-07-31 20:28:14 +00003348 return SelectInst::Create(IC, Constant::getNullValue(I.getType()),
Owen Andersoneed707b2009-07-24 23:12:02 +00003349 ConstantInt::get(I.getType(), 1));
Nick Lewycky8ca52482008-11-27 22:41:10 +00003350 }
Reid Spencer1628cec2006-10-26 06:15:43 +00003351 }
3352
3353 // X udiv (C1 << N), where C1 is "1<<C2" --> X >> (N+C2)
Reid Spencer832254e2007-02-02 02:16:23 +00003354 if (BinaryOperator *RHSI = dyn_cast<BinaryOperator>(I.getOperand(1))) {
Reid Spencer1628cec2006-10-26 06:15:43 +00003355 if (RHSI->getOpcode() == Instruction::Shl &&
3356 isa<ConstantInt>(RHSI->getOperand(0))) {
Zhou Sheng3a507fd2007-04-01 17:13:37 +00003357 const APInt& C1 = cast<ConstantInt>(RHSI->getOperand(0))->getValue();
Reid Spencerbca0e382007-03-23 20:05:17 +00003358 if (C1.isPowerOf2()) {
Reid Spencer1628cec2006-10-26 06:15:43 +00003359 Value *N = RHSI->getOperand(1);
Reid Spencer3da59db2006-11-27 01:05:10 +00003360 const Type *NTy = N->getType();
Chris Lattner74381062009-08-30 07:44:24 +00003361 if (uint32_t C2 = C1.logBase2())
3362 N = Builder->CreateAdd(N, ConstantInt::get(NTy, C2), "tmp");
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003363 return BinaryOperator::CreateLShr(Op0, N);
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00003364 }
3365 }
Chris Lattnerc812e5d2005-11-05 07:40:31 +00003366 }
3367
Reid Spencer1628cec2006-10-26 06:15:43 +00003368 // udiv X, (Select Cond, C1, C2) --> Select Cond, (shr X, C1), (shr X, C2)
3369 // where C1&C2 are powers of two.
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00003370 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
Reid Spencer1628cec2006-10-26 06:15:43 +00003371 if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00003372 if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2))) {
Zhou Sheng3a507fd2007-04-01 17:13:37 +00003373 const APInt &TVA = STO->getValue(), &FVA = SFO->getValue();
Reid Spencerbca0e382007-03-23 20:05:17 +00003374 if (TVA.isPowerOf2() && FVA.isPowerOf2()) {
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00003375 // Compute the shift amounts
Reid Spencerbca0e382007-03-23 20:05:17 +00003376 uint32_t TSA = TVA.logBase2(), FSA = FVA.logBase2();
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00003377 // Construct the "on true" case of the select
Owen Andersoneed707b2009-07-24 23:12:02 +00003378 Constant *TC = ConstantInt::get(Op0->getType(), TSA);
Chris Lattner74381062009-08-30 07:44:24 +00003379 Value *TSI = Builder->CreateLShr(Op0, TC, SI->getName()+".t");
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00003380
3381 // Construct the "on false" case of the select
Owen Andersoneed707b2009-07-24 23:12:02 +00003382 Constant *FC = ConstantInt::get(Op0->getType(), FSA);
Chris Lattner74381062009-08-30 07:44:24 +00003383 Value *FSI = Builder->CreateLShr(Op0, FC, SI->getName()+".f");
Reid Spencer1628cec2006-10-26 06:15:43 +00003384
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00003385 // construct the select instruction and return it.
Gabor Greif051a9502008-04-06 20:25:17 +00003386 return SelectInst::Create(SI->getOperand(0), TSI, FSI, SI->getName());
Reid Spencer1628cec2006-10-26 06:15:43 +00003387 }
Reid Spencerbaf1e4b2007-03-05 23:36:13 +00003388 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00003389 return 0;
3390}
3391
Reid Spencer1628cec2006-10-26 06:15:43 +00003392Instruction *InstCombiner::visitSDiv(BinaryOperator &I) {
3393 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3394
3395 // Handle the integer div common cases
3396 if (Instruction *Common = commonIDivTransforms(I))
3397 return Common;
3398
3399 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3400 // sdiv X, -1 == -X
3401 if (RHS->isAllOnesValue())
Dan Gohman4ae51262009-08-12 16:23:25 +00003402 return BinaryOperator::CreateNeg(Op0);
Dan Gohman1bdf5dc2009-08-11 20:47:47 +00003403
Dan Gohmanfa94b942009-08-12 16:33:09 +00003404 // sdiv X, C --> ashr X, log2(C)
Dan Gohman1bdf5dc2009-08-11 20:47:47 +00003405 if (cast<SDivOperator>(&I)->isExact() &&
3406 RHS->getValue().isNonNegative() &&
3407 RHS->getValue().isPowerOf2()) {
3408 Value *ShAmt = llvm::ConstantInt::get(RHS->getType(),
3409 RHS->getValue().exactLogBase2());
3410 return BinaryOperator::CreateAShr(Op0, ShAmt, I.getName());
3411 }
Dan Gohman9ca9daa2009-08-12 16:37:02 +00003412
3413 // -X/C --> X/-C provided the negation doesn't overflow.
3414 if (SubOperator *Sub = dyn_cast<SubOperator>(Op0))
3415 if (isa<Constant>(Sub->getOperand(0)) &&
3416 cast<Constant>(Sub->getOperand(0))->isNullValue() &&
Dan Gohman5078f842009-08-20 17:11:38 +00003417 Sub->hasNoSignedWrap())
Dan Gohman9ca9daa2009-08-12 16:37:02 +00003418 return BinaryOperator::CreateSDiv(Sub->getOperand(1),
3419 ConstantExpr::getNeg(RHS));
Reid Spencer1628cec2006-10-26 06:15:43 +00003420 }
3421
3422 // If the sign bits of both operands are zero (i.e. we can prove they are
3423 // unsigned inputs), turn this into a udiv.
Chris Lattner42a75512007-01-15 02:27:26 +00003424 if (I.getType()->isInteger()) {
Reid Spencerbca0e382007-03-23 20:05:17 +00003425 APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
Eli Friedman8be17392009-07-18 09:53:21 +00003426 if (MaskedValueIsZero(Op0, Mask)) {
3427 if (MaskedValueIsZero(Op1, Mask)) {
3428 // X sdiv Y -> X udiv Y, iff X and Y don't have sign bit set
3429 return BinaryOperator::CreateUDiv(Op0, Op1, I.getName());
3430 }
3431 ConstantInt *ShiftedInt;
Dan Gohman4ae51262009-08-12 16:23:25 +00003432 if (match(Op1, m_Shl(m_ConstantInt(ShiftedInt), m_Value())) &&
Eli Friedman8be17392009-07-18 09:53:21 +00003433 ShiftedInt->getValue().isPowerOf2()) {
3434 // X sdiv (1 << Y) -> X udiv (1 << Y) ( -> X u>> Y)
3435 // Safe because the only negative value (1 << Y) can take on is
3436 // INT_MIN, and X sdiv INT_MIN == X udiv INT_MIN == 0 if X doesn't have
3437 // the sign bit set.
3438 return BinaryOperator::CreateUDiv(Op0, Op1, I.getName());
3439 }
Reid Spencer1628cec2006-10-26 06:15:43 +00003440 }
Eli Friedman8be17392009-07-18 09:53:21 +00003441 }
Reid Spencer1628cec2006-10-26 06:15:43 +00003442
3443 return 0;
3444}
3445
3446Instruction *InstCombiner::visitFDiv(BinaryOperator &I) {
3447 return commonDivTransforms(I);
3448}
Chris Lattner3f5b8772002-05-06 16:14:14 +00003449
Reid Spencer0a783f72006-11-02 01:53:59 +00003450/// This function implements the transforms on rem instructions that work
3451/// regardless of the kind of rem instruction it is (urem, srem, or frem). It
3452/// is used by the visitors to those instructions.
3453/// @brief Transforms common to all three rem instructions
3454Instruction *InstCombiner::commonRemTransforms(BinaryOperator &I) {
Chris Lattner857e8cd2004-12-12 21:48:58 +00003455 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Reid Spencer0a783f72006-11-02 01:53:59 +00003456
Chris Lattner50b2ca42008-02-19 06:12:18 +00003457 if (isa<UndefValue>(Op0)) { // undef % X -> 0
3458 if (I.getType()->isFPOrFPVector())
3459 return ReplaceInstUsesWith(I, Op0); // X % undef -> undef (could be SNaN)
Owen Andersona7235ea2009-07-31 20:28:14 +00003460 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner50b2ca42008-02-19 06:12:18 +00003461 }
Chris Lattner19ccd5c2006-02-28 05:30:45 +00003462 if (isa<UndefValue>(Op1))
3463 return ReplaceInstUsesWith(I, Op1); // X % undef -> undef
Reid Spencer0a783f72006-11-02 01:53:59 +00003464
3465 // Handle cases involving: rem X, (select Cond, Y, Z)
Chris Lattnerfdb19e52008-07-14 00:15:52 +00003466 if (isa<SelectInst>(Op1) && SimplifyDivRemOfSelect(I))
3467 return &I;
Chris Lattner5b73c082004-07-06 07:01:22 +00003468
Reid Spencer0a783f72006-11-02 01:53:59 +00003469 return 0;
3470}
3471
3472/// This function implements the transforms common to both integer remainder
3473/// instructions (urem and srem). It is called by the visitors to those integer
3474/// remainder instructions.
3475/// @brief Common integer remainder transforms
3476Instruction *InstCombiner::commonIRemTransforms(BinaryOperator &I) {
3477 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3478
3479 if (Instruction *common = commonRemTransforms(I))
3480 return common;
3481
Dale Johannesened6af242009-01-21 00:35:19 +00003482 // 0 % X == 0 for integer, we don't need to preserve faults!
3483 if (Constant *LHS = dyn_cast<Constant>(Op0))
3484 if (LHS->isNullValue())
Owen Andersona7235ea2009-07-31 20:28:14 +00003485 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Dale Johannesened6af242009-01-21 00:35:19 +00003486
Chris Lattner857e8cd2004-12-12 21:48:58 +00003487 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner19ccd5c2006-02-28 05:30:45 +00003488 // X % 0 == undef, we don't need to preserve faults!
3489 if (RHS->equalsInt(0))
Owen Anderson9e9a0d52009-07-30 23:03:37 +00003490 return ReplaceInstUsesWith(I, UndefValue::get(I.getType()));
Chris Lattner19ccd5c2006-02-28 05:30:45 +00003491
Chris Lattnera2881962003-02-18 19:28:33 +00003492 if (RHS->equalsInt(1)) // X % 1 == 0
Owen Andersona7235ea2009-07-31 20:28:14 +00003493 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnera2881962003-02-18 19:28:33 +00003494
Chris Lattner97943922006-02-28 05:49:21 +00003495 if (Instruction *Op0I = dyn_cast<Instruction>(Op0)) {
3496 if (SelectInst *SI = dyn_cast<SelectInst>(Op0I)) {
3497 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
3498 return R;
3499 } else if (isa<PHINode>(Op0I)) {
3500 if (Instruction *NV = FoldOpIntoPhi(I))
3501 return NV;
Chris Lattner97943922006-02-28 05:49:21 +00003502 }
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00003503
3504 // See if we can fold away this rem instruction.
Chris Lattner886ab6c2009-01-31 08:15:18 +00003505 if (SimplifyDemandedInstructionBits(I))
Nick Lewyckyc1a2a612008-03-06 06:48:30 +00003506 return &I;
Chris Lattner97943922006-02-28 05:49:21 +00003507 }
Chris Lattnera2881962003-02-18 19:28:33 +00003508 }
3509
Reid Spencer0a783f72006-11-02 01:53:59 +00003510 return 0;
3511}
3512
3513Instruction *InstCombiner::visitURem(BinaryOperator &I) {
3514 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3515
3516 if (Instruction *common = commonIRemTransforms(I))
3517 return common;
3518
3519 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3520 // X urem C^2 -> X and C
3521 // Check to see if this is an unsigned remainder with an exact power of 2,
3522 // if so, convert to a bitwise and.
3523 if (ConstantInt *C = dyn_cast<ConstantInt>(RHS))
Reid Spencerbca0e382007-03-23 20:05:17 +00003524 if (C->getValue().isPowerOf2())
Dan Gohman186a6362009-08-12 16:04:34 +00003525 return BinaryOperator::CreateAnd(Op0, SubOne(C));
Reid Spencer0a783f72006-11-02 01:53:59 +00003526 }
3527
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00003528 if (Instruction *RHSI = dyn_cast<Instruction>(I.getOperand(1))) {
Reid Spencer0a783f72006-11-02 01:53:59 +00003529 // Turn A % (C << N), where C is 2^k, into A & ((C << N)-1)
3530 if (RHSI->getOpcode() == Instruction::Shl &&
3531 isa<ConstantInt>(RHSI->getOperand(0))) {
Zhou Sheng0fc50952007-03-25 05:01:29 +00003532 if (cast<ConstantInt>(RHSI->getOperand(0))->getValue().isPowerOf2()) {
Owen Andersona7235ea2009-07-31 20:28:14 +00003533 Constant *N1 = Constant::getAllOnesValue(I.getType());
Chris Lattner74381062009-08-30 07:44:24 +00003534 Value *Add = Builder->CreateAdd(RHSI, N1, "tmp");
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003535 return BinaryOperator::CreateAnd(Op0, Add);
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00003536 }
3537 }
Reid Spencer0a783f72006-11-02 01:53:59 +00003538 }
Chris Lattner8e49e082006-09-09 20:26:32 +00003539
Reid Spencer0a783f72006-11-02 01:53:59 +00003540 // urem X, (select Cond, 2^C1, 2^C2) --> select Cond, (and X, C1), (and X, C2)
3541 // where C1&C2 are powers of two.
3542 if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
3543 if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
3544 if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2))) {
3545 // STO == 0 and SFO == 0 handled above.
Reid Spencerbca0e382007-03-23 20:05:17 +00003546 if ((STO->getValue().isPowerOf2()) &&
3547 (SFO->getValue().isPowerOf2())) {
Chris Lattner74381062009-08-30 07:44:24 +00003548 Value *TrueAnd = Builder->CreateAnd(Op0, SubOne(STO),
3549 SI->getName()+".t");
3550 Value *FalseAnd = Builder->CreateAnd(Op0, SubOne(SFO),
3551 SI->getName()+".f");
Gabor Greif051a9502008-04-06 20:25:17 +00003552 return SelectInst::Create(SI->getOperand(0), TrueAnd, FalseAnd);
Reid Spencer0a783f72006-11-02 01:53:59 +00003553 }
3554 }
Chris Lattner5f3b0ee2006-02-05 07:54:04 +00003555 }
3556
Chris Lattner3f5b8772002-05-06 16:14:14 +00003557 return 0;
3558}
3559
Reid Spencer0a783f72006-11-02 01:53:59 +00003560Instruction *InstCombiner::visitSRem(BinaryOperator &I) {
3561 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3562
Dan Gohmancff55092007-11-05 23:16:33 +00003563 // Handle the integer rem common cases
Chris Lattnere5ecdb52009-08-30 06:22:51 +00003564 if (Instruction *Common = commonIRemTransforms(I))
3565 return Common;
Reid Spencer0a783f72006-11-02 01:53:59 +00003566
Dan Gohman186a6362009-08-12 16:04:34 +00003567 if (Value *RHSNeg = dyn_castNegVal(Op1))
Nick Lewycky23c04302008-09-03 06:24:21 +00003568 if (!isa<Constant>(RHSNeg) ||
3569 (isa<ConstantInt>(RHSNeg) &&
3570 cast<ConstantInt>(RHSNeg)->getValue().isStrictlyPositive())) {
Reid Spencer0a783f72006-11-02 01:53:59 +00003571 // X % -Y -> X % Y
Chris Lattner3c4e38e2009-08-30 06:27:41 +00003572 Worklist.AddValue(I.getOperand(1));
Reid Spencer0a783f72006-11-02 01:53:59 +00003573 I.setOperand(1, RHSNeg);
3574 return &I;
3575 }
Nick Lewyckya06cf822008-09-30 06:08:34 +00003576
Dan Gohmancff55092007-11-05 23:16:33 +00003577 // If the sign bits of both operands are zero (i.e. we can prove they are
Reid Spencer0a783f72006-11-02 01:53:59 +00003578 // unsigned inputs), turn this into a urem.
Dan Gohmancff55092007-11-05 23:16:33 +00003579 if (I.getType()->isInteger()) {
3580 APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
3581 if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
3582 // X srem Y -> X urem Y, iff X and Y don't have sign bit set
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003583 return BinaryOperator::CreateURem(Op0, Op1, I.getName());
Dan Gohmancff55092007-11-05 23:16:33 +00003584 }
Reid Spencer0a783f72006-11-02 01:53:59 +00003585 }
3586
Nick Lewycky2a8f6592008-12-18 06:31:11 +00003587 // If it's a constant vector, flip any negative values positive.
Nick Lewycky9dce8732008-12-20 16:48:00 +00003588 if (ConstantVector *RHSV = dyn_cast<ConstantVector>(Op1)) {
3589 unsigned VWidth = RHSV->getNumOperands();
Nick Lewycky2a8f6592008-12-18 06:31:11 +00003590
Nick Lewycky9dce8732008-12-20 16:48:00 +00003591 bool hasNegative = false;
3592 for (unsigned i = 0; !hasNegative && i != VWidth; ++i)
3593 if (ConstantInt *RHS = dyn_cast<ConstantInt>(RHSV->getOperand(i)))
3594 if (RHS->getValue().isNegative())
3595 hasNegative = true;
3596
3597 if (hasNegative) {
3598 std::vector<Constant *> Elts(VWidth);
Nick Lewycky2a8f6592008-12-18 06:31:11 +00003599 for (unsigned i = 0; i != VWidth; ++i) {
3600 if (ConstantInt *RHS = dyn_cast<ConstantInt>(RHSV->getOperand(i))) {
3601 if (RHS->getValue().isNegative())
Owen Andersonbaf3c402009-07-29 18:55:55 +00003602 Elts[i] = cast<ConstantInt>(ConstantExpr::getNeg(RHS));
Nick Lewycky2a8f6592008-12-18 06:31:11 +00003603 else
3604 Elts[i] = RHS;
3605 }
3606 }
3607
Owen Andersonaf7ec972009-07-28 21:19:26 +00003608 Constant *NewRHSV = ConstantVector::get(Elts);
Nick Lewycky2a8f6592008-12-18 06:31:11 +00003609 if (NewRHSV != RHSV) {
Chris Lattner3c4e38e2009-08-30 06:27:41 +00003610 Worklist.AddValue(I.getOperand(1));
Nick Lewycky2a8f6592008-12-18 06:31:11 +00003611 I.setOperand(1, NewRHSV);
3612 return &I;
3613 }
3614 }
3615 }
3616
Reid Spencer0a783f72006-11-02 01:53:59 +00003617 return 0;
3618}
3619
3620Instruction *InstCombiner::visitFRem(BinaryOperator &I) {
Reid Spencer0a783f72006-11-02 01:53:59 +00003621 return commonRemTransforms(I);
3622}
3623
Chris Lattner457dd822004-06-09 07:59:58 +00003624// isOneBitSet - Return true if there is exactly one bit set in the specified
3625// constant.
3626static bool isOneBitSet(const ConstantInt *CI) {
Reid Spencer5f6a8952007-03-20 00:16:52 +00003627 return CI->getValue().isPowerOf2();
Chris Lattner457dd822004-06-09 07:59:58 +00003628}
3629
Chris Lattnerb20ba0a2004-09-23 21:46:38 +00003630// isHighOnes - Return true if the constant is of the form 1+0+.
3631// This is the same as lowones(~X).
3632static bool isHighOnes(const ConstantInt *CI) {
Zhou Sheng2cde46c2007-03-20 12:49:06 +00003633 return (~CI->getValue() + 1).isPowerOf2();
Chris Lattnerb20ba0a2004-09-23 21:46:38 +00003634}
3635
Reid Spencere4d87aa2006-12-23 06:05:41 +00003636/// getICmpCode - Encode a icmp predicate into a three bit mask. These bits
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003637/// are carefully arranged to allow folding of expressions such as:
3638///
3639/// (A < B) | (A > B) --> (A != B)
3640///
Reid Spencere4d87aa2006-12-23 06:05:41 +00003641/// Note that this is only valid if the first and second predicates have the
3642/// same sign. Is illegal to do: (A u< B) | (A s> B)
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003643///
Reid Spencere4d87aa2006-12-23 06:05:41 +00003644/// Three bits are used to represent the condition, as follows:
3645/// 0 A > B
3646/// 1 A == B
3647/// 2 A < B
3648///
3649/// <=> Value Definition
3650/// 000 0 Always false
3651/// 001 1 A > B
3652/// 010 2 A == B
3653/// 011 3 A >= B
3654/// 100 4 A < B
3655/// 101 5 A != B
3656/// 110 6 A <= B
3657/// 111 7 Always true
3658///
3659static unsigned getICmpCode(const ICmpInst *ICI) {
3660 switch (ICI->getPredicate()) {
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003661 // False -> 0
Reid Spencere4d87aa2006-12-23 06:05:41 +00003662 case ICmpInst::ICMP_UGT: return 1; // 001
3663 case ICmpInst::ICMP_SGT: return 1; // 001
3664 case ICmpInst::ICMP_EQ: return 2; // 010
3665 case ICmpInst::ICMP_UGE: return 3; // 011
3666 case ICmpInst::ICMP_SGE: return 3; // 011
3667 case ICmpInst::ICMP_ULT: return 4; // 100
3668 case ICmpInst::ICMP_SLT: return 4; // 100
3669 case ICmpInst::ICMP_NE: return 5; // 101
3670 case ICmpInst::ICMP_ULE: return 6; // 110
3671 case ICmpInst::ICMP_SLE: return 6; // 110
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003672 // True -> 7
3673 default:
Torok Edwinc23197a2009-07-14 16:55:14 +00003674 llvm_unreachable("Invalid ICmp predicate!");
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003675 return 0;
3676 }
3677}
3678
Evan Cheng8db90722008-10-14 17:15:11 +00003679/// getFCmpCode - Similar to getICmpCode but for FCmpInst. This encodes a fcmp
3680/// predicate into a three bit mask. It also returns whether it is an ordered
3681/// predicate by reference.
3682static unsigned getFCmpCode(FCmpInst::Predicate CC, bool &isOrdered) {
3683 isOrdered = false;
3684 switch (CC) {
3685 case FCmpInst::FCMP_ORD: isOrdered = true; return 0; // 000
3686 case FCmpInst::FCMP_UNO: return 0; // 000
Evan Cheng4990b252008-10-14 18:13:38 +00003687 case FCmpInst::FCMP_OGT: isOrdered = true; return 1; // 001
3688 case FCmpInst::FCMP_UGT: return 1; // 001
3689 case FCmpInst::FCMP_OEQ: isOrdered = true; return 2; // 010
3690 case FCmpInst::FCMP_UEQ: return 2; // 010
Evan Cheng8db90722008-10-14 17:15:11 +00003691 case FCmpInst::FCMP_OGE: isOrdered = true; return 3; // 011
3692 case FCmpInst::FCMP_UGE: return 3; // 011
3693 case FCmpInst::FCMP_OLT: isOrdered = true; return 4; // 100
3694 case FCmpInst::FCMP_ULT: return 4; // 100
Evan Cheng4990b252008-10-14 18:13:38 +00003695 case FCmpInst::FCMP_ONE: isOrdered = true; return 5; // 101
3696 case FCmpInst::FCMP_UNE: return 5; // 101
Evan Cheng8db90722008-10-14 17:15:11 +00003697 case FCmpInst::FCMP_OLE: isOrdered = true; return 6; // 110
3698 case FCmpInst::FCMP_ULE: return 6; // 110
Evan Cheng40300622008-10-14 18:44:08 +00003699 // True -> 7
Evan Cheng8db90722008-10-14 17:15:11 +00003700 default:
3701 // Not expecting FCMP_FALSE and FCMP_TRUE;
Torok Edwinc23197a2009-07-14 16:55:14 +00003702 llvm_unreachable("Unexpected FCmp predicate!");
Evan Cheng8db90722008-10-14 17:15:11 +00003703 return 0;
3704 }
3705}
3706
Reid Spencere4d87aa2006-12-23 06:05:41 +00003707/// getICmpValue - This is the complement of getICmpCode, which turns an
3708/// opcode and two operands into either a constant true or false, or a brand
Dan Gohman5d066ff2007-09-17 17:31:57 +00003709/// new ICmp instruction. The sign is passed in to determine which kind
Evan Cheng8db90722008-10-14 17:15:11 +00003710/// of predicate to use in the new icmp instruction.
Owen Andersond672ecb2009-07-03 00:17:18 +00003711static Value *getICmpValue(bool sign, unsigned code, Value *LHS, Value *RHS,
Owen Anderson07cf79e2009-07-06 23:00:19 +00003712 LLVMContext *Context) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00003713 switch (code) {
Torok Edwinc23197a2009-07-14 16:55:14 +00003714 default: llvm_unreachable("Illegal ICmp code!");
Owen Anderson5defacc2009-07-31 17:39:07 +00003715 case 0: return ConstantInt::getFalse(*Context);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003716 case 1:
3717 if (sign)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003718 return new ICmpInst(ICmpInst::ICMP_SGT, LHS, RHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003719 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003720 return new ICmpInst(ICmpInst::ICMP_UGT, LHS, RHS);
3721 case 2: return new ICmpInst(ICmpInst::ICMP_EQ, LHS, RHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003722 case 3:
3723 if (sign)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003724 return new ICmpInst(ICmpInst::ICMP_SGE, LHS, RHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003725 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003726 return new ICmpInst(ICmpInst::ICMP_UGE, LHS, RHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003727 case 4:
3728 if (sign)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003729 return new ICmpInst(ICmpInst::ICMP_SLT, LHS, RHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003730 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003731 return new ICmpInst(ICmpInst::ICMP_ULT, LHS, RHS);
3732 case 5: return new ICmpInst(ICmpInst::ICMP_NE, LHS, RHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003733 case 6:
3734 if (sign)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003735 return new ICmpInst(ICmpInst::ICMP_SLE, LHS, RHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003736 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003737 return new ICmpInst(ICmpInst::ICMP_ULE, LHS, RHS);
Owen Anderson5defacc2009-07-31 17:39:07 +00003738 case 7: return ConstantInt::getTrue(*Context);
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003739 }
3740}
3741
Evan Cheng8db90722008-10-14 17:15:11 +00003742/// getFCmpValue - This is the complement of getFCmpCode, which turns an
3743/// opcode and two operands into either a FCmp instruction. isordered is passed
3744/// in to determine which kind of predicate to use in the new fcmp instruction.
3745static Value *getFCmpValue(bool isordered, unsigned code,
Owen Anderson07cf79e2009-07-06 23:00:19 +00003746 Value *LHS, Value *RHS, LLVMContext *Context) {
Evan Cheng8db90722008-10-14 17:15:11 +00003747 switch (code) {
Torok Edwinc23197a2009-07-14 16:55:14 +00003748 default: llvm_unreachable("Illegal FCmp code!");
Evan Cheng8db90722008-10-14 17:15:11 +00003749 case 0:
3750 if (isordered)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003751 return new FCmpInst(FCmpInst::FCMP_ORD, LHS, RHS);
Evan Cheng8db90722008-10-14 17:15:11 +00003752 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003753 return new FCmpInst(FCmpInst::FCMP_UNO, LHS, RHS);
Evan Cheng8db90722008-10-14 17:15:11 +00003754 case 1:
3755 if (isordered)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003756 return new FCmpInst(FCmpInst::FCMP_OGT, LHS, RHS);
Evan Cheng8db90722008-10-14 17:15:11 +00003757 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003758 return new FCmpInst(FCmpInst::FCMP_UGT, LHS, RHS);
Evan Cheng4990b252008-10-14 18:13:38 +00003759 case 2:
3760 if (isordered)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003761 return new FCmpInst(FCmpInst::FCMP_OEQ, LHS, RHS);
Evan Cheng4990b252008-10-14 18:13:38 +00003762 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003763 return new FCmpInst(FCmpInst::FCMP_UEQ, LHS, RHS);
Evan Cheng8db90722008-10-14 17:15:11 +00003764 case 3:
3765 if (isordered)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003766 return new FCmpInst(FCmpInst::FCMP_OGE, LHS, RHS);
Evan Cheng8db90722008-10-14 17:15:11 +00003767 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003768 return new FCmpInst(FCmpInst::FCMP_UGE, LHS, RHS);
Evan Cheng8db90722008-10-14 17:15:11 +00003769 case 4:
3770 if (isordered)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003771 return new FCmpInst(FCmpInst::FCMP_OLT, LHS, RHS);
Evan Cheng8db90722008-10-14 17:15:11 +00003772 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003773 return new FCmpInst(FCmpInst::FCMP_ULT, LHS, RHS);
Evan Cheng8db90722008-10-14 17:15:11 +00003774 case 5:
3775 if (isordered)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003776 return new FCmpInst(FCmpInst::FCMP_ONE, LHS, RHS);
Evan Cheng4990b252008-10-14 18:13:38 +00003777 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003778 return new FCmpInst(FCmpInst::FCMP_UNE, LHS, RHS);
Evan Cheng4990b252008-10-14 18:13:38 +00003779 case 6:
3780 if (isordered)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003781 return new FCmpInst(FCmpInst::FCMP_OLE, LHS, RHS);
Evan Cheng8db90722008-10-14 17:15:11 +00003782 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003783 return new FCmpInst(FCmpInst::FCMP_ULE, LHS, RHS);
Owen Anderson5defacc2009-07-31 17:39:07 +00003784 case 7: return ConstantInt::getTrue(*Context);
Evan Cheng8db90722008-10-14 17:15:11 +00003785 }
3786}
3787
Chris Lattnerb9553d62008-11-16 04:55:20 +00003788/// PredicatesFoldable - Return true if both predicates match sign or if at
3789/// least one of them is an equality comparison (which is signless).
Reid Spencere4d87aa2006-12-23 06:05:41 +00003790static bool PredicatesFoldable(ICmpInst::Predicate p1, ICmpInst::Predicate p2) {
Nick Lewycky4a134af2009-10-25 05:20:17 +00003791 return (CmpInst::isSigned(p1) == CmpInst::isSigned(p2)) ||
3792 (CmpInst::isSigned(p1) && ICmpInst::isEquality(p2)) ||
3793 (CmpInst::isSigned(p2) && ICmpInst::isEquality(p1));
Reid Spencere4d87aa2006-12-23 06:05:41 +00003794}
3795
3796namespace {
3797// FoldICmpLogical - Implements (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
3798struct FoldICmpLogical {
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003799 InstCombiner &IC;
3800 Value *LHS, *RHS;
Reid Spencere4d87aa2006-12-23 06:05:41 +00003801 ICmpInst::Predicate pred;
3802 FoldICmpLogical(InstCombiner &ic, ICmpInst *ICI)
3803 : IC(ic), LHS(ICI->getOperand(0)), RHS(ICI->getOperand(1)),
3804 pred(ICI->getPredicate()) {}
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003805 bool shouldApply(Value *V) const {
Reid Spencere4d87aa2006-12-23 06:05:41 +00003806 if (ICmpInst *ICI = dyn_cast<ICmpInst>(V))
3807 if (PredicatesFoldable(pred, ICI->getPredicate()))
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00003808 return ((ICI->getOperand(0) == LHS && ICI->getOperand(1) == RHS) ||
3809 (ICI->getOperand(0) == RHS && ICI->getOperand(1) == LHS));
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003810 return false;
3811 }
Reid Spencere4d87aa2006-12-23 06:05:41 +00003812 Instruction *apply(Instruction &Log) const {
3813 ICmpInst *ICI = cast<ICmpInst>(Log.getOperand(0));
3814 if (ICI->getOperand(0) != LHS) {
3815 assert(ICI->getOperand(1) == LHS);
3816 ICI->swapOperands(); // Swap the LHS and RHS of the ICmp
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003817 }
3818
Chris Lattnerbc1dbfc2007-03-13 14:27:42 +00003819 ICmpInst *RHSICI = cast<ICmpInst>(Log.getOperand(1));
Reid Spencere4d87aa2006-12-23 06:05:41 +00003820 unsigned LHSCode = getICmpCode(ICI);
Chris Lattnerbc1dbfc2007-03-13 14:27:42 +00003821 unsigned RHSCode = getICmpCode(RHSICI);
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003822 unsigned Code;
3823 switch (Log.getOpcode()) {
3824 case Instruction::And: Code = LHSCode & RHSCode; break;
3825 case Instruction::Or: Code = LHSCode | RHSCode; break;
3826 case Instruction::Xor: Code = LHSCode ^ RHSCode; break;
Torok Edwinc23197a2009-07-14 16:55:14 +00003827 default: llvm_unreachable("Illegal logical opcode!"); return 0;
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003828 }
3829
Nick Lewycky4a134af2009-10-25 05:20:17 +00003830 bool isSigned = RHSICI->isSigned() || ICI->isSigned();
Owen Andersond672ecb2009-07-03 00:17:18 +00003831 Value *RV = getICmpValue(isSigned, Code, LHS, RHS, IC.getContext());
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003832 if (Instruction *I = dyn_cast<Instruction>(RV))
3833 return I;
3834 // Otherwise, it's a constant boolean value...
3835 return IC.ReplaceInstUsesWith(Log, RV);
3836 }
3837};
Chris Lattnerd23b5ba2006-11-15 04:53:24 +00003838} // end anonymous namespace
Chris Lattneraa9c1f12003-08-13 20:16:26 +00003839
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003840// OptAndOp - This handles expressions of the form ((val OP C1) & C2). Where
3841// the Op parameter is 'OP', OpRHS is 'C1', and AndRHS is 'C2'. Op is
Reid Spencer832254e2007-02-02 02:16:23 +00003842// guaranteed to be a binary operator.
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003843Instruction *InstCombiner::OptAndOp(Instruction *Op,
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003844 ConstantInt *OpRHS,
3845 ConstantInt *AndRHS,
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003846 BinaryOperator &TheAnd) {
3847 Value *X = Op->getOperand(0);
Chris Lattner76f7fe22004-01-12 19:47:05 +00003848 Constant *Together = 0;
Reid Spencer832254e2007-02-02 02:16:23 +00003849 if (!Op->isShift())
Owen Andersonbaf3c402009-07-29 18:55:55 +00003850 Together = ConstantExpr::getAnd(AndRHS, OpRHS);
Chris Lattner7c4049c2004-01-12 19:35:11 +00003851
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003852 switch (Op->getOpcode()) {
3853 case Instruction::Xor:
Chris Lattner6e7ba452005-01-01 16:22:27 +00003854 if (Op->hasOneUse()) {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003855 // (X ^ C1) & C2 --> (X & C2) ^ (C1&C2)
Chris Lattner74381062009-08-30 07:44:24 +00003856 Value *And = Builder->CreateAnd(X, AndRHS);
Chris Lattner6934a042007-02-11 01:23:03 +00003857 And->takeName(Op);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003858 return BinaryOperator::CreateXor(And, Together);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003859 }
3860 break;
3861 case Instruction::Or:
Chris Lattner6e7ba452005-01-01 16:22:27 +00003862 if (Together == AndRHS) // (X | C) & C --> C
3863 return ReplaceInstUsesWith(TheAnd, AndRHS);
Misha Brukmanfd939082005-04-21 23:48:37 +00003864
Chris Lattner6e7ba452005-01-01 16:22:27 +00003865 if (Op->hasOneUse() && Together != OpRHS) {
3866 // (X | C1) & C2 --> (X | (C1&C2)) & C2
Chris Lattner74381062009-08-30 07:44:24 +00003867 Value *Or = Builder->CreateOr(X, Together);
Chris Lattner6934a042007-02-11 01:23:03 +00003868 Or->takeName(Op);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003869 return BinaryOperator::CreateAnd(Or, AndRHS);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003870 }
3871 break;
3872 case Instruction::Add:
Chris Lattnerfd059242003-10-15 16:48:29 +00003873 if (Op->hasOneUse()) {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003874 // Adding a one to a single bit bit-field should be turned into an XOR
3875 // of the bit. First thing to check is to see if this AND is with a
3876 // single bit constant.
Zhou Sheng3a507fd2007-04-01 17:13:37 +00003877 const APInt& AndRHSV = cast<ConstantInt>(AndRHS)->getValue();
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003878
3879 // If there is only one bit set...
Chris Lattner457dd822004-06-09 07:59:58 +00003880 if (isOneBitSet(cast<ConstantInt>(AndRHS))) {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003881 // Ok, at this point, we know that we are masking the result of the
3882 // ADD down to exactly one bit. If the constant we are adding has
3883 // no bits set below this bit, then we can eliminate the ADD.
Zhou Sheng3a507fd2007-04-01 17:13:37 +00003884 const APInt& AddRHS = cast<ConstantInt>(OpRHS)->getValue();
Misha Brukmanfd939082005-04-21 23:48:37 +00003885
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003886 // Check to see if any bits below the one bit set in AndRHSV are set.
3887 if ((AddRHS & (AndRHSV-1)) == 0) {
3888 // If not, the only thing that can effect the output of the AND is
3889 // the bit specified by AndRHSV. If that bit is set, the effect of
3890 // the XOR is to toggle the bit. If it is clear, then the ADD has
3891 // no effect.
3892 if ((AddRHS & AndRHSV) == 0) { // Bit is not set, noop
3893 TheAnd.setOperand(0, X);
3894 return &TheAnd;
3895 } else {
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003896 // Pull the XOR out of the AND.
Chris Lattner74381062009-08-30 07:44:24 +00003897 Value *NewAnd = Builder->CreateAnd(X, AndRHS);
Chris Lattner6934a042007-02-11 01:23:03 +00003898 NewAnd->takeName(Op);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003899 return BinaryOperator::CreateXor(NewAnd, AndRHS);
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003900 }
3901 }
3902 }
3903 }
3904 break;
Chris Lattner62a355c2003-09-19 19:05:02 +00003905
3906 case Instruction::Shl: {
3907 // We know that the AND will not produce any of the bits shifted in, so if
3908 // the anded constant includes them, clear them now!
3909 //
Zhou Sheng290bec52007-03-29 08:15:12 +00003910 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00003911 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
Zhou Sheng290bec52007-03-29 08:15:12 +00003912 APInt ShlMask(APInt::getHighBitsSet(BitWidth, BitWidth-OpRHSVal));
Owen Andersoneed707b2009-07-24 23:12:02 +00003913 ConstantInt *CI = ConstantInt::get(*Context, AndRHS->getValue() & ShlMask);
Misha Brukmanfd939082005-04-21 23:48:37 +00003914
Zhou Sheng290bec52007-03-29 08:15:12 +00003915 if (CI->getValue() == ShlMask) {
3916 // Masking out bits that the shift already masks
Chris Lattner0c967662004-09-24 15:21:34 +00003917 return ReplaceInstUsesWith(TheAnd, Op); // No need for the and.
3918 } else if (CI != AndRHS) { // Reducing bits set in and.
Chris Lattner62a355c2003-09-19 19:05:02 +00003919 TheAnd.setOperand(1, CI);
3920 return &TheAnd;
3921 }
3922 break;
Misha Brukmanfd939082005-04-21 23:48:37 +00003923 }
Reid Spencer3822ff52006-11-08 06:47:33 +00003924 case Instruction::LShr:
3925 {
Chris Lattner62a355c2003-09-19 19:05:02 +00003926 // We know that the AND will not produce any of the bits shifted in, so if
3927 // the anded constant includes them, clear them now! This only applies to
3928 // unsigned shifts, because a signed shr may bring in set bits!
3929 //
Zhou Sheng290bec52007-03-29 08:15:12 +00003930 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00003931 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
Zhou Sheng290bec52007-03-29 08:15:12 +00003932 APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
Owen Andersoneed707b2009-07-24 23:12:02 +00003933 ConstantInt *CI = ConstantInt::get(*Context, AndRHS->getValue() & ShrMask);
Chris Lattner0c967662004-09-24 15:21:34 +00003934
Zhou Sheng290bec52007-03-29 08:15:12 +00003935 if (CI->getValue() == ShrMask) {
3936 // Masking out bits that the shift already masks.
Reid Spencer3822ff52006-11-08 06:47:33 +00003937 return ReplaceInstUsesWith(TheAnd, Op);
3938 } else if (CI != AndRHS) {
3939 TheAnd.setOperand(1, CI); // Reduce bits set in and cst.
3940 return &TheAnd;
3941 }
3942 break;
3943 }
3944 case Instruction::AShr:
3945 // Signed shr.
3946 // See if this is shifting in some sign extension, then masking it out
3947 // with an and.
3948 if (Op->hasOneUse()) {
Zhou Sheng290bec52007-03-29 08:15:12 +00003949 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00003950 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
Zhou Sheng290bec52007-03-29 08:15:12 +00003951 APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
Owen Andersoneed707b2009-07-24 23:12:02 +00003952 Constant *C = ConstantInt::get(*Context, AndRHS->getValue() & ShrMask);
Reid Spencer7eb76382006-12-13 17:19:09 +00003953 if (C == AndRHS) { // Masking out bits shifted in.
Reid Spencer17212df2006-12-12 09:18:51 +00003954 // (Val ashr C1) & C2 -> (Val lshr C1) & C2
Reid Spencer3822ff52006-11-08 06:47:33 +00003955 // Make the argument unsigned.
3956 Value *ShVal = Op->getOperand(0);
Chris Lattner74381062009-08-30 07:44:24 +00003957 ShVal = Builder->CreateLShr(ShVal, OpRHS, Op->getName());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00003958 return BinaryOperator::CreateAnd(ShVal, AndRHS, TheAnd.getName());
Chris Lattner0c967662004-09-24 15:21:34 +00003959 }
Chris Lattner62a355c2003-09-19 19:05:02 +00003960 }
3961 break;
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00003962 }
3963 return 0;
3964}
3965
Chris Lattner8b170942002-08-09 23:47:40 +00003966
Chris Lattnera96879a2004-09-29 17:40:11 +00003967/// InsertRangeTest - Emit a computation of: (V >= Lo && V < Hi) if Inside is
3968/// true, otherwise (V < Lo || V >= Hi). In pratice, we emit the more efficient
Reid Spencere4d87aa2006-12-23 06:05:41 +00003969/// (V-Lo) <u Hi-Lo. This method expects that Lo <= Hi. isSigned indicates
3970/// whether to treat the V, Lo and HI as signed or not. IB is the location to
Chris Lattnera96879a2004-09-29 17:40:11 +00003971/// insert new instructions.
3972Instruction *InstCombiner::InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
Reid Spencere4d87aa2006-12-23 06:05:41 +00003973 bool isSigned, bool Inside,
3974 Instruction &IB) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00003975 assert(cast<ConstantInt>(ConstantExpr::getICmp((isSigned ?
Reid Spencer579dca12007-01-12 04:24:46 +00003976 ICmpInst::ICMP_SLE:ICmpInst::ICMP_ULE), Lo, Hi))->getZExtValue() &&
Chris Lattnera96879a2004-09-29 17:40:11 +00003977 "Lo is not <= Hi in range emission code!");
Reid Spencere4d87aa2006-12-23 06:05:41 +00003978
Chris Lattnera96879a2004-09-29 17:40:11 +00003979 if (Inside) {
3980 if (Lo == Hi) // Trivially false.
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003981 return new ICmpInst(ICmpInst::ICMP_NE, V, V);
Misha Brukmanfd939082005-04-21 23:48:37 +00003982
Reid Spencere4d87aa2006-12-23 06:05:41 +00003983 // V >= Min && V < Hi --> V < Hi
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00003984 if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
Reid Spencere4e40032007-03-21 23:19:50 +00003985 ICmpInst::Predicate pred = (isSigned ?
Reid Spencere4d87aa2006-12-23 06:05:41 +00003986 ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT);
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003987 return new ICmpInst(pred, V, Hi);
Reid Spencere4d87aa2006-12-23 06:05:41 +00003988 }
3989
3990 // Emit V-Lo <u Hi-Lo
Owen Andersonbaf3c402009-07-29 18:55:55 +00003991 Constant *NegLo = ConstantExpr::getNeg(Lo);
Chris Lattner74381062009-08-30 07:44:24 +00003992 Value *Add = Builder->CreateAdd(V, NegLo, V->getName()+".off");
Owen Andersonbaf3c402009-07-29 18:55:55 +00003993 Constant *UpperBound = ConstantExpr::getAdd(NegLo, Hi);
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003994 return new ICmpInst(ICmpInst::ICMP_ULT, Add, UpperBound);
Chris Lattnera96879a2004-09-29 17:40:11 +00003995 }
3996
3997 if (Lo == Hi) // Trivially true.
Dan Gohman1c8a23c2009-08-25 23:17:54 +00003998 return new ICmpInst(ICmpInst::ICMP_EQ, V, V);
Chris Lattnera96879a2004-09-29 17:40:11 +00003999
Reid Spencere4e40032007-03-21 23:19:50 +00004000 // V < Min || V >= Hi -> V > Hi-1
Dan Gohman186a6362009-08-12 16:04:34 +00004001 Hi = SubOne(cast<ConstantInt>(Hi));
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004002 if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00004003 ICmpInst::Predicate pred = (isSigned ?
4004 ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT);
Dan Gohman1c8a23c2009-08-25 23:17:54 +00004005 return new ICmpInst(pred, V, Hi);
Reid Spencere4d87aa2006-12-23 06:05:41 +00004006 }
Reid Spencerb83eb642006-10-20 07:07:24 +00004007
Reid Spencere4e40032007-03-21 23:19:50 +00004008 // Emit V-Lo >u Hi-1-Lo
4009 // Note that Hi has already had one subtracted from it, above.
Owen Andersonbaf3c402009-07-29 18:55:55 +00004010 ConstantInt *NegLo = cast<ConstantInt>(ConstantExpr::getNeg(Lo));
Chris Lattner74381062009-08-30 07:44:24 +00004011 Value *Add = Builder->CreateAdd(V, NegLo, V->getName()+".off");
Owen Andersonbaf3c402009-07-29 18:55:55 +00004012 Constant *LowerBound = ConstantExpr::getAdd(NegLo, Hi);
Dan Gohman1c8a23c2009-08-25 23:17:54 +00004013 return new ICmpInst(ICmpInst::ICMP_UGT, Add, LowerBound);
Chris Lattnera96879a2004-09-29 17:40:11 +00004014}
4015
Chris Lattner7203e152005-09-18 07:22:02 +00004016// isRunOfOnes - Returns true iff Val consists of one contiguous run of 1s with
4017// any number of 0s on either side. The 1s are allowed to wrap from LSB to
4018// MSB, so 0x000FFF0, 0x0000FFFF, and 0xFF0000FF are all runs. 0x0F0F0000 is
4019// not, since all 1s are not contiguous.
Zhou Sheng4351c642007-04-02 08:20:41 +00004020static bool isRunOfOnes(ConstantInt *Val, uint32_t &MB, uint32_t &ME) {
Zhou Sheng3a507fd2007-04-01 17:13:37 +00004021 const APInt& V = Val->getValue();
Reid Spencerf2442522007-03-24 00:42:08 +00004022 uint32_t BitWidth = Val->getType()->getBitWidth();
4023 if (!APIntOps::isShiftedMask(BitWidth, V)) return false;
Chris Lattner7203e152005-09-18 07:22:02 +00004024
4025 // look for the first zero bit after the run of ones
Reid Spencerf2442522007-03-24 00:42:08 +00004026 MB = BitWidth - ((V - 1) ^ V).countLeadingZeros();
Chris Lattner7203e152005-09-18 07:22:02 +00004027 // look for the first non-zero bit
Reid Spencerf2442522007-03-24 00:42:08 +00004028 ME = V.getActiveBits();
Chris Lattner7203e152005-09-18 07:22:02 +00004029 return true;
4030}
4031
Chris Lattner7203e152005-09-18 07:22:02 +00004032/// FoldLogicalPlusAnd - This is part of an expression (LHS +/- RHS) & Mask,
4033/// where isSub determines whether the operator is a sub. If we can fold one of
4034/// the following xforms:
Chris Lattnerc8e77562005-09-18 04:24:45 +00004035///
4036/// ((A & N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == Mask
4037/// ((A | N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
4038/// ((A ^ N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
4039///
4040/// return (A +/- B).
4041///
4042Value *InstCombiner::FoldLogicalPlusAnd(Value *LHS, Value *RHS,
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004043 ConstantInt *Mask, bool isSub,
Chris Lattnerc8e77562005-09-18 04:24:45 +00004044 Instruction &I) {
4045 Instruction *LHSI = dyn_cast<Instruction>(LHS);
4046 if (!LHSI || LHSI->getNumOperands() != 2 ||
4047 !isa<ConstantInt>(LHSI->getOperand(1))) return 0;
4048
4049 ConstantInt *N = cast<ConstantInt>(LHSI->getOperand(1));
4050
4051 switch (LHSI->getOpcode()) {
4052 default: return 0;
4053 case Instruction::And:
Owen Andersonbaf3c402009-07-29 18:55:55 +00004054 if (ConstantExpr::getAnd(N, Mask) == Mask) {
Chris Lattner7203e152005-09-18 07:22:02 +00004055 // If the AndRHS is a power of two minus one (0+1+), this is simple.
Zhou Sheng00f436c2007-03-24 15:34:37 +00004056 if ((Mask->getValue().countLeadingZeros() +
4057 Mask->getValue().countPopulation()) ==
4058 Mask->getValue().getBitWidth())
Chris Lattner7203e152005-09-18 07:22:02 +00004059 break;
4060
4061 // Otherwise, if Mask is 0+1+0+, and if B is known to have the low 0+
4062 // part, we don't need any explicit masks to take them out of A. If that
4063 // is all N is, ignore it.
Zhou Sheng4351c642007-04-02 08:20:41 +00004064 uint32_t MB = 0, ME = 0;
Chris Lattner7203e152005-09-18 07:22:02 +00004065 if (isRunOfOnes(Mask, MB, ME)) { // begin/end bit of run, inclusive
Reid Spencerb35ae032007-03-23 18:46:34 +00004066 uint32_t BitWidth = cast<IntegerType>(RHS->getType())->getBitWidth();
Zhou Sheng290bec52007-03-29 08:15:12 +00004067 APInt Mask(APInt::getLowBitsSet(BitWidth, MB-1));
Chris Lattner3bedbd92006-02-07 07:27:52 +00004068 if (MaskedValueIsZero(RHS, Mask))
Chris Lattner7203e152005-09-18 07:22:02 +00004069 break;
4070 }
4071 }
Chris Lattnerc8e77562005-09-18 04:24:45 +00004072 return 0;
4073 case Instruction::Or:
4074 case Instruction::Xor:
Chris Lattner7203e152005-09-18 07:22:02 +00004075 // If the AndRHS is a power of two minus one (0+1+), and N&Mask == 0
Zhou Sheng00f436c2007-03-24 15:34:37 +00004076 if ((Mask->getValue().countLeadingZeros() +
4077 Mask->getValue().countPopulation()) == Mask->getValue().getBitWidth()
Owen Andersonbaf3c402009-07-29 18:55:55 +00004078 && ConstantExpr::getAnd(N, Mask)->isNullValue())
Chris Lattnerc8e77562005-09-18 04:24:45 +00004079 break;
4080 return 0;
4081 }
4082
Chris Lattnerc8e77562005-09-18 04:24:45 +00004083 if (isSub)
Chris Lattner74381062009-08-30 07:44:24 +00004084 return Builder->CreateSub(LHSI->getOperand(0), RHS, "fold");
4085 return Builder->CreateAdd(LHSI->getOperand(0), RHS, "fold");
Chris Lattnerc8e77562005-09-18 04:24:45 +00004086}
4087
Chris Lattner29cd5ba2008-11-16 05:06:21 +00004088/// FoldAndOfICmps - Fold (icmp)&(icmp) if possible.
4089Instruction *InstCombiner::FoldAndOfICmps(Instruction &I,
4090 ICmpInst *LHS, ICmpInst *RHS) {
Chris Lattnerea065fb2008-11-16 05:10:52 +00004091 Value *Val, *Val2;
Chris Lattner29cd5ba2008-11-16 05:06:21 +00004092 ConstantInt *LHSCst, *RHSCst;
4093 ICmpInst::Predicate LHSCC, RHSCC;
4094
Chris Lattnerea065fb2008-11-16 05:10:52 +00004095 // This only handles icmp of constants: (icmp1 A, C1) & (icmp2 B, C2).
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004096 if (!match(LHS, m_ICmp(LHSCC, m_Value(Val),
Dan Gohman4ae51262009-08-12 16:23:25 +00004097 m_ConstantInt(LHSCst))) ||
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004098 !match(RHS, m_ICmp(RHSCC, m_Value(Val2),
Dan Gohman4ae51262009-08-12 16:23:25 +00004099 m_ConstantInt(RHSCst))))
Chris Lattner29cd5ba2008-11-16 05:06:21 +00004100 return 0;
Chris Lattnerea065fb2008-11-16 05:10:52 +00004101
Chris Lattner3f40e232009-11-29 00:51:17 +00004102 if (LHSCst == RHSCst && LHSCC == RHSCC) {
4103 // (icmp ult A, C) & (icmp ult B, C) --> (icmp ult (A|B), C)
4104 // where C is a power of 2
4105 if (LHSCC == ICmpInst::ICMP_ULT &&
4106 LHSCst->getValue().isPowerOf2()) {
4107 Value *NewOr = Builder->CreateOr(Val, Val2);
4108 return new ICmpInst(LHSCC, NewOr, LHSCst);
4109 }
4110
4111 // (icmp eq A, 0) & (icmp eq B, 0) --> (icmp eq (A|B), 0)
4112 if (LHSCC == ICmpInst::ICMP_EQ && LHSCst->isZero()) {
4113 Value *NewOr = Builder->CreateOr(Val, Val2);
4114 return new ICmpInst(LHSCC, NewOr, LHSCst);
4115 }
Chris Lattnerea065fb2008-11-16 05:10:52 +00004116 }
4117
4118 // From here on, we only handle:
4119 // (icmp1 A, C1) & (icmp2 A, C2) --> something simpler.
4120 if (Val != Val2) return 0;
4121
Chris Lattner29cd5ba2008-11-16 05:06:21 +00004122 // ICMP_[US][GL]E X, CST is folded to ICMP_[US][GL]T elsewhere.
4123 if (LHSCC == ICmpInst::ICMP_UGE || LHSCC == ICmpInst::ICMP_ULE ||
4124 RHSCC == ICmpInst::ICMP_UGE || RHSCC == ICmpInst::ICMP_ULE ||
4125 LHSCC == ICmpInst::ICMP_SGE || LHSCC == ICmpInst::ICMP_SLE ||
4126 RHSCC == ICmpInst::ICMP_SGE || RHSCC == ICmpInst::ICMP_SLE)
4127 return 0;
4128
4129 // We can't fold (ugt x, C) & (sgt x, C2).
4130 if (!PredicatesFoldable(LHSCC, RHSCC))
4131 return 0;
4132
4133 // Ensure that the larger constant is on the RHS.
Chris Lattneraa3e1572008-11-16 05:14:43 +00004134 bool ShouldSwap;
Nick Lewycky4a134af2009-10-25 05:20:17 +00004135 if (CmpInst::isSigned(LHSCC) ||
Chris Lattner29cd5ba2008-11-16 05:06:21 +00004136 (ICmpInst::isEquality(LHSCC) &&
Nick Lewycky4a134af2009-10-25 05:20:17 +00004137 CmpInst::isSigned(RHSCC)))
Chris Lattneraa3e1572008-11-16 05:14:43 +00004138 ShouldSwap = LHSCst->getValue().sgt(RHSCst->getValue());
Chris Lattner29cd5ba2008-11-16 05:06:21 +00004139 else
Chris Lattneraa3e1572008-11-16 05:14:43 +00004140 ShouldSwap = LHSCst->getValue().ugt(RHSCst->getValue());
4141
4142 if (ShouldSwap) {
Chris Lattner29cd5ba2008-11-16 05:06:21 +00004143 std::swap(LHS, RHS);
4144 std::swap(LHSCst, RHSCst);
4145 std::swap(LHSCC, RHSCC);
4146 }
4147
4148 // At this point, we know we have have two icmp instructions
4149 // comparing a value against two constants and and'ing the result
4150 // together. Because of the above check, we know that we only have
4151 // icmp eq, icmp ne, icmp [su]lt, and icmp [SU]gt here. We also know
4152 // (from the FoldICmpLogical check above), that the two constants
4153 // are not equal and that the larger constant is on the RHS
4154 assert(LHSCst != RHSCst && "Compares not folded above?");
4155
4156 switch (LHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00004157 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner29cd5ba2008-11-16 05:06:21 +00004158 case ICmpInst::ICMP_EQ:
4159 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00004160 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner29cd5ba2008-11-16 05:06:21 +00004161 case ICmpInst::ICMP_EQ: // (X == 13 & X == 15) -> false
4162 case ICmpInst::ICMP_UGT: // (X == 13 & X > 15) -> false
4163 case ICmpInst::ICMP_SGT: // (X == 13 & X > 15) -> false
Owen Anderson5defacc2009-07-31 17:39:07 +00004164 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Chris Lattner29cd5ba2008-11-16 05:06:21 +00004165 case ICmpInst::ICMP_NE: // (X == 13 & X != 15) -> X == 13
4166 case ICmpInst::ICMP_ULT: // (X == 13 & X < 15) -> X == 13
4167 case ICmpInst::ICMP_SLT: // (X == 13 & X < 15) -> X == 13
4168 return ReplaceInstUsesWith(I, LHS);
4169 }
4170 case ICmpInst::ICMP_NE:
4171 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00004172 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner29cd5ba2008-11-16 05:06:21 +00004173 case ICmpInst::ICMP_ULT:
Dan Gohman186a6362009-08-12 16:04:34 +00004174 if (LHSCst == SubOne(RHSCst)) // (X != 13 & X u< 14) -> X < 13
Dan Gohman1c8a23c2009-08-25 23:17:54 +00004175 return new ICmpInst(ICmpInst::ICMP_ULT, Val, LHSCst);
Chris Lattner29cd5ba2008-11-16 05:06:21 +00004176 break; // (X != 13 & X u< 15) -> no change
4177 case ICmpInst::ICMP_SLT:
Dan Gohman186a6362009-08-12 16:04:34 +00004178 if (LHSCst == SubOne(RHSCst)) // (X != 13 & X s< 14) -> X < 13
Dan Gohman1c8a23c2009-08-25 23:17:54 +00004179 return new ICmpInst(ICmpInst::ICMP_SLT, Val, LHSCst);
Chris Lattner29cd5ba2008-11-16 05:06:21 +00004180 break; // (X != 13 & X s< 15) -> no change
4181 case ICmpInst::ICMP_EQ: // (X != 13 & X == 15) -> X == 15
4182 case ICmpInst::ICMP_UGT: // (X != 13 & X u> 15) -> X u> 15
4183 case ICmpInst::ICMP_SGT: // (X != 13 & X s> 15) -> X s> 15
4184 return ReplaceInstUsesWith(I, RHS);
4185 case ICmpInst::ICMP_NE:
Dan Gohman186a6362009-08-12 16:04:34 +00004186 if (LHSCst == SubOne(RHSCst)){// (X != 13 & X != 14) -> X-13 >u 1
Owen Andersonbaf3c402009-07-29 18:55:55 +00004187 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
Chris Lattner74381062009-08-30 07:44:24 +00004188 Value *Add = Builder->CreateAdd(Val, AddCST, Val->getName()+".off");
Dan Gohman1c8a23c2009-08-25 23:17:54 +00004189 return new ICmpInst(ICmpInst::ICMP_UGT, Add,
Owen Andersoneed707b2009-07-24 23:12:02 +00004190 ConstantInt::get(Add->getType(), 1));
Chris Lattner29cd5ba2008-11-16 05:06:21 +00004191 }
4192 break; // (X != 13 & X != 15) -> no change
4193 }
4194 break;
4195 case ICmpInst::ICMP_ULT:
4196 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00004197 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner29cd5ba2008-11-16 05:06:21 +00004198 case ICmpInst::ICMP_EQ: // (X u< 13 & X == 15) -> false
4199 case ICmpInst::ICMP_UGT: // (X u< 13 & X u> 15) -> false
Owen Anderson5defacc2009-07-31 17:39:07 +00004200 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Chris Lattner29cd5ba2008-11-16 05:06:21 +00004201 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 u< 13
4204 case ICmpInst::ICMP_ULT: // (X u< 13 & X u< 15) -> X u< 13
4205 return ReplaceInstUsesWith(I, LHS);
4206 case ICmpInst::ICMP_SLT: // (X u< 13 & X s< 15) -> no change
4207 break;
4208 }
4209 break;
4210 case ICmpInst::ICMP_SLT:
4211 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00004212 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner29cd5ba2008-11-16 05:06:21 +00004213 case ICmpInst::ICMP_EQ: // (X s< 13 & X == 15) -> false
4214 case ICmpInst::ICMP_SGT: // (X s< 13 & X s> 15) -> false
Owen Anderson5defacc2009-07-31 17:39:07 +00004215 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Chris Lattner29cd5ba2008-11-16 05:06:21 +00004216 case ICmpInst::ICMP_UGT: // (X s< 13 & X u> 15) -> no change
4217 break;
4218 case ICmpInst::ICMP_NE: // (X s< 13 & X != 15) -> X < 13
4219 case ICmpInst::ICMP_SLT: // (X s< 13 & X s< 15) -> X < 13
4220 return ReplaceInstUsesWith(I, LHS);
4221 case ICmpInst::ICMP_ULT: // (X s< 13 & X u< 15) -> no change
4222 break;
4223 }
4224 break;
4225 case ICmpInst::ICMP_UGT:
4226 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00004227 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner29cd5ba2008-11-16 05:06:21 +00004228 case ICmpInst::ICMP_EQ: // (X u> 13 & X == 15) -> X == 15
4229 case ICmpInst::ICMP_UGT: // (X u> 13 & X u> 15) -> X u> 15
4230 return ReplaceInstUsesWith(I, RHS);
4231 case ICmpInst::ICMP_SGT: // (X u> 13 & X s> 15) -> no change
4232 break;
4233 case ICmpInst::ICMP_NE:
Dan Gohman186a6362009-08-12 16:04:34 +00004234 if (RHSCst == AddOne(LHSCst)) // (X u> 13 & X != 14) -> X u> 14
Dan Gohman1c8a23c2009-08-25 23:17:54 +00004235 return new ICmpInst(LHSCC, Val, RHSCst);
Chris Lattner29cd5ba2008-11-16 05:06:21 +00004236 break; // (X u> 13 & X != 15) -> no change
Chris Lattner69d4ced2008-11-16 05:20:07 +00004237 case ICmpInst::ICMP_ULT: // (X u> 13 & X u< 15) -> (X-14) <u 1
Dan Gohman186a6362009-08-12 16:04:34 +00004238 return InsertRangeTest(Val, AddOne(LHSCst),
Owen Andersond672ecb2009-07-03 00:17:18 +00004239 RHSCst, false, true, I);
Chris Lattner29cd5ba2008-11-16 05:06:21 +00004240 case ICmpInst::ICMP_SLT: // (X u> 13 & X s< 15) -> no change
4241 break;
4242 }
4243 break;
4244 case ICmpInst::ICMP_SGT:
4245 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00004246 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner29cd5ba2008-11-16 05:06:21 +00004247 case ICmpInst::ICMP_EQ: // (X s> 13 & X == 15) -> X == 15
4248 case ICmpInst::ICMP_SGT: // (X s> 13 & X s> 15) -> X s> 15
4249 return ReplaceInstUsesWith(I, RHS);
4250 case ICmpInst::ICMP_UGT: // (X s> 13 & X u> 15) -> no change
4251 break;
4252 case ICmpInst::ICMP_NE:
Dan Gohman186a6362009-08-12 16:04:34 +00004253 if (RHSCst == AddOne(LHSCst)) // (X s> 13 & X != 14) -> X s> 14
Dan Gohman1c8a23c2009-08-25 23:17:54 +00004254 return new ICmpInst(LHSCC, Val, RHSCst);
Chris Lattner29cd5ba2008-11-16 05:06:21 +00004255 break; // (X s> 13 & X != 15) -> no change
Chris Lattner69d4ced2008-11-16 05:20:07 +00004256 case ICmpInst::ICMP_SLT: // (X s> 13 & X s< 15) -> (X-14) s< 1
Dan Gohman186a6362009-08-12 16:04:34 +00004257 return InsertRangeTest(Val, AddOne(LHSCst),
Owen Andersond672ecb2009-07-03 00:17:18 +00004258 RHSCst, true, true, I);
Chris Lattner29cd5ba2008-11-16 05:06:21 +00004259 case ICmpInst::ICMP_ULT: // (X s> 13 & X u< 15) -> no change
4260 break;
4261 }
4262 break;
4263 }
Chris Lattner29cd5ba2008-11-16 05:06:21 +00004264
4265 return 0;
4266}
4267
Chris Lattner42d1be02009-07-23 05:14:02 +00004268Instruction *InstCombiner::FoldAndOfFCmps(Instruction &I, FCmpInst *LHS,
4269 FCmpInst *RHS) {
4270
4271 if (LHS->getPredicate() == FCmpInst::FCMP_ORD &&
4272 RHS->getPredicate() == FCmpInst::FCMP_ORD) {
4273 // (fcmp ord x, c) & (fcmp ord y, c) -> (fcmp ord x, y)
4274 if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
4275 if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
4276 // If either of the constants are nans, then the whole thing returns
4277 // false.
4278 if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
Owen Anderson5defacc2009-07-31 17:39:07 +00004279 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Dan Gohman1c8a23c2009-08-25 23:17:54 +00004280 return new FCmpInst(FCmpInst::FCMP_ORD,
Chris Lattner42d1be02009-07-23 05:14:02 +00004281 LHS->getOperand(0), RHS->getOperand(0));
4282 }
Chris Lattnerf98d2532009-07-23 05:32:17 +00004283
4284 // Handle vector zeros. This occurs because the canonical form of
4285 // "fcmp ord x,x" is "fcmp ord x, 0".
4286 if (isa<ConstantAggregateZero>(LHS->getOperand(1)) &&
4287 isa<ConstantAggregateZero>(RHS->getOperand(1)))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00004288 return new FCmpInst(FCmpInst::FCMP_ORD,
Chris Lattnerf98d2532009-07-23 05:32:17 +00004289 LHS->getOperand(0), RHS->getOperand(0));
Chris Lattner42d1be02009-07-23 05:14:02 +00004290 return 0;
4291 }
4292
4293 Value *Op0LHS = LHS->getOperand(0), *Op0RHS = LHS->getOperand(1);
4294 Value *Op1LHS = RHS->getOperand(0), *Op1RHS = RHS->getOperand(1);
4295 FCmpInst::Predicate Op0CC = LHS->getPredicate(), Op1CC = RHS->getPredicate();
4296
4297
4298 if (Op0LHS == Op1RHS && Op0RHS == Op1LHS) {
4299 // Swap RHS operands to match LHS.
4300 Op1CC = FCmpInst::getSwappedPredicate(Op1CC);
4301 std::swap(Op1LHS, Op1RHS);
4302 }
4303
4304 if (Op0LHS == Op1LHS && Op0RHS == Op1RHS) {
4305 // Simplify (fcmp cc0 x, y) & (fcmp cc1 x, y).
4306 if (Op0CC == Op1CC)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00004307 return new FCmpInst((FCmpInst::Predicate)Op0CC, Op0LHS, Op0RHS);
Chris Lattner42d1be02009-07-23 05:14:02 +00004308
4309 if (Op0CC == FCmpInst::FCMP_FALSE || Op1CC == FCmpInst::FCMP_FALSE)
Owen Anderson5defacc2009-07-31 17:39:07 +00004310 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Chris Lattner42d1be02009-07-23 05:14:02 +00004311 if (Op0CC == FCmpInst::FCMP_TRUE)
4312 return ReplaceInstUsesWith(I, RHS);
4313 if (Op1CC == FCmpInst::FCMP_TRUE)
4314 return ReplaceInstUsesWith(I, LHS);
4315
4316 bool Op0Ordered;
4317 bool Op1Ordered;
4318 unsigned Op0Pred = getFCmpCode(Op0CC, Op0Ordered);
4319 unsigned Op1Pred = getFCmpCode(Op1CC, Op1Ordered);
4320 if (Op1Pred == 0) {
4321 std::swap(LHS, RHS);
4322 std::swap(Op0Pred, Op1Pred);
4323 std::swap(Op0Ordered, Op1Ordered);
4324 }
4325 if (Op0Pred == 0) {
4326 // uno && ueq -> uno && (uno || eq) -> ueq
4327 // ord && olt -> ord && (ord && lt) -> olt
4328 if (Op0Ordered == Op1Ordered)
4329 return ReplaceInstUsesWith(I, RHS);
4330
4331 // uno && oeq -> uno && (ord && eq) -> false
4332 // uno && ord -> false
4333 if (!Op0Ordered)
Owen Anderson5defacc2009-07-31 17:39:07 +00004334 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Chris Lattner42d1be02009-07-23 05:14:02 +00004335 // ord && ueq -> ord && (uno || eq) -> oeq
4336 return cast<Instruction>(getFCmpValue(true, Op1Pred,
4337 Op0LHS, Op0RHS, Context));
4338 }
4339 }
4340
4341 return 0;
4342}
4343
Chris Lattner29cd5ba2008-11-16 05:06:21 +00004344
Chris Lattner7e708292002-06-25 16:13:24 +00004345Instruction *InstCombiner::visitAnd(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00004346 bool Changed = SimplifyCommutative(I);
Chris Lattner7e708292002-06-25 16:13:24 +00004347 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00004348
Chris Lattnerd06094f2009-11-10 00:55:12 +00004349 if (Value *V = SimplifyAndInst(Op0, Op1, TD))
4350 return ReplaceInstUsesWith(I, V);
Chris Lattner3f5b8772002-05-06 16:14:14 +00004351
Chris Lattnerf8c36f52006-02-12 08:02:11 +00004352 // See if we can simplify any instructions used by the instruction whose sole
Chris Lattner9ca96412006-02-08 03:25:32 +00004353 // purpose is to compute bits we don't care about.
Dan Gohman6de29f82009-06-15 22:12:54 +00004354 if (SimplifyDemandedInstructionBits(I))
Nick Lewycky546d6312010-01-02 15:25:44 +00004355 return &I;
Dan Gohman6de29f82009-06-15 22:12:54 +00004356
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00004357 if (ConstantInt *AndRHS = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner7acdf1d2009-10-11 22:00:32 +00004358 const APInt &AndRHSMask = AndRHS->getValue();
Zhou Sheng3a507fd2007-04-01 17:13:37 +00004359 APInt NotAndRHS(~AndRHSMask);
Chris Lattner6e7ba452005-01-01 16:22:27 +00004360
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00004361 // Optimize a variety of ((val OP C1) & C2) combinations...
Chris Lattner7acdf1d2009-10-11 22:00:32 +00004362 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
Chris Lattner6e7ba452005-01-01 16:22:27 +00004363 Value *Op0LHS = Op0I->getOperand(0);
4364 Value *Op0RHS = Op0I->getOperand(1);
4365 switch (Op0I->getOpcode()) {
Chris Lattner7acdf1d2009-10-11 22:00:32 +00004366 default: break;
Chris Lattner6e7ba452005-01-01 16:22:27 +00004367 case Instruction::Xor:
4368 case Instruction::Or:
Chris Lattnerad1e3022005-01-23 20:26:55 +00004369 // If the mask is only needed on one incoming arm, push it up.
Chris Lattner7acdf1d2009-10-11 22:00:32 +00004370 if (!Op0I->hasOneUse()) break;
4371
4372 if (MaskedValueIsZero(Op0LHS, NotAndRHS)) {
4373 // Not masking anything out for the LHS, move to RHS.
4374 Value *NewRHS = Builder->CreateAnd(Op0RHS, AndRHS,
4375 Op0RHS->getName()+".masked");
4376 return BinaryOperator::Create(Op0I->getOpcode(), Op0LHS, NewRHS);
4377 }
4378 if (!isa<Constant>(Op0RHS) &&
4379 MaskedValueIsZero(Op0RHS, NotAndRHS)) {
4380 // Not masking anything out for the RHS, move to LHS.
4381 Value *NewLHS = Builder->CreateAnd(Op0LHS, AndRHS,
4382 Op0LHS->getName()+".masked");
4383 return BinaryOperator::Create(Op0I->getOpcode(), NewLHS, Op0RHS);
Chris Lattnerad1e3022005-01-23 20:26:55 +00004384 }
4385
Chris Lattner6e7ba452005-01-01 16:22:27 +00004386 break;
Chris Lattnerc8e77562005-09-18 04:24:45 +00004387 case Instruction::Add:
Chris Lattner7203e152005-09-18 07:22:02 +00004388 // ((A & N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == AndRHS.
4389 // ((A | N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
4390 // ((A ^ N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
4391 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, false, I))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004392 return BinaryOperator::CreateAnd(V, AndRHS);
Chris Lattner7203e152005-09-18 07:22:02 +00004393 if (Value *V = FoldLogicalPlusAnd(Op0RHS, Op0LHS, AndRHS, false, I))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004394 return BinaryOperator::CreateAnd(V, AndRHS); // Add commutes
Chris Lattnerc8e77562005-09-18 04:24:45 +00004395 break;
4396
4397 case Instruction::Sub:
Chris Lattner7203e152005-09-18 07:22:02 +00004398 // ((A & N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == AndRHS.
4399 // ((A | N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
4400 // ((A ^ N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
4401 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, true, I))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004402 return BinaryOperator::CreateAnd(V, AndRHS);
Nick Lewyckyb4d1bc92008-07-09 04:32:37 +00004403
Nick Lewycky5dcc41f2008-07-10 05:51:40 +00004404 // (A - N) & AndRHS -> -N & AndRHS iff A&AndRHS==0 and AndRHS
4405 // has 1's for all bits that the subtraction with A might affect.
4406 if (Op0I->hasOneUse()) {
4407 uint32_t BitWidth = AndRHSMask.getBitWidth();
4408 uint32_t Zeros = AndRHSMask.countLeadingZeros();
4409 APInt Mask = APInt::getLowBitsSet(BitWidth, BitWidth - Zeros);
4410
Nick Lewyckyb4d1bc92008-07-09 04:32:37 +00004411 ConstantInt *A = dyn_cast<ConstantInt>(Op0LHS);
Nick Lewycky5dcc41f2008-07-10 05:51:40 +00004412 if (!(A && A->isZero()) && // avoid infinite recursion.
4413 MaskedValueIsZero(Op0LHS, Mask)) {
Chris Lattner74381062009-08-30 07:44:24 +00004414 Value *NewNeg = Builder->CreateNeg(Op0RHS);
Nick Lewyckyb4d1bc92008-07-09 04:32:37 +00004415 return BinaryOperator::CreateAnd(NewNeg, AndRHS);
4416 }
4417 }
Chris Lattnerc8e77562005-09-18 04:24:45 +00004418 break;
Nick Lewyckyd1f77bf2008-07-09 05:20:13 +00004419
4420 case Instruction::Shl:
4421 case Instruction::LShr:
4422 // (1 << x) & 1 --> zext(x == 0)
4423 // (1 >> x) & 1 --> zext(x == 0)
Nick Lewyckyd8ad4922008-07-09 07:35:26 +00004424 if (AndRHSMask == 1 && Op0LHS == AndRHS) {
Chris Lattner74381062009-08-30 07:44:24 +00004425 Value *NewICmp =
4426 Builder->CreateICmpEQ(Op0RHS, Constant::getNullValue(I.getType()));
Nick Lewyckyd1f77bf2008-07-09 05:20:13 +00004427 return new ZExtInst(NewICmp, I.getType());
4428 }
4429 break;
Chris Lattner6e7ba452005-01-01 16:22:27 +00004430 }
4431
Chris Lattner58403262003-07-23 19:25:52 +00004432 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
Chris Lattner6e7ba452005-01-01 16:22:27 +00004433 if (Instruction *Res = OptAndOp(Op0I, Op0CI, AndRHS, I))
Chris Lattnerbd7b5ff2003-09-19 17:17:26 +00004434 return Res;
Chris Lattner6e7ba452005-01-01 16:22:27 +00004435 } else if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
Chris Lattner2b83af22005-08-07 07:03:10 +00004436 // If this is an integer truncation or change from signed-to-unsigned, and
4437 // if the source is an and/or with immediate, transform it. This
4438 // frequently occurs for bitfield accesses.
4439 if (Instruction *CastOp = dyn_cast<Instruction>(CI->getOperand(0))) {
Reid Spencer3da59db2006-11-27 01:05:10 +00004440 if ((isa<TruncInst>(CI) || isa<BitCastInst>(CI)) &&
Chris Lattner2b83af22005-08-07 07:03:10 +00004441 CastOp->getNumOperands() == 2)
Chris Lattner48b59ec2009-10-26 15:40:07 +00004442 if (ConstantInt *AndCI =dyn_cast<ConstantInt>(CastOp->getOperand(1))){
Chris Lattner2b83af22005-08-07 07:03:10 +00004443 if (CastOp->getOpcode() == Instruction::And) {
4444 // Change: and (cast (and X, C1) to T), C2
Reid Spencer3da59db2006-11-27 01:05:10 +00004445 // into : and (cast X to T), trunc_or_bitcast(C1)&C2
4446 // This will fold the two constants together, which may allow
4447 // other simplifications.
Chris Lattner74381062009-08-30 07:44:24 +00004448 Value *NewCast = Builder->CreateTruncOrBitCast(
Reid Spencerd977d862006-12-12 23:36:14 +00004449 CastOp->getOperand(0), I.getType(),
4450 CastOp->getName()+".shrunk");
Reid Spencer3da59db2006-11-27 01:05:10 +00004451 // trunc_or_bitcast(C1)&C2
Chris Lattner74381062009-08-30 07:44:24 +00004452 Constant *C3 = ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
Owen Andersonbaf3c402009-07-29 18:55:55 +00004453 C3 = ConstantExpr::getAnd(C3, AndRHS);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004454 return BinaryOperator::CreateAnd(NewCast, C3);
Chris Lattner2b83af22005-08-07 07:03:10 +00004455 } else if (CastOp->getOpcode() == Instruction::Or) {
4456 // Change: and (cast (or X, C1) to T), C2
4457 // into : trunc(C1)&C2 iff trunc(C1)&C2 == C2
Chris Lattner74381062009-08-30 07:44:24 +00004458 Constant *C3 = ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
Owen Andersonbaf3c402009-07-29 18:55:55 +00004459 if (ConstantExpr::getAnd(C3, AndRHS) == AndRHS)
Owen Andersond672ecb2009-07-03 00:17:18 +00004460 // trunc(C1)&C2
Chris Lattner2b83af22005-08-07 07:03:10 +00004461 return ReplaceInstUsesWith(I, AndRHS);
4462 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00004463 }
Chris Lattner2b83af22005-08-07 07:03:10 +00004464 }
Chris Lattner06782f82003-07-23 19:36:21 +00004465 }
Chris Lattner2eefe512004-04-09 19:05:30 +00004466
4467 // Try to fold constant and into select arguments.
4468 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner6e7ba452005-01-01 16:22:27 +00004469 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00004470 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00004471 if (isa<PHINode>(Op0))
4472 if (Instruction *NV = FoldOpIntoPhi(I))
4473 return NV;
Chris Lattnerc6a8aff2003-07-23 17:57:01 +00004474 }
4475
Chris Lattner5b62aa72004-06-18 06:07:51 +00004476
Misha Brukmancb6267b2004-07-30 12:50:08 +00004477 // (~A & ~B) == (~(A | B)) - De Morgan's Law
Chris Lattnerd06094f2009-11-10 00:55:12 +00004478 if (Value *Op0NotVal = dyn_castNotVal(Op0))
4479 if (Value *Op1NotVal = dyn_castNotVal(Op1))
4480 if (Op0->hasOneUse() && Op1->hasOneUse()) {
4481 Value *Or = Builder->CreateOr(Op0NotVal, Op1NotVal,
4482 I.getName()+".demorgan");
4483 return BinaryOperator::CreateNot(Or);
4484 }
4485
Chris Lattner2082ad92006-02-13 23:07:23 +00004486 {
Chris Lattner003b6202007-06-15 05:58:24 +00004487 Value *A = 0, *B = 0, *C = 0, *D = 0;
Chris Lattnerd06094f2009-11-10 00:55:12 +00004488 // (A|B) & ~(A&B) -> A^B
4489 if (match(Op0, m_Or(m_Value(A), m_Value(B))) &&
4490 match(Op1, m_Not(m_And(m_Value(C), m_Value(D)))) &&
4491 ((A == C && B == D) || (A == D && B == C)))
4492 return BinaryOperator::CreateXor(A, B);
Chris Lattner003b6202007-06-15 05:58:24 +00004493
Chris Lattnerd06094f2009-11-10 00:55:12 +00004494 // ~(A&B) & (A|B) -> A^B
4495 if (match(Op1, m_Or(m_Value(A), m_Value(B))) &&
4496 match(Op0, m_Not(m_And(m_Value(C), m_Value(D)))) &&
4497 ((A == C && B == D) || (A == D && B == C)))
4498 return BinaryOperator::CreateXor(A, B);
Chris Lattner64daab52006-04-01 08:03:55 +00004499
4500 if (Op0->hasOneUse() &&
Dan Gohman4ae51262009-08-12 16:23:25 +00004501 match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
Chris Lattner64daab52006-04-01 08:03:55 +00004502 if (A == Op1) { // (A^B)&A -> A&(A^B)
4503 I.swapOperands(); // Simplify below
4504 std::swap(Op0, Op1);
4505 } else if (B == Op1) { // (A^B)&B -> B&(B^A)
4506 cast<BinaryOperator>(Op0)->swapOperands();
4507 I.swapOperands(); // Simplify below
4508 std::swap(Op0, Op1);
4509 }
4510 }
Bill Wendling7f0ef6b2008-11-30 13:08:13 +00004511
Chris Lattner64daab52006-04-01 08:03:55 +00004512 if (Op1->hasOneUse() &&
Dan Gohman4ae51262009-08-12 16:23:25 +00004513 match(Op1, m_Xor(m_Value(A), m_Value(B)))) {
Chris Lattner64daab52006-04-01 08:03:55 +00004514 if (B == Op0) { // B&(A^B) -> B&(B^A)
4515 cast<BinaryOperator>(Op1)->swapOperands();
4516 std::swap(A, B);
4517 }
Chris Lattner74381062009-08-30 07:44:24 +00004518 if (A == Op0) // A&(A^B) -> A & ~B
4519 return BinaryOperator::CreateAnd(A, Builder->CreateNot(B, "tmp"));
Chris Lattner64daab52006-04-01 08:03:55 +00004520 }
Bill Wendling7f0ef6b2008-11-30 13:08:13 +00004521
4522 // (A&((~A)|B)) -> A&B
Dan Gohman4ae51262009-08-12 16:23:25 +00004523 if (match(Op0, m_Or(m_Not(m_Specific(Op1)), m_Value(A))) ||
4524 match(Op0, m_Or(m_Value(A), m_Not(m_Specific(Op1)))))
Chris Lattnerd8aafcb2008-12-01 05:16:26 +00004525 return BinaryOperator::CreateAnd(A, Op1);
Dan Gohman4ae51262009-08-12 16:23:25 +00004526 if (match(Op1, m_Or(m_Not(m_Specific(Op0)), m_Value(A))) ||
4527 match(Op1, m_Or(m_Value(A), m_Not(m_Specific(Op0)))))
Chris Lattnerd8aafcb2008-12-01 05:16:26 +00004528 return BinaryOperator::CreateAnd(A, Op0);
Chris Lattner2082ad92006-02-13 23:07:23 +00004529 }
4530
Reid Spencere4d87aa2006-12-23 06:05:41 +00004531 if (ICmpInst *RHS = dyn_cast<ICmpInst>(Op1)) {
4532 // (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
Dan Gohman186a6362009-08-12 16:04:34 +00004533 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
Chris Lattneraa9c1f12003-08-13 20:16:26 +00004534 return R;
4535
Chris Lattner29cd5ba2008-11-16 05:06:21 +00004536 if (ICmpInst *LHS = dyn_cast<ICmpInst>(Op0))
4537 if (Instruction *Res = FoldAndOfICmps(I, LHS, RHS))
4538 return Res;
Chris Lattner955f3312004-09-28 21:48:02 +00004539 }
4540
Chris Lattner6fc205f2006-05-05 06:39:07 +00004541 // fold (and (cast A), (cast B)) -> (cast (and A, B))
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004542 if (CastInst *Op0C = dyn_cast<CastInst>(Op0))
4543 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
4544 if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind ?
4545 const Type *SrcTy = Op0C->getOperand(0)->getType();
Chris Lattnerf98d2532009-07-23 05:32:17 +00004546 if (SrcTy == Op1C->getOperand(0)->getType() &&
4547 SrcTy->isIntOrIntVector() &&
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004548 // Only do this if the casts both really cause code to be generated.
Reid Spencere4d87aa2006-12-23 06:05:41 +00004549 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
4550 I.getType(), TD) &&
4551 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
4552 I.getType(), TD)) {
Chris Lattner74381062009-08-30 07:44:24 +00004553 Value *NewOp = Builder->CreateAnd(Op0C->getOperand(0),
4554 Op1C->getOperand(0), I.getName());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004555 return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00004556 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00004557 }
Chris Lattnere511b742006-11-14 07:46:50 +00004558
4559 // (X >> Z) & (Y >> Z) -> (X&Y) >> Z for all shifts.
Reid Spencer832254e2007-02-02 02:16:23 +00004560 if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
4561 if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
4562 if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() &&
Chris Lattnere511b742006-11-14 07:46:50 +00004563 SI0->getOperand(1) == SI1->getOperand(1) &&
4564 (SI0->hasOneUse() || SI1->hasOneUse())) {
Chris Lattner74381062009-08-30 07:44:24 +00004565 Value *NewOp =
4566 Builder->CreateAnd(SI0->getOperand(0), SI1->getOperand(0),
4567 SI0->getName());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00004568 return BinaryOperator::Create(SI1->getOpcode(), NewOp,
Reid Spencer832254e2007-02-02 02:16:23 +00004569 SI1->getOperand(1));
Chris Lattnere511b742006-11-14 07:46:50 +00004570 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00004571 }
4572
Evan Cheng8db90722008-10-14 17:15:11 +00004573 // If and'ing two fcmp, try combine them into one.
Chris Lattner99c65742007-10-24 05:38:08 +00004574 if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0))) {
Chris Lattner42d1be02009-07-23 05:14:02 +00004575 if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1)))
4576 if (Instruction *Res = FoldAndOfFCmps(I, LHS, RHS))
4577 return Res;
Chris Lattner99c65742007-10-24 05:38:08 +00004578 }
Nick Lewyckyb4d1bc92008-07-09 04:32:37 +00004579
Chris Lattner7e708292002-06-25 16:13:24 +00004580 return Changed ? &I : 0;
Chris Lattner3f5b8772002-05-06 16:14:14 +00004581}
4582
Chris Lattner8c34cd22008-10-05 02:13:19 +00004583/// CollectBSwapParts - Analyze the specified subexpression and see if it is
4584/// capable of providing pieces of a bswap. The subexpression provides pieces
4585/// of a bswap if it is proven that each of the non-zero bytes in the output of
4586/// the expression came from the corresponding "byte swapped" byte in some other
4587/// value. For example, if the current subexpression is "(shl i32 %X, 24)" then
4588/// we know that the expression deposits the low byte of %X into the high byte
4589/// of the bswap result and that all other bytes are zero. This expression is
4590/// accepted, the high byte of ByteValues is set to X to indicate a correct
4591/// match.
4592///
4593/// This function returns true if the match was unsuccessful and false if so.
4594/// On entry to the function the "OverallLeftShift" is a signed integer value
4595/// indicating the number of bytes that the subexpression is later shifted. For
4596/// example, if the expression is later right shifted by 16 bits, the
4597/// OverallLeftShift value would be -2 on entry. This is used to specify which
4598/// byte of ByteValues is actually being set.
4599///
4600/// Similarly, ByteMask is a bitmask where a bit is clear if its corresponding
4601/// byte is masked to zero by a user. For example, in (X & 255), X will be
4602/// processed with a bytemask of 1. Because bytemask is 32-bits, this limits
4603/// this function to working on up to 32-byte (256 bit) values. ByteMask is
4604/// always in the local (OverallLeftShift) coordinate space.
4605///
4606static bool CollectBSwapParts(Value *V, int OverallLeftShift, uint32_t ByteMask,
4607 SmallVector<Value*, 8> &ByteValues) {
4608 if (Instruction *I = dyn_cast<Instruction>(V)) {
4609 // If this is an or instruction, it may be an inner node of the bswap.
4610 if (I->getOpcode() == Instruction::Or) {
4611 return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask,
4612 ByteValues) ||
4613 CollectBSwapParts(I->getOperand(1), OverallLeftShift, ByteMask,
4614 ByteValues);
Chris Lattnerafe91a52006-06-15 19:07:26 +00004615 }
Chris Lattner8c34cd22008-10-05 02:13:19 +00004616
4617 // If this is a logical shift by a constant multiple of 8, recurse with
4618 // OverallLeftShift and ByteMask adjusted.
4619 if (I->isLogicalShift() && isa<ConstantInt>(I->getOperand(1))) {
4620 unsigned ShAmt =
4621 cast<ConstantInt>(I->getOperand(1))->getLimitedValue(~0U);
4622 // Ensure the shift amount is defined and of a byte value.
4623 if ((ShAmt & 7) || (ShAmt > 8*ByteValues.size()))
4624 return true;
4625
4626 unsigned ByteShift = ShAmt >> 3;
4627 if (I->getOpcode() == Instruction::Shl) {
4628 // X << 2 -> collect(X, +2)
4629 OverallLeftShift += ByteShift;
4630 ByteMask >>= ByteShift;
4631 } else {
4632 // X >>u 2 -> collect(X, -2)
4633 OverallLeftShift -= ByteShift;
4634 ByteMask <<= ByteShift;
Chris Lattnerde17ddc2008-10-08 06:42:28 +00004635 ByteMask &= (~0U >> (32-ByteValues.size()));
Chris Lattner8c34cd22008-10-05 02:13:19 +00004636 }
4637
4638 if (OverallLeftShift >= (int)ByteValues.size()) return true;
4639 if (OverallLeftShift <= -(int)ByteValues.size()) return true;
4640
4641 return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask,
4642 ByteValues);
4643 }
4644
4645 // If this is a logical 'and' with a mask that clears bytes, clear the
4646 // corresponding bytes in ByteMask.
4647 if (I->getOpcode() == Instruction::And &&
4648 isa<ConstantInt>(I->getOperand(1))) {
4649 // Scan every byte of the and mask, seeing if the byte is either 0 or 255.
4650 unsigned NumBytes = ByteValues.size();
4651 APInt Byte(I->getType()->getPrimitiveSizeInBits(), 255);
4652 const APInt &AndMask = cast<ConstantInt>(I->getOperand(1))->getValue();
4653
4654 for (unsigned i = 0; i != NumBytes; ++i, Byte <<= 8) {
4655 // If this byte is masked out by a later operation, we don't care what
4656 // the and mask is.
4657 if ((ByteMask & (1 << i)) == 0)
4658 continue;
4659
4660 // If the AndMask is all zeros for this byte, clear the bit.
4661 APInt MaskB = AndMask & Byte;
4662 if (MaskB == 0) {
4663 ByteMask &= ~(1U << i);
4664 continue;
4665 }
4666
4667 // If the AndMask is not all ones for this byte, it's not a bytezap.
4668 if (MaskB != Byte)
4669 return true;
4670
4671 // Otherwise, this byte is kept.
4672 }
4673
4674 return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask,
4675 ByteValues);
4676 }
Chris Lattnerafe91a52006-06-15 19:07:26 +00004677 }
4678
Chris Lattner8c34cd22008-10-05 02:13:19 +00004679 // Okay, we got to something that isn't a shift, 'or' or 'and'. This must be
4680 // the input value to the bswap. Some observations: 1) if more than one byte
4681 // is demanded from this input, then it could not be successfully assembled
4682 // into a byteswap. At least one of the two bytes would not be aligned with
4683 // their ultimate destination.
4684 if (!isPowerOf2_32(ByteMask)) return true;
4685 unsigned InputByteNo = CountTrailingZeros_32(ByteMask);
Chris Lattnerafe91a52006-06-15 19:07:26 +00004686
Chris Lattner8c34cd22008-10-05 02:13:19 +00004687 // 2) The input and ultimate destinations must line up: if byte 3 of an i32
4688 // is demanded, it needs to go into byte 0 of the result. This means that the
4689 // byte needs to be shifted until it lands in the right byte bucket. The
4690 // shift amount depends on the position: if the byte is coming from the high
4691 // part of the value (e.g. byte 3) then it must be shifted right. If from the
4692 // low part, it must be shifted left.
4693 unsigned DestByteNo = InputByteNo + OverallLeftShift;
4694 if (InputByteNo < ByteValues.size()/2) {
4695 if (ByteValues.size()-1-DestByteNo != InputByteNo)
4696 return true;
4697 } else {
4698 if (ByteValues.size()-1-DestByteNo != InputByteNo)
4699 return true;
4700 }
Chris Lattnerafe91a52006-06-15 19:07:26 +00004701
4702 // If the destination byte value is already defined, the values are or'd
4703 // together, which isn't a bswap (unless it's an or of the same bits).
Chris Lattner8c34cd22008-10-05 02:13:19 +00004704 if (ByteValues[DestByteNo] && ByteValues[DestByteNo] != V)
Chris Lattnerafe91a52006-06-15 19:07:26 +00004705 return true;
Chris Lattner8c34cd22008-10-05 02:13:19 +00004706 ByteValues[DestByteNo] = V;
Chris Lattnerafe91a52006-06-15 19:07:26 +00004707 return false;
4708}
4709
4710/// MatchBSwap - Given an OR instruction, check to see if this is a bswap idiom.
4711/// If so, insert the new bswap intrinsic and return it.
4712Instruction *InstCombiner::MatchBSwap(BinaryOperator &I) {
Chris Lattner55fc8c42007-04-01 20:57:36 +00004713 const IntegerType *ITy = dyn_cast<IntegerType>(I.getType());
Chris Lattner8c34cd22008-10-05 02:13:19 +00004714 if (!ITy || ITy->getBitWidth() % 16 ||
4715 // ByteMask only allows up to 32-byte values.
4716 ITy->getBitWidth() > 32*8)
Chris Lattner55fc8c42007-04-01 20:57:36 +00004717 return 0; // Can only bswap pairs of bytes. Can't do vectors.
Chris Lattnerafe91a52006-06-15 19:07:26 +00004718
4719 /// ByteValues - For each byte of the result, we keep track of which value
4720 /// defines each byte.
Chris Lattner535014f2007-02-15 22:52:10 +00004721 SmallVector<Value*, 8> ByteValues;
Chris Lattner55fc8c42007-04-01 20:57:36 +00004722 ByteValues.resize(ITy->getBitWidth()/8);
Chris Lattnerafe91a52006-06-15 19:07:26 +00004723
4724 // Try to find all the pieces corresponding to the bswap.
Chris Lattner8c34cd22008-10-05 02:13:19 +00004725 uint32_t ByteMask = ~0U >> (32-ByteValues.size());
4726 if (CollectBSwapParts(&I, 0, ByteMask, ByteValues))
Chris Lattnerafe91a52006-06-15 19:07:26 +00004727 return 0;
4728
4729 // Check to see if all of the bytes come from the same value.
4730 Value *V = ByteValues[0];
4731 if (V == 0) return 0; // Didn't find a byte? Must be zero.
4732
4733 // Check to make sure that all of the bytes come from the same value.
4734 for (unsigned i = 1, e = ByteValues.size(); i != e; ++i)
4735 if (ByteValues[i] != V)
4736 return 0;
Chandler Carruth69940402007-08-04 01:51:18 +00004737 const Type *Tys[] = { ITy };
Chris Lattnerafe91a52006-06-15 19:07:26 +00004738 Module *M = I.getParent()->getParent()->getParent();
Chandler Carruth69940402007-08-04 01:51:18 +00004739 Function *F = Intrinsic::getDeclaration(M, Intrinsic::bswap, Tys, 1);
Gabor Greif051a9502008-04-06 20:25:17 +00004740 return CallInst::Create(F, V);
Chris Lattnerafe91a52006-06-15 19:07:26 +00004741}
4742
Chris Lattnerfaaf9512008-11-16 04:24:12 +00004743/// MatchSelectFromAndOr - We have an expression of the form (A&C)|(B&D). Check
4744/// If A is (cond?-1:0) and either B or D is ~(cond?-1,0) or (cond?0,-1), then
4745/// we can simplify this expression to "cond ? C : D or B".
4746static Instruction *MatchSelectFromAndOr(Value *A, Value *B,
Owen Andersonc7d2ce72009-07-10 17:35:01 +00004747 Value *C, Value *D,
4748 LLVMContext *Context) {
Chris Lattnera6a474d2008-11-16 04:26:55 +00004749 // If A is not a select of -1/0, this cannot match.
Chris Lattner6046fb72008-11-16 04:46:19 +00004750 Value *Cond = 0;
Dan Gohman4ae51262009-08-12 16:23:25 +00004751 if (!match(A, m_SelectCst<-1, 0>(m_Value(Cond))))
Chris Lattnerfaaf9512008-11-16 04:24:12 +00004752 return 0;
4753
Chris Lattnera6a474d2008-11-16 04:26:55 +00004754 // ((cond?-1:0)&C) | (B&(cond?0:-1)) -> cond ? C : B.
Dan Gohman4ae51262009-08-12 16:23:25 +00004755 if (match(D, m_SelectCst<0, -1>(m_Specific(Cond))))
Chris Lattnera6a474d2008-11-16 04:26:55 +00004756 return SelectInst::Create(Cond, C, B);
Dan Gohman4ae51262009-08-12 16:23:25 +00004757 if (match(D, m_Not(m_SelectCst<-1, 0>(m_Specific(Cond)))))
Chris Lattnera6a474d2008-11-16 04:26:55 +00004758 return SelectInst::Create(Cond, C, B);
4759 // ((cond?-1:0)&C) | ((cond?0:-1)&D) -> cond ? C : D.
Dan Gohman4ae51262009-08-12 16:23:25 +00004760 if (match(B, m_SelectCst<0, -1>(m_Specific(Cond))))
Chris Lattnera6a474d2008-11-16 04:26:55 +00004761 return SelectInst::Create(Cond, C, D);
Dan Gohman4ae51262009-08-12 16:23:25 +00004762 if (match(B, m_Not(m_SelectCst<-1, 0>(m_Specific(Cond)))))
Chris Lattnera6a474d2008-11-16 04:26:55 +00004763 return SelectInst::Create(Cond, C, D);
Chris Lattnerfaaf9512008-11-16 04:24:12 +00004764 return 0;
4765}
Chris Lattnerafe91a52006-06-15 19:07:26 +00004766
Chris Lattner69d4ced2008-11-16 05:20:07 +00004767/// FoldOrOfICmps - Fold (icmp)|(icmp) if possible.
4768Instruction *InstCombiner::FoldOrOfICmps(Instruction &I,
4769 ICmpInst *LHS, ICmpInst *RHS) {
4770 Value *Val, *Val2;
4771 ConstantInt *LHSCst, *RHSCst;
4772 ICmpInst::Predicate LHSCC, RHSCC;
4773
4774 // This only handles icmp of constants: (icmp1 A, C1) | (icmp2 B, C2).
Chris Lattner3f40e232009-11-29 00:51:17 +00004775 if (!match(LHS, m_ICmp(LHSCC, m_Value(Val), m_ConstantInt(LHSCst))) ||
4776 !match(RHS, m_ICmp(RHSCC, m_Value(Val2), m_ConstantInt(RHSCst))))
Chris Lattner69d4ced2008-11-16 05:20:07 +00004777 return 0;
Chris Lattner3f40e232009-11-29 00:51:17 +00004778
4779
4780 // (icmp ne A, 0) | (icmp ne B, 0) --> (icmp ne (A|B), 0)
4781 if (LHSCst == RHSCst && LHSCC == RHSCC &&
4782 LHSCC == ICmpInst::ICMP_NE && LHSCst->isZero()) {
4783 Value *NewOr = Builder->CreateOr(Val, Val2);
4784 return new ICmpInst(LHSCC, NewOr, LHSCst);
4785 }
Chris Lattner69d4ced2008-11-16 05:20:07 +00004786
4787 // From here on, we only handle:
4788 // (icmp1 A, C1) | (icmp2 A, C2) --> something simpler.
4789 if (Val != Val2) return 0;
4790
4791 // ICMP_[US][GL]E X, CST is folded to ICMP_[US][GL]T elsewhere.
4792 if (LHSCC == ICmpInst::ICMP_UGE || LHSCC == ICmpInst::ICMP_ULE ||
4793 RHSCC == ICmpInst::ICMP_UGE || RHSCC == ICmpInst::ICMP_ULE ||
4794 LHSCC == ICmpInst::ICMP_SGE || LHSCC == ICmpInst::ICMP_SLE ||
4795 RHSCC == ICmpInst::ICMP_SGE || RHSCC == ICmpInst::ICMP_SLE)
4796 return 0;
4797
4798 // We can't fold (ugt x, C) | (sgt x, C2).
4799 if (!PredicatesFoldable(LHSCC, RHSCC))
4800 return 0;
4801
4802 // Ensure that the larger constant is on the RHS.
4803 bool ShouldSwap;
Nick Lewycky4a134af2009-10-25 05:20:17 +00004804 if (CmpInst::isSigned(LHSCC) ||
Chris Lattner69d4ced2008-11-16 05:20:07 +00004805 (ICmpInst::isEquality(LHSCC) &&
Nick Lewycky4a134af2009-10-25 05:20:17 +00004806 CmpInst::isSigned(RHSCC)))
Chris Lattner69d4ced2008-11-16 05:20:07 +00004807 ShouldSwap = LHSCst->getValue().sgt(RHSCst->getValue());
4808 else
4809 ShouldSwap = LHSCst->getValue().ugt(RHSCst->getValue());
4810
4811 if (ShouldSwap) {
4812 std::swap(LHS, RHS);
4813 std::swap(LHSCst, RHSCst);
4814 std::swap(LHSCC, RHSCC);
4815 }
4816
4817 // At this point, we know we have have two icmp instructions
4818 // comparing a value against two constants and or'ing the result
4819 // together. Because of the above check, we know that we only have
4820 // ICMP_EQ, ICMP_NE, ICMP_LT, and ICMP_GT here. We also know (from the
4821 // FoldICmpLogical check above), that the two constants are not
4822 // equal.
4823 assert(LHSCst != RHSCst && "Compares not folded above?");
4824
4825 switch (LHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00004826 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner69d4ced2008-11-16 05:20:07 +00004827 case ICmpInst::ICMP_EQ:
4828 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00004829 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner69d4ced2008-11-16 05:20:07 +00004830 case ICmpInst::ICMP_EQ:
Dan Gohman186a6362009-08-12 16:04:34 +00004831 if (LHSCst == SubOne(RHSCst)) {
Owen Andersond672ecb2009-07-03 00:17:18 +00004832 // (X == 13 | X == 14) -> X-13 <u 2
Owen Andersonbaf3c402009-07-29 18:55:55 +00004833 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
Chris Lattner74381062009-08-30 07:44:24 +00004834 Value *Add = Builder->CreateAdd(Val, AddCST, Val->getName()+".off");
Dan Gohman186a6362009-08-12 16:04:34 +00004835 AddCST = ConstantExpr::getSub(AddOne(RHSCst), LHSCst);
Dan Gohman1c8a23c2009-08-25 23:17:54 +00004836 return new ICmpInst(ICmpInst::ICMP_ULT, Add, AddCST);
Chris Lattner69d4ced2008-11-16 05:20:07 +00004837 }
4838 break; // (X == 13 | X == 15) -> no change
4839 case ICmpInst::ICMP_UGT: // (X == 13 | X u> 14) -> no change
4840 case ICmpInst::ICMP_SGT: // (X == 13 | X s> 14) -> no change
4841 break;
4842 case ICmpInst::ICMP_NE: // (X == 13 | X != 15) -> X != 15
4843 case ICmpInst::ICMP_ULT: // (X == 13 | X u< 15) -> X u< 15
4844 case ICmpInst::ICMP_SLT: // (X == 13 | X s< 15) -> X s< 15
4845 return ReplaceInstUsesWith(I, RHS);
4846 }
4847 break;
4848 case ICmpInst::ICMP_NE:
4849 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00004850 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner69d4ced2008-11-16 05:20:07 +00004851 case ICmpInst::ICMP_EQ: // (X != 13 | X == 15) -> X != 13
4852 case ICmpInst::ICMP_UGT: // (X != 13 | X u> 15) -> X != 13
4853 case ICmpInst::ICMP_SGT: // (X != 13 | X s> 15) -> X != 13
4854 return ReplaceInstUsesWith(I, LHS);
4855 case ICmpInst::ICMP_NE: // (X != 13 | X != 15) -> true
4856 case ICmpInst::ICMP_ULT: // (X != 13 | X u< 15) -> true
4857 case ICmpInst::ICMP_SLT: // (X != 13 | X s< 15) -> true
Owen Anderson5defacc2009-07-31 17:39:07 +00004858 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Chris Lattner69d4ced2008-11-16 05:20:07 +00004859 }
4860 break;
4861 case ICmpInst::ICMP_ULT:
4862 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00004863 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner69d4ced2008-11-16 05:20:07 +00004864 case ICmpInst::ICMP_EQ: // (X u< 13 | X == 14) -> no change
4865 break;
4866 case ICmpInst::ICMP_UGT: // (X u< 13 | X u> 15) -> (X-13) u> 2
4867 // If RHSCst is [us]MAXINT, it is always false. Not handling
4868 // this can cause overflow.
4869 if (RHSCst->isMaxValue(false))
4870 return ReplaceInstUsesWith(I, LHS);
Dan Gohman186a6362009-08-12 16:04:34 +00004871 return InsertRangeTest(Val, LHSCst, AddOne(RHSCst),
Owen Andersond672ecb2009-07-03 00:17:18 +00004872 false, false, I);
Chris Lattner69d4ced2008-11-16 05:20:07 +00004873 case ICmpInst::ICMP_SGT: // (X u< 13 | X s> 15) -> no change
4874 break;
4875 case ICmpInst::ICMP_NE: // (X u< 13 | X != 15) -> X != 15
4876 case ICmpInst::ICMP_ULT: // (X u< 13 | X u< 15) -> X u< 15
4877 return ReplaceInstUsesWith(I, RHS);
4878 case ICmpInst::ICMP_SLT: // (X u< 13 | X s< 15) -> no change
4879 break;
4880 }
4881 break;
4882 case ICmpInst::ICMP_SLT:
4883 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00004884 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner69d4ced2008-11-16 05:20:07 +00004885 case ICmpInst::ICMP_EQ: // (X s< 13 | X == 14) -> no change
4886 break;
4887 case ICmpInst::ICMP_SGT: // (X s< 13 | X s> 15) -> (X-13) s> 2
4888 // If RHSCst is [us]MAXINT, it is always false. Not handling
4889 // this can cause overflow.
4890 if (RHSCst->isMaxValue(true))
4891 return ReplaceInstUsesWith(I, LHS);
Dan Gohman186a6362009-08-12 16:04:34 +00004892 return InsertRangeTest(Val, LHSCst, AddOne(RHSCst),
Owen Andersond672ecb2009-07-03 00:17:18 +00004893 true, false, I);
Chris Lattner69d4ced2008-11-16 05:20:07 +00004894 case ICmpInst::ICMP_UGT: // (X s< 13 | X u> 15) -> no change
4895 break;
4896 case ICmpInst::ICMP_NE: // (X s< 13 | X != 15) -> X != 15
4897 case ICmpInst::ICMP_SLT: // (X s< 13 | X s< 15) -> X s< 15
4898 return ReplaceInstUsesWith(I, RHS);
4899 case ICmpInst::ICMP_ULT: // (X s< 13 | X u< 15) -> no change
4900 break;
4901 }
4902 break;
4903 case ICmpInst::ICMP_UGT:
4904 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00004905 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner69d4ced2008-11-16 05:20:07 +00004906 case ICmpInst::ICMP_EQ: // (X u> 13 | X == 15) -> X u> 13
4907 case ICmpInst::ICMP_UGT: // (X u> 13 | X u> 15) -> X u> 13
4908 return ReplaceInstUsesWith(I, LHS);
4909 case ICmpInst::ICMP_SGT: // (X u> 13 | X s> 15) -> no change
4910 break;
4911 case ICmpInst::ICMP_NE: // (X u> 13 | X != 15) -> true
4912 case ICmpInst::ICMP_ULT: // (X u> 13 | X u< 15) -> true
Owen Anderson5defacc2009-07-31 17:39:07 +00004913 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Chris Lattner69d4ced2008-11-16 05:20:07 +00004914 case ICmpInst::ICMP_SLT: // (X u> 13 | X s< 15) -> no change
4915 break;
4916 }
4917 break;
4918 case ICmpInst::ICMP_SGT:
4919 switch (RHSCC) {
Torok Edwinc23197a2009-07-14 16:55:14 +00004920 default: llvm_unreachable("Unknown integer condition code!");
Chris Lattner69d4ced2008-11-16 05:20:07 +00004921 case ICmpInst::ICMP_EQ: // (X s> 13 | X == 15) -> X > 13
4922 case ICmpInst::ICMP_SGT: // (X s> 13 | X s> 15) -> X > 13
4923 return ReplaceInstUsesWith(I, LHS);
4924 case ICmpInst::ICMP_UGT: // (X s> 13 | X u> 15) -> no change
4925 break;
4926 case ICmpInst::ICMP_NE: // (X s> 13 | X != 15) -> true
4927 case ICmpInst::ICMP_SLT: // (X s> 13 | X s< 15) -> true
Owen Anderson5defacc2009-07-31 17:39:07 +00004928 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Chris Lattner69d4ced2008-11-16 05:20:07 +00004929 case ICmpInst::ICMP_ULT: // (X s> 13 | X u< 15) -> no change
4930 break;
4931 }
4932 break;
4933 }
4934 return 0;
4935}
4936
Chris Lattner5414cc52009-07-23 05:46:22 +00004937Instruction *InstCombiner::FoldOrOfFCmps(Instruction &I, FCmpInst *LHS,
4938 FCmpInst *RHS) {
4939 if (LHS->getPredicate() == FCmpInst::FCMP_UNO &&
4940 RHS->getPredicate() == FCmpInst::FCMP_UNO &&
4941 LHS->getOperand(0)->getType() == RHS->getOperand(0)->getType()) {
4942 if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
4943 if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
4944 // If either of the constants are nans, then the whole thing returns
4945 // true.
4946 if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
Owen Anderson5defacc2009-07-31 17:39:07 +00004947 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Chris Lattner5414cc52009-07-23 05:46:22 +00004948
4949 // Otherwise, no need to compare the two constants, compare the
4950 // rest.
Dan Gohman1c8a23c2009-08-25 23:17:54 +00004951 return new FCmpInst(FCmpInst::FCMP_UNO,
Chris Lattner5414cc52009-07-23 05:46:22 +00004952 LHS->getOperand(0), RHS->getOperand(0));
4953 }
4954
4955 // Handle vector zeros. This occurs because the canonical form of
4956 // "fcmp uno x,x" is "fcmp uno x, 0".
4957 if (isa<ConstantAggregateZero>(LHS->getOperand(1)) &&
4958 isa<ConstantAggregateZero>(RHS->getOperand(1)))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00004959 return new FCmpInst(FCmpInst::FCMP_UNO,
Chris Lattner5414cc52009-07-23 05:46:22 +00004960 LHS->getOperand(0), RHS->getOperand(0));
4961
4962 return 0;
4963 }
4964
4965 Value *Op0LHS = LHS->getOperand(0), *Op0RHS = LHS->getOperand(1);
4966 Value *Op1LHS = RHS->getOperand(0), *Op1RHS = RHS->getOperand(1);
4967 FCmpInst::Predicate Op0CC = LHS->getPredicate(), Op1CC = RHS->getPredicate();
4968
4969 if (Op0LHS == Op1RHS && Op0RHS == Op1LHS) {
4970 // Swap RHS operands to match LHS.
4971 Op1CC = FCmpInst::getSwappedPredicate(Op1CC);
4972 std::swap(Op1LHS, Op1RHS);
4973 }
4974 if (Op0LHS == Op1LHS && Op0RHS == Op1RHS) {
4975 // Simplify (fcmp cc0 x, y) | (fcmp cc1 x, y).
4976 if (Op0CC == Op1CC)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00004977 return new FCmpInst((FCmpInst::Predicate)Op0CC,
Chris Lattner5414cc52009-07-23 05:46:22 +00004978 Op0LHS, Op0RHS);
4979 if (Op0CC == FCmpInst::FCMP_TRUE || Op1CC == FCmpInst::FCMP_TRUE)
Owen Anderson5defacc2009-07-31 17:39:07 +00004980 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Chris Lattner5414cc52009-07-23 05:46:22 +00004981 if (Op0CC == FCmpInst::FCMP_FALSE)
4982 return ReplaceInstUsesWith(I, RHS);
4983 if (Op1CC == FCmpInst::FCMP_FALSE)
4984 return ReplaceInstUsesWith(I, LHS);
4985 bool Op0Ordered;
4986 bool Op1Ordered;
4987 unsigned Op0Pred = getFCmpCode(Op0CC, Op0Ordered);
4988 unsigned Op1Pred = getFCmpCode(Op1CC, Op1Ordered);
4989 if (Op0Ordered == Op1Ordered) {
4990 // If both are ordered or unordered, return a new fcmp with
4991 // or'ed predicates.
4992 Value *RV = getFCmpValue(Op0Ordered, Op0Pred|Op1Pred,
4993 Op0LHS, Op0RHS, Context);
4994 if (Instruction *I = dyn_cast<Instruction>(RV))
4995 return I;
4996 // Otherwise, it's a constant boolean value...
4997 return ReplaceInstUsesWith(I, RV);
4998 }
4999 }
5000 return 0;
5001}
5002
Bill Wendlinga698a472008-12-01 08:23:25 +00005003/// FoldOrWithConstants - This helper function folds:
5004///
Bill Wendlinga8bb13f2008-12-02 05:09:00 +00005005/// ((A | B) & C1) | (B & C2)
Bill Wendlinga698a472008-12-01 08:23:25 +00005006///
5007/// into:
5008///
Bill Wendlinga8bb13f2008-12-02 05:09:00 +00005009/// (A & C1) | B
Bill Wendlingd54d8602008-12-01 08:32:40 +00005010///
Bill Wendlinga8bb13f2008-12-02 05:09:00 +00005011/// when the XOR of the two constants is "all ones" (-1).
Bill Wendlingd54d8602008-12-01 08:32:40 +00005012Instruction *InstCombiner::FoldOrWithConstants(BinaryOperator &I, Value *Op,
Bill Wendlinga698a472008-12-01 08:23:25 +00005013 Value *A, Value *B, Value *C) {
Bill Wendlingdda74e02008-12-02 05:06:43 +00005014 ConstantInt *CI1 = dyn_cast<ConstantInt>(C);
5015 if (!CI1) return 0;
Bill Wendlinga698a472008-12-01 08:23:25 +00005016
Bill Wendling286a0542008-12-02 06:24:20 +00005017 Value *V1 = 0;
5018 ConstantInt *CI2 = 0;
Dan Gohman4ae51262009-08-12 16:23:25 +00005019 if (!match(Op, m_And(m_Value(V1), m_ConstantInt(CI2)))) return 0;
Bill Wendlinga698a472008-12-01 08:23:25 +00005020
Bill Wendling29976b92008-12-02 06:18:11 +00005021 APInt Xor = CI1->getValue() ^ CI2->getValue();
5022 if (!Xor.isAllOnesValue()) return 0;
5023
Bill Wendling286a0542008-12-02 06:24:20 +00005024 if (V1 == A || V1 == B) {
Chris Lattner74381062009-08-30 07:44:24 +00005025 Value *NewOp = Builder->CreateAnd((V1 == A) ? B : A, CI1);
Bill Wendlingd16c6e92008-12-02 06:22:04 +00005026 return BinaryOperator::CreateOr(NewOp, V1);
Bill Wendlinga698a472008-12-01 08:23:25 +00005027 }
5028
5029 return 0;
5030}
5031
Chris Lattner7e708292002-06-25 16:13:24 +00005032Instruction *InstCombiner::visitOr(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00005033 bool Changed = SimplifyCommutative(I);
Chris Lattner7e708292002-06-25 16:13:24 +00005034 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00005035
Chris Lattnerd06094f2009-11-10 00:55:12 +00005036 if (Value *V = SimplifyOrInst(Op0, Op1, TD))
5037 return ReplaceInstUsesWith(I, V);
5038
5039
Chris Lattnerf8c36f52006-02-12 08:02:11 +00005040 // See if we can simplify any instructions used by the instruction whose sole
5041 // purpose is to compute bits we don't care about.
Dan Gohman6de29f82009-06-15 22:12:54 +00005042 if (SimplifyDemandedInstructionBits(I))
5043 return &I;
Chris Lattner041a6c92007-06-15 05:26:55 +00005044
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005045 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner4f637d42006-01-06 17:59:59 +00005046 ConstantInt *C1 = 0; Value *X = 0;
Chris Lattneracd1f0f2004-07-30 07:50:03 +00005047 // (X & C1) | C2 --> (X | C2) & (C1|C2)
Dan Gohman4ae51262009-08-12 16:23:25 +00005048 if (match(Op0, m_And(m_Value(X), m_ConstantInt(C1))) &&
Owen Andersonc7d2ce72009-07-10 17:35:01 +00005049 isOnlyUse(Op0)) {
Chris Lattner74381062009-08-30 07:44:24 +00005050 Value *Or = Builder->CreateOr(X, RHS);
Chris Lattner6934a042007-02-11 01:23:03 +00005051 Or->takeName(Op0);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005052 return BinaryOperator::CreateAnd(Or,
Owen Andersoneed707b2009-07-24 23:12:02 +00005053 ConstantInt::get(*Context, RHS->getValue() | C1->getValue()));
Chris Lattneracd1f0f2004-07-30 07:50:03 +00005054 }
Chris Lattnerad44ebf2003-07-23 18:29:44 +00005055
Chris Lattneracd1f0f2004-07-30 07:50:03 +00005056 // (X ^ C1) | C2 --> (X | C2) ^ (C1&~C2)
Dan Gohman4ae51262009-08-12 16:23:25 +00005057 if (match(Op0, m_Xor(m_Value(X), m_ConstantInt(C1))) &&
Owen Andersonc7d2ce72009-07-10 17:35:01 +00005058 isOnlyUse(Op0)) {
Chris Lattner74381062009-08-30 07:44:24 +00005059 Value *Or = Builder->CreateOr(X, RHS);
Chris Lattner6934a042007-02-11 01:23:03 +00005060 Or->takeName(Op0);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005061 return BinaryOperator::CreateXor(Or,
Owen Andersoneed707b2009-07-24 23:12:02 +00005062 ConstantInt::get(*Context, C1->getValue() & ~RHS->getValue()));
Chris Lattnerad44ebf2003-07-23 18:29:44 +00005063 }
Chris Lattner2eefe512004-04-09 19:05:30 +00005064
5065 // Try to fold constant and into select arguments.
5066 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner6e7ba452005-01-01 16:22:27 +00005067 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00005068 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00005069 if (isa<PHINode>(Op0))
5070 if (Instruction *NV = FoldOpIntoPhi(I))
5071 return NV;
Chris Lattnerad44ebf2003-07-23 18:29:44 +00005072 }
5073
Chris Lattner4f637d42006-01-06 17:59:59 +00005074 Value *A = 0, *B = 0;
5075 ConstantInt *C1 = 0, *C2 = 0;
Chris Lattnerf4d4c872005-05-07 23:49:08 +00005076
Chris Lattner6423d4c2006-07-10 20:25:24 +00005077 // (A | B) | C and A | (B | C) -> bswap if possible.
5078 // (A >> B) | (C << D) and (A << B) | (B >> C) -> bswap if possible.
Dan Gohman4ae51262009-08-12 16:23:25 +00005079 if (match(Op0, m_Or(m_Value(), m_Value())) ||
5080 match(Op1, m_Or(m_Value(), m_Value())) ||
5081 (match(Op0, m_Shift(m_Value(), m_Value())) &&
5082 match(Op1, m_Shift(m_Value(), m_Value())))) {
Chris Lattnerafe91a52006-06-15 19:07:26 +00005083 if (Instruction *BSwap = MatchBSwap(I))
5084 return BSwap;
5085 }
5086
Chris Lattner6e4c6492005-05-09 04:58:36 +00005087 // (X^C)|Y -> (X|Y)^C iff Y&C == 0
Owen Andersonc7d2ce72009-07-10 17:35:01 +00005088 if (Op0->hasOneUse() &&
Dan Gohman4ae51262009-08-12 16:23:25 +00005089 match(Op0, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
Reid Spencera03d45f2007-03-22 22:19:58 +00005090 MaskedValueIsZero(Op1, C1->getValue())) {
Chris Lattner74381062009-08-30 07:44:24 +00005091 Value *NOr = Builder->CreateOr(A, Op1);
Chris Lattner6934a042007-02-11 01:23:03 +00005092 NOr->takeName(Op0);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005093 return BinaryOperator::CreateXor(NOr, C1);
Chris Lattner6e4c6492005-05-09 04:58:36 +00005094 }
5095
5096 // Y|(X^C) -> (X|Y)^C iff Y&C == 0
Owen Andersonc7d2ce72009-07-10 17:35:01 +00005097 if (Op1->hasOneUse() &&
Dan Gohman4ae51262009-08-12 16:23:25 +00005098 match(Op1, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
Reid Spencera03d45f2007-03-22 22:19:58 +00005099 MaskedValueIsZero(Op0, C1->getValue())) {
Chris Lattner74381062009-08-30 07:44:24 +00005100 Value *NOr = Builder->CreateOr(A, Op0);
Chris Lattner6934a042007-02-11 01:23:03 +00005101 NOr->takeName(Op0);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005102 return BinaryOperator::CreateXor(NOr, C1);
Chris Lattner6e4c6492005-05-09 04:58:36 +00005103 }
5104
Chris Lattnerc5e7ea42007-04-08 07:47:01 +00005105 // (A & C)|(B & D)
Chris Lattner2384d7b2007-06-19 05:43:49 +00005106 Value *C = 0, *D = 0;
Dan Gohman4ae51262009-08-12 16:23:25 +00005107 if (match(Op0, m_And(m_Value(A), m_Value(C))) &&
5108 match(Op1, m_And(m_Value(B), m_Value(D)))) {
Chris Lattner6cae0e02007-04-08 07:55:22 +00005109 Value *V1 = 0, *V2 = 0, *V3 = 0;
5110 C1 = dyn_cast<ConstantInt>(C);
5111 C2 = dyn_cast<ConstantInt>(D);
5112 if (C1 && C2) { // (A & C1)|(B & C2)
5113 // If we have: ((V + N) & C1) | (V & C2)
5114 // .. and C2 = ~C1 and C2 is 0+1+ and (N & C2) == 0
5115 // replace with V+N.
5116 if (C1->getValue() == ~C2->getValue()) {
5117 if ((C2->getValue() & (C2->getValue()+1)) == 0 && // C2 == 0+1+
Dan Gohman4ae51262009-08-12 16:23:25 +00005118 match(A, m_Add(m_Value(V1), m_Value(V2)))) {
Chris Lattner6cae0e02007-04-08 07:55:22 +00005119 // Add commutes, try both ways.
5120 if (V1 == B && MaskedValueIsZero(V2, C2->getValue()))
5121 return ReplaceInstUsesWith(I, A);
5122 if (V2 == B && MaskedValueIsZero(V1, C2->getValue()))
5123 return ReplaceInstUsesWith(I, A);
5124 }
5125 // Or commutes, try both ways.
5126 if ((C1->getValue() & (C1->getValue()+1)) == 0 &&
Dan Gohman4ae51262009-08-12 16:23:25 +00005127 match(B, m_Add(m_Value(V1), m_Value(V2)))) {
Chris Lattner6cae0e02007-04-08 07:55:22 +00005128 // Add commutes, try both ways.
5129 if (V1 == A && MaskedValueIsZero(V2, C1->getValue()))
5130 return ReplaceInstUsesWith(I, B);
5131 if (V2 == A && MaskedValueIsZero(V1, C1->getValue()))
5132 return ReplaceInstUsesWith(I, B);
5133 }
5134 }
Chris Lattnere4412c12010-01-04 06:03:59 +00005135
5136 // ((V | N) & C1) | (V & C2) --> (V|N) & (C1|C2)
5137 // iff (C1&C2) == 0 and (N&~C1) == 0
5138 if ((C1->getValue() & C2->getValue()) == 0) {
5139 if (match(A, m_Or(m_Value(V1), m_Value(V2))) &&
5140 ((V1 == B && MaskedValueIsZero(V2, ~C1->getValue())) || // (V|N)
5141 (V2 == B && MaskedValueIsZero(V1, ~C1->getValue())))) // (N|V)
5142 return BinaryOperator::CreateAnd(A,
5143 ConstantInt::get(A->getContext(),
5144 C1->getValue()|C2->getValue()));
5145 // Or commutes, try both ways.
5146 if (match(B, m_Or(m_Value(V1), m_Value(V2))) &&
5147 ((V1 == A && MaskedValueIsZero(V2, ~C2->getValue())) || // (V|N)
5148 (V2 == A && MaskedValueIsZero(V1, ~C2->getValue())))) // (N|V)
5149 return BinaryOperator::CreateAnd(B,
5150 ConstantInt::get(B->getContext(),
5151 C1->getValue()|C2->getValue()));
5152 }
Chris Lattner6cae0e02007-04-08 07:55:22 +00005153 }
5154
Chris Lattnerc5e7ea42007-04-08 07:47:01 +00005155 // Check to see if we have any common things being and'ed. If so, find the
5156 // terms for V1 & (V2|V3).
Chris Lattnerc5e7ea42007-04-08 07:47:01 +00005157 if (isOnlyUse(Op0) || isOnlyUse(Op1)) {
Chris Lattnere4412c12010-01-04 06:03:59 +00005158 V1 = 0;
Chris Lattnerc5e7ea42007-04-08 07:47:01 +00005159 if (A == B) // (A & C)|(A & D) == A & (C|D)
5160 V1 = A, V2 = C, V3 = D;
5161 else if (A == D) // (A & C)|(B & A) == A & (B|C)
5162 V1 = A, V2 = B, V3 = C;
5163 else if (C == B) // (A & C)|(C & D) == C & (A|D)
5164 V1 = C, V2 = A, V3 = D;
5165 else if (C == D) // (A & C)|(B & C) == C & (A|B)
5166 V1 = C, V2 = A, V3 = B;
5167
5168 if (V1) {
Chris Lattner74381062009-08-30 07:44:24 +00005169 Value *Or = Builder->CreateOr(V2, V3, "tmp");
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005170 return BinaryOperator::CreateAnd(V1, Or);
Chris Lattner0b7c0bf2005-09-18 06:02:59 +00005171 }
Chris Lattnerc5e7ea42007-04-08 07:47:01 +00005172 }
Dan Gohmanb493b272008-10-28 22:38:57 +00005173
Dan Gohman1975d032008-10-30 20:40:10 +00005174 // (A & (C0?-1:0)) | (B & ~(C0?-1:0)) -> C0 ? A : B, and commuted variants
Owen Andersonc7d2ce72009-07-10 17:35:01 +00005175 if (Instruction *Match = MatchSelectFromAndOr(A, B, C, D, Context))
Chris Lattnerfaaf9512008-11-16 04:24:12 +00005176 return Match;
Owen Andersonc7d2ce72009-07-10 17:35:01 +00005177 if (Instruction *Match = MatchSelectFromAndOr(B, A, D, C, Context))
Chris Lattnerfaaf9512008-11-16 04:24:12 +00005178 return Match;
Owen Andersonc7d2ce72009-07-10 17:35:01 +00005179 if (Instruction *Match = MatchSelectFromAndOr(C, B, A, D, Context))
Chris Lattnerfaaf9512008-11-16 04:24:12 +00005180 return Match;
Owen Andersonc7d2ce72009-07-10 17:35:01 +00005181 if (Instruction *Match = MatchSelectFromAndOr(D, A, B, C, Context))
Chris Lattnerfaaf9512008-11-16 04:24:12 +00005182 return Match;
Bill Wendlingb01865c2008-11-30 13:52:49 +00005183
Bill Wendlingb01865c2008-11-30 13:52:49 +00005184 // ((A&~B)|(~A&B)) -> A^B
Dan Gohman4ae51262009-08-12 16:23:25 +00005185 if ((match(C, m_Not(m_Specific(D))) &&
5186 match(B, m_Not(m_Specific(A)))))
Bill Wendling03aae5f2008-12-01 08:09:47 +00005187 return BinaryOperator::CreateXor(A, D);
Bill Wendlingb01865c2008-11-30 13:52:49 +00005188 // ((~B&A)|(~A&B)) -> A^B
Dan Gohman4ae51262009-08-12 16:23:25 +00005189 if ((match(A, m_Not(m_Specific(D))) &&
5190 match(B, m_Not(m_Specific(C)))))
Bill Wendling03aae5f2008-12-01 08:09:47 +00005191 return BinaryOperator::CreateXor(C, D);
Bill Wendlingb01865c2008-11-30 13:52:49 +00005192 // ((A&~B)|(B&~A)) -> A^B
Dan Gohman4ae51262009-08-12 16:23:25 +00005193 if ((match(C, m_Not(m_Specific(B))) &&
5194 match(D, m_Not(m_Specific(A)))))
Bill Wendling03aae5f2008-12-01 08:09:47 +00005195 return BinaryOperator::CreateXor(A, B);
Bill Wendlingb01865c2008-11-30 13:52:49 +00005196 // ((~B&A)|(B&~A)) -> A^B
Dan Gohman4ae51262009-08-12 16:23:25 +00005197 if ((match(A, m_Not(m_Specific(B))) &&
5198 match(D, m_Not(m_Specific(C)))))
Bill Wendling03aae5f2008-12-01 08:09:47 +00005199 return BinaryOperator::CreateXor(C, B);
Chris Lattnere9bed7d2005-09-18 03:42:07 +00005200 }
Chris Lattnere511b742006-11-14 07:46:50 +00005201
5202 // (X >> Z) | (Y >> Z) -> (X|Y) >> Z for all shifts.
Reid Spencer832254e2007-02-02 02:16:23 +00005203 if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
5204 if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
5205 if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() &&
Chris Lattnere511b742006-11-14 07:46:50 +00005206 SI0->getOperand(1) == SI1->getOperand(1) &&
5207 (SI0->hasOneUse() || SI1->hasOneUse())) {
Chris Lattner74381062009-08-30 07:44:24 +00005208 Value *NewOp = Builder->CreateOr(SI0->getOperand(0), SI1->getOperand(0),
5209 SI0->getName());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005210 return BinaryOperator::Create(SI1->getOpcode(), NewOp,
Reid Spencer832254e2007-02-02 02:16:23 +00005211 SI1->getOperand(1));
Chris Lattnere511b742006-11-14 07:46:50 +00005212 }
5213 }
Chris Lattner67ca7682003-08-12 19:11:07 +00005214
Bill Wendlingb3833d12008-12-01 01:07:11 +00005215 // ((A|B)&1)|(B&-2) -> (A&1) | B
Dan Gohman4ae51262009-08-12 16:23:25 +00005216 if (match(Op0, m_And(m_Or(m_Value(A), m_Value(B)), m_Value(C))) ||
5217 match(Op0, m_And(m_Value(C), m_Or(m_Value(A), m_Value(B))))) {
Bill Wendlingd54d8602008-12-01 08:32:40 +00005218 Instruction *Ret = FoldOrWithConstants(I, Op1, A, B, C);
Bill Wendlinga698a472008-12-01 08:23:25 +00005219 if (Ret) return Ret;
Bill Wendlingb3833d12008-12-01 01:07:11 +00005220 }
5221 // (B&-2)|((A|B)&1) -> (A&1) | B
Dan Gohman4ae51262009-08-12 16:23:25 +00005222 if (match(Op1, m_And(m_Or(m_Value(A), m_Value(B)), m_Value(C))) ||
5223 match(Op1, m_And(m_Value(C), m_Or(m_Value(A), m_Value(B))))) {
Bill Wendlingd54d8602008-12-01 08:32:40 +00005224 Instruction *Ret = FoldOrWithConstants(I, Op0, A, B, C);
Bill Wendlinga698a472008-12-01 08:23:25 +00005225 if (Ret) return Ret;
Bill Wendlingb3833d12008-12-01 01:07:11 +00005226 }
5227
Chris Lattnerd06094f2009-11-10 00:55:12 +00005228 // (~A | ~B) == (~(A & B)) - De Morgan's Law
5229 if (Value *Op0NotVal = dyn_castNotVal(Op0))
5230 if (Value *Op1NotVal = dyn_castNotVal(Op1))
5231 if (Op0->hasOneUse() && Op1->hasOneUse()) {
5232 Value *And = Builder->CreateAnd(Op0NotVal, Op1NotVal,
5233 I.getName()+".demorgan");
5234 return BinaryOperator::CreateNot(And);
5235 }
Chris Lattnera2881962003-02-18 19:28:33 +00005236
Reid Spencere4d87aa2006-12-23 06:05:41 +00005237 // (icmp1 A, B) | (icmp2 A, B) --> (icmp3 A, B)
5238 if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1))) {
Dan Gohman186a6362009-08-12 16:04:34 +00005239 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
Chris Lattneraa9c1f12003-08-13 20:16:26 +00005240 return R;
5241
Chris Lattner69d4ced2008-11-16 05:20:07 +00005242 if (ICmpInst *LHS = dyn_cast<ICmpInst>(I.getOperand(0)))
5243 if (Instruction *Res = FoldOrOfICmps(I, LHS, RHS))
5244 return Res;
Chris Lattnerb4f40d22004-09-28 22:33:08 +00005245 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00005246
5247 // fold (or (cast A), (cast B)) -> (cast (or A, B))
Chris Lattner99c65742007-10-24 05:38:08 +00005248 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
Chris Lattner6fc205f2006-05-05 06:39:07 +00005249 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00005250 if (Op0C->getOpcode() == Op1C->getOpcode()) {// same cast kind ?
Evan Chengb98a10e2008-03-24 00:21:34 +00005251 if (!isa<ICmpInst>(Op0C->getOperand(0)) ||
5252 !isa<ICmpInst>(Op1C->getOperand(0))) {
5253 const Type *SrcTy = Op0C->getOperand(0)->getType();
Chris Lattnerf98d2532009-07-23 05:32:17 +00005254 if (SrcTy == Op1C->getOperand(0)->getType() &&
5255 SrcTy->isIntOrIntVector() &&
Evan Chengb98a10e2008-03-24 00:21:34 +00005256 // Only do this if the casts both really cause code to be
5257 // generated.
5258 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
5259 I.getType(), TD) &&
5260 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
5261 I.getType(), TD)) {
Chris Lattner74381062009-08-30 07:44:24 +00005262 Value *NewOp = Builder->CreateOr(Op0C->getOperand(0),
5263 Op1C->getOperand(0), I.getName());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005264 return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
Evan Chengb98a10e2008-03-24 00:21:34 +00005265 }
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00005266 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00005267 }
Chris Lattner99c65742007-10-24 05:38:08 +00005268 }
5269
5270
5271 // (fcmp uno x, c) | (fcmp uno y, c) -> (fcmp uno x, y)
5272 if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0))) {
Chris Lattner5414cc52009-07-23 05:46:22 +00005273 if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1)))
5274 if (Instruction *Res = FoldOrOfFCmps(I, LHS, RHS))
5275 return Res;
Chris Lattner99c65742007-10-24 05:38:08 +00005276 }
Chris Lattnere9bed7d2005-09-18 03:42:07 +00005277
Chris Lattner7e708292002-06-25 16:13:24 +00005278 return Changed ? &I : 0;
Chris Lattner3f5b8772002-05-06 16:14:14 +00005279}
5280
Dan Gohman844731a2008-05-13 00:00:25 +00005281namespace {
5282
Chris Lattnerc317d392004-02-16 01:20:27 +00005283// XorSelf - Implements: X ^ X --> 0
5284struct XorSelf {
5285 Value *RHS;
5286 XorSelf(Value *rhs) : RHS(rhs) {}
5287 bool shouldApply(Value *LHS) const { return LHS == RHS; }
5288 Instruction *apply(BinaryOperator &Xor) const {
5289 return &Xor;
5290 }
5291};
Chris Lattner3f5b8772002-05-06 16:14:14 +00005292
Dan Gohman844731a2008-05-13 00:00:25 +00005293}
Chris Lattner3f5b8772002-05-06 16:14:14 +00005294
Chris Lattner7e708292002-06-25 16:13:24 +00005295Instruction *InstCombiner::visitXor(BinaryOperator &I) {
Chris Lattner4f98c562003-03-10 21:43:22 +00005296 bool Changed = SimplifyCommutative(I);
Chris Lattner7e708292002-06-25 16:13:24 +00005297 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00005298
Evan Chengd34af782008-03-25 20:07:13 +00005299 if (isa<UndefValue>(Op1)) {
5300 if (isa<UndefValue>(Op0))
5301 // Handle undef ^ undef -> 0 special case. This is a common
5302 // idiom (misuse).
Owen Andersona7235ea2009-07-31 20:28:14 +00005303 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnere87597f2004-10-16 18:11:37 +00005304 return ReplaceInstUsesWith(I, Op1); // X ^ undef -> undef
Evan Chengd34af782008-03-25 20:07:13 +00005305 }
Chris Lattnere87597f2004-10-16 18:11:37 +00005306
Chris Lattnerc317d392004-02-16 01:20:27 +00005307 // xor X, X = 0, even if X is nested in a sequence of Xor's.
Dan Gohman186a6362009-08-12 16:04:34 +00005308 if (Instruction *Result = AssociativeOpt(I, XorSelf(Op1))) {
Chris Lattnera9ff5eb2007-08-05 08:47:58 +00005309 assert(Result == &I && "AssociativeOpt didn't work?"); Result=Result;
Owen Andersona7235ea2009-07-31 20:28:14 +00005310 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnerc317d392004-02-16 01:20:27 +00005311 }
Chris Lattnerf8c36f52006-02-12 08:02:11 +00005312
5313 // See if we can simplify any instructions used by the instruction whose sole
5314 // purpose is to compute bits we don't care about.
Dan Gohman6de29f82009-06-15 22:12:54 +00005315 if (SimplifyDemandedInstructionBits(I))
5316 return &I;
5317 if (isa<VectorType>(I.getType()))
5318 if (isa<ConstantAggregateZero>(Op1))
5319 return ReplaceInstUsesWith(I, Op0); // X ^ <0,0> -> X
Chris Lattner3f5b8772002-05-06 16:14:14 +00005320
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00005321 // Is this a ~ operation?
Dan Gohman186a6362009-08-12 16:04:34 +00005322 if (Value *NotOp = dyn_castNotVal(&I)) {
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00005323 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(NotOp)) {
5324 if (Op0I->getOpcode() == Instruction::And ||
5325 Op0I->getOpcode() == Instruction::Or) {
Chris Lattner48b59ec2009-10-26 15:40:07 +00005326 // ~(~X & Y) --> (X | ~Y) - De Morgan's Law
5327 // ~(~X | Y) === (X & ~Y) - De Morgan's Law
5328 if (dyn_castNotVal(Op0I->getOperand(1)))
5329 Op0I->swapOperands();
Dan Gohman186a6362009-08-12 16:04:34 +00005330 if (Value *Op0NotVal = dyn_castNotVal(Op0I->getOperand(0))) {
Chris Lattner74381062009-08-30 07:44:24 +00005331 Value *NotY =
5332 Builder->CreateNot(Op0I->getOperand(1),
5333 Op0I->getOperand(1)->getName()+".not");
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00005334 if (Op0I->getOpcode() == Instruction::And)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005335 return BinaryOperator::CreateOr(Op0NotVal, NotY);
Chris Lattner74381062009-08-30 07:44:24 +00005336 return BinaryOperator::CreateAnd(Op0NotVal, NotY);
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00005337 }
Chris Lattner48b59ec2009-10-26 15:40:07 +00005338
5339 // ~(X & Y) --> (~X | ~Y) - De Morgan's Law
5340 // ~(X | Y) === (~X & ~Y) - De Morgan's Law
5341 if (isFreeToInvert(Op0I->getOperand(0)) &&
5342 isFreeToInvert(Op0I->getOperand(1))) {
5343 Value *NotX =
5344 Builder->CreateNot(Op0I->getOperand(0), "notlhs");
5345 Value *NotY =
5346 Builder->CreateNot(Op0I->getOperand(1), "notrhs");
5347 if (Op0I->getOpcode() == Instruction::And)
5348 return BinaryOperator::CreateOr(NotX, NotY);
5349 return BinaryOperator::CreateAnd(NotX, NotY);
5350 }
Chris Lattner7cbe2eb2007-06-15 06:23:19 +00005351 }
5352 }
5353 }
5354
5355
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00005356 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner7acdf1d2009-10-11 22:00:32 +00005357 if (RHS->isOne() && Op0->hasOneUse()) {
Bill Wendling3479be92009-01-01 01:18:23 +00005358 // xor (cmp A, B), true = not (cmp A, B) = !cmp A, B
Nick Lewyckyf947b3e2007-08-06 20:04:16 +00005359 if (ICmpInst *ICI = dyn_cast<ICmpInst>(Op0))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00005360 return new ICmpInst(ICI->getInversePredicate(),
Reid Spencere4d87aa2006-12-23 06:05:41 +00005361 ICI->getOperand(0), ICI->getOperand(1));
Chris Lattnerad5b4fb2003-11-04 23:50:51 +00005362
Nick Lewyckyf947b3e2007-08-06 20:04:16 +00005363 if (FCmpInst *FCI = dyn_cast<FCmpInst>(Op0))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00005364 return new FCmpInst(FCI->getInversePredicate(),
Nick Lewyckyf947b3e2007-08-06 20:04:16 +00005365 FCI->getOperand(0), FCI->getOperand(1));
5366 }
5367
Nick Lewycky517e1f52008-05-31 19:01:33 +00005368 // fold (xor(zext(cmp)), 1) and (xor(sext(cmp)), -1) to ext(!cmp).
5369 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
5370 if (CmpInst *CI = dyn_cast<CmpInst>(Op0C->getOperand(0))) {
5371 if (CI->hasOneUse() && Op0C->hasOneUse()) {
5372 Instruction::CastOps Opcode = Op0C->getOpcode();
Chris Lattner74381062009-08-30 07:44:24 +00005373 if ((Opcode == Instruction::ZExt || Opcode == Instruction::SExt) &&
5374 (RHS == ConstantExpr::getCast(Opcode,
5375 ConstantInt::getTrue(*Context),
5376 Op0C->getDestTy()))) {
5377 CI->setPredicate(CI->getInversePredicate());
5378 return CastInst::Create(Opcode, CI, Op0C->getType());
Nick Lewycky517e1f52008-05-31 19:01:33 +00005379 }
5380 }
5381 }
5382 }
5383
Reid Spencere4d87aa2006-12-23 06:05:41 +00005384 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
Chris Lattnerd65460f2003-11-05 01:06:05 +00005385 // ~(c-X) == X-c-1 == X+(-c-1)
Chris Lattner7c4049c2004-01-12 19:35:11 +00005386 if (Op0I->getOpcode() == Instruction::Sub && RHS->isAllOnesValue())
5387 if (Constant *Op0I0C = dyn_cast<Constant>(Op0I->getOperand(0))) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00005388 Constant *NegOp0I0C = ConstantExpr::getNeg(Op0I0C);
5389 Constant *ConstantRHS = ConstantExpr::getSub(NegOp0I0C,
Owen Andersoneed707b2009-07-24 23:12:02 +00005390 ConstantInt::get(I.getType(), 1));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005391 return BinaryOperator::CreateAdd(Op0I->getOperand(1), ConstantRHS);
Chris Lattner7c4049c2004-01-12 19:35:11 +00005392 }
Chris Lattner5c6e2db2007-04-02 05:36:22 +00005393
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00005394 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
Chris Lattnerf8c36f52006-02-12 08:02:11 +00005395 if (Op0I->getOpcode() == Instruction::Add) {
Chris Lattner689d24b2003-11-04 23:37:10 +00005396 // ~(X-c) --> (-c-1)-X
Chris Lattner7c4049c2004-01-12 19:35:11 +00005397 if (RHS->isAllOnesValue()) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00005398 Constant *NegOp0CI = ConstantExpr::getNeg(Op0CI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005399 return BinaryOperator::CreateSub(
Owen Andersonbaf3c402009-07-29 18:55:55 +00005400 ConstantExpr::getSub(NegOp0CI,
Owen Andersoneed707b2009-07-24 23:12:02 +00005401 ConstantInt::get(I.getType(), 1)),
Owen Andersond672ecb2009-07-03 00:17:18 +00005402 Op0I->getOperand(0));
Chris Lattneracf4e072007-04-02 05:42:22 +00005403 } else if (RHS->getValue().isSignBit()) {
Chris Lattner5c6e2db2007-04-02 05:36:22 +00005404 // (X + C) ^ signbit -> (X + C + signbit)
Owen Andersoneed707b2009-07-24 23:12:02 +00005405 Constant *C = ConstantInt::get(*Context,
5406 RHS->getValue() + Op0CI->getValue());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005407 return BinaryOperator::CreateAdd(Op0I->getOperand(0), C);
Chris Lattnercd1d6d52007-04-02 05:48:58 +00005408
Chris Lattner7c4049c2004-01-12 19:35:11 +00005409 }
Chris Lattner02bd1b32006-02-26 19:57:54 +00005410 } else if (Op0I->getOpcode() == Instruction::Or) {
5411 // (X|C1)^C2 -> X^(C1|C2) iff X&~C1 == 0
Reid Spencera03d45f2007-03-22 22:19:58 +00005412 if (MaskedValueIsZero(Op0I->getOperand(0), Op0CI->getValue())) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00005413 Constant *NewRHS = ConstantExpr::getOr(Op0CI, RHS);
Chris Lattner02bd1b32006-02-26 19:57:54 +00005414 // Anything in both C1 and C2 is known to be zero, remove it from
5415 // NewRHS.
Owen Andersonbaf3c402009-07-29 18:55:55 +00005416 Constant *CommonBits = ConstantExpr::getAnd(Op0CI, RHS);
5417 NewRHS = ConstantExpr::getAnd(NewRHS,
5418 ConstantExpr::getNot(CommonBits));
Chris Lattner7a1e9242009-08-30 06:13:40 +00005419 Worklist.Add(Op0I);
Chris Lattner02bd1b32006-02-26 19:57:54 +00005420 I.setOperand(0, Op0I->getOperand(0));
5421 I.setOperand(1, NewRHS);
5422 return &I;
5423 }
Chris Lattnereca0c5c2003-07-23 21:37:07 +00005424 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00005425 }
Chris Lattner05bd1b22002-08-20 18:24:26 +00005426 }
Chris Lattner2eefe512004-04-09 19:05:30 +00005427
5428 // Try to fold constant and into select arguments.
5429 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
Chris Lattner6e7ba452005-01-01 16:22:27 +00005430 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00005431 return R;
Chris Lattner4e998b22004-09-29 05:07:12 +00005432 if (isa<PHINode>(Op0))
5433 if (Instruction *NV = FoldOpIntoPhi(I))
5434 return NV;
Chris Lattner3f5b8772002-05-06 16:14:14 +00005435 }
5436
Dan Gohman186a6362009-08-12 16:04:34 +00005437 if (Value *X = dyn_castNotVal(Op0)) // ~A ^ A == -1
Chris Lattnera2881962003-02-18 19:28:33 +00005438 if (X == Op1)
Owen Andersona7235ea2009-07-31 20:28:14 +00005439 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Chris Lattnera2881962003-02-18 19:28:33 +00005440
Dan Gohman186a6362009-08-12 16:04:34 +00005441 if (Value *X = dyn_castNotVal(Op1)) // A ^ ~A == -1
Chris Lattnera2881962003-02-18 19:28:33 +00005442 if (X == Op0)
Owen Andersona7235ea2009-07-31 20:28:14 +00005443 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
Chris Lattnera2881962003-02-18 19:28:33 +00005444
Chris Lattner318bf792007-03-18 22:51:34 +00005445
5446 BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1);
5447 if (Op1I) {
5448 Value *A, *B;
Dan Gohman4ae51262009-08-12 16:23:25 +00005449 if (match(Op1I, m_Or(m_Value(A), m_Value(B)))) {
Chris Lattner318bf792007-03-18 22:51:34 +00005450 if (A == Op0) { // B^(B|A) == (A|B)^B
Chris Lattner64daab52006-04-01 08:03:55 +00005451 Op1I->swapOperands();
Chris Lattnercb40a372003-03-10 18:24:17 +00005452 I.swapOperands();
5453 std::swap(Op0, Op1);
Chris Lattner318bf792007-03-18 22:51:34 +00005454 } else if (B == Op0) { // B^(A|B) == (A|B)^B
Chris Lattner64daab52006-04-01 08:03:55 +00005455 I.swapOperands(); // Simplified below.
Chris Lattnercb40a372003-03-10 18:24:17 +00005456 std::swap(Op0, Op1);
Misha Brukmanfd939082005-04-21 23:48:37 +00005457 }
Dan Gohman4ae51262009-08-12 16:23:25 +00005458 } else if (match(Op1I, m_Xor(m_Specific(Op0), m_Value(B)))) {
Chris Lattnercb504b92008-11-16 05:38:51 +00005459 return ReplaceInstUsesWith(I, B); // A^(A^B) == B
Dan Gohman4ae51262009-08-12 16:23:25 +00005460 } else if (match(Op1I, m_Xor(m_Value(A), m_Specific(Op0)))) {
Chris Lattnercb504b92008-11-16 05:38:51 +00005461 return ReplaceInstUsesWith(I, A); // A^(B^A) == B
Dan Gohman4ae51262009-08-12 16:23:25 +00005462 } else if (match(Op1I, m_And(m_Value(A), m_Value(B))) &&
Owen Andersonc7d2ce72009-07-10 17:35:01 +00005463 Op1I->hasOneUse()){
Chris Lattner6abbdf92007-04-01 05:36:37 +00005464 if (A == Op0) { // A^(A&B) -> A^(B&A)
Chris Lattner64daab52006-04-01 08:03:55 +00005465 Op1I->swapOperands();
Chris Lattner6abbdf92007-04-01 05:36:37 +00005466 std::swap(A, B);
5467 }
Chris Lattner318bf792007-03-18 22:51:34 +00005468 if (B == Op0) { // A^(B&A) -> (B&A)^A
Chris Lattner64daab52006-04-01 08:03:55 +00005469 I.swapOperands(); // Simplified below.
5470 std::swap(Op0, Op1);
5471 }
Chris Lattner26ca7e12004-02-16 03:54:20 +00005472 }
Chris Lattner318bf792007-03-18 22:51:34 +00005473 }
5474
5475 BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0);
5476 if (Op0I) {
5477 Value *A, *B;
Dan Gohman4ae51262009-08-12 16:23:25 +00005478 if (match(Op0I, m_Or(m_Value(A), m_Value(B))) &&
Owen Andersonc7d2ce72009-07-10 17:35:01 +00005479 Op0I->hasOneUse()) {
Chris Lattner318bf792007-03-18 22:51:34 +00005480 if (A == Op1) // (B|A)^B == (A|B)^B
5481 std::swap(A, B);
Chris Lattner74381062009-08-30 07:44:24 +00005482 if (B == Op1) // (A|B)^B == A & ~B
5483 return BinaryOperator::CreateAnd(A, Builder->CreateNot(Op1, "tmp"));
Dan Gohman4ae51262009-08-12 16:23:25 +00005484 } else if (match(Op0I, m_Xor(m_Specific(Op1), m_Value(B)))) {
Chris Lattnercb504b92008-11-16 05:38:51 +00005485 return ReplaceInstUsesWith(I, B); // (A^B)^A == B
Dan Gohman4ae51262009-08-12 16:23:25 +00005486 } else if (match(Op0I, m_Xor(m_Value(A), m_Specific(Op1)))) {
Chris Lattnercb504b92008-11-16 05:38:51 +00005487 return ReplaceInstUsesWith(I, A); // (B^A)^A == B
Dan Gohman4ae51262009-08-12 16:23:25 +00005488 } else if (match(Op0I, m_And(m_Value(A), m_Value(B))) &&
Owen Andersonc7d2ce72009-07-10 17:35:01 +00005489 Op0I->hasOneUse()){
Chris Lattner318bf792007-03-18 22:51:34 +00005490 if (A == Op1) // (A&B)^A -> (B&A)^A
5491 std::swap(A, B);
5492 if (B == Op1 && // (B&A)^A == ~B & A
Chris Lattnerae1ab392006-04-01 22:05:01 +00005493 !isa<ConstantInt>(Op1)) { // Canonical form is (B&C)^C
Chris Lattner74381062009-08-30 07:44:24 +00005494 return BinaryOperator::CreateAnd(Builder->CreateNot(A, "tmp"), Op1);
Chris Lattner64daab52006-04-01 08:03:55 +00005495 }
Chris Lattnercb40a372003-03-10 18:24:17 +00005496 }
Chris Lattner318bf792007-03-18 22:51:34 +00005497 }
5498
5499 // (X >> Z) ^ (Y >> Z) -> (X^Y) >> Z for all shifts.
5500 if (Op0I && Op1I && Op0I->isShift() &&
5501 Op0I->getOpcode() == Op1I->getOpcode() &&
5502 Op0I->getOperand(1) == Op1I->getOperand(1) &&
5503 (Op1I->hasOneUse() || Op1I->hasOneUse())) {
Chris Lattner74381062009-08-30 07:44:24 +00005504 Value *NewOp =
5505 Builder->CreateXor(Op0I->getOperand(0), Op1I->getOperand(0),
5506 Op0I->getName());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005507 return BinaryOperator::Create(Op1I->getOpcode(), NewOp,
Chris Lattner318bf792007-03-18 22:51:34 +00005508 Op1I->getOperand(1));
5509 }
5510
5511 if (Op0I && Op1I) {
5512 Value *A, *B, *C, *D;
5513 // (A & B)^(A | B) -> A ^ B
Dan Gohman4ae51262009-08-12 16:23:25 +00005514 if (match(Op0I, m_And(m_Value(A), m_Value(B))) &&
5515 match(Op1I, m_Or(m_Value(C), m_Value(D)))) {
Chris Lattner318bf792007-03-18 22:51:34 +00005516 if ((A == C && B == D) || (A == D && B == C))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005517 return BinaryOperator::CreateXor(A, B);
Chris Lattner318bf792007-03-18 22:51:34 +00005518 }
5519 // (A | B)^(A & B) -> A ^ B
Dan Gohman4ae51262009-08-12 16:23:25 +00005520 if (match(Op0I, m_Or(m_Value(A), m_Value(B))) &&
5521 match(Op1I, m_And(m_Value(C), m_Value(D)))) {
Chris Lattner318bf792007-03-18 22:51:34 +00005522 if ((A == C && B == D) || (A == D && B == C))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005523 return BinaryOperator::CreateXor(A, B);
Chris Lattner318bf792007-03-18 22:51:34 +00005524 }
5525
5526 // (A & B)^(C & D)
5527 if ((Op0I->hasOneUse() || Op1I->hasOneUse()) &&
Dan Gohman4ae51262009-08-12 16:23:25 +00005528 match(Op0I, m_And(m_Value(A), m_Value(B))) &&
5529 match(Op1I, m_And(m_Value(C), m_Value(D)))) {
Chris Lattner318bf792007-03-18 22:51:34 +00005530 // (X & Y)^(X & Y) -> (Y^Z) & X
5531 Value *X = 0, *Y = 0, *Z = 0;
5532 if (A == C)
5533 X = A, Y = B, Z = D;
5534 else if (A == D)
5535 X = A, Y = B, Z = C;
5536 else if (B == C)
5537 X = B, Y = A, Z = D;
5538 else if (B == D)
5539 X = B, Y = A, Z = C;
5540
5541 if (X) {
Chris Lattner74381062009-08-30 07:44:24 +00005542 Value *NewOp = Builder->CreateXor(Y, Z, Op0->getName());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005543 return BinaryOperator::CreateAnd(NewOp, X);
Chris Lattner318bf792007-03-18 22:51:34 +00005544 }
5545 }
5546 }
5547
Reid Spencere4d87aa2006-12-23 06:05:41 +00005548 // (icmp1 A, B) ^ (icmp2 A, B) --> (icmp3 A, B)
5549 if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1)))
Dan Gohman186a6362009-08-12 16:04:34 +00005550 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
Chris Lattneraa9c1f12003-08-13 20:16:26 +00005551 return R;
5552
Chris Lattner6fc205f2006-05-05 06:39:07 +00005553 // fold (xor (cast A), (cast B)) -> (cast (xor A, B))
Chris Lattner99c65742007-10-24 05:38:08 +00005554 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
Chris Lattner6fc205f2006-05-05 06:39:07 +00005555 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00005556 if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind?
5557 const Type *SrcTy = Op0C->getOperand(0)->getType();
Chris Lattner42a75512007-01-15 02:27:26 +00005558 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00005559 // Only do this if the casts both really cause code to be generated.
Reid Spencere4d87aa2006-12-23 06:05:41 +00005560 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
5561 I.getType(), TD) &&
5562 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
5563 I.getType(), TD)) {
Chris Lattner74381062009-08-30 07:44:24 +00005564 Value *NewOp = Builder->CreateXor(Op0C->getOperand(0),
5565 Op1C->getOperand(0), I.getName());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00005566 return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
Reid Spencer5ae9ceb2006-12-13 08:27:15 +00005567 }
Chris Lattner6fc205f2006-05-05 06:39:07 +00005568 }
Chris Lattner99c65742007-10-24 05:38:08 +00005569 }
Nick Lewycky517e1f52008-05-31 19:01:33 +00005570
Chris Lattner7e708292002-06-25 16:13:24 +00005571 return Changed ? &I : 0;
Chris Lattner3f5b8772002-05-06 16:14:14 +00005572}
5573
Owen Andersond672ecb2009-07-03 00:17:18 +00005574static ConstantInt *ExtractElement(Constant *V, Constant *Idx,
Owen Anderson07cf79e2009-07-06 23:00:19 +00005575 LLVMContext *Context) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00005576 return cast<ConstantInt>(ConstantExpr::getExtractElement(V, Idx));
Dan Gohman6de29f82009-06-15 22:12:54 +00005577}
Chris Lattnera96879a2004-09-29 17:40:11 +00005578
Dan Gohman6de29f82009-06-15 22:12:54 +00005579static bool HasAddOverflow(ConstantInt *Result,
5580 ConstantInt *In1, ConstantInt *In2,
5581 bool IsSigned) {
Reid Spencere4e40032007-03-21 23:19:50 +00005582 if (IsSigned)
5583 if (In2->getValue().isNegative())
5584 return Result->getValue().sgt(In1->getValue());
5585 else
5586 return Result->getValue().slt(In1->getValue());
5587 else
5588 return Result->getValue().ult(In1->getValue());
Chris Lattnera96879a2004-09-29 17:40:11 +00005589}
5590
Dan Gohman6de29f82009-06-15 22:12:54 +00005591/// AddWithOverflow - Compute Result = In1+In2, returning true if the result
Dan Gohman1df3fd62008-09-10 23:30:57 +00005592/// overflowed for this type.
Dan Gohman6de29f82009-06-15 22:12:54 +00005593static bool AddWithOverflow(Constant *&Result, Constant *In1,
Owen Anderson07cf79e2009-07-06 23:00:19 +00005594 Constant *In2, LLVMContext *Context,
Owen Andersond672ecb2009-07-03 00:17:18 +00005595 bool IsSigned = false) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00005596 Result = ConstantExpr::getAdd(In1, In2);
Dan Gohman1df3fd62008-09-10 23:30:57 +00005597
Dan Gohman6de29f82009-06-15 22:12:54 +00005598 if (const VectorType *VTy = dyn_cast<VectorType>(In1->getType())) {
5599 for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) {
Owen Anderson1d0be152009-08-13 21:58:54 +00005600 Constant *Idx = ConstantInt::get(Type::getInt32Ty(*Context), i);
Owen Andersond672ecb2009-07-03 00:17:18 +00005601 if (HasAddOverflow(ExtractElement(Result, Idx, Context),
5602 ExtractElement(In1, Idx, Context),
5603 ExtractElement(In2, Idx, Context),
Dan Gohman6de29f82009-06-15 22:12:54 +00005604 IsSigned))
5605 return true;
5606 }
5607 return false;
5608 }
5609
5610 return HasAddOverflow(cast<ConstantInt>(Result),
5611 cast<ConstantInt>(In1), cast<ConstantInt>(In2),
5612 IsSigned);
5613}
5614
5615static bool HasSubOverflow(ConstantInt *Result,
5616 ConstantInt *In1, ConstantInt *In2,
5617 bool IsSigned) {
Dan Gohman1df3fd62008-09-10 23:30:57 +00005618 if (IsSigned)
5619 if (In2->getValue().isNegative())
5620 return Result->getValue().slt(In1->getValue());
5621 else
5622 return Result->getValue().sgt(In1->getValue());
5623 else
5624 return Result->getValue().ugt(In1->getValue());
5625}
5626
Dan Gohman6de29f82009-06-15 22:12:54 +00005627/// SubWithOverflow - Compute Result = In1-In2, returning true if the result
5628/// overflowed for this type.
5629static bool SubWithOverflow(Constant *&Result, Constant *In1,
Owen Anderson07cf79e2009-07-06 23:00:19 +00005630 Constant *In2, LLVMContext *Context,
Owen Andersond672ecb2009-07-03 00:17:18 +00005631 bool IsSigned = false) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00005632 Result = ConstantExpr::getSub(In1, In2);
Dan Gohman6de29f82009-06-15 22:12:54 +00005633
5634 if (const VectorType *VTy = dyn_cast<VectorType>(In1->getType())) {
5635 for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) {
Owen Anderson1d0be152009-08-13 21:58:54 +00005636 Constant *Idx = ConstantInt::get(Type::getInt32Ty(*Context), i);
Owen Andersond672ecb2009-07-03 00:17:18 +00005637 if (HasSubOverflow(ExtractElement(Result, Idx, Context),
5638 ExtractElement(In1, Idx, Context),
5639 ExtractElement(In2, Idx, Context),
Dan Gohman6de29f82009-06-15 22:12:54 +00005640 IsSigned))
5641 return true;
5642 }
5643 return false;
5644 }
5645
5646 return HasSubOverflow(cast<ConstantInt>(Result),
5647 cast<ConstantInt>(In1), cast<ConstantInt>(In2),
5648 IsSigned);
5649}
5650
Chris Lattner10c0d912008-04-22 02:53:33 +00005651
Reid Spencere4d87aa2006-12-23 06:05:41 +00005652/// FoldGEPICmp - Fold comparisons between a GEP instruction and something
Chris Lattner574da9b2005-01-13 20:14:25 +00005653/// else. At this point we know that the GEP is on the LHS of the comparison.
Dan Gohmand6aa02d2009-07-28 01:40:03 +00005654Instruction *InstCombiner::FoldGEPICmp(GEPOperator *GEPLHS, Value *RHS,
Reid Spencere4d87aa2006-12-23 06:05:41 +00005655 ICmpInst::Predicate Cond,
5656 Instruction &I) {
Chris Lattner10c0d912008-04-22 02:53:33 +00005657 // Look through bitcasts.
5658 if (BitCastInst *BCI = dyn_cast<BitCastInst>(RHS))
5659 RHS = BCI->getOperand(0);
Chris Lattnere9d782b2005-01-13 22:25:21 +00005660
Chris Lattner574da9b2005-01-13 20:14:25 +00005661 Value *PtrBase = GEPLHS->getOperand(0);
Dan Gohmand6aa02d2009-07-28 01:40:03 +00005662 if (TD && PtrBase == RHS && GEPLHS->isInBounds()) {
Chris Lattner7c95deb2008-02-05 04:45:32 +00005663 // ((gep Ptr, OFFSET) cmp Ptr) ---> (OFFSET cmp 0).
Chris Lattner10c0d912008-04-22 02:53:33 +00005664 // This transformation (ignoring the base and scales) is valid because we
Dan Gohmand6aa02d2009-07-28 01:40:03 +00005665 // know pointers can't overflow since the gep is inbounds. See if we can
5666 // output an optimized form.
Chris Lattner10c0d912008-04-22 02:53:33 +00005667 Value *Offset = EvaluateGEPOffsetExpression(GEPLHS, I, *this);
5668
5669 // If not, synthesize the offset the hard way.
5670 if (Offset == 0)
Chris Lattner092543c2009-11-04 08:05:20 +00005671 Offset = EmitGEPOffset(GEPLHS, *this);
Dan Gohman1c8a23c2009-08-25 23:17:54 +00005672 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), Offset,
Owen Andersona7235ea2009-07-31 20:28:14 +00005673 Constant::getNullValue(Offset->getType()));
Dan Gohmand6aa02d2009-07-28 01:40:03 +00005674 } else if (GEPOperator *GEPRHS = dyn_cast<GEPOperator>(RHS)) {
Chris Lattnera70b66d2005-04-25 20:17:30 +00005675 // If the base pointers are different, but the indices are the same, just
5676 // compare the base pointer.
5677 if (PtrBase != GEPRHS->getOperand(0)) {
5678 bool IndicesTheSame = GEPLHS->getNumOperands()==GEPRHS->getNumOperands();
Jeff Cohen00b168892005-07-27 06:12:32 +00005679 IndicesTheSame &= GEPLHS->getOperand(0)->getType() ==
Chris Lattner93b94a62005-04-26 14:40:41 +00005680 GEPRHS->getOperand(0)->getType();
Chris Lattnera70b66d2005-04-25 20:17:30 +00005681 if (IndicesTheSame)
5682 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
5683 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
5684 IndicesTheSame = false;
5685 break;
5686 }
5687
5688 // If all indices are the same, just compare the base pointers.
5689 if (IndicesTheSame)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00005690 return new ICmpInst(ICmpInst::getSignedPredicate(Cond),
Reid Spencere4d87aa2006-12-23 06:05:41 +00005691 GEPLHS->getOperand(0), GEPRHS->getOperand(0));
Chris Lattnera70b66d2005-04-25 20:17:30 +00005692
5693 // Otherwise, the base pointers are different and the indices are
5694 // different, bail out.
Chris Lattner574da9b2005-01-13 20:14:25 +00005695 return 0;
Chris Lattnera70b66d2005-04-25 20:17:30 +00005696 }
Chris Lattner574da9b2005-01-13 20:14:25 +00005697
Chris Lattnere9d782b2005-01-13 22:25:21 +00005698 // If one of the GEPs has all zero indices, recurse.
5699 bool AllZeros = true;
5700 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
5701 if (!isa<Constant>(GEPLHS->getOperand(i)) ||
5702 !cast<Constant>(GEPLHS->getOperand(i))->isNullValue()) {
5703 AllZeros = false;
5704 break;
5705 }
5706 if (AllZeros)
Reid Spencere4d87aa2006-12-23 06:05:41 +00005707 return FoldGEPICmp(GEPRHS, GEPLHS->getOperand(0),
5708 ICmpInst::getSwappedPredicate(Cond), I);
Chris Lattner4401c9c2005-01-14 00:20:05 +00005709
5710 // If the other GEP has all zero indices, recurse.
Chris Lattnere9d782b2005-01-13 22:25:21 +00005711 AllZeros = true;
5712 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
5713 if (!isa<Constant>(GEPRHS->getOperand(i)) ||
5714 !cast<Constant>(GEPRHS->getOperand(i))->isNullValue()) {
5715 AllZeros = false;
5716 break;
5717 }
5718 if (AllZeros)
Reid Spencere4d87aa2006-12-23 06:05:41 +00005719 return FoldGEPICmp(GEPLHS, GEPRHS->getOperand(0), Cond, I);
Chris Lattnere9d782b2005-01-13 22:25:21 +00005720
Chris Lattner4401c9c2005-01-14 00:20:05 +00005721 if (GEPLHS->getNumOperands() == GEPRHS->getNumOperands()) {
5722 // If the GEPs only differ by one index, compare it.
5723 unsigned NumDifferences = 0; // Keep track of # differences.
5724 unsigned DiffOperand = 0; // The operand that differs.
5725 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
5726 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
Chris Lattner484d3cf2005-04-24 06:59:08 +00005727 if (GEPLHS->getOperand(i)->getType()->getPrimitiveSizeInBits() !=
5728 GEPRHS->getOperand(i)->getType()->getPrimitiveSizeInBits()) {
Chris Lattner45f57b82005-01-21 23:06:49 +00005729 // Irreconcilable differences.
Chris Lattner4401c9c2005-01-14 00:20:05 +00005730 NumDifferences = 2;
5731 break;
5732 } else {
5733 if (NumDifferences++) break;
5734 DiffOperand = i;
5735 }
5736 }
5737
5738 if (NumDifferences == 0) // SAME GEP?
5739 return ReplaceInstUsesWith(I, // No comparison is needed here.
Owen Anderson1d0be152009-08-13 21:58:54 +00005740 ConstantInt::get(Type::getInt1Ty(*Context),
Nick Lewyckyfc1efbb2008-05-17 07:33:39 +00005741 ICmpInst::isTrueWhenEqual(Cond)));
Nick Lewycky455e1762007-09-06 02:40:25 +00005742
Chris Lattner4401c9c2005-01-14 00:20:05 +00005743 else if (NumDifferences == 1) {
Chris Lattner45f57b82005-01-21 23:06:49 +00005744 Value *LHSV = GEPLHS->getOperand(DiffOperand);
5745 Value *RHSV = GEPRHS->getOperand(DiffOperand);
Reid Spencere4d87aa2006-12-23 06:05:41 +00005746 // Make sure we do a signed comparison here.
Dan Gohman1c8a23c2009-08-25 23:17:54 +00005747 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), LHSV, RHSV);
Chris Lattner4401c9c2005-01-14 00:20:05 +00005748 }
5749 }
5750
Reid Spencere4d87aa2006-12-23 06:05:41 +00005751 // Only lower this if the icmp is the only user of the GEP or if we expect
Chris Lattner574da9b2005-01-13 20:14:25 +00005752 // the result to fold to a constant!
Dan Gohmance9fe9f2009-07-21 23:21:54 +00005753 if (TD &&
5754 (isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) &&
Chris Lattner574da9b2005-01-13 20:14:25 +00005755 (isa<ConstantExpr>(GEPRHS) || GEPRHS->hasOneUse())) {
5756 // ((gep Ptr, OFFSET1) cmp (gep Ptr, OFFSET2) ---> (OFFSET1 cmp OFFSET2)
Chris Lattner092543c2009-11-04 08:05:20 +00005757 Value *L = EmitGEPOffset(GEPLHS, *this);
5758 Value *R = EmitGEPOffset(GEPRHS, *this);
Dan Gohman1c8a23c2009-08-25 23:17:54 +00005759 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), L, R);
Chris Lattner574da9b2005-01-13 20:14:25 +00005760 }
5761 }
5762 return 0;
5763}
5764
Chris Lattnera5406232008-05-19 20:18:56 +00005765/// FoldFCmp_IntToFP_Cst - Fold fcmp ([us]itofp x, cst) if possible.
5766///
5767Instruction *InstCombiner::FoldFCmp_IntToFP_Cst(FCmpInst &I,
5768 Instruction *LHSI,
5769 Constant *RHSC) {
5770 if (!isa<ConstantFP>(RHSC)) return 0;
5771 const APFloat &RHS = cast<ConstantFP>(RHSC)->getValueAPF();
5772
5773 // Get the width of the mantissa. We don't want to hack on conversions that
5774 // might lose information from the integer, e.g. "i64 -> float"
Chris Lattner7be1c452008-05-19 21:17:23 +00005775 int MantissaWidth = LHSI->getType()->getFPMantissaWidth();
Chris Lattnera5406232008-05-19 20:18:56 +00005776 if (MantissaWidth == -1) return 0; // Unknown.
5777
5778 // Check to see that the input is converted from an integer type that is small
5779 // enough that preserves all bits. TODO: check here for "known" sign bits.
5780 // This would allow us to handle (fptosi (x >>s 62) to float) if x is i64 f.e.
Dan Gohman6de29f82009-06-15 22:12:54 +00005781 unsigned InputSize = LHSI->getOperand(0)->getType()->getScalarSizeInBits();
Chris Lattnera5406232008-05-19 20:18:56 +00005782
5783 // If this is a uitofp instruction, we need an extra bit to hold the sign.
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005784 bool LHSUnsigned = isa<UIToFPInst>(LHSI);
5785 if (LHSUnsigned)
Chris Lattnera5406232008-05-19 20:18:56 +00005786 ++InputSize;
5787
5788 // If the conversion would lose info, don't hack on this.
5789 if ((int)InputSize > MantissaWidth)
5790 return 0;
5791
5792 // Otherwise, we can potentially simplify the comparison. We know that it
5793 // will always come through as an integer value and we know the constant is
5794 // not a NAN (it would have been previously simplified).
5795 assert(!RHS.isNaN() && "NaN comparison not already folded!");
5796
5797 ICmpInst::Predicate Pred;
5798 switch (I.getPredicate()) {
Torok Edwinc23197a2009-07-14 16:55:14 +00005799 default: llvm_unreachable("Unexpected predicate!");
Chris Lattnera5406232008-05-19 20:18:56 +00005800 case FCmpInst::FCMP_UEQ:
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005801 case FCmpInst::FCMP_OEQ:
5802 Pred = ICmpInst::ICMP_EQ;
5803 break;
Chris Lattnera5406232008-05-19 20:18:56 +00005804 case FCmpInst::FCMP_UGT:
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005805 case FCmpInst::FCMP_OGT:
5806 Pred = LHSUnsigned ? ICmpInst::ICMP_UGT : ICmpInst::ICMP_SGT;
5807 break;
Chris Lattnera5406232008-05-19 20:18:56 +00005808 case FCmpInst::FCMP_UGE:
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005809 case FCmpInst::FCMP_OGE:
5810 Pred = LHSUnsigned ? ICmpInst::ICMP_UGE : ICmpInst::ICMP_SGE;
5811 break;
Chris Lattnera5406232008-05-19 20:18:56 +00005812 case FCmpInst::FCMP_ULT:
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005813 case FCmpInst::FCMP_OLT:
5814 Pred = LHSUnsigned ? ICmpInst::ICMP_ULT : ICmpInst::ICMP_SLT;
5815 break;
Chris Lattnera5406232008-05-19 20:18:56 +00005816 case FCmpInst::FCMP_ULE:
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005817 case FCmpInst::FCMP_OLE:
5818 Pred = LHSUnsigned ? ICmpInst::ICMP_ULE : ICmpInst::ICMP_SLE;
5819 break;
Chris Lattnera5406232008-05-19 20:18:56 +00005820 case FCmpInst::FCMP_UNE:
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005821 case FCmpInst::FCMP_ONE:
5822 Pred = ICmpInst::ICMP_NE;
5823 break;
Chris Lattnera5406232008-05-19 20:18:56 +00005824 case FCmpInst::FCMP_ORD:
Owen Anderson5defacc2009-07-31 17:39:07 +00005825 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Chris Lattnera5406232008-05-19 20:18:56 +00005826 case FCmpInst::FCMP_UNO:
Owen Anderson5defacc2009-07-31 17:39:07 +00005827 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Chris Lattnera5406232008-05-19 20:18:56 +00005828 }
5829
5830 const IntegerType *IntTy = cast<IntegerType>(LHSI->getOperand(0)->getType());
5831
5832 // Now we know that the APFloat is a normal number, zero or inf.
5833
Chris Lattner85162782008-05-20 03:50:52 +00005834 // See if the FP constant is too large for the integer. For example,
Chris Lattnera5406232008-05-19 20:18:56 +00005835 // comparing an i8 to 300.0.
Dan Gohman6de29f82009-06-15 22:12:54 +00005836 unsigned IntWidth = IntTy->getScalarSizeInBits();
Chris Lattnera5406232008-05-19 20:18:56 +00005837
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005838 if (!LHSUnsigned) {
5839 // If the RHS value is > SignedMax, fold the comparison. This handles +INF
5840 // and large values.
5841 APFloat SMax(RHS.getSemantics(), APFloat::fcZero, false);
5842 SMax.convertFromAPInt(APInt::getSignedMaxValue(IntWidth), true,
5843 APFloat::rmNearestTiesToEven);
5844 if (SMax.compare(RHS) == APFloat::cmpLessThan) { // smax < 13123.0
5845 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_SLT ||
5846 Pred == ICmpInst::ICMP_SLE)
Owen Anderson5defacc2009-07-31 17:39:07 +00005847 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
5848 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005849 }
5850 } else {
5851 // If the RHS value is > UnsignedMax, fold the comparison. This handles
5852 // +INF and large values.
5853 APFloat UMax(RHS.getSemantics(), APFloat::fcZero, false);
5854 UMax.convertFromAPInt(APInt::getMaxValue(IntWidth), false,
5855 APFloat::rmNearestTiesToEven);
5856 if (UMax.compare(RHS) == APFloat::cmpLessThan) { // umax < 13123.0
5857 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_ULT ||
5858 Pred == ICmpInst::ICMP_ULE)
Owen Anderson5defacc2009-07-31 17:39:07 +00005859 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
5860 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005861 }
Chris Lattnera5406232008-05-19 20:18:56 +00005862 }
5863
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005864 if (!LHSUnsigned) {
5865 // See if the RHS value is < SignedMin.
5866 APFloat SMin(RHS.getSemantics(), APFloat::fcZero, false);
5867 SMin.convertFromAPInt(APInt::getSignedMinValue(IntWidth), true,
5868 APFloat::rmNearestTiesToEven);
5869 if (SMin.compare(RHS) == APFloat::cmpGreaterThan) { // smin > 12312.0
5870 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_SGT ||
5871 Pred == ICmpInst::ICMP_SGE)
Owen Anderson5defacc2009-07-31 17:39:07 +00005872 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
5873 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005874 }
Chris Lattnera5406232008-05-19 20:18:56 +00005875 }
5876
Bill Wendlingc143bcf2008-11-09 04:26:50 +00005877 // Okay, now we know that the FP constant fits in the range [SMIN, SMAX] or
5878 // [0, UMAX], but it may still be fractional. See if it is fractional by
5879 // casting the FP value to the integer value and back, checking for equality.
5880 // Don't do this for zero, because -0.0 is not fractional.
Evan Cheng2ddb6f12009-05-22 23:10:53 +00005881 Constant *RHSInt = LHSUnsigned
Owen Andersonbaf3c402009-07-29 18:55:55 +00005882 ? ConstantExpr::getFPToUI(RHSC, IntTy)
5883 : ConstantExpr::getFPToSI(RHSC, IntTy);
Evan Cheng2ddb6f12009-05-22 23:10:53 +00005884 if (!RHS.isZero()) {
5885 bool Equal = LHSUnsigned
Owen Andersonbaf3c402009-07-29 18:55:55 +00005886 ? ConstantExpr::getUIToFP(RHSInt, RHSC->getType()) == RHSC
5887 : ConstantExpr::getSIToFP(RHSInt, RHSC->getType()) == RHSC;
Evan Cheng2ddb6f12009-05-22 23:10:53 +00005888 if (!Equal) {
5889 // If we had a comparison against a fractional value, we have to adjust
5890 // the compare predicate and sometimes the value. RHSC is rounded towards
5891 // zero at this point.
5892 switch (Pred) {
Torok Edwinc23197a2009-07-14 16:55:14 +00005893 default: llvm_unreachable("Unexpected integer comparison!");
Evan Cheng2ddb6f12009-05-22 23:10:53 +00005894 case ICmpInst::ICMP_NE: // (float)int != 4.4 --> true
Owen Anderson5defacc2009-07-31 17:39:07 +00005895 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Evan Cheng2ddb6f12009-05-22 23:10:53 +00005896 case ICmpInst::ICMP_EQ: // (float)int == 4.4 --> false
Owen Anderson5defacc2009-07-31 17:39:07 +00005897 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Evan Cheng2ddb6f12009-05-22 23:10:53 +00005898 case ICmpInst::ICMP_ULE:
5899 // (float)int <= 4.4 --> int <= 4
5900 // (float)int <= -4.4 --> false
5901 if (RHS.isNegative())
Owen Anderson5defacc2009-07-31 17:39:07 +00005902 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Evan Cheng2ddb6f12009-05-22 23:10:53 +00005903 break;
5904 case ICmpInst::ICMP_SLE:
5905 // (float)int <= 4.4 --> int <= 4
5906 // (float)int <= -4.4 --> int < -4
5907 if (RHS.isNegative())
5908 Pred = ICmpInst::ICMP_SLT;
5909 break;
5910 case ICmpInst::ICMP_ULT:
5911 // (float)int < -4.4 --> false
5912 // (float)int < 4.4 --> int <= 4
5913 if (RHS.isNegative())
Owen Anderson5defacc2009-07-31 17:39:07 +00005914 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Evan Cheng2ddb6f12009-05-22 23:10:53 +00005915 Pred = ICmpInst::ICMP_ULE;
5916 break;
5917 case ICmpInst::ICMP_SLT:
5918 // (float)int < -4.4 --> int < -4
5919 // (float)int < 4.4 --> int <= 4
5920 if (!RHS.isNegative())
5921 Pred = ICmpInst::ICMP_SLE;
5922 break;
5923 case ICmpInst::ICMP_UGT:
5924 // (float)int > 4.4 --> int > 4
5925 // (float)int > -4.4 --> true
5926 if (RHS.isNegative())
Owen Anderson5defacc2009-07-31 17:39:07 +00005927 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Evan Cheng2ddb6f12009-05-22 23:10:53 +00005928 break;
5929 case ICmpInst::ICMP_SGT:
5930 // (float)int > 4.4 --> int > 4
5931 // (float)int > -4.4 --> int >= -4
5932 if (RHS.isNegative())
5933 Pred = ICmpInst::ICMP_SGE;
5934 break;
5935 case ICmpInst::ICMP_UGE:
5936 // (float)int >= -4.4 --> true
5937 // (float)int >= 4.4 --> int > 4
5938 if (!RHS.isNegative())
Owen Anderson5defacc2009-07-31 17:39:07 +00005939 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Evan Cheng2ddb6f12009-05-22 23:10:53 +00005940 Pred = ICmpInst::ICMP_UGT;
5941 break;
5942 case ICmpInst::ICMP_SGE:
5943 // (float)int >= -4.4 --> int >= -4
5944 // (float)int >= 4.4 --> int > 4
5945 if (!RHS.isNegative())
5946 Pred = ICmpInst::ICMP_SGT;
5947 break;
5948 }
Chris Lattnera5406232008-05-19 20:18:56 +00005949 }
5950 }
5951
5952 // Lower this FP comparison into an appropriate integer version of the
5953 // comparison.
Dan Gohman1c8a23c2009-08-25 23:17:54 +00005954 return new ICmpInst(Pred, LHSI->getOperand(0), RHSInt);
Chris Lattnera5406232008-05-19 20:18:56 +00005955}
5956
Chris Lattner1f12e442010-01-02 08:12:04 +00005957/// FoldCmpLoadFromIndexedGlobal - Called we see this pattern:
5958/// cmp pred (load (gep GV, ...)), cmpcst
5959/// where GV is a global variable with a constant initializer. Try to simplify
Chris Lattner82602bc2010-01-02 20:20:33 +00005960/// this into some simple computation that does not need the load. For example
5961/// we can optimize "icmp eq (load (gep "foo", 0, i)), 0" into "icmp eq i, 3".
Chris Lattnerdf3d63b2010-01-02 22:08:28 +00005962///
5963/// If AndCst is non-null, then the loaded value is masked with that constant
5964/// before doing the comparison. This handles cases like "A[i]&4 == 0".
Chris Lattner1f12e442010-01-02 08:12:04 +00005965Instruction *InstCombiner::
5966FoldCmpLoadFromIndexedGlobal(GetElementPtrInst *GEP, GlobalVariable *GV,
Chris Lattnerdf3d63b2010-01-02 22:08:28 +00005967 CmpInst &ICI, ConstantInt *AndCst) {
Chris Lattner56ba7a72010-01-03 03:03:27 +00005968 ConstantArray *Init = dyn_cast<ConstantArray>(GV->getInitializer());
5969 if (Init == 0 || Init->getNumOperands() > 1024) return 0;
Chris Lattner1f12e442010-01-02 08:12:04 +00005970
5971 // There are many forms of this optimization we can handle, for now, just do
5972 // the simple index into a single-dimensional array.
5973 //
Chris Lattner56ba7a72010-01-03 03:03:27 +00005974 // Require: GEP GV, 0, i {{, constant indices}}
5975 if (GEP->getNumOperands() < 3 ||
Chris Lattner1f12e442010-01-02 08:12:04 +00005976 !isa<ConstantInt>(GEP->getOperand(1)) ||
Chris Lattner56ba7a72010-01-03 03:03:27 +00005977 !cast<ConstantInt>(GEP->getOperand(1))->isZero() ||
5978 isa<Constant>(GEP->getOperand(2)))
Chris Lattner1f12e442010-01-02 08:12:04 +00005979 return 0;
Chris Lattner56ba7a72010-01-03 03:03:27 +00005980
5981 // Check that indices after the variable are constants and in-range for the
5982 // type they index. Collect the indices. This is typically for arrays of
5983 // structs.
5984 SmallVector<unsigned, 4> LaterIndices;
Chris Lattner1f12e442010-01-02 08:12:04 +00005985
Chris Lattner56ba7a72010-01-03 03:03:27 +00005986 const Type *EltTy = cast<ArrayType>(Init->getType())->getElementType();
5987 for (unsigned i = 3, e = GEP->getNumOperands(); i != e; ++i) {
5988 ConstantInt *Idx = dyn_cast<ConstantInt>(GEP->getOperand(i));
5989 if (Idx == 0) return 0; // Variable index.
5990
5991 uint64_t IdxVal = Idx->getZExtValue();
5992 if ((unsigned)IdxVal != IdxVal) return 0; // Too large array index.
5993
5994 if (const StructType *STy = dyn_cast<StructType>(EltTy))
5995 EltTy = STy->getElementType(IdxVal);
5996 else if (const ArrayType *ATy = dyn_cast<ArrayType>(EltTy)) {
5997 if (IdxVal >= ATy->getNumElements()) return 0;
5998 EltTy = ATy->getElementType();
5999 } else {
6000 return 0; // Unknown type.
6001 }
6002
6003 LaterIndices.push_back(IdxVal);
6004 }
Chris Lattner1f12e442010-01-02 08:12:04 +00006005
Chris Lattner82602bc2010-01-02 20:20:33 +00006006 enum { Overdefined = -3, Undefined = -2 };
6007
Chris Lattner1f12e442010-01-02 08:12:04 +00006008 // Variables for our state machines.
6009
Chris Lattnerbef37372010-01-02 09:35:17 +00006010 // FirstTrueElement/SecondTrueElement - Used to emit a comparison of the form
6011 // "i == 47 | i == 87", where 47 is the first index the condition is true for,
Chris Lattner82602bc2010-01-02 20:20:33 +00006012 // and 87 is the second (and last) index. FirstTrueElement is -2 when
Chris Lattnerbef37372010-01-02 09:35:17 +00006013 // undefined, otherwise set to the first true element. SecondTrueElement is
Chris Lattner82602bc2010-01-02 20:20:33 +00006014 // -2 when undefined, -3 when overdefined and >= 0 when that index is true.
6015 int FirstTrueElement = Undefined, SecondTrueElement = Undefined;
Chris Lattner1f12e442010-01-02 08:12:04 +00006016
Chris Lattnerbef37372010-01-02 09:35:17 +00006017 // FirstFalseElement/SecondFalseElement - Used to emit a comparison of the
6018 // form "i != 47 & i != 87". Same state transitions as for true elements.
Chris Lattner82602bc2010-01-02 20:20:33 +00006019 int FirstFalseElement = Undefined, SecondFalseElement = Undefined;
Chris Lattner1f12e442010-01-02 08:12:04 +00006020
Chris Lattnerb4f82b42010-01-02 21:50:18 +00006021 /// TrueRangeEnd/FalseRangeEnd - In conjunction with First*Element, these
6022 /// define a state machine that triggers for ranges of values that the index
6023 /// is true or false for. This triggers on things like "abbbbc"[i] == 'b'.
6024 /// This is -2 when undefined, -3 when overdefined, and otherwise the last
6025 /// index in the range (inclusive). We use -2 for undefined here because we
6026 /// use relative comparisons and don't want 0-1 to match -1.
6027 int TrueRangeEnd = Undefined, FalseRangeEnd = Undefined;
6028
Chris Lattner10d514e2010-01-02 08:56:52 +00006029 // MagicBitvector - This is a magic bitvector where we set a bit if the
6030 // comparison is true for element 'i'. If there are 64 elements or less in
6031 // the array, this will fully represent all the comparison results.
6032 uint64_t MagicBitvector = 0;
6033
6034
Chris Lattner1f12e442010-01-02 08:12:04 +00006035 // Scan the array and see if one of our patterns matches.
6036 Constant *CompareRHS = cast<Constant>(ICI.getOperand(1));
6037 for (unsigned i = 0, e = Init->getNumOperands(); i != e; ++i) {
Chris Lattnerdf3d63b2010-01-02 22:08:28 +00006038 Constant *Elt = Init->getOperand(i);
6039
Chris Lattner56ba7a72010-01-03 03:03:27 +00006040 // If this is indexing an array of structures, get the structure element.
6041 if (!LaterIndices.empty())
6042 Elt = ConstantExpr::getExtractValue(Elt, LaterIndices.data(),
6043 LaterIndices.size());
6044
Chris Lattnerdf3d63b2010-01-02 22:08:28 +00006045 // If the element is masked, handle it.
6046 if (AndCst) Elt = ConstantExpr::getAnd(Elt, AndCst);
6047
Chris Lattner1f12e442010-01-02 08:12:04 +00006048 // Find out if the comparison would be true or false for the i'th element.
Chris Lattnerdf3d63b2010-01-02 22:08:28 +00006049 Constant *C = ConstantFoldCompareInstOperands(ICI.getPredicate(), Elt,
Chris Lattner1f12e442010-01-02 08:12:04 +00006050 CompareRHS, TD);
6051 // If the result is undef for this element, ignore it.
Chris Lattnerb4f82b42010-01-02 21:50:18 +00006052 if (isa<UndefValue>(C)) {
6053 // Extend range state machines to cover this element in case there is an
6054 // undef in the middle of the range.
6055 if (TrueRangeEnd == (int)i-1)
6056 TrueRangeEnd = i;
6057 if (FalseRangeEnd == (int)i-1)
6058 FalseRangeEnd = i;
6059 continue;
6060 }
Chris Lattner1f12e442010-01-02 08:12:04 +00006061
6062 // If we can't compute the result for any of the elements, we have to give
6063 // up evaluating the entire conditional.
6064 if (!isa<ConstantInt>(C)) return 0;
6065
6066 // Otherwise, we know if the comparison is true or false for this element,
6067 // update our state machines.
6068 bool IsTrueForElt = !cast<ConstantInt>(C)->isZero();
6069
Chris Lattnerb4f82b42010-01-02 21:50:18 +00006070 // State machine for single/double/range index comparison.
Chris Lattner1f12e442010-01-02 08:12:04 +00006071 if (IsTrueForElt) {
Chris Lattnerbef37372010-01-02 09:35:17 +00006072 // Update the TrueElement state machine.
Chris Lattner82602bc2010-01-02 20:20:33 +00006073 if (FirstTrueElement == Undefined)
Chris Lattnerb4f82b42010-01-02 21:50:18 +00006074 FirstTrueElement = TrueRangeEnd = i; // First true element.
6075 else {
6076 // Update double-compare state machine.
6077 if (SecondTrueElement == Undefined)
6078 SecondTrueElement = i;
6079 else
6080 SecondTrueElement = Overdefined;
6081
6082 // Update range state machine.
6083 if (TrueRangeEnd == (int)i-1)
6084 TrueRangeEnd = i;
6085 else
6086 TrueRangeEnd = Overdefined;
6087 }
Chris Lattner1f12e442010-01-02 08:12:04 +00006088 } else {
Chris Lattnerbef37372010-01-02 09:35:17 +00006089 // Update the FalseElement state machine.
Chris Lattner82602bc2010-01-02 20:20:33 +00006090 if (FirstFalseElement == Undefined)
Chris Lattnerb4f82b42010-01-02 21:50:18 +00006091 FirstFalseElement = FalseRangeEnd = i; // First false element.
6092 else {
6093 // Update double-compare state machine.
6094 if (SecondFalseElement == Undefined)
6095 SecondFalseElement = i;
6096 else
6097 SecondFalseElement = Overdefined;
6098
6099 // Update range state machine.
6100 if (FalseRangeEnd == (int)i-1)
6101 FalseRangeEnd = i;
6102 else
6103 FalseRangeEnd = Overdefined;
6104 }
Chris Lattner1f12e442010-01-02 08:12:04 +00006105 }
6106
Chris Lattnerb4f82b42010-01-02 21:50:18 +00006107
Chris Lattner10d514e2010-01-02 08:56:52 +00006108 // If this element is in range, update our magic bitvector.
6109 if (i < 64 && IsTrueForElt)
Chris Lattner33a1ec72010-01-02 09:22:13 +00006110 MagicBitvector |= 1ULL << i;
Chris Lattner10d514e2010-01-02 08:56:52 +00006111
Chris Lattnerb4f82b42010-01-02 21:50:18 +00006112 // If all of our states become overdefined, bail out early. Since the
6113 // predicate is expensive, only check it every 8 elements. This is only
6114 // really useful for really huge arrays.
6115 if ((i & 8) == 0 && i >= 64 && SecondTrueElement == Overdefined &&
6116 SecondFalseElement == Overdefined && TrueRangeEnd == Overdefined &&
6117 FalseRangeEnd == Overdefined)
Chris Lattner1f12e442010-01-02 08:12:04 +00006118 return 0;
6119 }
6120
6121 // Now that we've scanned the entire array, emit our new comparison(s). We
6122 // order the state machines in complexity of the generated code.
Chris Lattnerbef37372010-01-02 09:35:17 +00006123 Value *Idx = GEP->getOperand(2);
6124
Chris Lattnerb4f82b42010-01-02 21:50:18 +00006125
Chris Lattnerbef37372010-01-02 09:35:17 +00006126 // If the comparison is only true for one or two elements, emit direct
6127 // comparisons.
Chris Lattner82602bc2010-01-02 20:20:33 +00006128 if (SecondTrueElement != Overdefined) {
Chris Lattner1f12e442010-01-02 08:12:04 +00006129 // None true -> false.
Chris Lattner82602bc2010-01-02 20:20:33 +00006130 if (FirstTrueElement == Undefined)
Chris Lattner1f12e442010-01-02 08:12:04 +00006131 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse(*Context));
6132
Chris Lattnerbef37372010-01-02 09:35:17 +00006133 Value *FirstTrueIdx = ConstantInt::get(Idx->getType(), FirstTrueElement);
6134
Chris Lattner1f12e442010-01-02 08:12:04 +00006135 // True for one element -> 'i == 47'.
Chris Lattner82602bc2010-01-02 20:20:33 +00006136 if (SecondTrueElement == Undefined)
Chris Lattnerbef37372010-01-02 09:35:17 +00006137 return new ICmpInst(ICmpInst::ICMP_EQ, Idx, FirstTrueIdx);
6138
6139 // True for two elements -> 'i == 47 | i == 72'.
6140 Value *C1 = Builder->CreateICmpEQ(Idx, FirstTrueIdx);
6141 Value *SecondTrueIdx = ConstantInt::get(Idx->getType(), SecondTrueElement);
6142 Value *C2 = Builder->CreateICmpEQ(Idx, SecondTrueIdx);
6143 return BinaryOperator::CreateOr(C1, C2);
Chris Lattner1f12e442010-01-02 08:12:04 +00006144 }
6145
Chris Lattnerbef37372010-01-02 09:35:17 +00006146 // If the comparison is only false for one or two elements, emit direct
6147 // comparisons.
Chris Lattner82602bc2010-01-02 20:20:33 +00006148 if (SecondFalseElement != Overdefined) {
Chris Lattner1f12e442010-01-02 08:12:04 +00006149 // None false -> true.
Chris Lattner82602bc2010-01-02 20:20:33 +00006150 if (FirstFalseElement == Undefined)
Chris Lattner1f12e442010-01-02 08:12:04 +00006151 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue(*Context));
6152
Chris Lattnerbef37372010-01-02 09:35:17 +00006153 Value *FirstFalseIdx = ConstantInt::get(Idx->getType(), FirstFalseElement);
6154
6155 // False for one element -> 'i != 47'.
Chris Lattner82602bc2010-01-02 20:20:33 +00006156 if (SecondFalseElement == Undefined)
Chris Lattnerbef37372010-01-02 09:35:17 +00006157 return new ICmpInst(ICmpInst::ICMP_NE, Idx, FirstFalseIdx);
6158
6159 // False for two elements -> 'i != 47 & i != 72'.
6160 Value *C1 = Builder->CreateICmpNE(Idx, FirstFalseIdx);
6161 Value *SecondFalseIdx = ConstantInt::get(Idx->getType(),SecondFalseElement);
6162 Value *C2 = Builder->CreateICmpNE(Idx, SecondFalseIdx);
6163 return BinaryOperator::CreateAnd(C1, C2);
Chris Lattner1f12e442010-01-02 08:12:04 +00006164 }
6165
Chris Lattnerb4f82b42010-01-02 21:50:18 +00006166 // If the comparison can be replaced with a range comparison for the elements
6167 // where it is true, emit the range check.
6168 if (TrueRangeEnd != Overdefined) {
6169 assert(TrueRangeEnd != FirstTrueElement && "Should emit single compare");
6170
6171 // Generate (i-FirstTrue) <u (TrueRangeEnd-FirstTrue+1).
6172 if (FirstTrueElement) {
6173 Value *Offs = ConstantInt::get(Idx->getType(), -FirstTrueElement);
6174 Idx = Builder->CreateAdd(Idx, Offs);
6175 }
6176
6177 Value *End = ConstantInt::get(Idx->getType(),
6178 TrueRangeEnd-FirstTrueElement+1);
6179 return new ICmpInst(ICmpInst::ICMP_ULT, Idx, End);
6180 }
6181
6182 // False range check.
6183 if (FalseRangeEnd != Overdefined) {
6184 assert(FalseRangeEnd != FirstFalseElement && "Should emit single compare");
6185 // Generate (i-FirstFalse) >u (FalseRangeEnd-FirstFalse).
6186 if (FirstFalseElement) {
6187 Value *Offs = ConstantInt::get(Idx->getType(), -FirstFalseElement);
6188 Idx = Builder->CreateAdd(Idx, Offs);
6189 }
6190
6191 Value *End = ConstantInt::get(Idx->getType(),
6192 FalseRangeEnd-FirstFalseElement);
6193 return new ICmpInst(ICmpInst::ICMP_UGT, Idx, End);
6194 }
6195
6196
Chris Lattner10d514e2010-01-02 08:56:52 +00006197 // If a 32-bit or 64-bit magic bitvector captures the entire comparison state
6198 // of this load, replace it with computation that does:
6199 // ((magic_cst >> i) & 1) != 0
6200 if (Init->getNumOperands() <= 32 ||
6201 (TD && Init->getNumOperands() <= 64 && TD->isLegalInteger(64))) {
6202 const Type *Ty;
6203 if (Init->getNumOperands() <= 32)
6204 Ty = Type::getInt32Ty(Init->getContext());
6205 else
6206 Ty = Type::getInt64Ty(Init->getContext());
Chris Lattnerbef37372010-01-02 09:35:17 +00006207 Value *V = Builder->CreateIntCast(Idx, Ty, false);
Chris Lattner10d514e2010-01-02 08:56:52 +00006208 V = Builder->CreateLShr(ConstantInt::get(Ty, MagicBitvector), V);
6209 V = Builder->CreateAnd(ConstantInt::get(Ty, 1), V);
6210 return new ICmpInst(ICmpInst::ICMP_NE, V, ConstantInt::get(Ty, 0));
6211 }
Chris Lattner1f12e442010-01-02 08:12:04 +00006212
Chris Lattner1f12e442010-01-02 08:12:04 +00006213 return 0;
6214}
6215
6216
Reid Spencere4d87aa2006-12-23 06:05:41 +00006217Instruction *InstCombiner::visitFCmpInst(FCmpInst &I) {
Chris Lattnerb0bdac02009-11-09 23:31:49 +00006218 bool Changed = false;
6219
6220 /// Orders the operands of the compare so that they are listed from most
6221 /// complex to least complex. This puts constants before unary operators,
6222 /// before binary operators.
6223 if (getComplexity(I.getOperand(0)) < getComplexity(I.getOperand(1))) {
6224 I.swapOperands();
6225 Changed = true;
6226 }
6227
Chris Lattner8b170942002-08-09 23:47:40 +00006228 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner58e97462007-01-14 19:42:17 +00006229
Chris Lattner210c5d42009-11-09 23:55:12 +00006230 if (Value *V = SimplifyFCmpInst(I.getPredicate(), Op0, Op1, TD))
6231 return ReplaceInstUsesWith(I, V);
6232
Chris Lattner58e97462007-01-14 19:42:17 +00006233 // Simplify 'fcmp pred X, X'
6234 if (Op0 == Op1) {
6235 switch (I.getPredicate()) {
Torok Edwinc23197a2009-07-14 16:55:14 +00006236 default: llvm_unreachable("Unknown predicate!");
Chris Lattner58e97462007-01-14 19:42:17 +00006237 case FCmpInst::FCMP_UNO: // True if unordered: isnan(X) | isnan(Y)
6238 case FCmpInst::FCMP_ULT: // True if unordered or less than
6239 case FCmpInst::FCMP_UGT: // True if unordered or greater than
6240 case FCmpInst::FCMP_UNE: // True if unordered or not equal
6241 // Canonicalize these to be 'fcmp uno %X, 0.0'.
6242 I.setPredicate(FCmpInst::FCMP_UNO);
Owen Andersona7235ea2009-07-31 20:28:14 +00006243 I.setOperand(1, Constant::getNullValue(Op0->getType()));
Chris Lattner58e97462007-01-14 19:42:17 +00006244 return &I;
6245
6246 case FCmpInst::FCMP_ORD: // True if ordered (no nans)
6247 case FCmpInst::FCMP_OEQ: // True if ordered and equal
6248 case FCmpInst::FCMP_OGE: // True if ordered and greater than or equal
6249 case FCmpInst::FCMP_OLE: // True if ordered and less than or equal
6250 // Canonicalize these to be 'fcmp ord %X, 0.0'.
6251 I.setPredicate(FCmpInst::FCMP_ORD);
Owen Andersona7235ea2009-07-31 20:28:14 +00006252 I.setOperand(1, Constant::getNullValue(Op0->getType()));
Chris Lattner58e97462007-01-14 19:42:17 +00006253 return &I;
6254 }
6255 }
6256
Reid Spencere4d87aa2006-12-23 06:05:41 +00006257 // Handle fcmp with constant RHS
6258 if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
6259 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
6260 switch (LHSI->getOpcode()) {
6261 case Instruction::PHI:
Chris Lattner7d8ab4e2008-06-08 20:52:11 +00006262 // Only fold fcmp into the PHI if the phi and fcmp are in the same
6263 // block. If in the same block, we're encouraging jump threading. If
6264 // not, we are just pessimizing the code by making an i1 phi.
6265 if (LHSI->getParent() == I.getParent())
Chris Lattner213cd612009-09-27 20:46:36 +00006266 if (Instruction *NV = FoldOpIntoPhi(I, true))
Chris Lattner7d8ab4e2008-06-08 20:52:11 +00006267 return NV;
Reid Spencere4d87aa2006-12-23 06:05:41 +00006268 break;
Chris Lattnera5406232008-05-19 20:18:56 +00006269 case Instruction::SIToFP:
6270 case Instruction::UIToFP:
6271 if (Instruction *NV = FoldFCmp_IntToFP_Cst(I, LHSI, RHSC))
6272 return NV;
6273 break;
Chris Lattner34e0c762010-01-02 08:20:51 +00006274 case Instruction::Select: {
Reid Spencere4d87aa2006-12-23 06:05:41 +00006275 // If either operand of the select is a constant, we can fold the
6276 // comparison into the select arms, which will cause one to be
6277 // constant folded and the select turned into a bitwise or.
6278 Value *Op1 = 0, *Op2 = 0;
6279 if (LHSI->hasOneUse()) {
6280 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
6281 // Fold the known value into the constant operand.
Owen Andersonbaf3c402009-07-29 18:55:55 +00006282 Op1 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
Reid Spencere4d87aa2006-12-23 06:05:41 +00006283 // Insert a new FCmp of the other select operand.
Chris Lattner74381062009-08-30 07:44:24 +00006284 Op2 = Builder->CreateFCmp(I.getPredicate(),
6285 LHSI->getOperand(2), RHSC, I.getName());
Reid Spencere4d87aa2006-12-23 06:05:41 +00006286 } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
6287 // Fold the known value into the constant operand.
Owen Andersonbaf3c402009-07-29 18:55:55 +00006288 Op2 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
Reid Spencere4d87aa2006-12-23 06:05:41 +00006289 // Insert a new FCmp of the other select operand.
Chris Lattner74381062009-08-30 07:44:24 +00006290 Op1 = Builder->CreateFCmp(I.getPredicate(), LHSI->getOperand(1),
6291 RHSC, I.getName());
Reid Spencere4d87aa2006-12-23 06:05:41 +00006292 }
6293 }
6294
6295 if (Op1)
Gabor Greif051a9502008-04-06 20:25:17 +00006296 return SelectInst::Create(LHSI->getOperand(0), Op1, Op2);
Reid Spencere4d87aa2006-12-23 06:05:41 +00006297 break;
6298 }
Chris Lattner34e0c762010-01-02 08:20:51 +00006299 case Instruction::Load:
6300 if (GetElementPtrInst *GEP =
6301 dyn_cast<GetElementPtrInst>(LHSI->getOperand(0))) {
6302 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(GEP->getOperand(0)))
6303 if (GV->isConstant() && GV->hasDefinitiveInitializer() &&
Chris Lattnera0085af2010-01-03 06:58:48 +00006304 !cast<LoadInst>(LHSI)->isVolatile())
Chris Lattner34e0c762010-01-02 08:20:51 +00006305 if (Instruction *Res = FoldCmpLoadFromIndexedGlobal(GEP, GV, I))
6306 return Res;
Chris Lattner34e0c762010-01-02 08:20:51 +00006307 }
6308 break;
6309 }
Reid Spencere4d87aa2006-12-23 06:05:41 +00006310 }
6311
6312 return Changed ? &I : 0;
6313}
6314
6315Instruction *InstCombiner::visitICmpInst(ICmpInst &I) {
Chris Lattnerb0bdac02009-11-09 23:31:49 +00006316 bool Changed = false;
6317
6318 /// Orders the operands of the compare so that they are listed from most
6319 /// complex to least complex. This puts constants before unary operators,
6320 /// before binary operators.
6321 if (getComplexity(I.getOperand(0)) < getComplexity(I.getOperand(1))) {
6322 I.swapOperands();
6323 Changed = true;
6324 }
6325
Reid Spencere4d87aa2006-12-23 06:05:41 +00006326 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Christopher Lamb7a0678c2007-12-18 21:32:20 +00006327
Chris Lattner210c5d42009-11-09 23:55:12 +00006328 if (Value *V = SimplifyICmpInst(I.getPredicate(), Op0, Op1, TD))
6329 return ReplaceInstUsesWith(I, V);
6330
6331 const Type *Ty = Op0->getType();
Chris Lattner8b170942002-08-09 23:47:40 +00006332
Reid Spencere4d87aa2006-12-23 06:05:41 +00006333 // icmp's with boolean values can always be turned into bitwise operations
Owen Anderson1d0be152009-08-13 21:58:54 +00006334 if (Ty == Type::getInt1Ty(*Context)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00006335 switch (I.getPredicate()) {
Torok Edwinc23197a2009-07-14 16:55:14 +00006336 default: llvm_unreachable("Invalid icmp instruction!");
Chris Lattner85b5eb02008-07-11 04:20:58 +00006337 case ICmpInst::ICMP_EQ: { // icmp eq i1 A, B -> ~(A^B)
Chris Lattner74381062009-08-30 07:44:24 +00006338 Value *Xor = Builder->CreateXor(Op0, Op1, I.getName()+"tmp");
Dan Gohman4ae51262009-08-12 16:23:25 +00006339 return BinaryOperator::CreateNot(Xor);
Chris Lattner8b170942002-08-09 23:47:40 +00006340 }
Chris Lattner85b5eb02008-07-11 04:20:58 +00006341 case ICmpInst::ICMP_NE: // icmp eq i1 A, B -> A^B
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006342 return BinaryOperator::CreateXor(Op0, Op1);
Chris Lattner8b170942002-08-09 23:47:40 +00006343
Reid Spencere4d87aa2006-12-23 06:05:41 +00006344 case ICmpInst::ICMP_UGT:
Chris Lattner85b5eb02008-07-11 04:20:58 +00006345 std::swap(Op0, Op1); // Change icmp ugt -> icmp ult
Chris Lattner5dbef222004-08-11 00:50:51 +00006346 // FALL THROUGH
Chris Lattner85b5eb02008-07-11 04:20:58 +00006347 case ICmpInst::ICMP_ULT:{ // icmp ult i1 A, B -> ~A & B
Chris Lattner74381062009-08-30 07:44:24 +00006348 Value *Not = Builder->CreateNot(Op0, I.getName()+"tmp");
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006349 return BinaryOperator::CreateAnd(Not, Op1);
Chris Lattner5dbef222004-08-11 00:50:51 +00006350 }
Chris Lattner85b5eb02008-07-11 04:20:58 +00006351 case ICmpInst::ICMP_SGT:
6352 std::swap(Op0, Op1); // Change icmp sgt -> icmp slt
Chris Lattner5dbef222004-08-11 00:50:51 +00006353 // FALL THROUGH
Chris Lattner85b5eb02008-07-11 04:20:58 +00006354 case ICmpInst::ICMP_SLT: { // icmp slt i1 A, B -> A & ~B
Chris Lattner74381062009-08-30 07:44:24 +00006355 Value *Not = Builder->CreateNot(Op1, I.getName()+"tmp");
Chris Lattner85b5eb02008-07-11 04:20:58 +00006356 return BinaryOperator::CreateAnd(Not, Op0);
6357 }
6358 case ICmpInst::ICMP_UGE:
6359 std::swap(Op0, Op1); // Change icmp uge -> icmp ule
6360 // FALL THROUGH
6361 case ICmpInst::ICMP_ULE: { // icmp ule i1 A, B -> ~A | B
Chris Lattner74381062009-08-30 07:44:24 +00006362 Value *Not = Builder->CreateNot(Op0, I.getName()+"tmp");
Gabor Greif7cbd8a32008-05-16 19:29:10 +00006363 return BinaryOperator::CreateOr(Not, Op1);
Chris Lattner5dbef222004-08-11 00:50:51 +00006364 }
Chris Lattner85b5eb02008-07-11 04:20:58 +00006365 case ICmpInst::ICMP_SGE:
6366 std::swap(Op0, Op1); // Change icmp sge -> icmp sle
6367 // FALL THROUGH
6368 case ICmpInst::ICMP_SLE: { // icmp sle i1 A, B -> A | ~B
Chris Lattner74381062009-08-30 07:44:24 +00006369 Value *Not = Builder->CreateNot(Op1, I.getName()+"tmp");
Chris Lattner85b5eb02008-07-11 04:20:58 +00006370 return BinaryOperator::CreateOr(Not, Op0);
6371 }
Chris Lattner5dbef222004-08-11 00:50:51 +00006372 }
Chris Lattner8b170942002-08-09 23:47:40 +00006373 }
6374
Dan Gohman1c8491e2009-04-25 17:12:48 +00006375 unsigned BitWidth = 0;
6376 if (TD)
Dan Gohmanc6ac3222009-06-16 19:55:29 +00006377 BitWidth = TD->getTypeSizeInBits(Ty->getScalarType());
6378 else if (Ty->isIntOrIntVector())
6379 BitWidth = Ty->getScalarSizeInBits();
Dan Gohman1c8491e2009-04-25 17:12:48 +00006380
6381 bool isSignBit = false;
6382
Dan Gohman81b28ce2008-09-16 18:46:06 +00006383 // See if we are doing a comparison with a constant.
Chris Lattner8b170942002-08-09 23:47:40 +00006384 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Nick Lewycky579214a2009-02-27 06:37:39 +00006385 Value *A = 0, *B = 0;
Christopher Lamb103e1a32007-12-20 07:21:11 +00006386
Chris Lattnerb6566012008-01-05 01:18:20 +00006387 // (icmp ne/eq (sub A B) 0) -> (icmp ne/eq A, B)
Chris Lattner1f12e442010-01-02 08:12:04 +00006388 if (I.isEquality() && CI->isZero() &&
Dan Gohman4ae51262009-08-12 16:23:25 +00006389 match(Op0, m_Sub(m_Value(A), m_Value(B)))) {
Chris Lattnerb6566012008-01-05 01:18:20 +00006390 // (icmp cond A B) if cond is equality
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006391 return new ICmpInst(I.getPredicate(), A, B);
Owen Andersonf5783f82007-12-28 07:42:12 +00006392 }
Christopher Lamb103e1a32007-12-20 07:21:11 +00006393
Dan Gohman81b28ce2008-09-16 18:46:06 +00006394 // If we have an icmp le or icmp ge instruction, turn it into the
6395 // appropriate icmp lt or icmp gt instruction. This allows us to rely on
Chris Lattner210c5d42009-11-09 23:55:12 +00006396 // them being folded in the code below. The SimplifyICmpInst code has
6397 // already handled the edge cases for us, so we just assert on them.
Chris Lattner84dff672008-07-11 05:08:55 +00006398 switch (I.getPredicate()) {
6399 default: break;
6400 case ICmpInst::ICMP_ULE:
Chris Lattner210c5d42009-11-09 23:55:12 +00006401 assert(!CI->isMaxValue(false)); // A <=u MAX -> TRUE
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006402 return new ICmpInst(ICmpInst::ICMP_ULT, Op0,
Dan Gohman186a6362009-08-12 16:04:34 +00006403 AddOne(CI));
Chris Lattner84dff672008-07-11 05:08:55 +00006404 case ICmpInst::ICMP_SLE:
Chris Lattner210c5d42009-11-09 23:55:12 +00006405 assert(!CI->isMaxValue(true)); // A <=s MAX -> TRUE
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006406 return new ICmpInst(ICmpInst::ICMP_SLT, Op0,
Dan Gohman186a6362009-08-12 16:04:34 +00006407 AddOne(CI));
Chris Lattner84dff672008-07-11 05:08:55 +00006408 case ICmpInst::ICMP_UGE:
Chris Lattner210c5d42009-11-09 23:55:12 +00006409 assert(!CI->isMinValue(false)); // A >=u MIN -> TRUE
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006410 return new ICmpInst(ICmpInst::ICMP_UGT, Op0,
Dan Gohman186a6362009-08-12 16:04:34 +00006411 SubOne(CI));
Chris Lattner84dff672008-07-11 05:08:55 +00006412 case ICmpInst::ICMP_SGE:
Chris Lattner210c5d42009-11-09 23:55:12 +00006413 assert(!CI->isMinValue(true)); // A >=s MIN -> TRUE
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006414 return new ICmpInst(ICmpInst::ICMP_SGT, Op0,
Dan Gohman186a6362009-08-12 16:04:34 +00006415 SubOne(CI));
Chris Lattner84dff672008-07-11 05:08:55 +00006416 }
6417
Chris Lattner183661e2008-07-11 05:40:05 +00006418 // If this comparison is a normal comparison, it demands all
Chris Lattner4241e4d2007-07-15 20:54:51 +00006419 // bits, if it is a sign bit comparison, it only demands the sign bit.
Chris Lattner4241e4d2007-07-15 20:54:51 +00006420 bool UnusedBit;
Dan Gohman1c8491e2009-04-25 17:12:48 +00006421 isSignBit = isSignBitCheck(I.getPredicate(), CI, UnusedBit);
6422 }
6423
6424 // See if we can fold the comparison based on range information we can get
6425 // by checking whether bits are known to be zero or one in the input.
6426 if (BitWidth != 0) {
6427 APInt Op0KnownZero(BitWidth, 0), Op0KnownOne(BitWidth, 0);
6428 APInt Op1KnownZero(BitWidth, 0), Op1KnownOne(BitWidth, 0);
6429
6430 if (SimplifyDemandedBits(I.getOperandUse(0),
Chris Lattner4241e4d2007-07-15 20:54:51 +00006431 isSignBit ? APInt::getSignBit(BitWidth)
6432 : APInt::getAllOnesValue(BitWidth),
Dan Gohman1c8491e2009-04-25 17:12:48 +00006433 Op0KnownZero, Op0KnownOne, 0))
Chris Lattnerbf5d8a82006-02-12 02:07:56 +00006434 return &I;
Dan Gohman1c8491e2009-04-25 17:12:48 +00006435 if (SimplifyDemandedBits(I.getOperandUse(1),
6436 APInt::getAllOnesValue(BitWidth),
6437 Op1KnownZero, Op1KnownOne, 0))
6438 return &I;
6439
Chris Lattnerbf5d8a82006-02-12 02:07:56 +00006440 // Given the known and unknown bits, compute a range that the LHS could be
Chris Lattner84dff672008-07-11 05:08:55 +00006441 // in. Compute the Min, Max and RHS values based on the known bits. For the
6442 // EQ and NE we use unsigned values.
Dan Gohman1c8491e2009-04-25 17:12:48 +00006443 APInt Op0Min(BitWidth, 0), Op0Max(BitWidth, 0);
6444 APInt Op1Min(BitWidth, 0), Op1Max(BitWidth, 0);
Nick Lewycky4a134af2009-10-25 05:20:17 +00006445 if (I.isSigned()) {
Dan Gohman1c8491e2009-04-25 17:12:48 +00006446 ComputeSignedMinMaxValuesFromKnownBits(Op0KnownZero, Op0KnownOne,
6447 Op0Min, Op0Max);
6448 ComputeSignedMinMaxValuesFromKnownBits(Op1KnownZero, Op1KnownOne,
6449 Op1Min, Op1Max);
6450 } else {
6451 ComputeUnsignedMinMaxValuesFromKnownBits(Op0KnownZero, Op0KnownOne,
6452 Op0Min, Op0Max);
6453 ComputeUnsignedMinMaxValuesFromKnownBits(Op1KnownZero, Op1KnownOne,
6454 Op1Min, Op1Max);
6455 }
6456
Chris Lattner183661e2008-07-11 05:40:05 +00006457 // If Min and Max are known to be the same, then SimplifyDemandedBits
6458 // figured out that the LHS is a constant. Just constant fold this now so
6459 // that code below can assume that Min != Max.
Dan Gohman1c8491e2009-04-25 17:12:48 +00006460 if (!isa<Constant>(Op0) && Op0Min == Op0Max)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006461 return new ICmpInst(I.getPredicate(),
Owen Andersoneed707b2009-07-24 23:12:02 +00006462 ConstantInt::get(*Context, Op0Min), Op1);
Dan Gohman1c8491e2009-04-25 17:12:48 +00006463 if (!isa<Constant>(Op1) && Op1Min == Op1Max)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006464 return new ICmpInst(I.getPredicate(), Op0,
Owen Andersoneed707b2009-07-24 23:12:02 +00006465 ConstantInt::get(*Context, Op1Min));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006466
Chris Lattner183661e2008-07-11 05:40:05 +00006467 // Based on the range information we know about the LHS, see if we can
6468 // simplify this comparison. For example, (x&4) < 8 is always true.
Dan Gohman1c8491e2009-04-25 17:12:48 +00006469 switch (I.getPredicate()) {
Torok Edwinc23197a2009-07-14 16:55:14 +00006470 default: llvm_unreachable("Unknown icmp opcode!");
Chris Lattner84dff672008-07-11 05:08:55 +00006471 case ICmpInst::ICMP_EQ:
Dan Gohman1c8491e2009-04-25 17:12:48 +00006472 if (Op0Max.ult(Op1Min) || Op0Min.ugt(Op1Max))
Owen Anderson5defacc2009-07-31 17:39:07 +00006473 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Chris Lattner84dff672008-07-11 05:08:55 +00006474 break;
6475 case ICmpInst::ICMP_NE:
Dan Gohman1c8491e2009-04-25 17:12:48 +00006476 if (Op0Max.ult(Op1Min) || Op0Min.ugt(Op1Max))
Owen Anderson5defacc2009-07-31 17:39:07 +00006477 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Chris Lattner84dff672008-07-11 05:08:55 +00006478 break;
6479 case ICmpInst::ICMP_ULT:
Dan Gohman1c8491e2009-04-25 17:12:48 +00006480 if (Op0Max.ult(Op1Min)) // A <u B -> true if max(A) < min(B)
Owen Anderson5defacc2009-07-31 17:39:07 +00006481 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006482 if (Op0Min.uge(Op1Max)) // A <u B -> false if min(A) >= max(B)
Owen Anderson5defacc2009-07-31 17:39:07 +00006483 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006484 if (Op1Min == Op0Max) // A <u B -> A != B if max(A) == min(B)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006485 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
Dan Gohman1c8491e2009-04-25 17:12:48 +00006486 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6487 if (Op1Max == Op0Min+1) // A <u C -> A == C-1 if min(A)+1 == C
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006488 return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
Dan Gohman186a6362009-08-12 16:04:34 +00006489 SubOne(CI));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006490
6491 // (x <u 2147483648) -> (x >s -1) -> true if sign bit clear
6492 if (CI->isMinValue(true))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006493 return new ICmpInst(ICmpInst::ICMP_SGT, Op0,
Owen Andersona7235ea2009-07-31 20:28:14 +00006494 Constant::getAllOnesValue(Op0->getType()));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006495 }
Chris Lattner84dff672008-07-11 05:08:55 +00006496 break;
6497 case ICmpInst::ICMP_UGT:
Dan Gohman1c8491e2009-04-25 17:12:48 +00006498 if (Op0Min.ugt(Op1Max)) // A >u B -> true if min(A) > max(B)
Owen Anderson5defacc2009-07-31 17:39:07 +00006499 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006500 if (Op0Max.ule(Op1Min)) // A >u B -> false if max(A) <= max(B)
Owen Anderson5defacc2009-07-31 17:39:07 +00006501 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006502
6503 if (Op1Max == Op0Min) // A >u B -> A != B if min(A) == max(B)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006504 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
Dan Gohman1c8491e2009-04-25 17:12:48 +00006505 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6506 if (Op1Min == Op0Max-1) // A >u C -> A == C+1 if max(a)-1 == C
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006507 return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
Dan Gohman186a6362009-08-12 16:04:34 +00006508 AddOne(CI));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006509
6510 // (x >u 2147483647) -> (x <s 0) -> true if sign bit set
6511 if (CI->isMaxValue(true))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006512 return new ICmpInst(ICmpInst::ICMP_SLT, Op0,
Owen Andersona7235ea2009-07-31 20:28:14 +00006513 Constant::getNullValue(Op0->getType()));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006514 }
Chris Lattner84dff672008-07-11 05:08:55 +00006515 break;
6516 case ICmpInst::ICMP_SLT:
Dan Gohman1c8491e2009-04-25 17:12:48 +00006517 if (Op0Max.slt(Op1Min)) // A <s B -> true if max(A) < min(C)
Owen Anderson5defacc2009-07-31 17:39:07 +00006518 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006519 if (Op0Min.sge(Op1Max)) // A <s B -> false if min(A) >= max(C)
Owen Anderson5defacc2009-07-31 17:39:07 +00006520 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006521 if (Op1Min == Op0Max) // A <s B -> A != B if max(A) == min(B)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006522 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
Dan Gohman1c8491e2009-04-25 17:12:48 +00006523 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6524 if (Op1Max == Op0Min+1) // A <s C -> A == C-1 if min(A)+1 == C
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006525 return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
Dan Gohman186a6362009-08-12 16:04:34 +00006526 SubOne(CI));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006527 }
Chris Lattner84dff672008-07-11 05:08:55 +00006528 break;
Dan Gohman1c8491e2009-04-25 17:12:48 +00006529 case ICmpInst::ICMP_SGT:
6530 if (Op0Min.sgt(Op1Max)) // A >s B -> true if min(A) > max(B)
Owen Anderson5defacc2009-07-31 17:39:07 +00006531 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006532 if (Op0Max.sle(Op1Min)) // A >s B -> false if max(A) <= min(B)
Owen Anderson5defacc2009-07-31 17:39:07 +00006533 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006534
6535 if (Op1Max == Op0Min) // A >s B -> A != B if min(A) == max(B)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006536 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
Dan Gohman1c8491e2009-04-25 17:12:48 +00006537 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6538 if (Op1Min == Op0Max-1) // A >s C -> A == C+1 if max(A)-1 == C
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006539 return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
Dan Gohman186a6362009-08-12 16:04:34 +00006540 AddOne(CI));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006541 }
6542 break;
6543 case ICmpInst::ICMP_SGE:
6544 assert(!isa<ConstantInt>(Op1) && "ICMP_SGE with ConstantInt not folded!");
6545 if (Op0Min.sge(Op1Max)) // A >=s B -> true if min(A) >= max(B)
Owen Anderson5defacc2009-07-31 17:39:07 +00006546 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006547 if (Op0Max.slt(Op1Min)) // A >=s B -> false if max(A) < min(B)
Owen Anderson5defacc2009-07-31 17:39:07 +00006548 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006549 break;
6550 case ICmpInst::ICMP_SLE:
6551 assert(!isa<ConstantInt>(Op1) && "ICMP_SLE with ConstantInt not folded!");
6552 if (Op0Max.sle(Op1Min)) // A <=s B -> true if max(A) <= min(B)
Owen Anderson5defacc2009-07-31 17:39:07 +00006553 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006554 if (Op0Min.sgt(Op1Max)) // A <=s B -> false if min(A) > max(B)
Owen Anderson5defacc2009-07-31 17:39:07 +00006555 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006556 break;
6557 case ICmpInst::ICMP_UGE:
6558 assert(!isa<ConstantInt>(Op1) && "ICMP_UGE with ConstantInt not folded!");
6559 if (Op0Min.uge(Op1Max)) // A >=u B -> true if min(A) >= max(B)
Owen Anderson5defacc2009-07-31 17:39:07 +00006560 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006561 if (Op0Max.ult(Op1Min)) // A >=u B -> false if max(A) < min(B)
Owen Anderson5defacc2009-07-31 17:39:07 +00006562 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006563 break;
6564 case ICmpInst::ICMP_ULE:
6565 assert(!isa<ConstantInt>(Op1) && "ICMP_ULE with ConstantInt not folded!");
6566 if (Op0Max.ule(Op1Min)) // A <=u B -> true if max(A) <= min(B)
Owen Anderson5defacc2009-07-31 17:39:07 +00006567 return ReplaceInstUsesWith(I, ConstantInt::getTrue(*Context));
Dan Gohman1c8491e2009-04-25 17:12:48 +00006568 if (Op0Min.ugt(Op1Max)) // A <=u B -> false if min(A) > max(B)
Owen Anderson5defacc2009-07-31 17:39:07 +00006569 return ReplaceInstUsesWith(I, ConstantInt::getFalse(*Context));
Chris Lattner84dff672008-07-11 05:08:55 +00006570 break;
Chris Lattnerbf5d8a82006-02-12 02:07:56 +00006571 }
Dan Gohman1c8491e2009-04-25 17:12:48 +00006572
6573 // Turn a signed comparison into an unsigned one if both operands
6574 // are known to have the same sign.
Nick Lewycky4a134af2009-10-25 05:20:17 +00006575 if (I.isSigned() &&
Dan Gohman1c8491e2009-04-25 17:12:48 +00006576 ((Op0KnownZero.isNegative() && Op1KnownZero.isNegative()) ||
6577 (Op0KnownOne.isNegative() && Op1KnownOne.isNegative())))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006578 return new ICmpInst(I.getUnsignedPredicate(), Op0, Op1);
Dan Gohman81b28ce2008-09-16 18:46:06 +00006579 }
6580
6581 // Test if the ICmpInst instruction is used exclusively by a select as
6582 // part of a minimum or maximum operation. If so, refrain from doing
6583 // any other folding. This helps out other analyses which understand
6584 // non-obfuscated minimum and maximum idioms, such as ScalarEvolution
6585 // and CodeGen. And in this case, at least one of the comparison
6586 // operands has at least one user besides the compare (the select),
6587 // which would often largely negate the benefit of folding anyway.
6588 if (I.hasOneUse())
6589 if (SelectInst *SI = dyn_cast<SelectInst>(*I.use_begin()))
6590 if ((SI->getOperand(1) == Op0 && SI->getOperand(2) == Op1) ||
6591 (SI->getOperand(2) == Op0 && SI->getOperand(1) == Op1))
6592 return 0;
6593
6594 // See if we are doing a comparison between a constant and an instruction that
6595 // can be folded into the comparison.
6596 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00006597 // Since the RHS is a ConstantInt (CI), if the left hand side is an
Reid Spencer1628cec2006-10-26 06:15:43 +00006598 // instruction, see if that instruction also has constants so that the
Reid Spencere4d87aa2006-12-23 06:05:41 +00006599 // instruction can be folded into the icmp
Chris Lattner3c6a0d42004-05-25 06:32:08 +00006600 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
Chris Lattner01deb9d2007-04-03 17:43:25 +00006601 if (Instruction *Res = visitICmpInstWithInstAndIntCst(I, LHSI, CI))
6602 return Res;
Chris Lattner3f5b8772002-05-06 16:14:14 +00006603 }
6604
Chris Lattner01deb9d2007-04-03 17:43:25 +00006605 // Handle icmp with constant (but not simple integer constant) RHS
Chris Lattner6970b662005-04-23 15:31:55 +00006606 if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
6607 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
6608 switch (LHSI->getOpcode()) {
Chris Lattner9fb25db2005-05-01 04:42:15 +00006609 case Instruction::GetElementPtr:
Reid Spencere4d87aa2006-12-23 06:05:41 +00006610 // icmp pred GEP (P, int 0, int 0, int 0), null -> icmp pred P, null
Chris Lattnerec12d052010-01-01 23:09:08 +00006611 if (RHSC->isNullValue() &&
6612 cast<GetElementPtrInst>(LHSI)->hasAllZeroIndices())
6613 return new ICmpInst(I.getPredicate(), LHSI->getOperand(0),
6614 Constant::getNullValue(LHSI->getOperand(0)->getType()));
Chris Lattner9fb25db2005-05-01 04:42:15 +00006615 break;
Chris Lattner6970b662005-04-23 15:31:55 +00006616 case Instruction::PHI:
Chris Lattner213cd612009-09-27 20:46:36 +00006617 // Only fold icmp into the PHI if the phi and icmp are in the same
Chris Lattner7d8ab4e2008-06-08 20:52:11 +00006618 // block. If in the same block, we're encouraging jump threading. If
6619 // not, we are just pessimizing the code by making an i1 phi.
6620 if (LHSI->getParent() == I.getParent())
Chris Lattner213cd612009-09-27 20:46:36 +00006621 if (Instruction *NV = FoldOpIntoPhi(I, true))
Chris Lattner7d8ab4e2008-06-08 20:52:11 +00006622 return NV;
Chris Lattner6970b662005-04-23 15:31:55 +00006623 break;
Chris Lattner4802d902007-04-06 18:57:34 +00006624 case Instruction::Select: {
Chris Lattner6970b662005-04-23 15:31:55 +00006625 // If either operand of the select is a constant, we can fold the
6626 // comparison into the select arms, which will cause one to be
6627 // constant folded and the select turned into a bitwise or.
6628 Value *Op1 = 0, *Op2 = 0;
Eli Friedman97b087c2009-12-18 08:22:35 +00006629 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1)))
6630 Op1 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
6631 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2)))
6632 Op2 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
6633
6634 // We only want to perform this transformation if it will not lead to
6635 // additional code. This is true if either both sides of the select
6636 // fold to a constant (in which case the icmp is replaced with a select
6637 // which will usually simplify) or this is the only user of the
6638 // select (in which case we are trading a select+icmp for a simpler
6639 // select+icmp).
6640 if ((Op1 && Op2) || (LHSI->hasOneUse() && (Op1 || Op2))) {
6641 if (!Op1)
Chris Lattner74381062009-08-30 07:44:24 +00006642 Op1 = Builder->CreateICmp(I.getPredicate(), LHSI->getOperand(1),
6643 RHSC, I.getName());
Eli Friedman97b087c2009-12-18 08:22:35 +00006644 if (!Op2)
6645 Op2 = Builder->CreateICmp(I.getPredicate(), LHSI->getOperand(2),
6646 RHSC, I.getName());
Gabor Greif051a9502008-04-06 20:25:17 +00006647 return SelectInst::Create(LHSI->getOperand(0), Op1, Op2);
Eli Friedman97b087c2009-12-18 08:22:35 +00006648 }
Chris Lattner6970b662005-04-23 15:31:55 +00006649 break;
6650 }
Victor Hernandez83d63912009-09-18 22:35:49 +00006651 case Instruction::Call:
6652 // If we have (malloc != null), and if the malloc has a single use, we
6653 // can assume it is successful and remove the malloc.
6654 if (isMalloc(LHSI) && LHSI->hasOneUse() &&
6655 isa<ConstantPointerNull>(RHSC)) {
Victor Hernandez68afa542009-10-21 19:11:40 +00006656 // Need to explicitly erase malloc call here, instead of adding it to
6657 // Worklist, because it won't get DCE'd from the Worklist since
6658 // isInstructionTriviallyDead() returns false for function calls.
6659 // It is OK to replace LHSI/MallocCall with Undef because the
6660 // instruction that uses it will be erased via Worklist.
6661 if (extractMallocCall(LHSI)) {
6662 LHSI->replaceAllUsesWith(UndefValue::get(LHSI->getType()));
6663 EraseInstFromFunction(*LHSI);
6664 return ReplaceInstUsesWith(I,
Victor Hernandez83d63912009-09-18 22:35:49 +00006665 ConstantInt::get(Type::getInt1Ty(*Context),
6666 !I.isTrueWhenEqual()));
Victor Hernandez68afa542009-10-21 19:11:40 +00006667 }
6668 if (CallInst* MallocCall = extractMallocCallFromBitCast(LHSI))
6669 if (MallocCall->hasOneUse()) {
6670 MallocCall->replaceAllUsesWith(
6671 UndefValue::get(MallocCall->getType()));
6672 EraseInstFromFunction(*MallocCall);
6673 Worklist.Add(LHSI); // The malloc's bitcast use.
6674 return ReplaceInstUsesWith(I,
6675 ConstantInt::get(Type::getInt1Ty(*Context),
6676 !I.isTrueWhenEqual()));
6677 }
Victor Hernandez83d63912009-09-18 22:35:49 +00006678 }
6679 break;
Chris Lattnerec12d052010-01-01 23:09:08 +00006680 case Instruction::IntToPtr:
6681 // icmp pred inttoptr(X), null -> icmp pred X, 0
6682 if (RHSC->isNullValue() && TD &&
6683 TD->getIntPtrType(RHSC->getContext()) ==
6684 LHSI->getOperand(0)->getType())
6685 return new ICmpInst(I.getPredicate(), LHSI->getOperand(0),
6686 Constant::getNullValue(LHSI->getOperand(0)->getType()));
6687 break;
Chris Lattner1f12e442010-01-02 08:12:04 +00006688
6689 case Instruction::Load:
Chris Lattnerdf3d63b2010-01-02 22:08:28 +00006690 // Try to optimize things like "A[i] > 4" to index computations.
Chris Lattner1f12e442010-01-02 08:12:04 +00006691 if (GetElementPtrInst *GEP =
Chris Lattner34e0c762010-01-02 08:20:51 +00006692 dyn_cast<GetElementPtrInst>(LHSI->getOperand(0))) {
Chris Lattner1f12e442010-01-02 08:12:04 +00006693 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(GEP->getOperand(0)))
6694 if (GV->isConstant() && GV->hasDefinitiveInitializer() &&
Chris Lattnera0085af2010-01-03 06:58:48 +00006695 !cast<LoadInst>(LHSI)->isVolatile())
Chris Lattner1f12e442010-01-02 08:12:04 +00006696 if (Instruction *Res = FoldCmpLoadFromIndexedGlobal(GEP, GV, I))
6697 return Res;
Chris Lattner34e0c762010-01-02 08:20:51 +00006698 }
Chris Lattner1f12e442010-01-02 08:12:04 +00006699 break;
Chris Lattner4802d902007-04-06 18:57:34 +00006700 }
Chris Lattner6970b662005-04-23 15:31:55 +00006701 }
6702
Reid Spencere4d87aa2006-12-23 06:05:41 +00006703 // If we can optimize a 'icmp GEP, P' or 'icmp P, GEP', do so now.
Dan Gohmand6aa02d2009-07-28 01:40:03 +00006704 if (GEPOperator *GEP = dyn_cast<GEPOperator>(Op0))
Reid Spencere4d87aa2006-12-23 06:05:41 +00006705 if (Instruction *NI = FoldGEPICmp(GEP, Op1, I.getPredicate(), I))
Chris Lattner574da9b2005-01-13 20:14:25 +00006706 return NI;
Dan Gohmand6aa02d2009-07-28 01:40:03 +00006707 if (GEPOperator *GEP = dyn_cast<GEPOperator>(Op1))
Reid Spencere4d87aa2006-12-23 06:05:41 +00006708 if (Instruction *NI = FoldGEPICmp(GEP, Op0,
6709 ICmpInst::getSwappedPredicate(I.getPredicate()), I))
Chris Lattner574da9b2005-01-13 20:14:25 +00006710 return NI;
6711
Reid Spencere4d87aa2006-12-23 06:05:41 +00006712 // Test to see if the operands of the icmp are casted versions of other
Chris Lattner57d86372007-01-06 01:45:59 +00006713 // values. If the ptr->ptr cast can be stripped off both arguments, we do so
6714 // now.
6715 if (BitCastInst *CI = dyn_cast<BitCastInst>(Op0)) {
6716 if (isa<PointerType>(Op0->getType()) &&
6717 (isa<Constant>(Op1) || isa<BitCastInst>(Op1))) {
Chris Lattnerde90b762003-11-03 04:25:02 +00006718 // We keep moving the cast from the left operand over to the right
6719 // operand, where it can often be eliminated completely.
Chris Lattner57d86372007-01-06 01:45:59 +00006720 Op0 = CI->getOperand(0);
Misha Brukmanfd939082005-04-21 23:48:37 +00006721
Chris Lattner57d86372007-01-06 01:45:59 +00006722 // If operand #1 is a bitcast instruction, it must also be a ptr->ptr cast
6723 // so eliminate it as well.
6724 if (BitCastInst *CI2 = dyn_cast<BitCastInst>(Op1))
6725 Op1 = CI2->getOperand(0);
Misha Brukmanfd939082005-04-21 23:48:37 +00006726
Chris Lattnerde90b762003-11-03 04:25:02 +00006727 // If Op1 is a constant, we can fold the cast into the constant.
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00006728 if (Op0->getType() != Op1->getType()) {
Chris Lattnerde90b762003-11-03 04:25:02 +00006729 if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00006730 Op1 = ConstantExpr::getBitCast(Op1C, Op0->getType());
Chris Lattnerde90b762003-11-03 04:25:02 +00006731 } else {
Reid Spencere4d87aa2006-12-23 06:05:41 +00006732 // Otherwise, cast the RHS right before the icmp
Chris Lattner08142f22009-08-30 19:47:22 +00006733 Op1 = Builder->CreateBitCast(Op1, Op0->getType());
Chris Lattnerde90b762003-11-03 04:25:02 +00006734 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00006735 }
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006736 return new ICmpInst(I.getPredicate(), Op0, Op1);
Chris Lattnerde90b762003-11-03 04:25:02 +00006737 }
Chris Lattner57d86372007-01-06 01:45:59 +00006738 }
6739
6740 if (isa<CastInst>(Op0)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00006741 // Handle the special case of: icmp (cast bool to X), <cst>
Chris Lattner68708052003-11-03 05:17:03 +00006742 // This comes up when you have code like
6743 // int X = A < B;
6744 // if (X) ...
6745 // For generality, we handle any zero-extension of any operand comparison
Chris Lattner484d3cf2005-04-24 06:59:08 +00006746 // with a constant or another cast from the same type.
Eli Friedman8e4b1972009-12-17 21:27:47 +00006747 if (isa<Constant>(Op1) || isa<CastInst>(Op1))
Reid Spencere4d87aa2006-12-23 06:05:41 +00006748 if (Instruction *R = visitICmpInstWithCastAndCast(I))
Chris Lattner484d3cf2005-04-24 06:59:08 +00006749 return R;
Chris Lattner68708052003-11-03 05:17:03 +00006750 }
Chris Lattner26ab9a92006-02-27 01:44:11 +00006751
Nick Lewycky4bf1e592008-07-11 07:20:53 +00006752 // See if it's the same type of instruction on the left and right.
6753 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
6754 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
Nick Lewycky5d52c452008-08-21 05:56:10 +00006755 if (Op0I->getOpcode() == Op1I->getOpcode() && Op0I->hasOneUse() &&
Nick Lewycky4333f492009-01-31 21:30:05 +00006756 Op1I->hasOneUse() && Op0I->getOperand(1) == Op1I->getOperand(1)) {
Nick Lewycky23c04302008-09-03 06:24:21 +00006757 switch (Op0I->getOpcode()) {
Nick Lewycky4bf1e592008-07-11 07:20:53 +00006758 default: break;
6759 case Instruction::Add:
6760 case Instruction::Sub:
6761 case Instruction::Xor:
Chris Lattnerf5db1fb2009-02-02 07:15:30 +00006762 if (I.isEquality()) // a+x icmp eq/ne b+x --> a icmp b
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006763 return new ICmpInst(I.getPredicate(), Op0I->getOperand(0),
Nick Lewycky4333f492009-01-31 21:30:05 +00006764 Op1I->getOperand(0));
Chris Lattnerf5db1fb2009-02-02 07:15:30 +00006765 // icmp u/s (a ^ signbit), (b ^ signbit) --> icmp s/u a, b
6766 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
6767 if (CI->getValue().isSignBit()) {
Nick Lewycky4a134af2009-10-25 05:20:17 +00006768 ICmpInst::Predicate Pred = I.isSigned()
Chris Lattnerf5db1fb2009-02-02 07:15:30 +00006769 ? I.getUnsignedPredicate()
6770 : I.getSignedPredicate();
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006771 return new ICmpInst(Pred, Op0I->getOperand(0),
Chris Lattnerf5db1fb2009-02-02 07:15:30 +00006772 Op1I->getOperand(0));
6773 }
6774
6775 if (CI->getValue().isMaxSignedValue()) {
Nick Lewycky4a134af2009-10-25 05:20:17 +00006776 ICmpInst::Predicate Pred = I.isSigned()
Chris Lattnerf5db1fb2009-02-02 07:15:30 +00006777 ? I.getUnsignedPredicate()
6778 : I.getSignedPredicate();
6779 Pred = I.getSwappedPredicate(Pred);
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006780 return new ICmpInst(Pred, Op0I->getOperand(0),
Chris Lattnerf5db1fb2009-02-02 07:15:30 +00006781 Op1I->getOperand(0));
Nick Lewycky4333f492009-01-31 21:30:05 +00006782 }
6783 }
Nick Lewycky4bf1e592008-07-11 07:20:53 +00006784 break;
6785 case Instruction::Mul:
Nick Lewycky4333f492009-01-31 21:30:05 +00006786 if (!I.isEquality())
6787 break;
6788
Nick Lewycky5d52c452008-08-21 05:56:10 +00006789 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
6790 // a * Cst icmp eq/ne b * Cst --> a & Mask icmp b & Mask
6791 // Mask = -1 >> count-trailing-zeros(Cst).
6792 if (!CI->isZero() && !CI->isOne()) {
6793 const APInt &AP = CI->getValue();
Owen Andersoneed707b2009-07-24 23:12:02 +00006794 ConstantInt *Mask = ConstantInt::get(*Context,
Nick Lewycky5d52c452008-08-21 05:56:10 +00006795 APInt::getLowBitsSet(AP.getBitWidth(),
6796 AP.getBitWidth() -
Nick Lewycky4bf1e592008-07-11 07:20:53 +00006797 AP.countTrailingZeros()));
Chris Lattner74381062009-08-30 07:44:24 +00006798 Value *And1 = Builder->CreateAnd(Op0I->getOperand(0), Mask);
6799 Value *And2 = Builder->CreateAnd(Op1I->getOperand(0), Mask);
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006800 return new ICmpInst(I.getPredicate(), And1, And2);
Nick Lewycky4bf1e592008-07-11 07:20:53 +00006801 }
6802 }
6803 break;
6804 }
6805 }
6806 }
6807 }
6808
Chris Lattner7d2cbd22008-05-09 05:19:28 +00006809 // ~x < ~y --> y < x
6810 { Value *A, *B;
Dan Gohman4ae51262009-08-12 16:23:25 +00006811 if (match(Op0, m_Not(m_Value(A))) &&
6812 match(Op1, m_Not(m_Value(B))))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006813 return new ICmpInst(I.getPredicate(), B, A);
Chris Lattner7d2cbd22008-05-09 05:19:28 +00006814 }
6815
Chris Lattner65b72ba2006-09-18 04:22:48 +00006816 if (I.isEquality()) {
Chris Lattner4f0e33d2007-01-05 03:04:57 +00006817 Value *A, *B, *C, *D;
Chris Lattner7d2cbd22008-05-09 05:19:28 +00006818
6819 // -x == -y --> x == y
Dan Gohman4ae51262009-08-12 16:23:25 +00006820 if (match(Op0, m_Neg(m_Value(A))) &&
6821 match(Op1, m_Neg(m_Value(B))))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006822 return new ICmpInst(I.getPredicate(), A, B);
Chris Lattner7d2cbd22008-05-09 05:19:28 +00006823
Dan Gohman4ae51262009-08-12 16:23:25 +00006824 if (match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
Chris Lattner4f0e33d2007-01-05 03:04:57 +00006825 if (A == Op1 || B == Op1) { // (A^B) == A -> B == 0
6826 Value *OtherVal = A == Op1 ? B : A;
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006827 return new ICmpInst(I.getPredicate(), OtherVal,
Owen Andersona7235ea2009-07-31 20:28:14 +00006828 Constant::getNullValue(A->getType()));
Chris Lattner4f0e33d2007-01-05 03:04:57 +00006829 }
6830
Dan Gohman4ae51262009-08-12 16:23:25 +00006831 if (match(Op1, m_Xor(m_Value(C), m_Value(D)))) {
Chris Lattner4f0e33d2007-01-05 03:04:57 +00006832 // A^c1 == C^c2 --> A == C^(c1^c2)
Chris Lattnercb504b92008-11-16 05:38:51 +00006833 ConstantInt *C1, *C2;
Dan Gohman4ae51262009-08-12 16:23:25 +00006834 if (match(B, m_ConstantInt(C1)) &&
6835 match(D, m_ConstantInt(C2)) && Op1->hasOneUse()) {
Owen Andersond672ecb2009-07-03 00:17:18 +00006836 Constant *NC =
Owen Andersoneed707b2009-07-24 23:12:02 +00006837 ConstantInt::get(*Context, C1->getValue() ^ C2->getValue());
Chris Lattner74381062009-08-30 07:44:24 +00006838 Value *Xor = Builder->CreateXor(C, NC, "tmp");
6839 return new ICmpInst(I.getPredicate(), A, Xor);
Chris Lattnercb504b92008-11-16 05:38:51 +00006840 }
Chris Lattner4f0e33d2007-01-05 03:04:57 +00006841
6842 // A^B == A^D -> B == D
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006843 if (A == C) return new ICmpInst(I.getPredicate(), B, D);
6844 if (A == D) return new ICmpInst(I.getPredicate(), B, C);
6845 if (B == C) return new ICmpInst(I.getPredicate(), A, D);
6846 if (B == D) return new ICmpInst(I.getPredicate(), A, C);
Chris Lattner4f0e33d2007-01-05 03:04:57 +00006847 }
6848 }
6849
Dan Gohman4ae51262009-08-12 16:23:25 +00006850 if (match(Op1, m_Xor(m_Value(A), m_Value(B))) &&
Chris Lattner4f0e33d2007-01-05 03:04:57 +00006851 (A == Op0 || B == Op0)) {
Chris Lattner26ab9a92006-02-27 01:44:11 +00006852 // A == (A^B) -> B == 0
6853 Value *OtherVal = A == Op0 ? B : A;
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006854 return new ICmpInst(I.getPredicate(), OtherVal,
Owen Andersona7235ea2009-07-31 20:28:14 +00006855 Constant::getNullValue(A->getType()));
Chris Lattner4f0e33d2007-01-05 03:04:57 +00006856 }
Chris Lattnercb504b92008-11-16 05:38:51 +00006857
6858 // (A-B) == A -> B == 0
Dan Gohman4ae51262009-08-12 16:23:25 +00006859 if (match(Op0, m_Sub(m_Specific(Op1), m_Value(B))))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006860 return new ICmpInst(I.getPredicate(), B,
Owen Andersona7235ea2009-07-31 20:28:14 +00006861 Constant::getNullValue(B->getType()));
Chris Lattnercb504b92008-11-16 05:38:51 +00006862
6863 // A == (A-B) -> B == 0
Dan Gohman4ae51262009-08-12 16:23:25 +00006864 if (match(Op1, m_Sub(m_Specific(Op0), m_Value(B))))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00006865 return new ICmpInst(I.getPredicate(), B,
Owen Andersona7235ea2009-07-31 20:28:14 +00006866 Constant::getNullValue(B->getType()));
Chris Lattner9c2328e2006-11-14 06:06:06 +00006867
Chris Lattner9c2328e2006-11-14 06:06:06 +00006868 // (X&Z) == (Y&Z) -> (X^Y) & Z == 0
6869 if (Op0->hasOneUse() && Op1->hasOneUse() &&
Dan Gohman4ae51262009-08-12 16:23:25 +00006870 match(Op0, m_And(m_Value(A), m_Value(B))) &&
6871 match(Op1, m_And(m_Value(C), m_Value(D)))) {
Chris Lattner9c2328e2006-11-14 06:06:06 +00006872 Value *X = 0, *Y = 0, *Z = 0;
6873
6874 if (A == C) {
6875 X = B; Y = D; Z = A;
6876 } else if (A == D) {
6877 X = B; Y = C; Z = A;
6878 } else if (B == C) {
6879 X = A; Y = D; Z = B;
6880 } else if (B == D) {
6881 X = A; Y = C; Z = B;
6882 }
6883
6884 if (X) { // Build (X^Y) & Z
Chris Lattner74381062009-08-30 07:44:24 +00006885 Op1 = Builder->CreateXor(X, Y, "tmp");
6886 Op1 = Builder->CreateAnd(Op1, Z, "tmp");
Chris Lattner9c2328e2006-11-14 06:06:06 +00006887 I.setOperand(0, Op1);
Owen Andersona7235ea2009-07-31 20:28:14 +00006888 I.setOperand(1, Constant::getNullValue(Op1->getType()));
Chris Lattner9c2328e2006-11-14 06:06:06 +00006889 return &I;
6890 }
6891 }
Chris Lattner26ab9a92006-02-27 01:44:11 +00006892 }
Chris Lattner2799baf2009-12-21 03:19:28 +00006893
6894 {
6895 Value *X; ConstantInt *Cst;
Chris Lattner3bf68152009-12-21 04:04:05 +00006896 // icmp X+Cst, X
Chris Lattner2799baf2009-12-21 03:19:28 +00006897 if (match(Op0, m_Add(m_Value(X), m_ConstantInt(Cst))) && Op1 == X)
Chris Lattner3bf68152009-12-21 04:04:05 +00006898 return FoldICmpAddOpCst(I, X, Cst, I.getPredicate(), Op0);
6899
Chris Lattner2799baf2009-12-21 03:19:28 +00006900 // icmp X, X+Cst
6901 if (match(Op1, m_Add(m_Value(X), m_ConstantInt(Cst))) && Op0 == X)
Chris Lattner3bf68152009-12-21 04:04:05 +00006902 return FoldICmpAddOpCst(I, X, Cst, I.getSwappedPredicate(), Op1);
Chris Lattner2799baf2009-12-21 03:19:28 +00006903 }
Chris Lattner7e708292002-06-25 16:13:24 +00006904 return Changed ? &I : 0;
Chris Lattner3f5b8772002-05-06 16:14:14 +00006905}
6906
Chris Lattner2799baf2009-12-21 03:19:28 +00006907/// FoldICmpAddOpCst - Fold "icmp pred (X+CI), X".
6908Instruction *InstCombiner::FoldICmpAddOpCst(ICmpInst &ICI,
6909 Value *X, ConstantInt *CI,
Chris Lattner3bf68152009-12-21 04:04:05 +00006910 ICmpInst::Predicate Pred,
6911 Value *TheAdd) {
Chris Lattner2799baf2009-12-21 03:19:28 +00006912 // If we have X+0, exit early (simplifying logic below) and let it get folded
6913 // elsewhere. icmp X+0, X -> icmp X, X
6914 if (CI->isZero()) {
6915 bool isTrue = ICmpInst::isTrueWhenEqual(Pred);
6916 return ReplaceInstUsesWith(ICI, ConstantInt::get(ICI.getType(), isTrue));
6917 }
6918
6919 // (X+4) == X -> false.
6920 if (Pred == ICmpInst::ICMP_EQ)
6921 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse(X->getContext()));
6922
6923 // (X+4) != X -> true.
6924 if (Pred == ICmpInst::ICMP_NE)
6925 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue(X->getContext()));
Chris Lattner3bf68152009-12-21 04:04:05 +00006926
6927 // If this is an instruction (as opposed to constantexpr) get NUW/NSW info.
6928 bool isNUW = false, isNSW = false;
6929 if (BinaryOperator *Add = dyn_cast<BinaryOperator>(TheAdd)) {
6930 isNUW = Add->hasNoUnsignedWrap();
6931 isNSW = Add->hasNoSignedWrap();
6932 }
Chris Lattner2799baf2009-12-21 03:19:28 +00006933
6934 // From this point on, we know that (X+C <= X) --> (X+C < X) because C != 0,
6935 // so the values can never be equal. Similiarly for all other "or equals"
6936 // operators.
6937
6938 // (X+1) <u X --> X >u (MAXUINT-1) --> X != 255
6939 // (X+2) <u X --> X >u (MAXUINT-2) --> X > 253
6940 // (X+MAXUINT) <u X --> X >u (MAXUINT-MAXUINT) --> X != 0
6941 if (Pred == ICmpInst::ICMP_ULT || Pred == ICmpInst::ICMP_ULE) {
Chris Lattner3bf68152009-12-21 04:04:05 +00006942 // If this is an NUW add, then this is always false.
6943 if (isNUW)
6944 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse(X->getContext()));
6945
Chris Lattner2799baf2009-12-21 03:19:28 +00006946 Value *R = ConstantExpr::getSub(ConstantInt::get(CI->getType(), -1ULL), CI);
6947 return new ICmpInst(ICmpInst::ICMP_UGT, X, R);
6948 }
6949
6950 // (X+1) >u X --> X <u (0-1) --> X != 255
6951 // (X+2) >u X --> X <u (0-2) --> X <u 254
6952 // (X+MAXUINT) >u X --> X <u (0-MAXUINT) --> X <u 1 --> X == 0
Chris Lattner3bf68152009-12-21 04:04:05 +00006953 if (Pred == ICmpInst::ICMP_UGT || Pred == ICmpInst::ICMP_UGE) {
6954 // If this is an NUW add, then this is always true.
6955 if (isNUW)
6956 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue(X->getContext()));
Chris Lattner2799baf2009-12-21 03:19:28 +00006957 return new ICmpInst(ICmpInst::ICMP_ULT, X, ConstantExpr::getNeg(CI));
Chris Lattner3bf68152009-12-21 04:04:05 +00006958 }
Chris Lattner2799baf2009-12-21 03:19:28 +00006959
6960 unsigned BitWidth = CI->getType()->getPrimitiveSizeInBits();
6961 ConstantInt *SMax = ConstantInt::get(X->getContext(),
6962 APInt::getSignedMaxValue(BitWidth));
6963
6964 // (X+ 1) <s X --> X >s (MAXSINT-1) --> X == 127
6965 // (X+ 2) <s X --> X >s (MAXSINT-2) --> X >s 125
6966 // (X+MAXSINT) <s X --> X >s (MAXSINT-MAXSINT) --> X >s 0
6967 // (X+MINSINT) <s X --> X >s (MAXSINT-MINSINT) --> X >s -1
6968 // (X+ -2) <s X --> X >s (MAXSINT- -2) --> X >s 126
6969 // (X+ -1) <s X --> X >s (MAXSINT- -1) --> X != 127
Chris Lattner3bf68152009-12-21 04:04:05 +00006970 if (Pred == ICmpInst::ICMP_SLT || Pred == ICmpInst::ICMP_SLE) {
6971 // If this is an NSW add, then we have two cases: if the constant is
6972 // positive, then this is always false, if negative, this is always true.
6973 if (isNSW) {
6974 bool isTrue = CI->getValue().isNegative();
6975 return ReplaceInstUsesWith(ICI, ConstantInt::get(ICI.getType(), isTrue));
6976 }
6977
Chris Lattner2799baf2009-12-21 03:19:28 +00006978 return new ICmpInst(ICmpInst::ICMP_SGT, X, ConstantExpr::getSub(SMax, CI));
Chris Lattner3bf68152009-12-21 04:04:05 +00006979 }
Chris Lattner2799baf2009-12-21 03:19:28 +00006980
6981 // (X+ 1) >s X --> X <s (MAXSINT-(1-1)) --> X != 127
6982 // (X+ 2) >s X --> X <s (MAXSINT-(2-1)) --> X <s 126
6983 // (X+MAXSINT) >s X --> X <s (MAXSINT-(MAXSINT-1)) --> X <s 1
6984 // (X+MINSINT) >s X --> X <s (MAXSINT-(MINSINT-1)) --> X <s -2
6985 // (X+ -2) >s X --> X <s (MAXSINT-(-2-1)) --> X <s -126
6986 // (X+ -1) >s X --> X <s (MAXSINT-(-1-1)) --> X == -128
Chris Lattner3bf68152009-12-21 04:04:05 +00006987
6988 // If this is an NSW add, then we have two cases: if the constant is
6989 // positive, then this is always true, if negative, this is always false.
6990 if (isNSW) {
6991 bool isTrue = !CI->getValue().isNegative();
6992 return ReplaceInstUsesWith(ICI, ConstantInt::get(ICI.getType(), isTrue));
6993 }
6994
Chris Lattner2799baf2009-12-21 03:19:28 +00006995 assert(Pred == ICmpInst::ICMP_SGT || Pred == ICmpInst::ICMP_SGE);
6996 Constant *C = ConstantInt::get(X->getContext(), CI->getValue()-1);
6997 return new ICmpInst(ICmpInst::ICMP_SLT, X, ConstantExpr::getSub(SMax, C));
6998}
Chris Lattner562ef782007-06-20 23:46:26 +00006999
7000/// FoldICmpDivCst - Fold "icmp pred, ([su]div X, DivRHS), CmpRHS" where DivRHS
7001/// and CmpRHS are both known to be integer constants.
7002Instruction *InstCombiner::FoldICmpDivCst(ICmpInst &ICI, BinaryOperator *DivI,
7003 ConstantInt *DivRHS) {
7004 ConstantInt *CmpRHS = cast<ConstantInt>(ICI.getOperand(1));
7005 const APInt &CmpRHSV = CmpRHS->getValue();
7006
7007 // FIXME: If the operand types don't match the type of the divide
7008 // then don't attempt this transform. The code below doesn't have the
7009 // logic to deal with a signed divide and an unsigned compare (and
7010 // vice versa). This is because (x /s C1) <s C2 produces different
7011 // results than (x /s C1) <u C2 or (x /u C1) <s C2 or even
7012 // (x /u C1) <u C2. Simply casting the operands and result won't
7013 // work. :( The if statement below tests that condition and bails
7014 // if it finds it.
7015 bool DivIsSigned = DivI->getOpcode() == Instruction::SDiv;
Nick Lewycky4a134af2009-10-25 05:20:17 +00007016 if (!ICI.isEquality() && DivIsSigned != ICI.isSigned())
Chris Lattner562ef782007-06-20 23:46:26 +00007017 return 0;
7018 if (DivRHS->isZero())
Chris Lattner1dbfd482007-06-21 18:11:19 +00007019 return 0; // The ProdOV computation fails on divide by zero.
Chris Lattnera6321b42008-10-11 22:55:00 +00007020 if (DivIsSigned && DivRHS->isAllOnesValue())
7021 return 0; // The overflow computation also screws up here
7022 if (DivRHS->isOne())
7023 return 0; // Not worth bothering, and eliminates some funny cases
7024 // with INT_MIN.
Chris Lattner562ef782007-06-20 23:46:26 +00007025
7026 // Compute Prod = CI * DivRHS. We are essentially solving an equation
7027 // of form X/C1=C2. We solve for X by multiplying C1 (DivRHS) and
7028 // C2 (CI). By solving for X we can turn this into a range check
7029 // instead of computing a divide.
Owen Andersonbaf3c402009-07-29 18:55:55 +00007030 Constant *Prod = ConstantExpr::getMul(CmpRHS, DivRHS);
Chris Lattner562ef782007-06-20 23:46:26 +00007031
7032 // Determine if the product overflows by seeing if the product is
7033 // not equal to the divide. Make sure we do the same kind of divide
7034 // as in the LHS instruction that we're folding.
Owen Andersonbaf3c402009-07-29 18:55:55 +00007035 bool ProdOV = (DivIsSigned ? ConstantExpr::getSDiv(Prod, DivRHS) :
7036 ConstantExpr::getUDiv(Prod, DivRHS)) != CmpRHS;
Chris Lattner562ef782007-06-20 23:46:26 +00007037
7038 // Get the ICmp opcode
Chris Lattner1dbfd482007-06-21 18:11:19 +00007039 ICmpInst::Predicate Pred = ICI.getPredicate();
Chris Lattner562ef782007-06-20 23:46:26 +00007040
Chris Lattner1dbfd482007-06-21 18:11:19 +00007041 // Figure out the interval that is being checked. For example, a comparison
7042 // like "X /u 5 == 0" is really checking that X is in the interval [0, 5).
7043 // Compute this interval based on the constants involved and the signedness of
7044 // the compare/divide. This computes a half-open interval, keeping track of
7045 // whether either value in the interval overflows. After analysis each
7046 // overflow variable is set to 0 if it's corresponding bound variable is valid
7047 // -1 if overflowed off the bottom end, or +1 if overflowed off the top end.
7048 int LoOverflow = 0, HiOverflow = 0;
Dan Gohman6de29f82009-06-15 22:12:54 +00007049 Constant *LoBound = 0, *HiBound = 0;
Chris Lattner1dbfd482007-06-21 18:11:19 +00007050
Chris Lattner562ef782007-06-20 23:46:26 +00007051 if (!DivIsSigned) { // udiv
Chris Lattner1dbfd482007-06-21 18:11:19 +00007052 // e.g. X/5 op 3 --> [15, 20)
Chris Lattner562ef782007-06-20 23:46:26 +00007053 LoBound = Prod;
Chris Lattner1dbfd482007-06-21 18:11:19 +00007054 HiOverflow = LoOverflow = ProdOV;
7055 if (!HiOverflow)
Owen Andersond672ecb2009-07-03 00:17:18 +00007056 HiOverflow = AddWithOverflow(HiBound, LoBound, DivRHS, Context, false);
Dan Gohman76491272008-02-13 22:09:18 +00007057 } else if (DivRHS->getValue().isStrictlyPositive()) { // Divisor is > 0.
Chris Lattner562ef782007-06-20 23:46:26 +00007058 if (CmpRHSV == 0) { // (X / pos) op 0
Chris Lattner1dbfd482007-06-21 18:11:19 +00007059 // Can't overflow. e.g. X/2 op 0 --> [-1, 2)
Dan Gohman186a6362009-08-12 16:04:34 +00007060 LoBound = cast<ConstantInt>(ConstantExpr::getNeg(SubOne(DivRHS)));
Chris Lattner562ef782007-06-20 23:46:26 +00007061 HiBound = DivRHS;
Dan Gohman76491272008-02-13 22:09:18 +00007062 } else if (CmpRHSV.isStrictlyPositive()) { // (X / pos) op pos
Chris Lattner1dbfd482007-06-21 18:11:19 +00007063 LoBound = Prod; // e.g. X/5 op 3 --> [15, 20)
7064 HiOverflow = LoOverflow = ProdOV;
7065 if (!HiOverflow)
Owen Andersond672ecb2009-07-03 00:17:18 +00007066 HiOverflow = AddWithOverflow(HiBound, Prod, DivRHS, Context, true);
Chris Lattner562ef782007-06-20 23:46:26 +00007067 } else { // (X / pos) op neg
Chris Lattner1dbfd482007-06-21 18:11:19 +00007068 // e.g. X/5 op -3 --> [-15-4, -15+1) --> [-19, -14)
Dan Gohman186a6362009-08-12 16:04:34 +00007069 HiBound = AddOne(Prod);
Chris Lattnera6321b42008-10-11 22:55:00 +00007070 LoOverflow = HiOverflow = ProdOV ? -1 : 0;
7071 if (!LoOverflow) {
Owen Andersond672ecb2009-07-03 00:17:18 +00007072 ConstantInt* DivNeg =
Owen Andersonbaf3c402009-07-29 18:55:55 +00007073 cast<ConstantInt>(ConstantExpr::getNeg(DivRHS));
Owen Andersond672ecb2009-07-03 00:17:18 +00007074 LoOverflow = AddWithOverflow(LoBound, HiBound, DivNeg, Context,
Chris Lattnera6321b42008-10-11 22:55:00 +00007075 true) ? -1 : 0;
7076 }
Chris Lattner562ef782007-06-20 23:46:26 +00007077 }
Dan Gohman76491272008-02-13 22:09:18 +00007078 } else if (DivRHS->getValue().isNegative()) { // Divisor is < 0.
Chris Lattner562ef782007-06-20 23:46:26 +00007079 if (CmpRHSV == 0) { // (X / neg) op 0
Chris Lattner1dbfd482007-06-21 18:11:19 +00007080 // e.g. X/-5 op 0 --> [-4, 5)
Dan Gohman186a6362009-08-12 16:04:34 +00007081 LoBound = AddOne(DivRHS);
Owen Andersonbaf3c402009-07-29 18:55:55 +00007082 HiBound = cast<ConstantInt>(ConstantExpr::getNeg(DivRHS));
Chris Lattner1dbfd482007-06-21 18:11:19 +00007083 if (HiBound == DivRHS) { // -INTMIN = INTMIN
7084 HiOverflow = 1; // [INTMIN+1, overflow)
7085 HiBound = 0; // e.g. X/INTMIN = 0 --> X > INTMIN
7086 }
Dan Gohman76491272008-02-13 22:09:18 +00007087 } else if (CmpRHSV.isStrictlyPositive()) { // (X / neg) op pos
Chris Lattner1dbfd482007-06-21 18:11:19 +00007088 // e.g. X/-5 op 3 --> [-19, -14)
Dan Gohman186a6362009-08-12 16:04:34 +00007089 HiBound = AddOne(Prod);
Chris Lattner1dbfd482007-06-21 18:11:19 +00007090 HiOverflow = LoOverflow = ProdOV ? -1 : 0;
Chris Lattner562ef782007-06-20 23:46:26 +00007091 if (!LoOverflow)
Owen Andersond672ecb2009-07-03 00:17:18 +00007092 LoOverflow = AddWithOverflow(LoBound, HiBound,
7093 DivRHS, Context, true) ? -1 : 0;
Chris Lattner562ef782007-06-20 23:46:26 +00007094 } else { // (X / neg) op neg
Chris Lattnera6321b42008-10-11 22:55:00 +00007095 LoBound = Prod; // e.g. X/-5 op -3 --> [15, 20)
7096 LoOverflow = HiOverflow = ProdOV;
Dan Gohman7f85fbd2008-09-11 00:25:00 +00007097 if (!HiOverflow)
Owen Andersond672ecb2009-07-03 00:17:18 +00007098 HiOverflow = SubWithOverflow(HiBound, Prod, DivRHS, Context, true);
Chris Lattner562ef782007-06-20 23:46:26 +00007099 }
7100
Chris Lattner1dbfd482007-06-21 18:11:19 +00007101 // Dividing by a negative swaps the condition. LT <-> GT
7102 Pred = ICmpInst::getSwappedPredicate(Pred);
Chris Lattner562ef782007-06-20 23:46:26 +00007103 }
7104
7105 Value *X = DivI->getOperand(0);
Chris Lattner1dbfd482007-06-21 18:11:19 +00007106 switch (Pred) {
Torok Edwinc23197a2009-07-14 16:55:14 +00007107 default: llvm_unreachable("Unhandled icmp opcode!");
Chris Lattner562ef782007-06-20 23:46:26 +00007108 case ICmpInst::ICMP_EQ:
7109 if (LoOverflow && HiOverflow)
Owen Anderson5defacc2009-07-31 17:39:07 +00007110 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse(*Context));
Chris Lattner562ef782007-06-20 23:46:26 +00007111 else if (HiOverflow)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007112 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE :
Chris Lattner562ef782007-06-20 23:46:26 +00007113 ICmpInst::ICMP_UGE, X, LoBound);
7114 else if (LoOverflow)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007115 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT :
Chris Lattner562ef782007-06-20 23:46:26 +00007116 ICmpInst::ICMP_ULT, X, HiBound);
7117 else
Chris Lattner1dbfd482007-06-21 18:11:19 +00007118 return InsertRangeTest(X, LoBound, HiBound, DivIsSigned, true, ICI);
Chris Lattner562ef782007-06-20 23:46:26 +00007119 case ICmpInst::ICMP_NE:
7120 if (LoOverflow && HiOverflow)
Owen Anderson5defacc2009-07-31 17:39:07 +00007121 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue(*Context));
Chris Lattner562ef782007-06-20 23:46:26 +00007122 else if (HiOverflow)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007123 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT :
Chris Lattner562ef782007-06-20 23:46:26 +00007124 ICmpInst::ICMP_ULT, X, LoBound);
7125 else if (LoOverflow)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007126 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE :
Chris Lattner562ef782007-06-20 23:46:26 +00007127 ICmpInst::ICMP_UGE, X, HiBound);
7128 else
Chris Lattner1dbfd482007-06-21 18:11:19 +00007129 return InsertRangeTest(X, LoBound, HiBound, DivIsSigned, false, ICI);
Chris Lattner562ef782007-06-20 23:46:26 +00007130 case ICmpInst::ICMP_ULT:
7131 case ICmpInst::ICMP_SLT:
Chris Lattner1dbfd482007-06-21 18:11:19 +00007132 if (LoOverflow == +1) // Low bound is greater than input range.
Owen Anderson5defacc2009-07-31 17:39:07 +00007133 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue(*Context));
Chris Lattner1dbfd482007-06-21 18:11:19 +00007134 if (LoOverflow == -1) // Low bound is less than input range.
Owen Anderson5defacc2009-07-31 17:39:07 +00007135 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse(*Context));
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007136 return new ICmpInst(Pred, X, LoBound);
Chris Lattner562ef782007-06-20 23:46:26 +00007137 case ICmpInst::ICMP_UGT:
7138 case ICmpInst::ICMP_SGT:
Chris Lattner1dbfd482007-06-21 18:11:19 +00007139 if (HiOverflow == +1) // High bound greater than input range.
Owen Anderson5defacc2009-07-31 17:39:07 +00007140 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse(*Context));
Chris Lattner1dbfd482007-06-21 18:11:19 +00007141 else if (HiOverflow == -1) // High bound less than input range.
Owen Anderson5defacc2009-07-31 17:39:07 +00007142 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue(*Context));
Chris Lattner1dbfd482007-06-21 18:11:19 +00007143 if (Pred == ICmpInst::ICMP_UGT)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007144 return new ICmpInst(ICmpInst::ICMP_UGE, X, HiBound);
Chris Lattner562ef782007-06-20 23:46:26 +00007145 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007146 return new ICmpInst(ICmpInst::ICMP_SGE, X, HiBound);
Chris Lattner562ef782007-06-20 23:46:26 +00007147 }
7148}
7149
7150
Chris Lattner01deb9d2007-04-03 17:43:25 +00007151/// visitICmpInstWithInstAndIntCst - Handle "icmp (instr, intcst)".
7152///
7153Instruction *InstCombiner::visitICmpInstWithInstAndIntCst(ICmpInst &ICI,
7154 Instruction *LHSI,
7155 ConstantInt *RHS) {
7156 const APInt &RHSV = RHS->getValue();
7157
7158 switch (LHSI->getOpcode()) {
Chris Lattnera80d6682009-01-09 07:47:06 +00007159 case Instruction::Trunc:
7160 if (ICI.isEquality() && LHSI->hasOneUse()) {
7161 // Simplify icmp eq (trunc x to i8), 42 -> icmp eq x, 42|highbits if all
7162 // of the high bits truncated out of x are known.
7163 unsigned DstBits = LHSI->getType()->getPrimitiveSizeInBits(),
7164 SrcBits = LHSI->getOperand(0)->getType()->getPrimitiveSizeInBits();
7165 APInt Mask(APInt::getHighBitsSet(SrcBits, SrcBits-DstBits));
7166 APInt KnownZero(SrcBits, 0), KnownOne(SrcBits, 0);
7167 ComputeMaskedBits(LHSI->getOperand(0), Mask, KnownZero, KnownOne);
7168
7169 // If all the high bits are known, we can do this xform.
7170 if ((KnownZero|KnownOne).countLeadingOnes() >= SrcBits-DstBits) {
7171 // Pull in the high bits from known-ones set.
7172 APInt NewRHS(RHS->getValue());
7173 NewRHS.zext(SrcBits);
7174 NewRHS |= KnownOne;
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007175 return new ICmpInst(ICI.getPredicate(), LHSI->getOperand(0),
Owen Andersoneed707b2009-07-24 23:12:02 +00007176 ConstantInt::get(*Context, NewRHS));
Chris Lattnera80d6682009-01-09 07:47:06 +00007177 }
7178 }
7179 break;
7180
Duncan Sands0091bf22007-04-04 06:42:45 +00007181 case Instruction::Xor: // (icmp pred (xor X, XorCST), CI)
Chris Lattner01deb9d2007-04-03 17:43:25 +00007182 if (ConstantInt *XorCST = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
7183 // If this is a comparison that tests the signbit (X < 0) or (x > -1),
7184 // fold the xor.
Anton Korobeynikov07e6e562008-02-20 11:26:25 +00007185 if ((ICI.getPredicate() == ICmpInst::ICMP_SLT && RHSV == 0) ||
7186 (ICI.getPredicate() == ICmpInst::ICMP_SGT && RHSV.isAllOnesValue())) {
Chris Lattner01deb9d2007-04-03 17:43:25 +00007187 Value *CompareVal = LHSI->getOperand(0);
7188
7189 // If the sign bit of the XorCST is not set, there is no change to
7190 // the operation, just stop using the Xor.
7191 if (!XorCST->getValue().isNegative()) {
7192 ICI.setOperand(0, CompareVal);
Chris Lattner7a1e9242009-08-30 06:13:40 +00007193 Worklist.Add(LHSI);
Chris Lattner01deb9d2007-04-03 17:43:25 +00007194 return &ICI;
7195 }
7196
7197 // Was the old condition true if the operand is positive?
7198 bool isTrueIfPositive = ICI.getPredicate() == ICmpInst::ICMP_SGT;
7199
7200 // If so, the new one isn't.
7201 isTrueIfPositive ^= true;
7202
7203 if (isTrueIfPositive)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007204 return new ICmpInst(ICmpInst::ICMP_SGT, CompareVal,
Dan Gohman186a6362009-08-12 16:04:34 +00007205 SubOne(RHS));
Chris Lattner01deb9d2007-04-03 17:43:25 +00007206 else
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007207 return new ICmpInst(ICmpInst::ICMP_SLT, CompareVal,
Dan Gohman186a6362009-08-12 16:04:34 +00007208 AddOne(RHS));
Chris Lattner01deb9d2007-04-03 17:43:25 +00007209 }
Nick Lewycky4333f492009-01-31 21:30:05 +00007210
7211 if (LHSI->hasOneUse()) {
7212 // (icmp u/s (xor A SignBit), C) -> (icmp s/u A, (xor C SignBit))
7213 if (!ICI.isEquality() && XorCST->getValue().isSignBit()) {
7214 const APInt &SignBit = XorCST->getValue();
Nick Lewycky4a134af2009-10-25 05:20:17 +00007215 ICmpInst::Predicate Pred = ICI.isSigned()
Nick Lewycky4333f492009-01-31 21:30:05 +00007216 ? ICI.getUnsignedPredicate()
7217 : ICI.getSignedPredicate();
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007218 return new ICmpInst(Pred, LHSI->getOperand(0),
Owen Andersoneed707b2009-07-24 23:12:02 +00007219 ConstantInt::get(*Context, RHSV ^ SignBit));
Nick Lewycky4333f492009-01-31 21:30:05 +00007220 }
7221
7222 // (icmp u/s (xor A ~SignBit), C) -> (icmp s/u (xor C ~SignBit), A)
Chris Lattnerf5db1fb2009-02-02 07:15:30 +00007223 if (!ICI.isEquality() && XorCST->getValue().isMaxSignedValue()) {
Nick Lewycky4333f492009-01-31 21:30:05 +00007224 const APInt &NotSignBit = XorCST->getValue();
Nick Lewycky4a134af2009-10-25 05:20:17 +00007225 ICmpInst::Predicate Pred = ICI.isSigned()
Nick Lewycky4333f492009-01-31 21:30:05 +00007226 ? ICI.getUnsignedPredicate()
7227 : ICI.getSignedPredicate();
7228 Pred = ICI.getSwappedPredicate(Pred);
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007229 return new ICmpInst(Pred, LHSI->getOperand(0),
Owen Andersoneed707b2009-07-24 23:12:02 +00007230 ConstantInt::get(*Context, RHSV ^ NotSignBit));
Nick Lewycky4333f492009-01-31 21:30:05 +00007231 }
7232 }
Chris Lattner01deb9d2007-04-03 17:43:25 +00007233 }
7234 break;
7235 case Instruction::And: // (icmp pred (and X, AndCST), RHS)
7236 if (LHSI->hasOneUse() && isa<ConstantInt>(LHSI->getOperand(1)) &&
7237 LHSI->getOperand(0)->hasOneUse()) {
7238 ConstantInt *AndCST = cast<ConstantInt>(LHSI->getOperand(1));
7239
7240 // If the LHS is an AND of a truncating cast, we can widen the
7241 // and/compare to be the input width without changing the value
7242 // produced, eliminating a cast.
7243 if (TruncInst *Cast = dyn_cast<TruncInst>(LHSI->getOperand(0))) {
7244 // We can do this transformation if either the AND constant does not
7245 // have its sign bit set or if it is an equality comparison.
7246 // Extending a relational comparison when we're checking the sign
7247 // bit would not work.
7248 if (Cast->hasOneUse() &&
Anton Korobeynikov4aefd6b2008-02-20 12:07:57 +00007249 (ICI.isEquality() ||
7250 (AndCST->getValue().isNonNegative() && RHSV.isNonNegative()))) {
Chris Lattner01deb9d2007-04-03 17:43:25 +00007251 uint32_t BitWidth =
7252 cast<IntegerType>(Cast->getOperand(0)->getType())->getBitWidth();
7253 APInt NewCST = AndCST->getValue();
7254 NewCST.zext(BitWidth);
7255 APInt NewCI = RHSV;
7256 NewCI.zext(BitWidth);
Chris Lattner74381062009-08-30 07:44:24 +00007257 Value *NewAnd =
7258 Builder->CreateAnd(Cast->getOperand(0),
Owen Andersoneed707b2009-07-24 23:12:02 +00007259 ConstantInt::get(*Context, NewCST), LHSI->getName());
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007260 return new ICmpInst(ICI.getPredicate(), NewAnd,
Owen Andersoneed707b2009-07-24 23:12:02 +00007261 ConstantInt::get(*Context, NewCI));
Chris Lattner01deb9d2007-04-03 17:43:25 +00007262 }
7263 }
7264
7265 // If this is: (X >> C1) & C2 != C3 (where any shift and any compare
7266 // could exist), turn it into (X & (C2 << C1)) != (C3 << C1). This
7267 // happens a LOT in code produced by the C front-end, for bitfield
7268 // access.
7269 BinaryOperator *Shift = dyn_cast<BinaryOperator>(LHSI->getOperand(0));
7270 if (Shift && !Shift->isShift())
7271 Shift = 0;
7272
7273 ConstantInt *ShAmt;
7274 ShAmt = Shift ? dyn_cast<ConstantInt>(Shift->getOperand(1)) : 0;
7275 const Type *Ty = Shift ? Shift->getType() : 0; // Type of the shift.
7276 const Type *AndTy = AndCST->getType(); // Type of the and.
7277
7278 // We can fold this as long as we can't shift unknown bits
7279 // into the mask. This can only happen with signed shift
7280 // rights, as they sign-extend.
7281 if (ShAmt) {
7282 bool CanFold = Shift->isLogicalShift();
7283 if (!CanFold) {
7284 // To test for the bad case of the signed shr, see if any
7285 // of the bits shifted in could be tested after the mask.
7286 uint32_t TyBits = Ty->getPrimitiveSizeInBits();
7287 int ShAmtVal = TyBits - ShAmt->getLimitedValue(TyBits);
7288
7289 uint32_t BitWidth = AndTy->getPrimitiveSizeInBits();
7290 if ((APInt::getHighBitsSet(BitWidth, BitWidth-ShAmtVal) &
7291 AndCST->getValue()) == 0)
7292 CanFold = true;
7293 }
7294
7295 if (CanFold) {
7296 Constant *NewCst;
7297 if (Shift->getOpcode() == Instruction::Shl)
Owen Andersonbaf3c402009-07-29 18:55:55 +00007298 NewCst = ConstantExpr::getLShr(RHS, ShAmt);
Chris Lattner01deb9d2007-04-03 17:43:25 +00007299 else
Owen Andersonbaf3c402009-07-29 18:55:55 +00007300 NewCst = ConstantExpr::getShl(RHS, ShAmt);
Chris Lattner01deb9d2007-04-03 17:43:25 +00007301
7302 // Check to see if we are shifting out any of the bits being
7303 // compared.
Owen Andersonbaf3c402009-07-29 18:55:55 +00007304 if (ConstantExpr::get(Shift->getOpcode(),
Owen Andersond672ecb2009-07-03 00:17:18 +00007305 NewCst, ShAmt) != RHS) {
Chris Lattner01deb9d2007-04-03 17:43:25 +00007306 // If we shifted bits out, the fold is not going to work out.
7307 // As a special case, check to see if this means that the
7308 // result is always true or false now.
7309 if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
Owen Anderson5defacc2009-07-31 17:39:07 +00007310 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse(*Context));
Chris Lattner01deb9d2007-04-03 17:43:25 +00007311 if (ICI.getPredicate() == ICmpInst::ICMP_NE)
Owen Anderson5defacc2009-07-31 17:39:07 +00007312 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue(*Context));
Chris Lattner01deb9d2007-04-03 17:43:25 +00007313 } else {
7314 ICI.setOperand(1, NewCst);
7315 Constant *NewAndCST;
7316 if (Shift->getOpcode() == Instruction::Shl)
Owen Andersonbaf3c402009-07-29 18:55:55 +00007317 NewAndCST = ConstantExpr::getLShr(AndCST, ShAmt);
Chris Lattner01deb9d2007-04-03 17:43:25 +00007318 else
Owen Andersonbaf3c402009-07-29 18:55:55 +00007319 NewAndCST = ConstantExpr::getShl(AndCST, ShAmt);
Chris Lattner01deb9d2007-04-03 17:43:25 +00007320 LHSI->setOperand(1, NewAndCST);
7321 LHSI->setOperand(0, Shift->getOperand(0));
Chris Lattner7a1e9242009-08-30 06:13:40 +00007322 Worklist.Add(Shift); // Shift is dead.
Chris Lattner01deb9d2007-04-03 17:43:25 +00007323 return &ICI;
7324 }
7325 }
7326 }
7327
7328 // Turn ((X >> Y) & C) == 0 into (X & (C << Y)) == 0. The later is
7329 // preferable because it allows the C<<Y expression to be hoisted out
7330 // of a loop if Y is invariant and X is not.
7331 if (Shift && Shift->hasOneUse() && RHSV == 0 &&
Chris Lattnere8e49212009-03-25 00:28:58 +00007332 ICI.isEquality() && !Shift->isArithmeticShift() &&
7333 !isa<Constant>(Shift->getOperand(0))) {
Chris Lattner01deb9d2007-04-03 17:43:25 +00007334 // Compute C << Y.
7335 Value *NS;
7336 if (Shift->getOpcode() == Instruction::LShr) {
Chris Lattner74381062009-08-30 07:44:24 +00007337 NS = Builder->CreateShl(AndCST, Shift->getOperand(1), "tmp");
Chris Lattner01deb9d2007-04-03 17:43:25 +00007338 } else {
7339 // Insert a logical shift.
Chris Lattner74381062009-08-30 07:44:24 +00007340 NS = Builder->CreateLShr(AndCST, Shift->getOperand(1), "tmp");
Chris Lattner01deb9d2007-04-03 17:43:25 +00007341 }
Chris Lattner01deb9d2007-04-03 17:43:25 +00007342
7343 // Compute X & (C << Y).
Chris Lattner74381062009-08-30 07:44:24 +00007344 Value *NewAnd =
7345 Builder->CreateAnd(Shift->getOperand(0), NS, LHSI->getName());
Chris Lattner01deb9d2007-04-03 17:43:25 +00007346
7347 ICI.setOperand(0, NewAnd);
7348 return &ICI;
7349 }
7350 }
Chris Lattnerdf3d63b2010-01-02 22:08:28 +00007351
7352 // Try to optimize things like "A[i]&42 == 0" to index computations.
7353 if (LoadInst *LI = dyn_cast<LoadInst>(LHSI->getOperand(0))) {
7354 if (GetElementPtrInst *GEP =
7355 dyn_cast<GetElementPtrInst>(LI->getOperand(0)))
7356 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(GEP->getOperand(0)))
7357 if (GV->isConstant() && GV->hasDefinitiveInitializer() &&
7358 !LI->isVolatile() && isa<ConstantInt>(LHSI->getOperand(1))) {
7359 ConstantInt *C = cast<ConstantInt>(LHSI->getOperand(1));
7360 if (Instruction *Res = FoldCmpLoadFromIndexedGlobal(GEP, GV,ICI, C))
7361 return Res;
Chris Lattnerdf3d63b2010-01-02 22:08:28 +00007362 }
7363 }
Chris Lattner01deb9d2007-04-03 17:43:25 +00007364 break;
Nick Lewycky546d6312010-01-02 15:25:44 +00007365
7366 case Instruction::Or: {
7367 if (!ICI.isEquality() || !RHS->isNullValue() || !LHSI->hasOneUse())
7368 break;
7369 Value *P, *Q;
7370 if (match(LHSI, m_Or(m_PtrToInt(m_Value(P)), m_PtrToInt(m_Value(Q))))) {
7371 // Simplify icmp eq (or (ptrtoint P), (ptrtoint Q)), 0
7372 // -> and (icmp eq P, null), (icmp eq Q, null).
7373
7374 Value *ICIP = Builder->CreateICmp(ICI.getPredicate(), P,
7375 Constant::getNullValue(P->getType()));
7376 Value *ICIQ = Builder->CreateICmp(ICI.getPredicate(), Q,
7377 Constant::getNullValue(Q->getType()));
Nick Lewyckyf994bf02010-01-02 16:14:56 +00007378 Instruction *Op;
7379 if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
Nick Lewycky11ed0312010-01-03 00:55:31 +00007380 Op = BinaryOperator::CreateAnd(ICIP, ICIQ);
Nick Lewyckyf994bf02010-01-02 16:14:56 +00007381 else
Nick Lewycky11ed0312010-01-03 00:55:31 +00007382 Op = BinaryOperator::CreateOr(ICIP, ICIQ);
Nick Lewyckyf994bf02010-01-02 16:14:56 +00007383 return Op;
Nick Lewycky546d6312010-01-02 15:25:44 +00007384 }
7385 break;
7386 }
Chris Lattner01deb9d2007-04-03 17:43:25 +00007387
Chris Lattnera0141b92007-07-15 20:42:37 +00007388 case Instruction::Shl: { // (icmp pred (shl X, ShAmt), CI)
7389 ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1));
7390 if (!ShAmt) break;
7391
7392 uint32_t TypeBits = RHSV.getBitWidth();
7393
7394 // Check that the shift amount is in range. If not, don't perform
7395 // undefined shifts. When the shift is visited it will be
7396 // simplified.
7397 if (ShAmt->uge(TypeBits))
7398 break;
7399
7400 if (ICI.isEquality()) {
7401 // If we are comparing against bits always shifted out, the
7402 // comparison cannot succeed.
7403 Constant *Comp =
Owen Andersonbaf3c402009-07-29 18:55:55 +00007404 ConstantExpr::getShl(ConstantExpr::getLShr(RHS, ShAmt),
Owen Andersond672ecb2009-07-03 00:17:18 +00007405 ShAmt);
Chris Lattnera0141b92007-07-15 20:42:37 +00007406 if (Comp != RHS) {// Comparing against a bit that we know is zero.
7407 bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
Owen Anderson1d0be152009-08-13 21:58:54 +00007408 Constant *Cst = ConstantInt::get(Type::getInt1Ty(*Context), IsICMP_NE);
Chris Lattnera0141b92007-07-15 20:42:37 +00007409 return ReplaceInstUsesWith(ICI, Cst);
7410 }
7411
7412 if (LHSI->hasOneUse()) {
7413 // Otherwise strength reduce the shift into an and.
7414 uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
7415 Constant *Mask =
Owen Andersoneed707b2009-07-24 23:12:02 +00007416 ConstantInt::get(*Context, APInt::getLowBitsSet(TypeBits,
Owen Andersond672ecb2009-07-03 00:17:18 +00007417 TypeBits-ShAmtVal));
Chris Lattner01deb9d2007-04-03 17:43:25 +00007418
Chris Lattner74381062009-08-30 07:44:24 +00007419 Value *And =
7420 Builder->CreateAnd(LHSI->getOperand(0),Mask, LHSI->getName()+".mask");
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007421 return new ICmpInst(ICI.getPredicate(), And,
Owen Andersoneed707b2009-07-24 23:12:02 +00007422 ConstantInt::get(*Context, RHSV.lshr(ShAmtVal)));
Chris Lattner01deb9d2007-04-03 17:43:25 +00007423 }
7424 }
Chris Lattnera0141b92007-07-15 20:42:37 +00007425
7426 // Otherwise, if this is a comparison of the sign bit, simplify to and/test.
7427 bool TrueIfSigned = false;
7428 if (LHSI->hasOneUse() &&
7429 isSignBitCheck(ICI.getPredicate(), RHS, TrueIfSigned)) {
7430 // (X << 31) <s 0 --> (X&1) != 0
Owen Andersoneed707b2009-07-24 23:12:02 +00007431 Constant *Mask = ConstantInt::get(*Context, APInt(TypeBits, 1) <<
Chris Lattnera0141b92007-07-15 20:42:37 +00007432 (TypeBits-ShAmt->getZExtValue()-1));
Chris Lattner74381062009-08-30 07:44:24 +00007433 Value *And =
7434 Builder->CreateAnd(LHSI->getOperand(0), Mask, LHSI->getName()+".mask");
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007435 return new ICmpInst(TrueIfSigned ? ICmpInst::ICMP_NE : ICmpInst::ICMP_EQ,
Owen Andersona7235ea2009-07-31 20:28:14 +00007436 And, Constant::getNullValue(And->getType()));
Chris Lattnera0141b92007-07-15 20:42:37 +00007437 }
Chris Lattner01deb9d2007-04-03 17:43:25 +00007438 break;
Chris Lattnera0141b92007-07-15 20:42:37 +00007439 }
Chris Lattner01deb9d2007-04-03 17:43:25 +00007440
7441 case Instruction::LShr: // (icmp pred (shr X, ShAmt), CI)
Chris Lattnera0141b92007-07-15 20:42:37 +00007442 case Instruction::AShr: {
Chris Lattner41dc0fc2008-03-21 05:19:58 +00007443 // Only handle equality comparisons of shift-by-constant.
Chris Lattnera0141b92007-07-15 20:42:37 +00007444 ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1));
Chris Lattner41dc0fc2008-03-21 05:19:58 +00007445 if (!ShAmt || !ICI.isEquality()) break;
Chris Lattnera0141b92007-07-15 20:42:37 +00007446
Chris Lattner41dc0fc2008-03-21 05:19:58 +00007447 // Check that the shift amount is in range. If not, don't perform
7448 // undefined shifts. When the shift is visited it will be
7449 // simplified.
7450 uint32_t TypeBits = RHSV.getBitWidth();
7451 if (ShAmt->uge(TypeBits))
7452 break;
7453
7454 uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
Chris Lattnera0141b92007-07-15 20:42:37 +00007455
Chris Lattner41dc0fc2008-03-21 05:19:58 +00007456 // If we are comparing against bits always shifted out, the
7457 // comparison cannot succeed.
7458 APInt Comp = RHSV << ShAmtVal;
7459 if (LHSI->getOpcode() == Instruction::LShr)
7460 Comp = Comp.lshr(ShAmtVal);
7461 else
7462 Comp = Comp.ashr(ShAmtVal);
7463
7464 if (Comp != RHSV) { // Comparing against a bit that we know is zero.
7465 bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
Owen Anderson1d0be152009-08-13 21:58:54 +00007466 Constant *Cst = ConstantInt::get(Type::getInt1Ty(*Context), IsICMP_NE);
Chris Lattner41dc0fc2008-03-21 05:19:58 +00007467 return ReplaceInstUsesWith(ICI, Cst);
7468 }
7469
7470 // Otherwise, check to see if the bits shifted out are known to be zero.
7471 // If so, we can compare against the unshifted value:
7472 // (X & 4) >> 1 == 2 --> (X & 4) == 4.
Evan Chengf30752c2008-04-23 00:38:06 +00007473 if (LHSI->hasOneUse() &&
7474 MaskedValueIsZero(LHSI->getOperand(0),
Chris Lattner41dc0fc2008-03-21 05:19:58 +00007475 APInt::getLowBitsSet(Comp.getBitWidth(), ShAmtVal))) {
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007476 return new ICmpInst(ICI.getPredicate(), LHSI->getOperand(0),
Owen Andersonbaf3c402009-07-29 18:55:55 +00007477 ConstantExpr::getShl(RHS, ShAmt));
Chris Lattner41dc0fc2008-03-21 05:19:58 +00007478 }
Chris Lattnera0141b92007-07-15 20:42:37 +00007479
Evan Chengf30752c2008-04-23 00:38:06 +00007480 if (LHSI->hasOneUse()) {
Chris Lattner41dc0fc2008-03-21 05:19:58 +00007481 // Otherwise strength reduce the shift into an and.
7482 APInt Val(APInt::getHighBitsSet(TypeBits, TypeBits - ShAmtVal));
Owen Andersoneed707b2009-07-24 23:12:02 +00007483 Constant *Mask = ConstantInt::get(*Context, Val);
Chris Lattnera0141b92007-07-15 20:42:37 +00007484
Chris Lattner74381062009-08-30 07:44:24 +00007485 Value *And = Builder->CreateAnd(LHSI->getOperand(0),
7486 Mask, LHSI->getName()+".mask");
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007487 return new ICmpInst(ICI.getPredicate(), And,
Owen Andersonbaf3c402009-07-29 18:55:55 +00007488 ConstantExpr::getShl(RHS, ShAmt));
Chris Lattner01deb9d2007-04-03 17:43:25 +00007489 }
7490 break;
Chris Lattnera0141b92007-07-15 20:42:37 +00007491 }
Chris Lattner01deb9d2007-04-03 17:43:25 +00007492
7493 case Instruction::SDiv:
7494 case Instruction::UDiv:
7495 // Fold: icmp pred ([us]div X, C1), C2 -> range test
7496 // Fold this div into the comparison, producing a range check.
7497 // Determine, based on the divide type, what the range is being
7498 // checked. If there is an overflow on the low or high side, remember
7499 // it, otherwise compute the range [low, hi) bounding the new value.
7500 // See: InsertRangeTest above for the kinds of replacements possible.
Chris Lattner562ef782007-06-20 23:46:26 +00007501 if (ConstantInt *DivRHS = dyn_cast<ConstantInt>(LHSI->getOperand(1)))
7502 if (Instruction *R = FoldICmpDivCst(ICI, cast<BinaryOperator>(LHSI),
7503 DivRHS))
7504 return R;
Chris Lattner01deb9d2007-04-03 17:43:25 +00007505 break;
Nick Lewycky5be29202008-02-03 16:33:09 +00007506
7507 case Instruction::Add:
Chris Lattner2799baf2009-12-21 03:19:28 +00007508 // Fold: icmp pred (add X, C1), C2
Nick Lewycky5be29202008-02-03 16:33:09 +00007509 if (!ICI.isEquality()) {
7510 ConstantInt *LHSC = dyn_cast<ConstantInt>(LHSI->getOperand(1));
7511 if (!LHSC) break;
7512 const APInt &LHSV = LHSC->getValue();
7513
7514 ConstantRange CR = ICI.makeConstantRange(ICI.getPredicate(), RHSV)
7515 .subtract(LHSV);
7516
Nick Lewycky4a134af2009-10-25 05:20:17 +00007517 if (ICI.isSigned()) {
Nick Lewycky5be29202008-02-03 16:33:09 +00007518 if (CR.getLower().isSignBit()) {
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007519 return new ICmpInst(ICmpInst::ICMP_SLT, LHSI->getOperand(0),
Owen Andersoneed707b2009-07-24 23:12:02 +00007520 ConstantInt::get(*Context, CR.getUpper()));
Nick Lewycky5be29202008-02-03 16:33:09 +00007521 } else if (CR.getUpper().isSignBit()) {
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007522 return new ICmpInst(ICmpInst::ICMP_SGE, LHSI->getOperand(0),
Owen Andersoneed707b2009-07-24 23:12:02 +00007523 ConstantInt::get(*Context, CR.getLower()));
Nick Lewycky5be29202008-02-03 16:33:09 +00007524 }
7525 } else {
7526 if (CR.getLower().isMinValue()) {
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007527 return new ICmpInst(ICmpInst::ICMP_ULT, LHSI->getOperand(0),
Owen Andersoneed707b2009-07-24 23:12:02 +00007528 ConstantInt::get(*Context, CR.getUpper()));
Nick Lewycky5be29202008-02-03 16:33:09 +00007529 } else if (CR.getUpper().isMinValue()) {
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007530 return new ICmpInst(ICmpInst::ICMP_UGE, LHSI->getOperand(0),
Owen Andersoneed707b2009-07-24 23:12:02 +00007531 ConstantInt::get(*Context, CR.getLower()));
Nick Lewycky5be29202008-02-03 16:33:09 +00007532 }
7533 }
7534 }
7535 break;
Chris Lattner01deb9d2007-04-03 17:43:25 +00007536 }
7537
7538 // Simplify icmp_eq and icmp_ne instructions with integer constant RHS.
7539 if (ICI.isEquality()) {
7540 bool isICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
7541
7542 // If the first operand is (add|sub|and|or|xor|rem) with a constant, and
7543 // the second operand is a constant, simplify a bit.
7544 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(LHSI)) {
7545 switch (BO->getOpcode()) {
7546 case Instruction::SRem:
7547 // If we have a signed (X % (2^c)) == 0, turn it into an unsigned one.
7548 if (RHSV == 0 && isa<ConstantInt>(BO->getOperand(1)) &&BO->hasOneUse()){
7549 const APInt &V = cast<ConstantInt>(BO->getOperand(1))->getValue();
7550 if (V.sgt(APInt(V.getBitWidth(), 1)) && V.isPowerOf2()) {
Chris Lattner74381062009-08-30 07:44:24 +00007551 Value *NewRem =
7552 Builder->CreateURem(BO->getOperand(0), BO->getOperand(1),
7553 BO->getName());
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007554 return new ICmpInst(ICI.getPredicate(), NewRem,
Owen Andersona7235ea2009-07-31 20:28:14 +00007555 Constant::getNullValue(BO->getType()));
Chris Lattner01deb9d2007-04-03 17:43:25 +00007556 }
7557 }
7558 break;
7559 case Instruction::Add:
7560 // Replace ((add A, B) != C) with (A != C-B) if B & C are constants.
7561 if (ConstantInt *BOp1C = dyn_cast<ConstantInt>(BO->getOperand(1))) {
7562 if (BO->hasOneUse())
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007563 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
Owen Andersonbaf3c402009-07-29 18:55:55 +00007564 ConstantExpr::getSub(RHS, BOp1C));
Chris Lattner01deb9d2007-04-03 17:43:25 +00007565 } else if (RHSV == 0) {
7566 // Replace ((add A, B) != 0) with (A != -B) if A or B is
7567 // efficiently invertible, or if the add has just this one use.
7568 Value *BOp0 = BO->getOperand(0), *BOp1 = BO->getOperand(1);
7569
Dan Gohman186a6362009-08-12 16:04:34 +00007570 if (Value *NegVal = dyn_castNegVal(BOp1))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007571 return new ICmpInst(ICI.getPredicate(), BOp0, NegVal);
Dan Gohman186a6362009-08-12 16:04:34 +00007572 else if (Value *NegVal = dyn_castNegVal(BOp0))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007573 return new ICmpInst(ICI.getPredicate(), NegVal, BOp1);
Chris Lattner01deb9d2007-04-03 17:43:25 +00007574 else if (BO->hasOneUse()) {
Chris Lattner74381062009-08-30 07:44:24 +00007575 Value *Neg = Builder->CreateNeg(BOp1);
Chris Lattner01deb9d2007-04-03 17:43:25 +00007576 Neg->takeName(BO);
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007577 return new ICmpInst(ICI.getPredicate(), BOp0, Neg);
Chris Lattner01deb9d2007-04-03 17:43:25 +00007578 }
7579 }
7580 break;
7581 case Instruction::Xor:
7582 // For the xor case, we can xor two constants together, eliminating
7583 // the explicit xor.
7584 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1)))
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007585 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
Owen Andersonbaf3c402009-07-29 18:55:55 +00007586 ConstantExpr::getXor(RHS, BOC));
Chris Lattner01deb9d2007-04-03 17:43:25 +00007587
7588 // FALLTHROUGH
7589 case Instruction::Sub:
7590 // Replace (([sub|xor] A, B) != 0) with (A != B)
7591 if (RHSV == 0)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007592 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
Chris Lattner01deb9d2007-04-03 17:43:25 +00007593 BO->getOperand(1));
7594 break;
7595
7596 case Instruction::Or:
7597 // If bits are being or'd in that are not present in the constant we
7598 // are comparing against, then the comparison could never succeed!
7599 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1))) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00007600 Constant *NotCI = ConstantExpr::getNot(RHS);
7601 if (!ConstantExpr::getAnd(BOC, NotCI)->isNullValue())
Owen Andersond672ecb2009-07-03 00:17:18 +00007602 return ReplaceInstUsesWith(ICI,
Owen Anderson1d0be152009-08-13 21:58:54 +00007603 ConstantInt::get(Type::getInt1Ty(*Context),
Owen Andersond672ecb2009-07-03 00:17:18 +00007604 isICMP_NE));
Chris Lattner01deb9d2007-04-03 17:43:25 +00007605 }
7606 break;
7607
7608 case Instruction::And:
7609 if (ConstantInt *BOC = dyn_cast<ConstantInt>(BO->getOperand(1))) {
7610 // If bits are being compared against that are and'd out, then the
7611 // comparison can never succeed!
7612 if ((RHSV & ~BOC->getValue()) != 0)
Owen Andersond672ecb2009-07-03 00:17:18 +00007613 return ReplaceInstUsesWith(ICI,
Owen Anderson1d0be152009-08-13 21:58:54 +00007614 ConstantInt::get(Type::getInt1Ty(*Context),
Owen Andersond672ecb2009-07-03 00:17:18 +00007615 isICMP_NE));
Chris Lattner01deb9d2007-04-03 17:43:25 +00007616
7617 // If we have ((X & C) == C), turn it into ((X & C) != 0).
7618 if (RHS == BOC && RHSV.isPowerOf2())
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007619 return new ICmpInst(isICMP_NE ? ICmpInst::ICMP_EQ :
Chris Lattner01deb9d2007-04-03 17:43:25 +00007620 ICmpInst::ICMP_NE, LHSI,
Owen Andersona7235ea2009-07-31 20:28:14 +00007621 Constant::getNullValue(RHS->getType()));
Chris Lattner01deb9d2007-04-03 17:43:25 +00007622
7623 // Replace (and X, (1 << size(X)-1) != 0) with x s< 0
Chris Lattner833f25d2008-06-02 01:29:46 +00007624 if (BOC->getValue().isSignBit()) {
Chris Lattner01deb9d2007-04-03 17:43:25 +00007625 Value *X = BO->getOperand(0);
Owen Andersona7235ea2009-07-31 20:28:14 +00007626 Constant *Zero = Constant::getNullValue(X->getType());
Chris Lattner01deb9d2007-04-03 17:43:25 +00007627 ICmpInst::Predicate pred = isICMP_NE ?
7628 ICmpInst::ICMP_SLT : ICmpInst::ICMP_SGE;
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007629 return new ICmpInst(pred, X, Zero);
Chris Lattner01deb9d2007-04-03 17:43:25 +00007630 }
7631
7632 // ((X & ~7) == 0) --> X < 8
7633 if (RHSV == 0 && isHighOnes(BOC)) {
7634 Value *X = BO->getOperand(0);
Owen Andersonbaf3c402009-07-29 18:55:55 +00007635 Constant *NegX = ConstantExpr::getNeg(BOC);
Chris Lattner01deb9d2007-04-03 17:43:25 +00007636 ICmpInst::Predicate pred = isICMP_NE ?
7637 ICmpInst::ICMP_UGE : ICmpInst::ICMP_ULT;
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007638 return new ICmpInst(pred, X, NegX);
Chris Lattner01deb9d2007-04-03 17:43:25 +00007639 }
7640 }
7641 default: break;
7642 }
7643 } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(LHSI)) {
7644 // Handle icmp {eq|ne} <intrinsic>, intcst.
7645 if (II->getIntrinsicID() == Intrinsic::bswap) {
Chris Lattner7a1e9242009-08-30 06:13:40 +00007646 Worklist.Add(II);
Chris Lattner01deb9d2007-04-03 17:43:25 +00007647 ICI.setOperand(0, II->getOperand(1));
Owen Andersoneed707b2009-07-24 23:12:02 +00007648 ICI.setOperand(1, ConstantInt::get(*Context, RHSV.byteSwap()));
Chris Lattner01deb9d2007-04-03 17:43:25 +00007649 return &ICI;
7650 }
7651 }
Chris Lattner01deb9d2007-04-03 17:43:25 +00007652 }
7653 return 0;
7654}
7655
7656/// visitICmpInstWithCastAndCast - Handle icmp (cast x to y), (cast/cst).
7657/// We only handle extending casts so far.
7658///
Reid Spencere4d87aa2006-12-23 06:05:41 +00007659Instruction *InstCombiner::visitICmpInstWithCastAndCast(ICmpInst &ICI) {
7660 const CastInst *LHSCI = cast<CastInst>(ICI.getOperand(0));
Reid Spencer3da59db2006-11-27 01:05:10 +00007661 Value *LHSCIOp = LHSCI->getOperand(0);
7662 const Type *SrcTy = LHSCIOp->getType();
Reid Spencere4d87aa2006-12-23 06:05:41 +00007663 const Type *DestTy = LHSCI->getType();
Chris Lattner484d3cf2005-04-24 06:59:08 +00007664 Value *RHSCIOp;
7665
Chris Lattner8c756c12007-05-05 22:41:33 +00007666 // Turn icmp (ptrtoint x), (ptrtoint/c) into a compare of the input if the
7667 // integer type is the same size as the pointer type.
Dan Gohmance9fe9f2009-07-21 23:21:54 +00007668 if (TD && LHSCI->getOpcode() == Instruction::PtrToInt &&
7669 TD->getPointerSizeInBits() ==
Chris Lattner8c756c12007-05-05 22:41:33 +00007670 cast<IntegerType>(DestTy)->getBitWidth()) {
7671 Value *RHSOp = 0;
7672 if (Constant *RHSC = dyn_cast<Constant>(ICI.getOperand(1))) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00007673 RHSOp = ConstantExpr::getIntToPtr(RHSC, SrcTy);
Chris Lattner8c756c12007-05-05 22:41:33 +00007674 } else if (PtrToIntInst *RHSC = dyn_cast<PtrToIntInst>(ICI.getOperand(1))) {
7675 RHSOp = RHSC->getOperand(0);
7676 // If the pointer types don't match, insert a bitcast.
7677 if (LHSCIOp->getType() != RHSOp->getType())
Chris Lattner08142f22009-08-30 19:47:22 +00007678 RHSOp = Builder->CreateBitCast(RHSOp, LHSCIOp->getType());
Chris Lattner8c756c12007-05-05 22:41:33 +00007679 }
7680
7681 if (RHSOp)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007682 return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSOp);
Chris Lattner8c756c12007-05-05 22:41:33 +00007683 }
7684
7685 // The code below only handles extension cast instructions, so far.
7686 // Enforce this.
Reid Spencere4d87aa2006-12-23 06:05:41 +00007687 if (LHSCI->getOpcode() != Instruction::ZExt &&
7688 LHSCI->getOpcode() != Instruction::SExt)
Chris Lattnerb352fa52005-01-17 03:20:02 +00007689 return 0;
7690
Reid Spencere4d87aa2006-12-23 06:05:41 +00007691 bool isSignedExt = LHSCI->getOpcode() == Instruction::SExt;
Nick Lewycky4a134af2009-10-25 05:20:17 +00007692 bool isSignedCmp = ICI.isSigned();
Chris Lattner484d3cf2005-04-24 06:59:08 +00007693
Reid Spencere4d87aa2006-12-23 06:05:41 +00007694 if (CastInst *CI = dyn_cast<CastInst>(ICI.getOperand(1))) {
Chris Lattner484d3cf2005-04-24 06:59:08 +00007695 // Not an extension from the same type?
7696 RHSCIOp = CI->getOperand(0);
Reid Spencere4d87aa2006-12-23 06:05:41 +00007697 if (RHSCIOp->getType() != LHSCIOp->getType())
7698 return 0;
Chris Lattnera5c5e772007-01-13 23:11:38 +00007699
Nick Lewycky4189a532008-01-28 03:48:02 +00007700 // If the signedness of the two casts doesn't agree (i.e. one is a sext
Chris Lattnera5c5e772007-01-13 23:11:38 +00007701 // and the other is a zext), then we can't handle this.
7702 if (CI->getOpcode() != LHSCI->getOpcode())
7703 return 0;
7704
Nick Lewycky4189a532008-01-28 03:48:02 +00007705 // Deal with equality cases early.
7706 if (ICI.isEquality())
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007707 return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSCIOp);
Nick Lewycky4189a532008-01-28 03:48:02 +00007708
7709 // A signed comparison of sign extended values simplifies into a
7710 // signed comparison.
7711 if (isSignedCmp && isSignedExt)
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007712 return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSCIOp);
Nick Lewycky4189a532008-01-28 03:48:02 +00007713
7714 // The other three cases all fold into an unsigned comparison.
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007715 return new ICmpInst(ICI.getUnsignedPredicate(), LHSCIOp, RHSCIOp);
Reid Spencer6731d5c2004-11-28 21:31:15 +00007716 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00007717
Reid Spencere4d87aa2006-12-23 06:05:41 +00007718 // If we aren't dealing with a constant on the RHS, exit early
7719 ConstantInt *CI = dyn_cast<ConstantInt>(ICI.getOperand(1));
7720 if (!CI)
7721 return 0;
7722
7723 // Compute the constant that would happen if we truncated to SrcTy then
7724 // reextended to DestTy.
Owen Andersonbaf3c402009-07-29 18:55:55 +00007725 Constant *Res1 = ConstantExpr::getTrunc(CI, SrcTy);
7726 Constant *Res2 = ConstantExpr::getCast(LHSCI->getOpcode(),
Owen Andersond672ecb2009-07-03 00:17:18 +00007727 Res1, DestTy);
Reid Spencere4d87aa2006-12-23 06:05:41 +00007728
7729 // If the re-extended constant didn't change...
7730 if (Res2 == CI) {
Eli Friedmanb17cb062009-12-17 22:42:29 +00007731 // Deal with equality cases early.
7732 if (ICI.isEquality())
Dan Gohman1c8a23c2009-08-25 23:17:54 +00007733 return new ICmpInst(ICI.getPredicate(), LHSCIOp, Res1);
Eli Friedmanb17cb062009-12-17 22:42:29 +00007734
7735 // A signed comparison of sign extended values simplifies into a
7736 // signed comparison.
7737 if (isSignedExt && isSignedCmp)
7738 return new ICmpInst(ICI.getPredicate(), LHSCIOp, Res1);
7739
7740 // The other three cases all fold into an unsigned comparison.
7741 return new ICmpInst(ICI.getUnsignedPredicate(), LHSCIOp, Res1);
Reid Spencere4d87aa2006-12-23 06:05:41 +00007742 }
7743
7744 // The re-extended constant changed so the constant cannot be represented
7745 // in the shorter type. Consequently, we cannot emit a simple comparison.
7746
7747 // First, handle some easy cases. We know the result cannot be equal at this
7748 // point so handle the ICI.isEquality() cases
7749 if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
Owen Anderson5defacc2009-07-31 17:39:07 +00007750 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse(*Context));
Reid Spencere4d87aa2006-12-23 06:05:41 +00007751 if (ICI.getPredicate() == ICmpInst::ICMP_NE)
Owen Anderson5defacc2009-07-31 17:39:07 +00007752 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue(*Context));
Reid Spencere4d87aa2006-12-23 06:05:41 +00007753
7754 // Evaluate the comparison for LT (we invert for GT below). LE and GE cases
7755 // should have been folded away previously and not enter in here.
7756 Value *Result;
7757 if (isSignedCmp) {
7758 // We're performing a signed comparison.
Reid Spencer0460fb32007-03-22 20:36:03 +00007759 if (cast<ConstantInt>(CI)->getValue().isNegative())
Owen Anderson5defacc2009-07-31 17:39:07 +00007760 Result = ConstantInt::getFalse(*Context); // X < (small) --> false
Reid Spencere4d87aa2006-12-23 06:05:41 +00007761 else
Owen Anderson5defacc2009-07-31 17:39:07 +00007762 Result = ConstantInt::getTrue(*Context); // X < (large) --> true
Reid Spencere4d87aa2006-12-23 06:05:41 +00007763 } else {
7764 // We're performing an unsigned comparison.
7765 if (isSignedExt) {
7766 // We're performing an unsigned comp with a sign extended value.
7767 // This is true if the input is >= 0. [aka >s -1]
Owen Andersona7235ea2009-07-31 20:28:14 +00007768 Constant *NegOne = Constant::getAllOnesValue(SrcTy);
Chris Lattner74381062009-08-30 07:44:24 +00007769 Result = Builder->CreateICmpSGT(LHSCIOp, NegOne, ICI.getName());
Reid Spencere4d87aa2006-12-23 06:05:41 +00007770 } else {
7771 // Unsigned extend & unsigned compare -> always true.
Owen Anderson5defacc2009-07-31 17:39:07 +00007772 Result = ConstantInt::getTrue(*Context);
Reid Spencere4d87aa2006-12-23 06:05:41 +00007773 }
7774 }
7775
7776 // Finally, return the value computed.
7777 if (ICI.getPredicate() == ICmpInst::ICMP_ULT ||
Chris Lattnerf2991842008-07-11 04:09:09 +00007778 ICI.getPredicate() == ICmpInst::ICMP_SLT)
Reid Spencere4d87aa2006-12-23 06:05:41 +00007779 return ReplaceInstUsesWith(ICI, Result);
Chris Lattnerf2991842008-07-11 04:09:09 +00007780
7781 assert((ICI.getPredicate()==ICmpInst::ICMP_UGT ||
7782 ICI.getPredicate()==ICmpInst::ICMP_SGT) &&
7783 "ICmp should be folded!");
7784 if (Constant *CI = dyn_cast<Constant>(Result))
Owen Andersonbaf3c402009-07-29 18:55:55 +00007785 return ReplaceInstUsesWith(ICI, ConstantExpr::getNot(CI));
Dan Gohman4ae51262009-08-12 16:23:25 +00007786 return BinaryOperator::CreateNot(Result);
Chris Lattner484d3cf2005-04-24 06:59:08 +00007787}
Chris Lattner3f5b8772002-05-06 16:14:14 +00007788
Reid Spencer832254e2007-02-02 02:16:23 +00007789Instruction *InstCombiner::visitShl(BinaryOperator &I) {
7790 return commonShiftTransforms(I);
7791}
7792
7793Instruction *InstCombiner::visitLShr(BinaryOperator &I) {
7794 return commonShiftTransforms(I);
7795}
7796
7797Instruction *InstCombiner::visitAShr(BinaryOperator &I) {
Chris Lattner348f6652007-12-06 01:59:46 +00007798 if (Instruction *R = commonShiftTransforms(I))
7799 return R;
7800
7801 Value *Op0 = I.getOperand(0);
7802
7803 // ashr int -1, X = -1 (for any arithmetic shift rights of ~0)
7804 if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
7805 if (CSI->isAllOnesValue())
7806 return ReplaceInstUsesWith(I, CSI);
Dan Gohman0001e562009-02-24 02:00:40 +00007807
Dan Gohmanc6ac3222009-06-16 19:55:29 +00007808 // See if we can turn a signed shr into an unsigned shr.
7809 if (MaskedValueIsZero(Op0,
7810 APInt::getSignBit(I.getType()->getScalarSizeInBits())))
7811 return BinaryOperator::CreateLShr(Op0, I.getOperand(1));
7812
7813 // Arithmetic shifting an all-sign-bit value is a no-op.
7814 unsigned NumSignBits = ComputeNumSignBits(Op0);
7815 if (NumSignBits == Op0->getType()->getScalarSizeInBits())
7816 return ReplaceInstUsesWith(I, Op0);
Dan Gohman0001e562009-02-24 02:00:40 +00007817
Chris Lattner348f6652007-12-06 01:59:46 +00007818 return 0;
Reid Spencer832254e2007-02-02 02:16:23 +00007819}
7820
7821Instruction *InstCombiner::commonShiftTransforms(BinaryOperator &I) {
7822 assert(I.getOperand(1)->getType() == I.getOperand(0)->getType());
Chris Lattner7e708292002-06-25 16:13:24 +00007823 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
Chris Lattner3f5b8772002-05-06 16:14:14 +00007824
7825 // shl X, 0 == X and shr X, 0 == X
7826 // shl 0, X == 0 and shr 0, X == 0
Owen Andersona7235ea2009-07-31 20:28:14 +00007827 if (Op1 == Constant::getNullValue(Op1->getType()) ||
7828 Op0 == Constant::getNullValue(Op0->getType()))
Chris Lattner233f7dc2002-08-12 21:17:25 +00007829 return ReplaceInstUsesWith(I, Op0);
Chris Lattner8d6bbdb2006-02-12 08:07:37 +00007830
Reid Spencere4d87aa2006-12-23 06:05:41 +00007831 if (isa<UndefValue>(Op0)) {
7832 if (I.getOpcode() == Instruction::AShr) // undef >>s X -> undef
Chris Lattner79a564c2004-10-16 23:28:04 +00007833 return ReplaceInstUsesWith(I, Op0);
Reid Spencere4d87aa2006-12-23 06:05:41 +00007834 else // undef << X -> 0, undef >>u X -> 0
Owen Andersona7235ea2009-07-31 20:28:14 +00007835 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnere87597f2004-10-16 18:11:37 +00007836 }
7837 if (isa<UndefValue>(Op1)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00007838 if (I.getOpcode() == Instruction::AShr) // X >>s undef -> X
7839 return ReplaceInstUsesWith(I, Op0);
7840 else // X << undef, X >>u undef -> 0
Owen Andersona7235ea2009-07-31 20:28:14 +00007841 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattnere87597f2004-10-16 18:11:37 +00007842 }
7843
Dan Gohman9004c8a2009-05-21 02:28:33 +00007844 // See if we can fold away this shift.
Dan Gohman6de29f82009-06-15 22:12:54 +00007845 if (SimplifyDemandedInstructionBits(I))
Dan Gohman9004c8a2009-05-21 02:28:33 +00007846 return &I;
7847
Chris Lattner2eefe512004-04-09 19:05:30 +00007848 // Try to fold constant and into select arguments.
7849 if (isa<Constant>(Op0))
7850 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
Chris Lattner6e7ba452005-01-01 16:22:27 +00007851 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
Chris Lattner2eefe512004-04-09 19:05:30 +00007852 return R;
7853
Reid Spencerb83eb642006-10-20 07:07:24 +00007854 if (ConstantInt *CUI = dyn_cast<ConstantInt>(Op1))
Reid Spencerc5b206b2006-12-31 05:48:39 +00007855 if (Instruction *Res = FoldShiftByConstant(Op0, CUI, I))
7856 return Res;
Chris Lattner4d5542c2006-01-06 07:12:35 +00007857 return 0;
7858}
7859
Reid Spencerb83eb642006-10-20 07:07:24 +00007860Instruction *InstCombiner::FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
Reid Spencer832254e2007-02-02 02:16:23 +00007861 BinaryOperator &I) {
Chris Lattner4598c942009-01-31 08:24:16 +00007862 bool isLeftShift = I.getOpcode() == Instruction::Shl;
Chris Lattner4d5542c2006-01-06 07:12:35 +00007863
Chris Lattner8d6bbdb2006-02-12 08:07:37 +00007864 // See if we can simplify any instructions used by the instruction whose sole
7865 // purpose is to compute bits we don't care about.
Dan Gohmanc6ac3222009-06-16 19:55:29 +00007866 uint32_t TypeBits = Op0->getType()->getScalarSizeInBits();
Chris Lattner8d6bbdb2006-02-12 08:07:37 +00007867
Dan Gohmana119de82009-06-14 23:30:43 +00007868 // shl i32 X, 32 = 0 and srl i8 Y, 9 = 0, ... just don't eliminate
7869 // a signed shift.
Chris Lattner4d5542c2006-01-06 07:12:35 +00007870 //
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00007871 if (Op1->uge(TypeBits)) {
Chris Lattner0737c242007-02-02 05:29:55 +00007872 if (I.getOpcode() != Instruction::AShr)
Owen Andersona7235ea2009-07-31 20:28:14 +00007873 return ReplaceInstUsesWith(I, Constant::getNullValue(Op0->getType()));
Chris Lattner4d5542c2006-01-06 07:12:35 +00007874 else {
Owen Andersoneed707b2009-07-24 23:12:02 +00007875 I.setOperand(1, ConstantInt::get(I.getType(), TypeBits-1));
Chris Lattner4d5542c2006-01-06 07:12:35 +00007876 return &I;
Chris Lattner8adac752004-02-23 20:30:06 +00007877 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00007878 }
7879
7880 // ((X*C1) << C2) == (X * (C1 << C2))
7881 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0))
7882 if (BO->getOpcode() == Instruction::Mul && isLeftShift)
7883 if (Constant *BOOp = dyn_cast<Constant>(BO->getOperand(1)))
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007884 return BinaryOperator::CreateMul(BO->getOperand(0),
Owen Andersonbaf3c402009-07-29 18:55:55 +00007885 ConstantExpr::getShl(BOOp, Op1));
Chris Lattner4d5542c2006-01-06 07:12:35 +00007886
7887 // Try to fold constant and into select arguments.
7888 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
7889 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
7890 return R;
7891 if (isa<PHINode>(Op0))
7892 if (Instruction *NV = FoldOpIntoPhi(I))
7893 return NV;
7894
Chris Lattner8999dd32007-12-22 09:07:47 +00007895 // Fold shift2(trunc(shift1(x,c1)), c2) -> trunc(shift2(shift1(x,c1),c2))
7896 if (TruncInst *TI = dyn_cast<TruncInst>(Op0)) {
7897 Instruction *TrOp = dyn_cast<Instruction>(TI->getOperand(0));
7898 // If 'shift2' is an ashr, we would have to get the sign bit into a funny
7899 // place. Don't try to do this transformation in this case. Also, we
7900 // require that the input operand is a shift-by-constant so that we have
7901 // confidence that the shifts will get folded together. We could do this
7902 // xform in more cases, but it is unlikely to be profitable.
7903 if (TrOp && I.isLogicalShift() && TrOp->isShift() &&
7904 isa<ConstantInt>(TrOp->getOperand(1))) {
7905 // Okay, we'll do this xform. Make the shift of shift.
Owen Andersonbaf3c402009-07-29 18:55:55 +00007906 Constant *ShAmt = ConstantExpr::getZExt(Op1, TrOp->getType());
Chris Lattner74381062009-08-30 07:44:24 +00007907 // (shift2 (shift1 & 0x00FF), c2)
7908 Value *NSh = Builder->CreateBinOp(I.getOpcode(), TrOp, ShAmt,I.getName());
Chris Lattner8999dd32007-12-22 09:07:47 +00007909
7910 // For logical shifts, the truncation has the effect of making the high
7911 // part of the register be zeros. Emulate this by inserting an AND to
7912 // clear the top bits as needed. This 'and' will usually be zapped by
7913 // other xforms later if dead.
Dan Gohmanc6ac3222009-06-16 19:55:29 +00007914 unsigned SrcSize = TrOp->getType()->getScalarSizeInBits();
7915 unsigned DstSize = TI->getType()->getScalarSizeInBits();
Chris Lattner8999dd32007-12-22 09:07:47 +00007916 APInt MaskV(APInt::getLowBitsSet(SrcSize, DstSize));
7917
7918 // The mask we constructed says what the trunc would do if occurring
7919 // between the shifts. We want to know the effect *after* the second
7920 // shift. We know that it is a logical shift by a constant, so adjust the
7921 // mask as appropriate.
7922 if (I.getOpcode() == Instruction::Shl)
7923 MaskV <<= Op1->getZExtValue();
7924 else {
7925 assert(I.getOpcode() == Instruction::LShr && "Unknown logical shift");
7926 MaskV = MaskV.lshr(Op1->getZExtValue());
7927 }
7928
Chris Lattner74381062009-08-30 07:44:24 +00007929 // shift1 & 0x00FF
7930 Value *And = Builder->CreateAnd(NSh, ConstantInt::get(*Context, MaskV),
7931 TI->getName());
Chris Lattner8999dd32007-12-22 09:07:47 +00007932
7933 // Return the value truncated to the interesting size.
7934 return new TruncInst(And, I.getType());
7935 }
7936 }
7937
Chris Lattner4d5542c2006-01-06 07:12:35 +00007938 if (Op0->hasOneUse()) {
Chris Lattner4d5542c2006-01-06 07:12:35 +00007939 if (BinaryOperator *Op0BO = dyn_cast<BinaryOperator>(Op0)) {
7940 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
7941 Value *V1, *V2;
7942 ConstantInt *CC;
7943 switch (Op0BO->getOpcode()) {
Chris Lattner11021cb2005-09-18 05:12:10 +00007944 default: break;
7945 case Instruction::Add:
7946 case Instruction::And:
7947 case Instruction::Or:
Reid Spencera07cb7d2007-02-02 14:41:37 +00007948 case Instruction::Xor: {
Chris Lattner11021cb2005-09-18 05:12:10 +00007949 // These operators commute.
7950 // Turn (Y + (X >> C)) << C -> (X + (Y << C)) & (~0 << C)
Chris Lattner150f12a2005-09-18 06:30:59 +00007951 if (isLeftShift && Op0BO->getOperand(1)->hasOneUse() &&
Owen Andersonc7d2ce72009-07-10 17:35:01 +00007952 match(Op0BO->getOperand(1), m_Shr(m_Value(V1),
Chris Lattnerf925cbd2009-08-30 18:50:58 +00007953 m_Specific(Op1)))) {
7954 Value *YS = // (Y << C)
7955 Builder->CreateShl(Op0BO->getOperand(0), Op1, Op0BO->getName());
7956 // (X + (Y << C))
7957 Value *X = Builder->CreateBinOp(Op0BO->getOpcode(), YS, V1,
7958 Op0BO->getOperand(1)->getName());
Zhou Sheng302748d2007-03-30 17:20:39 +00007959 uint32_t Op1Val = Op1->getLimitedValue(TypeBits);
Owen Andersoneed707b2009-07-24 23:12:02 +00007960 return BinaryOperator::CreateAnd(X, ConstantInt::get(*Context,
Zhou Sheng90b96812007-03-30 05:45:18 +00007961 APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
Chris Lattner150f12a2005-09-18 06:30:59 +00007962 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00007963
Chris Lattner150f12a2005-09-18 06:30:59 +00007964 // Turn (Y + ((X >> C) & CC)) << C -> ((X & (CC << C)) + (Y << C))
Reid Spencera07cb7d2007-02-02 14:41:37 +00007965 Value *Op0BOOp1 = Op0BO->getOperand(1);
Chris Lattner3c698492007-03-05 00:11:19 +00007966 if (isLeftShift && Op0BOOp1->hasOneUse() &&
Reid Spencera07cb7d2007-02-02 14:41:37 +00007967 match(Op0BOOp1,
Chris Lattnercb504b92008-11-16 05:38:51 +00007968 m_And(m_Shr(m_Value(V1), m_Specific(Op1)),
Dan Gohman4ae51262009-08-12 16:23:25 +00007969 m_ConstantInt(CC))) &&
Chris Lattnercb504b92008-11-16 05:38:51 +00007970 cast<BinaryOperator>(Op0BOOp1)->getOperand(0)->hasOneUse()) {
Chris Lattnerf925cbd2009-08-30 18:50:58 +00007971 Value *YS = // (Y << C)
7972 Builder->CreateShl(Op0BO->getOperand(0), Op1,
7973 Op0BO->getName());
7974 // X & (CC << C)
7975 Value *XM = Builder->CreateAnd(V1, ConstantExpr::getShl(CC, Op1),
7976 V1->getName()+".mask");
Gabor Greif7cbd8a32008-05-16 19:29:10 +00007977 return BinaryOperator::Create(Op0BO->getOpcode(), YS, XM);
Chris Lattner150f12a2005-09-18 06:30:59 +00007978 }
Reid Spencera07cb7d2007-02-02 14:41:37 +00007979 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00007980
Reid Spencera07cb7d2007-02-02 14:41:37 +00007981 // FALL THROUGH.
7982 case Instruction::Sub: {
Chris Lattner11021cb2005-09-18 05:12:10 +00007983 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
Chris Lattner150f12a2005-09-18 06:30:59 +00007984 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
Owen Andersonc7d2ce72009-07-10 17:35:01 +00007985 match(Op0BO->getOperand(0), m_Shr(m_Value(V1),
Dan Gohman4ae51262009-08-12 16:23:25 +00007986 m_Specific(Op1)))) {
Chris Lattnerf925cbd2009-08-30 18:50:58 +00007987 Value *YS = // (Y << C)
7988 Builder->CreateShl(Op0BO->getOperand(1), Op1, Op0BO->getName());
7989 // (X + (Y << C))
7990 Value *X = Builder->CreateBinOp(Op0BO->getOpcode(), V1, YS,
7991 Op0BO->getOperand(0)->getName());
Zhou Sheng302748d2007-03-30 17:20:39 +00007992 uint32_t Op1Val = Op1->getLimitedValue(TypeBits);
Owen Andersoneed707b2009-07-24 23:12:02 +00007993 return BinaryOperator::CreateAnd(X, ConstantInt::get(*Context,
Zhou Sheng90b96812007-03-30 05:45:18 +00007994 APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
Chris Lattner150f12a2005-09-18 06:30:59 +00007995 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00007996
Chris Lattner13d4ab42006-05-31 21:14:00 +00007997 // Turn (((X >> C)&CC) + Y) << C -> (X + (Y << C)) & (CC << C)
Chris Lattner150f12a2005-09-18 06:30:59 +00007998 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
7999 match(Op0BO->getOperand(0),
8000 m_And(m_Shr(m_Value(V1), m_Value(V2)),
Dan Gohman4ae51262009-08-12 16:23:25 +00008001 m_ConstantInt(CC))) && V2 == Op1 &&
Chris Lattner9a4cacb2006-02-09 07:41:14 +00008002 cast<BinaryOperator>(Op0BO->getOperand(0))
8003 ->getOperand(0)->hasOneUse()) {
Chris Lattnerf925cbd2009-08-30 18:50:58 +00008004 Value *YS = // (Y << C)
8005 Builder->CreateShl(Op0BO->getOperand(1), Op1, Op0BO->getName());
8006 // X & (CC << C)
8007 Value *XM = Builder->CreateAnd(V1, ConstantExpr::getShl(CC, Op1),
8008 V1->getName()+".mask");
Chris Lattner150f12a2005-09-18 06:30:59 +00008009
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008010 return BinaryOperator::Create(Op0BO->getOpcode(), XM, YS);
Chris Lattner150f12a2005-09-18 06:30:59 +00008011 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00008012
Chris Lattner11021cb2005-09-18 05:12:10 +00008013 break;
Reid Spencera07cb7d2007-02-02 14:41:37 +00008014 }
Chris Lattner4d5542c2006-01-06 07:12:35 +00008015 }
8016
8017
8018 // If the operand is an bitwise operator with a constant RHS, and the
8019 // shift is the only use, we can pull it out of the shift.
8020 if (ConstantInt *Op0C = dyn_cast<ConstantInt>(Op0BO->getOperand(1))) {
8021 bool isValid = true; // Valid only for And, Or, Xor
8022 bool highBitSet = false; // Transform if high bit of constant set?
8023
8024 switch (Op0BO->getOpcode()) {
Chris Lattnerdf17af12003-08-12 21:53:41 +00008025 default: isValid = false; break; // Do not perform transform!
Chris Lattner1f7e1602004-10-08 03:46:20 +00008026 case Instruction::Add:
8027 isValid = isLeftShift;
8028 break;
Chris Lattnerdf17af12003-08-12 21:53:41 +00008029 case Instruction::Or:
8030 case Instruction::Xor:
8031 highBitSet = false;
8032 break;
8033 case Instruction::And:
8034 highBitSet = true;
8035 break;
Chris Lattner4d5542c2006-01-06 07:12:35 +00008036 }
8037
8038 // If this is a signed shift right, and the high bit is modified
8039 // by the logical operation, do not perform the transformation.
8040 // The highBitSet boolean indicates the value of the high bit of
8041 // the constant which would cause it to be modified for this
8042 // operation.
8043 //
Chris Lattnerc95ba442007-12-06 06:25:04 +00008044 if (isValid && I.getOpcode() == Instruction::AShr)
Zhou Shenge9e03f62007-03-28 15:02:20 +00008045 isValid = Op0C->getValue()[TypeBits-1] == highBitSet;
Chris Lattner4d5542c2006-01-06 07:12:35 +00008046
8047 if (isValid) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00008048 Constant *NewRHS = ConstantExpr::get(I.getOpcode(), Op0C, Op1);
Chris Lattner4d5542c2006-01-06 07:12:35 +00008049
Chris Lattnerf925cbd2009-08-30 18:50:58 +00008050 Value *NewShift =
8051 Builder->CreateBinOp(I.getOpcode(), Op0BO->getOperand(0), Op1);
Chris Lattner6934a042007-02-11 01:23:03 +00008052 NewShift->takeName(Op0BO);
Chris Lattner4d5542c2006-01-06 07:12:35 +00008053
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008054 return BinaryOperator::Create(Op0BO->getOpcode(), NewShift,
Chris Lattner4d5542c2006-01-06 07:12:35 +00008055 NewRHS);
8056 }
8057 }
8058 }
8059 }
8060
Chris Lattnerad0124c2006-01-06 07:52:12 +00008061 // Find out if this is a shift of a shift by a constant.
Reid Spencer832254e2007-02-02 02:16:23 +00008062 BinaryOperator *ShiftOp = dyn_cast<BinaryOperator>(Op0);
8063 if (ShiftOp && !ShiftOp->isShift())
8064 ShiftOp = 0;
Chris Lattnerad0124c2006-01-06 07:52:12 +00008065
Reid Spencerb83eb642006-10-20 07:07:24 +00008066 if (ShiftOp && isa<ConstantInt>(ShiftOp->getOperand(1))) {
Reid Spencerb83eb642006-10-20 07:07:24 +00008067 ConstantInt *ShiftAmt1C = cast<ConstantInt>(ShiftOp->getOperand(1));
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +00008068 uint32_t ShiftAmt1 = ShiftAmt1C->getLimitedValue(TypeBits);
8069 uint32_t ShiftAmt2 = Op1->getLimitedValue(TypeBits);
Chris Lattnerb87056f2007-02-05 00:57:54 +00008070 assert(ShiftAmt2 != 0 && "Should have been simplified earlier");
8071 if (ShiftAmt1 == 0) return 0; // Will be simplified in the future.
8072 Value *X = ShiftOp->getOperand(0);
Chris Lattnerad0124c2006-01-06 07:52:12 +00008073
Zhou Sheng4351c642007-04-02 08:20:41 +00008074 uint32_t AmtSum = ShiftAmt1+ShiftAmt2; // Fold into one big shift.
Chris Lattnerb87056f2007-02-05 00:57:54 +00008075
8076 const IntegerType *Ty = cast<IntegerType>(I.getType());
8077
8078 // Check for (X << c1) << c2 and (X >> c1) >> c2
Chris Lattner7f3da2d2007-02-03 23:28:07 +00008079 if (I.getOpcode() == ShiftOp->getOpcode()) {
Chris Lattner344c7c52009-03-20 22:41:15 +00008080 // If this is oversized composite shift, then unsigned shifts get 0, ashr
8081 // saturates.
8082 if (AmtSum >= TypeBits) {
8083 if (I.getOpcode() != Instruction::AShr)
Owen Andersona7235ea2009-07-31 20:28:14 +00008084 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner344c7c52009-03-20 22:41:15 +00008085 AmtSum = TypeBits-1; // Saturate to 31 for i32 ashr.
8086 }
8087
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008088 return BinaryOperator::Create(I.getOpcode(), X,
Owen Andersoneed707b2009-07-24 23:12:02 +00008089 ConstantInt::get(Ty, AmtSum));
Chris Lattnerf925cbd2009-08-30 18:50:58 +00008090 }
8091
8092 if (ShiftOp->getOpcode() == Instruction::LShr &&
8093 I.getOpcode() == Instruction::AShr) {
Chris Lattner344c7c52009-03-20 22:41:15 +00008094 if (AmtSum >= TypeBits)
Owen Andersona7235ea2009-07-31 20:28:14 +00008095 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner344c7c52009-03-20 22:41:15 +00008096
Chris Lattnerb87056f2007-02-05 00:57:54 +00008097 // ((X >>u C1) >>s C2) -> (X >>u (C1+C2)) since C1 != 0.
Owen Andersoneed707b2009-07-24 23:12:02 +00008098 return BinaryOperator::CreateLShr(X, ConstantInt::get(Ty, AmtSum));
Chris Lattnerf925cbd2009-08-30 18:50:58 +00008099 }
8100
8101 if (ShiftOp->getOpcode() == Instruction::AShr &&
8102 I.getOpcode() == Instruction::LShr) {
Chris Lattnerb87056f2007-02-05 00:57:54 +00008103 // ((X >>s C1) >>u C2) -> ((X >>s (C1+C2)) & mask) since C1 != 0.
Chris Lattner344c7c52009-03-20 22:41:15 +00008104 if (AmtSum >= TypeBits)
8105 AmtSum = TypeBits-1;
8106
Chris Lattnerf925cbd2009-08-30 18:50:58 +00008107 Value *Shift = Builder->CreateAShr(X, ConstantInt::get(Ty, AmtSum));
Chris Lattnerb87056f2007-02-05 00:57:54 +00008108
Zhou Shenge9e03f62007-03-28 15:02:20 +00008109 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
Owen Andersoneed707b2009-07-24 23:12:02 +00008110 return BinaryOperator::CreateAnd(Shift, ConstantInt::get(*Context, Mask));
Chris Lattnerad0124c2006-01-06 07:52:12 +00008111 }
8112
Chris Lattnerb87056f2007-02-05 00:57:54 +00008113 // Okay, if we get here, one shift must be left, and the other shift must be
8114 // right. See if the amounts are equal.
8115 if (ShiftAmt1 == ShiftAmt2) {
8116 // If we have ((X >>? C) << C), turn this into X & (-1 << C).
8117 if (I.getOpcode() == Instruction::Shl) {
Reid Spencer55702aa2007-03-25 21:11:44 +00008118 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt1));
Owen Andersoneed707b2009-07-24 23:12:02 +00008119 return BinaryOperator::CreateAnd(X, ConstantInt::get(*Context, Mask));
Chris Lattnerb87056f2007-02-05 00:57:54 +00008120 }
8121 // If we have ((X << C) >>u C), turn this into X & (-1 >>u C).
8122 if (I.getOpcode() == Instruction::LShr) {
Zhou Sheng3a507fd2007-04-01 17:13:37 +00008123 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt1));
Owen Andersoneed707b2009-07-24 23:12:02 +00008124 return BinaryOperator::CreateAnd(X, ConstantInt::get(*Context, Mask));
Chris Lattnerb87056f2007-02-05 00:57:54 +00008125 }
8126 // We can simplify ((X << C) >>s C) into a trunc + sext.
8127 // NOTE: we could do this for any C, but that would make 'unusual' integer
8128 // types. For now, just stick to ones well-supported by the code
8129 // generators.
8130 const Type *SExtType = 0;
8131 switch (Ty->getBitWidth() - ShiftAmt1) {
Zhou Shenge9e03f62007-03-28 15:02:20 +00008132 case 1 :
8133 case 8 :
8134 case 16 :
8135 case 32 :
8136 case 64 :
8137 case 128:
Owen Anderson1d0be152009-08-13 21:58:54 +00008138 SExtType = IntegerType::get(*Context, Ty->getBitWidth() - ShiftAmt1);
Zhou Shenge9e03f62007-03-28 15:02:20 +00008139 break;
Chris Lattnerb87056f2007-02-05 00:57:54 +00008140 default: break;
8141 }
Chris Lattnerf925cbd2009-08-30 18:50:58 +00008142 if (SExtType)
8143 return new SExtInst(Builder->CreateTrunc(X, SExtType, "sext"), Ty);
Chris Lattnerb87056f2007-02-05 00:57:54 +00008144 // Otherwise, we can't handle it yet.
8145 } else if (ShiftAmt1 < ShiftAmt2) {
Zhou Sheng4351c642007-04-02 08:20:41 +00008146 uint32_t ShiftDiff = ShiftAmt2-ShiftAmt1;
Chris Lattnerad0124c2006-01-06 07:52:12 +00008147
Chris Lattnerb0b991a2007-02-05 05:57:49 +00008148 // (X >>? C1) << C2 --> X << (C2-C1) & (-1 << C2)
Chris Lattnerb87056f2007-02-05 00:57:54 +00008149 if (I.getOpcode() == Instruction::Shl) {
8150 assert(ShiftOp->getOpcode() == Instruction::LShr ||
8151 ShiftOp->getOpcode() == Instruction::AShr);
Chris Lattnerf925cbd2009-08-30 18:50:58 +00008152 Value *Shift = Builder->CreateShl(X, ConstantInt::get(Ty, ShiftDiff));
Chris Lattnere8d56c52006-01-07 01:32:28 +00008153
Reid Spencer55702aa2007-03-25 21:11:44 +00008154 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
Owen Andersoneed707b2009-07-24 23:12:02 +00008155 return BinaryOperator::CreateAnd(Shift,
8156 ConstantInt::get(*Context, Mask));
Chris Lattnerad0124c2006-01-06 07:52:12 +00008157 }
Chris Lattnerb87056f2007-02-05 00:57:54 +00008158
Chris Lattnerb0b991a2007-02-05 05:57:49 +00008159 // (X << C1) >>u C2 --> X >>u (C2-C1) & (-1 >> C2)
Chris Lattnerb87056f2007-02-05 00:57:54 +00008160 if (I.getOpcode() == Instruction::LShr) {
8161 assert(ShiftOp->getOpcode() == Instruction::Shl);
Chris Lattnerf925cbd2009-08-30 18:50:58 +00008162 Value *Shift = Builder->CreateLShr(X, ConstantInt::get(Ty, ShiftDiff));
Chris Lattnerad0124c2006-01-06 07:52:12 +00008163
Reid Spencerd5e30f02007-03-26 17:18:58 +00008164 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
Owen Andersoneed707b2009-07-24 23:12:02 +00008165 return BinaryOperator::CreateAnd(Shift,
8166 ConstantInt::get(*Context, Mask));
Chris Lattner11021cb2005-09-18 05:12:10 +00008167 }
Chris Lattnerb87056f2007-02-05 00:57:54 +00008168
8169 // We can't handle (X << C1) >>s C2, it shifts arbitrary bits in.
8170 } else {
8171 assert(ShiftAmt2 < ShiftAmt1);
Zhou Sheng4351c642007-04-02 08:20:41 +00008172 uint32_t ShiftDiff = ShiftAmt1-ShiftAmt2;
Chris Lattnerb87056f2007-02-05 00:57:54 +00008173
Chris Lattnerb0b991a2007-02-05 05:57:49 +00008174 // (X >>? C1) << C2 --> X >>? (C1-C2) & (-1 << C2)
Chris Lattnerb87056f2007-02-05 00:57:54 +00008175 if (I.getOpcode() == Instruction::Shl) {
8176 assert(ShiftOp->getOpcode() == Instruction::LShr ||
8177 ShiftOp->getOpcode() == Instruction::AShr);
Chris Lattnerf925cbd2009-08-30 18:50:58 +00008178 Value *Shift = Builder->CreateBinOp(ShiftOp->getOpcode(), X,
8179 ConstantInt::get(Ty, ShiftDiff));
Chris Lattnerb87056f2007-02-05 00:57:54 +00008180
Reid Spencer55702aa2007-03-25 21:11:44 +00008181 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
Owen Andersoneed707b2009-07-24 23:12:02 +00008182 return BinaryOperator::CreateAnd(Shift,
8183 ConstantInt::get(*Context, Mask));
Chris Lattnerb87056f2007-02-05 00:57:54 +00008184 }
8185
Chris Lattnerb0b991a2007-02-05 05:57:49 +00008186 // (X << C1) >>u C2 --> X << (C1-C2) & (-1 >> C2)
Chris Lattnerb87056f2007-02-05 00:57:54 +00008187 if (I.getOpcode() == Instruction::LShr) {
8188 assert(ShiftOp->getOpcode() == Instruction::Shl);
Chris Lattnerf925cbd2009-08-30 18:50:58 +00008189 Value *Shift = Builder->CreateShl(X, ConstantInt::get(Ty, ShiftDiff));
Chris Lattnerb87056f2007-02-05 00:57:54 +00008190
Reid Spencer68d27cf2007-03-26 23:45:51 +00008191 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
Owen Andersoneed707b2009-07-24 23:12:02 +00008192 return BinaryOperator::CreateAnd(Shift,
8193 ConstantInt::get(*Context, Mask));
Chris Lattnerb87056f2007-02-05 00:57:54 +00008194 }
8195
8196 // We can't handle (X << C1) >>a C2, it shifts arbitrary bits in.
Chris Lattner6e7ba452005-01-01 16:22:27 +00008197 }
Chris Lattnerad0124c2006-01-06 07:52:12 +00008198 }
Chris Lattner3f5b8772002-05-06 16:14:14 +00008199 return 0;
8200}
8201
Chris Lattnera1be5662002-05-02 17:06:02 +00008202
Chris Lattnercfd65102005-10-29 04:36:15 +00008203/// DecomposeSimpleLinearExpr - Analyze 'Val', seeing if it is a simple linear
8204/// expression. If so, decompose it, returning some value X, such that Val is
8205/// X*Scale+Offset.
8206///
8207static Value *DecomposeSimpleLinearExpr(Value *Val, unsigned &Scale,
Owen Anderson07cf79e2009-07-06 23:00:19 +00008208 int &Offset, LLVMContext *Context) {
Chris Lattnerf925cbd2009-08-30 18:50:58 +00008209 assert(Val->getType() == Type::getInt32Ty(*Context) &&
8210 "Unexpected allocation size type!");
Reid Spencerb83eb642006-10-20 07:07:24 +00008211 if (ConstantInt *CI = dyn_cast<ConstantInt>(Val)) {
Reid Spencerc5b206b2006-12-31 05:48:39 +00008212 Offset = CI->getZExtValue();
Chris Lattner6a94de22007-10-12 05:30:59 +00008213 Scale = 0;
Owen Anderson1d0be152009-08-13 21:58:54 +00008214 return ConstantInt::get(Type::getInt32Ty(*Context), 0);
Chris Lattner6a94de22007-10-12 05:30:59 +00008215 } else if (BinaryOperator *I = dyn_cast<BinaryOperator>(Val)) {
8216 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
8217 if (I->getOpcode() == Instruction::Shl) {
8218 // This is a value scaled by '1 << the shift amt'.
8219 Scale = 1U << RHS->getZExtValue();
8220 Offset = 0;
8221 return I->getOperand(0);
8222 } else if (I->getOpcode() == Instruction::Mul) {
8223 // This value is scaled by 'RHS'.
8224 Scale = RHS->getZExtValue();
8225 Offset = 0;
8226 return I->getOperand(0);
8227 } else if (I->getOpcode() == Instruction::Add) {
8228 // We have X+C. Check to see if we really have (X*C2)+C1,
8229 // where C1 is divisible by C2.
8230 unsigned SubScale;
8231 Value *SubVal =
Owen Andersond672ecb2009-07-03 00:17:18 +00008232 DecomposeSimpleLinearExpr(I->getOperand(0), SubScale,
8233 Offset, Context);
Chris Lattner6a94de22007-10-12 05:30:59 +00008234 Offset += RHS->getZExtValue();
8235 Scale = SubScale;
8236 return SubVal;
Chris Lattnercfd65102005-10-29 04:36:15 +00008237 }
8238 }
8239 }
8240
8241 // Otherwise, we can't look past this.
8242 Scale = 1;
8243 Offset = 0;
8244 return Val;
8245}
8246
8247
Chris Lattnerb3f83972005-10-24 06:03:58 +00008248/// PromoteCastOfAllocation - If we find a cast of an allocation instruction,
8249/// try to eliminate the cast by moving the type information into the alloc.
Chris Lattnerd3e28342007-04-27 17:44:50 +00008250Instruction *InstCombiner::PromoteCastOfAllocation(BitCastInst &CI,
Victor Hernandez7b929da2009-10-23 21:09:37 +00008251 AllocaInst &AI) {
Chris Lattnerd3e28342007-04-27 17:44:50 +00008252 const PointerType *PTy = cast<PointerType>(CI.getType());
Chris Lattnerb3f83972005-10-24 06:03:58 +00008253
Chris Lattnerf925cbd2009-08-30 18:50:58 +00008254 BuilderTy AllocaBuilder(*Builder);
8255 AllocaBuilder.SetInsertPoint(AI.getParent(), &AI);
8256
Chris Lattnerb53c2382005-10-24 06:22:12 +00008257 // Remove any uses of AI that are dead.
8258 assert(!CI.use_empty() && "Dead instructions should be removed earlier!");
Chris Lattner535014f2007-02-15 22:52:10 +00008259
Chris Lattnerb53c2382005-10-24 06:22:12 +00008260 for (Value::use_iterator UI = AI.use_begin(), E = AI.use_end(); UI != E; ) {
8261 Instruction *User = cast<Instruction>(*UI++);
8262 if (isInstructionTriviallyDead(User)) {
8263 while (UI != E && *UI == User)
8264 ++UI; // If this instruction uses AI more than once, don't break UI.
8265
Chris Lattnerb53c2382005-10-24 06:22:12 +00008266 ++NumDeadInst;
Chris Lattnerbdff5482009-08-23 04:37:46 +00008267 DEBUG(errs() << "IC: DCE: " << *User << '\n');
Chris Lattnerf22a5c62007-03-02 19:59:19 +00008268 EraseInstFromFunction(*User);
Chris Lattnerb53c2382005-10-24 06:22:12 +00008269 }
8270 }
Dan Gohmance9fe9f2009-07-21 23:21:54 +00008271
8272 // This requires TargetData to get the alloca alignment and size information.
8273 if (!TD) return 0;
8274
Chris Lattnerb3f83972005-10-24 06:03:58 +00008275 // Get the type really allocated and the type casted to.
8276 const Type *AllocElTy = AI.getAllocatedType();
8277 const Type *CastElTy = PTy->getElementType();
8278 if (!AllocElTy->isSized() || !CastElTy->isSized()) return 0;
Chris Lattner18e78bb2005-10-24 06:26:18 +00008279
Chris Lattnerd2b7cec2007-02-14 05:52:17 +00008280 unsigned AllocElTyAlign = TD->getABITypeAlignment(AllocElTy);
8281 unsigned CastElTyAlign = TD->getABITypeAlignment(CastElTy);
Chris Lattner18e78bb2005-10-24 06:26:18 +00008282 if (CastElTyAlign < AllocElTyAlign) return 0;
8283
Chris Lattner39387a52005-10-24 06:35:18 +00008284 // If the allocation has multiple uses, only promote it if we are strictly
8285 // increasing the alignment of the resultant allocation. If we keep it the
Dale Johannesena0a66372009-03-05 00:39:02 +00008286 // same, we open the door to infinite loops of various kinds. (A reference
8287 // from a dbg.declare doesn't count as a use for this purpose.)
8288 if (!AI.hasOneUse() && !hasOneUsePlusDeclare(&AI) &&
8289 CastElTyAlign == AllocElTyAlign) return 0;
Chris Lattner39387a52005-10-24 06:35:18 +00008290
Duncan Sands777d2302009-05-09 07:06:46 +00008291 uint64_t AllocElTySize = TD->getTypeAllocSize(AllocElTy);
8292 uint64_t CastElTySize = TD->getTypeAllocSize(CastElTy);
Chris Lattner0ddac2a2005-10-27 05:53:56 +00008293 if (CastElTySize == 0 || AllocElTySize == 0) return 0;
Chris Lattner18e78bb2005-10-24 06:26:18 +00008294
Chris Lattner455fcc82005-10-29 03:19:53 +00008295 // See if we can satisfy the modulus by pulling a scale out of the array
8296 // size argument.
Jeff Cohen86796be2007-04-04 16:58:57 +00008297 unsigned ArraySizeScale;
8298 int ArrayOffset;
Chris Lattnercfd65102005-10-29 04:36:15 +00008299 Value *NumElements = // See if the array size is a decomposable linear expr.
Owen Andersond672ecb2009-07-03 00:17:18 +00008300 DecomposeSimpleLinearExpr(AI.getOperand(0), ArraySizeScale,
8301 ArrayOffset, Context);
Chris Lattnercfd65102005-10-29 04:36:15 +00008302
Chris Lattner455fcc82005-10-29 03:19:53 +00008303 // If we can now satisfy the modulus, by using a non-1 scale, we really can
8304 // do the xform.
Chris Lattnercfd65102005-10-29 04:36:15 +00008305 if ((AllocElTySize*ArraySizeScale) % CastElTySize != 0 ||
8306 (AllocElTySize*ArrayOffset ) % CastElTySize != 0) return 0;
Chris Lattner8142b0a2005-10-27 06:12:00 +00008307
Chris Lattner455fcc82005-10-29 03:19:53 +00008308 unsigned Scale = (AllocElTySize*ArraySizeScale)/CastElTySize;
8309 Value *Amt = 0;
8310 if (Scale == 1) {
8311 Amt = NumElements;
8312 } else {
Owen Anderson1d0be152009-08-13 21:58:54 +00008313 Amt = ConstantInt::get(Type::getInt32Ty(*Context), Scale);
Chris Lattnerf925cbd2009-08-30 18:50:58 +00008314 // Insert before the alloca, not before the cast.
8315 Amt = AllocaBuilder.CreateMul(Amt, NumElements, "tmp");
Chris Lattner0ddac2a2005-10-27 05:53:56 +00008316 }
8317
Jeff Cohen86796be2007-04-04 16:58:57 +00008318 if (int Offset = (AllocElTySize*ArrayOffset)/CastElTySize) {
Owen Anderson1d0be152009-08-13 21:58:54 +00008319 Value *Off = ConstantInt::get(Type::getInt32Ty(*Context), Offset, true);
Chris Lattnerf925cbd2009-08-30 18:50:58 +00008320 Amt = AllocaBuilder.CreateAdd(Amt, Off, "tmp");
Chris Lattnercfd65102005-10-29 04:36:15 +00008321 }
8322
Victor Hernandez7b929da2009-10-23 21:09:37 +00008323 AllocaInst *New = AllocaBuilder.CreateAlloca(CastElTy, Amt);
Chris Lattnerf925cbd2009-08-30 18:50:58 +00008324 New->setAlignment(AI.getAlignment());
Chris Lattner6934a042007-02-11 01:23:03 +00008325 New->takeName(&AI);
Chris Lattner39387a52005-10-24 06:35:18 +00008326
Dale Johannesena0a66372009-03-05 00:39:02 +00008327 // If the allocation has one real use plus a dbg.declare, just remove the
8328 // declare.
8329 if (DbgDeclareInst *DI = hasOneUsePlusDeclare(&AI)) {
8330 EraseInstFromFunction(*DI);
8331 }
8332 // If the allocation has multiple real uses, insert a cast and change all
8333 // things that used it to use the new cast. This will also hack on CI, but it
8334 // will die soon.
8335 else if (!AI.hasOneUse()) {
Reid Spencer3da59db2006-11-27 01:05:10 +00008336 // New is the allocation instruction, pointer typed. AI is the original
8337 // allocation instruction, also pointer typed. Thus, cast to use is BitCast.
Chris Lattnerf925cbd2009-08-30 18:50:58 +00008338 Value *NewCast = AllocaBuilder.CreateBitCast(New, AI.getType(), "tmpcast");
Chris Lattner39387a52005-10-24 06:35:18 +00008339 AI.replaceAllUsesWith(NewCast);
8340 }
Chris Lattnerb3f83972005-10-24 06:03:58 +00008341 return ReplaceInstUsesWith(CI, New);
8342}
8343
Chris Lattner70074e02006-05-13 02:06:03 +00008344/// CanEvaluateInDifferentType - Return true if we can take the specified value
Chris Lattnerc739cd62007-03-03 05:27:34 +00008345/// and return it as type Ty without inserting any new casts and without
8346/// changing the computed value. This is used by code that tries to decide
8347/// whether promoting or shrinking integer operations to wider or smaller types
8348/// will allow us to eliminate a truncate or extend.
8349///
8350/// This is a truncation operation if Ty is smaller than V->getType(), or an
8351/// extension operation if Ty is larger.
Chris Lattner8114b712008-06-18 04:00:49 +00008352///
8353/// If CastOpc is a truncation, then Ty will be a type smaller than V. We
8354/// should return true if trunc(V) can be computed by computing V in the smaller
8355/// type. If V is an instruction, then trunc(inst(x,y)) can be computed as
8356/// inst(trunc(x),trunc(y)), which only makes sense if x and y can be
8357/// efficiently truncated.
8358///
8359/// If CastOpc is a sext or zext, we are asking if the low bits of the value can
8360/// bit computed in a larger type, which is then and'd or sext_in_reg'd to get
8361/// the final result.
Dan Gohman6de29f82009-06-15 22:12:54 +00008362bool InstCombiner::CanEvaluateInDifferentType(Value *V, const Type *Ty,
Evan Cheng4e56ab22009-01-16 02:11:43 +00008363 unsigned CastOpc,
8364 int &NumCastsRemoved){
Chris Lattnerc739cd62007-03-03 05:27:34 +00008365 // We can always evaluate constants in another type.
Dan Gohman6de29f82009-06-15 22:12:54 +00008366 if (isa<Constant>(V))
Chris Lattnerc739cd62007-03-03 05:27:34 +00008367 return true;
Chris Lattner70074e02006-05-13 02:06:03 +00008368
8369 Instruction *I = dyn_cast<Instruction>(V);
Chris Lattnerc739cd62007-03-03 05:27:34 +00008370 if (!I) return false;
8371
Dan Gohman6de29f82009-06-15 22:12:54 +00008372 const Type *OrigTy = V->getType();
Chris Lattner70074e02006-05-13 02:06:03 +00008373
Chris Lattner951626b2007-08-02 06:11:14 +00008374 // If this is an extension or truncate, we can often eliminate it.
8375 if (isa<TruncInst>(I) || isa<ZExtInst>(I) || isa<SExtInst>(I)) {
8376 // If this is a cast from the destination type, we can trivially eliminate
8377 // it, and this will remove a cast overall.
8378 if (I->getOperand(0)->getType() == Ty) {
8379 // If the first operand is itself a cast, and is eliminable, do not count
8380 // this as an eliminable cast. We would prefer to eliminate those two
8381 // casts first.
Chris Lattner8114b712008-06-18 04:00:49 +00008382 if (!isa<CastInst>(I->getOperand(0)) && I->hasOneUse())
Chris Lattner951626b2007-08-02 06:11:14 +00008383 ++NumCastsRemoved;
8384 return true;
8385 }
8386 }
8387
8388 // We can't extend or shrink something that has multiple uses: doing so would
8389 // require duplicating the instruction in general, which isn't profitable.
8390 if (!I->hasOneUse()) return false;
8391
Evan Chengf35fd542009-01-15 17:01:23 +00008392 unsigned Opc = I->getOpcode();
8393 switch (Opc) {
Chris Lattnerc739cd62007-03-03 05:27:34 +00008394 case Instruction::Add:
8395 case Instruction::Sub:
Nick Lewyckyb8cd6a42008-07-05 21:19:34 +00008396 case Instruction::Mul:
Chris Lattner70074e02006-05-13 02:06:03 +00008397 case Instruction::And:
8398 case Instruction::Or:
8399 case Instruction::Xor:
8400 // These operators can all arbitrarily be extended or truncated.
Chris Lattner951626b2007-08-02 06:11:14 +00008401 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
Evan Cheng4e56ab22009-01-16 02:11:43 +00008402 NumCastsRemoved) &&
Chris Lattner951626b2007-08-02 06:11:14 +00008403 CanEvaluateInDifferentType(I->getOperand(1), Ty, CastOpc,
Evan Cheng4e56ab22009-01-16 02:11:43 +00008404 NumCastsRemoved);
Chris Lattnerc739cd62007-03-03 05:27:34 +00008405
Eli Friedman070a9812009-07-13 22:46:01 +00008406 case Instruction::UDiv:
8407 case Instruction::URem: {
8408 // UDiv and URem can be truncated if all the truncated bits are zero.
8409 uint32_t OrigBitWidth = OrigTy->getScalarSizeInBits();
8410 uint32_t BitWidth = Ty->getScalarSizeInBits();
8411 if (BitWidth < OrigBitWidth) {
8412 APInt Mask = APInt::getHighBitsSet(OrigBitWidth, OrigBitWidth-BitWidth);
8413 if (MaskedValueIsZero(I->getOperand(0), Mask) &&
8414 MaskedValueIsZero(I->getOperand(1), Mask)) {
8415 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
8416 NumCastsRemoved) &&
8417 CanEvaluateInDifferentType(I->getOperand(1), Ty, CastOpc,
8418 NumCastsRemoved);
8419 }
8420 }
8421 break;
8422 }
Chris Lattner46b96052006-11-29 07:18:39 +00008423 case Instruction::Shl:
Chris Lattnerc739cd62007-03-03 05:27:34 +00008424 // If we are truncating the result of this SHL, and if it's a shift of a
8425 // constant amount, we can always perform a SHL in a smaller type.
8426 if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
Dan Gohman6de29f82009-06-15 22:12:54 +00008427 uint32_t BitWidth = Ty->getScalarSizeInBits();
8428 if (BitWidth < OrigTy->getScalarSizeInBits() &&
Zhou Sheng302748d2007-03-30 17:20:39 +00008429 CI->getLimitedValue(BitWidth) < BitWidth)
Chris Lattner951626b2007-08-02 06:11:14 +00008430 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
Evan Cheng4e56ab22009-01-16 02:11:43 +00008431 NumCastsRemoved);
Chris Lattnerc739cd62007-03-03 05:27:34 +00008432 }
8433 break;
8434 case Instruction::LShr:
Chris Lattnerc739cd62007-03-03 05:27:34 +00008435 // If this is a truncate of a logical shr, we can truncate it to a smaller
8436 // lshr iff we know that the bits we would otherwise be shifting in are
8437 // already zeros.
8438 if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
Dan Gohman6de29f82009-06-15 22:12:54 +00008439 uint32_t OrigBitWidth = OrigTy->getScalarSizeInBits();
8440 uint32_t BitWidth = Ty->getScalarSizeInBits();
Zhou Sheng302748d2007-03-30 17:20:39 +00008441 if (BitWidth < OrigBitWidth &&
Chris Lattnerc739cd62007-03-03 05:27:34 +00008442 MaskedValueIsZero(I->getOperand(0),
Zhou Sheng302748d2007-03-30 17:20:39 +00008443 APInt::getHighBitsSet(OrigBitWidth, OrigBitWidth-BitWidth)) &&
8444 CI->getLimitedValue(BitWidth) < BitWidth) {
Chris Lattner951626b2007-08-02 06:11:14 +00008445 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
Evan Cheng4e56ab22009-01-16 02:11:43 +00008446 NumCastsRemoved);
Chris Lattnerc739cd62007-03-03 05:27:34 +00008447 }
8448 }
Chris Lattner46b96052006-11-29 07:18:39 +00008449 break;
Reid Spencer3da59db2006-11-27 01:05:10 +00008450 case Instruction::ZExt:
8451 case Instruction::SExt:
Chris Lattner951626b2007-08-02 06:11:14 +00008452 case Instruction::Trunc:
8453 // If this is the same kind of case as our original (e.g. zext+zext), we
Chris Lattner5543a852007-08-02 17:23:38 +00008454 // can safely replace it. Note that replacing it does not reduce the number
8455 // of casts in the input.
Evan Chengf35fd542009-01-15 17:01:23 +00008456 if (Opc == CastOpc)
8457 return true;
8458
8459 // sext (zext ty1), ty2 -> zext ty2
Evan Cheng661d9c32009-01-15 17:09:07 +00008460 if (CastOpc == Instruction::SExt && Opc == Instruction::ZExt)
Chris Lattner70074e02006-05-13 02:06:03 +00008461 return true;
Reid Spencer3da59db2006-11-27 01:05:10 +00008462 break;
Nick Lewyckyb8cd6a42008-07-05 21:19:34 +00008463 case Instruction::Select: {
8464 SelectInst *SI = cast<SelectInst>(I);
8465 return CanEvaluateInDifferentType(SI->getTrueValue(), Ty, CastOpc,
Evan Cheng4e56ab22009-01-16 02:11:43 +00008466 NumCastsRemoved) &&
Nick Lewyckyb8cd6a42008-07-05 21:19:34 +00008467 CanEvaluateInDifferentType(SI->getFalseValue(), Ty, CastOpc,
Evan Cheng4e56ab22009-01-16 02:11:43 +00008468 NumCastsRemoved);
Nick Lewyckyb8cd6a42008-07-05 21:19:34 +00008469 }
Chris Lattner8114b712008-06-18 04:00:49 +00008470 case Instruction::PHI: {
8471 // We can change a phi if we can change all operands.
8472 PHINode *PN = cast<PHINode>(I);
8473 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
8474 if (!CanEvaluateInDifferentType(PN->getIncomingValue(i), Ty, CastOpc,
Evan Cheng4e56ab22009-01-16 02:11:43 +00008475 NumCastsRemoved))
Chris Lattner8114b712008-06-18 04:00:49 +00008476 return false;
8477 return true;
8478 }
Reid Spencer3da59db2006-11-27 01:05:10 +00008479 default:
Chris Lattner70074e02006-05-13 02:06:03 +00008480 // TODO: Can handle more cases here.
8481 break;
8482 }
8483
8484 return false;
8485}
8486
8487/// EvaluateInDifferentType - Given an expression that
8488/// CanEvaluateInDifferentType returns true for, actually insert the code to
8489/// evaluate the expression.
Reid Spencerc55b2432006-12-13 18:21:21 +00008490Value *InstCombiner::EvaluateInDifferentType(Value *V, const Type *Ty,
Chris Lattnerc739cd62007-03-03 05:27:34 +00008491 bool isSigned) {
Chris Lattner70074e02006-05-13 02:06:03 +00008492 if (Constant *C = dyn_cast<Constant>(V))
Chris Lattner9956c052009-11-08 19:23:30 +00008493 return ConstantExpr::getIntegerCast(C, Ty, isSigned /*Sext or ZExt*/);
Chris Lattner70074e02006-05-13 02:06:03 +00008494
8495 // Otherwise, it must be an instruction.
8496 Instruction *I = cast<Instruction>(V);
Chris Lattner01859e82006-05-20 23:14:03 +00008497 Instruction *Res = 0;
Evan Chengf35fd542009-01-15 17:01:23 +00008498 unsigned Opc = I->getOpcode();
8499 switch (Opc) {
Chris Lattnerc739cd62007-03-03 05:27:34 +00008500 case Instruction::Add:
8501 case Instruction::Sub:
Nick Lewyckye6b0c002008-01-22 05:08:48 +00008502 case Instruction::Mul:
Chris Lattner70074e02006-05-13 02:06:03 +00008503 case Instruction::And:
8504 case Instruction::Or:
Chris Lattnerc739cd62007-03-03 05:27:34 +00008505 case Instruction::Xor:
Chris Lattner46b96052006-11-29 07:18:39 +00008506 case Instruction::AShr:
8507 case Instruction::LShr:
Eli Friedman070a9812009-07-13 22:46:01 +00008508 case Instruction::Shl:
8509 case Instruction::UDiv:
8510 case Instruction::URem: {
Reid Spencerc55b2432006-12-13 18:21:21 +00008511 Value *LHS = EvaluateInDifferentType(I->getOperand(0), Ty, isSigned);
Chris Lattnerc739cd62007-03-03 05:27:34 +00008512 Value *RHS = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned);
Evan Chengf35fd542009-01-15 17:01:23 +00008513 Res = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
Chris Lattner46b96052006-11-29 07:18:39 +00008514 break;
8515 }
Reid Spencer3da59db2006-11-27 01:05:10 +00008516 case Instruction::Trunc:
8517 case Instruction::ZExt:
8518 case Instruction::SExt:
Reid Spencer3da59db2006-11-27 01:05:10 +00008519 // If the source type of the cast is the type we're trying for then we can
Chris Lattner951626b2007-08-02 06:11:14 +00008520 // just return the source. There's no need to insert it because it is not
8521 // new.
Chris Lattner70074e02006-05-13 02:06:03 +00008522 if (I->getOperand(0)->getType() == Ty)
8523 return I->getOperand(0);
8524
Chris Lattner8114b712008-06-18 04:00:49 +00008525 // Otherwise, must be the same type of cast, so just reinsert a new one.
Chris Lattner9956c052009-11-08 19:23:30 +00008526 Res = CastInst::Create(cast<CastInst>(I)->getOpcode(), I->getOperand(0),Ty);
Chris Lattner951626b2007-08-02 06:11:14 +00008527 break;
Nick Lewyckyb8cd6a42008-07-05 21:19:34 +00008528 case Instruction::Select: {
8529 Value *True = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned);
8530 Value *False = EvaluateInDifferentType(I->getOperand(2), Ty, isSigned);
8531 Res = SelectInst::Create(I->getOperand(0), True, False);
8532 break;
8533 }
Chris Lattner8114b712008-06-18 04:00:49 +00008534 case Instruction::PHI: {
8535 PHINode *OPN = cast<PHINode>(I);
8536 PHINode *NPN = PHINode::Create(Ty);
8537 for (unsigned i = 0, e = OPN->getNumIncomingValues(); i != e; ++i) {
8538 Value *V =EvaluateInDifferentType(OPN->getIncomingValue(i), Ty, isSigned);
8539 NPN->addIncoming(V, OPN->getIncomingBlock(i));
8540 }
8541 Res = NPN;
8542 break;
8543 }
Reid Spencer3da59db2006-11-27 01:05:10 +00008544 default:
Chris Lattner70074e02006-05-13 02:06:03 +00008545 // TODO: Can handle more cases here.
Torok Edwinc23197a2009-07-14 16:55:14 +00008546 llvm_unreachable("Unreachable!");
Chris Lattner70074e02006-05-13 02:06:03 +00008547 break;
8548 }
8549
Chris Lattner8114b712008-06-18 04:00:49 +00008550 Res->takeName(I);
Chris Lattner70074e02006-05-13 02:06:03 +00008551 return InsertNewInstBefore(Res, *I);
8552}
8553
Reid Spencer3da59db2006-11-27 01:05:10 +00008554/// @brief Implement the transforms common to all CastInst visitors.
8555Instruction *InstCombiner::commonCastTransforms(CastInst &CI) {
Chris Lattner79d35b32003-06-23 21:59:52 +00008556 Value *Src = CI.getOperand(0);
8557
Dan Gohman23d9d272007-05-11 21:10:54 +00008558 // Many cases of "cast of a cast" are eliminable. If it's eliminable we just
Reid Spencer3da59db2006-11-27 01:05:10 +00008559 // eliminate it now.
Chris Lattner6e7ba452005-01-01 16:22:27 +00008560 if (CastInst *CSrc = dyn_cast<CastInst>(Src)) { // A->B->C cast
Reid Spencer3da59db2006-11-27 01:05:10 +00008561 if (Instruction::CastOps opc =
8562 isEliminableCastPair(CSrc, CI.getOpcode(), CI.getType(), TD)) {
8563 // The first cast (CSrc) is eliminable so we need to fix up or replace
8564 // the second cast (CI). CSrc will then have a good chance of being dead.
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008565 return CastInst::Create(opc, CSrc->getOperand(0), CI.getType());
Chris Lattner8fd217c2002-08-02 20:00:25 +00008566 }
8567 }
Chris Lattnera710ddc2004-05-25 04:29:21 +00008568
Reid Spencer3da59db2006-11-27 01:05:10 +00008569 // If we are casting a select then fold the cast into the select
Chris Lattner6e7ba452005-01-01 16:22:27 +00008570 if (SelectInst *SI = dyn_cast<SelectInst>(Src))
8571 if (Instruction *NV = FoldOpIntoSelect(CI, SI, this))
8572 return NV;
Reid Spencer3da59db2006-11-27 01:05:10 +00008573
8574 // If we are casting a PHI then fold the cast into the PHI
Chris Lattner9956c052009-11-08 19:23:30 +00008575 if (isa<PHINode>(Src)) {
8576 // We don't do this if this would create a PHI node with an illegal type if
8577 // it is currently legal.
8578 if (!isa<IntegerType>(Src->getType()) ||
8579 !isa<IntegerType>(CI.getType()) ||
Chris Lattnerc22d4d12009-11-10 07:23:37 +00008580 ShouldChangeType(CI.getType(), Src->getType(), TD))
Chris Lattner9956c052009-11-08 19:23:30 +00008581 if (Instruction *NV = FoldOpIntoPhi(CI))
8582 return NV;
Chris Lattner9956c052009-11-08 19:23:30 +00008583 }
Chris Lattner9fb92132006-04-12 18:09:35 +00008584
Reid Spencer3da59db2006-11-27 01:05:10 +00008585 return 0;
8586}
8587
Chris Lattner46cd5a12009-01-09 05:44:56 +00008588/// FindElementAtOffset - Given a type and a constant offset, determine whether
8589/// or not there is a sequence of GEP indices into the type that will land us at
Chris Lattner3914f722009-01-24 01:00:13 +00008590/// the specified offset. If so, fill them into NewIndices and return the
8591/// resultant element type, otherwise return null.
8592static const Type *FindElementAtOffset(const Type *Ty, int64_t Offset,
8593 SmallVectorImpl<Value*> &NewIndices,
Owen Andersond672ecb2009-07-03 00:17:18 +00008594 const TargetData *TD,
Owen Anderson07cf79e2009-07-06 23:00:19 +00008595 LLVMContext *Context) {
Dan Gohmance9fe9f2009-07-21 23:21:54 +00008596 if (!TD) return 0;
Chris Lattner3914f722009-01-24 01:00:13 +00008597 if (!Ty->isSized()) return 0;
Chris Lattner46cd5a12009-01-09 05:44:56 +00008598
8599 // Start with the index over the outer type. Note that the type size
8600 // might be zero (even if the offset isn't zero) if the indexed type
8601 // is something like [0 x {int, int}]
Owen Anderson1d0be152009-08-13 21:58:54 +00008602 const Type *IntPtrTy = TD->getIntPtrType(*Context);
Chris Lattner46cd5a12009-01-09 05:44:56 +00008603 int64_t FirstIdx = 0;
Duncan Sands777d2302009-05-09 07:06:46 +00008604 if (int64_t TySize = TD->getTypeAllocSize(Ty)) {
Chris Lattner46cd5a12009-01-09 05:44:56 +00008605 FirstIdx = Offset/TySize;
Chris Lattner31a69cb2009-01-11 20:41:36 +00008606 Offset -= FirstIdx*TySize;
Chris Lattner46cd5a12009-01-09 05:44:56 +00008607
Chris Lattnerdbc3bc22009-01-11 20:15:20 +00008608 // Handle hosts where % returns negative instead of values [0..TySize).
Chris Lattner46cd5a12009-01-09 05:44:56 +00008609 if (Offset < 0) {
8610 --FirstIdx;
8611 Offset += TySize;
8612 assert(Offset >= 0);
8613 }
8614 assert((uint64_t)Offset < (uint64_t)TySize && "Out of range offset");
8615 }
8616
Owen Andersoneed707b2009-07-24 23:12:02 +00008617 NewIndices.push_back(ConstantInt::get(IntPtrTy, FirstIdx));
Chris Lattner46cd5a12009-01-09 05:44:56 +00008618
8619 // Index into the types. If we fail, set OrigBase to null.
8620 while (Offset) {
Chris Lattnerdbc3bc22009-01-11 20:15:20 +00008621 // Indexing into tail padding between struct/array elements.
8622 if (uint64_t(Offset*8) >= TD->getTypeSizeInBits(Ty))
Chris Lattner3914f722009-01-24 01:00:13 +00008623 return 0;
Chris Lattnerdbc3bc22009-01-11 20:15:20 +00008624
Chris Lattner46cd5a12009-01-09 05:44:56 +00008625 if (const StructType *STy = dyn_cast<StructType>(Ty)) {
8626 const StructLayout *SL = TD->getStructLayout(STy);
Chris Lattnerdbc3bc22009-01-11 20:15:20 +00008627 assert(Offset < (int64_t)SL->getSizeInBytes() &&
8628 "Offset must stay within the indexed type");
8629
Chris Lattner46cd5a12009-01-09 05:44:56 +00008630 unsigned Elt = SL->getElementContainingOffset(Offset);
Owen Anderson1d0be152009-08-13 21:58:54 +00008631 NewIndices.push_back(ConstantInt::get(Type::getInt32Ty(*Context), Elt));
Chris Lattner46cd5a12009-01-09 05:44:56 +00008632
8633 Offset -= SL->getElementOffset(Elt);
8634 Ty = STy->getElementType(Elt);
Chris Lattner1c412d92009-01-11 20:23:52 +00008635 } else if (const ArrayType *AT = dyn_cast<ArrayType>(Ty)) {
Duncan Sands777d2302009-05-09 07:06:46 +00008636 uint64_t EltSize = TD->getTypeAllocSize(AT->getElementType());
Chris Lattnerdbc3bc22009-01-11 20:15:20 +00008637 assert(EltSize && "Cannot index into a zero-sized array");
Owen Andersoneed707b2009-07-24 23:12:02 +00008638 NewIndices.push_back(ConstantInt::get(IntPtrTy,Offset/EltSize));
Chris Lattnerdbc3bc22009-01-11 20:15:20 +00008639 Offset %= EltSize;
Chris Lattner1c412d92009-01-11 20:23:52 +00008640 Ty = AT->getElementType();
Chris Lattner46cd5a12009-01-09 05:44:56 +00008641 } else {
Chris Lattnerdbc3bc22009-01-11 20:15:20 +00008642 // Otherwise, we can't index into the middle of this atomic type, bail.
Chris Lattner3914f722009-01-24 01:00:13 +00008643 return 0;
Chris Lattner46cd5a12009-01-09 05:44:56 +00008644 }
8645 }
8646
Chris Lattner3914f722009-01-24 01:00:13 +00008647 return Ty;
Chris Lattner46cd5a12009-01-09 05:44:56 +00008648}
8649
Chris Lattnerd3e28342007-04-27 17:44:50 +00008650/// @brief Implement the transforms for cast of pointer (bitcast/ptrtoint)
8651Instruction *InstCombiner::commonPointerCastTransforms(CastInst &CI) {
8652 Value *Src = CI.getOperand(0);
8653
Chris Lattnerd3e28342007-04-27 17:44:50 +00008654 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Src)) {
Chris Lattner9bc14642007-04-28 00:57:34 +00008655 // If casting the result of a getelementptr instruction with no offset, turn
8656 // this into a cast of the original pointer!
Chris Lattnerd3e28342007-04-27 17:44:50 +00008657 if (GEP->hasAllZeroIndices()) {
8658 // Changing the cast operand is usually not a good idea but it is safe
8659 // here because the pointer operand is being replaced with another
8660 // pointer operand so the opcode doesn't need to change.
Chris Lattner7a1e9242009-08-30 06:13:40 +00008661 Worklist.Add(GEP);
Chris Lattnerd3e28342007-04-27 17:44:50 +00008662 CI.setOperand(0, GEP->getOperand(0));
8663 return &CI;
8664 }
Chris Lattner9bc14642007-04-28 00:57:34 +00008665
8666 // If the GEP has a single use, and the base pointer is a bitcast, and the
8667 // GEP computes a constant offset, see if we can convert these three
8668 // instructions into fewer. This typically happens with unions and other
8669 // non-type-safe code.
Dan Gohmance9fe9f2009-07-21 23:21:54 +00008670 if (TD && GEP->hasOneUse() && isa<BitCastInst>(GEP->getOperand(0))) {
Chris Lattner9bc14642007-04-28 00:57:34 +00008671 if (GEP->hasAllConstantIndices()) {
8672 // We are guaranteed to get a constant from EmitGEPOffset.
Chris Lattner092543c2009-11-04 08:05:20 +00008673 ConstantInt *OffsetV = cast<ConstantInt>(EmitGEPOffset(GEP, *this));
Chris Lattner9bc14642007-04-28 00:57:34 +00008674 int64_t Offset = OffsetV->getSExtValue();
8675
8676 // Get the base pointer input of the bitcast, and the type it points to.
8677 Value *OrigBase = cast<BitCastInst>(GEP->getOperand(0))->getOperand(0);
8678 const Type *GEPIdxTy =
8679 cast<PointerType>(OrigBase->getType())->getElementType();
Chris Lattner46cd5a12009-01-09 05:44:56 +00008680 SmallVector<Value*, 8> NewIndices;
Owen Andersond672ecb2009-07-03 00:17:18 +00008681 if (FindElementAtOffset(GEPIdxTy, Offset, NewIndices, TD, Context)) {
Chris Lattner46cd5a12009-01-09 05:44:56 +00008682 // If we were able to index down into an element, create the GEP
8683 // and bitcast the result. This eliminates one bitcast, potentially
8684 // two.
Dan Gohmanf8dbee72009-09-07 23:54:19 +00008685 Value *NGEP = cast<GEPOperator>(GEP)->isInBounds() ?
8686 Builder->CreateInBoundsGEP(OrigBase,
8687 NewIndices.begin(), NewIndices.end()) :
8688 Builder->CreateGEP(OrigBase, NewIndices.begin(), NewIndices.end());
Chris Lattner46cd5a12009-01-09 05:44:56 +00008689 NGEP->takeName(GEP);
Chris Lattner9bc14642007-04-28 00:57:34 +00008690
Chris Lattner46cd5a12009-01-09 05:44:56 +00008691 if (isa<BitCastInst>(CI))
8692 return new BitCastInst(NGEP, CI.getType());
8693 assert(isa<PtrToIntInst>(CI));
8694 return new PtrToIntInst(NGEP, CI.getType());
Chris Lattner9bc14642007-04-28 00:57:34 +00008695 }
8696 }
8697 }
Chris Lattnerd3e28342007-04-27 17:44:50 +00008698 }
8699
8700 return commonCastTransforms(CI);
8701}
8702
Eli Friedmaneb7f7a82009-07-13 20:58:59 +00008703/// commonIntCastTransforms - This function implements the common transforms
8704/// for trunc, zext, and sext.
Reid Spencer3da59db2006-11-27 01:05:10 +00008705Instruction *InstCombiner::commonIntCastTransforms(CastInst &CI) {
8706 if (Instruction *Result = commonCastTransforms(CI))
8707 return Result;
8708
8709 Value *Src = CI.getOperand(0);
8710 const Type *SrcTy = Src->getType();
8711 const Type *DestTy = CI.getType();
Dan Gohman6de29f82009-06-15 22:12:54 +00008712 uint32_t SrcBitSize = SrcTy->getScalarSizeInBits();
8713 uint32_t DestBitSize = DestTy->getScalarSizeInBits();
Reid Spencer3da59db2006-11-27 01:05:10 +00008714
Reid Spencer3da59db2006-11-27 01:05:10 +00008715 // See if we can simplify any instructions used by the LHS whose sole
8716 // purpose is to compute bits we don't care about.
Chris Lattner886ab6c2009-01-31 08:15:18 +00008717 if (SimplifyDemandedInstructionBits(CI))
Reid Spencer3da59db2006-11-27 01:05:10 +00008718 return &CI;
8719
8720 // If the source isn't an instruction or has more than one use then we
8721 // can't do anything more.
Reid Spencere4d87aa2006-12-23 06:05:41 +00008722 Instruction *SrcI = dyn_cast<Instruction>(Src);
8723 if (!SrcI || !Src->hasOneUse())
Reid Spencer3da59db2006-11-27 01:05:10 +00008724 return 0;
8725
Chris Lattnerc739cd62007-03-03 05:27:34 +00008726 // Attempt to propagate the cast into the instruction for int->int casts.
Reid Spencer3da59db2006-11-27 01:05:10 +00008727 int NumCastsRemoved = 0;
Eli Friedman65445c52009-07-13 21:45:57 +00008728 // Only do this if the dest type is a simple type, don't convert the
8729 // expression tree to something weird like i93 unless the source is also
8730 // strange.
Chris Lattner6b583912009-11-10 17:00:47 +00008731 if ((isa<VectorType>(DestTy) ||
8732 ShouldChangeType(SrcI->getType(), DestTy, TD)) &&
8733 CanEvaluateInDifferentType(SrcI, DestTy,
8734 CI.getOpcode(), NumCastsRemoved)) {
Reid Spencer3da59db2006-11-27 01:05:10 +00008735 // If this cast is a truncate, evaluting in a different type always
Chris Lattner951626b2007-08-02 06:11:14 +00008736 // eliminates the cast, so it is always a win. If this is a zero-extension,
8737 // we need to do an AND to maintain the clear top-part of the computation,
8738 // so we require that the input have eliminated at least one cast. If this
8739 // is a sign extension, we insert two new casts (to do the extension) so we
Reid Spencer3da59db2006-11-27 01:05:10 +00008740 // require that two casts have been eliminated.
Evan Chengf35fd542009-01-15 17:01:23 +00008741 bool DoXForm = false;
8742 bool JustReplace = false;
Chris Lattnerc739cd62007-03-03 05:27:34 +00008743 switch (CI.getOpcode()) {
8744 default:
8745 // All the others use floating point so we shouldn't actually
8746 // get here because of the check above.
Torok Edwinc23197a2009-07-14 16:55:14 +00008747 llvm_unreachable("Unknown cast type");
Chris Lattnerc739cd62007-03-03 05:27:34 +00008748 case Instruction::Trunc:
8749 DoXForm = true;
8750 break;
Evan Cheng4e56ab22009-01-16 02:11:43 +00008751 case Instruction::ZExt: {
Chris Lattnerc739cd62007-03-03 05:27:34 +00008752 DoXForm = NumCastsRemoved >= 1;
Chris Lattner918871e2009-11-07 19:11:46 +00008753
Chris Lattner39c27ed2009-01-31 19:05:27 +00008754 if (!DoXForm && 0) {
Evan Cheng4e56ab22009-01-16 02:11:43 +00008755 // If it's unnecessary to issue an AND to clear the high bits, it's
8756 // always profitable to do this xform.
Chris Lattner39c27ed2009-01-31 19:05:27 +00008757 Value *TryRes = EvaluateInDifferentType(SrcI, DestTy, false);
Evan Cheng4e56ab22009-01-16 02:11:43 +00008758 APInt Mask(APInt::getBitsSet(DestBitSize, SrcBitSize, DestBitSize));
8759 if (MaskedValueIsZero(TryRes, Mask))
8760 return ReplaceInstUsesWith(CI, TryRes);
Chris Lattner39c27ed2009-01-31 19:05:27 +00008761
8762 if (Instruction *TryI = dyn_cast<Instruction>(TryRes))
Evan Cheng4e56ab22009-01-16 02:11:43 +00008763 if (TryI->use_empty())
8764 EraseInstFromFunction(*TryI);
8765 }
Chris Lattnerc739cd62007-03-03 05:27:34 +00008766 break;
Evan Cheng4e56ab22009-01-16 02:11:43 +00008767 }
Evan Chengf35fd542009-01-15 17:01:23 +00008768 case Instruction::SExt: {
Chris Lattnerc739cd62007-03-03 05:27:34 +00008769 DoXForm = NumCastsRemoved >= 2;
Chris Lattner39c27ed2009-01-31 19:05:27 +00008770 if (!DoXForm && !isa<TruncInst>(SrcI) && 0) {
Evan Cheng4e56ab22009-01-16 02:11:43 +00008771 // If we do not have to emit the truncate + sext pair, then it's always
8772 // profitable to do this xform.
Evan Chengf35fd542009-01-15 17:01:23 +00008773 //
8774 // It's not safe to eliminate the trunc + sext pair if one of the
8775 // eliminated cast is a truncate. e.g.
8776 // t2 = trunc i32 t1 to i16
8777 // t3 = sext i16 t2 to i32
8778 // !=
8779 // i32 t1
Chris Lattner39c27ed2009-01-31 19:05:27 +00008780 Value *TryRes = EvaluateInDifferentType(SrcI, DestTy, true);
Evan Cheng4e56ab22009-01-16 02:11:43 +00008781 unsigned NumSignBits = ComputeNumSignBits(TryRes);
8782 if (NumSignBits > (DestBitSize - SrcBitSize))
8783 return ReplaceInstUsesWith(CI, TryRes);
Chris Lattner39c27ed2009-01-31 19:05:27 +00008784
8785 if (Instruction *TryI = dyn_cast<Instruction>(TryRes))
Evan Cheng4e56ab22009-01-16 02:11:43 +00008786 if (TryI->use_empty())
8787 EraseInstFromFunction(*TryI);
Evan Chengf35fd542009-01-15 17:01:23 +00008788 }
Chris Lattnerc739cd62007-03-03 05:27:34 +00008789 break;
Reid Spencer3da59db2006-11-27 01:05:10 +00008790 }
Evan Chengf35fd542009-01-15 17:01:23 +00008791 }
Reid Spencer3da59db2006-11-27 01:05:10 +00008792
8793 if (DoXForm) {
Chris Lattnerbdff5482009-08-23 04:37:46 +00008794 DEBUG(errs() << "ICE: EvaluateInDifferentType converting expression type"
8795 " to avoid cast: " << CI);
Reid Spencerc55b2432006-12-13 18:21:21 +00008796 Value *Res = EvaluateInDifferentType(SrcI, DestTy,
8797 CI.getOpcode() == Instruction::SExt);
Evan Cheng4e56ab22009-01-16 02:11:43 +00008798 if (JustReplace)
Chris Lattner39c27ed2009-01-31 19:05:27 +00008799 // Just replace this cast with the result.
8800 return ReplaceInstUsesWith(CI, Res);
Evan Cheng4e56ab22009-01-16 02:11:43 +00008801
Reid Spencer3da59db2006-11-27 01:05:10 +00008802 assert(Res->getType() == DestTy);
8803 switch (CI.getOpcode()) {
Torok Edwinc23197a2009-07-14 16:55:14 +00008804 default: llvm_unreachable("Unknown cast type!");
Reid Spencer3da59db2006-11-27 01:05:10 +00008805 case Instruction::Trunc:
Reid Spencer3da59db2006-11-27 01:05:10 +00008806 // Just replace this cast with the result.
8807 return ReplaceInstUsesWith(CI, Res);
8808 case Instruction::ZExt: {
Reid Spencer3da59db2006-11-27 01:05:10 +00008809 assert(SrcBitSize < DestBitSize && "Not a zext?");
Evan Cheng4e56ab22009-01-16 02:11:43 +00008810
8811 // If the high bits are already zero, just replace this cast with the
8812 // result.
8813 APInt Mask(APInt::getBitsSet(DestBitSize, SrcBitSize, DestBitSize));
8814 if (MaskedValueIsZero(Res, Mask))
8815 return ReplaceInstUsesWith(CI, Res);
8816
8817 // We need to emit an AND to clear the high bits.
Owen Andersoneed707b2009-07-24 23:12:02 +00008818 Constant *C = ConstantInt::get(*Context,
8819 APInt::getLowBitsSet(DestBitSize, SrcBitSize));
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008820 return BinaryOperator::CreateAnd(Res, C);
Reid Spencer3da59db2006-11-27 01:05:10 +00008821 }
Evan Cheng4e56ab22009-01-16 02:11:43 +00008822 case Instruction::SExt: {
8823 // If the high bits are already filled with sign bit, just replace this
8824 // cast with the result.
8825 unsigned NumSignBits = ComputeNumSignBits(Res);
8826 if (NumSignBits > (DestBitSize - SrcBitSize))
Evan Chengf35fd542009-01-15 17:01:23 +00008827 return ReplaceInstUsesWith(CI, Res);
8828
Reid Spencer3da59db2006-11-27 01:05:10 +00008829 // We need to emit a cast to truncate, then a cast to sext.
Chris Lattner2345d1d2009-08-30 20:01:10 +00008830 return new SExtInst(Builder->CreateTrunc(Res, Src->getType()), DestTy);
Reid Spencer3da59db2006-11-27 01:05:10 +00008831 }
Evan Cheng4e56ab22009-01-16 02:11:43 +00008832 }
Reid Spencer3da59db2006-11-27 01:05:10 +00008833 }
8834 }
8835
8836 Value *Op0 = SrcI->getNumOperands() > 0 ? SrcI->getOperand(0) : 0;
8837 Value *Op1 = SrcI->getNumOperands() > 1 ? SrcI->getOperand(1) : 0;
8838
8839 switch (SrcI->getOpcode()) {
8840 case Instruction::Add:
8841 case Instruction::Mul:
8842 case Instruction::And:
8843 case Instruction::Or:
8844 case Instruction::Xor:
Chris Lattner01deb9d2007-04-03 17:43:25 +00008845 // If we are discarding information, rewrite.
Eli Friedman65445c52009-07-13 21:45:57 +00008846 if (DestBitSize < SrcBitSize && DestBitSize != 1) {
8847 // Don't insert two casts unless at least one can be eliminated.
8848 if (!ValueRequiresCast(CI.getOpcode(), Op1, DestTy, TD) ||
Reid Spencere4d87aa2006-12-23 06:05:41 +00008849 !ValueRequiresCast(CI.getOpcode(), Op0, DestTy, TD)) {
Chris Lattner2345d1d2009-08-30 20:01:10 +00008850 Value *Op0c = Builder->CreateTrunc(Op0, DestTy, Op0->getName());
8851 Value *Op1c = Builder->CreateTrunc(Op1, DestTy, Op1->getName());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008852 return BinaryOperator::Create(
Reid Spencer17212df2006-12-12 09:18:51 +00008853 cast<BinaryOperator>(SrcI)->getOpcode(), Op0c, Op1c);
Reid Spencer3da59db2006-11-27 01:05:10 +00008854 }
8855 }
8856
8857 // cast (xor bool X, true) to int --> xor (cast bool X to int), 1
8858 if (isa<ZExtInst>(CI) && SrcBitSize == 1 &&
8859 SrcI->getOpcode() == Instruction::Xor &&
Owen Anderson5defacc2009-07-31 17:39:07 +00008860 Op1 == ConstantInt::getTrue(*Context) &&
Reid Spencere4d87aa2006-12-23 06:05:41 +00008861 (!Op0->hasOneUse() || !isa<CmpInst>(Op0))) {
Chris Lattner2345d1d2009-08-30 20:01:10 +00008862 Value *New = Builder->CreateZExt(Op0, DestTy, Op0->getName());
Owen Andersond672ecb2009-07-03 00:17:18 +00008863 return BinaryOperator::CreateXor(New,
Owen Andersoneed707b2009-07-24 23:12:02 +00008864 ConstantInt::get(CI.getType(), 1));
Reid Spencer3da59db2006-11-27 01:05:10 +00008865 }
8866 break;
Reid Spencer3da59db2006-11-27 01:05:10 +00008867
Eli Friedman65445c52009-07-13 21:45:57 +00008868 case Instruction::Shl: {
8869 // Canonicalize trunc inside shl, if we can.
8870 ConstantInt *CI = dyn_cast<ConstantInt>(Op1);
8871 if (CI && DestBitSize < SrcBitSize &&
8872 CI->getLimitedValue(DestBitSize) < DestBitSize) {
Chris Lattner2345d1d2009-08-30 20:01:10 +00008873 Value *Op0c = Builder->CreateTrunc(Op0, DestTy, Op0->getName());
8874 Value *Op1c = Builder->CreateTrunc(Op1, DestTy, Op1->getName());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00008875 return BinaryOperator::CreateShl(Op0c, Op1c);
Reid Spencer3da59db2006-11-27 01:05:10 +00008876 }
8877 break;
Eli Friedman65445c52009-07-13 21:45:57 +00008878 }
Reid Spencer3da59db2006-11-27 01:05:10 +00008879 }
8880 return 0;
8881}
8882
Chris Lattner8a9f5712007-04-11 06:57:46 +00008883Instruction *InstCombiner::visitTrunc(TruncInst &CI) {
Chris Lattner6aa5eb12006-11-29 07:04:07 +00008884 if (Instruction *Result = commonIntCastTransforms(CI))
8885 return Result;
8886
8887 Value *Src = CI.getOperand(0);
8888 const Type *Ty = CI.getType();
Dan Gohman6de29f82009-06-15 22:12:54 +00008889 uint32_t DestBitWidth = Ty->getScalarSizeInBits();
8890 uint32_t SrcBitWidth = Src->getType()->getScalarSizeInBits();
Chris Lattner4f9797d2009-03-24 18:15:30 +00008891
8892 // Canonicalize trunc x to i1 -> (icmp ne (and x, 1), 0)
Eli Friedman191a0ae2009-07-18 09:21:25 +00008893 if (DestBitWidth == 1) {
Owen Andersoneed707b2009-07-24 23:12:02 +00008894 Constant *One = ConstantInt::get(Src->getType(), 1);
Chris Lattnerf925cbd2009-08-30 18:50:58 +00008895 Src = Builder->CreateAnd(Src, One, "tmp");
Owen Andersona7235ea2009-07-31 20:28:14 +00008896 Value *Zero = Constant::getNullValue(Src->getType());
Dan Gohman1c8a23c2009-08-25 23:17:54 +00008897 return new ICmpInst(ICmpInst::ICMP_NE, Src, Zero);
Chris Lattner4f9797d2009-03-24 18:15:30 +00008898 }
Dan Gohman6de29f82009-06-15 22:12:54 +00008899
Chris Lattner4f9797d2009-03-24 18:15:30 +00008900 // Optimize trunc(lshr(), c) to pull the shift through the truncate.
8901 ConstantInt *ShAmtV = 0;
8902 Value *ShiftOp = 0;
8903 if (Src->hasOneUse() &&
Dan Gohman4ae51262009-08-12 16:23:25 +00008904 match(Src, m_LShr(m_Value(ShiftOp), m_ConstantInt(ShAmtV)))) {
Chris Lattner4f9797d2009-03-24 18:15:30 +00008905 uint32_t ShAmt = ShAmtV->getLimitedValue(SrcBitWidth);
8906
8907 // Get a mask for the bits shifting in.
8908 APInt Mask(APInt::getLowBitsSet(SrcBitWidth, ShAmt).shl(DestBitWidth));
8909 if (MaskedValueIsZero(ShiftOp, Mask)) {
8910 if (ShAmt >= DestBitWidth) // All zeros.
Owen Andersona7235ea2009-07-31 20:28:14 +00008911 return ReplaceInstUsesWith(CI, Constant::getNullValue(Ty));
Chris Lattner4f9797d2009-03-24 18:15:30 +00008912
8913 // Okay, we can shrink this. Truncate the input, then return a new
8914 // shift.
Chris Lattner2345d1d2009-08-30 20:01:10 +00008915 Value *V1 = Builder->CreateTrunc(ShiftOp, Ty, ShiftOp->getName());
Owen Andersonbaf3c402009-07-29 18:55:55 +00008916 Value *V2 = ConstantExpr::getTrunc(ShAmtV, Ty);
Chris Lattner4f9797d2009-03-24 18:15:30 +00008917 return BinaryOperator::CreateLShr(V1, V2);
Chris Lattner6aa5eb12006-11-29 07:04:07 +00008918 }
8919 }
Chris Lattner9956c052009-11-08 19:23:30 +00008920
Chris Lattner6aa5eb12006-11-29 07:04:07 +00008921 return 0;
Reid Spencer3da59db2006-11-27 01:05:10 +00008922}
8923
Evan Chengb98a10e2008-03-24 00:21:34 +00008924/// transformZExtICmp - Transform (zext icmp) to bitwise / integer operations
8925/// in order to eliminate the icmp.
8926Instruction *InstCombiner::transformZExtICmp(ICmpInst *ICI, Instruction &CI,
8927 bool DoXform) {
8928 // If we are just checking for a icmp eq of a single bit and zext'ing it
8929 // to an integer, then shift the bit to the appropriate place and then
8930 // cast to integer to avoid the comparison.
8931 if (ConstantInt *Op1C = dyn_cast<ConstantInt>(ICI->getOperand(1))) {
8932 const APInt &Op1CV = Op1C->getValue();
8933
8934 // zext (x <s 0) to i32 --> x>>u31 true if signbit set.
8935 // zext (x >s -1) to i32 --> (x>>u31)^1 true if signbit clear.
8936 if ((ICI->getPredicate() == ICmpInst::ICMP_SLT && Op1CV == 0) ||
8937 (ICI->getPredicate() == ICmpInst::ICMP_SGT &&Op1CV.isAllOnesValue())) {
8938 if (!DoXform) return ICI;
8939
8940 Value *In = ICI->getOperand(0);
Owen Andersoneed707b2009-07-24 23:12:02 +00008941 Value *Sh = ConstantInt::get(In->getType(),
Dan Gohman6de29f82009-06-15 22:12:54 +00008942 In->getType()->getScalarSizeInBits()-1);
Chris Lattnerf925cbd2009-08-30 18:50:58 +00008943 In = Builder->CreateLShr(In, Sh, In->getName()+".lobit");
Evan Chengb98a10e2008-03-24 00:21:34 +00008944 if (In->getType() != CI.getType())
Chris Lattnerf925cbd2009-08-30 18:50:58 +00008945 In = Builder->CreateIntCast(In, CI.getType(), false/*ZExt*/, "tmp");
Evan Chengb98a10e2008-03-24 00:21:34 +00008946
8947 if (ICI->getPredicate() == ICmpInst::ICMP_SGT) {
Owen Andersoneed707b2009-07-24 23:12:02 +00008948 Constant *One = ConstantInt::get(In->getType(), 1);
Chris Lattnerf925cbd2009-08-30 18:50:58 +00008949 In = Builder->CreateXor(In, One, In->getName()+".not");
Evan Chengb98a10e2008-03-24 00:21:34 +00008950 }
8951
8952 return ReplaceInstUsesWith(CI, In);
8953 }
8954
8955
8956
8957 // zext (X == 0) to i32 --> X^1 iff X has only the low bit set.
8958 // zext (X == 0) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
8959 // zext (X == 1) to i32 --> X iff X has only the low bit set.
8960 // zext (X == 2) to i32 --> X>>1 iff X has only the 2nd bit set.
8961 // zext (X != 0) to i32 --> X iff X has only the low bit set.
8962 // zext (X != 0) to i32 --> X>>1 iff X has only the 2nd bit set.
8963 // zext (X != 1) to i32 --> X^1 iff X has only the low bit set.
8964 // zext (X != 2) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
8965 if ((Op1CV == 0 || Op1CV.isPowerOf2()) &&
8966 // This only works for EQ and NE
8967 ICI->isEquality()) {
8968 // If Op1C some other power of two, convert:
8969 uint32_t BitWidth = Op1C->getType()->getBitWidth();
8970 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
8971 APInt TypeMask(APInt::getAllOnesValue(BitWidth));
8972 ComputeMaskedBits(ICI->getOperand(0), TypeMask, KnownZero, KnownOne);
8973
8974 APInt KnownZeroMask(~KnownZero);
8975 if (KnownZeroMask.isPowerOf2()) { // Exactly 1 possible 1?
8976 if (!DoXform) return ICI;
8977
8978 bool isNE = ICI->getPredicate() == ICmpInst::ICMP_NE;
8979 if (Op1CV != 0 && (Op1CV != KnownZeroMask)) {
8980 // (X&4) == 2 --> false
8981 // (X&4) != 2 --> true
Owen Anderson1d0be152009-08-13 21:58:54 +00008982 Constant *Res = ConstantInt::get(Type::getInt1Ty(*Context), isNE);
Owen Andersonbaf3c402009-07-29 18:55:55 +00008983 Res = ConstantExpr::getZExt(Res, CI.getType());
Evan Chengb98a10e2008-03-24 00:21:34 +00008984 return ReplaceInstUsesWith(CI, Res);
8985 }
8986
8987 uint32_t ShiftAmt = KnownZeroMask.logBase2();
8988 Value *In = ICI->getOperand(0);
8989 if (ShiftAmt) {
8990 // Perform a logical shr by shiftamt.
8991 // Insert the shift to put the result in the low bit.
Chris Lattnerf925cbd2009-08-30 18:50:58 +00008992 In = Builder->CreateLShr(In, ConstantInt::get(In->getType(),ShiftAmt),
8993 In->getName()+".lobit");
Evan Chengb98a10e2008-03-24 00:21:34 +00008994 }
8995
8996 if ((Op1CV != 0) == isNE) { // Toggle the low bit.
Owen Andersoneed707b2009-07-24 23:12:02 +00008997 Constant *One = ConstantInt::get(In->getType(), 1);
Chris Lattnerf925cbd2009-08-30 18:50:58 +00008998 In = Builder->CreateXor(In, One, "tmp");
Evan Chengb98a10e2008-03-24 00:21:34 +00008999 }
9000
9001 if (CI.getType() == In->getType())
9002 return ReplaceInstUsesWith(CI, In);
9003 else
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009004 return CastInst::CreateIntegerCast(In, CI.getType(), false/*ZExt*/);
Evan Chengb98a10e2008-03-24 00:21:34 +00009005 }
9006 }
9007 }
9008
Nick Lewycky55bd8bd2009-11-23 03:17:33 +00009009 // icmp ne A, B is equal to xor A, B when A and B only really have one bit.
9010 // It is also profitable to transform icmp eq into not(xor(A, B)) because that
9011 // may lead to additional simplifications.
9012 if (ICI->isEquality() && CI.getType() == ICI->getOperand(0)->getType()) {
9013 if (const IntegerType *ITy = dyn_cast<IntegerType>(CI.getType())) {
9014 uint32_t BitWidth = ITy->getBitWidth();
Nick Lewycky83e8ec72009-12-05 05:00:00 +00009015 Value *LHS = ICI->getOperand(0);
9016 Value *RHS = ICI->getOperand(1);
Nick Lewycky55bd8bd2009-11-23 03:17:33 +00009017
Nick Lewycky83e8ec72009-12-05 05:00:00 +00009018 APInt KnownZeroLHS(BitWidth, 0), KnownOneLHS(BitWidth, 0);
9019 APInt KnownZeroRHS(BitWidth, 0), KnownOneRHS(BitWidth, 0);
9020 APInt TypeMask(APInt::getAllOnesValue(BitWidth));
9021 ComputeMaskedBits(LHS, TypeMask, KnownZeroLHS, KnownOneLHS);
9022 ComputeMaskedBits(RHS, TypeMask, KnownZeroRHS, KnownOneRHS);
Nick Lewycky55bd8bd2009-11-23 03:17:33 +00009023
Nick Lewycky83e8ec72009-12-05 05:00:00 +00009024 if (KnownZeroLHS == KnownZeroRHS && KnownOneLHS == KnownOneRHS) {
9025 APInt KnownBits = KnownZeroLHS | KnownOneLHS;
9026 APInt UnknownBit = ~KnownBits;
9027 if (UnknownBit.countPopulation() == 1) {
Nick Lewycky55bd8bd2009-11-23 03:17:33 +00009028 if (!DoXform) return ICI;
9029
Nick Lewycky83e8ec72009-12-05 05:00:00 +00009030 Value *Result = Builder->CreateXor(LHS, RHS);
9031
9032 // Mask off any bits that are set and won't be shifted away.
9033 if (KnownOneLHS.uge(UnknownBit))
9034 Result = Builder->CreateAnd(Result,
9035 ConstantInt::get(ITy, UnknownBit));
9036
9037 // Shift the bit we're testing down to the lsb.
9038 Result = Builder->CreateLShr(
9039 Result, ConstantInt::get(ITy, UnknownBit.countTrailingZeros()));
9040
Nick Lewycky55bd8bd2009-11-23 03:17:33 +00009041 if (ICI->getPredicate() == ICmpInst::ICMP_EQ)
Nick Lewycky83e8ec72009-12-05 05:00:00 +00009042 Result = Builder->CreateXor(Result, ConstantInt::get(ITy, 1));
9043 Result->takeName(ICI);
9044 return ReplaceInstUsesWith(CI, Result);
Nick Lewycky55bd8bd2009-11-23 03:17:33 +00009045 }
9046 }
9047 }
9048 }
9049
Evan Chengb98a10e2008-03-24 00:21:34 +00009050 return 0;
9051}
9052
Chris Lattner8a9f5712007-04-11 06:57:46 +00009053Instruction *InstCombiner::visitZExt(ZExtInst &CI) {
Chris Lattnerdffbef02010-01-04 06:23:24 +00009054 // If one of the common conversion will work, do it.
Reid Spencer3da59db2006-11-27 01:05:10 +00009055 if (Instruction *Result = commonIntCastTransforms(CI))
9056 return Result;
9057
9058 Value *Src = CI.getOperand(0);
9059
Chris Lattnera84f47c2009-02-17 20:47:23 +00009060 // If this is a TRUNC followed by a ZEXT then we are dealing with integral
9061 // types and if the sizes are just right we can convert this into a logical
9062 // 'and' which will be much cheaper than the pair of casts.
9063 if (TruncInst *CSrc = dyn_cast<TruncInst>(Src)) { // A->B->C cast
9064 // Get the sizes of the types involved. We know that the intermediate type
9065 // will be smaller than A or C, but don't know the relation between A and C.
9066 Value *A = CSrc->getOperand(0);
Dan Gohman6de29f82009-06-15 22:12:54 +00009067 unsigned SrcSize = A->getType()->getScalarSizeInBits();
9068 unsigned MidSize = CSrc->getType()->getScalarSizeInBits();
9069 unsigned DstSize = CI.getType()->getScalarSizeInBits();
Chris Lattnera84f47c2009-02-17 20:47:23 +00009070 // If we're actually extending zero bits, then if
9071 // SrcSize < DstSize: zext(a & mask)
9072 // SrcSize == DstSize: a & mask
9073 // SrcSize > DstSize: trunc(a) & mask
9074 if (SrcSize < DstSize) {
9075 APInt AndValue(APInt::getLowBitsSet(SrcSize, MidSize));
Owen Andersoneed707b2009-07-24 23:12:02 +00009076 Constant *AndConst = ConstantInt::get(A->getType(), AndValue);
Chris Lattnerf925cbd2009-08-30 18:50:58 +00009077 Value *And = Builder->CreateAnd(A, AndConst, CSrc->getName()+".mask");
Chris Lattnera84f47c2009-02-17 20:47:23 +00009078 return new ZExtInst(And, CI.getType());
Chris Lattnerf925cbd2009-08-30 18:50:58 +00009079 }
9080
9081 if (SrcSize == DstSize) {
Chris Lattnera84f47c2009-02-17 20:47:23 +00009082 APInt AndValue(APInt::getLowBitsSet(SrcSize, MidSize));
Owen Andersoneed707b2009-07-24 23:12:02 +00009083 return BinaryOperator::CreateAnd(A, ConstantInt::get(A->getType(),
Dan Gohman6de29f82009-06-15 22:12:54 +00009084 AndValue));
Chris Lattnerf925cbd2009-08-30 18:50:58 +00009085 }
9086 if (SrcSize > DstSize) {
9087 Value *Trunc = Builder->CreateTrunc(A, CI.getType(), "tmp");
Chris Lattnera84f47c2009-02-17 20:47:23 +00009088 APInt AndValue(APInt::getLowBitsSet(DstSize, MidSize));
Owen Andersond672ecb2009-07-03 00:17:18 +00009089 return BinaryOperator::CreateAnd(Trunc,
Owen Andersoneed707b2009-07-24 23:12:02 +00009090 ConstantInt::get(Trunc->getType(),
Dan Gohman6de29f82009-06-15 22:12:54 +00009091 AndValue));
Reid Spencer3da59db2006-11-27 01:05:10 +00009092 }
9093 }
9094
Evan Chengb98a10e2008-03-24 00:21:34 +00009095 if (ICmpInst *ICI = dyn_cast<ICmpInst>(Src))
9096 return transformZExtICmp(ICI, CI);
Chris Lattnera2e2c9b2007-04-11 06:53:04 +00009097
Evan Chengb98a10e2008-03-24 00:21:34 +00009098 BinaryOperator *SrcI = dyn_cast<BinaryOperator>(Src);
9099 if (SrcI && SrcI->getOpcode() == Instruction::Or) {
9100 // zext (or icmp, icmp) --> or (zext icmp), (zext icmp) if at least one
9101 // of the (zext icmp) will be transformed.
9102 ICmpInst *LHS = dyn_cast<ICmpInst>(SrcI->getOperand(0));
9103 ICmpInst *RHS = dyn_cast<ICmpInst>(SrcI->getOperand(1));
9104 if (LHS && RHS && LHS->hasOneUse() && RHS->hasOneUse() &&
9105 (transformZExtICmp(LHS, CI, false) ||
9106 transformZExtICmp(RHS, CI, false))) {
Chris Lattner2345d1d2009-08-30 20:01:10 +00009107 Value *LCast = Builder->CreateZExt(LHS, CI.getType(), LHS->getName());
9108 Value *RCast = Builder->CreateZExt(RHS, CI.getType(), RHS->getName());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009109 return BinaryOperator::Create(Instruction::Or, LCast, RCast);
Chris Lattner66bc3252007-04-11 05:45:39 +00009110 }
Evan Chengb98a10e2008-03-24 00:21:34 +00009111 }
9112
Dan Gohmanfd3daa72009-06-18 16:30:21 +00009113 // zext(trunc(t) & C) -> (t & zext(C)).
Dan Gohmana392c782009-06-17 23:17:05 +00009114 if (SrcI && SrcI->getOpcode() == Instruction::And && SrcI->hasOneUse())
9115 if (ConstantInt *C = dyn_cast<ConstantInt>(SrcI->getOperand(1)))
9116 if (TruncInst *TI = dyn_cast<TruncInst>(SrcI->getOperand(0))) {
9117 Value *TI0 = TI->getOperand(0);
Dan Gohmanfd3daa72009-06-18 16:30:21 +00009118 if (TI0->getType() == CI.getType())
9119 return
9120 BinaryOperator::CreateAnd(TI0,
Owen Andersonbaf3c402009-07-29 18:55:55 +00009121 ConstantExpr::getZExt(C, CI.getType()));
Dan Gohmana392c782009-06-17 23:17:05 +00009122 }
9123
Dan Gohmanfd3daa72009-06-18 16:30:21 +00009124 // zext((trunc(t) & C) ^ C) -> ((t & zext(C)) ^ zext(C)).
9125 if (SrcI && SrcI->getOpcode() == Instruction::Xor && SrcI->hasOneUse())
9126 if (ConstantInt *C = dyn_cast<ConstantInt>(SrcI->getOperand(1)))
9127 if (BinaryOperator *And = dyn_cast<BinaryOperator>(SrcI->getOperand(0)))
9128 if (And->getOpcode() == Instruction::And && And->hasOneUse() &&
9129 And->getOperand(1) == C)
9130 if (TruncInst *TI = dyn_cast<TruncInst>(And->getOperand(0))) {
9131 Value *TI0 = TI->getOperand(0);
9132 if (TI0->getType() == CI.getType()) {
Owen Andersonbaf3c402009-07-29 18:55:55 +00009133 Constant *ZC = ConstantExpr::getZExt(C, CI.getType());
Chris Lattnerf925cbd2009-08-30 18:50:58 +00009134 Value *NewAnd = Builder->CreateAnd(TI0, ZC, "tmp");
Dan Gohmanfd3daa72009-06-18 16:30:21 +00009135 return BinaryOperator::CreateXor(NewAnd, ZC);
9136 }
9137 }
9138
Reid Spencer3da59db2006-11-27 01:05:10 +00009139 return 0;
9140}
9141
Chris Lattner8a9f5712007-04-11 06:57:46 +00009142Instruction *InstCombiner::visitSExt(SExtInst &CI) {
Chris Lattnerba417832007-04-11 06:12:58 +00009143 if (Instruction *I = commonIntCastTransforms(CI))
9144 return I;
9145
Chris Lattner8a9f5712007-04-11 06:57:46 +00009146 Value *Src = CI.getOperand(0);
9147
Dan Gohman1975d032008-10-30 20:40:10 +00009148 // Canonicalize sign-extend from i1 to a select.
Owen Anderson1d0be152009-08-13 21:58:54 +00009149 if (Src->getType() == Type::getInt1Ty(*Context))
Dan Gohman1975d032008-10-30 20:40:10 +00009150 return SelectInst::Create(Src,
Owen Andersona7235ea2009-07-31 20:28:14 +00009151 Constant::getAllOnesValue(CI.getType()),
9152 Constant::getNullValue(CI.getType()));
Dan Gohmanf35c8822008-05-20 21:01:12 +00009153
9154 // See if the value being truncated is already sign extended. If so, just
9155 // eliminate the trunc/sext pair.
Dan Gohmanca178902009-07-17 20:47:02 +00009156 if (Operator::getOpcode(Src) == Instruction::Trunc) {
Dan Gohmanf35c8822008-05-20 21:01:12 +00009157 Value *Op = cast<User>(Src)->getOperand(0);
Dan Gohman6de29f82009-06-15 22:12:54 +00009158 unsigned OpBits = Op->getType()->getScalarSizeInBits();
9159 unsigned MidBits = Src->getType()->getScalarSizeInBits();
9160 unsigned DestBits = CI.getType()->getScalarSizeInBits();
Dan Gohmanf35c8822008-05-20 21:01:12 +00009161 unsigned NumSignBits = ComputeNumSignBits(Op);
9162
9163 if (OpBits == DestBits) {
9164 // Op is i32, Mid is i8, and Dest is i32. If Op has more than 24 sign
9165 // bits, it is already ready.
9166 if (NumSignBits > DestBits-MidBits)
9167 return ReplaceInstUsesWith(CI, Op);
9168 } else if (OpBits < DestBits) {
9169 // Op is i32, Mid is i8, and Dest is i64. If Op has more than 24 sign
9170 // bits, just sext from i32.
9171 if (NumSignBits > OpBits-MidBits)
9172 return new SExtInst(Op, CI.getType(), "tmp");
9173 } else {
9174 // Op is i64, Mid is i8, and Dest is i32. If Op has more than 56 sign
9175 // bits, just truncate to i32.
9176 if (NumSignBits > OpBits-MidBits)
9177 return new TruncInst(Op, CI.getType(), "tmp");
9178 }
9179 }
Chris Lattner46bbad22008-08-06 07:35:52 +00009180
9181 // If the input is a shl/ashr pair of a same constant, then this is a sign
9182 // extension from a smaller value. If we could trust arbitrary bitwidth
9183 // integers, we could turn this into a truncate to the smaller bit and then
9184 // use a sext for the whole extension. Since we don't, look deeper and check
9185 // for a truncate. If the source and dest are the same type, eliminate the
9186 // trunc and extend and just do shifts. For example, turn:
9187 // %a = trunc i32 %i to i8
9188 // %b = shl i8 %a, 6
9189 // %c = ashr i8 %b, 6
9190 // %d = sext i8 %c to i32
9191 // into:
9192 // %a = shl i32 %i, 30
9193 // %d = ashr i32 %a, 30
9194 Value *A = 0;
9195 ConstantInt *BA = 0, *CA = 0;
9196 if (match(Src, m_AShr(m_Shl(m_Value(A), m_ConstantInt(BA)),
Dan Gohman4ae51262009-08-12 16:23:25 +00009197 m_ConstantInt(CA))) &&
Chris Lattner46bbad22008-08-06 07:35:52 +00009198 BA == CA && isa<TruncInst>(A)) {
9199 Value *I = cast<TruncInst>(A)->getOperand(0);
9200 if (I->getType() == CI.getType()) {
Dan Gohman6de29f82009-06-15 22:12:54 +00009201 unsigned MidSize = Src->getType()->getScalarSizeInBits();
9202 unsigned SrcDstSize = CI.getType()->getScalarSizeInBits();
Chris Lattner46bbad22008-08-06 07:35:52 +00009203 unsigned ShAmt = CA->getZExtValue()+SrcDstSize-MidSize;
Owen Andersoneed707b2009-07-24 23:12:02 +00009204 Constant *ShAmtV = ConstantInt::get(CI.getType(), ShAmt);
Chris Lattnerf925cbd2009-08-30 18:50:58 +00009205 I = Builder->CreateShl(I, ShAmtV, CI.getName());
Chris Lattner46bbad22008-08-06 07:35:52 +00009206 return BinaryOperator::CreateAShr(I, ShAmtV);
9207 }
9208 }
9209
Chris Lattnerba417832007-04-11 06:12:58 +00009210 return 0;
Reid Spencer3da59db2006-11-27 01:05:10 +00009211}
9212
Chris Lattnerb7530652008-01-27 05:29:54 +00009213/// FitsInFPType - Return a Constant* for the specified FP constant if it fits
9214/// in the specified FP type without changing its value.
Owen Andersond672ecb2009-07-03 00:17:18 +00009215static Constant *FitsInFPType(ConstantFP *CFP, const fltSemantics &Sem,
Owen Anderson07cf79e2009-07-06 23:00:19 +00009216 LLVMContext *Context) {
Dale Johannesen23a98552008-10-09 23:00:39 +00009217 bool losesInfo;
Chris Lattnerb7530652008-01-27 05:29:54 +00009218 APFloat F = CFP->getValueAPF();
Dale Johannesen23a98552008-10-09 23:00:39 +00009219 (void)F.convert(Sem, APFloat::rmNearestTiesToEven, &losesInfo);
9220 if (!losesInfo)
Owen Anderson6f83c9c2009-07-27 20:59:43 +00009221 return ConstantFP::get(*Context, F);
Chris Lattnerb7530652008-01-27 05:29:54 +00009222 return 0;
9223}
9224
9225/// LookThroughFPExtensions - If this is an fp extension instruction, look
9226/// through it until we get the source value.
Owen Anderson07cf79e2009-07-06 23:00:19 +00009227static Value *LookThroughFPExtensions(Value *V, LLVMContext *Context) {
Chris Lattnerb7530652008-01-27 05:29:54 +00009228 if (Instruction *I = dyn_cast<Instruction>(V))
9229 if (I->getOpcode() == Instruction::FPExt)
Owen Andersond672ecb2009-07-03 00:17:18 +00009230 return LookThroughFPExtensions(I->getOperand(0), Context);
Chris Lattnerb7530652008-01-27 05:29:54 +00009231
9232 // If this value is a constant, return the constant in the smallest FP type
9233 // that can accurately represent it. This allows us to turn
9234 // (float)((double)X+2.0) into x+2.0f.
9235 if (ConstantFP *CFP = dyn_cast<ConstantFP>(V)) {
Owen Anderson1d0be152009-08-13 21:58:54 +00009236 if (CFP->getType() == Type::getPPC_FP128Ty(*Context))
Chris Lattnerb7530652008-01-27 05:29:54 +00009237 return V; // No constant folding of this.
9238 // See if the value can be truncated to float and then reextended.
Owen Andersond672ecb2009-07-03 00:17:18 +00009239 if (Value *V = FitsInFPType(CFP, APFloat::IEEEsingle, Context))
Chris Lattnerb7530652008-01-27 05:29:54 +00009240 return V;
Owen Anderson1d0be152009-08-13 21:58:54 +00009241 if (CFP->getType() == Type::getDoubleTy(*Context))
Chris Lattnerb7530652008-01-27 05:29:54 +00009242 return V; // Won't shrink.
Owen Andersond672ecb2009-07-03 00:17:18 +00009243 if (Value *V = FitsInFPType(CFP, APFloat::IEEEdouble, Context))
Chris Lattnerb7530652008-01-27 05:29:54 +00009244 return V;
9245 // Don't try to shrink to various long double types.
9246 }
9247
9248 return V;
9249}
9250
9251Instruction *InstCombiner::visitFPTrunc(FPTruncInst &CI) {
9252 if (Instruction *I = commonCastTransforms(CI))
9253 return I;
9254
Dan Gohmanae3a0be2009-06-04 22:49:04 +00009255 // If we have fptrunc(fadd (fpextend x), (fpextend y)), where x and y are
Chris Lattnerb7530652008-01-27 05:29:54 +00009256 // smaller than the destination type, we can eliminate the truncate by doing
Dan Gohmanae3a0be2009-06-04 22:49:04 +00009257 // the add as the smaller type. This applies to fadd/fsub/fmul/fdiv as well as
Chris Lattnerb7530652008-01-27 05:29:54 +00009258 // many builtins (sqrt, etc).
9259 BinaryOperator *OpI = dyn_cast<BinaryOperator>(CI.getOperand(0));
9260 if (OpI && OpI->hasOneUse()) {
9261 switch (OpI->getOpcode()) {
9262 default: break;
Dan Gohmanae3a0be2009-06-04 22:49:04 +00009263 case Instruction::FAdd:
9264 case Instruction::FSub:
9265 case Instruction::FMul:
Chris Lattnerb7530652008-01-27 05:29:54 +00009266 case Instruction::FDiv:
9267 case Instruction::FRem:
9268 const Type *SrcTy = OpI->getType();
Owen Andersond672ecb2009-07-03 00:17:18 +00009269 Value *LHSTrunc = LookThroughFPExtensions(OpI->getOperand(0), Context);
9270 Value *RHSTrunc = LookThroughFPExtensions(OpI->getOperand(1), Context);
Chris Lattnerb7530652008-01-27 05:29:54 +00009271 if (LHSTrunc->getType() != SrcTy &&
9272 RHSTrunc->getType() != SrcTy) {
Dan Gohman6de29f82009-06-15 22:12:54 +00009273 unsigned DstSize = CI.getType()->getScalarSizeInBits();
Chris Lattnerb7530652008-01-27 05:29:54 +00009274 // If the source types were both smaller than the destination type of
9275 // the cast, do this xform.
Dan Gohman6de29f82009-06-15 22:12:54 +00009276 if (LHSTrunc->getType()->getScalarSizeInBits() <= DstSize &&
9277 RHSTrunc->getType()->getScalarSizeInBits() <= DstSize) {
Chris Lattner2345d1d2009-08-30 20:01:10 +00009278 LHSTrunc = Builder->CreateFPExt(LHSTrunc, CI.getType());
9279 RHSTrunc = Builder->CreateFPExt(RHSTrunc, CI.getType());
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009280 return BinaryOperator::Create(OpI->getOpcode(), LHSTrunc, RHSTrunc);
Chris Lattnerb7530652008-01-27 05:29:54 +00009281 }
9282 }
9283 break;
9284 }
9285 }
9286 return 0;
Reid Spencer3da59db2006-11-27 01:05:10 +00009287}
9288
9289Instruction *InstCombiner::visitFPExt(CastInst &CI) {
9290 return commonCastTransforms(CI);
9291}
9292
Chris Lattner0c7a9a02008-05-19 20:25:04 +00009293Instruction *InstCombiner::visitFPToUI(FPToUIInst &FI) {
Chris Lattner5af5f462008-08-06 05:13:06 +00009294 Instruction *OpI = dyn_cast<Instruction>(FI.getOperand(0));
9295 if (OpI == 0)
9296 return commonCastTransforms(FI);
9297
9298 // fptoui(uitofp(X)) --> X
9299 // fptoui(sitofp(X)) --> X
9300 // This is safe if the intermediate type has enough bits in its mantissa to
9301 // accurately represent all values of X. For example, do not do this with
9302 // i64->float->i64. This is also safe for sitofp case, because any negative
9303 // 'X' value would cause an undefined result for the fptoui.
9304 if ((isa<UIToFPInst>(OpI) || isa<SIToFPInst>(OpI)) &&
9305 OpI->getOperand(0)->getType() == FI.getType() &&
Dan Gohman6de29f82009-06-15 22:12:54 +00009306 (int)FI.getType()->getScalarSizeInBits() < /*extra bit for sign */
Chris Lattner5af5f462008-08-06 05:13:06 +00009307 OpI->getType()->getFPMantissaWidth())
9308 return ReplaceInstUsesWith(FI, OpI->getOperand(0));
Chris Lattner0c7a9a02008-05-19 20:25:04 +00009309
9310 return commonCastTransforms(FI);
Reid Spencer3da59db2006-11-27 01:05:10 +00009311}
9312
Chris Lattner0c7a9a02008-05-19 20:25:04 +00009313Instruction *InstCombiner::visitFPToSI(FPToSIInst &FI) {
Chris Lattner5af5f462008-08-06 05:13:06 +00009314 Instruction *OpI = dyn_cast<Instruction>(FI.getOperand(0));
9315 if (OpI == 0)
9316 return commonCastTransforms(FI);
9317
9318 // fptosi(sitofp(X)) --> X
9319 // fptosi(uitofp(X)) --> X
9320 // This is safe if the intermediate type has enough bits in its mantissa to
9321 // accurately represent all values of X. For example, do not do this with
9322 // i64->float->i64. This is also safe for sitofp case, because any negative
9323 // 'X' value would cause an undefined result for the fptoui.
9324 if ((isa<UIToFPInst>(OpI) || isa<SIToFPInst>(OpI)) &&
9325 OpI->getOperand(0)->getType() == FI.getType() &&
Dan Gohman6de29f82009-06-15 22:12:54 +00009326 (int)FI.getType()->getScalarSizeInBits() <=
Chris Lattner5af5f462008-08-06 05:13:06 +00009327 OpI->getType()->getFPMantissaWidth())
9328 return ReplaceInstUsesWith(FI, OpI->getOperand(0));
Chris Lattner0c7a9a02008-05-19 20:25:04 +00009329
9330 return commonCastTransforms(FI);
Reid Spencer3da59db2006-11-27 01:05:10 +00009331}
9332
9333Instruction *InstCombiner::visitUIToFP(CastInst &CI) {
9334 return commonCastTransforms(CI);
9335}
9336
9337Instruction *InstCombiner::visitSIToFP(CastInst &CI) {
9338 return commonCastTransforms(CI);
9339}
9340
Chris Lattnera0e69692009-03-24 18:35:40 +00009341Instruction *InstCombiner::visitPtrToInt(PtrToIntInst &CI) {
9342 // If the destination integer type is smaller than the intptr_t type for
9343 // this target, do a ptrtoint to intptr_t then do a trunc. This allows the
9344 // trunc to be exposed to other transforms. Don't do this for extending
9345 // ptrtoint's, because we don't know if the target sign or zero extends its
9346 // pointers.
Dan Gohmance9fe9f2009-07-21 23:21:54 +00009347 if (TD &&
9348 CI.getType()->getScalarSizeInBits() < TD->getPointerSizeInBits()) {
Chris Lattnerf925cbd2009-08-30 18:50:58 +00009349 Value *P = Builder->CreatePtrToInt(CI.getOperand(0),
9350 TD->getIntPtrType(CI.getContext()),
9351 "tmp");
Chris Lattnera0e69692009-03-24 18:35:40 +00009352 return new TruncInst(P, CI.getType());
9353 }
9354
Chris Lattnerd3e28342007-04-27 17:44:50 +00009355 return commonPointerCastTransforms(CI);
Reid Spencer3da59db2006-11-27 01:05:10 +00009356}
9357
Chris Lattnerf9d9e452008-01-08 07:23:51 +00009358Instruction *InstCombiner::visitIntToPtr(IntToPtrInst &CI) {
Chris Lattnera0e69692009-03-24 18:35:40 +00009359 // If the source integer type is larger than the intptr_t type for
9360 // this target, do a trunc to the intptr_t type, then inttoptr of it. This
9361 // allows the trunc to be exposed to other transforms. Don't do this for
9362 // extending inttoptr's, because we don't know if the target sign or zero
9363 // extends to pointers.
Chris Lattnerf925cbd2009-08-30 18:50:58 +00009364 if (TD && CI.getOperand(0)->getType()->getScalarSizeInBits() >
Chris Lattnera0e69692009-03-24 18:35:40 +00009365 TD->getPointerSizeInBits()) {
Chris Lattnerf925cbd2009-08-30 18:50:58 +00009366 Value *P = Builder->CreateTrunc(CI.getOperand(0),
9367 TD->getIntPtrType(CI.getContext()), "tmp");
Chris Lattnera0e69692009-03-24 18:35:40 +00009368 return new IntToPtrInst(P, CI.getType());
9369 }
9370
Chris Lattnerf9d9e452008-01-08 07:23:51 +00009371 if (Instruction *I = commonCastTransforms(CI))
9372 return I;
Chris Lattnerf9d9e452008-01-08 07:23:51 +00009373
Chris Lattnerf9d9e452008-01-08 07:23:51 +00009374 return 0;
Reid Spencer3da59db2006-11-27 01:05:10 +00009375}
9376
Chris Lattnerd3e28342007-04-27 17:44:50 +00009377Instruction *InstCombiner::visitBitCast(BitCastInst &CI) {
Reid Spencer3da59db2006-11-27 01:05:10 +00009378 // If the operands are integer typed then apply the integer transforms,
9379 // otherwise just apply the common ones.
9380 Value *Src = CI.getOperand(0);
9381 const Type *SrcTy = Src->getType();
9382 const Type *DestTy = CI.getType();
9383
Eli Friedman7e25d452009-07-13 20:53:00 +00009384 if (isa<PointerType>(SrcTy)) {
Chris Lattnerd3e28342007-04-27 17:44:50 +00009385 if (Instruction *I = commonPointerCastTransforms(CI))
9386 return I;
Reid Spencer3da59db2006-11-27 01:05:10 +00009387 } else {
9388 if (Instruction *Result = commonCastTransforms(CI))
9389 return Result;
9390 }
9391
9392
9393 // Get rid of casts from one type to the same type. These are useless and can
9394 // be replaced by the operand.
9395 if (DestTy == Src->getType())
9396 return ReplaceInstUsesWith(CI, Src);
9397
Reid Spencer3da59db2006-11-27 01:05:10 +00009398 if (const PointerType *DstPTy = dyn_cast<PointerType>(DestTy)) {
Chris Lattnerd3e28342007-04-27 17:44:50 +00009399 const PointerType *SrcPTy = cast<PointerType>(SrcTy);
9400 const Type *DstElTy = DstPTy->getElementType();
9401 const Type *SrcElTy = SrcPTy->getElementType();
9402
Nate Begeman83ad90a2008-03-31 00:22:16 +00009403 // If the address spaces don't match, don't eliminate the bitcast, which is
9404 // required for changing types.
9405 if (SrcPTy->getAddressSpace() != DstPTy->getAddressSpace())
9406 return 0;
9407
Victor Hernandez83d63912009-09-18 22:35:49 +00009408 // If we are casting a alloca to a pointer to a type of the same
Chris Lattnerd3e28342007-04-27 17:44:50 +00009409 // size, rewrite the allocation instruction to allocate the "right" type.
Victor Hernandez83d63912009-09-18 22:35:49 +00009410 // There is no need to modify malloc calls because it is their bitcast that
9411 // needs to be cleaned up.
Victor Hernandez7b929da2009-10-23 21:09:37 +00009412 if (AllocaInst *AI = dyn_cast<AllocaInst>(Src))
Chris Lattnerd3e28342007-04-27 17:44:50 +00009413 if (Instruction *V = PromoteCastOfAllocation(CI, *AI))
9414 return V;
9415
Chris Lattnerd717c182007-05-05 22:32:24 +00009416 // If the source and destination are pointers, and this cast is equivalent
9417 // to a getelementptr X, 0, 0, 0... turn it into the appropriate gep.
Chris Lattnerd3e28342007-04-27 17:44:50 +00009418 // This can enhance SROA and other transforms that want type-safe pointers.
Owen Anderson1d0be152009-08-13 21:58:54 +00009419 Constant *ZeroUInt = Constant::getNullValue(Type::getInt32Ty(*Context));
Chris Lattnerd3e28342007-04-27 17:44:50 +00009420 unsigned NumZeros = 0;
9421 while (SrcElTy != DstElTy &&
9422 isa<CompositeType>(SrcElTy) && !isa<PointerType>(SrcElTy) &&
9423 SrcElTy->getNumContainedTypes() /* not "{}" */) {
9424 SrcElTy = cast<CompositeType>(SrcElTy)->getTypeAtIndex(ZeroUInt);
9425 ++NumZeros;
9426 }
Chris Lattner4e998b22004-09-29 05:07:12 +00009427
Chris Lattnerd3e28342007-04-27 17:44:50 +00009428 // If we found a path from the src to dest, create the getelementptr now.
9429 if (SrcElTy == DstElTy) {
9430 SmallVector<Value*, 8> Idxs(NumZeros+1, ZeroUInt);
Dan Gohmanf8dbee72009-09-07 23:54:19 +00009431 return GetElementPtrInst::CreateInBounds(Src, Idxs.begin(), Idxs.end(), "",
9432 ((Instruction*) NULL));
Chris Lattner9fb92132006-04-12 18:09:35 +00009433 }
Reid Spencer3da59db2006-11-27 01:05:10 +00009434 }
Chris Lattner24c8e382003-07-24 17:35:25 +00009435
Eli Friedman2451a642009-07-18 23:06:53 +00009436 if (const VectorType *DestVTy = dyn_cast<VectorType>(DestTy)) {
9437 if (DestVTy->getNumElements() == 1) {
9438 if (!isa<VectorType>(SrcTy)) {
Chris Lattner2345d1d2009-08-30 20:01:10 +00009439 Value *Elem = Builder->CreateBitCast(Src, DestVTy->getElementType());
Owen Anderson9e9a0d52009-07-30 23:03:37 +00009440 return InsertElementInst::Create(UndefValue::get(DestTy), Elem,
Chris Lattner2345d1d2009-08-30 20:01:10 +00009441 Constant::getNullValue(Type::getInt32Ty(*Context)));
Eli Friedman2451a642009-07-18 23:06:53 +00009442 }
9443 // FIXME: Canonicalize bitcast(insertelement) -> insertelement(bitcast)
9444 }
9445 }
9446
9447 if (const VectorType *SrcVTy = dyn_cast<VectorType>(SrcTy)) {
9448 if (SrcVTy->getNumElements() == 1) {
9449 if (!isa<VectorType>(DestTy)) {
Chris Lattnerf925cbd2009-08-30 18:50:58 +00009450 Value *Elem =
9451 Builder->CreateExtractElement(Src,
9452 Constant::getNullValue(Type::getInt32Ty(*Context)));
Eli Friedman2451a642009-07-18 23:06:53 +00009453 return CastInst::Create(Instruction::BitCast, Elem, DestTy);
9454 }
9455 }
9456 }
9457
Reid Spencer3da59db2006-11-27 01:05:10 +00009458 if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(Src)) {
9459 if (SVI->hasOneUse()) {
9460 // Okay, we have (bitconvert (shuffle ..)). Check to see if this is
9461 // a bitconvert to a vector with the same # elts.
Reid Spencer9d6565a2007-02-15 02:26:10 +00009462 if (isa<VectorType>(DestTy) &&
Mon P Wangaeb06d22008-11-10 04:46:22 +00009463 cast<VectorType>(DestTy)->getNumElements() ==
9464 SVI->getType()->getNumElements() &&
9465 SVI->getType()->getNumElements() ==
9466 cast<VectorType>(SVI->getOperand(0)->getType())->getNumElements()) {
Reid Spencer3da59db2006-11-27 01:05:10 +00009467 CastInst *Tmp;
9468 // If either of the operands is a cast from CI.getType(), then
9469 // evaluating the shuffle in the casted destination's type will allow
9470 // us to eliminate at least one cast.
9471 if (((Tmp = dyn_cast<CastInst>(SVI->getOperand(0))) &&
9472 Tmp->getOperand(0)->getType() == DestTy) ||
9473 ((Tmp = dyn_cast<CastInst>(SVI->getOperand(1))) &&
9474 Tmp->getOperand(0)->getType() == DestTy)) {
Chris Lattner2345d1d2009-08-30 20:01:10 +00009475 Value *LHS = Builder->CreateBitCast(SVI->getOperand(0), DestTy);
9476 Value *RHS = Builder->CreateBitCast(SVI->getOperand(1), DestTy);
Reid Spencer3da59db2006-11-27 01:05:10 +00009477 // Return a new shuffle vector. Use the same element ID's, as we
9478 // know the vector types match #elts.
9479 return new ShuffleVectorInst(LHS, RHS, SVI->getOperand(2));
Chris Lattner01575b72006-05-25 23:24:33 +00009480 }
9481 }
9482 }
9483 }
Chris Lattnerdd841ae2002-04-18 17:39:14 +00009484 return 0;
Chris Lattner8a2a3112001-12-14 16:52:21 +00009485}
9486
Chris Lattnere576b912004-04-09 23:46:01 +00009487/// GetSelectFoldableOperands - We want to turn code that looks like this:
9488/// %C = or %A, %B
9489/// %D = select %cond, %C, %A
9490/// into:
9491/// %C = select %cond, %B, 0
9492/// %D = or %A, %C
9493///
9494/// Assuming that the specified instruction is an operand to the select, return
9495/// a bitmask indicating which operands of this instruction are foldable if they
9496/// equal the other incoming value of the select.
9497///
9498static unsigned GetSelectFoldableOperands(Instruction *I) {
9499 switch (I->getOpcode()) {
9500 case Instruction::Add:
9501 case Instruction::Mul:
9502 case Instruction::And:
9503 case Instruction::Or:
9504 case Instruction::Xor:
9505 return 3; // Can fold through either operand.
9506 case Instruction::Sub: // Can only fold on the amount subtracted.
9507 case Instruction::Shl: // Can only fold on the shift amount.
Reid Spencer3822ff52006-11-08 06:47:33 +00009508 case Instruction::LShr:
9509 case Instruction::AShr:
Misha Brukmanfd939082005-04-21 23:48:37 +00009510 return 1;
Chris Lattnere576b912004-04-09 23:46:01 +00009511 default:
9512 return 0; // Cannot fold
9513 }
9514}
9515
9516/// GetSelectFoldableConstant - For the same transformation as the previous
9517/// function, return the identity constant that goes into the select.
Owen Andersond672ecb2009-07-03 00:17:18 +00009518static Constant *GetSelectFoldableConstant(Instruction *I,
Owen Anderson07cf79e2009-07-06 23:00:19 +00009519 LLVMContext *Context) {
Chris Lattnere576b912004-04-09 23:46:01 +00009520 switch (I->getOpcode()) {
Torok Edwinc23197a2009-07-14 16:55:14 +00009521 default: llvm_unreachable("This cannot happen!");
Chris Lattnere576b912004-04-09 23:46:01 +00009522 case Instruction::Add:
9523 case Instruction::Sub:
9524 case Instruction::Or:
9525 case Instruction::Xor:
Chris Lattnere576b912004-04-09 23:46:01 +00009526 case Instruction::Shl:
Reid Spencer3822ff52006-11-08 06:47:33 +00009527 case Instruction::LShr:
9528 case Instruction::AShr:
Owen Andersona7235ea2009-07-31 20:28:14 +00009529 return Constant::getNullValue(I->getType());
Chris Lattnere576b912004-04-09 23:46:01 +00009530 case Instruction::And:
Owen Andersona7235ea2009-07-31 20:28:14 +00009531 return Constant::getAllOnesValue(I->getType());
Chris Lattnere576b912004-04-09 23:46:01 +00009532 case Instruction::Mul:
Owen Andersoneed707b2009-07-24 23:12:02 +00009533 return ConstantInt::get(I->getType(), 1);
Chris Lattnere576b912004-04-09 23:46:01 +00009534 }
9535}
9536
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00009537/// FoldSelectOpOp - Here we have (select c, TI, FI), and we know that TI and FI
9538/// have the same opcode and only one use each. Try to simplify this.
9539Instruction *InstCombiner::FoldSelectOpOp(SelectInst &SI, Instruction *TI,
9540 Instruction *FI) {
9541 if (TI->getNumOperands() == 1) {
9542 // If this is a non-volatile load or a cast from the same type,
9543 // merge.
Reid Spencer3da59db2006-11-27 01:05:10 +00009544 if (TI->isCast()) {
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00009545 if (TI->getOperand(0)->getType() != FI->getOperand(0)->getType())
9546 return 0;
9547 } else {
9548 return 0; // unknown unary op.
9549 }
Misha Brukmanfd939082005-04-21 23:48:37 +00009550
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00009551 // Fold this by inserting a select from the input values.
Gabor Greif051a9502008-04-06 20:25:17 +00009552 SelectInst *NewSI = SelectInst::Create(SI.getCondition(), TI->getOperand(0),
Eric Christophera66297a2009-07-25 02:45:27 +00009553 FI->getOperand(0), SI.getName()+".v");
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00009554 InsertNewInstBefore(NewSI, SI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009555 return CastInst::Create(Instruction::CastOps(TI->getOpcode()), NewSI,
Reid Spencer3da59db2006-11-27 01:05:10 +00009556 TI->getType());
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00009557 }
9558
Reid Spencer832254e2007-02-02 02:16:23 +00009559 // Only handle binary operators here.
9560 if (!isa<BinaryOperator>(TI))
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00009561 return 0;
9562
9563 // Figure out if the operations have any operands in common.
9564 Value *MatchOp, *OtherOpT, *OtherOpF;
9565 bool MatchIsOpZero;
9566 if (TI->getOperand(0) == FI->getOperand(0)) {
9567 MatchOp = TI->getOperand(0);
9568 OtherOpT = TI->getOperand(1);
9569 OtherOpF = FI->getOperand(1);
9570 MatchIsOpZero = true;
9571 } else if (TI->getOperand(1) == FI->getOperand(1)) {
9572 MatchOp = TI->getOperand(1);
9573 OtherOpT = TI->getOperand(0);
9574 OtherOpF = FI->getOperand(0);
9575 MatchIsOpZero = false;
9576 } else if (!TI->isCommutative()) {
9577 return 0;
9578 } else if (TI->getOperand(0) == FI->getOperand(1)) {
9579 MatchOp = TI->getOperand(0);
9580 OtherOpT = TI->getOperand(1);
9581 OtherOpF = FI->getOperand(0);
9582 MatchIsOpZero = true;
9583 } else if (TI->getOperand(1) == FI->getOperand(0)) {
9584 MatchOp = TI->getOperand(1);
9585 OtherOpT = TI->getOperand(0);
9586 OtherOpF = FI->getOperand(1);
9587 MatchIsOpZero = true;
9588 } else {
9589 return 0;
9590 }
9591
9592 // If we reach here, they do have operations in common.
Gabor Greif051a9502008-04-06 20:25:17 +00009593 SelectInst *NewSI = SelectInst::Create(SI.getCondition(), OtherOpT,
9594 OtherOpF, SI.getName()+".v");
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00009595 InsertNewInstBefore(NewSI, SI);
9596
9597 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TI)) {
9598 if (MatchIsOpZero)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009599 return BinaryOperator::Create(BO->getOpcode(), MatchOp, NewSI);
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00009600 else
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009601 return BinaryOperator::Create(BO->getOpcode(), NewSI, MatchOp);
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00009602 }
Torok Edwinc23197a2009-07-14 16:55:14 +00009603 llvm_unreachable("Shouldn't get here");
Reid Spencera07cb7d2007-02-02 14:41:37 +00009604 return 0;
Chris Lattner6fb5a4a2005-01-19 21:50:18 +00009605}
9606
Evan Chengde621922009-03-31 20:42:45 +00009607static bool isSelect01(Constant *C1, Constant *C2) {
9608 ConstantInt *C1I = dyn_cast<ConstantInt>(C1);
9609 if (!C1I)
9610 return false;
9611 ConstantInt *C2I = dyn_cast<ConstantInt>(C2);
9612 if (!C2I)
9613 return false;
9614 return (C1I->isZero() || C1I->isOne()) && (C2I->isZero() || C2I->isOne());
9615}
9616
9617/// FoldSelectIntoOp - Try fold the select into one of the operands to
9618/// facilitate further optimization.
9619Instruction *InstCombiner::FoldSelectIntoOp(SelectInst &SI, Value *TrueVal,
9620 Value *FalseVal) {
9621 // See the comment above GetSelectFoldableOperands for a description of the
9622 // transformation we are doing here.
9623 if (Instruction *TVI = dyn_cast<Instruction>(TrueVal)) {
9624 if (TVI->hasOneUse() && TVI->getNumOperands() == 2 &&
9625 !isa<Constant>(FalseVal)) {
9626 if (unsigned SFO = GetSelectFoldableOperands(TVI)) {
9627 unsigned OpToFold = 0;
9628 if ((SFO & 1) && FalseVal == TVI->getOperand(0)) {
9629 OpToFold = 1;
9630 } else if ((SFO & 2) && FalseVal == TVI->getOperand(1)) {
9631 OpToFold = 2;
9632 }
9633
9634 if (OpToFold) {
Owen Andersond672ecb2009-07-03 00:17:18 +00009635 Constant *C = GetSelectFoldableConstant(TVI, Context);
Evan Chengde621922009-03-31 20:42:45 +00009636 Value *OOp = TVI->getOperand(2-OpToFold);
9637 // Avoid creating select between 2 constants unless it's selecting
9638 // between 0 and 1.
9639 if (!isa<Constant>(OOp) || isSelect01(C, cast<Constant>(OOp))) {
9640 Instruction *NewSel = SelectInst::Create(SI.getCondition(), OOp, C);
9641 InsertNewInstBefore(NewSel, SI);
9642 NewSel->takeName(TVI);
9643 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TVI))
9644 return BinaryOperator::Create(BO->getOpcode(), FalseVal, NewSel);
Torok Edwinc23197a2009-07-14 16:55:14 +00009645 llvm_unreachable("Unknown instruction!!");
Evan Chengde621922009-03-31 20:42:45 +00009646 }
9647 }
9648 }
9649 }
9650 }
9651
9652 if (Instruction *FVI = dyn_cast<Instruction>(FalseVal)) {
9653 if (FVI->hasOneUse() && FVI->getNumOperands() == 2 &&
9654 !isa<Constant>(TrueVal)) {
9655 if (unsigned SFO = GetSelectFoldableOperands(FVI)) {
9656 unsigned OpToFold = 0;
9657 if ((SFO & 1) && TrueVal == FVI->getOperand(0)) {
9658 OpToFold = 1;
9659 } else if ((SFO & 2) && TrueVal == FVI->getOperand(1)) {
9660 OpToFold = 2;
9661 }
9662
9663 if (OpToFold) {
Owen Andersond672ecb2009-07-03 00:17:18 +00009664 Constant *C = GetSelectFoldableConstant(FVI, Context);
Evan Chengde621922009-03-31 20:42:45 +00009665 Value *OOp = FVI->getOperand(2-OpToFold);
9666 // Avoid creating select between 2 constants unless it's selecting
9667 // between 0 and 1.
9668 if (!isa<Constant>(OOp) || isSelect01(C, cast<Constant>(OOp))) {
9669 Instruction *NewSel = SelectInst::Create(SI.getCondition(), C, OOp);
9670 InsertNewInstBefore(NewSel, SI);
9671 NewSel->takeName(FVI);
9672 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(FVI))
9673 return BinaryOperator::Create(BO->getOpcode(), TrueVal, NewSel);
Torok Edwinc23197a2009-07-14 16:55:14 +00009674 llvm_unreachable("Unknown instruction!!");
Evan Chengde621922009-03-31 20:42:45 +00009675 }
9676 }
9677 }
9678 }
9679 }
9680
9681 return 0;
9682}
9683
Dan Gohman81b28ce2008-09-16 18:46:06 +00009684/// visitSelectInstWithICmp - Visit a SelectInst that has an
9685/// ICmpInst as its first operand.
9686///
9687Instruction *InstCombiner::visitSelectInstWithICmp(SelectInst &SI,
9688 ICmpInst *ICI) {
9689 bool Changed = false;
9690 ICmpInst::Predicate Pred = ICI->getPredicate();
9691 Value *CmpLHS = ICI->getOperand(0);
9692 Value *CmpRHS = ICI->getOperand(1);
9693 Value *TrueVal = SI.getTrueValue();
9694 Value *FalseVal = SI.getFalseValue();
9695
9696 // Check cases where the comparison is with a constant that
9697 // can be adjusted to fit the min/max idiom. We may edit ICI in
9698 // place here, so make sure the select is the only user.
9699 if (ICI->hasOneUse())
Dan Gohman1975d032008-10-30 20:40:10 +00009700 if (ConstantInt *CI = dyn_cast<ConstantInt>(CmpRHS)) {
Dan Gohman81b28ce2008-09-16 18:46:06 +00009701 switch (Pred) {
9702 default: break;
9703 case ICmpInst::ICMP_ULT:
9704 case ICmpInst::ICMP_SLT: {
9705 // X < MIN ? T : F --> F
9706 if (CI->isMinValue(Pred == ICmpInst::ICMP_SLT))
9707 return ReplaceInstUsesWith(SI, FalseVal);
9708 // X < C ? X : C-1 --> X > C-1 ? C-1 : X
Dan Gohman186a6362009-08-12 16:04:34 +00009709 Constant *AdjustedRHS = SubOne(CI);
Dan Gohman81b28ce2008-09-16 18:46:06 +00009710 if ((CmpLHS == TrueVal && AdjustedRHS == FalseVal) ||
9711 (CmpLHS == FalseVal && AdjustedRHS == TrueVal)) {
9712 Pred = ICmpInst::getSwappedPredicate(Pred);
9713 CmpRHS = AdjustedRHS;
9714 std::swap(FalseVal, TrueVal);
9715 ICI->setPredicate(Pred);
9716 ICI->setOperand(1, CmpRHS);
9717 SI.setOperand(1, TrueVal);
9718 SI.setOperand(2, FalseVal);
9719 Changed = true;
9720 }
9721 break;
9722 }
9723 case ICmpInst::ICMP_UGT:
9724 case ICmpInst::ICMP_SGT: {
9725 // X > MAX ? T : F --> F
9726 if (CI->isMaxValue(Pred == ICmpInst::ICMP_SGT))
9727 return ReplaceInstUsesWith(SI, FalseVal);
9728 // X > C ? X : C+1 --> X < C+1 ? C+1 : X
Dan Gohman186a6362009-08-12 16:04:34 +00009729 Constant *AdjustedRHS = AddOne(CI);
Dan Gohman81b28ce2008-09-16 18:46:06 +00009730 if ((CmpLHS == TrueVal && AdjustedRHS == FalseVal) ||
9731 (CmpLHS == FalseVal && AdjustedRHS == TrueVal)) {
9732 Pred = ICmpInst::getSwappedPredicate(Pred);
9733 CmpRHS = AdjustedRHS;
9734 std::swap(FalseVal, TrueVal);
9735 ICI->setPredicate(Pred);
9736 ICI->setOperand(1, CmpRHS);
9737 SI.setOperand(1, TrueVal);
9738 SI.setOperand(2, FalseVal);
9739 Changed = true;
9740 }
9741 break;
9742 }
9743 }
9744
Dan Gohman1975d032008-10-30 20:40:10 +00009745 // (x <s 0) ? -1 : 0 -> ashr x, 31 -> all ones if signed
9746 // (x >s -1) ? -1 : 0 -> ashr x, 31 -> all ones if not signed
Chris Lattnercb504b92008-11-16 05:38:51 +00009747 CmpInst::Predicate Pred = CmpInst::BAD_ICMP_PREDICATE;
Dan Gohman4ae51262009-08-12 16:23:25 +00009748 if (match(TrueVal, m_ConstantInt<-1>()) &&
9749 match(FalseVal, m_ConstantInt<0>()))
Chris Lattnercb504b92008-11-16 05:38:51 +00009750 Pred = ICI->getPredicate();
Dan Gohman4ae51262009-08-12 16:23:25 +00009751 else if (match(TrueVal, m_ConstantInt<0>()) &&
9752 match(FalseVal, m_ConstantInt<-1>()))
Chris Lattnercb504b92008-11-16 05:38:51 +00009753 Pred = CmpInst::getInversePredicate(ICI->getPredicate());
9754
Dan Gohman1975d032008-10-30 20:40:10 +00009755 if (Pred != CmpInst::BAD_ICMP_PREDICATE) {
9756 // If we are just checking for a icmp eq of a single bit and zext'ing it
9757 // to an integer, then shift the bit to the appropriate place and then
9758 // cast to integer to avoid the comparison.
9759 const APInt &Op1CV = CI->getValue();
9760
9761 // sext (x <s 0) to i32 --> x>>s31 true if signbit set.
9762 // sext (x >s -1) to i32 --> (x>>s31)^-1 true if signbit clear.
9763 if ((Pred == ICmpInst::ICMP_SLT && Op1CV == 0) ||
Chris Lattnercb504b92008-11-16 05:38:51 +00009764 (Pred == ICmpInst::ICMP_SGT && Op1CV.isAllOnesValue())) {
Dan Gohman1975d032008-10-30 20:40:10 +00009765 Value *In = ICI->getOperand(0);
Owen Andersoneed707b2009-07-24 23:12:02 +00009766 Value *Sh = ConstantInt::get(In->getType(),
Dan Gohman6de29f82009-06-15 22:12:54 +00009767 In->getType()->getScalarSizeInBits()-1);
Dan Gohman1975d032008-10-30 20:40:10 +00009768 In = InsertNewInstBefore(BinaryOperator::CreateAShr(In, Sh,
Eric Christophera66297a2009-07-25 02:45:27 +00009769 In->getName()+".lobit"),
Dan Gohman1975d032008-10-30 20:40:10 +00009770 *ICI);
Dan Gohman21440ac2008-11-02 00:17:33 +00009771 if (In->getType() != SI.getType())
9772 In = CastInst::CreateIntegerCast(In, SI.getType(),
Dan Gohman1975d032008-10-30 20:40:10 +00009773 true/*SExt*/, "tmp", ICI);
9774
9775 if (Pred == ICmpInst::ICMP_SGT)
Dan Gohman4ae51262009-08-12 16:23:25 +00009776 In = InsertNewInstBefore(BinaryOperator::CreateNot(In,
Dan Gohman1975d032008-10-30 20:40:10 +00009777 In->getName()+".not"), *ICI);
9778
9779 return ReplaceInstUsesWith(SI, In);
9780 }
9781 }
9782 }
9783
Dan Gohman81b28ce2008-09-16 18:46:06 +00009784 if (CmpLHS == TrueVal && CmpRHS == FalseVal) {
9785 // Transform (X == Y) ? X : Y -> Y
9786 if (Pred == ICmpInst::ICMP_EQ)
9787 return ReplaceInstUsesWith(SI, FalseVal);
9788 // Transform (X != Y) ? X : Y -> X
9789 if (Pred == ICmpInst::ICMP_NE)
9790 return ReplaceInstUsesWith(SI, TrueVal);
9791 /// NOTE: if we wanted to, this is where to detect integer MIN/MAX
9792
9793 } else if (CmpLHS == FalseVal && CmpRHS == TrueVal) {
9794 // Transform (X == Y) ? Y : X -> X
9795 if (Pred == ICmpInst::ICMP_EQ)
9796 return ReplaceInstUsesWith(SI, FalseVal);
9797 // Transform (X != Y) ? Y : X -> Y
9798 if (Pred == ICmpInst::ICMP_NE)
9799 return ReplaceInstUsesWith(SI, TrueVal);
9800 /// NOTE: if we wanted to, this is where to detect integer MIN/MAX
9801 }
Dan Gohman81b28ce2008-09-16 18:46:06 +00009802 return Changed ? &SI : 0;
9803}
9804
Chris Lattnerc6df8f42009-09-27 20:18:49 +00009805
Chris Lattner7f239582009-10-22 00:17:26 +00009806/// CanSelectOperandBeMappingIntoPredBlock - SI is a select whose condition is a
9807/// PHI node (but the two may be in different blocks). See if the true/false
9808/// values (V) are live in all of the predecessor blocks of the PHI. For
9809/// example, cases like this cannot be mapped:
9810///
9811/// X = phi [ C1, BB1], [C2, BB2]
9812/// Y = add
9813/// Z = select X, Y, 0
9814///
9815/// because Y is not live in BB1/BB2.
9816///
9817static bool CanSelectOperandBeMappingIntoPredBlock(const Value *V,
9818 const SelectInst &SI) {
9819 // If the value is a non-instruction value like a constant or argument, it
9820 // can always be mapped.
9821 const Instruction *I = dyn_cast<Instruction>(V);
9822 if (I == 0) return true;
9823
9824 // If V is a PHI node defined in the same block as the condition PHI, we can
9825 // map the arguments.
9826 const PHINode *CondPHI = cast<PHINode>(SI.getCondition());
9827
9828 if (const PHINode *VP = dyn_cast<PHINode>(I))
9829 if (VP->getParent() == CondPHI->getParent())
9830 return true;
9831
9832 // Otherwise, if the PHI and select are defined in the same block and if V is
9833 // defined in a different block, then we can transform it.
9834 if (SI.getParent() == CondPHI->getParent() &&
9835 I->getParent() != CondPHI->getParent())
9836 return true;
9837
9838 // Otherwise we have a 'hard' case and we can't tell without doing more
9839 // detailed dominator based analysis, punt.
9840 return false;
9841}
Chris Lattnerc6df8f42009-09-27 20:18:49 +00009842
Chris Lattnerb109b5c2009-12-21 06:03:05 +00009843/// FoldSPFofSPF - We have an SPF (e.g. a min or max) of an SPF of the form:
9844/// SPF2(SPF1(A, B), C)
9845Instruction *InstCombiner::FoldSPFofSPF(Instruction *Inner,
9846 SelectPatternFlavor SPF1,
9847 Value *A, Value *B,
9848 Instruction &Outer,
9849 SelectPatternFlavor SPF2, Value *C) {
9850 if (C == A || C == B) {
9851 // MAX(MAX(A, B), B) -> MAX(A, B)
9852 // MIN(MIN(a, b), a) -> MIN(a, b)
9853 if (SPF1 == SPF2)
9854 return ReplaceInstUsesWith(Outer, Inner);
9855
9856 // MAX(MIN(a, b), a) -> a
9857 // MIN(MAX(a, b), a) -> a
Daniel Dunbareddfaaf2009-12-21 23:27:57 +00009858 if ((SPF1 == SPF_SMIN && SPF2 == SPF_SMAX) ||
9859 (SPF1 == SPF_SMAX && SPF2 == SPF_SMIN) ||
9860 (SPF1 == SPF_UMIN && SPF2 == SPF_UMAX) ||
9861 (SPF1 == SPF_UMAX && SPF2 == SPF_UMIN))
Chris Lattnerb109b5c2009-12-21 06:03:05 +00009862 return ReplaceInstUsesWith(Outer, C);
9863 }
9864
9865 // TODO: MIN(MIN(A, 23), 97)
9866 return 0;
9867}
9868
9869
9870
9871
Chris Lattner3d69f462004-03-12 05:52:32 +00009872Instruction *InstCombiner::visitSelectInst(SelectInst &SI) {
Chris Lattnerc32b30a2004-03-30 19:37:13 +00009873 Value *CondVal = SI.getCondition();
9874 Value *TrueVal = SI.getTrueValue();
9875 Value *FalseVal = SI.getFalseValue();
9876
9877 // select true, X, Y -> X
9878 // select false, X, Y -> Y
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00009879 if (ConstantInt *C = dyn_cast<ConstantInt>(CondVal))
Reid Spencer579dca12007-01-12 04:24:46 +00009880 return ReplaceInstUsesWith(SI, C->getZExtValue() ? TrueVal : FalseVal);
Chris Lattnerc32b30a2004-03-30 19:37:13 +00009881
9882 // select C, X, X -> X
9883 if (TrueVal == FalseVal)
9884 return ReplaceInstUsesWith(SI, TrueVal);
9885
Chris Lattnere87597f2004-10-16 18:11:37 +00009886 if (isa<UndefValue>(TrueVal)) // select C, undef, X -> X
9887 return ReplaceInstUsesWith(SI, FalseVal);
9888 if (isa<UndefValue>(FalseVal)) // select C, X, undef -> X
9889 return ReplaceInstUsesWith(SI, TrueVal);
9890 if (isa<UndefValue>(CondVal)) { // select undef, X, Y -> X or Y
9891 if (isa<Constant>(TrueVal))
9892 return ReplaceInstUsesWith(SI, TrueVal);
9893 else
9894 return ReplaceInstUsesWith(SI, FalseVal);
9895 }
9896
Owen Anderson1d0be152009-08-13 21:58:54 +00009897 if (SI.getType() == Type::getInt1Ty(*Context)) {
Reid Spencera54b7cb2007-01-12 07:05:14 +00009898 if (ConstantInt *C = dyn_cast<ConstantInt>(TrueVal)) {
Reid Spencer579dca12007-01-12 04:24:46 +00009899 if (C->getZExtValue()) {
Chris Lattner0c199a72004-04-08 04:43:23 +00009900 // Change: A = select B, true, C --> A = or B, C
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009901 return BinaryOperator::CreateOr(CondVal, FalseVal);
Chris Lattner0c199a72004-04-08 04:43:23 +00009902 } else {
9903 // Change: A = select B, false, C --> A = and !B, C
9904 Value *NotCond =
Dan Gohman4ae51262009-08-12 16:23:25 +00009905 InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
Chris Lattner0c199a72004-04-08 04:43:23 +00009906 "not."+CondVal->getName()), SI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009907 return BinaryOperator::CreateAnd(NotCond, FalseVal);
Chris Lattner0c199a72004-04-08 04:43:23 +00009908 }
Reid Spencera54b7cb2007-01-12 07:05:14 +00009909 } else if (ConstantInt *C = dyn_cast<ConstantInt>(FalseVal)) {
Reid Spencer579dca12007-01-12 04:24:46 +00009910 if (C->getZExtValue() == false) {
Chris Lattner0c199a72004-04-08 04:43:23 +00009911 // Change: A = select B, C, false --> A = and B, C
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009912 return BinaryOperator::CreateAnd(CondVal, TrueVal);
Chris Lattner0c199a72004-04-08 04:43:23 +00009913 } else {
9914 // Change: A = select B, C, true --> A = or !B, C
9915 Value *NotCond =
Dan Gohman4ae51262009-08-12 16:23:25 +00009916 InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
Chris Lattner0c199a72004-04-08 04:43:23 +00009917 "not."+CondVal->getName()), SI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009918 return BinaryOperator::CreateOr(NotCond, TrueVal);
Chris Lattner0c199a72004-04-08 04:43:23 +00009919 }
9920 }
Chris Lattnercfa59752007-11-25 21:27:53 +00009921
9922 // select a, b, a -> a&b
9923 // select a, a, b -> a|b
9924 if (CondVal == TrueVal)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009925 return BinaryOperator::CreateOr(CondVal, FalseVal);
Chris Lattnercfa59752007-11-25 21:27:53 +00009926 else if (CondVal == FalseVal)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009927 return BinaryOperator::CreateAnd(CondVal, TrueVal);
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00009928 }
Chris Lattner0c199a72004-04-08 04:43:23 +00009929
Chris Lattner2eefe512004-04-09 19:05:30 +00009930 // Selecting between two integer constants?
9931 if (ConstantInt *TrueValC = dyn_cast<ConstantInt>(TrueVal))
9932 if (ConstantInt *FalseValC = dyn_cast<ConstantInt>(FalseVal)) {
Chris Lattnerba417832007-04-11 06:12:58 +00009933 // select C, 1, 0 -> zext C to int
Reid Spencer2ec619a2007-03-23 21:24:59 +00009934 if (FalseValC->isZero() && TrueValC->getValue() == 1) {
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009935 return CastInst::Create(Instruction::ZExt, CondVal, SI.getType());
Reid Spencer2ec619a2007-03-23 21:24:59 +00009936 } else if (TrueValC->isZero() && FalseValC->getValue() == 1) {
Chris Lattnerba417832007-04-11 06:12:58 +00009937 // select C, 0, 1 -> zext !C to int
Chris Lattner2eefe512004-04-09 19:05:30 +00009938 Value *NotCond =
Dan Gohman4ae51262009-08-12 16:23:25 +00009939 InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
Chris Lattner82e14fe2004-04-09 18:19:44 +00009940 "not."+CondVal->getName()), SI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009941 return CastInst::Create(Instruction::ZExt, NotCond, SI.getType());
Chris Lattner82e14fe2004-04-09 18:19:44 +00009942 }
Chris Lattner457dd822004-06-09 07:59:58 +00009943
Reid Spencere4d87aa2006-12-23 06:05:41 +00009944 if (ICmpInst *IC = dyn_cast<ICmpInst>(SI.getCondition())) {
Chris Lattnerb8456462006-09-20 04:44:59 +00009945 // If one of the constants is zero (we know they can't both be) and we
Chris Lattnerba417832007-04-11 06:12:58 +00009946 // have an icmp instruction with zero, and we have an 'and' with the
Chris Lattnerb8456462006-09-20 04:44:59 +00009947 // non-constant value, eliminate this whole mess. This corresponds to
9948 // cases like this: ((X & 27) ? 27 : 0)
Reid Spencer2ec619a2007-03-23 21:24:59 +00009949 if (TrueValC->isZero() || FalseValC->isZero())
Chris Lattner65b72ba2006-09-18 04:22:48 +00009950 if (IC->isEquality() && isa<ConstantInt>(IC->getOperand(1)) &&
Chris Lattner457dd822004-06-09 07:59:58 +00009951 cast<Constant>(IC->getOperand(1))->isNullValue())
9952 if (Instruction *ICA = dyn_cast<Instruction>(IC->getOperand(0)))
9953 if (ICA->getOpcode() == Instruction::And &&
Misha Brukmanfd939082005-04-21 23:48:37 +00009954 isa<ConstantInt>(ICA->getOperand(1)) &&
9955 (ICA->getOperand(1) == TrueValC ||
9956 ICA->getOperand(1) == FalseValC) &&
Chris Lattner457dd822004-06-09 07:59:58 +00009957 isOneBitSet(cast<ConstantInt>(ICA->getOperand(1)))) {
9958 // Okay, now we know that everything is set up, we just don't
Reid Spencere4d87aa2006-12-23 06:05:41 +00009959 // know whether we have a icmp_ne or icmp_eq and whether the
9960 // true or false val is the zero.
Reid Spencer2ec619a2007-03-23 21:24:59 +00009961 bool ShouldNotVal = !TrueValC->isZero();
Reid Spencere4d87aa2006-12-23 06:05:41 +00009962 ShouldNotVal ^= IC->getPredicate() == ICmpInst::ICMP_NE;
Chris Lattner457dd822004-06-09 07:59:58 +00009963 Value *V = ICA;
9964 if (ShouldNotVal)
Gabor Greif7cbd8a32008-05-16 19:29:10 +00009965 V = InsertNewInstBefore(BinaryOperator::Create(
Chris Lattner457dd822004-06-09 07:59:58 +00009966 Instruction::Xor, V, ICA->getOperand(1)), SI);
9967 return ReplaceInstUsesWith(SI, V);
9968 }
Chris Lattnerb8456462006-09-20 04:44:59 +00009969 }
Chris Lattnerc32b30a2004-03-30 19:37:13 +00009970 }
Chris Lattnerd76956d2004-04-10 22:21:27 +00009971
9972 // See if we are selecting two values based on a comparison of the two values.
Reid Spencere4d87aa2006-12-23 06:05:41 +00009973 if (FCmpInst *FCI = dyn_cast<FCmpInst>(CondVal)) {
9974 if (FCI->getOperand(0) == TrueVal && FCI->getOperand(1) == FalseVal) {
Chris Lattnerd76956d2004-04-10 22:21:27 +00009975 // Transform (X == Y) ? X : Y -> Y
Dale Johannesen5a2174f2007-10-03 17:45:27 +00009976 if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
9977 // This is not safe in general for floating point:
9978 // consider X== -0, Y== +0.
9979 // It becomes safe if either operand is a nonzero constant.
9980 ConstantFP *CFPt, *CFPf;
9981 if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
9982 !CFPt->getValueAPF().isZero()) ||
9983 ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
9984 !CFPf->getValueAPF().isZero()))
Chris Lattnerd76956d2004-04-10 22:21:27 +00009985 return ReplaceInstUsesWith(SI, FalseVal);
Dale Johannesen5a2174f2007-10-03 17:45:27 +00009986 }
Chris Lattnerd76956d2004-04-10 22:21:27 +00009987 // Transform (X != Y) ? X : Y -> X
Reid Spencere4d87aa2006-12-23 06:05:41 +00009988 if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
Chris Lattnerd76956d2004-04-10 22:21:27 +00009989 return ReplaceInstUsesWith(SI, TrueVal);
Dan Gohman81b28ce2008-09-16 18:46:06 +00009990 // NOTE: if we wanted to, this is where to detect MIN/MAX
Chris Lattnerd76956d2004-04-10 22:21:27 +00009991
Reid Spencere4d87aa2006-12-23 06:05:41 +00009992 } else if (FCI->getOperand(0) == FalseVal && FCI->getOperand(1) == TrueVal){
Chris Lattnerd76956d2004-04-10 22:21:27 +00009993 // Transform (X == Y) ? Y : X -> X
Dale Johannesen5a2174f2007-10-03 17:45:27 +00009994 if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
9995 // This is not safe in general for floating point:
9996 // consider X== -0, Y== +0.
9997 // It becomes safe if either operand is a nonzero constant.
9998 ConstantFP *CFPt, *CFPf;
9999 if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
10000 !CFPt->getValueAPF().isZero()) ||
10001 ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
10002 !CFPf->getValueAPF().isZero()))
10003 return ReplaceInstUsesWith(SI, FalseVal);
10004 }
Chris Lattnerd76956d2004-04-10 22:21:27 +000010005 // Transform (X != Y) ? Y : X -> Y
Reid Spencere4d87aa2006-12-23 06:05:41 +000010006 if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
10007 return ReplaceInstUsesWith(SI, TrueVal);
Dan Gohman81b28ce2008-09-16 18:46:06 +000010008 // NOTE: if we wanted to, this is where to detect MIN/MAX
Reid Spencere4d87aa2006-12-23 06:05:41 +000010009 }
Dan Gohman81b28ce2008-09-16 18:46:06 +000010010 // NOTE: if we wanted to, this is where to detect ABS
Reid Spencere4d87aa2006-12-23 06:05:41 +000010011 }
10012
10013 // See if we are selecting two values based on a comparison of the two values.
Dan Gohman81b28ce2008-09-16 18:46:06 +000010014 if (ICmpInst *ICI = dyn_cast<ICmpInst>(CondVal))
10015 if (Instruction *Result = visitSelectInstWithICmp(SI, ICI))
10016 return Result;
Misha Brukmanfd939082005-04-21 23:48:37 +000010017
Chris Lattner87875da2005-01-13 22:52:24 +000010018 if (Instruction *TI = dyn_cast<Instruction>(TrueVal))
10019 if (Instruction *FI = dyn_cast<Instruction>(FalseVal))
10020 if (TI->hasOneUse() && FI->hasOneUse()) {
Chris Lattner87875da2005-01-13 22:52:24 +000010021 Instruction *AddOp = 0, *SubOp = 0;
10022
Chris Lattner6fb5a4a2005-01-19 21:50:18 +000010023 // Turn (select C, (op X, Y), (op X, Z)) -> (op X, (select C, Y, Z))
10024 if (TI->getOpcode() == FI->getOpcode())
10025 if (Instruction *IV = FoldSelectOpOp(SI, TI, FI))
10026 return IV;
10027
10028 // Turn select C, (X+Y), (X-Y) --> (X+(select C, Y, (-Y))). This is
10029 // even legal for FP.
Dan Gohmanae3a0be2009-06-04 22:49:04 +000010030 if ((TI->getOpcode() == Instruction::Sub &&
10031 FI->getOpcode() == Instruction::Add) ||
10032 (TI->getOpcode() == Instruction::FSub &&
10033 FI->getOpcode() == Instruction::FAdd)) {
Chris Lattner87875da2005-01-13 22:52:24 +000010034 AddOp = FI; SubOp = TI;
Dan Gohmanae3a0be2009-06-04 22:49:04 +000010035 } else if ((FI->getOpcode() == Instruction::Sub &&
10036 TI->getOpcode() == Instruction::Add) ||
10037 (FI->getOpcode() == Instruction::FSub &&
10038 TI->getOpcode() == Instruction::FAdd)) {
Chris Lattner87875da2005-01-13 22:52:24 +000010039 AddOp = TI; SubOp = FI;
10040 }
10041
10042 if (AddOp) {
10043 Value *OtherAddOp = 0;
10044 if (SubOp->getOperand(0) == AddOp->getOperand(0)) {
10045 OtherAddOp = AddOp->getOperand(1);
10046 } else if (SubOp->getOperand(0) == AddOp->getOperand(1)) {
10047 OtherAddOp = AddOp->getOperand(0);
10048 }
10049
10050 if (OtherAddOp) {
Chris Lattner97f37a42006-02-24 18:05:58 +000010051 // So at this point we know we have (Y -> OtherAddOp):
10052 // select C, (add X, Y), (sub X, Z)
10053 Value *NegVal; // Compute -Z
10054 if (Constant *C = dyn_cast<Constant>(SubOp->getOperand(1))) {
Owen Andersonbaf3c402009-07-29 18:55:55 +000010055 NegVal = ConstantExpr::getNeg(C);
Chris Lattner97f37a42006-02-24 18:05:58 +000010056 } else {
10057 NegVal = InsertNewInstBefore(
Dan Gohman4ae51262009-08-12 16:23:25 +000010058 BinaryOperator::CreateNeg(SubOp->getOperand(1),
Owen Anderson0a5372e2009-07-13 04:09:18 +000010059 "tmp"), SI);
Chris Lattner87875da2005-01-13 22:52:24 +000010060 }
Chris Lattner97f37a42006-02-24 18:05:58 +000010061
10062 Value *NewTrueOp = OtherAddOp;
10063 Value *NewFalseOp = NegVal;
10064 if (AddOp != TI)
10065 std::swap(NewTrueOp, NewFalseOp);
10066 Instruction *NewSel =
Gabor Greifb1dbcd82008-05-15 10:04:30 +000010067 SelectInst::Create(CondVal, NewTrueOp,
10068 NewFalseOp, SI.getName() + ".p");
Chris Lattner97f37a42006-02-24 18:05:58 +000010069
10070 NewSel = InsertNewInstBefore(NewSel, SI);
Gabor Greif7cbd8a32008-05-16 19:29:10 +000010071 return BinaryOperator::CreateAdd(SubOp->getOperand(0), NewSel);
Chris Lattner87875da2005-01-13 22:52:24 +000010072 }
10073 }
10074 }
Misha Brukmanfd939082005-04-21 23:48:37 +000010075
Chris Lattnere576b912004-04-09 23:46:01 +000010076 // See if we can fold the select into one of our operands.
Chris Lattner42a75512007-01-15 02:27:26 +000010077 if (SI.getType()->isInteger()) {
Chris Lattnerb109b5c2009-12-21 06:03:05 +000010078 if (Instruction *FoldI = FoldSelectIntoOp(SI, TrueVal, FalseVal))
Evan Chengde621922009-03-31 20:42:45 +000010079 return FoldI;
Chris Lattnerb109b5c2009-12-21 06:03:05 +000010080
10081 // MAX(MAX(a, b), a) -> MAX(a, b)
10082 // MIN(MIN(a, b), a) -> MIN(a, b)
10083 // MAX(MIN(a, b), a) -> a
10084 // MIN(MAX(a, b), a) -> a
10085 Value *LHS, *RHS, *LHS2, *RHS2;
10086 if (SelectPatternFlavor SPF = MatchSelectPattern(&SI, LHS, RHS)) {
10087 if (SelectPatternFlavor SPF2 = MatchSelectPattern(LHS, LHS2, RHS2))
10088 if (Instruction *R = FoldSPFofSPF(cast<Instruction>(LHS),SPF2,LHS2,RHS2,
10089 SI, SPF, RHS))
10090 return R;
10091 if (SelectPatternFlavor SPF2 = MatchSelectPattern(RHS, LHS2, RHS2))
10092 if (Instruction *R = FoldSPFofSPF(cast<Instruction>(RHS),SPF2,LHS2,RHS2,
10093 SI, SPF, LHS))
10094 return R;
10095 }
10096
10097 // TODO.
10098 // ABS(-X) -> ABS(X)
10099 // ABS(ABS(X)) -> ABS(X)
Chris Lattnere576b912004-04-09 23:46:01 +000010100 }
Chris Lattnera1df33c2005-04-24 07:30:14 +000010101
Chris Lattner7f239582009-10-22 00:17:26 +000010102 // See if we can fold the select into a phi node if the condition is a select.
10103 if (isa<PHINode>(SI.getCondition()))
10104 // The true/false values have to be live in the PHI predecessor's blocks.
10105 if (CanSelectOperandBeMappingIntoPredBlock(TrueVal, SI) &&
10106 CanSelectOperandBeMappingIntoPredBlock(FalseVal, SI))
10107 if (Instruction *NV = FoldOpIntoPhi(SI))
10108 return NV;
Chris Lattner5d1704d2009-09-27 19:57:57 +000010109
Chris Lattnera1df33c2005-04-24 07:30:14 +000010110 if (BinaryOperator::isNot(CondVal)) {
10111 SI.setOperand(0, BinaryOperator::getNotArgument(CondVal));
10112 SI.setOperand(1, FalseVal);
10113 SI.setOperand(2, TrueVal);
10114 return &SI;
10115 }
10116
Chris Lattner3d69f462004-03-12 05:52:32 +000010117 return 0;
10118}
10119
Dan Gohmaneee962e2008-04-10 18:43:06 +000010120/// EnforceKnownAlignment - If the specified pointer points to an object that
10121/// we control, modify the object's alignment to PrefAlign. This isn't
10122/// often possible though. If alignment is important, a more reliable approach
10123/// is to simply align all global variables and allocation instructions to
10124/// their preferred alignment from the beginning.
10125///
10126static unsigned EnforceKnownAlignment(Value *V,
10127 unsigned Align, unsigned PrefAlign) {
Chris Lattnerf2369f22007-08-09 19:05:49 +000010128
Dan Gohmaneee962e2008-04-10 18:43:06 +000010129 User *U = dyn_cast<User>(V);
10130 if (!U) return Align;
10131
Dan Gohmanca178902009-07-17 20:47:02 +000010132 switch (Operator::getOpcode(U)) {
Dan Gohmaneee962e2008-04-10 18:43:06 +000010133 default: break;
10134 case Instruction::BitCast:
10135 return EnforceKnownAlignment(U->getOperand(0), Align, PrefAlign);
10136 case Instruction::GetElementPtr: {
Chris Lattner95a959d2006-03-06 20:18:44 +000010137 // If all indexes are zero, it is just the alignment of the base pointer.
10138 bool AllZeroOperands = true;
Gabor Greif52ed3632008-06-12 21:51:29 +000010139 for (User::op_iterator i = U->op_begin() + 1, e = U->op_end(); i != e; ++i)
Gabor Greif177dd3f2008-06-12 21:37:33 +000010140 if (!isa<Constant>(*i) ||
10141 !cast<Constant>(*i)->isNullValue()) {
Chris Lattner95a959d2006-03-06 20:18:44 +000010142 AllZeroOperands = false;
10143 break;
10144 }
Chris Lattnerf2369f22007-08-09 19:05:49 +000010145
10146 if (AllZeroOperands) {
10147 // Treat this like a bitcast.
Dan Gohmaneee962e2008-04-10 18:43:06 +000010148 return EnforceKnownAlignment(U->getOperand(0), Align, PrefAlign);
Chris Lattnerf2369f22007-08-09 19:05:49 +000010149 }
Dan Gohmaneee962e2008-04-10 18:43:06 +000010150 break;
Chris Lattner95a959d2006-03-06 20:18:44 +000010151 }
Dan Gohmaneee962e2008-04-10 18:43:06 +000010152 }
10153
10154 if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
10155 // If there is a large requested alignment and we can, bump up the alignment
10156 // of the global.
10157 if (!GV->isDeclaration()) {
Dan Gohmanecd0fb52009-02-16 23:02:21 +000010158 if (GV->getAlignment() >= PrefAlign)
10159 Align = GV->getAlignment();
10160 else {
10161 GV->setAlignment(PrefAlign);
10162 Align = PrefAlign;
10163 }
Dan Gohmaneee962e2008-04-10 18:43:06 +000010164 }
Chris Lattner42ebefa2009-09-27 21:42:46 +000010165 } else if (AllocaInst *AI = dyn_cast<AllocaInst>(V)) {
10166 // If there is a requested alignment and if this is an alloca, round up.
10167 if (AI->getAlignment() >= PrefAlign)
10168 Align = AI->getAlignment();
10169 else {
10170 AI->setAlignment(PrefAlign);
10171 Align = PrefAlign;
Dan Gohmaneee962e2008-04-10 18:43:06 +000010172 }
10173 }
10174
10175 return Align;
10176}
10177
10178/// GetOrEnforceKnownAlignment - If the specified pointer has an alignment that
10179/// we can determine, return it, otherwise return 0. If PrefAlign is specified,
10180/// and it is more than the alignment of the ultimate object, see if we can
10181/// increase the alignment of the ultimate object, making this check succeed.
10182unsigned InstCombiner::GetOrEnforceKnownAlignment(Value *V,
10183 unsigned PrefAlign) {
10184 unsigned BitWidth = TD ? TD->getTypeSizeInBits(V->getType()) :
10185 sizeof(PrefAlign) * CHAR_BIT;
10186 APInt Mask = APInt::getAllOnesValue(BitWidth);
10187 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
10188 ComputeMaskedBits(V, Mask, KnownZero, KnownOne);
10189 unsigned TrailZ = KnownZero.countTrailingOnes();
10190 unsigned Align = 1u << std::min(BitWidth - 1, TrailZ);
10191
10192 if (PrefAlign > Align)
10193 Align = EnforceKnownAlignment(V, Align, PrefAlign);
10194
10195 // We don't need to make any adjustment.
10196 return Align;
Chris Lattner95a959d2006-03-06 20:18:44 +000010197}
10198
Chris Lattnerf497b022008-01-13 23:50:23 +000010199Instruction *InstCombiner::SimplifyMemTransfer(MemIntrinsic *MI) {
Dan Gohmaneee962e2008-04-10 18:43:06 +000010200 unsigned DstAlign = GetOrEnforceKnownAlignment(MI->getOperand(1));
Dan Gohmanbc989d42009-02-22 18:06:32 +000010201 unsigned SrcAlign = GetOrEnforceKnownAlignment(MI->getOperand(2));
Chris Lattnerf497b022008-01-13 23:50:23 +000010202 unsigned MinAlign = std::min(DstAlign, SrcAlign);
Chris Lattnerdfe964c2009-03-08 03:59:00 +000010203 unsigned CopyAlign = MI->getAlignment();
Chris Lattnerf497b022008-01-13 23:50:23 +000010204
10205 if (CopyAlign < MinAlign) {
Owen Andersoneed707b2009-07-24 23:12:02 +000010206 MI->setAlignment(ConstantInt::get(MI->getAlignmentType(),
Owen Andersona547b472009-07-09 18:36:20 +000010207 MinAlign, false));
Chris Lattnerf497b022008-01-13 23:50:23 +000010208 return MI;
10209 }
10210
10211 // If MemCpyInst length is 1/2/4/8 bytes then replace memcpy with
10212 // load/store.
10213 ConstantInt *MemOpLength = dyn_cast<ConstantInt>(MI->getOperand(3));
10214 if (MemOpLength == 0) return 0;
10215
Chris Lattner37ac6082008-01-14 00:28:35 +000010216 // Source and destination pointer types are always "i8*" for intrinsic. See
10217 // if the size is something we can handle with a single primitive load/store.
10218 // A single load+store correctly handles overlapping memory in the memmove
10219 // case.
Chris Lattnerf497b022008-01-13 23:50:23 +000010220 unsigned Size = MemOpLength->getZExtValue();
Chris Lattner69ea9d22008-04-30 06:39:11 +000010221 if (Size == 0) return MI; // Delete this mem transfer.
10222
10223 if (Size > 8 || (Size&(Size-1)))
Chris Lattner37ac6082008-01-14 00:28:35 +000010224 return 0; // If not 1/2/4/8 bytes, exit.
Chris Lattnerf497b022008-01-13 23:50:23 +000010225
Chris Lattner37ac6082008-01-14 00:28:35 +000010226 // Use an integer load+store unless we can find something better.
Owen Andersond672ecb2009-07-03 00:17:18 +000010227 Type *NewPtrTy =
Owen Anderson1d0be152009-08-13 21:58:54 +000010228 PointerType::getUnqual(IntegerType::get(*Context, Size<<3));
Chris Lattner37ac6082008-01-14 00:28:35 +000010229
10230 // Memcpy forces the use of i8* for the source and destination. That means
10231 // that if you're using memcpy to move one double around, you'll get a cast
10232 // from double* to i8*. We'd much rather use a double load+store rather than
10233 // an i64 load+store, here because this improves the odds that the source or
10234 // dest address will be promotable. See if we can find a better type than the
10235 // integer datatype.
10236 if (Value *Op = getBitCastOperand(MI->getOperand(1))) {
10237 const Type *SrcETy = cast<PointerType>(Op->getType())->getElementType();
Dan Gohmance9fe9f2009-07-21 23:21:54 +000010238 if (TD && SrcETy->isSized() && TD->getTypeStoreSize(SrcETy) == Size) {
Chris Lattner37ac6082008-01-14 00:28:35 +000010239 // The SrcETy might be something like {{{double}}} or [1 x double]. Rip
10240 // down through these levels if so.
Dan Gohman8f8e2692008-05-23 01:52:21 +000010241 while (!SrcETy->isSingleValueType()) {
Chris Lattner37ac6082008-01-14 00:28:35 +000010242 if (const StructType *STy = dyn_cast<StructType>(SrcETy)) {
10243 if (STy->getNumElements() == 1)
10244 SrcETy = STy->getElementType(0);
10245 else
10246 break;
10247 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(SrcETy)) {
10248 if (ATy->getNumElements() == 1)
10249 SrcETy = ATy->getElementType();
10250 else
10251 break;
10252 } else
10253 break;
10254 }
10255
Dan Gohman8f8e2692008-05-23 01:52:21 +000010256 if (SrcETy->isSingleValueType())
Owen Andersondebcb012009-07-29 22:17:13 +000010257 NewPtrTy = PointerType::getUnqual(SrcETy);
Chris Lattner37ac6082008-01-14 00:28:35 +000010258 }
10259 }
10260
10261
Chris Lattnerf497b022008-01-13 23:50:23 +000010262 // If the memcpy/memmove provides better alignment info than we can
10263 // infer, use it.
10264 SrcAlign = std::max(SrcAlign, CopyAlign);
10265 DstAlign = std::max(DstAlign, CopyAlign);
10266
Chris Lattner08142f22009-08-30 19:47:22 +000010267 Value *Src = Builder->CreateBitCast(MI->getOperand(2), NewPtrTy);
10268 Value *Dest = Builder->CreateBitCast(MI->getOperand(1), NewPtrTy);
Chris Lattner37ac6082008-01-14 00:28:35 +000010269 Instruction *L = new LoadInst(Src, "tmp", false, SrcAlign);
10270 InsertNewInstBefore(L, *MI);
10271 InsertNewInstBefore(new StoreInst(L, Dest, false, DstAlign), *MI);
10272
10273 // Set the size of the copy to 0, it will be deleted on the next iteration.
Owen Andersona7235ea2009-07-31 20:28:14 +000010274 MI->setOperand(3, Constant::getNullValue(MemOpLength->getType()));
Chris Lattner37ac6082008-01-14 00:28:35 +000010275 return MI;
Chris Lattnerf497b022008-01-13 23:50:23 +000010276}
Chris Lattner3d69f462004-03-12 05:52:32 +000010277
Chris Lattner69ea9d22008-04-30 06:39:11 +000010278Instruction *InstCombiner::SimplifyMemSet(MemSetInst *MI) {
10279 unsigned Alignment = GetOrEnforceKnownAlignment(MI->getDest());
Chris Lattnerdfe964c2009-03-08 03:59:00 +000010280 if (MI->getAlignment() < Alignment) {
Owen Andersoneed707b2009-07-24 23:12:02 +000010281 MI->setAlignment(ConstantInt::get(MI->getAlignmentType(),
Owen Andersona547b472009-07-09 18:36:20 +000010282 Alignment, false));
Chris Lattner69ea9d22008-04-30 06:39:11 +000010283 return MI;
10284 }
10285
10286 // Extract the length and alignment and fill if they are constant.
10287 ConstantInt *LenC = dyn_cast<ConstantInt>(MI->getLength());
10288 ConstantInt *FillC = dyn_cast<ConstantInt>(MI->getValue());
Owen Anderson1d0be152009-08-13 21:58:54 +000010289 if (!LenC || !FillC || FillC->getType() != Type::getInt8Ty(*Context))
Chris Lattner69ea9d22008-04-30 06:39:11 +000010290 return 0;
10291 uint64_t Len = LenC->getZExtValue();
Chris Lattnerdfe964c2009-03-08 03:59:00 +000010292 Alignment = MI->getAlignment();
Chris Lattner69ea9d22008-04-30 06:39:11 +000010293
10294 // If the length is zero, this is a no-op
10295 if (Len == 0) return MI; // memset(d,c,0,a) -> noop
10296
10297 // memset(s,c,n) -> store s, c (for n=1,2,4,8)
10298 if (Len <= 8 && isPowerOf2_32((uint32_t)Len)) {
Owen Anderson1d0be152009-08-13 21:58:54 +000010299 const Type *ITy = IntegerType::get(*Context, Len*8); // n=1 -> i8.
Chris Lattner69ea9d22008-04-30 06:39:11 +000010300
10301 Value *Dest = MI->getDest();
Chris Lattner08142f22009-08-30 19:47:22 +000010302 Dest = Builder->CreateBitCast(Dest, PointerType::getUnqual(ITy));
Chris Lattner69ea9d22008-04-30 06:39:11 +000010303
10304 // Alignment 0 is identity for alignment 1 for memset, but not store.
10305 if (Alignment == 0) Alignment = 1;
10306
10307 // Extract the fill value and store.
10308 uint64_t Fill = FillC->getZExtValue()*0x0101010101010101ULL;
Owen Andersoneed707b2009-07-24 23:12:02 +000010309 InsertNewInstBefore(new StoreInst(ConstantInt::get(ITy, Fill),
Owen Andersond672ecb2009-07-03 00:17:18 +000010310 Dest, false, Alignment), *MI);
Chris Lattner69ea9d22008-04-30 06:39:11 +000010311
10312 // Set the size of the copy to 0, it will be deleted on the next iteration.
Owen Andersona7235ea2009-07-31 20:28:14 +000010313 MI->setLength(Constant::getNullValue(LenC->getType()));
Chris Lattner69ea9d22008-04-30 06:39:11 +000010314 return MI;
10315 }
10316
10317 return 0;
10318}
10319
10320
Chris Lattner8b0ea312006-01-13 20:11:04 +000010321/// visitCallInst - CallInst simplification. This mostly only handles folding
10322/// of intrinsic instructions. For normal calls, it allows visitCallSite to do
10323/// the heavy lifting.
10324///
Chris Lattner9fe38862003-06-19 17:00:31 +000010325Instruction *InstCombiner::visitCallInst(CallInst &CI) {
Victor Hernandez66284e02009-10-24 04:23:03 +000010326 if (isFreeCall(&CI))
10327 return visitFree(CI);
10328
Chris Lattneraab6ec42009-05-13 17:39:14 +000010329 // If the caller function is nounwind, mark the call as nounwind, even if the
10330 // callee isn't.
10331 if (CI.getParent()->getParent()->doesNotThrow() &&
10332 !CI.doesNotThrow()) {
10333 CI.setDoesNotThrow();
10334 return &CI;
10335 }
10336
Chris Lattner8b0ea312006-01-13 20:11:04 +000010337 IntrinsicInst *II = dyn_cast<IntrinsicInst>(&CI);
10338 if (!II) return visitCallSite(&CI);
10339
Chris Lattner7bcc0e72004-02-28 05:22:00 +000010340 // Intrinsics cannot occur in an invoke, so handle them here instead of in
10341 // visitCallSite.
Chris Lattner8b0ea312006-01-13 20:11:04 +000010342 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(II)) {
Chris Lattner35b9e482004-10-12 04:52:52 +000010343 bool Changed = false;
10344
10345 // memmove/cpy/set of zero bytes is a noop.
10346 if (Constant *NumBytes = dyn_cast<Constant>(MI->getLength())) {
10347 if (NumBytes->isNullValue()) return EraseInstFromFunction(CI);
10348
Chris Lattner35b9e482004-10-12 04:52:52 +000010349 if (ConstantInt *CI = dyn_cast<ConstantInt>(NumBytes))
Reid Spencerb83eb642006-10-20 07:07:24 +000010350 if (CI->getZExtValue() == 1) {
Chris Lattner35b9e482004-10-12 04:52:52 +000010351 // Replace the instruction with just byte operations. We would
10352 // transform other cases to loads/stores, but we don't know if
10353 // alignment is sufficient.
10354 }
Chris Lattner7bcc0e72004-02-28 05:22:00 +000010355 }
10356
Chris Lattner35b9e482004-10-12 04:52:52 +000010357 // If we have a memmove and the source operation is a constant global,
10358 // then the source and dest pointers can't alias, so we can change this
10359 // into a call to memcpy.
Chris Lattnerf497b022008-01-13 23:50:23 +000010360 if (MemMoveInst *MMI = dyn_cast<MemMoveInst>(MI)) {
Chris Lattner35b9e482004-10-12 04:52:52 +000010361 if (GlobalVariable *GVSrc = dyn_cast<GlobalVariable>(MMI->getSource()))
10362 if (GVSrc->isConstant()) {
10363 Module *M = CI.getParent()->getParent()->getParent();
Chris Lattner824b9582008-11-21 16:42:48 +000010364 Intrinsic::ID MemCpyID = Intrinsic::memcpy;
10365 const Type *Tys[1];
10366 Tys[0] = CI.getOperand(3)->getType();
10367 CI.setOperand(0,
10368 Intrinsic::getDeclaration(M, MemCpyID, Tys, 1));
Chris Lattner35b9e482004-10-12 04:52:52 +000010369 Changed = true;
10370 }
Eli Friedman0c826d92009-12-17 21:07:31 +000010371 }
Chris Lattnera935db82008-05-28 05:30:41 +000010372
Eli Friedman0c826d92009-12-17 21:07:31 +000010373 if (MemTransferInst *MTI = dyn_cast<MemTransferInst>(MI)) {
Chris Lattnera935db82008-05-28 05:30:41 +000010374 // memmove(x,x,size) -> noop.
Eli Friedman0c826d92009-12-17 21:07:31 +000010375 if (MTI->getSource() == MTI->getDest())
Chris Lattnera935db82008-05-28 05:30:41 +000010376 return EraseInstFromFunction(CI);
Chris Lattner95a959d2006-03-06 20:18:44 +000010377 }
Chris Lattner35b9e482004-10-12 04:52:52 +000010378
Chris Lattner95a959d2006-03-06 20:18:44 +000010379 // If we can determine a pointer alignment that is bigger than currently
10380 // set, update the alignment.
Chris Lattner3ce5e882009-03-08 03:37:16 +000010381 if (isa<MemTransferInst>(MI)) {
Chris Lattnerf497b022008-01-13 23:50:23 +000010382 if (Instruction *I = SimplifyMemTransfer(MI))
10383 return I;
Chris Lattner69ea9d22008-04-30 06:39:11 +000010384 } else if (MemSetInst *MSI = dyn_cast<MemSetInst>(MI)) {
10385 if (Instruction *I = SimplifyMemSet(MSI))
10386 return I;
Chris Lattner95a959d2006-03-06 20:18:44 +000010387 }
10388
Chris Lattner8b0ea312006-01-13 20:11:04 +000010389 if (Changed) return II;
Chris Lattner0521e3c2008-06-18 04:33:20 +000010390 }
10391
10392 switch (II->getIntrinsicID()) {
10393 default: break;
10394 case Intrinsic::bswap:
10395 // bswap(bswap(x)) -> x
10396 if (IntrinsicInst *Operand = dyn_cast<IntrinsicInst>(II->getOperand(1)))
10397 if (Operand->getIntrinsicID() == Intrinsic::bswap)
10398 return ReplaceInstUsesWith(CI, Operand->getOperand(1));
Chris Lattnere33d4132010-01-01 18:34:40 +000010399
10400 // bswap(trunc(bswap(x))) -> trunc(lshr(x, c))
10401 if (TruncInst *TI = dyn_cast<TruncInst>(II->getOperand(1))) {
10402 if (IntrinsicInst *Operand = dyn_cast<IntrinsicInst>(TI->getOperand(0)))
10403 if (Operand->getIntrinsicID() == Intrinsic::bswap) {
10404 unsigned C = Operand->getType()->getPrimitiveSizeInBits() -
10405 TI->getType()->getPrimitiveSizeInBits();
10406 Value *CV = ConstantInt::get(Operand->getType(), C);
10407 Value *V = Builder->CreateLShr(Operand->getOperand(1), CV);
10408 return new TruncInst(V, TI->getType());
10409 }
10410 }
10411
Chris Lattner0521e3c2008-06-18 04:33:20 +000010412 break;
Chris Lattnerd27f9112010-01-01 01:52:15 +000010413 case Intrinsic::powi:
10414 if (ConstantInt *Power = dyn_cast<ConstantInt>(II->getOperand(2))) {
10415 // powi(x, 0) -> 1.0
10416 if (Power->isZero())
10417 return ReplaceInstUsesWith(CI, ConstantFP::get(CI.getType(), 1.0));
10418 // powi(x, 1) -> x
10419 if (Power->isOne())
10420 return ReplaceInstUsesWith(CI, II->getOperand(1));
10421 // powi(x, -1) -> 1/x
Chris Lattnerf9ead872010-01-01 01:54:08 +000010422 if (Power->isAllOnesValue())
10423 return BinaryOperator::CreateFDiv(ConstantFP::get(CI.getType(), 1.0),
10424 II->getOperand(1));
Chris Lattnerd27f9112010-01-01 01:52:15 +000010425 }
10426 break;
10427
Chris Lattner2bbac752009-11-26 21:42:47 +000010428 case Intrinsic::uadd_with_overflow: {
10429 Value *LHS = II->getOperand(1), *RHS = II->getOperand(2);
10430 const IntegerType *IT = cast<IntegerType>(II->getOperand(1)->getType());
10431 uint32_t BitWidth = IT->getBitWidth();
10432 APInt Mask = APInt::getSignBit(BitWidth);
Chris Lattner998e25a2009-11-26 22:08:06 +000010433 APInt LHSKnownZero(BitWidth, 0);
10434 APInt LHSKnownOne(BitWidth, 0);
Chris Lattner2bbac752009-11-26 21:42:47 +000010435 ComputeMaskedBits(LHS, Mask, LHSKnownZero, LHSKnownOne);
10436 bool LHSKnownNegative = LHSKnownOne[BitWidth - 1];
10437 bool LHSKnownPositive = LHSKnownZero[BitWidth - 1];
10438
10439 if (LHSKnownNegative || LHSKnownPositive) {
Chris Lattner998e25a2009-11-26 22:08:06 +000010440 APInt RHSKnownZero(BitWidth, 0);
10441 APInt RHSKnownOne(BitWidth, 0);
Chris Lattner2bbac752009-11-26 21:42:47 +000010442 ComputeMaskedBits(RHS, Mask, RHSKnownZero, RHSKnownOne);
10443 bool RHSKnownNegative = RHSKnownOne[BitWidth - 1];
10444 bool RHSKnownPositive = RHSKnownZero[BitWidth - 1];
10445 if (LHSKnownNegative && RHSKnownNegative) {
10446 // The sign bit is set in both cases: this MUST overflow.
10447 // Create a simple add instruction, and insert it into the struct.
10448 Instruction *Add = BinaryOperator::CreateAdd(LHS, RHS, "", &CI);
10449 Worklist.Add(Add);
Chris Lattnercd188e92009-11-29 02:57:29 +000010450 Constant *V[] = {
10451 UndefValue::get(LHS->getType()), ConstantInt::getTrue(*Context)
10452 };
Chris Lattner2bbac752009-11-26 21:42:47 +000010453 Constant *Struct = ConstantStruct::get(*Context, V, 2, false);
10454 return InsertValueInst::Create(Struct, Add, 0);
10455 }
10456
10457 if (LHSKnownPositive && RHSKnownPositive) {
10458 // The sign bit is clear in both cases: this CANNOT overflow.
10459 // Create a simple add instruction, and insert it into the struct.
10460 Instruction *Add = BinaryOperator::CreateNUWAdd(LHS, RHS, "", &CI);
10461 Worklist.Add(Add);
Chris Lattnercd188e92009-11-29 02:57:29 +000010462 Constant *V[] = {
10463 UndefValue::get(LHS->getType()), ConstantInt::getFalse(*Context)
10464 };
Chris Lattner2bbac752009-11-26 21:42:47 +000010465 Constant *Struct = ConstantStruct::get(*Context, V, 2, false);
10466 return InsertValueInst::Create(Struct, Add, 0);
10467 }
10468 }
10469 }
10470 // FALL THROUGH uadd into sadd
10471 case Intrinsic::sadd_with_overflow:
10472 // Canonicalize constants into the RHS.
10473 if (isa<Constant>(II->getOperand(1)) &&
10474 !isa<Constant>(II->getOperand(2))) {
10475 Value *LHS = II->getOperand(1);
10476 II->setOperand(1, II->getOperand(2));
10477 II->setOperand(2, LHS);
10478 return II;
10479 }
10480
10481 // X + undef -> undef
10482 if (isa<UndefValue>(II->getOperand(2)))
10483 return ReplaceInstUsesWith(CI, UndefValue::get(II->getType()));
10484
10485 if (ConstantInt *RHS = dyn_cast<ConstantInt>(II->getOperand(2))) {
10486 // X + 0 -> {X, false}
10487 if (RHS->isZero()) {
10488 Constant *V[] = {
Chris Lattnercd188e92009-11-29 02:57:29 +000010489 UndefValue::get(II->getOperand(0)->getType()),
10490 ConstantInt::getFalse(*Context)
Chris Lattner2bbac752009-11-26 21:42:47 +000010491 };
10492 Constant *Struct = ConstantStruct::get(*Context, V, 2, false);
10493 return InsertValueInst::Create(Struct, II->getOperand(1), 0);
10494 }
10495 }
10496 break;
10497 case Intrinsic::usub_with_overflow:
10498 case Intrinsic::ssub_with_overflow:
10499 // undef - X -> undef
10500 // X - undef -> undef
10501 if (isa<UndefValue>(II->getOperand(1)) ||
10502 isa<UndefValue>(II->getOperand(2)))
10503 return ReplaceInstUsesWith(CI, UndefValue::get(II->getType()));
10504
10505 if (ConstantInt *RHS = dyn_cast<ConstantInt>(II->getOperand(2))) {
10506 // X - 0 -> {X, false}
10507 if (RHS->isZero()) {
10508 Constant *V[] = {
Chris Lattnercd188e92009-11-29 02:57:29 +000010509 UndefValue::get(II->getOperand(1)->getType()),
10510 ConstantInt::getFalse(*Context)
Chris Lattner2bbac752009-11-26 21:42:47 +000010511 };
10512 Constant *Struct = ConstantStruct::get(*Context, V, 2, false);
10513 return InsertValueInst::Create(Struct, II->getOperand(1), 0);
10514 }
10515 }
10516 break;
10517 case Intrinsic::umul_with_overflow:
10518 case Intrinsic::smul_with_overflow:
10519 // Canonicalize constants into the RHS.
10520 if (isa<Constant>(II->getOperand(1)) &&
10521 !isa<Constant>(II->getOperand(2))) {
10522 Value *LHS = II->getOperand(1);
10523 II->setOperand(1, II->getOperand(2));
10524 II->setOperand(2, LHS);
10525 return II;
10526 }
10527
10528 // X * undef -> undef
10529 if (isa<UndefValue>(II->getOperand(2)))
10530 return ReplaceInstUsesWith(CI, UndefValue::get(II->getType()));
10531
10532 if (ConstantInt *RHSI = dyn_cast<ConstantInt>(II->getOperand(2))) {
10533 // X*0 -> {0, false}
10534 if (RHSI->isZero())
10535 return ReplaceInstUsesWith(CI, Constant::getNullValue(II->getType()));
10536
10537 // X * 1 -> {X, false}
10538 if (RHSI->equalsInt(1)) {
Chris Lattnercd188e92009-11-29 02:57:29 +000010539 Constant *V[] = {
10540 UndefValue::get(II->getOperand(1)->getType()),
10541 ConstantInt::getFalse(*Context)
10542 };
Chris Lattner2bbac752009-11-26 21:42:47 +000010543 Constant *Struct = ConstantStruct::get(*Context, V, 2, false);
Chris Lattnercd188e92009-11-29 02:57:29 +000010544 return InsertValueInst::Create(Struct, II->getOperand(1), 0);
Chris Lattner2bbac752009-11-26 21:42:47 +000010545 }
10546 }
10547 break;
Chris Lattner0521e3c2008-06-18 04:33:20 +000010548 case Intrinsic::ppc_altivec_lvx:
10549 case Intrinsic::ppc_altivec_lvxl:
10550 case Intrinsic::x86_sse_loadu_ps:
10551 case Intrinsic::x86_sse2_loadu_pd:
10552 case Intrinsic::x86_sse2_loadu_dq:
10553 // Turn PPC lvx -> load if the pointer is known aligned.
10554 // Turn X86 loadups -> load if the pointer is known aligned.
10555 if (GetOrEnforceKnownAlignment(II->getOperand(1), 16) >= 16) {
Chris Lattner08142f22009-08-30 19:47:22 +000010556 Value *Ptr = Builder->CreateBitCast(II->getOperand(1),
10557 PointerType::getUnqual(II->getType()));
Chris Lattner0521e3c2008-06-18 04:33:20 +000010558 return new LoadInst(Ptr);
Chris Lattner867b99f2006-10-05 06:55:50 +000010559 }
Chris Lattner0521e3c2008-06-18 04:33:20 +000010560 break;
10561 case Intrinsic::ppc_altivec_stvx:
10562 case Intrinsic::ppc_altivec_stvxl:
10563 // Turn stvx -> store if the pointer is known aligned.
10564 if (GetOrEnforceKnownAlignment(II->getOperand(2), 16) >= 16) {
10565 const Type *OpPtrTy =
Owen Andersondebcb012009-07-29 22:17:13 +000010566 PointerType::getUnqual(II->getOperand(1)->getType());
Chris Lattner08142f22009-08-30 19:47:22 +000010567 Value *Ptr = Builder->CreateBitCast(II->getOperand(2), OpPtrTy);
Chris Lattner0521e3c2008-06-18 04:33:20 +000010568 return new StoreInst(II->getOperand(1), Ptr);
10569 }
10570 break;
10571 case Intrinsic::x86_sse_storeu_ps:
10572 case Intrinsic::x86_sse2_storeu_pd:
10573 case Intrinsic::x86_sse2_storeu_dq:
Chris Lattner0521e3c2008-06-18 04:33:20 +000010574 // Turn X86 storeu -> store if the pointer is known aligned.
10575 if (GetOrEnforceKnownAlignment(II->getOperand(1), 16) >= 16) {
10576 const Type *OpPtrTy =
Owen Andersondebcb012009-07-29 22:17:13 +000010577 PointerType::getUnqual(II->getOperand(2)->getType());
Chris Lattner08142f22009-08-30 19:47:22 +000010578 Value *Ptr = Builder->CreateBitCast(II->getOperand(1), OpPtrTy);
Chris Lattner0521e3c2008-06-18 04:33:20 +000010579 return new StoreInst(II->getOperand(2), Ptr);
10580 }
10581 break;
10582
10583 case Intrinsic::x86_sse_cvttss2si: {
10584 // These intrinsics only demands the 0th element of its input vector. If
10585 // we can simplify the input based on that, do so now.
Evan Cheng388df622009-02-03 10:05:09 +000010586 unsigned VWidth =
10587 cast<VectorType>(II->getOperand(1)->getType())->getNumElements();
10588 APInt DemandedElts(VWidth, 1);
10589 APInt UndefElts(VWidth, 0);
10590 if (Value *V = SimplifyDemandedVectorElts(II->getOperand(1), DemandedElts,
Chris Lattner0521e3c2008-06-18 04:33:20 +000010591 UndefElts)) {
10592 II->setOperand(1, V);
10593 return II;
10594 }
10595 break;
10596 }
10597
10598 case Intrinsic::ppc_altivec_vperm:
10599 // Turn vperm(V1,V2,mask) -> shuffle(V1,V2,mask) if mask is a constant.
10600 if (ConstantVector *Mask = dyn_cast<ConstantVector>(II->getOperand(3))) {
10601 assert(Mask->getNumOperands() == 16 && "Bad type for intrinsic!");
Chris Lattner867b99f2006-10-05 06:55:50 +000010602
Chris Lattner0521e3c2008-06-18 04:33:20 +000010603 // Check that all of the elements are integer constants or undefs.
10604 bool AllEltsOk = true;
10605 for (unsigned i = 0; i != 16; ++i) {
10606 if (!isa<ConstantInt>(Mask->getOperand(i)) &&
10607 !isa<UndefValue>(Mask->getOperand(i))) {
10608 AllEltsOk = false;
10609 break;
10610 }
10611 }
10612
10613 if (AllEltsOk) {
10614 // Cast the input vectors to byte vectors.
Chris Lattner08142f22009-08-30 19:47:22 +000010615 Value *Op0 = Builder->CreateBitCast(II->getOperand(1), Mask->getType());
10616 Value *Op1 = Builder->CreateBitCast(II->getOperand(2), Mask->getType());
Owen Anderson9e9a0d52009-07-30 23:03:37 +000010617 Value *Result = UndefValue::get(Op0->getType());
Chris Lattnere2ed0572006-04-06 19:19:17 +000010618
Chris Lattner0521e3c2008-06-18 04:33:20 +000010619 // Only extract each element once.
10620 Value *ExtractedElts[32];
10621 memset(ExtractedElts, 0, sizeof(ExtractedElts));
10622
Chris Lattnere2ed0572006-04-06 19:19:17 +000010623 for (unsigned i = 0; i != 16; ++i) {
Chris Lattner0521e3c2008-06-18 04:33:20 +000010624 if (isa<UndefValue>(Mask->getOperand(i)))
10625 continue;
10626 unsigned Idx=cast<ConstantInt>(Mask->getOperand(i))->getZExtValue();
10627 Idx &= 31; // Match the hardware behavior.
10628
10629 if (ExtractedElts[Idx] == 0) {
Chris Lattnerf925cbd2009-08-30 18:50:58 +000010630 ExtractedElts[Idx] =
10631 Builder->CreateExtractElement(Idx < 16 ? Op0 : Op1,
10632 ConstantInt::get(Type::getInt32Ty(*Context), Idx&15, false),
10633 "tmp");
Chris Lattnere2ed0572006-04-06 19:19:17 +000010634 }
Chris Lattnere2ed0572006-04-06 19:19:17 +000010635
Chris Lattner0521e3c2008-06-18 04:33:20 +000010636 // Insert this value into the result vector.
Chris Lattnerf925cbd2009-08-30 18:50:58 +000010637 Result = Builder->CreateInsertElement(Result, ExtractedElts[Idx],
10638 ConstantInt::get(Type::getInt32Ty(*Context), i, false),
10639 "tmp");
Chris Lattnere2ed0572006-04-06 19:19:17 +000010640 }
Chris Lattner0521e3c2008-06-18 04:33:20 +000010641 return CastInst::Create(Instruction::BitCast, Result, CI.getType());
Chris Lattnere2ed0572006-04-06 19:19:17 +000010642 }
Chris Lattner0521e3c2008-06-18 04:33:20 +000010643 }
10644 break;
Chris Lattnere2ed0572006-04-06 19:19:17 +000010645
Chris Lattner0521e3c2008-06-18 04:33:20 +000010646 case Intrinsic::stackrestore: {
10647 // If the save is right next to the restore, remove the restore. This can
10648 // happen when variable allocas are DCE'd.
10649 if (IntrinsicInst *SS = dyn_cast<IntrinsicInst>(II->getOperand(1))) {
10650 if (SS->getIntrinsicID() == Intrinsic::stacksave) {
10651 BasicBlock::iterator BI = SS;
10652 if (&*++BI == II)
10653 return EraseInstFromFunction(CI);
Chris Lattnera728ddc2006-01-13 21:28:09 +000010654 }
Chris Lattner0521e3c2008-06-18 04:33:20 +000010655 }
10656
10657 // Scan down this block to see if there is another stack restore in the
10658 // same block without an intervening call/alloca.
10659 BasicBlock::iterator BI = II;
10660 TerminatorInst *TI = II->getParent()->getTerminator();
10661 bool CannotRemove = false;
10662 for (++BI; &*BI != TI; ++BI) {
Victor Hernandez83d63912009-09-18 22:35:49 +000010663 if (isa<AllocaInst>(BI) || isMalloc(BI)) {
Chris Lattner0521e3c2008-06-18 04:33:20 +000010664 CannotRemove = true;
10665 break;
10666 }
Chris Lattneraa0bf522008-06-25 05:59:28 +000010667 if (CallInst *BCI = dyn_cast<CallInst>(BI)) {
10668 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(BCI)) {
10669 // If there is a stackrestore below this one, remove this one.
10670 if (II->getIntrinsicID() == Intrinsic::stackrestore)
10671 return EraseInstFromFunction(CI);
10672 // Otherwise, ignore the intrinsic.
10673 } else {
10674 // If we found a non-intrinsic call, we can't remove the stack
10675 // restore.
Chris Lattnerbf1d8a72008-02-18 06:12:38 +000010676 CannotRemove = true;
10677 break;
10678 }
Chris Lattner0521e3c2008-06-18 04:33:20 +000010679 }
Chris Lattnera728ddc2006-01-13 21:28:09 +000010680 }
Chris Lattner0521e3c2008-06-18 04:33:20 +000010681
10682 // If the stack restore is in a return/unwind block and if there are no
10683 // allocas or calls between the restore and the return, nuke the restore.
10684 if (!CannotRemove && (isa<ReturnInst>(TI) || isa<UnwindInst>(TI)))
10685 return EraseInstFromFunction(CI);
10686 break;
10687 }
Chris Lattner35b9e482004-10-12 04:52:52 +000010688 }
10689
Chris Lattner8b0ea312006-01-13 20:11:04 +000010690 return visitCallSite(II);
Chris Lattner9fe38862003-06-19 17:00:31 +000010691}
10692
10693// InvokeInst simplification
10694//
10695Instruction *InstCombiner::visitInvokeInst(InvokeInst &II) {
Chris Lattnera44d8a22003-10-07 22:32:43 +000010696 return visitCallSite(&II);
Chris Lattner9fe38862003-06-19 17:00:31 +000010697}
10698
Dale Johannesenda30ccb2008-04-25 21:16:07 +000010699/// isSafeToEliminateVarargsCast - If this cast does not affect the value
10700/// passed through the varargs area, we can eliminate the use of the cast.
Dale Johannesen1f530a52008-04-23 18:34:37 +000010701static bool isSafeToEliminateVarargsCast(const CallSite CS,
10702 const CastInst * const CI,
10703 const TargetData * const TD,
10704 const int ix) {
10705 if (!CI->isLosslessCast())
10706 return false;
10707
10708 // The size of ByVal arguments is derived from the type, so we
10709 // can't change to a type with a different size. If the size were
10710 // passed explicitly we could avoid this check.
Devang Patel05988662008-09-25 21:00:45 +000010711 if (!CS.paramHasAttr(ix, Attribute::ByVal))
Dale Johannesen1f530a52008-04-23 18:34:37 +000010712 return true;
10713
10714 const Type* SrcTy =
10715 cast<PointerType>(CI->getOperand(0)->getType())->getElementType();
10716 const Type* DstTy = cast<PointerType>(CI->getType())->getElementType();
10717 if (!SrcTy->isSized() || !DstTy->isSized())
10718 return false;
Dan Gohmance9fe9f2009-07-21 23:21:54 +000010719 if (!TD || TD->getTypeAllocSize(SrcTy) != TD->getTypeAllocSize(DstTy))
Dale Johannesen1f530a52008-04-23 18:34:37 +000010720 return false;
10721 return true;
10722}
10723
Chris Lattnera44d8a22003-10-07 22:32:43 +000010724// visitCallSite - Improvements for call and invoke instructions.
10725//
10726Instruction *InstCombiner::visitCallSite(CallSite CS) {
Chris Lattner6c266db2003-10-07 22:54:13 +000010727 bool Changed = false;
10728
10729 // If the callee is a constexpr cast of a function, attempt to move the cast
10730 // to the arguments of the call/invoke.
Chris Lattnera44d8a22003-10-07 22:32:43 +000010731 if (transformConstExprCastCall(CS)) return 0;
10732
Chris Lattner6c266db2003-10-07 22:54:13 +000010733 Value *Callee = CS.getCalledValue();
Chris Lattnere87597f2004-10-16 18:11:37 +000010734
Chris Lattner08b22ec2005-05-13 07:09:09 +000010735 if (Function *CalleeF = dyn_cast<Function>(Callee))
10736 if (CalleeF->getCallingConv() != CS.getCallingConv()) {
10737 Instruction *OldCall = CS.getInstruction();
10738 // If the call and callee calling conventions don't match, this call must
10739 // be unreachable, as the call is undefined.
Owen Anderson5defacc2009-07-31 17:39:07 +000010740 new StoreInst(ConstantInt::getTrue(*Context),
Duncan Sandsac53a0b2009-10-06 15:40:36 +000010741 UndefValue::get(Type::getInt1PtrTy(*Context)),
Owen Andersond672ecb2009-07-03 00:17:18 +000010742 OldCall);
Devang Patel228ebd02009-10-13 22:56:32 +000010743 // If OldCall dues not return void then replaceAllUsesWith undef.
10744 // This allows ValueHandlers and custom metadata to adjust itself.
Devang Patel9674d152009-10-14 17:29:00 +000010745 if (!OldCall->getType()->isVoidTy())
Devang Patel228ebd02009-10-13 22:56:32 +000010746 OldCall->replaceAllUsesWith(UndefValue::get(OldCall->getType()));
Chris Lattner08b22ec2005-05-13 07:09:09 +000010747 if (isa<CallInst>(OldCall)) // Not worth removing an invoke here.
10748 return EraseInstFromFunction(*OldCall);
10749 return 0;
10750 }
10751
Chris Lattner17be6352004-10-18 02:59:09 +000010752 if (isa<ConstantPointerNull>(Callee) || isa<UndefValue>(Callee)) {
10753 // This instruction is not reachable, just remove it. We insert a store to
10754 // undef so that we know that this code is not reachable, despite the fact
10755 // that we can't modify the CFG here.
Owen Anderson5defacc2009-07-31 17:39:07 +000010756 new StoreInst(ConstantInt::getTrue(*Context),
Duncan Sandsac53a0b2009-10-06 15:40:36 +000010757 UndefValue::get(Type::getInt1PtrTy(*Context)),
Chris Lattner17be6352004-10-18 02:59:09 +000010758 CS.getInstruction());
10759
Devang Patel228ebd02009-10-13 22:56:32 +000010760 // If CS dues not return void then replaceAllUsesWith undef.
10761 // This allows ValueHandlers and custom metadata to adjust itself.
Devang Patel9674d152009-10-14 17:29:00 +000010762 if (!CS.getInstruction()->getType()->isVoidTy())
Devang Patel228ebd02009-10-13 22:56:32 +000010763 CS.getInstruction()->
10764 replaceAllUsesWith(UndefValue::get(CS.getInstruction()->getType()));
Chris Lattner17be6352004-10-18 02:59:09 +000010765
10766 if (InvokeInst *II = dyn_cast<InvokeInst>(CS.getInstruction())) {
10767 // Don't break the CFG, insert a dummy cond branch.
Gabor Greif051a9502008-04-06 20:25:17 +000010768 BranchInst::Create(II->getNormalDest(), II->getUnwindDest(),
Owen Anderson5defacc2009-07-31 17:39:07 +000010769 ConstantInt::getTrue(*Context), II);
Chris Lattnere87597f2004-10-16 18:11:37 +000010770 }
Chris Lattner17be6352004-10-18 02:59:09 +000010771 return EraseInstFromFunction(*CS.getInstruction());
10772 }
Chris Lattnere87597f2004-10-16 18:11:37 +000010773
Duncan Sandscdb6d922007-09-17 10:26:40 +000010774 if (BitCastInst *BC = dyn_cast<BitCastInst>(Callee))
10775 if (IntrinsicInst *In = dyn_cast<IntrinsicInst>(BC->getOperand(0)))
10776 if (In->getIntrinsicID() == Intrinsic::init_trampoline)
10777 return transformCallThroughTrampoline(CS);
10778
Chris Lattner6c266db2003-10-07 22:54:13 +000010779 const PointerType *PTy = cast<PointerType>(Callee->getType());
10780 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
10781 if (FTy->isVarArg()) {
Dale Johannesen63e7eb42008-04-23 01:03:05 +000010782 int ix = FTy->getNumParams() + (isa<InvokeInst>(Callee) ? 3 : 1);
Chris Lattner6c266db2003-10-07 22:54:13 +000010783 // See if we can optimize any arguments passed through the varargs area of
10784 // the call.
10785 for (CallSite::arg_iterator I = CS.arg_begin()+FTy->getNumParams(),
Dale Johannesen1f530a52008-04-23 18:34:37 +000010786 E = CS.arg_end(); I != E; ++I, ++ix) {
10787 CastInst *CI = dyn_cast<CastInst>(*I);
10788 if (CI && isSafeToEliminateVarargsCast(CS, CI, TD, ix)) {
10789 *I = CI->getOperand(0);
10790 Changed = true;
Chris Lattner6c266db2003-10-07 22:54:13 +000010791 }
Dale Johannesen1f530a52008-04-23 18:34:37 +000010792 }
Chris Lattner6c266db2003-10-07 22:54:13 +000010793 }
Misha Brukmanfd939082005-04-21 23:48:37 +000010794
Duncan Sandsf0c33542007-12-19 21:13:37 +000010795 if (isa<InlineAsm>(Callee) && !CS.doesNotThrow()) {
Duncan Sandsece2c042007-12-16 15:51:49 +000010796 // Inline asm calls cannot throw - mark them 'nounwind'.
Duncan Sandsf0c33542007-12-19 21:13:37 +000010797 CS.setDoesNotThrow();
Duncan Sandsece2c042007-12-16 15:51:49 +000010798 Changed = true;
10799 }
10800
Chris Lattner6c266db2003-10-07 22:54:13 +000010801 return Changed ? CS.getInstruction() : 0;
Chris Lattnera44d8a22003-10-07 22:32:43 +000010802}
10803
Chris Lattner9fe38862003-06-19 17:00:31 +000010804// transformConstExprCastCall - If the callee is a constexpr cast of a function,
10805// attempt to move the cast to the arguments of the call/invoke.
10806//
10807bool InstCombiner::transformConstExprCastCall(CallSite CS) {
10808 if (!isa<ConstantExpr>(CS.getCalledValue())) return false;
10809 ConstantExpr *CE = cast<ConstantExpr>(CS.getCalledValue());
Reid Spencer3da59db2006-11-27 01:05:10 +000010810 if (CE->getOpcode() != Instruction::BitCast ||
10811 !isa<Function>(CE->getOperand(0)))
Chris Lattner9fe38862003-06-19 17:00:31 +000010812 return false;
Reid Spencer8863f182004-07-18 00:38:32 +000010813 Function *Callee = cast<Function>(CE->getOperand(0));
Chris Lattner9fe38862003-06-19 17:00:31 +000010814 Instruction *Caller = CS.getInstruction();
Devang Patel05988662008-09-25 21:00:45 +000010815 const AttrListPtr &CallerPAL = CS.getAttributes();
Chris Lattner9fe38862003-06-19 17:00:31 +000010816
10817 // Okay, this is a cast from a function to a different type. Unless doing so
10818 // would cause a type conversion of one of our arguments, change this call to
10819 // be a direct call with arguments casted to the appropriate types.
10820 //
10821 const FunctionType *FT = Callee->getFunctionType();
10822 const Type *OldRetTy = Caller->getType();
Duncan Sandsf413cdf2008-06-01 07:38:42 +000010823 const Type *NewRetTy = FT->getReturnType();
Chris Lattner9fe38862003-06-19 17:00:31 +000010824
Duncan Sandsf413cdf2008-06-01 07:38:42 +000010825 if (isa<StructType>(NewRetTy))
Devang Patel75e6f022008-03-11 18:04:06 +000010826 return false; // TODO: Handle multiple return values.
10827
Chris Lattnerf78616b2004-01-14 06:06:08 +000010828 // Check to see if we are changing the return type...
Duncan Sandsf413cdf2008-06-01 07:38:42 +000010829 if (OldRetTy != NewRetTy) {
Bill Wendlinga6c31122008-05-14 22:45:20 +000010830 if (Callee->isDeclaration() &&
Duncan Sandsf413cdf2008-06-01 07:38:42 +000010831 // Conversion is ok if changing from one pointer type to another or from
10832 // a pointer to an integer of the same size.
Dan Gohmance9fe9f2009-07-21 23:21:54 +000010833 !((isa<PointerType>(OldRetTy) || !TD ||
Owen Anderson1d0be152009-08-13 21:58:54 +000010834 OldRetTy == TD->getIntPtrType(Caller->getContext())) &&
Dan Gohmance9fe9f2009-07-21 23:21:54 +000010835 (isa<PointerType>(NewRetTy) || !TD ||
Owen Anderson1d0be152009-08-13 21:58:54 +000010836 NewRetTy == TD->getIntPtrType(Caller->getContext()))))
Chris Lattnerec479922007-01-06 02:09:32 +000010837 return false; // Cannot transform this return value.
Chris Lattnerf78616b2004-01-14 06:06:08 +000010838
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +000010839 if (!Caller->use_empty() &&
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +000010840 // void -> non-void is handled specially
Devang Patel9674d152009-10-14 17:29:00 +000010841 !NewRetTy->isVoidTy() && !CastInst::isCastable(NewRetTy, OldRetTy))
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +000010842 return false; // Cannot transform this return value.
10843
Chris Lattner58d74912008-03-12 17:45:29 +000010844 if (!CallerPAL.isEmpty() && !Caller->use_empty()) {
Devang Patel19c87462008-09-26 22:53:05 +000010845 Attributes RAttrs = CallerPAL.getRetAttributes();
Devang Patel05988662008-09-25 21:00:45 +000010846 if (RAttrs & Attribute::typeIncompatible(NewRetTy))
Duncan Sands6c3470e2008-01-07 17:16:06 +000010847 return false; // Attribute not compatible with transformed value.
10848 }
Duncan Sandsad9a9e12008-01-06 18:27:01 +000010849
Chris Lattnerf78616b2004-01-14 06:06:08 +000010850 // If the callsite is an invoke instruction, and the return value is used by
10851 // a PHI node in a successor, we cannot change the return type of the call
10852 // because there is no place to put the cast instruction (without breaking
10853 // the critical edge). Bail out in this case.
10854 if (!Caller->use_empty())
10855 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller))
10856 for (Value::use_iterator UI = II->use_begin(), E = II->use_end();
10857 UI != E; ++UI)
10858 if (PHINode *PN = dyn_cast<PHINode>(*UI))
10859 if (PN->getParent() == II->getNormalDest() ||
Chris Lattneraeb2a1d2004-02-08 21:44:31 +000010860 PN->getParent() == II->getUnwindDest())
Chris Lattnerf78616b2004-01-14 06:06:08 +000010861 return false;
10862 }
Chris Lattner9fe38862003-06-19 17:00:31 +000010863
10864 unsigned NumActualArgs = unsigned(CS.arg_end()-CS.arg_begin());
10865 unsigned NumCommonArgs = std::min(FT->getNumParams(), NumActualArgs);
Misha Brukmanfd939082005-04-21 23:48:37 +000010866
Chris Lattner9fe38862003-06-19 17:00:31 +000010867 CallSite::arg_iterator AI = CS.arg_begin();
10868 for (unsigned i = 0, e = NumCommonArgs; i != e; ++i, ++AI) {
10869 const Type *ParamTy = FT->getParamType(i);
Andrew Lenharthb8e604c2006-06-28 01:01:52 +000010870 const Type *ActTy = (*AI)->getType();
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +000010871
10872 if (!CastInst::isCastable(ActTy, ParamTy))
Duncan Sandsad9a9e12008-01-06 18:27:01 +000010873 return false; // Cannot transform this parameter value.
10874
Devang Patel19c87462008-09-26 22:53:05 +000010875 if (CallerPAL.getParamAttributes(i + 1)
10876 & Attribute::typeIncompatible(ParamTy))
Chris Lattner58d74912008-03-12 17:45:29 +000010877 return false; // Attribute not compatible with transformed value.
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +000010878
Duncan Sandsf413cdf2008-06-01 07:38:42 +000010879 // Converting from one pointer type to another or between a pointer and an
10880 // integer of the same size is safe even if we do not have a body.
Chris Lattnerec479922007-01-06 02:09:32 +000010881 bool isConvertible = ActTy == ParamTy ||
Owen Anderson1d0be152009-08-13 21:58:54 +000010882 (TD && ((isa<PointerType>(ParamTy) ||
10883 ParamTy == TD->getIntPtrType(Caller->getContext())) &&
10884 (isa<PointerType>(ActTy) ||
10885 ActTy == TD->getIntPtrType(Caller->getContext()))));
Reid Spencer5cbf9852007-01-30 20:08:39 +000010886 if (Callee->isDeclaration() && !isConvertible) return false;
Chris Lattner9fe38862003-06-19 17:00:31 +000010887 }
10888
10889 if (FT->getNumParams() < NumActualArgs && !FT->isVarArg() &&
Reid Spencer5cbf9852007-01-30 20:08:39 +000010890 Callee->isDeclaration())
Chris Lattner58d74912008-03-12 17:45:29 +000010891 return false; // Do not delete arguments unless we have a function body.
Chris Lattner9fe38862003-06-19 17:00:31 +000010892
Chris Lattner58d74912008-03-12 17:45:29 +000010893 if (FT->getNumParams() < NumActualArgs && FT->isVarArg() &&
10894 !CallerPAL.isEmpty())
Duncan Sandsad9a9e12008-01-06 18:27:01 +000010895 // In this case we have more arguments than the new function type, but we
Duncan Sandse1e520f2008-01-13 08:02:44 +000010896 // won't be dropping them. Check that these extra arguments have attributes
10897 // that are compatible with being a vararg call argument.
Chris Lattner58d74912008-03-12 17:45:29 +000010898 for (unsigned i = CallerPAL.getNumSlots(); i; --i) {
10899 if (CallerPAL.getSlot(i - 1).Index <= FT->getNumParams())
Duncan Sandse1e520f2008-01-13 08:02:44 +000010900 break;
Devang Pateleaf42ab2008-09-23 23:03:40 +000010901 Attributes PAttrs = CallerPAL.getSlot(i - 1).Attrs;
Devang Patel05988662008-09-25 21:00:45 +000010902 if (PAttrs & Attribute::VarArgsIncompatible)
Duncan Sandse1e520f2008-01-13 08:02:44 +000010903 return false;
10904 }
Duncan Sandsad9a9e12008-01-06 18:27:01 +000010905
Chris Lattner9fe38862003-06-19 17:00:31 +000010906 // Okay, we decided that this is a safe thing to do: go ahead and start
10907 // inserting cast instructions as necessary...
10908 std::vector<Value*> Args;
10909 Args.reserve(NumActualArgs);
Devang Patel05988662008-09-25 21:00:45 +000010910 SmallVector<AttributeWithIndex, 8> attrVec;
Duncan Sandsad9a9e12008-01-06 18:27:01 +000010911 attrVec.reserve(NumCommonArgs);
10912
10913 // Get any return attributes.
Devang Patel19c87462008-09-26 22:53:05 +000010914 Attributes RAttrs = CallerPAL.getRetAttributes();
Duncan Sandsad9a9e12008-01-06 18:27:01 +000010915
10916 // If the return value is not being used, the type may not be compatible
10917 // with the existing attributes. Wipe out any problematic attributes.
Devang Patel05988662008-09-25 21:00:45 +000010918 RAttrs &= ~Attribute::typeIncompatible(NewRetTy);
Duncan Sandsad9a9e12008-01-06 18:27:01 +000010919
10920 // Add the new return attributes.
10921 if (RAttrs)
Devang Patel05988662008-09-25 21:00:45 +000010922 attrVec.push_back(AttributeWithIndex::get(0, RAttrs));
Chris Lattner9fe38862003-06-19 17:00:31 +000010923
10924 AI = CS.arg_begin();
10925 for (unsigned i = 0; i != NumCommonArgs; ++i, ++AI) {
10926 const Type *ParamTy = FT->getParamType(i);
10927 if ((*AI)->getType() == ParamTy) {
10928 Args.push_back(*AI);
10929 } else {
Reid Spencer8a903db2006-12-18 08:47:13 +000010930 Instruction::CastOps opcode = CastInst::getCastOpcode(*AI,
Reid Spencerc5b206b2006-12-31 05:48:39 +000010931 false, ParamTy, false);
Chris Lattnerf925cbd2009-08-30 18:50:58 +000010932 Args.push_back(Builder->CreateCast(opcode, *AI, ParamTy, "tmp"));
Chris Lattner9fe38862003-06-19 17:00:31 +000010933 }
Duncan Sandsad9a9e12008-01-06 18:27:01 +000010934
10935 // Add any parameter attributes.
Devang Patel19c87462008-09-26 22:53:05 +000010936 if (Attributes PAttrs = CallerPAL.getParamAttributes(i + 1))
Devang Patel05988662008-09-25 21:00:45 +000010937 attrVec.push_back(AttributeWithIndex::get(i + 1, PAttrs));
Chris Lattner9fe38862003-06-19 17:00:31 +000010938 }
10939
10940 // If the function takes more arguments than the call was taking, add them
Chris Lattnerf925cbd2009-08-30 18:50:58 +000010941 // now.
Chris Lattner9fe38862003-06-19 17:00:31 +000010942 for (unsigned i = NumCommonArgs; i != FT->getNumParams(); ++i)
Owen Andersona7235ea2009-07-31 20:28:14 +000010943 Args.push_back(Constant::getNullValue(FT->getParamType(i)));
Chris Lattner9fe38862003-06-19 17:00:31 +000010944
Chris Lattnerf925cbd2009-08-30 18:50:58 +000010945 // If we are removing arguments to the function, emit an obnoxious warning.
Anton Korobeynikov07e6e562008-02-20 11:26:25 +000010946 if (FT->getNumParams() < NumActualArgs) {
Chris Lattner9fe38862003-06-19 17:00:31 +000010947 if (!FT->isVarArg()) {
Daniel Dunbarce63ffb2009-07-25 00:23:56 +000010948 errs() << "WARNING: While resolving call to function '"
10949 << Callee->getName() << "' arguments were dropped!\n";
Chris Lattner9fe38862003-06-19 17:00:31 +000010950 } else {
Chris Lattnerf925cbd2009-08-30 18:50:58 +000010951 // Add all of the arguments in their promoted form to the arg list.
Chris Lattner9fe38862003-06-19 17:00:31 +000010952 for (unsigned i = FT->getNumParams(); i != NumActualArgs; ++i, ++AI) {
10953 const Type *PTy = getPromotedType((*AI)->getType());
10954 if (PTy != (*AI)->getType()) {
10955 // Must promote to pass through va_arg area!
Chris Lattnerf925cbd2009-08-30 18:50:58 +000010956 Instruction::CastOps opcode =
10957 CastInst::getCastOpcode(*AI, false, PTy, false);
10958 Args.push_back(Builder->CreateCast(opcode, *AI, PTy, "tmp"));
Chris Lattner9fe38862003-06-19 17:00:31 +000010959 } else {
10960 Args.push_back(*AI);
10961 }
Duncan Sandsad9a9e12008-01-06 18:27:01 +000010962
Duncan Sandse1e520f2008-01-13 08:02:44 +000010963 // Add any parameter attributes.
Devang Patel19c87462008-09-26 22:53:05 +000010964 if (Attributes PAttrs = CallerPAL.getParamAttributes(i + 1))
Devang Patel05988662008-09-25 21:00:45 +000010965 attrVec.push_back(AttributeWithIndex::get(i + 1, PAttrs));
Duncan Sandse1e520f2008-01-13 08:02:44 +000010966 }
Chris Lattner9fe38862003-06-19 17:00:31 +000010967 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +000010968 }
Chris Lattner9fe38862003-06-19 17:00:31 +000010969
Devang Patel19c87462008-09-26 22:53:05 +000010970 if (Attributes FnAttrs = CallerPAL.getFnAttributes())
10971 attrVec.push_back(AttributeWithIndex::get(~0, FnAttrs));
10972
Devang Patel9674d152009-10-14 17:29:00 +000010973 if (NewRetTy->isVoidTy())
Chris Lattner6934a042007-02-11 01:23:03 +000010974 Caller->setName(""); // Void type should not have a name.
Chris Lattner9fe38862003-06-19 17:00:31 +000010975
Eric Christophera66297a2009-07-25 02:45:27 +000010976 const AttrListPtr &NewCallerPAL = AttrListPtr::get(attrVec.begin(),
10977 attrVec.end());
Duncan Sandsad9a9e12008-01-06 18:27:01 +000010978
Chris Lattner9fe38862003-06-19 17:00:31 +000010979 Instruction *NC;
10980 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Gabor Greif051a9502008-04-06 20:25:17 +000010981 NC = InvokeInst::Create(Callee, II->getNormalDest(), II->getUnwindDest(),
Gabor Greifb1dbcd82008-05-15 10:04:30 +000010982 Args.begin(), Args.end(),
10983 Caller->getName(), Caller);
Reid Spencered3fa852007-07-30 19:53:57 +000010984 cast<InvokeInst>(NC)->setCallingConv(II->getCallingConv());
Devang Patel05988662008-09-25 21:00:45 +000010985 cast<InvokeInst>(NC)->setAttributes(NewCallerPAL);
Chris Lattner9fe38862003-06-19 17:00:31 +000010986 } else {
Gabor Greif051a9502008-04-06 20:25:17 +000010987 NC = CallInst::Create(Callee, Args.begin(), Args.end(),
10988 Caller->getName(), Caller);
Duncan Sandsdc024672007-11-27 13:23:08 +000010989 CallInst *CI = cast<CallInst>(Caller);
10990 if (CI->isTailCall())
Chris Lattnera9e92112005-05-06 06:48:21 +000010991 cast<CallInst>(NC)->setTailCall();
Duncan Sandsdc024672007-11-27 13:23:08 +000010992 cast<CallInst>(NC)->setCallingConv(CI->getCallingConv());
Devang Patel05988662008-09-25 21:00:45 +000010993 cast<CallInst>(NC)->setAttributes(NewCallerPAL);
Chris Lattner9fe38862003-06-19 17:00:31 +000010994 }
10995
Chris Lattner6934a042007-02-11 01:23:03 +000010996 // Insert a cast of the return type as necessary.
Chris Lattner9fe38862003-06-19 17:00:31 +000010997 Value *NV = NC;
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +000010998 if (OldRetTy != NV->getType() && !Caller->use_empty()) {
Devang Patel9674d152009-10-14 17:29:00 +000010999 if (!NV->getType()->isVoidTy()) {
Reid Spencerc5b206b2006-12-31 05:48:39 +000011000 Instruction::CastOps opcode = CastInst::getCastOpcode(NC, false,
Duncan Sandsa9d0c9d2008-01-06 10:12:28 +000011001 OldRetTy, false);
Gabor Greif7cbd8a32008-05-16 19:29:10 +000011002 NV = NC = CastInst::Create(opcode, NC, OldRetTy, "tmp");
Chris Lattnerbb609042003-10-30 00:46:41 +000011003
11004 // If this is an invoke instruction, we should insert it after the first
11005 // non-phi, instruction in the normal successor block.
11006 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Dan Gohman02dea8b2008-05-23 21:05:58 +000011007 BasicBlock::iterator I = II->getNormalDest()->getFirstNonPHI();
Chris Lattnerbb609042003-10-30 00:46:41 +000011008 InsertNewInstBefore(NC, *I);
11009 } else {
11010 // Otherwise, it's a call, just insert cast right after the call instr
11011 InsertNewInstBefore(NC, *Caller);
11012 }
Chris Lattnere5ecdb52009-08-30 06:22:51 +000011013 Worklist.AddUsersToWorkList(*Caller);
Chris Lattner9fe38862003-06-19 17:00:31 +000011014 } else {
Owen Anderson9e9a0d52009-07-30 23:03:37 +000011015 NV = UndefValue::get(Caller->getType());
Chris Lattner9fe38862003-06-19 17:00:31 +000011016 }
11017 }
11018
Devang Patel1bf5ebc2009-10-13 21:41:20 +000011019
Chris Lattner931f8f32009-08-31 05:17:58 +000011020 if (!Caller->use_empty())
Chris Lattner9fe38862003-06-19 17:00:31 +000011021 Caller->replaceAllUsesWith(NV);
Chris Lattner931f8f32009-08-31 05:17:58 +000011022
11023 EraseInstFromFunction(*Caller);
Chris Lattner9fe38862003-06-19 17:00:31 +000011024 return true;
11025}
11026
Duncan Sandscdb6d922007-09-17 10:26:40 +000011027// transformCallThroughTrampoline - Turn a call to a function created by the
11028// init_trampoline intrinsic into a direct call to the underlying function.
11029//
11030Instruction *InstCombiner::transformCallThroughTrampoline(CallSite CS) {
11031 Value *Callee = CS.getCalledValue();
11032 const PointerType *PTy = cast<PointerType>(Callee->getType());
11033 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
Devang Patel05988662008-09-25 21:00:45 +000011034 const AttrListPtr &Attrs = CS.getAttributes();
Duncan Sandsb0c9b932008-01-14 19:52:09 +000011035
11036 // If the call already has the 'nest' attribute somewhere then give up -
11037 // otherwise 'nest' would occur twice after splicing in the chain.
Devang Patel05988662008-09-25 21:00:45 +000011038 if (Attrs.hasAttrSomewhere(Attribute::Nest))
Duncan Sandsb0c9b932008-01-14 19:52:09 +000011039 return 0;
Duncan Sandscdb6d922007-09-17 10:26:40 +000011040
11041 IntrinsicInst *Tramp =
11042 cast<IntrinsicInst>(cast<BitCastInst>(Callee)->getOperand(0));
11043
Anton Korobeynikov0b12ecf2008-05-07 22:54:15 +000011044 Function *NestF = cast<Function>(Tramp->getOperand(2)->stripPointerCasts());
Duncan Sandscdb6d922007-09-17 10:26:40 +000011045 const PointerType *NestFPTy = cast<PointerType>(NestF->getType());
11046 const FunctionType *NestFTy = cast<FunctionType>(NestFPTy->getElementType());
11047
Devang Patel05988662008-09-25 21:00:45 +000011048 const AttrListPtr &NestAttrs = NestF->getAttributes();
Chris Lattner58d74912008-03-12 17:45:29 +000011049 if (!NestAttrs.isEmpty()) {
Duncan Sandscdb6d922007-09-17 10:26:40 +000011050 unsigned NestIdx = 1;
11051 const Type *NestTy = 0;
Devang Patel05988662008-09-25 21:00:45 +000011052 Attributes NestAttr = Attribute::None;
Duncan Sandscdb6d922007-09-17 10:26:40 +000011053
11054 // Look for a parameter marked with the 'nest' attribute.
11055 for (FunctionType::param_iterator I = NestFTy->param_begin(),
11056 E = NestFTy->param_end(); I != E; ++NestIdx, ++I)
Devang Patel05988662008-09-25 21:00:45 +000011057 if (NestAttrs.paramHasAttr(NestIdx, Attribute::Nest)) {
Duncan Sandscdb6d922007-09-17 10:26:40 +000011058 // Record the parameter type and any other attributes.
11059 NestTy = *I;
Devang Patel19c87462008-09-26 22:53:05 +000011060 NestAttr = NestAttrs.getParamAttributes(NestIdx);
Duncan Sandscdb6d922007-09-17 10:26:40 +000011061 break;
11062 }
11063
11064 if (NestTy) {
11065 Instruction *Caller = CS.getInstruction();
11066 std::vector<Value*> NewArgs;
11067 NewArgs.reserve(unsigned(CS.arg_end()-CS.arg_begin())+1);
11068
Devang Patel05988662008-09-25 21:00:45 +000011069 SmallVector<AttributeWithIndex, 8> NewAttrs;
Chris Lattner58d74912008-03-12 17:45:29 +000011070 NewAttrs.reserve(Attrs.getNumSlots() + 1);
Duncan Sandsb0c9b932008-01-14 19:52:09 +000011071
Duncan Sandscdb6d922007-09-17 10:26:40 +000011072 // Insert the nest argument into the call argument list, which may
Duncan Sandsb0c9b932008-01-14 19:52:09 +000011073 // mean appending it. Likewise for attributes.
11074
Devang Patel19c87462008-09-26 22:53:05 +000011075 // Add any result attributes.
11076 if (Attributes Attr = Attrs.getRetAttributes())
Devang Patel05988662008-09-25 21:00:45 +000011077 NewAttrs.push_back(AttributeWithIndex::get(0, Attr));
Duncan Sandsb0c9b932008-01-14 19:52:09 +000011078
Duncan Sandscdb6d922007-09-17 10:26:40 +000011079 {
11080 unsigned Idx = 1;
11081 CallSite::arg_iterator I = CS.arg_begin(), E = CS.arg_end();
11082 do {
11083 if (Idx == NestIdx) {
Duncan Sandsb0c9b932008-01-14 19:52:09 +000011084 // Add the chain argument and attributes.
Duncan Sandscdb6d922007-09-17 10:26:40 +000011085 Value *NestVal = Tramp->getOperand(3);
11086 if (NestVal->getType() != NestTy)
11087 NestVal = new BitCastInst(NestVal, NestTy, "nest", Caller);
11088 NewArgs.push_back(NestVal);
Devang Patel05988662008-09-25 21:00:45 +000011089 NewAttrs.push_back(AttributeWithIndex::get(NestIdx, NestAttr));
Duncan Sandscdb6d922007-09-17 10:26:40 +000011090 }
11091
11092 if (I == E)
11093 break;
11094
Duncan Sandsb0c9b932008-01-14 19:52:09 +000011095 // Add the original argument and attributes.
Duncan Sandscdb6d922007-09-17 10:26:40 +000011096 NewArgs.push_back(*I);
Devang Patel19c87462008-09-26 22:53:05 +000011097 if (Attributes Attr = Attrs.getParamAttributes(Idx))
Duncan Sandsb0c9b932008-01-14 19:52:09 +000011098 NewAttrs.push_back
Devang Patel05988662008-09-25 21:00:45 +000011099 (AttributeWithIndex::get(Idx + (Idx >= NestIdx), Attr));
Duncan Sandscdb6d922007-09-17 10:26:40 +000011100
11101 ++Idx, ++I;
11102 } while (1);
11103 }
11104
Devang Patel19c87462008-09-26 22:53:05 +000011105 // Add any function attributes.
11106 if (Attributes Attr = Attrs.getFnAttributes())
11107 NewAttrs.push_back(AttributeWithIndex::get(~0, Attr));
11108
Duncan Sandscdb6d922007-09-17 10:26:40 +000011109 // The trampoline may have been bitcast to a bogus type (FTy).
11110 // Handle this by synthesizing a new function type, equal to FTy
Duncan Sandsb0c9b932008-01-14 19:52:09 +000011111 // with the chain parameter inserted.
Duncan Sandscdb6d922007-09-17 10:26:40 +000011112
Duncan Sandscdb6d922007-09-17 10:26:40 +000011113 std::vector<const Type*> NewTypes;
Duncan Sandscdb6d922007-09-17 10:26:40 +000011114 NewTypes.reserve(FTy->getNumParams()+1);
11115
Duncan Sandscdb6d922007-09-17 10:26:40 +000011116 // Insert the chain's type into the list of parameter types, which may
Duncan Sandsb0c9b932008-01-14 19:52:09 +000011117 // mean appending it.
Duncan Sandscdb6d922007-09-17 10:26:40 +000011118 {
11119 unsigned Idx = 1;
11120 FunctionType::param_iterator I = FTy->param_begin(),
11121 E = FTy->param_end();
11122
11123 do {
Duncan Sandsb0c9b932008-01-14 19:52:09 +000011124 if (Idx == NestIdx)
11125 // Add the chain's type.
Duncan Sandscdb6d922007-09-17 10:26:40 +000011126 NewTypes.push_back(NestTy);
Duncan Sandscdb6d922007-09-17 10:26:40 +000011127
11128 if (I == E)
11129 break;
11130
Duncan Sandsb0c9b932008-01-14 19:52:09 +000011131 // Add the original type.
Duncan Sandscdb6d922007-09-17 10:26:40 +000011132 NewTypes.push_back(*I);
Duncan Sandscdb6d922007-09-17 10:26:40 +000011133
11134 ++Idx, ++I;
11135 } while (1);
11136 }
11137
11138 // Replace the trampoline call with a direct call. Let the generic
11139 // code sort out any function type mismatches.
Owen Andersondebcb012009-07-29 22:17:13 +000011140 FunctionType *NewFTy = FunctionType::get(FTy->getReturnType(), NewTypes,
Owen Andersond672ecb2009-07-03 00:17:18 +000011141 FTy->isVarArg());
11142 Constant *NewCallee =
Owen Andersondebcb012009-07-29 22:17:13 +000011143 NestF->getType() == PointerType::getUnqual(NewFTy) ?
Owen Andersonbaf3c402009-07-29 18:55:55 +000011144 NestF : ConstantExpr::getBitCast(NestF,
Owen Andersondebcb012009-07-29 22:17:13 +000011145 PointerType::getUnqual(NewFTy));
Eric Christophera66297a2009-07-25 02:45:27 +000011146 const AttrListPtr &NewPAL = AttrListPtr::get(NewAttrs.begin(),
11147 NewAttrs.end());
Duncan Sandscdb6d922007-09-17 10:26:40 +000011148
11149 Instruction *NewCaller;
11150 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Gabor Greif051a9502008-04-06 20:25:17 +000011151 NewCaller = InvokeInst::Create(NewCallee,
11152 II->getNormalDest(), II->getUnwindDest(),
11153 NewArgs.begin(), NewArgs.end(),
11154 Caller->getName(), Caller);
Duncan Sandscdb6d922007-09-17 10:26:40 +000011155 cast<InvokeInst>(NewCaller)->setCallingConv(II->getCallingConv());
Devang Patel05988662008-09-25 21:00:45 +000011156 cast<InvokeInst>(NewCaller)->setAttributes(NewPAL);
Duncan Sandscdb6d922007-09-17 10:26:40 +000011157 } else {
Gabor Greif051a9502008-04-06 20:25:17 +000011158 NewCaller = CallInst::Create(NewCallee, NewArgs.begin(), NewArgs.end(),
11159 Caller->getName(), Caller);
Duncan Sandscdb6d922007-09-17 10:26:40 +000011160 if (cast<CallInst>(Caller)->isTailCall())
11161 cast<CallInst>(NewCaller)->setTailCall();
11162 cast<CallInst>(NewCaller)->
11163 setCallingConv(cast<CallInst>(Caller)->getCallingConv());
Devang Patel05988662008-09-25 21:00:45 +000011164 cast<CallInst>(NewCaller)->setAttributes(NewPAL);
Duncan Sandscdb6d922007-09-17 10:26:40 +000011165 }
Devang Patel9674d152009-10-14 17:29:00 +000011166 if (!Caller->getType()->isVoidTy())
Duncan Sandscdb6d922007-09-17 10:26:40 +000011167 Caller->replaceAllUsesWith(NewCaller);
11168 Caller->eraseFromParent();
Chris Lattner7a1e9242009-08-30 06:13:40 +000011169 Worklist.Remove(Caller);
Duncan Sandscdb6d922007-09-17 10:26:40 +000011170 return 0;
11171 }
11172 }
11173
11174 // Replace the trampoline call with a direct call. Since there is no 'nest'
11175 // parameter, there is no need to adjust the argument list. Let the generic
11176 // code sort out any function type mismatches.
11177 Constant *NewCallee =
Owen Andersond672ecb2009-07-03 00:17:18 +000011178 NestF->getType() == PTy ? NestF :
Owen Andersonbaf3c402009-07-29 18:55:55 +000011179 ConstantExpr::getBitCast(NestF, PTy);
Duncan Sandscdb6d922007-09-17 10:26:40 +000011180 CS.setCalledFunction(NewCallee);
11181 return CS.getInstruction();
11182}
11183
Dan Gohman9ad29202009-09-16 16:50:24 +000011184/// FoldPHIArgBinOpIntoPHI - If we have something like phi [add (a,b), add(a,c)]
11185/// and if a/b/c and the add's all have a single use, turn this into a phi
Chris Lattner7da52b22006-11-01 04:51:18 +000011186/// and a single binop.
11187Instruction *InstCombiner::FoldPHIArgBinOpIntoPHI(PHINode &PN) {
11188 Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
Chris Lattner38b3dcc2008-12-01 03:42:51 +000011189 assert(isa<BinaryOperator>(FirstInst) || isa<CmpInst>(FirstInst));
Chris Lattner7da52b22006-11-01 04:51:18 +000011190 unsigned Opc = FirstInst->getOpcode();
Chris Lattnerf6fd94d2006-11-08 19:29:23 +000011191 Value *LHSVal = FirstInst->getOperand(0);
11192 Value *RHSVal = FirstInst->getOperand(1);
11193
11194 const Type *LHSType = LHSVal->getType();
11195 const Type *RHSType = RHSVal->getType();
Chris Lattner7da52b22006-11-01 04:51:18 +000011196
Dan Gohman9ad29202009-09-16 16:50:24 +000011197 // Scan to see if all operands are the same opcode, and all have one use.
Chris Lattner05f18922008-12-01 02:34:36 +000011198 for (unsigned i = 1; i != PN.getNumIncomingValues(); ++i) {
Chris Lattner7da52b22006-11-01 04:51:18 +000011199 Instruction *I = dyn_cast<Instruction>(PN.getIncomingValue(i));
Chris Lattnera90a24c2006-11-01 04:55:47 +000011200 if (!I || I->getOpcode() != Opc || !I->hasOneUse() ||
Reid Spencere4d87aa2006-12-23 06:05:41 +000011201 // Verify type of the LHS matches so we don't fold cmp's of different
Chris Lattner9c080502006-11-01 07:43:41 +000011202 // types or GEP's with different index types.
11203 I->getOperand(0)->getType() != LHSType ||
11204 I->getOperand(1)->getType() != RHSType)
Chris Lattner7da52b22006-11-01 04:51:18 +000011205 return 0;
Reid Spencere4d87aa2006-12-23 06:05:41 +000011206
11207 // If they are CmpInst instructions, check their predicates
11208 if (Opc == Instruction::ICmp || Opc == Instruction::FCmp)
11209 if (cast<CmpInst>(I)->getPredicate() !=
11210 cast<CmpInst>(FirstInst)->getPredicate())
11211 return 0;
Chris Lattnerf6fd94d2006-11-08 19:29:23 +000011212
11213 // Keep track of which operand needs a phi node.
11214 if (I->getOperand(0) != LHSVal) LHSVal = 0;
11215 if (I->getOperand(1) != RHSVal) RHSVal = 0;
Chris Lattner7da52b22006-11-01 04:51:18 +000011216 }
Dan Gohman9ad29202009-09-16 16:50:24 +000011217
11218 // If both LHS and RHS would need a PHI, don't do this transformation,
11219 // because it would increase the number of PHIs entering the block,
11220 // which leads to higher register pressure. This is especially
11221 // bad when the PHIs are in the header of a loop.
11222 if (!LHSVal && !RHSVal)
11223 return 0;
Chris Lattner7da52b22006-11-01 04:51:18 +000011224
Chris Lattner38b3dcc2008-12-01 03:42:51 +000011225 // Otherwise, this is safe to transform!
Chris Lattner53738a42006-11-08 19:42:28 +000011226
Chris Lattner7da52b22006-11-01 04:51:18 +000011227 Value *InLHS = FirstInst->getOperand(0);
Chris Lattner7da52b22006-11-01 04:51:18 +000011228 Value *InRHS = FirstInst->getOperand(1);
Chris Lattner53738a42006-11-08 19:42:28 +000011229 PHINode *NewLHS = 0, *NewRHS = 0;
Chris Lattnerf6fd94d2006-11-08 19:29:23 +000011230 if (LHSVal == 0) {
Gabor Greifb1dbcd82008-05-15 10:04:30 +000011231 NewLHS = PHINode::Create(LHSType,
11232 FirstInst->getOperand(0)->getName() + ".pn");
Chris Lattnerf6fd94d2006-11-08 19:29:23 +000011233 NewLHS->reserveOperandSpace(PN.getNumOperands()/2);
11234 NewLHS->addIncoming(InLHS, PN.getIncomingBlock(0));
Chris Lattner9c080502006-11-01 07:43:41 +000011235 InsertNewInstBefore(NewLHS, PN);
11236 LHSVal = NewLHS;
11237 }
Chris Lattnerf6fd94d2006-11-08 19:29:23 +000011238
11239 if (RHSVal == 0) {
Gabor Greifb1dbcd82008-05-15 10:04:30 +000011240 NewRHS = PHINode::Create(RHSType,
11241 FirstInst->getOperand(1)->getName() + ".pn");
Chris Lattnerf6fd94d2006-11-08 19:29:23 +000011242 NewRHS->reserveOperandSpace(PN.getNumOperands()/2);
11243 NewRHS->addIncoming(InRHS, PN.getIncomingBlock(0));
Chris Lattner9c080502006-11-01 07:43:41 +000011244 InsertNewInstBefore(NewRHS, PN);
11245 RHSVal = NewRHS;
11246 }
11247
Chris Lattnerf6fd94d2006-11-08 19:29:23 +000011248 // Add all operands to the new PHIs.
Chris Lattner05f18922008-12-01 02:34:36 +000011249 if (NewLHS || NewRHS) {
11250 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
11251 Instruction *InInst = cast<Instruction>(PN.getIncomingValue(i));
11252 if (NewLHS) {
11253 Value *NewInLHS = InInst->getOperand(0);
11254 NewLHS->addIncoming(NewInLHS, PN.getIncomingBlock(i));
11255 }
11256 if (NewRHS) {
11257 Value *NewInRHS = InInst->getOperand(1);
11258 NewRHS->addIncoming(NewInRHS, PN.getIncomingBlock(i));
11259 }
Chris Lattnerf6fd94d2006-11-08 19:29:23 +000011260 }
11261 }
11262
Chris Lattner7da52b22006-11-01 04:51:18 +000011263 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
Gabor Greif7cbd8a32008-05-16 19:29:10 +000011264 return BinaryOperator::Create(BinOp->getOpcode(), LHSVal, RHSVal);
Chris Lattner38b3dcc2008-12-01 03:42:51 +000011265 CmpInst *CIOp = cast<CmpInst>(FirstInst);
Dan Gohman1c8a23c2009-08-25 23:17:54 +000011266 return CmpInst::Create(CIOp->getOpcode(), CIOp->getPredicate(),
Owen Anderson333c4002009-07-09 23:48:35 +000011267 LHSVal, RHSVal);
Chris Lattner7da52b22006-11-01 04:51:18 +000011268}
11269
Chris Lattner05f18922008-12-01 02:34:36 +000011270Instruction *InstCombiner::FoldPHIArgGEPIntoPHI(PHINode &PN) {
11271 GetElementPtrInst *FirstInst =cast<GetElementPtrInst>(PN.getIncomingValue(0));
11272
11273 SmallVector<Value*, 16> FixedOperands(FirstInst->op_begin(),
11274 FirstInst->op_end());
Chris Lattner36d3e322009-02-21 00:46:50 +000011275 // This is true if all GEP bases are allocas and if all indices into them are
11276 // constants.
11277 bool AllBasePointersAreAllocas = true;
Dan Gohmanb6c33852009-09-16 02:01:52 +000011278
11279 // We don't want to replace this phi if the replacement would require
Dan Gohman9ad29202009-09-16 16:50:24 +000011280 // more than one phi, which leads to higher register pressure. This is
11281 // especially bad when the PHIs are in the header of a loop.
Dan Gohmanb6c33852009-09-16 02:01:52 +000011282 bool NeededPhi = false;
Chris Lattner05f18922008-12-01 02:34:36 +000011283
Dan Gohman9ad29202009-09-16 16:50:24 +000011284 // Scan to see if all operands are the same opcode, and all have one use.
Chris Lattner05f18922008-12-01 02:34:36 +000011285 for (unsigned i = 1; i != PN.getNumIncomingValues(); ++i) {
11286 GetElementPtrInst *GEP= dyn_cast<GetElementPtrInst>(PN.getIncomingValue(i));
11287 if (!GEP || !GEP->hasOneUse() || GEP->getType() != FirstInst->getType() ||
11288 GEP->getNumOperands() != FirstInst->getNumOperands())
11289 return 0;
11290
Chris Lattner36d3e322009-02-21 00:46:50 +000011291 // Keep track of whether or not all GEPs are of alloca pointers.
11292 if (AllBasePointersAreAllocas &&
11293 (!isa<AllocaInst>(GEP->getOperand(0)) ||
11294 !GEP->hasAllConstantIndices()))
11295 AllBasePointersAreAllocas = false;
11296
Chris Lattner05f18922008-12-01 02:34:36 +000011297 // Compare the operand lists.
11298 for (unsigned op = 0, e = FirstInst->getNumOperands(); op != e; ++op) {
11299 if (FirstInst->getOperand(op) == GEP->getOperand(op))
11300 continue;
11301
11302 // Don't merge two GEPs when two operands differ (introducing phi nodes)
11303 // if one of the PHIs has a constant for the index. The index may be
11304 // substantially cheaper to compute for the constants, so making it a
11305 // variable index could pessimize the path. This also handles the case
11306 // for struct indices, which must always be constant.
11307 if (isa<ConstantInt>(FirstInst->getOperand(op)) ||
11308 isa<ConstantInt>(GEP->getOperand(op)))
11309 return 0;
11310
11311 if (FirstInst->getOperand(op)->getType() !=GEP->getOperand(op)->getType())
11312 return 0;
Dan Gohmanb6c33852009-09-16 02:01:52 +000011313
11314 // If we already needed a PHI for an earlier operand, and another operand
11315 // also requires a PHI, we'd be introducing more PHIs than we're
11316 // eliminating, which increases register pressure on entry to the PHI's
11317 // block.
11318 if (NeededPhi)
11319 return 0;
11320
Chris Lattner05f18922008-12-01 02:34:36 +000011321 FixedOperands[op] = 0; // Needs a PHI.
Dan Gohmanb6c33852009-09-16 02:01:52 +000011322 NeededPhi = true;
Chris Lattner05f18922008-12-01 02:34:36 +000011323 }
11324 }
11325
Chris Lattner36d3e322009-02-21 00:46:50 +000011326 // If all of the base pointers of the PHI'd GEPs are from allocas, don't
Chris Lattner21550882009-02-23 05:56:17 +000011327 // bother doing this transformation. At best, this will just save a bit of
Chris Lattner36d3e322009-02-21 00:46:50 +000011328 // offset calculation, but all the predecessors will have to materialize the
11329 // stack address into a register anyway. We'd actually rather *clone* the
11330 // load up into the predecessors so that we have a load of a gep of an alloca,
11331 // which can usually all be folded into the load.
11332 if (AllBasePointersAreAllocas)
11333 return 0;
11334
Chris Lattner05f18922008-12-01 02:34:36 +000011335 // Otherwise, this is safe to transform. Insert PHI nodes for each operand
11336 // that is variable.
11337 SmallVector<PHINode*, 16> OperandPhis(FixedOperands.size());
11338
11339 bool HasAnyPHIs = false;
11340 for (unsigned i = 0, e = FixedOperands.size(); i != e; ++i) {
11341 if (FixedOperands[i]) continue; // operand doesn't need a phi.
11342 Value *FirstOp = FirstInst->getOperand(i);
11343 PHINode *NewPN = PHINode::Create(FirstOp->getType(),
11344 FirstOp->getName()+".pn");
11345 InsertNewInstBefore(NewPN, PN);
11346
11347 NewPN->reserveOperandSpace(e);
11348 NewPN->addIncoming(FirstOp, PN.getIncomingBlock(0));
11349 OperandPhis[i] = NewPN;
11350 FixedOperands[i] = NewPN;
11351 HasAnyPHIs = true;
11352 }
11353
11354
11355 // Add all operands to the new PHIs.
11356 if (HasAnyPHIs) {
11357 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
11358 GetElementPtrInst *InGEP =cast<GetElementPtrInst>(PN.getIncomingValue(i));
11359 BasicBlock *InBB = PN.getIncomingBlock(i);
11360
11361 for (unsigned op = 0, e = OperandPhis.size(); op != e; ++op)
11362 if (PHINode *OpPhi = OperandPhis[op])
11363 OpPhi->addIncoming(InGEP->getOperand(op), InBB);
11364 }
11365 }
11366
11367 Value *Base = FixedOperands[0];
Dan Gohmanf8dbee72009-09-07 23:54:19 +000011368 return cast<GEPOperator>(FirstInst)->isInBounds() ?
11369 GetElementPtrInst::CreateInBounds(Base, FixedOperands.begin()+1,
11370 FixedOperands.end()) :
Dan Gohmand6aa02d2009-07-28 01:40:03 +000011371 GetElementPtrInst::Create(Base, FixedOperands.begin()+1,
11372 FixedOperands.end());
Chris Lattner05f18922008-12-01 02:34:36 +000011373}
11374
11375
Chris Lattner21550882009-02-23 05:56:17 +000011376/// isSafeAndProfitableToSinkLoad - Return true if we know that it is safe to
11377/// sink the load out of the block that defines it. This means that it must be
Chris Lattner36d3e322009-02-21 00:46:50 +000011378/// obvious the value of the load is not changed from the point of the load to
11379/// the end of the block it is in.
Chris Lattnerfd905ca2007-02-01 22:30:07 +000011380///
11381/// Finally, it is safe, but not profitable, to sink a load targetting a
11382/// non-address-taken alloca. Doing so will cause us to not promote the alloca
11383/// to a register.
Chris Lattner36d3e322009-02-21 00:46:50 +000011384static bool isSafeAndProfitableToSinkLoad(LoadInst *L) {
Chris Lattner76c73142006-11-01 07:13:54 +000011385 BasicBlock::iterator BBI = L, E = L->getParent()->end();
11386
11387 for (++BBI; BBI != E; ++BBI)
11388 if (BBI->mayWriteToMemory())
11389 return false;
Chris Lattnerfd905ca2007-02-01 22:30:07 +000011390
11391 // Check for non-address taken alloca. If not address-taken already, it isn't
11392 // profitable to do this xform.
11393 if (AllocaInst *AI = dyn_cast<AllocaInst>(L->getOperand(0))) {
11394 bool isAddressTaken = false;
11395 for (Value::use_iterator UI = AI->use_begin(), E = AI->use_end();
11396 UI != E; ++UI) {
11397 if (isa<LoadInst>(UI)) continue;
11398 if (StoreInst *SI = dyn_cast<StoreInst>(*UI)) {
11399 // If storing TO the alloca, then the address isn't taken.
11400 if (SI->getOperand(1) == AI) continue;
11401 }
11402 isAddressTaken = true;
11403 break;
11404 }
11405
Chris Lattner36d3e322009-02-21 00:46:50 +000011406 if (!isAddressTaken && AI->isStaticAlloca())
Chris Lattnerfd905ca2007-02-01 22:30:07 +000011407 return false;
11408 }
11409
Chris Lattner36d3e322009-02-21 00:46:50 +000011410 // If this load is a load from a GEP with a constant offset from an alloca,
11411 // then we don't want to sink it. In its present form, it will be
11412 // load [constant stack offset]. Sinking it will cause us to have to
11413 // materialize the stack addresses in each predecessor in a register only to
11414 // do a shared load from register in the successor.
11415 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(L->getOperand(0)))
11416 if (AllocaInst *AI = dyn_cast<AllocaInst>(GEP->getOperand(0)))
11417 if (AI->isStaticAlloca() && GEP->hasAllConstantIndices())
11418 return false;
11419
Chris Lattner76c73142006-11-01 07:13:54 +000011420 return true;
11421}
11422
Chris Lattner751a3622009-11-01 20:04:24 +000011423Instruction *InstCombiner::FoldPHIArgLoadIntoPHI(PHINode &PN) {
11424 LoadInst *FirstLI = cast<LoadInst>(PN.getIncomingValue(0));
11425
11426 // When processing loads, we need to propagate two bits of information to the
11427 // sunk load: whether it is volatile, and what its alignment is. We currently
11428 // don't sink loads when some have their alignment specified and some don't.
11429 // visitLoadInst will propagate an alignment onto the load when TD is around,
11430 // and if TD isn't around, we can't handle the mixed case.
11431 bool isVolatile = FirstLI->isVolatile();
11432 unsigned LoadAlignment = FirstLI->getAlignment();
11433
11434 // We can't sink the load if the loaded value could be modified between the
11435 // load and the PHI.
11436 if (FirstLI->getParent() != PN.getIncomingBlock(0) ||
11437 !isSafeAndProfitableToSinkLoad(FirstLI))
11438 return 0;
11439
11440 // If the PHI is of volatile loads and the load block has multiple
11441 // successors, sinking it would remove a load of the volatile value from
11442 // the path through the other successor.
11443 if (isVolatile &&
11444 FirstLI->getParent()->getTerminator()->getNumSuccessors() != 1)
11445 return 0;
11446
11447 // Check to see if all arguments are the same operation.
11448 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
11449 LoadInst *LI = dyn_cast<LoadInst>(PN.getIncomingValue(i));
11450 if (!LI || !LI->hasOneUse())
11451 return 0;
11452
11453 // We can't sink the load if the loaded value could be modified between
11454 // the load and the PHI.
11455 if (LI->isVolatile() != isVolatile ||
11456 LI->getParent() != PN.getIncomingBlock(i) ||
11457 !isSafeAndProfitableToSinkLoad(LI))
11458 return 0;
11459
11460 // If some of the loads have an alignment specified but not all of them,
11461 // we can't do the transformation.
11462 if ((LoadAlignment != 0) != (LI->getAlignment() != 0))
11463 return 0;
11464
Chris Lattnera664bb72009-11-01 20:07:07 +000011465 LoadAlignment = std::min(LoadAlignment, LI->getAlignment());
Chris Lattner751a3622009-11-01 20:04:24 +000011466
11467 // If the PHI is of volatile loads and the load block has multiple
11468 // successors, sinking it would remove a load of the volatile value from
11469 // the path through the other successor.
11470 if (isVolatile &&
11471 LI->getParent()->getTerminator()->getNumSuccessors() != 1)
11472 return 0;
11473 }
11474
11475 // Okay, they are all the same operation. Create a new PHI node of the
11476 // correct type, and PHI together all of the LHS's of the instructions.
11477 PHINode *NewPN = PHINode::Create(FirstLI->getOperand(0)->getType(),
11478 PN.getName()+".in");
11479 NewPN->reserveOperandSpace(PN.getNumOperands()/2);
11480
11481 Value *InVal = FirstLI->getOperand(0);
11482 NewPN->addIncoming(InVal, PN.getIncomingBlock(0));
11483
11484 // Add all operands to the new PHI.
11485 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
11486 Value *NewInVal = cast<LoadInst>(PN.getIncomingValue(i))->getOperand(0);
11487 if (NewInVal != InVal)
11488 InVal = 0;
11489 NewPN->addIncoming(NewInVal, PN.getIncomingBlock(i));
11490 }
11491
11492 Value *PhiVal;
11493 if (InVal) {
11494 // The new PHI unions all of the same values together. This is really
11495 // common, so we handle it intelligently here for compile-time speed.
11496 PhiVal = InVal;
11497 delete NewPN;
11498 } else {
11499 InsertNewInstBefore(NewPN, PN);
11500 PhiVal = NewPN;
11501 }
11502
11503 // If this was a volatile load that we are merging, make sure to loop through
11504 // and mark all the input loads as non-volatile. If we don't do this, we will
11505 // insert a new volatile load and the old ones will not be deletable.
11506 if (isVolatile)
11507 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i)
11508 cast<LoadInst>(PN.getIncomingValue(i))->setVolatile(false);
11509
11510 return new LoadInst(PhiVal, "", isVolatile, LoadAlignment);
11511}
11512
Chris Lattner9fe38862003-06-19 17:00:31 +000011513
Chris Lattnerc22d4d12009-11-10 07:23:37 +000011514
11515/// FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
11516/// operator and they all are only used by the PHI, PHI together their
11517/// inputs, and do the operation once, to the result of the PHI.
Chris Lattnerbac32862004-11-14 19:13:23 +000011518Instruction *InstCombiner::FoldPHIArgOpIntoPHI(PHINode &PN) {
11519 Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
11520
Chris Lattner751a3622009-11-01 20:04:24 +000011521 if (isa<GetElementPtrInst>(FirstInst))
11522 return FoldPHIArgGEPIntoPHI(PN);
11523 if (isa<LoadInst>(FirstInst))
11524 return FoldPHIArgLoadIntoPHI(PN);
11525
Chris Lattnerbac32862004-11-14 19:13:23 +000011526 // Scan the instruction, looking for input operations that can be folded away.
11527 // If all input operands to the phi are the same instruction (e.g. a cast from
11528 // the same type or "+42") we can pull the operation through the PHI, reducing
11529 // code size and simplifying code.
11530 Constant *ConstantOp = 0;
11531 const Type *CastSrcTy = 0;
Chris Lattnere3c62812009-11-01 19:50:13 +000011532
Chris Lattnerbac32862004-11-14 19:13:23 +000011533 if (isa<CastInst>(FirstInst)) {
11534 CastSrcTy = FirstInst->getOperand(0)->getType();
Chris Lattnerbf382b52009-11-08 21:20:06 +000011535
11536 // Be careful about transforming integer PHIs. We don't want to pessimize
11537 // the code by turning an i32 into an i1293.
11538 if (isa<IntegerType>(PN.getType()) && isa<IntegerType>(CastSrcTy)) {
Chris Lattnerc22d4d12009-11-10 07:23:37 +000011539 if (!ShouldChangeType(PN.getType(), CastSrcTy, TD))
Chris Lattnerbf382b52009-11-08 21:20:06 +000011540 return 0;
11541 }
Reid Spencer832254e2007-02-02 02:16:23 +000011542 } else if (isa<BinaryOperator>(FirstInst) || isa<CmpInst>(FirstInst)) {
Reid Spencere4d87aa2006-12-23 06:05:41 +000011543 // Can fold binop, compare or shift here if the RHS is a constant,
11544 // otherwise call FoldPHIArgBinOpIntoPHI.
Chris Lattnerbac32862004-11-14 19:13:23 +000011545 ConstantOp = dyn_cast<Constant>(FirstInst->getOperand(1));
Chris Lattner7da52b22006-11-01 04:51:18 +000011546 if (ConstantOp == 0)
11547 return FoldPHIArgBinOpIntoPHI(PN);
Chris Lattnerbac32862004-11-14 19:13:23 +000011548 } else {
11549 return 0; // Cannot fold this operation.
11550 }
11551
11552 // Check to see if all arguments are the same operation.
11553 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
Chris Lattner751a3622009-11-01 20:04:24 +000011554 Instruction *I = dyn_cast<Instruction>(PN.getIncomingValue(i));
11555 if (I == 0 || !I->hasOneUse() || !I->isSameOperationAs(FirstInst))
Chris Lattnerbac32862004-11-14 19:13:23 +000011556 return 0;
11557 if (CastSrcTy) {
11558 if (I->getOperand(0)->getType() != CastSrcTy)
11559 return 0; // Cast operation must match.
11560 } else if (I->getOperand(1) != ConstantOp) {
11561 return 0;
11562 }
11563 }
11564
11565 // Okay, they are all the same operation. Create a new PHI node of the
11566 // correct type, and PHI together all of the LHS's of the instructions.
Gabor Greif051a9502008-04-06 20:25:17 +000011567 PHINode *NewPN = PHINode::Create(FirstInst->getOperand(0)->getType(),
11568 PN.getName()+".in");
Chris Lattner55517062005-01-29 00:39:08 +000011569 NewPN->reserveOperandSpace(PN.getNumOperands()/2);
Chris Lattnerb5893442004-11-14 19:29:34 +000011570
11571 Value *InVal = FirstInst->getOperand(0);
11572 NewPN->addIncoming(InVal, PN.getIncomingBlock(0));
Chris Lattnerbac32862004-11-14 19:13:23 +000011573
11574 // Add all operands to the new PHI.
Chris Lattnerb5893442004-11-14 19:29:34 +000011575 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
11576 Value *NewInVal = cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
11577 if (NewInVal != InVal)
11578 InVal = 0;
11579 NewPN->addIncoming(NewInVal, PN.getIncomingBlock(i));
11580 }
11581
11582 Value *PhiVal;
11583 if (InVal) {
11584 // The new PHI unions all of the same values together. This is really
11585 // common, so we handle it intelligently here for compile-time speed.
11586 PhiVal = InVal;
11587 delete NewPN;
11588 } else {
11589 InsertNewInstBefore(NewPN, PN);
11590 PhiVal = NewPN;
11591 }
Misha Brukmanfd939082005-04-21 23:48:37 +000011592
Chris Lattnerbac32862004-11-14 19:13:23 +000011593 // Insert and return the new operation.
Chris Lattnere3c62812009-11-01 19:50:13 +000011594 if (CastInst *FirstCI = dyn_cast<CastInst>(FirstInst))
Gabor Greif7cbd8a32008-05-16 19:29:10 +000011595 return CastInst::Create(FirstCI->getOpcode(), PhiVal, PN.getType());
Chris Lattnere3c62812009-11-01 19:50:13 +000011596
Chris Lattner54545ac2008-04-29 17:13:43 +000011597 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
Gabor Greif7cbd8a32008-05-16 19:29:10 +000011598 return BinaryOperator::Create(BinOp->getOpcode(), PhiVal, ConstantOp);
Chris Lattnere3c62812009-11-01 19:50:13 +000011599
Chris Lattner751a3622009-11-01 20:04:24 +000011600 CmpInst *CIOp = cast<CmpInst>(FirstInst);
11601 return CmpInst::Create(CIOp->getOpcode(), CIOp->getPredicate(),
11602 PhiVal, ConstantOp);
Chris Lattnerbac32862004-11-14 19:13:23 +000011603}
Chris Lattnera1be5662002-05-02 17:06:02 +000011604
Chris Lattnera3fd1c52005-01-17 05:10:15 +000011605/// DeadPHICycle - Return true if this PHI node is only used by a PHI node cycle
11606/// that is dead.
Chris Lattner0e5444b2007-03-26 20:40:50 +000011607static bool DeadPHICycle(PHINode *PN,
11608 SmallPtrSet<PHINode*, 16> &PotentiallyDeadPHIs) {
Chris Lattnera3fd1c52005-01-17 05:10:15 +000011609 if (PN->use_empty()) return true;
11610 if (!PN->hasOneUse()) return false;
11611
11612 // Remember this node, and if we find the cycle, return.
Chris Lattner0e5444b2007-03-26 20:40:50 +000011613 if (!PotentiallyDeadPHIs.insert(PN))
Chris Lattnera3fd1c52005-01-17 05:10:15 +000011614 return true;
Chris Lattner92103de2007-08-28 04:23:55 +000011615
11616 // Don't scan crazily complex things.
11617 if (PotentiallyDeadPHIs.size() == 16)
11618 return false;
Chris Lattnera3fd1c52005-01-17 05:10:15 +000011619
11620 if (PHINode *PU = dyn_cast<PHINode>(PN->use_back()))
11621 return DeadPHICycle(PU, PotentiallyDeadPHIs);
Misha Brukmanfd939082005-04-21 23:48:37 +000011622
Chris Lattnera3fd1c52005-01-17 05:10:15 +000011623 return false;
11624}
11625
Chris Lattnercf5008a2007-11-06 21:52:06 +000011626/// PHIsEqualValue - Return true if this phi node is always equal to
11627/// NonPhiInVal. This happens with mutually cyclic phi nodes like:
11628/// z = some value; x = phi (y, z); y = phi (x, z)
11629static bool PHIsEqualValue(PHINode *PN, Value *NonPhiInVal,
11630 SmallPtrSet<PHINode*, 16> &ValueEqualPHIs) {
11631 // See if we already saw this PHI node.
11632 if (!ValueEqualPHIs.insert(PN))
11633 return true;
11634
11635 // Don't scan crazily complex things.
11636 if (ValueEqualPHIs.size() == 16)
11637 return false;
11638
11639 // Scan the operands to see if they are either phi nodes or are equal to
11640 // the value.
11641 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
11642 Value *Op = PN->getIncomingValue(i);
11643 if (PHINode *OpPN = dyn_cast<PHINode>(Op)) {
11644 if (!PHIsEqualValue(OpPN, NonPhiInVal, ValueEqualPHIs))
11645 return false;
11646 } else if (Op != NonPhiInVal)
11647 return false;
11648 }
11649
11650 return true;
11651}
11652
11653
Chris Lattner9956c052009-11-08 19:23:30 +000011654namespace {
11655struct PHIUsageRecord {
Chris Lattnerdd21a1c2009-11-09 01:38:00 +000011656 unsigned PHIId; // The ID # of the PHI (something determinstic to sort on)
Chris Lattner9956c052009-11-08 19:23:30 +000011657 unsigned Shift; // The amount shifted.
11658 Instruction *Inst; // The trunc instruction.
11659
Chris Lattnerdd21a1c2009-11-09 01:38:00 +000011660 PHIUsageRecord(unsigned pn, unsigned Sh, Instruction *User)
11661 : PHIId(pn), Shift(Sh), Inst(User) {}
Chris Lattner9956c052009-11-08 19:23:30 +000011662
11663 bool operator<(const PHIUsageRecord &RHS) const {
Chris Lattnerdd21a1c2009-11-09 01:38:00 +000011664 if (PHIId < RHS.PHIId) return true;
11665 if (PHIId > RHS.PHIId) return false;
Chris Lattner9956c052009-11-08 19:23:30 +000011666 if (Shift < RHS.Shift) return true;
Chris Lattnerdd21a1c2009-11-09 01:38:00 +000011667 if (Shift > RHS.Shift) return false;
11668 return Inst->getType()->getPrimitiveSizeInBits() <
Chris Lattner9956c052009-11-08 19:23:30 +000011669 RHS.Inst->getType()->getPrimitiveSizeInBits();
11670 }
11671};
Chris Lattnerdd21a1c2009-11-09 01:38:00 +000011672
11673struct LoweredPHIRecord {
11674 PHINode *PN; // The PHI that was lowered.
11675 unsigned Shift; // The amount shifted.
11676 unsigned Width; // The width extracted.
11677
11678 LoweredPHIRecord(PHINode *pn, unsigned Sh, const Type *Ty)
11679 : PN(pn), Shift(Sh), Width(Ty->getPrimitiveSizeInBits()) {}
11680
11681 // Ctor form used by DenseMap.
11682 LoweredPHIRecord(PHINode *pn, unsigned Sh)
11683 : PN(pn), Shift(Sh), Width(0) {}
11684};
11685}
11686
11687namespace llvm {
11688 template<>
11689 struct DenseMapInfo<LoweredPHIRecord> {
11690 static inline LoweredPHIRecord getEmptyKey() {
11691 return LoweredPHIRecord(0, 0);
11692 }
11693 static inline LoweredPHIRecord getTombstoneKey() {
11694 return LoweredPHIRecord(0, 1);
11695 }
11696 static unsigned getHashValue(const LoweredPHIRecord &Val) {
11697 return DenseMapInfo<PHINode*>::getHashValue(Val.PN) ^ (Val.Shift>>3) ^
11698 (Val.Width>>3);
11699 }
11700 static bool isEqual(const LoweredPHIRecord &LHS,
11701 const LoweredPHIRecord &RHS) {
11702 return LHS.PN == RHS.PN && LHS.Shift == RHS.Shift &&
11703 LHS.Width == RHS.Width;
11704 }
Chris Lattnerdd21a1c2009-11-09 01:38:00 +000011705 };
Chris Lattner4bbf4ee2009-12-15 07:26:43 +000011706 template <>
11707 struct isPodLike<LoweredPHIRecord> { static const bool value = true; };
Chris Lattner9956c052009-11-08 19:23:30 +000011708}
11709
11710
11711/// SliceUpIllegalIntegerPHI - This is an integer PHI and we know that it has an
11712/// illegal type: see if it is only used by trunc or trunc(lshr) operations. If
11713/// so, we split the PHI into the various pieces being extracted. This sort of
11714/// thing is introduced when SROA promotes an aggregate to large integer values.
11715///
11716/// TODO: The user of the trunc may be an bitcast to float/double/vector or an
11717/// inttoptr. We should produce new PHIs in the right type.
11718///
Chris Lattnerdd21a1c2009-11-09 01:38:00 +000011719Instruction *InstCombiner::SliceUpIllegalIntegerPHI(PHINode &FirstPhi) {
11720 // PHIUsers - Keep track of all of the truncated values extracted from a set
11721 // of PHIs, along with their offset. These are the things we want to rewrite.
Chris Lattner9956c052009-11-08 19:23:30 +000011722 SmallVector<PHIUsageRecord, 16> PHIUsers;
11723
Chris Lattnerdd21a1c2009-11-09 01:38:00 +000011724 // PHIs are often mutually cyclic, so we keep track of a whole set of PHI
11725 // nodes which are extracted from. PHIsToSlice is a set we use to avoid
11726 // revisiting PHIs, PHIsInspected is a ordered list of PHIs that we need to
11727 // check the uses of (to ensure they are all extracts).
11728 SmallVector<PHINode*, 8> PHIsToSlice;
11729 SmallPtrSet<PHINode*, 8> PHIsInspected;
11730
11731 PHIsToSlice.push_back(&FirstPhi);
11732 PHIsInspected.insert(&FirstPhi);
11733
11734 for (unsigned PHIId = 0; PHIId != PHIsToSlice.size(); ++PHIId) {
11735 PHINode *PN = PHIsToSlice[PHIId];
Chris Lattner9956c052009-11-08 19:23:30 +000011736
Chris Lattner0ebc6ce2009-12-19 07:01:15 +000011737 // Scan the input list of the PHI. If any input is an invoke, and if the
11738 // input is defined in the predecessor, then we won't be split the critical
11739 // edge which is required to insert a truncate. Because of this, we have to
11740 // bail out.
11741 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
11742 InvokeInst *II = dyn_cast<InvokeInst>(PN->getIncomingValue(i));
11743 if (II == 0) continue;
11744 if (II->getParent() != PN->getIncomingBlock(i))
11745 continue;
11746
11747 // If we have a phi, and if it's directly in the predecessor, then we have
11748 // a critical edge where we need to put the truncate. Since we can't
11749 // split the edge in instcombine, we have to bail out.
11750 return 0;
11751 }
11752
11753
Chris Lattnerdd21a1c2009-11-09 01:38:00 +000011754 for (Value::use_iterator UI = PN->use_begin(), E = PN->use_end();
11755 UI != E; ++UI) {
11756 Instruction *User = cast<Instruction>(*UI);
11757
11758 // If the user is a PHI, inspect its uses recursively.
11759 if (PHINode *UserPN = dyn_cast<PHINode>(User)) {
11760 if (PHIsInspected.insert(UserPN))
11761 PHIsToSlice.push_back(UserPN);
11762 continue;
11763 }
11764
11765 // Truncates are always ok.
11766 if (isa<TruncInst>(User)) {
11767 PHIUsers.push_back(PHIUsageRecord(PHIId, 0, User));
11768 continue;
11769 }
11770
11771 // Otherwise it must be a lshr which can only be used by one trunc.
11772 if (User->getOpcode() != Instruction::LShr ||
11773 !User->hasOneUse() || !isa<TruncInst>(User->use_back()) ||
11774 !isa<ConstantInt>(User->getOperand(1)))
11775 return 0;
11776
11777 unsigned Shift = cast<ConstantInt>(User->getOperand(1))->getZExtValue();
11778 PHIUsers.push_back(PHIUsageRecord(PHIId, Shift, User->use_back()));
Chris Lattner9956c052009-11-08 19:23:30 +000011779 }
Chris Lattner9956c052009-11-08 19:23:30 +000011780 }
11781
11782 // If we have no users, they must be all self uses, just nuke the PHI.
11783 if (PHIUsers.empty())
Chris Lattnerdd21a1c2009-11-09 01:38:00 +000011784 return ReplaceInstUsesWith(FirstPhi, UndefValue::get(FirstPhi.getType()));
Chris Lattner9956c052009-11-08 19:23:30 +000011785
11786 // If this phi node is transformable, create new PHIs for all the pieces
11787 // extracted out of it. First, sort the users by their offset and size.
11788 array_pod_sort(PHIUsers.begin(), PHIUsers.end());
11789
Chris Lattnerdd21a1c2009-11-09 01:38:00 +000011790 DEBUG(errs() << "SLICING UP PHI: " << FirstPhi << '\n';
11791 for (unsigned i = 1, e = PHIsToSlice.size(); i != e; ++i)
11792 errs() << "AND USER PHI #" << i << ": " << *PHIsToSlice[i] <<'\n';
11793 );
Chris Lattner9956c052009-11-08 19:23:30 +000011794
Chris Lattnerdd21a1c2009-11-09 01:38:00 +000011795 // PredValues - This is a temporary used when rewriting PHI nodes. It is
11796 // hoisted out here to avoid construction/destruction thrashing.
Chris Lattner9956c052009-11-08 19:23:30 +000011797 DenseMap<BasicBlock*, Value*> PredValues;
11798
Chris Lattnerdd21a1c2009-11-09 01:38:00 +000011799 // ExtractedVals - Each new PHI we introduce is saved here so we don't
11800 // introduce redundant PHIs.
11801 DenseMap<LoweredPHIRecord, PHINode*> ExtractedVals;
11802
11803 for (unsigned UserI = 0, UserE = PHIUsers.size(); UserI != UserE; ++UserI) {
11804 unsigned PHIId = PHIUsers[UserI].PHIId;
11805 PHINode *PN = PHIsToSlice[PHIId];
Chris Lattner9956c052009-11-08 19:23:30 +000011806 unsigned Offset = PHIUsers[UserI].Shift;
11807 const Type *Ty = PHIUsers[UserI].Inst->getType();
Chris Lattner9956c052009-11-08 19:23:30 +000011808
Chris Lattnerdd21a1c2009-11-09 01:38:00 +000011809 PHINode *EltPHI;
11810
11811 // If we've already lowered a user like this, reuse the previously lowered
11812 // value.
11813 if ((EltPHI = ExtractedVals[LoweredPHIRecord(PN, Offset, Ty)]) == 0) {
Chris Lattner9956c052009-11-08 19:23:30 +000011814
Chris Lattnerdd21a1c2009-11-09 01:38:00 +000011815 // Otherwise, Create the new PHI node for this user.
11816 EltPHI = PHINode::Create(Ty, PN->getName()+".off"+Twine(Offset), PN);
11817 assert(EltPHI->getType() != PN->getType() &&
11818 "Truncate didn't shrink phi?");
11819
11820 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
11821 BasicBlock *Pred = PN->getIncomingBlock(i);
11822 Value *&PredVal = PredValues[Pred];
11823
11824 // If we already have a value for this predecessor, reuse it.
11825 if (PredVal) {
11826 EltPHI->addIncoming(PredVal, Pred);
11827 continue;
11828 }
Chris Lattner9956c052009-11-08 19:23:30 +000011829
Chris Lattnerdd21a1c2009-11-09 01:38:00 +000011830 // Handle the PHI self-reuse case.
11831 Value *InVal = PN->getIncomingValue(i);
11832 if (InVal == PN) {
11833 PredVal = EltPHI;
11834 EltPHI->addIncoming(PredVal, Pred);
11835 continue;
Chris Lattner0ebc6ce2009-12-19 07:01:15 +000011836 }
11837
11838 if (PHINode *InPHI = dyn_cast<PHINode>(PN)) {
Chris Lattnerdd21a1c2009-11-09 01:38:00 +000011839 // If the incoming value was a PHI, and if it was one of the PHIs we
11840 // already rewrote it, just use the lowered value.
11841 if (Value *Res = ExtractedVals[LoweredPHIRecord(InPHI, Offset, Ty)]) {
11842 PredVal = Res;
11843 EltPHI->addIncoming(PredVal, Pred);
11844 continue;
11845 }
11846 }
11847
11848 // Otherwise, do an extract in the predecessor.
11849 Builder->SetInsertPoint(Pred, Pred->getTerminator());
11850 Value *Res = InVal;
11851 if (Offset)
11852 Res = Builder->CreateLShr(Res, ConstantInt::get(InVal->getType(),
11853 Offset), "extract");
11854 Res = Builder->CreateTrunc(Res, Ty, "extract.t");
11855 PredVal = Res;
11856 EltPHI->addIncoming(Res, Pred);
11857
11858 // If the incoming value was a PHI, and if it was one of the PHIs we are
11859 // rewriting, we will ultimately delete the code we inserted. This
11860 // means we need to revisit that PHI to make sure we extract out the
11861 // needed piece.
11862 if (PHINode *OldInVal = dyn_cast<PHINode>(PN->getIncomingValue(i)))
11863 if (PHIsInspected.count(OldInVal)) {
11864 unsigned RefPHIId = std::find(PHIsToSlice.begin(),PHIsToSlice.end(),
11865 OldInVal)-PHIsToSlice.begin();
11866 PHIUsers.push_back(PHIUsageRecord(RefPHIId, Offset,
11867 cast<Instruction>(Res)));
11868 ++UserE;
11869 }
Chris Lattner9956c052009-11-08 19:23:30 +000011870 }
Chris Lattnerdd21a1c2009-11-09 01:38:00 +000011871 PredValues.clear();
Chris Lattner9956c052009-11-08 19:23:30 +000011872
Chris Lattnerdd21a1c2009-11-09 01:38:00 +000011873 DEBUG(errs() << " Made element PHI for offset " << Offset << ": "
11874 << *EltPHI << '\n');
11875 ExtractedVals[LoweredPHIRecord(PN, Offset, Ty)] = EltPHI;
Chris Lattner9956c052009-11-08 19:23:30 +000011876 }
Chris Lattner9956c052009-11-08 19:23:30 +000011877
Chris Lattnerdd21a1c2009-11-09 01:38:00 +000011878 // Replace the use of this piece with the PHI node.
11879 ReplaceInstUsesWith(*PHIUsers[UserI].Inst, EltPHI);
Chris Lattner9956c052009-11-08 19:23:30 +000011880 }
Chris Lattnerdd21a1c2009-11-09 01:38:00 +000011881
11882 // Replace all the remaining uses of the PHI nodes (self uses and the lshrs)
11883 // with undefs.
11884 Value *Undef = UndefValue::get(FirstPhi.getType());
11885 for (unsigned i = 1, e = PHIsToSlice.size(); i != e; ++i)
11886 ReplaceInstUsesWith(*PHIsToSlice[i], Undef);
11887 return ReplaceInstUsesWith(FirstPhi, Undef);
Chris Lattner9956c052009-11-08 19:23:30 +000011888}
11889
Chris Lattner473945d2002-05-06 18:06:38 +000011890// PHINode simplification
11891//
Chris Lattner7e708292002-06-25 16:13:24 +000011892Instruction *InstCombiner::visitPHINode(PHINode &PN) {
Owen Andersonb64ab872006-07-10 22:15:25 +000011893 // If LCSSA is around, don't mess with Phi nodes
Chris Lattnerf964f322007-03-04 04:27:24 +000011894 if (MustPreserveLCSSA) return 0;
Owen Andersond1b78a12006-07-10 19:03:49 +000011895
Owen Anderson7e057142006-07-10 22:03:18 +000011896 if (Value *V = PN.hasConstantValue())
11897 return ReplaceInstUsesWith(PN, V);
11898
Owen Anderson7e057142006-07-10 22:03:18 +000011899 // If all PHI operands are the same operation, pull them through the PHI,
11900 // reducing code size.
11901 if (isa<Instruction>(PN.getIncomingValue(0)) &&
Chris Lattner05f18922008-12-01 02:34:36 +000011902 isa<Instruction>(PN.getIncomingValue(1)) &&
11903 cast<Instruction>(PN.getIncomingValue(0))->getOpcode() ==
11904 cast<Instruction>(PN.getIncomingValue(1))->getOpcode() &&
11905 // FIXME: The hasOneUse check will fail for PHIs that use the value more
11906 // than themselves more than once.
Owen Anderson7e057142006-07-10 22:03:18 +000011907 PN.getIncomingValue(0)->hasOneUse())
11908 if (Instruction *Result = FoldPHIArgOpIntoPHI(PN))
11909 return Result;
11910
11911 // If this is a trivial cycle in the PHI node graph, remove it. Basically, if
11912 // this PHI only has a single use (a PHI), and if that PHI only has one use (a
11913 // PHI)... break the cycle.
Chris Lattnerff9f13a2007-01-15 07:30:06 +000011914 if (PN.hasOneUse()) {
11915 Instruction *PHIUser = cast<Instruction>(PN.use_back());
11916 if (PHINode *PU = dyn_cast<PHINode>(PHIUser)) {
Chris Lattner0e5444b2007-03-26 20:40:50 +000011917 SmallPtrSet<PHINode*, 16> PotentiallyDeadPHIs;
Owen Anderson7e057142006-07-10 22:03:18 +000011918 PotentiallyDeadPHIs.insert(&PN);
11919 if (DeadPHICycle(PU, PotentiallyDeadPHIs))
Owen Anderson9e9a0d52009-07-30 23:03:37 +000011920 return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
Owen Anderson7e057142006-07-10 22:03:18 +000011921 }
Chris Lattnerff9f13a2007-01-15 07:30:06 +000011922
11923 // If this phi has a single use, and if that use just computes a value for
11924 // the next iteration of a loop, delete the phi. This occurs with unused
11925 // induction variables, e.g. "for (int j = 0; ; ++j);". Detecting this
11926 // common case here is good because the only other things that catch this
11927 // are induction variable analysis (sometimes) and ADCE, which is only run
11928 // late.
11929 if (PHIUser->hasOneUse() &&
11930 (isa<BinaryOperator>(PHIUser) || isa<GetElementPtrInst>(PHIUser)) &&
11931 PHIUser->use_back() == &PN) {
Owen Anderson9e9a0d52009-07-30 23:03:37 +000011932 return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
Chris Lattnerff9f13a2007-01-15 07:30:06 +000011933 }
11934 }
Owen Anderson7e057142006-07-10 22:03:18 +000011935
Chris Lattnercf5008a2007-11-06 21:52:06 +000011936 // We sometimes end up with phi cycles that non-obviously end up being the
11937 // same value, for example:
11938 // z = some value; x = phi (y, z); y = phi (x, z)
11939 // where the phi nodes don't necessarily need to be in the same block. Do a
11940 // quick check to see if the PHI node only contains a single non-phi value, if
11941 // so, scan to see if the phi cycle is actually equal to that value.
11942 {
11943 unsigned InValNo = 0, NumOperandVals = PN.getNumIncomingValues();
11944 // Scan for the first non-phi operand.
11945 while (InValNo != NumOperandVals &&
11946 isa<PHINode>(PN.getIncomingValue(InValNo)))
11947 ++InValNo;
11948
11949 if (InValNo != NumOperandVals) {
11950 Value *NonPhiInVal = PN.getOperand(InValNo);
11951
11952 // Scan the rest of the operands to see if there are any conflicts, if so
11953 // there is no need to recursively scan other phis.
11954 for (++InValNo; InValNo != NumOperandVals; ++InValNo) {
11955 Value *OpVal = PN.getIncomingValue(InValNo);
11956 if (OpVal != NonPhiInVal && !isa<PHINode>(OpVal))
11957 break;
11958 }
11959
11960 // If we scanned over all operands, then we have one unique value plus
11961 // phi values. Scan PHI nodes to see if they all merge in each other or
11962 // the value.
11963 if (InValNo == NumOperandVals) {
11964 SmallPtrSet<PHINode*, 16> ValueEqualPHIs;
11965 if (PHIsEqualValue(&PN, NonPhiInVal, ValueEqualPHIs))
11966 return ReplaceInstUsesWith(PN, NonPhiInVal);
11967 }
11968 }
11969 }
Dan Gohman8e42e4b2009-10-30 22:22:22 +000011970
Dan Gohman5b097012009-10-31 14:22:52 +000011971 // If there are multiple PHIs, sort their operands so that they all list
11972 // the blocks in the same order. This will help identical PHIs be eliminated
11973 // by other passes. Other passes shouldn't depend on this for correctness
11974 // however.
11975 PHINode *FirstPN = cast<PHINode>(PN.getParent()->begin());
11976 if (&PN != FirstPN)
11977 for (unsigned i = 0, e = FirstPN->getNumIncomingValues(); i != e; ++i) {
Dan Gohman8e42e4b2009-10-30 22:22:22 +000011978 BasicBlock *BBA = PN.getIncomingBlock(i);
Dan Gohman5b097012009-10-31 14:22:52 +000011979 BasicBlock *BBB = FirstPN->getIncomingBlock(i);
11980 if (BBA != BBB) {
11981 Value *VA = PN.getIncomingValue(i);
11982 unsigned j = PN.getBasicBlockIndex(BBB);
11983 Value *VB = PN.getIncomingValue(j);
11984 PN.setIncomingBlock(i, BBB);
11985 PN.setIncomingValue(i, VB);
11986 PN.setIncomingBlock(j, BBA);
11987 PN.setIncomingValue(j, VA);
Chris Lattner28f3d342009-10-31 17:48:31 +000011988 // NOTE: Instcombine normally would want us to "return &PN" if we
11989 // modified any of the operands of an instruction. However, since we
11990 // aren't adding or removing uses (just rearranging them) we don't do
11991 // this in this case.
Dan Gohman5b097012009-10-31 14:22:52 +000011992 }
Dan Gohman8e42e4b2009-10-30 22:22:22 +000011993 }
11994
Chris Lattner9956c052009-11-08 19:23:30 +000011995 // If this is an integer PHI and we know that it has an illegal type, see if
11996 // it is only used by trunc or trunc(lshr) operations. If so, we split the
11997 // PHI into the various pieces being extracted. This sort of thing is
11998 // introduced when SROA promotes an aggregate to a single large integer type.
Chris Lattnerbf382b52009-11-08 21:20:06 +000011999 if (isa<IntegerType>(PN.getType()) && TD &&
Chris Lattner9956c052009-11-08 19:23:30 +000012000 !TD->isLegalInteger(PN.getType()->getPrimitiveSizeInBits()))
12001 if (Instruction *Res = SliceUpIllegalIntegerPHI(PN))
12002 return Res;
12003
Chris Lattner60921c92003-12-19 05:58:40 +000012004 return 0;
Chris Lattner473945d2002-05-06 18:06:38 +000012005}
12006
Chris Lattner7e708292002-06-25 16:13:24 +000012007Instruction *InstCombiner::visitGetElementPtrInst(GetElementPtrInst &GEP) {
Chris Lattnerc514c1f2009-11-27 00:29:05 +000012008 SmallVector<Value*, 8> Ops(GEP.op_begin(), GEP.op_end());
12009
12010 if (Value *V = SimplifyGEPInst(&Ops[0], Ops.size(), TD))
12011 return ReplaceInstUsesWith(GEP, V);
12012
Chris Lattner620ce142004-05-07 22:09:22 +000012013 Value *PtrOp = GEP.getOperand(0);
Chris Lattnerc6bd1952004-02-22 05:25:17 +000012014
Chris Lattnere87597f2004-10-16 18:11:37 +000012015 if (isa<UndefValue>(GEP.getOperand(0)))
Owen Anderson9e9a0d52009-07-30 23:03:37 +000012016 return ReplaceInstUsesWith(GEP, UndefValue::get(GEP.getType()));
Chris Lattnere87597f2004-10-16 18:11:37 +000012017
Chris Lattner28977af2004-04-05 01:30:19 +000012018 // Eliminate unneeded casts for indices.
Chris Lattnerccf4b342009-08-30 04:49:01 +000012019 if (TD) {
12020 bool MadeChange = false;
12021 unsigned PtrSize = TD->getPointerSizeInBits();
12022
12023 gep_type_iterator GTI = gep_type_begin(GEP);
12024 for (User::op_iterator I = GEP.op_begin() + 1, E = GEP.op_end();
12025 I != E; ++I, ++GTI) {
12026 if (!isa<SequentialType>(*GTI)) continue;
12027
Chris Lattnercb69a4e2004-04-07 18:38:20 +000012028 // If we are using a wider index than needed for this platform, shrink it
Chris Lattnerccf4b342009-08-30 04:49:01 +000012029 // to what we need. If narrower, sign-extend it to what we need. This
12030 // explicit cast can make subsequent optimizations more obvious.
12031 unsigned OpBits = cast<IntegerType>((*I)->getType())->getBitWidth();
Chris Lattnerccf4b342009-08-30 04:49:01 +000012032 if (OpBits == PtrSize)
12033 continue;
12034
Chris Lattner2345d1d2009-08-30 20:01:10 +000012035 *I = Builder->CreateIntCast(*I, TD->getIntPtrType(GEP.getContext()),true);
Chris Lattnerccf4b342009-08-30 04:49:01 +000012036 MadeChange = true;
Chris Lattner28977af2004-04-05 01:30:19 +000012037 }
Chris Lattnerccf4b342009-08-30 04:49:01 +000012038 if (MadeChange) return &GEP;
Chris Lattnerdb9654e2007-03-25 20:43:09 +000012039 }
Chris Lattner28977af2004-04-05 01:30:19 +000012040
Chris Lattner90ac28c2002-08-02 19:29:35 +000012041 // Combine Indices - If the source pointer to this getelementptr instruction
12042 // is a getelementptr instruction, combine the indices of the two
12043 // getelementptr instructions into a single instruction.
12044 //
Dan Gohmand6aa02d2009-07-28 01:40:03 +000012045 if (GEPOperator *Src = dyn_cast<GEPOperator>(PtrOp)) {
Chris Lattner620ce142004-05-07 22:09:22 +000012046 // Note that if our source is a gep chain itself that we wait for that
12047 // chain to be resolved before we perform this transformation. This
12048 // avoids us creating a TON of code in some cases.
12049 //
Chris Lattnerf9b91bb2009-08-30 05:08:50 +000012050 if (GetElementPtrInst *SrcGEP =
12051 dyn_cast<GetElementPtrInst>(Src->getOperand(0)))
12052 if (SrcGEP->getNumOperands() == 2)
12053 return 0; // Wait until our source is folded to completion.
Chris Lattner620ce142004-05-07 22:09:22 +000012054
Chris Lattner72588fc2007-02-15 22:48:32 +000012055 SmallVector<Value*, 8> Indices;
Chris Lattner620ce142004-05-07 22:09:22 +000012056
12057 // Find out whether the last index in the source GEP is a sequential idx.
12058 bool EndsWithSequential = false;
Chris Lattnerab984842009-08-30 05:30:55 +000012059 for (gep_type_iterator I = gep_type_begin(*Src), E = gep_type_end(*Src);
12060 I != E; ++I)
Chris Lattnerbe97b4e2004-05-08 22:41:42 +000012061 EndsWithSequential = !isa<StructType>(*I);
Misha Brukmanfd939082005-04-21 23:48:37 +000012062
Chris Lattner90ac28c2002-08-02 19:29:35 +000012063 // Can we combine the two pointer arithmetics offsets?
Chris Lattner620ce142004-05-07 22:09:22 +000012064 if (EndsWithSequential) {
Chris Lattnerdecd0812003-03-05 22:33:14 +000012065 // Replace: gep (gep %P, long B), long A, ...
12066 // With: T = long A+B; gep %P, T, ...
12067 //
Chris Lattnerf9b91bb2009-08-30 05:08:50 +000012068 Value *Sum;
12069 Value *SO1 = Src->getOperand(Src->getNumOperands()-1);
12070 Value *GO1 = GEP.getOperand(1);
Owen Andersona7235ea2009-07-31 20:28:14 +000012071 if (SO1 == Constant::getNullValue(SO1->getType())) {
Chris Lattner28977af2004-04-05 01:30:19 +000012072 Sum = GO1;
Owen Andersona7235ea2009-07-31 20:28:14 +000012073 } else if (GO1 == Constant::getNullValue(GO1->getType())) {
Chris Lattner28977af2004-04-05 01:30:19 +000012074 Sum = SO1;
12075 } else {
Chris Lattnerab984842009-08-30 05:30:55 +000012076 // If they aren't the same type, then the input hasn't been processed
12077 // by the loop above yet (which canonicalizes sequential index types to
12078 // intptr_t). Just avoid transforming this until the input has been
12079 // normalized.
12080 if (SO1->getType() != GO1->getType())
12081 return 0;
Chris Lattnerf925cbd2009-08-30 18:50:58 +000012082 Sum = Builder->CreateAdd(SO1, GO1, PtrOp->getName()+".sum");
Chris Lattner28977af2004-04-05 01:30:19 +000012083 }
Chris Lattner620ce142004-05-07 22:09:22 +000012084
Chris Lattnerab984842009-08-30 05:30:55 +000012085 // Update the GEP in place if possible.
Chris Lattnerf9b91bb2009-08-30 05:08:50 +000012086 if (Src->getNumOperands() == 2) {
12087 GEP.setOperand(0, Src->getOperand(0));
Chris Lattner620ce142004-05-07 22:09:22 +000012088 GEP.setOperand(1, Sum);
12089 return &GEP;
Chris Lattner620ce142004-05-07 22:09:22 +000012090 }
Chris Lattnerab984842009-08-30 05:30:55 +000012091 Indices.append(Src->op_begin()+1, Src->op_end()-1);
Chris Lattnerccf4b342009-08-30 04:49:01 +000012092 Indices.push_back(Sum);
Chris Lattnerab984842009-08-30 05:30:55 +000012093 Indices.append(GEP.op_begin()+2, GEP.op_end());
Misha Brukmanfd939082005-04-21 23:48:37 +000012094 } else if (isa<Constant>(*GEP.idx_begin()) &&
Chris Lattner28977af2004-04-05 01:30:19 +000012095 cast<Constant>(*GEP.idx_begin())->isNullValue() &&
Chris Lattnerf9b91bb2009-08-30 05:08:50 +000012096 Src->getNumOperands() != 1) {
Chris Lattner90ac28c2002-08-02 19:29:35 +000012097 // Otherwise we can do the fold if the first index of the GEP is a zero
Chris Lattnerab984842009-08-30 05:30:55 +000012098 Indices.append(Src->op_begin()+1, Src->op_end());
12099 Indices.append(GEP.idx_begin()+1, GEP.idx_end());
Chris Lattner90ac28c2002-08-02 19:29:35 +000012100 }
12101
Dan Gohmanf8dbee72009-09-07 23:54:19 +000012102 if (!Indices.empty())
12103 return (cast<GEPOperator>(&GEP)->isInBounds() &&
12104 Src->isInBounds()) ?
12105 GetElementPtrInst::CreateInBounds(Src->getOperand(0), Indices.begin(),
12106 Indices.end(), GEP.getName()) :
Chris Lattnerf9b91bb2009-08-30 05:08:50 +000012107 GetElementPtrInst::Create(Src->getOperand(0), Indices.begin(),
Chris Lattnerccf4b342009-08-30 04:49:01 +000012108 Indices.end(), GEP.getName());
Chris Lattner6e24d832009-08-30 05:00:50 +000012109 }
12110
Chris Lattnerf9b91bb2009-08-30 05:08:50 +000012111 // Handle gep(bitcast x) and gep(gep x, 0, 0, 0).
12112 if (Value *X = getBitCastOperand(PtrOp)) {
Chris Lattner6e24d832009-08-30 05:00:50 +000012113 assert(isa<PointerType>(X->getType()) && "Must be cast from pointer");
Chris Lattner963f4ba2009-08-30 20:36:46 +000012114
Chris Lattner2de23192009-08-30 20:38:21 +000012115 // If the input bitcast is actually "bitcast(bitcast(x))", then we don't
12116 // want to change the gep until the bitcasts are eliminated.
12117 if (getBitCastOperand(X)) {
12118 Worklist.AddValue(PtrOp);
12119 return 0;
12120 }
12121
Chris Lattnerc514c1f2009-11-27 00:29:05 +000012122 bool HasZeroPointerIndex = false;
12123 if (ConstantInt *C = dyn_cast<ConstantInt>(GEP.getOperand(1)))
12124 HasZeroPointerIndex = C->isZero();
12125
Chris Lattner963f4ba2009-08-30 20:36:46 +000012126 // Transform: GEP (bitcast [10 x i8]* X to [0 x i8]*), i32 0, ...
12127 // into : GEP [10 x i8]* X, i32 0, ...
12128 //
12129 // Likewise, transform: GEP (bitcast i8* X to [0 x i8]*), i32 0, ...
12130 // into : GEP i8* X, ...
12131 //
12132 // This occurs when the program declares an array extern like "int X[];"
Chris Lattner6e24d832009-08-30 05:00:50 +000012133 if (HasZeroPointerIndex) {
Chris Lattnereed48272005-09-13 00:40:14 +000012134 const PointerType *CPTy = cast<PointerType>(PtrOp->getType());
12135 const PointerType *XTy = cast<PointerType>(X->getType());
Duncan Sands5b7cfb02009-03-02 09:18:21 +000012136 if (const ArrayType *CATy =
12137 dyn_cast<ArrayType>(CPTy->getElementType())) {
12138 // GEP (bitcast i8* X to [0 x i8]*), i32 0, ... ?
12139 if (CATy->getElementType() == XTy->getElementType()) {
12140 // -> GEP i8* X, ...
12141 SmallVector<Value*, 8> Indices(GEP.idx_begin()+1, GEP.idx_end());
Dan Gohmanf8dbee72009-09-07 23:54:19 +000012142 return cast<GEPOperator>(&GEP)->isInBounds() ?
12143 GetElementPtrInst::CreateInBounds(X, Indices.begin(), Indices.end(),
12144 GEP.getName()) :
Dan Gohmand6aa02d2009-07-28 01:40:03 +000012145 GetElementPtrInst::Create(X, Indices.begin(), Indices.end(),
12146 GEP.getName());
Chris Lattner963f4ba2009-08-30 20:36:46 +000012147 }
12148
12149 if (const ArrayType *XATy = dyn_cast<ArrayType>(XTy->getElementType())){
Duncan Sands5b7cfb02009-03-02 09:18:21 +000012150 // GEP (bitcast [10 x i8]* X to [0 x i8]*), i32 0, ... ?
Chris Lattnereed48272005-09-13 00:40:14 +000012151 if (CATy->getElementType() == XATy->getElementType()) {
Duncan Sands5b7cfb02009-03-02 09:18:21 +000012152 // -> GEP [10 x i8]* X, i32 0, ...
Chris Lattnereed48272005-09-13 00:40:14 +000012153 // At this point, we know that the cast source type is a pointer
12154 // to an array of the same type as the destination pointer
12155 // array. Because the array type is never stepped over (there
12156 // is a leading zero) we can fold the cast into this GEP.
12157 GEP.setOperand(0, X);
12158 return &GEP;
12159 }
Duncan Sands5b7cfb02009-03-02 09:18:21 +000012160 }
12161 }
Chris Lattnereed48272005-09-13 00:40:14 +000012162 } else if (GEP.getNumOperands() == 2) {
12163 // Transform things like:
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000012164 // %t = getelementptr i32* bitcast ([2 x i32]* %str to i32*), i32 %V
12165 // into: %t1 = getelementptr [2 x i32]* %str, i32 0, i32 %V; bitcast
Chris Lattnereed48272005-09-13 00:40:14 +000012166 const Type *SrcElTy = cast<PointerType>(X->getType())->getElementType();
12167 const Type *ResElTy=cast<PointerType>(PtrOp->getType())->getElementType();
Dan Gohmance9fe9f2009-07-21 23:21:54 +000012168 if (TD && isa<ArrayType>(SrcElTy) &&
Duncan Sands777d2302009-05-09 07:06:46 +000012169 TD->getTypeAllocSize(cast<ArrayType>(SrcElTy)->getElementType()) ==
12170 TD->getTypeAllocSize(ResElTy)) {
David Greeneb8f74792007-09-04 15:46:09 +000012171 Value *Idx[2];
Owen Anderson1d0be152009-08-13 21:58:54 +000012172 Idx[0] = Constant::getNullValue(Type::getInt32Ty(*Context));
David Greeneb8f74792007-09-04 15:46:09 +000012173 Idx[1] = GEP.getOperand(1);
Dan Gohmanf8dbee72009-09-07 23:54:19 +000012174 Value *NewGEP = cast<GEPOperator>(&GEP)->isInBounds() ?
12175 Builder->CreateInBoundsGEP(X, Idx, Idx + 2, GEP.getName()) :
Chris Lattnerf925cbd2009-08-30 18:50:58 +000012176 Builder->CreateGEP(X, Idx, Idx + 2, GEP.getName());
Reid Spencer3da59db2006-11-27 01:05:10 +000012177 // V and GEP are both pointer types --> BitCast
Chris Lattnerf925cbd2009-08-30 18:50:58 +000012178 return new BitCastInst(NewGEP, GEP.getType());
Chris Lattnerc6bd1952004-02-22 05:25:17 +000012179 }
Chris Lattner7835cdd2005-09-13 18:36:04 +000012180
12181 // Transform things like:
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000012182 // getelementptr i8* bitcast ([100 x double]* X to i8*), i32 %tmp
Chris Lattner7835cdd2005-09-13 18:36:04 +000012183 // (where tmp = 8*tmp2) into:
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000012184 // getelementptr [100 x double]* %arr, i32 0, i32 %tmp2; bitcast
Chris Lattner7835cdd2005-09-13 18:36:04 +000012185
Owen Anderson1d0be152009-08-13 21:58:54 +000012186 if (TD && isa<ArrayType>(SrcElTy) && ResElTy == Type::getInt8Ty(*Context)) {
Chris Lattner7835cdd2005-09-13 18:36:04 +000012187 uint64_t ArrayEltSize =
Duncan Sands777d2302009-05-09 07:06:46 +000012188 TD->getTypeAllocSize(cast<ArrayType>(SrcElTy)->getElementType());
Chris Lattner7835cdd2005-09-13 18:36:04 +000012189
12190 // Check to see if "tmp" is a scale by a multiple of ArrayEltSize. We
12191 // allow either a mul, shift, or constant here.
12192 Value *NewIdx = 0;
12193 ConstantInt *Scale = 0;
12194 if (ArrayEltSize == 1) {
12195 NewIdx = GEP.getOperand(1);
Chris Lattnerab984842009-08-30 05:30:55 +000012196 Scale = ConstantInt::get(cast<IntegerType>(NewIdx->getType()), 1);
Chris Lattner7835cdd2005-09-13 18:36:04 +000012197 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP.getOperand(1))) {
Owen Andersoneed707b2009-07-24 23:12:02 +000012198 NewIdx = ConstantInt::get(CI->getType(), 1);
Chris Lattner7835cdd2005-09-13 18:36:04 +000012199 Scale = CI;
12200 } else if (Instruction *Inst =dyn_cast<Instruction>(GEP.getOperand(1))){
12201 if (Inst->getOpcode() == Instruction::Shl &&
12202 isa<ConstantInt>(Inst->getOperand(1))) {
Zhou Sheng0e2d3ac2007-03-30 09:29:48 +000012203 ConstantInt *ShAmt = cast<ConstantInt>(Inst->getOperand(1));
12204 uint32_t ShAmtVal = ShAmt->getLimitedValue(64);
Owen Andersoneed707b2009-07-24 23:12:02 +000012205 Scale = ConstantInt::get(cast<IntegerType>(Inst->getType()),
Dan Gohman6de29f82009-06-15 22:12:54 +000012206 1ULL << ShAmtVal);
Chris Lattner7835cdd2005-09-13 18:36:04 +000012207 NewIdx = Inst->getOperand(0);
12208 } else if (Inst->getOpcode() == Instruction::Mul &&
12209 isa<ConstantInt>(Inst->getOperand(1))) {
12210 Scale = cast<ConstantInt>(Inst->getOperand(1));
12211 NewIdx = Inst->getOperand(0);
12212 }
12213 }
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000012214
Chris Lattner7835cdd2005-09-13 18:36:04 +000012215 // If the index will be to exactly the right offset with the scale taken
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000012216 // out, perform the transformation. Note, we don't know whether Scale is
12217 // signed or not. We'll use unsigned version of division/modulo
12218 // operation after making sure Scale doesn't have the sign bit set.
Chris Lattner58b1ac72009-02-25 18:20:01 +000012219 if (ArrayEltSize && Scale && Scale->getSExtValue() >= 0LL &&
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000012220 Scale->getZExtValue() % ArrayEltSize == 0) {
Owen Andersoneed707b2009-07-24 23:12:02 +000012221 Scale = ConstantInt::get(Scale->getType(),
Wojciech Matyjewiczed223252007-12-12 15:21:32 +000012222 Scale->getZExtValue() / ArrayEltSize);
Reid Spencerb83eb642006-10-20 07:07:24 +000012223 if (Scale->getZExtValue() != 1) {
Chris Lattner878daed2009-08-30 05:56:44 +000012224 Constant *C = ConstantExpr::getIntegerCast(Scale, NewIdx->getType(),
12225 false /*ZExt*/);
Chris Lattnerf925cbd2009-08-30 18:50:58 +000012226 NewIdx = Builder->CreateMul(NewIdx, C, "idxscale");
Chris Lattner7835cdd2005-09-13 18:36:04 +000012227 }
12228
12229 // Insert the new GEP instruction.
David Greeneb8f74792007-09-04 15:46:09 +000012230 Value *Idx[2];
Owen Anderson1d0be152009-08-13 21:58:54 +000012231 Idx[0] = Constant::getNullValue(Type::getInt32Ty(*Context));
David Greeneb8f74792007-09-04 15:46:09 +000012232 Idx[1] = NewIdx;
Dan Gohmanf8dbee72009-09-07 23:54:19 +000012233 Value *NewGEP = cast<GEPOperator>(&GEP)->isInBounds() ?
12234 Builder->CreateInBoundsGEP(X, Idx, Idx + 2, GEP.getName()) :
12235 Builder->CreateGEP(X, Idx, Idx + 2, GEP.getName());
Reid Spencer3da59db2006-11-27 01:05:10 +000012236 // The NewGEP must be pointer typed, so must the old one -> BitCast
12237 return new BitCastInst(NewGEP, GEP.getType());
Chris Lattner7835cdd2005-09-13 18:36:04 +000012238 }
12239 }
Chris Lattnerc6bd1952004-02-22 05:25:17 +000012240 }
Chris Lattner8a2a3112001-12-14 16:52:21 +000012241 }
Chris Lattner58407792009-01-09 04:53:57 +000012242
Chris Lattner46cd5a12009-01-09 05:44:56 +000012243 /// See if we can simplify:
Chris Lattner873ff012009-08-30 05:55:36 +000012244 /// X = bitcast A* to B*
Chris Lattner46cd5a12009-01-09 05:44:56 +000012245 /// Y = gep X, <...constant indices...>
12246 /// into a gep of the original struct. This is important for SROA and alias
12247 /// analysis of unions. If "A" is also a bitcast, wait for A/X to be merged.
Chris Lattner58407792009-01-09 04:53:57 +000012248 if (BitCastInst *BCI = dyn_cast<BitCastInst>(PtrOp)) {
Dan Gohmance9fe9f2009-07-21 23:21:54 +000012249 if (TD &&
12250 !isa<BitCastInst>(BCI->getOperand(0)) && GEP.hasAllConstantIndices()) {
Chris Lattner46cd5a12009-01-09 05:44:56 +000012251 // Determine how much the GEP moves the pointer. We are guaranteed to get
12252 // a constant back from EmitGEPOffset.
Chris Lattner092543c2009-11-04 08:05:20 +000012253 ConstantInt *OffsetV = cast<ConstantInt>(EmitGEPOffset(&GEP, *this));
Chris Lattner46cd5a12009-01-09 05:44:56 +000012254 int64_t Offset = OffsetV->getSExtValue();
12255
12256 // If this GEP instruction doesn't move the pointer, just replace the GEP
12257 // with a bitcast of the real input to the dest type.
12258 if (Offset == 0) {
12259 // If the bitcast is of an allocation, and the allocation will be
12260 // converted to match the type of the cast, don't touch this.
Victor Hernandez7b929da2009-10-23 21:09:37 +000012261 if (isa<AllocaInst>(BCI->getOperand(0)) ||
Victor Hernandez83d63912009-09-18 22:35:49 +000012262 isMalloc(BCI->getOperand(0))) {
Chris Lattner46cd5a12009-01-09 05:44:56 +000012263 // See if the bitcast simplifies, if so, don't nuke this GEP yet.
12264 if (Instruction *I = visitBitCast(*BCI)) {
12265 if (I != BCI) {
12266 I->takeName(BCI);
12267 BCI->getParent()->getInstList().insert(BCI, I);
12268 ReplaceInstUsesWith(*BCI, I);
12269 }
12270 return &GEP;
Chris Lattner58407792009-01-09 04:53:57 +000012271 }
Chris Lattner58407792009-01-09 04:53:57 +000012272 }
Chris Lattner46cd5a12009-01-09 05:44:56 +000012273 return new BitCastInst(BCI->getOperand(0), GEP.getType());
Chris Lattner58407792009-01-09 04:53:57 +000012274 }
Chris Lattner46cd5a12009-01-09 05:44:56 +000012275
12276 // Otherwise, if the offset is non-zero, we need to find out if there is a
12277 // field at Offset in 'A's type. If so, we can pull the cast through the
12278 // GEP.
12279 SmallVector<Value*, 8> NewIndices;
12280 const Type *InTy =
12281 cast<PointerType>(BCI->getOperand(0)->getType())->getElementType();
Owen Andersond672ecb2009-07-03 00:17:18 +000012282 if (FindElementAtOffset(InTy, Offset, NewIndices, TD, Context)) {
Dan Gohmanf8dbee72009-09-07 23:54:19 +000012283 Value *NGEP = cast<GEPOperator>(&GEP)->isInBounds() ?
12284 Builder->CreateInBoundsGEP(BCI->getOperand(0), NewIndices.begin(),
12285 NewIndices.end()) :
12286 Builder->CreateGEP(BCI->getOperand(0), NewIndices.begin(),
12287 NewIndices.end());
Chris Lattnerf925cbd2009-08-30 18:50:58 +000012288
12289 if (NGEP->getType() == GEP.getType())
12290 return ReplaceInstUsesWith(GEP, NGEP);
Chris Lattner46cd5a12009-01-09 05:44:56 +000012291 NGEP->takeName(&GEP);
12292 return new BitCastInst(NGEP, GEP.getType());
12293 }
Chris Lattner58407792009-01-09 04:53:57 +000012294 }
12295 }
12296
Chris Lattner8a2a3112001-12-14 16:52:21 +000012297 return 0;
12298}
12299
Victor Hernandez7b929da2009-10-23 21:09:37 +000012300Instruction *InstCombiner::visitAllocaInst(AllocaInst &AI) {
Chris Lattnere3c62812009-11-01 19:50:13 +000012301 // Convert: alloca Ty, C - where C is a constant != 1 into: alloca [C x Ty], 1
Anton Korobeynikov07e6e562008-02-20 11:26:25 +000012302 if (AI.isArrayAllocation()) { // Check C != 1
Reid Spencerb83eb642006-10-20 07:07:24 +000012303 if (const ConstantInt *C = dyn_cast<ConstantInt>(AI.getArraySize())) {
12304 const Type *NewTy =
Owen Andersondebcb012009-07-29 22:17:13 +000012305 ArrayType::get(AI.getAllocatedType(), C->getZExtValue());
Victor Hernandeza276c602009-10-17 01:18:07 +000012306 assert(isa<AllocaInst>(AI) && "Unknown type of allocation inst!");
Victor Hernandez7b929da2009-10-23 21:09:37 +000012307 AllocaInst *New = Builder->CreateAlloca(NewTy, 0, AI.getName());
Chris Lattnerf925cbd2009-08-30 18:50:58 +000012308 New->setAlignment(AI.getAlignment());
Misha Brukmanfd939082005-04-21 23:48:37 +000012309
Chris Lattner0864acf2002-11-04 16:18:53 +000012310 // Scan to the end of the allocation instructions, to skip over a block of
Dale Johannesena8915182009-03-11 22:19:43 +000012311 // allocas if possible...also skip interleaved debug info
Chris Lattner0864acf2002-11-04 16:18:53 +000012312 //
12313 BasicBlock::iterator It = New;
Victor Hernandez7b929da2009-10-23 21:09:37 +000012314 while (isa<AllocaInst>(*It) || isa<DbgInfoIntrinsic>(*It)) ++It;
Chris Lattner0864acf2002-11-04 16:18:53 +000012315
12316 // Now that I is pointing to the first non-allocation-inst in the block,
12317 // insert our getelementptr instruction...
12318 //
Owen Anderson1d0be152009-08-13 21:58:54 +000012319 Value *NullIdx = Constant::getNullValue(Type::getInt32Ty(*Context));
David Greeneb8f74792007-09-04 15:46:09 +000012320 Value *Idx[2];
12321 Idx[0] = NullIdx;
12322 Idx[1] = NullIdx;
Dan Gohmanf8dbee72009-09-07 23:54:19 +000012323 Value *V = GetElementPtrInst::CreateInBounds(New, Idx, Idx + 2,
12324 New->getName()+".sub", It);
Chris Lattner0864acf2002-11-04 16:18:53 +000012325
12326 // Now make everything use the getelementptr instead of the original
12327 // allocation.
Chris Lattner7c881df2004-03-19 06:08:10 +000012328 return ReplaceInstUsesWith(AI, V);
Chris Lattnere87597f2004-10-16 18:11:37 +000012329 } else if (isa<UndefValue>(AI.getArraySize())) {
Owen Andersona7235ea2009-07-31 20:28:14 +000012330 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
Chris Lattner0864acf2002-11-04 16:18:53 +000012331 }
Anton Korobeynikov07e6e562008-02-20 11:26:25 +000012332 }
Chris Lattner7c881df2004-03-19 06:08:10 +000012333
Dan Gohmance9fe9f2009-07-21 23:21:54 +000012334 if (TD && isa<AllocaInst>(AI) && AI.getAllocatedType()->isSized()) {
Dan Gohman6893cd72009-01-13 20:18:38 +000012335 // If alloca'ing a zero byte object, replace the alloca with a null pointer.
Chris Lattner46d232d2009-03-17 17:55:15 +000012336 // Note that we only do this for alloca's, because malloc should allocate
12337 // and return a unique pointer, even for a zero byte allocation.
Duncan Sands777d2302009-05-09 07:06:46 +000012338 if (TD->getTypeAllocSize(AI.getAllocatedType()) == 0)
Owen Andersona7235ea2009-07-31 20:28:14 +000012339 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
Dan Gohman6893cd72009-01-13 20:18:38 +000012340
12341 // If the alignment is 0 (unspecified), assign it the preferred alignment.
12342 if (AI.getAlignment() == 0)
12343 AI.setAlignment(TD->getPrefTypeAlignment(AI.getAllocatedType()));
12344 }
Chris Lattner7c881df2004-03-19 06:08:10 +000012345
Chris Lattner0864acf2002-11-04 16:18:53 +000012346 return 0;
12347}
12348
Victor Hernandez66284e02009-10-24 04:23:03 +000012349Instruction *InstCombiner::visitFree(Instruction &FI) {
12350 Value *Op = FI.getOperand(1);
12351
12352 // free undef -> unreachable.
12353 if (isa<UndefValue>(Op)) {
12354 // Insert a new store to null because we cannot modify the CFG here.
12355 new StoreInst(ConstantInt::getTrue(*Context),
12356 UndefValue::get(Type::getInt1PtrTy(*Context)), &FI);
12357 return EraseInstFromFunction(FI);
12358 }
12359
12360 // If we have 'free null' delete the instruction. This can happen in stl code
12361 // when lots of inlining happens.
12362 if (isa<ConstantPointerNull>(Op))
12363 return EraseInstFromFunction(FI);
12364
Victor Hernandez046e78c2009-10-26 23:43:48 +000012365 // If we have a malloc call whose only use is a free call, delete both.
Dan Gohman7f712a12009-10-27 00:11:02 +000012366 if (isMalloc(Op)) {
Victor Hernandez66284e02009-10-24 04:23:03 +000012367 if (CallInst* CI = extractMallocCallFromBitCast(Op)) {
12368 if (Op->hasOneUse() && CI->hasOneUse()) {
12369 EraseInstFromFunction(FI);
12370 EraseInstFromFunction(*CI);
12371 return EraseInstFromFunction(*cast<Instruction>(Op));
12372 }
12373 } else {
12374 // Op is a call to malloc
12375 if (Op->hasOneUse()) {
12376 EraseInstFromFunction(FI);
12377 return EraseInstFromFunction(*cast<Instruction>(Op));
12378 }
12379 }
Dan Gohman7f712a12009-10-27 00:11:02 +000012380 }
Victor Hernandez66284e02009-10-24 04:23:03 +000012381
12382 return 0;
12383}
Chris Lattner67b1e1b2003-12-07 01:24:23 +000012384
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000012385/// InstCombineLoadCast - Fold 'load (cast P)' -> cast (load P)' when possible.
Devang Patel99db6ad2007-10-18 19:52:32 +000012386static Instruction *InstCombineLoadCast(InstCombiner &IC, LoadInst &LI,
Bill Wendling587c01d2008-02-26 10:53:30 +000012387 const TargetData *TD) {
Chris Lattnerb89e0712004-07-13 01:49:43 +000012388 User *CI = cast<User>(LI.getOperand(0));
Chris Lattnerf9527852005-01-31 04:50:46 +000012389 Value *CastOp = CI->getOperand(0);
Owen Anderson07cf79e2009-07-06 23:00:19 +000012390 LLVMContext *Context = IC.getContext();
Chris Lattnerb89e0712004-07-13 01:49:43 +000012391
Mon P Wang6753f952009-02-07 22:19:29 +000012392 const PointerType *DestTy = cast<PointerType>(CI->getType());
12393 const Type *DestPTy = DestTy->getElementType();
Chris Lattnerf9527852005-01-31 04:50:46 +000012394 if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
Mon P Wang6753f952009-02-07 22:19:29 +000012395
12396 // If the address spaces don't match, don't eliminate the cast.
12397 if (DestTy->getAddressSpace() != SrcTy->getAddressSpace())
12398 return 0;
12399
Chris Lattnerb89e0712004-07-13 01:49:43 +000012400 const Type *SrcPTy = SrcTy->getElementType();
Chris Lattnerf9527852005-01-31 04:50:46 +000012401
Reid Spencer42230162007-01-22 05:51:25 +000012402 if (DestPTy->isInteger() || isa<PointerType>(DestPTy) ||
Reid Spencer9d6565a2007-02-15 02:26:10 +000012403 isa<VectorType>(DestPTy)) {
Chris Lattnerf9527852005-01-31 04:50:46 +000012404 // If the source is an array, the code below will not succeed. Check to
12405 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
12406 // constants.
12407 if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
12408 if (Constant *CSrc = dyn_cast<Constant>(CastOp))
12409 if (ASrcTy->getNumElements() != 0) {
Chris Lattner55eb1c42007-01-31 04:40:53 +000012410 Value *Idxs[2];
Chris Lattnere00c43f2009-10-22 06:44:07 +000012411 Idxs[0] = Constant::getNullValue(Type::getInt32Ty(*Context));
12412 Idxs[1] = Idxs[0];
Owen Andersonbaf3c402009-07-29 18:55:55 +000012413 CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs, 2);
Chris Lattnerf9527852005-01-31 04:50:46 +000012414 SrcTy = cast<PointerType>(CastOp->getType());
12415 SrcPTy = SrcTy->getElementType();
12416 }
12417
Dan Gohmance9fe9f2009-07-21 23:21:54 +000012418 if (IC.getTargetData() &&
12419 (SrcPTy->isInteger() || isa<PointerType>(SrcPTy) ||
Reid Spencer9d6565a2007-02-15 02:26:10 +000012420 isa<VectorType>(SrcPTy)) &&
Chris Lattnerb1515fe2005-03-29 06:37:47 +000012421 // Do not allow turning this into a load of an integer, which is then
12422 // casted to a pointer, this pessimizes pointer analysis a lot.
12423 (isa<PointerType>(SrcPTy) == isa<PointerType>(LI.getType())) &&
Dan Gohmance9fe9f2009-07-21 23:21:54 +000012424 IC.getTargetData()->getTypeSizeInBits(SrcPTy) ==
12425 IC.getTargetData()->getTypeSizeInBits(DestPTy)) {
Misha Brukmanfd939082005-04-21 23:48:37 +000012426
Chris Lattnerf9527852005-01-31 04:50:46 +000012427 // Okay, we are casting from one integer or pointer type to another of
12428 // the same size. Instead of casting the pointer before the load, cast
12429 // the result of the loaded value.
Chris Lattnerf925cbd2009-08-30 18:50:58 +000012430 Value *NewLoad =
12431 IC.Builder->CreateLoad(CastOp, LI.isVolatile(), CI->getName());
Chris Lattnerf9527852005-01-31 04:50:46 +000012432 // Now cast the result of the load.
Reid Spencerd977d862006-12-12 23:36:14 +000012433 return new BitCastInst(NewLoad, LI.getType());
Chris Lattnerf9527852005-01-31 04:50:46 +000012434 }
Chris Lattnerb89e0712004-07-13 01:49:43 +000012435 }
12436 }
12437 return 0;
12438}
12439
Chris Lattner833b8a42003-06-26 05:06:25 +000012440Instruction *InstCombiner::visitLoadInst(LoadInst &LI) {
12441 Value *Op = LI.getOperand(0);
Chris Lattner5f16a132004-01-12 04:13:56 +000012442
Dan Gohman9941f742007-07-20 16:34:21 +000012443 // Attempt to improve the alignment.
Dan Gohmance9fe9f2009-07-21 23:21:54 +000012444 if (TD) {
12445 unsigned KnownAlign =
12446 GetOrEnforceKnownAlignment(Op, TD->getPrefTypeAlignment(LI.getType()));
12447 if (KnownAlign >
12448 (LI.getAlignment() == 0 ? TD->getABITypeAlignment(LI.getType()) :
12449 LI.getAlignment()))
12450 LI.setAlignment(KnownAlign);
12451 }
Dan Gohman9941f742007-07-20 16:34:21 +000012452
Chris Lattner963f4ba2009-08-30 20:36:46 +000012453 // load (cast X) --> cast (load X) iff safe.
Reid Spencer3ed469c2006-11-02 20:25:50 +000012454 if (isa<CastInst>(Op))
Devang Patel99db6ad2007-10-18 19:52:32 +000012455 if (Instruction *Res = InstCombineLoadCast(*this, LI, TD))
Chris Lattner37366c12005-05-01 04:24:53 +000012456 return Res;
12457
12458 // None of the following transforms are legal for volatile loads.
12459 if (LI.isVolatile()) return 0;
Chris Lattner62f254d2005-09-12 22:00:15 +000012460
Dan Gohman2276a7b2008-10-15 23:19:35 +000012461 // Do really simple store-to-load forwarding and load CSE, to catch cases
12462 // where there are several consequtive memory accesses to the same location,
12463 // separated by a few arithmetic operations.
12464 BasicBlock::iterator BBI = &LI;
Chris Lattner4aebaee2008-11-27 08:56:30 +000012465 if (Value *AvailableVal = FindAvailableLoadedValue(Op, LI.getParent(), BBI,6))
12466 return ReplaceInstUsesWith(LI, AvailableVal);
Chris Lattner37366c12005-05-01 04:24:53 +000012467
Chris Lattner878e4942009-10-22 06:25:11 +000012468 // load(gep null, ...) -> unreachable
Christopher Lambb15147e2007-12-29 07:56:53 +000012469 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op)) {
12470 const Value *GEPI0 = GEPI->getOperand(0);
12471 // TODO: Consider a target hook for valid address spaces for this xform.
Chris Lattner8a67ac52009-08-30 20:06:40 +000012472 if (isa<ConstantPointerNull>(GEPI0) && GEPI->getPointerAddressSpace() == 0){
Chris Lattner37366c12005-05-01 04:24:53 +000012473 // Insert a new store to null instruction before the load to indicate
12474 // that this code is not reachable. We do this instead of inserting
12475 // an unreachable instruction directly because we cannot modify the
12476 // CFG.
Owen Anderson9e9a0d52009-07-30 23:03:37 +000012477 new StoreInst(UndefValue::get(LI.getType()),
Owen Andersona7235ea2009-07-31 20:28:14 +000012478 Constant::getNullValue(Op->getType()), &LI);
Owen Anderson9e9a0d52009-07-30 23:03:37 +000012479 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
Chris Lattner37366c12005-05-01 04:24:53 +000012480 }
Christopher Lambb15147e2007-12-29 07:56:53 +000012481 }
Chris Lattner37366c12005-05-01 04:24:53 +000012482
Chris Lattner878e4942009-10-22 06:25:11 +000012483 // load null/undef -> unreachable
12484 // TODO: Consider a target hook for valid address spaces for this xform.
12485 if (isa<UndefValue>(Op) ||
12486 (isa<ConstantPointerNull>(Op) && LI.getPointerAddressSpace() == 0)) {
12487 // Insert a new store to null instruction before the load to indicate that
12488 // this code is not reachable. We do this instead of inserting an
12489 // unreachable instruction directly because we cannot modify the CFG.
12490 new StoreInst(UndefValue::get(LI.getType()),
12491 Constant::getNullValue(Op->getType()), &LI);
12492 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
Chris Lattnere87597f2004-10-16 18:11:37 +000012493 }
Chris Lattner878e4942009-10-22 06:25:11 +000012494
12495 // Instcombine load (constantexpr_cast global) -> cast (load global)
12496 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Op))
12497 if (CE->isCast())
12498 if (Instruction *Res = InstCombineLoadCast(*this, LI, TD))
12499 return Res;
12500
Chris Lattner37366c12005-05-01 04:24:53 +000012501 if (Op->hasOneUse()) {
Chris Lattnerc10aced2004-09-19 18:43:46 +000012502 // Change select and PHI nodes to select values instead of addresses: this
12503 // helps alias analysis out a lot, allows many others simplifications, and
12504 // exposes redundancy in the code.
12505 //
12506 // Note that we cannot do the transformation unless we know that the
12507 // introduced loads cannot trap! Something like this is valid as long as
12508 // the condition is always false: load (select bool %C, int* null, int* %G),
12509 // but it would not be valid if we transformed it to load from null
12510 // unconditionally.
12511 //
12512 if (SelectInst *SI = dyn_cast<SelectInst>(Op)) {
12513 // load (select (Cond, &V1, &V2)) --> select(Cond, load &V1, load &V2).
Chris Lattner8a375202004-09-19 19:18:10 +000012514 if (isSafeToLoadUnconditionally(SI->getOperand(1), SI) &&
12515 isSafeToLoadUnconditionally(SI->getOperand(2), SI)) {
Chris Lattnerf925cbd2009-08-30 18:50:58 +000012516 Value *V1 = Builder->CreateLoad(SI->getOperand(1),
12517 SI->getOperand(1)->getName()+".val");
12518 Value *V2 = Builder->CreateLoad(SI->getOperand(2),
12519 SI->getOperand(2)->getName()+".val");
Gabor Greif051a9502008-04-06 20:25:17 +000012520 return SelectInst::Create(SI->getCondition(), V1, V2);
Chris Lattnerc10aced2004-09-19 18:43:46 +000012521 }
12522
Chris Lattner684fe212004-09-23 15:46:00 +000012523 // load (select (cond, null, P)) -> load P
12524 if (Constant *C = dyn_cast<Constant>(SI->getOperand(1)))
12525 if (C->isNullValue()) {
12526 LI.setOperand(0, SI->getOperand(2));
12527 return &LI;
12528 }
12529
12530 // load (select (cond, P, null)) -> load P
12531 if (Constant *C = dyn_cast<Constant>(SI->getOperand(2)))
12532 if (C->isNullValue()) {
12533 LI.setOperand(0, SI->getOperand(1));
12534 return &LI;
12535 }
Chris Lattnerc10aced2004-09-19 18:43:46 +000012536 }
12537 }
Chris Lattner833b8a42003-06-26 05:06:25 +000012538 return 0;
12539}
12540
Reid Spencer55af2b52007-01-19 21:20:31 +000012541/// InstCombineStoreToCast - Fold store V, (cast P) -> store (cast V), P
Chris Lattner3914f722009-01-24 01:00:13 +000012542/// when possible. This makes it generally easy to do alias analysis and/or
12543/// SROA/mem2reg of the memory object.
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000012544static Instruction *InstCombineStoreToCast(InstCombiner &IC, StoreInst &SI) {
12545 User *CI = cast<User>(SI.getOperand(1));
12546 Value *CastOp = CI->getOperand(0);
12547
12548 const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
Chris Lattner1b8eaf52009-01-16 20:08:59 +000012549 const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType());
12550 if (SrcTy == 0) return 0;
12551
12552 const Type *SrcPTy = SrcTy->getElementType();
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000012553
Chris Lattner1b8eaf52009-01-16 20:08:59 +000012554 if (!DestPTy->isInteger() && !isa<PointerType>(DestPTy))
12555 return 0;
12556
Chris Lattner3914f722009-01-24 01:00:13 +000012557 /// NewGEPIndices - If SrcPTy is an aggregate type, we can emit a "noop gep"
12558 /// to its first element. This allows us to handle things like:
12559 /// store i32 xxx, (bitcast {foo*, float}* %P to i32*)
12560 /// on 32-bit hosts.
12561 SmallVector<Value*, 4> NewGEPIndices;
12562
Chris Lattner1b8eaf52009-01-16 20:08:59 +000012563 // If the source is an array, the code below will not succeed. Check to
12564 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
12565 // constants.
Chris Lattner3914f722009-01-24 01:00:13 +000012566 if (isa<ArrayType>(SrcPTy) || isa<StructType>(SrcPTy)) {
12567 // Index through pointer.
Owen Anderson1d0be152009-08-13 21:58:54 +000012568 Constant *Zero = Constant::getNullValue(Type::getInt32Ty(*IC.getContext()));
Chris Lattner3914f722009-01-24 01:00:13 +000012569 NewGEPIndices.push_back(Zero);
12570
12571 while (1) {
12572 if (const StructType *STy = dyn_cast<StructType>(SrcPTy)) {
Torok Edwin08ffee52009-01-24 17:16:04 +000012573 if (!STy->getNumElements()) /* Struct can be empty {} */
Torok Edwin629e92b2009-01-24 11:30:49 +000012574 break;
Chris Lattner3914f722009-01-24 01:00:13 +000012575 NewGEPIndices.push_back(Zero);
12576 SrcPTy = STy->getElementType(0);
12577 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(SrcPTy)) {
12578 NewGEPIndices.push_back(Zero);
12579 SrcPTy = ATy->getElementType();
12580 } else {
12581 break;
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000012582 }
Chris Lattner3914f722009-01-24 01:00:13 +000012583 }
12584
Owen Andersondebcb012009-07-29 22:17:13 +000012585 SrcTy = PointerType::get(SrcPTy, SrcTy->getAddressSpace());
Chris Lattner3914f722009-01-24 01:00:13 +000012586 }
Chris Lattner1b8eaf52009-01-16 20:08:59 +000012587
12588 if (!SrcPTy->isInteger() && !isa<PointerType>(SrcPTy))
12589 return 0;
12590
Chris Lattner71759c42009-01-16 20:12:52 +000012591 // If the pointers point into different address spaces or if they point to
12592 // values with different sizes, we can't do the transformation.
Dan Gohmance9fe9f2009-07-21 23:21:54 +000012593 if (!IC.getTargetData() ||
12594 SrcTy->getAddressSpace() !=
Chris Lattner71759c42009-01-16 20:12:52 +000012595 cast<PointerType>(CI->getType())->getAddressSpace() ||
Dan Gohmance9fe9f2009-07-21 23:21:54 +000012596 IC.getTargetData()->getTypeSizeInBits(SrcPTy) !=
12597 IC.getTargetData()->getTypeSizeInBits(DestPTy))
Chris Lattner1b8eaf52009-01-16 20:08:59 +000012598 return 0;
12599
12600 // Okay, we are casting from one integer or pointer type to another of
12601 // the same size. Instead of casting the pointer before
12602 // the store, cast the value to be stored.
12603 Value *NewCast;
12604 Value *SIOp0 = SI.getOperand(0);
12605 Instruction::CastOps opcode = Instruction::BitCast;
12606 const Type* CastSrcTy = SIOp0->getType();
12607 const Type* CastDstTy = SrcPTy;
12608 if (isa<PointerType>(CastDstTy)) {
12609 if (CastSrcTy->isInteger())
12610 opcode = Instruction::IntToPtr;
12611 } else if (isa<IntegerType>(CastDstTy)) {
12612 if (isa<PointerType>(SIOp0->getType()))
12613 opcode = Instruction::PtrToInt;
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000012614 }
Chris Lattner3914f722009-01-24 01:00:13 +000012615
12616 // SIOp0 is a pointer to aggregate and this is a store to the first field,
12617 // emit a GEP to index into its first field.
Dan Gohmanf8dbee72009-09-07 23:54:19 +000012618 if (!NewGEPIndices.empty())
12619 CastOp = IC.Builder->CreateInBoundsGEP(CastOp, NewGEPIndices.begin(),
12620 NewGEPIndices.end());
Chris Lattner3914f722009-01-24 01:00:13 +000012621
Chris Lattnerf925cbd2009-08-30 18:50:58 +000012622 NewCast = IC.Builder->CreateCast(opcode, SIOp0, CastDstTy,
12623 SIOp0->getName()+".c");
Chris Lattner1b8eaf52009-01-16 20:08:59 +000012624 return new StoreInst(NewCast, CastOp);
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000012625}
12626
Chris Lattner4aebaee2008-11-27 08:56:30 +000012627/// equivalentAddressValues - Test if A and B will obviously have the same
12628/// value. This includes recognizing that %t0 and %t1 will have the same
12629/// value in code like this:
Dan Gohman0f8b53f2009-03-03 02:55:14 +000012630/// %t0 = getelementptr \@a, 0, 3
Chris Lattner4aebaee2008-11-27 08:56:30 +000012631/// store i32 0, i32* %t0
Dan Gohman0f8b53f2009-03-03 02:55:14 +000012632/// %t1 = getelementptr \@a, 0, 3
Chris Lattner4aebaee2008-11-27 08:56:30 +000012633/// %t2 = load i32* %t1
12634///
12635static bool equivalentAddressValues(Value *A, Value *B) {
12636 // Test if the values are trivially equivalent.
12637 if (A == B) return true;
12638
12639 // Test if the values come form identical arithmetic instructions.
Dan Gohman58cfa3b2009-08-25 22:11:20 +000012640 // This uses isIdenticalToWhenDefined instead of isIdenticalTo because
12641 // its only used to compare two uses within the same basic block, which
12642 // means that they'll always either have the same value or one of them
12643 // will have an undefined value.
Chris Lattner4aebaee2008-11-27 08:56:30 +000012644 if (isa<BinaryOperator>(A) ||
12645 isa<CastInst>(A) ||
12646 isa<PHINode>(A) ||
12647 isa<GetElementPtrInst>(A))
12648 if (Instruction *BI = dyn_cast<Instruction>(B))
Dan Gohman58cfa3b2009-08-25 22:11:20 +000012649 if (cast<Instruction>(A)->isIdenticalToWhenDefined(BI))
Chris Lattner4aebaee2008-11-27 08:56:30 +000012650 return true;
12651
12652 // Otherwise they may not be equivalent.
12653 return false;
12654}
12655
Dale Johannesen4945c652009-03-03 21:26:39 +000012656// If this instruction has two uses, one of which is a llvm.dbg.declare,
12657// return the llvm.dbg.declare.
12658DbgDeclareInst *InstCombiner::hasOneUsePlusDeclare(Value *V) {
12659 if (!V->hasNUses(2))
12660 return 0;
12661 for (Value::use_iterator UI = V->use_begin(), E = V->use_end();
12662 UI != E; ++UI) {
12663 if (DbgDeclareInst *DI = dyn_cast<DbgDeclareInst>(UI))
12664 return DI;
12665 if (isa<BitCastInst>(UI) && UI->hasOneUse()) {
12666 if (DbgDeclareInst *DI = dyn_cast<DbgDeclareInst>(UI->use_begin()))
12667 return DI;
12668 }
12669 }
12670 return 0;
12671}
12672
Chris Lattner2f503e62005-01-31 05:36:43 +000012673Instruction *InstCombiner::visitStoreInst(StoreInst &SI) {
12674 Value *Val = SI.getOperand(0);
12675 Value *Ptr = SI.getOperand(1);
12676
Chris Lattner836692d2007-01-15 06:51:56 +000012677 // If the RHS is an alloca with a single use, zapify the store, making the
12678 // alloca dead.
Dale Johannesen4945c652009-03-03 21:26:39 +000012679 // If the RHS is an alloca with a two uses, the other one being a
12680 // llvm.dbg.declare, zapify the store and the declare, making the
12681 // alloca dead. We must do this to prevent declare's from affecting
12682 // codegen.
12683 if (!SI.isVolatile()) {
12684 if (Ptr->hasOneUse()) {
12685 if (isa<AllocaInst>(Ptr)) {
Chris Lattner836692d2007-01-15 06:51:56 +000012686 EraseInstFromFunction(SI);
12687 ++NumCombined;
12688 return 0;
12689 }
Dale Johannesen4945c652009-03-03 21:26:39 +000012690 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr)) {
12691 if (isa<AllocaInst>(GEP->getOperand(0))) {
12692 if (GEP->getOperand(0)->hasOneUse()) {
12693 EraseInstFromFunction(SI);
12694 ++NumCombined;
12695 return 0;
12696 }
12697 if (DbgDeclareInst *DI = hasOneUsePlusDeclare(GEP->getOperand(0))) {
12698 EraseInstFromFunction(*DI);
12699 EraseInstFromFunction(SI);
12700 ++NumCombined;
12701 return 0;
12702 }
12703 }
12704 }
12705 }
12706 if (DbgDeclareInst *DI = hasOneUsePlusDeclare(Ptr)) {
12707 EraseInstFromFunction(*DI);
12708 EraseInstFromFunction(SI);
12709 ++NumCombined;
12710 return 0;
12711 }
Chris Lattner836692d2007-01-15 06:51:56 +000012712 }
Chris Lattner2f503e62005-01-31 05:36:43 +000012713
Dan Gohman9941f742007-07-20 16:34:21 +000012714 // Attempt to improve the alignment.
Dan Gohmance9fe9f2009-07-21 23:21:54 +000012715 if (TD) {
12716 unsigned KnownAlign =
12717 GetOrEnforceKnownAlignment(Ptr, TD->getPrefTypeAlignment(Val->getType()));
12718 if (KnownAlign >
12719 (SI.getAlignment() == 0 ? TD->getABITypeAlignment(Val->getType()) :
12720 SI.getAlignment()))
12721 SI.setAlignment(KnownAlign);
12722 }
Dan Gohman9941f742007-07-20 16:34:21 +000012723
Dale Johannesenacb51a32009-03-03 01:43:03 +000012724 // Do really simple DSE, to catch cases where there are several consecutive
Chris Lattner9ca96412006-02-08 03:25:32 +000012725 // stores to the same location, separated by a few arithmetic operations. This
12726 // situation often occurs with bitfield accesses.
12727 BasicBlock::iterator BBI = &SI;
12728 for (unsigned ScanInsts = 6; BBI != SI.getParent()->begin() && ScanInsts;
12729 --ScanInsts) {
Dale Johannesen0d6596b2009-03-04 01:20:34 +000012730 --BBI;
Dale Johannesencdb16aa2009-03-04 01:53:05 +000012731 // Don't count debug info directives, lest they affect codegen,
12732 // and we skip pointer-to-pointer bitcasts, which are NOPs.
12733 // It is necessary for correctness to skip those that feed into a
12734 // llvm.dbg.declare, as these are not present when debugging is off.
Dale Johannesen4ded40a2009-03-03 22:36:47 +000012735 if (isa<DbgInfoIntrinsic>(BBI) ||
Dale Johannesencdb16aa2009-03-04 01:53:05 +000012736 (isa<BitCastInst>(BBI) && isa<PointerType>(BBI->getType()))) {
Dale Johannesenacb51a32009-03-03 01:43:03 +000012737 ScanInsts++;
Dale Johannesenacb51a32009-03-03 01:43:03 +000012738 continue;
12739 }
Chris Lattner9ca96412006-02-08 03:25:32 +000012740
12741 if (StoreInst *PrevSI = dyn_cast<StoreInst>(BBI)) {
12742 // Prev store isn't volatile, and stores to the same location?
Chris Lattner4aebaee2008-11-27 08:56:30 +000012743 if (!PrevSI->isVolatile() &&equivalentAddressValues(PrevSI->getOperand(1),
12744 SI.getOperand(1))) {
Chris Lattner9ca96412006-02-08 03:25:32 +000012745 ++NumDeadStore;
12746 ++BBI;
12747 EraseInstFromFunction(*PrevSI);
12748 continue;
12749 }
12750 break;
12751 }
12752
Chris Lattnerb4db97f2006-05-26 19:19:20 +000012753 // If this is a load, we have to stop. However, if the loaded value is from
12754 // the pointer we're loading and is producing the pointer we're storing,
12755 // then *this* store is dead (X = load P; store X -> P).
12756 if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
Dan Gohman2276a7b2008-10-15 23:19:35 +000012757 if (LI == Val && equivalentAddressValues(LI->getOperand(0), Ptr) &&
12758 !SI.isVolatile()) {
Chris Lattnerb4db97f2006-05-26 19:19:20 +000012759 EraseInstFromFunction(SI);
12760 ++NumCombined;
12761 return 0;
12762 }
12763 // Otherwise, this is a load from some other location. Stores before it
12764 // may not be dead.
12765 break;
12766 }
12767
Chris Lattner9ca96412006-02-08 03:25:32 +000012768 // Don't skip over loads or things that can modify memory.
Chris Lattner0ef546e2008-05-08 17:20:30 +000012769 if (BBI->mayWriteToMemory() || BBI->mayReadFromMemory())
Chris Lattner9ca96412006-02-08 03:25:32 +000012770 break;
12771 }
12772
12773
12774 if (SI.isVolatile()) return 0; // Don't hack volatile stores.
Chris Lattner2f503e62005-01-31 05:36:43 +000012775
12776 // store X, null -> turns into 'unreachable' in SimplifyCFG
Chris Lattner8a67ac52009-08-30 20:06:40 +000012777 if (isa<ConstantPointerNull>(Ptr) && SI.getPointerAddressSpace() == 0) {
Chris Lattner2f503e62005-01-31 05:36:43 +000012778 if (!isa<UndefValue>(Val)) {
Owen Anderson9e9a0d52009-07-30 23:03:37 +000012779 SI.setOperand(0, UndefValue::get(Val->getType()));
Chris Lattner2f503e62005-01-31 05:36:43 +000012780 if (Instruction *U = dyn_cast<Instruction>(Val))
Chris Lattner7a1e9242009-08-30 06:13:40 +000012781 Worklist.Add(U); // Dropped a use.
Chris Lattner2f503e62005-01-31 05:36:43 +000012782 ++NumCombined;
12783 }
12784 return 0; // Do not modify these!
12785 }
12786
12787 // store undef, Ptr -> noop
12788 if (isa<UndefValue>(Val)) {
Chris Lattner9ca96412006-02-08 03:25:32 +000012789 EraseInstFromFunction(SI);
Chris Lattner2f503e62005-01-31 05:36:43 +000012790 ++NumCombined;
12791 return 0;
12792 }
12793
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000012794 // If the pointer destination is a cast, see if we can fold the cast into the
12795 // source instead.
Reid Spencer3ed469c2006-11-02 20:25:50 +000012796 if (isa<CastInst>(Ptr))
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000012797 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
12798 return Res;
12799 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr))
Reid Spencer3da59db2006-11-27 01:05:10 +000012800 if (CE->isCast())
Chris Lattnerfcfe33a2005-01-31 05:51:45 +000012801 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
12802 return Res;
12803
Chris Lattner408902b2005-09-12 23:23:25 +000012804
Dale Johannesen4084c4e2009-03-05 02:06:48 +000012805 // If this store is the last instruction in the basic block (possibly
12806 // excepting debug info instructions and the pointer bitcasts that feed
12807 // into them), and if the block ends with an unconditional branch, try
12808 // to move it to the successor block.
12809 BBI = &SI;
12810 do {
12811 ++BBI;
12812 } while (isa<DbgInfoIntrinsic>(BBI) ||
12813 (isa<BitCastInst>(BBI) && isa<PointerType>(BBI->getType())));
Chris Lattner408902b2005-09-12 23:23:25 +000012814 if (BranchInst *BI = dyn_cast<BranchInst>(BBI))
Chris Lattner3284d1f2007-04-15 00:07:55 +000012815 if (BI->isUnconditional())
12816 if (SimplifyStoreAtEndOfBlock(SI))
12817 return 0; // xform done!
Chris Lattner408902b2005-09-12 23:23:25 +000012818
Chris Lattner2f503e62005-01-31 05:36:43 +000012819 return 0;
12820}
12821
Chris Lattner3284d1f2007-04-15 00:07:55 +000012822/// SimplifyStoreAtEndOfBlock - Turn things like:
12823/// if () { *P = v1; } else { *P = v2 }
12824/// into a phi node with a store in the successor.
12825///
Chris Lattner31755a02007-04-15 01:02:18 +000012826/// Simplify things like:
12827/// *P = v1; if () { *P = v2; }
12828/// into a phi node with a store in the successor.
12829///
Chris Lattner3284d1f2007-04-15 00:07:55 +000012830bool InstCombiner::SimplifyStoreAtEndOfBlock(StoreInst &SI) {
12831 BasicBlock *StoreBB = SI.getParent();
12832
12833 // Check to see if the successor block has exactly two incoming edges. If
12834 // so, see if the other predecessor contains a store to the same location.
12835 // if so, insert a PHI node (if needed) and move the stores down.
Chris Lattner31755a02007-04-15 01:02:18 +000012836 BasicBlock *DestBB = StoreBB->getTerminator()->getSuccessor(0);
Chris Lattner3284d1f2007-04-15 00:07:55 +000012837
12838 // Determine whether Dest has exactly two predecessors and, if so, compute
12839 // the other predecessor.
Chris Lattner31755a02007-04-15 01:02:18 +000012840 pred_iterator PI = pred_begin(DestBB);
12841 BasicBlock *OtherBB = 0;
Chris Lattner3284d1f2007-04-15 00:07:55 +000012842 if (*PI != StoreBB)
Chris Lattner31755a02007-04-15 01:02:18 +000012843 OtherBB = *PI;
Chris Lattner3284d1f2007-04-15 00:07:55 +000012844 ++PI;
Chris Lattner31755a02007-04-15 01:02:18 +000012845 if (PI == pred_end(DestBB))
Chris Lattner3284d1f2007-04-15 00:07:55 +000012846 return false;
12847
12848 if (*PI != StoreBB) {
Chris Lattner31755a02007-04-15 01:02:18 +000012849 if (OtherBB)
Chris Lattner3284d1f2007-04-15 00:07:55 +000012850 return false;
Chris Lattner31755a02007-04-15 01:02:18 +000012851 OtherBB = *PI;
Chris Lattner3284d1f2007-04-15 00:07:55 +000012852 }
Chris Lattner31755a02007-04-15 01:02:18 +000012853 if (++PI != pred_end(DestBB))
Chris Lattner3284d1f2007-04-15 00:07:55 +000012854 return false;
Eli Friedman66fe80a2008-06-13 21:17:49 +000012855
12856 // Bail out if all the relevant blocks aren't distinct (this can happen,
12857 // for example, if SI is in an infinite loop)
12858 if (StoreBB == DestBB || OtherBB == DestBB)
12859 return false;
12860
Chris Lattner31755a02007-04-15 01:02:18 +000012861 // Verify that the other block ends in a branch and is not otherwise empty.
12862 BasicBlock::iterator BBI = OtherBB->getTerminator();
Chris Lattner3284d1f2007-04-15 00:07:55 +000012863 BranchInst *OtherBr = dyn_cast<BranchInst>(BBI);
Chris Lattner31755a02007-04-15 01:02:18 +000012864 if (!OtherBr || BBI == OtherBB->begin())
Chris Lattner3284d1f2007-04-15 00:07:55 +000012865 return false;
12866
Chris Lattner31755a02007-04-15 01:02:18 +000012867 // If the other block ends in an unconditional branch, check for the 'if then
12868 // else' case. there is an instruction before the branch.
12869 StoreInst *OtherStore = 0;
12870 if (OtherBr->isUnconditional()) {
Chris Lattner31755a02007-04-15 01:02:18 +000012871 --BBI;
Dale Johannesen4084c4e2009-03-05 02:06:48 +000012872 // Skip over debugging info.
12873 while (isa<DbgInfoIntrinsic>(BBI) ||
12874 (isa<BitCastInst>(BBI) && isa<PointerType>(BBI->getType()))) {
12875 if (BBI==OtherBB->begin())
12876 return false;
12877 --BBI;
12878 }
Chris Lattner7ebbabf2009-11-02 02:06:37 +000012879 // If this isn't a store, isn't a store to the same location, or if the
12880 // alignments differ, bail out.
Chris Lattner31755a02007-04-15 01:02:18 +000012881 OtherStore = dyn_cast<StoreInst>(BBI);
Chris Lattner7ebbabf2009-11-02 02:06:37 +000012882 if (!OtherStore || OtherStore->getOperand(1) != SI.getOperand(1) ||
12883 OtherStore->getAlignment() != SI.getAlignment())
Chris Lattner31755a02007-04-15 01:02:18 +000012884 return false;
12885 } else {
Chris Lattnerd717c182007-05-05 22:32:24 +000012886 // Otherwise, the other block ended with a conditional branch. If one of the
Chris Lattner31755a02007-04-15 01:02:18 +000012887 // destinations is StoreBB, then we have the if/then case.
12888 if (OtherBr->getSuccessor(0) != StoreBB &&
12889 OtherBr->getSuccessor(1) != StoreBB)
12890 return false;
12891
12892 // Okay, we know that OtherBr now goes to Dest and StoreBB, so this is an
Chris Lattnerd717c182007-05-05 22:32:24 +000012893 // if/then triangle. See if there is a store to the same ptr as SI that
12894 // lives in OtherBB.
Chris Lattner31755a02007-04-15 01:02:18 +000012895 for (;; --BBI) {
12896 // Check to see if we find the matching store.
12897 if ((OtherStore = dyn_cast<StoreInst>(BBI))) {
Chris Lattner7ebbabf2009-11-02 02:06:37 +000012898 if (OtherStore->getOperand(1) != SI.getOperand(1) ||
12899 OtherStore->getAlignment() != SI.getAlignment())
Chris Lattner31755a02007-04-15 01:02:18 +000012900 return false;
12901 break;
12902 }
Eli Friedman6903a242008-06-13 22:02:12 +000012903 // If we find something that may be using or overwriting the stored
12904 // value, or if we run out of instructions, we can't do the xform.
12905 if (BBI->mayReadFromMemory() || BBI->mayWriteToMemory() ||
Chris Lattner31755a02007-04-15 01:02:18 +000012906 BBI == OtherBB->begin())
12907 return false;
12908 }
12909
12910 // In order to eliminate the store in OtherBr, we have to
Eli Friedman6903a242008-06-13 22:02:12 +000012911 // make sure nothing reads or overwrites the stored value in
12912 // StoreBB.
Chris Lattner31755a02007-04-15 01:02:18 +000012913 for (BasicBlock::iterator I = StoreBB->begin(); &*I != &SI; ++I) {
12914 // FIXME: This should really be AA driven.
Eli Friedman6903a242008-06-13 22:02:12 +000012915 if (I->mayReadFromMemory() || I->mayWriteToMemory())
Chris Lattner31755a02007-04-15 01:02:18 +000012916 return false;
12917 }
12918 }
Chris Lattner3284d1f2007-04-15 00:07:55 +000012919
Chris Lattner31755a02007-04-15 01:02:18 +000012920 // Insert a PHI node now if we need it.
Chris Lattner3284d1f2007-04-15 00:07:55 +000012921 Value *MergedVal = OtherStore->getOperand(0);
12922 if (MergedVal != SI.getOperand(0)) {
Gabor Greif051a9502008-04-06 20:25:17 +000012923 PHINode *PN = PHINode::Create(MergedVal->getType(), "storemerge");
Chris Lattner3284d1f2007-04-15 00:07:55 +000012924 PN->reserveOperandSpace(2);
12925 PN->addIncoming(SI.getOperand(0), SI.getParent());
Chris Lattner31755a02007-04-15 01:02:18 +000012926 PN->addIncoming(OtherStore->getOperand(0), OtherBB);
12927 MergedVal = InsertNewInstBefore(PN, DestBB->front());
Chris Lattner3284d1f2007-04-15 00:07:55 +000012928 }
12929
12930 // Advance to a place where it is safe to insert the new store and
12931 // insert it.
Dan Gohman02dea8b2008-05-23 21:05:58 +000012932 BBI = DestBB->getFirstNonPHI();
Chris Lattner3284d1f2007-04-15 00:07:55 +000012933 InsertNewInstBefore(new StoreInst(MergedVal, SI.getOperand(1),
Chris Lattner7ebbabf2009-11-02 02:06:37 +000012934 OtherStore->isVolatile(),
12935 SI.getAlignment()), *BBI);
Chris Lattner3284d1f2007-04-15 00:07:55 +000012936
12937 // Nuke the old stores.
12938 EraseInstFromFunction(SI);
12939 EraseInstFromFunction(*OtherStore);
12940 ++NumCombined;
12941 return true;
12942}
12943
Chris Lattner2f503e62005-01-31 05:36:43 +000012944
Chris Lattnerc4d10eb2003-06-04 04:46:00 +000012945Instruction *InstCombiner::visitBranchInst(BranchInst &BI) {
12946 // Change br (not X), label True, label False to: br X, label False, True
Reid Spencer4b828e62005-06-18 17:37:34 +000012947 Value *X = 0;
Chris Lattneracd1f0f2004-07-30 07:50:03 +000012948 BasicBlock *TrueDest;
12949 BasicBlock *FalseDest;
Dan Gohman4ae51262009-08-12 16:23:25 +000012950 if (match(&BI, m_Br(m_Not(m_Value(X)), TrueDest, FalseDest)) &&
Chris Lattneracd1f0f2004-07-30 07:50:03 +000012951 !isa<Constant>(X)) {
12952 // Swap Destinations and condition...
12953 BI.setCondition(X);
12954 BI.setSuccessor(0, FalseDest);
12955 BI.setSuccessor(1, TrueDest);
12956 return &BI;
12957 }
12958
Reid Spencere4d87aa2006-12-23 06:05:41 +000012959 // Cannonicalize fcmp_one -> fcmp_oeq
12960 FCmpInst::Predicate FPred; Value *Y;
12961 if (match(&BI, m_Br(m_FCmp(FPred, m_Value(X), m_Value(Y)),
Chris Lattner7a1e9242009-08-30 06:13:40 +000012962 TrueDest, FalseDest)) &&
12963 BI.getCondition()->hasOneUse())
12964 if (FPred == FCmpInst::FCMP_ONE || FPred == FCmpInst::FCMP_OLE ||
12965 FPred == FCmpInst::FCMP_OGE) {
12966 FCmpInst *Cond = cast<FCmpInst>(BI.getCondition());
12967 Cond->setPredicate(FCmpInst::getInversePredicate(FPred));
12968
12969 // Swap Destinations and condition.
Reid Spencere4d87aa2006-12-23 06:05:41 +000012970 BI.setSuccessor(0, FalseDest);
12971 BI.setSuccessor(1, TrueDest);
Chris Lattner7a1e9242009-08-30 06:13:40 +000012972 Worklist.Add(Cond);
Reid Spencere4d87aa2006-12-23 06:05:41 +000012973 return &BI;
12974 }
12975
12976 // Cannonicalize icmp_ne -> icmp_eq
12977 ICmpInst::Predicate IPred;
12978 if (match(&BI, m_Br(m_ICmp(IPred, m_Value(X), m_Value(Y)),
Chris Lattner7a1e9242009-08-30 06:13:40 +000012979 TrueDest, FalseDest)) &&
12980 BI.getCondition()->hasOneUse())
12981 if (IPred == ICmpInst::ICMP_NE || IPred == ICmpInst::ICMP_ULE ||
12982 IPred == ICmpInst::ICMP_SLE || IPred == ICmpInst::ICMP_UGE ||
12983 IPred == ICmpInst::ICMP_SGE) {
12984 ICmpInst *Cond = cast<ICmpInst>(BI.getCondition());
12985 Cond->setPredicate(ICmpInst::getInversePredicate(IPred));
12986 // Swap Destinations and condition.
Chris Lattner40f5d702003-06-04 05:10:11 +000012987 BI.setSuccessor(0, FalseDest);
12988 BI.setSuccessor(1, TrueDest);
Chris Lattner7a1e9242009-08-30 06:13:40 +000012989 Worklist.Add(Cond);
Chris Lattner40f5d702003-06-04 05:10:11 +000012990 return &BI;
12991 }
Misha Brukmanfd939082005-04-21 23:48:37 +000012992
Chris Lattnerc4d10eb2003-06-04 04:46:00 +000012993 return 0;
12994}
Chris Lattner0864acf2002-11-04 16:18:53 +000012995
Chris Lattner46238a62004-07-03 00:26:11 +000012996Instruction *InstCombiner::visitSwitchInst(SwitchInst &SI) {
12997 Value *Cond = SI.getCondition();
12998 if (Instruction *I = dyn_cast<Instruction>(Cond)) {
12999 if (I->getOpcode() == Instruction::Add)
13000 if (ConstantInt *AddRHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
13001 // change 'switch (X+4) case 1:' into 'switch (X) case -3'
13002 for (unsigned i = 2, e = SI.getNumOperands(); i != e; i += 2)
Owen Andersond672ecb2009-07-03 00:17:18 +000013003 SI.setOperand(i,
Owen Andersonbaf3c402009-07-29 18:55:55 +000013004 ConstantExpr::getSub(cast<Constant>(SI.getOperand(i)),
Chris Lattner46238a62004-07-03 00:26:11 +000013005 AddRHS));
13006 SI.setOperand(0, I->getOperand(0));
Chris Lattner7a1e9242009-08-30 06:13:40 +000013007 Worklist.Add(I);
Chris Lattner46238a62004-07-03 00:26:11 +000013008 return &SI;
13009 }
13010 }
13011 return 0;
13012}
13013
Matthijs Kooijmana9012ec2008-06-11 14:05:05 +000013014Instruction *InstCombiner::visitExtractValueInst(ExtractValueInst &EV) {
Matthijs Kooijman780ae5e2008-07-16 12:55:45 +000013015 Value *Agg = EV.getAggregateOperand();
Matthijs Kooijmana9012ec2008-06-11 14:05:05 +000013016
Matthijs Kooijman780ae5e2008-07-16 12:55:45 +000013017 if (!EV.hasIndices())
13018 return ReplaceInstUsesWith(EV, Agg);
13019
13020 if (Constant *C = dyn_cast<Constant>(Agg)) {
13021 if (isa<UndefValue>(C))
Owen Anderson9e9a0d52009-07-30 23:03:37 +000013022 return ReplaceInstUsesWith(EV, UndefValue::get(EV.getType()));
Matthijs Kooijman780ae5e2008-07-16 12:55:45 +000013023
13024 if (isa<ConstantAggregateZero>(C))
Owen Andersona7235ea2009-07-31 20:28:14 +000013025 return ReplaceInstUsesWith(EV, Constant::getNullValue(EV.getType()));
Matthijs Kooijman780ae5e2008-07-16 12:55:45 +000013026
13027 if (isa<ConstantArray>(C) || isa<ConstantStruct>(C)) {
13028 // Extract the element indexed by the first index out of the constant
13029 Value *V = C->getOperand(*EV.idx_begin());
13030 if (EV.getNumIndices() > 1)
13031 // Extract the remaining indices out of the constant indexed by the
13032 // first index
13033 return ExtractValueInst::Create(V, EV.idx_begin() + 1, EV.idx_end());
13034 else
13035 return ReplaceInstUsesWith(EV, V);
13036 }
13037 return 0; // Can't handle other constants
13038 }
13039 if (InsertValueInst *IV = dyn_cast<InsertValueInst>(Agg)) {
13040 // We're extracting from an insertvalue instruction, compare the indices
13041 const unsigned *exti, *exte, *insi, *inse;
13042 for (exti = EV.idx_begin(), insi = IV->idx_begin(),
13043 exte = EV.idx_end(), inse = IV->idx_end();
13044 exti != exte && insi != inse;
13045 ++exti, ++insi) {
13046 if (*insi != *exti)
13047 // The insert and extract both reference distinctly different elements.
13048 // This means the extract is not influenced by the insert, and we can
13049 // replace the aggregate operand of the extract with the aggregate
13050 // operand of the insert. i.e., replace
13051 // %I = insertvalue { i32, { i32 } } %A, { i32 } { i32 42 }, 1
13052 // %E = extractvalue { i32, { i32 } } %I, 0
13053 // with
13054 // %E = extractvalue { i32, { i32 } } %A, 0
13055 return ExtractValueInst::Create(IV->getAggregateOperand(),
13056 EV.idx_begin(), EV.idx_end());
13057 }
13058 if (exti == exte && insi == inse)
13059 // Both iterators are at the end: Index lists are identical. Replace
13060 // %B = insertvalue { i32, { i32 } } %A, i32 42, 1, 0
13061 // %C = extractvalue { i32, { i32 } } %B, 1, 0
13062 // with "i32 42"
13063 return ReplaceInstUsesWith(EV, IV->getInsertedValueOperand());
13064 if (exti == exte) {
13065 // The extract list is a prefix of the insert list. i.e. replace
13066 // %I = insertvalue { i32, { i32 } } %A, i32 42, 1, 0
13067 // %E = extractvalue { i32, { i32 } } %I, 1
13068 // with
13069 // %X = extractvalue { i32, { i32 } } %A, 1
13070 // %E = insertvalue { i32 } %X, i32 42, 0
13071 // by switching the order of the insert and extract (though the
13072 // insertvalue should be left in, since it may have other uses).
Chris Lattnerf925cbd2009-08-30 18:50:58 +000013073 Value *NewEV = Builder->CreateExtractValue(IV->getAggregateOperand(),
13074 EV.idx_begin(), EV.idx_end());
Matthijs Kooijman780ae5e2008-07-16 12:55:45 +000013075 return InsertValueInst::Create(NewEV, IV->getInsertedValueOperand(),
13076 insi, inse);
13077 }
13078 if (insi == inse)
13079 // The insert list is a prefix of the extract list
13080 // We can simply remove the common indices from the extract and make it
13081 // operate on the inserted value instead of the insertvalue result.
13082 // i.e., replace
13083 // %I = insertvalue { i32, { i32 } } %A, { i32 } { i32 42 }, 1
13084 // %E = extractvalue { i32, { i32 } } %I, 1, 0
13085 // with
13086 // %E extractvalue { i32 } { i32 42 }, 0
13087 return ExtractValueInst::Create(IV->getInsertedValueOperand(),
13088 exti, exte);
13089 }
Chris Lattner7e606e22009-11-09 07:07:56 +000013090 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(Agg)) {
13091 // We're extracting from an intrinsic, see if we're the only user, which
13092 // allows us to simplify multiple result intrinsics to simpler things that
13093 // just get one value..
13094 if (II->hasOneUse()) {
13095 // Check if we're grabbing the overflow bit or the result of a 'with
13096 // overflow' intrinsic. If it's the latter we can remove the intrinsic
13097 // and replace it with a traditional binary instruction.
13098 switch (II->getIntrinsicID()) {
13099 case Intrinsic::uadd_with_overflow:
13100 case Intrinsic::sadd_with_overflow:
13101 if (*EV.idx_begin() == 0) { // Normal result.
13102 Value *LHS = II->getOperand(1), *RHS = II->getOperand(2);
13103 II->replaceAllUsesWith(UndefValue::get(II->getType()));
13104 EraseInstFromFunction(*II);
13105 return BinaryOperator::CreateAdd(LHS, RHS);
13106 }
13107 break;
13108 case Intrinsic::usub_with_overflow:
13109 case Intrinsic::ssub_with_overflow:
13110 if (*EV.idx_begin() == 0) { // Normal result.
13111 Value *LHS = II->getOperand(1), *RHS = II->getOperand(2);
13112 II->replaceAllUsesWith(UndefValue::get(II->getType()));
13113 EraseInstFromFunction(*II);
13114 return BinaryOperator::CreateSub(LHS, RHS);
13115 }
13116 break;
13117 case Intrinsic::umul_with_overflow:
13118 case Intrinsic::smul_with_overflow:
13119 if (*EV.idx_begin() == 0) { // Normal result.
13120 Value *LHS = II->getOperand(1), *RHS = II->getOperand(2);
13121 II->replaceAllUsesWith(UndefValue::get(II->getType()));
13122 EraseInstFromFunction(*II);
13123 return BinaryOperator::CreateMul(LHS, RHS);
13124 }
13125 break;
13126 default:
13127 break;
13128 }
13129 }
13130 }
Matthijs Kooijman780ae5e2008-07-16 12:55:45 +000013131 // Can't simplify extracts from other values. Note that nested extracts are
13132 // already simplified implicitely by the above (extract ( extract (insert) )
13133 // will be translated into extract ( insert ( extract ) ) first and then just
13134 // the value inserted, if appropriate).
Matthijs Kooijmana9012ec2008-06-11 14:05:05 +000013135 return 0;
13136}
13137
Chris Lattner220b0cf2006-03-05 00:22:33 +000013138/// CheapToScalarize - Return true if the value is cheaper to scalarize than it
13139/// is to leave as a vector operation.
13140static bool CheapToScalarize(Value *V, bool isConstant) {
13141 if (isa<ConstantAggregateZero>(V))
13142 return true;
Reid Spencer9d6565a2007-02-15 02:26:10 +000013143 if (ConstantVector *C = dyn_cast<ConstantVector>(V)) {
Chris Lattner220b0cf2006-03-05 00:22:33 +000013144 if (isConstant) return true;
13145 // If all elts are the same, we can extract.
13146 Constant *Op0 = C->getOperand(0);
13147 for (unsigned i = 1; i < C->getNumOperands(); ++i)
13148 if (C->getOperand(i) != Op0)
13149 return false;
13150 return true;
13151 }
13152 Instruction *I = dyn_cast<Instruction>(V);
13153 if (!I) return false;
13154
13155 // Insert element gets simplified to the inserted element or is deleted if
13156 // this is constant idx extract element and its a constant idx insertelt.
13157 if (I->getOpcode() == Instruction::InsertElement && isConstant &&
13158 isa<ConstantInt>(I->getOperand(2)))
13159 return true;
13160 if (I->getOpcode() == Instruction::Load && I->hasOneUse())
13161 return true;
13162 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I))
13163 if (BO->hasOneUse() &&
13164 (CheapToScalarize(BO->getOperand(0), isConstant) ||
13165 CheapToScalarize(BO->getOperand(1), isConstant)))
13166 return true;
Reid Spencere4d87aa2006-12-23 06:05:41 +000013167 if (CmpInst *CI = dyn_cast<CmpInst>(I))
13168 if (CI->hasOneUse() &&
13169 (CheapToScalarize(CI->getOperand(0), isConstant) ||
13170 CheapToScalarize(CI->getOperand(1), isConstant)))
13171 return true;
Chris Lattner220b0cf2006-03-05 00:22:33 +000013172
13173 return false;
13174}
13175
Chris Lattnerd2b7cec2007-02-14 05:52:17 +000013176/// Read and decode a shufflevector mask.
13177///
13178/// It turns undef elements into values that are larger than the number of
13179/// elements in the input.
Chris Lattner863bcff2006-05-25 23:48:38 +000013180static std::vector<unsigned> getShuffleMask(const ShuffleVectorInst *SVI) {
13181 unsigned NElts = SVI->getType()->getNumElements();
13182 if (isa<ConstantAggregateZero>(SVI->getOperand(2)))
13183 return std::vector<unsigned>(NElts, 0);
13184 if (isa<UndefValue>(SVI->getOperand(2)))
13185 return std::vector<unsigned>(NElts, 2*NElts);
13186
13187 std::vector<unsigned> Result;
Reid Spencer9d6565a2007-02-15 02:26:10 +000013188 const ConstantVector *CP = cast<ConstantVector>(SVI->getOperand(2));
Gabor Greif177dd3f2008-06-12 21:37:33 +000013189 for (User::const_op_iterator i = CP->op_begin(), e = CP->op_end(); i!=e; ++i)
13190 if (isa<UndefValue>(*i))
Chris Lattner863bcff2006-05-25 23:48:38 +000013191 Result.push_back(NElts*2); // undef -> 8
13192 else
Gabor Greif177dd3f2008-06-12 21:37:33 +000013193 Result.push_back(cast<ConstantInt>(*i)->getZExtValue());
Chris Lattner863bcff2006-05-25 23:48:38 +000013194 return Result;
13195}
13196
Chris Lattner6e6b0da2006-03-31 23:01:56 +000013197/// FindScalarElement - Given a vector and an element number, see if the scalar
13198/// value is already around as a register, for example if it were inserted then
13199/// extracted from the vector.
Owen Andersond672ecb2009-07-03 00:17:18 +000013200static Value *FindScalarElement(Value *V, unsigned EltNo,
Owen Anderson07cf79e2009-07-06 23:00:19 +000013201 LLVMContext *Context) {
Reid Spencer9d6565a2007-02-15 02:26:10 +000013202 assert(isa<VectorType>(V->getType()) && "Not looking at a vector?");
13203 const VectorType *PTy = cast<VectorType>(V->getType());
Chris Lattner389a6f52006-04-10 23:06:36 +000013204 unsigned Width = PTy->getNumElements();
13205 if (EltNo >= Width) // Out of range access.
Owen Anderson9e9a0d52009-07-30 23:03:37 +000013206 return UndefValue::get(PTy->getElementType());
Chris Lattner6e6b0da2006-03-31 23:01:56 +000013207
13208 if (isa<UndefValue>(V))
Owen Anderson9e9a0d52009-07-30 23:03:37 +000013209 return UndefValue::get(PTy->getElementType());
Chris Lattner6e6b0da2006-03-31 23:01:56 +000013210 else if (isa<ConstantAggregateZero>(V))
Owen Andersona7235ea2009-07-31 20:28:14 +000013211 return Constant::getNullValue(PTy->getElementType());
Reid Spencer9d6565a2007-02-15 02:26:10 +000013212 else if (ConstantVector *CP = dyn_cast<ConstantVector>(V))
Chris Lattner6e6b0da2006-03-31 23:01:56 +000013213 return CP->getOperand(EltNo);
13214 else if (InsertElementInst *III = dyn_cast<InsertElementInst>(V)) {
13215 // If this is an insert to a variable element, we don't know what it is.
Reid Spencerb83eb642006-10-20 07:07:24 +000013216 if (!isa<ConstantInt>(III->getOperand(2)))
13217 return 0;
13218 unsigned IIElt = cast<ConstantInt>(III->getOperand(2))->getZExtValue();
Chris Lattner6e6b0da2006-03-31 23:01:56 +000013219
13220 // If this is an insert to the element we are looking for, return the
13221 // inserted value.
Reid Spencerb83eb642006-10-20 07:07:24 +000013222 if (EltNo == IIElt)
13223 return III->getOperand(1);
Chris Lattner6e6b0da2006-03-31 23:01:56 +000013224
13225 // Otherwise, the insertelement doesn't modify the value, recurse on its
13226 // vector input.
Owen Andersond672ecb2009-07-03 00:17:18 +000013227 return FindScalarElement(III->getOperand(0), EltNo, Context);
Chris Lattner389a6f52006-04-10 23:06:36 +000013228 } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(V)) {
Mon P Wangaeb06d22008-11-10 04:46:22 +000013229 unsigned LHSWidth =
13230 cast<VectorType>(SVI->getOperand(0)->getType())->getNumElements();
Chris Lattner863bcff2006-05-25 23:48:38 +000013231 unsigned InEl = getShuffleMask(SVI)[EltNo];
Mon P Wangaeb06d22008-11-10 04:46:22 +000013232 if (InEl < LHSWidth)
Owen Andersond672ecb2009-07-03 00:17:18 +000013233 return FindScalarElement(SVI->getOperand(0), InEl, Context);
Mon P Wangaeb06d22008-11-10 04:46:22 +000013234 else if (InEl < LHSWidth*2)
Owen Andersond672ecb2009-07-03 00:17:18 +000013235 return FindScalarElement(SVI->getOperand(1), InEl - LHSWidth, Context);
Chris Lattner863bcff2006-05-25 23:48:38 +000013236 else
Owen Anderson9e9a0d52009-07-30 23:03:37 +000013237 return UndefValue::get(PTy->getElementType());
Chris Lattner6e6b0da2006-03-31 23:01:56 +000013238 }
13239
13240 // Otherwise, we don't know.
13241 return 0;
13242}
13243
Robert Bocchino1d7456d2006-01-13 22:48:06 +000013244Instruction *InstCombiner::visitExtractElementInst(ExtractElementInst &EI) {
Dan Gohman07a96762007-07-16 14:29:03 +000013245 // If vector val is undef, replace extract with scalar undef.
Chris Lattner1f13c882006-03-31 18:25:14 +000013246 if (isa<UndefValue>(EI.getOperand(0)))
Owen Anderson9e9a0d52009-07-30 23:03:37 +000013247 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
Chris Lattner1f13c882006-03-31 18:25:14 +000013248
Dan Gohman07a96762007-07-16 14:29:03 +000013249 // If vector val is constant 0, replace extract with scalar 0.
Chris Lattner1f13c882006-03-31 18:25:14 +000013250 if (isa<ConstantAggregateZero>(EI.getOperand(0)))
Owen Andersona7235ea2009-07-31 20:28:14 +000013251 return ReplaceInstUsesWith(EI, Constant::getNullValue(EI.getType()));
Chris Lattner1f13c882006-03-31 18:25:14 +000013252
Reid Spencer9d6565a2007-02-15 02:26:10 +000013253 if (ConstantVector *C = dyn_cast<ConstantVector>(EI.getOperand(0))) {
Matthijs Kooijmanb4d6a5a2008-06-11 09:00:12 +000013254 // If vector val is constant with all elements the same, replace EI with
13255 // that element. When the elements are not identical, we cannot replace yet
13256 // (we do that below, but only when the index is constant).
Chris Lattner220b0cf2006-03-05 00:22:33 +000013257 Constant *op0 = C->getOperand(0);
Chris Lattner4cb81bd2009-09-08 03:44:51 +000013258 for (unsigned i = 1; i != C->getNumOperands(); ++i)
Chris Lattner220b0cf2006-03-05 00:22:33 +000013259 if (C->getOperand(i) != op0) {
13260 op0 = 0;
13261 break;
13262 }
13263 if (op0)
13264 return ReplaceInstUsesWith(EI, op0);
Robert Bocchino1d7456d2006-01-13 22:48:06 +000013265 }
Eli Friedman76e7ba82009-07-18 19:04:16 +000013266
Chris Lattner6e6b0da2006-03-31 23:01:56 +000013267 // If extracting a specified index from the vector, see if we can recursively
13268 // find a previously computed scalar that was inserted into the vector.
Reid Spencerb83eb642006-10-20 07:07:24 +000013269 if (ConstantInt *IdxC = dyn_cast<ConstantInt>(EI.getOperand(1))) {
Chris Lattner85464092007-04-09 01:37:55 +000013270 unsigned IndexVal = IdxC->getZExtValue();
Chris Lattner4cb81bd2009-09-08 03:44:51 +000013271 unsigned VectorWidth = EI.getVectorOperandType()->getNumElements();
Chris Lattner85464092007-04-09 01:37:55 +000013272
13273 // If this is extracting an invalid index, turn this into undef, to avoid
13274 // crashing the code below.
13275 if (IndexVal >= VectorWidth)
Owen Anderson9e9a0d52009-07-30 23:03:37 +000013276 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
Chris Lattner85464092007-04-09 01:37:55 +000013277
Chris Lattner867b99f2006-10-05 06:55:50 +000013278 // This instruction only demands the single element from the input vector.
13279 // If the input vector has a single use, simplify it based on this use
13280 // property.
Eli Friedman76e7ba82009-07-18 19:04:16 +000013281 if (EI.getOperand(0)->hasOneUse() && VectorWidth != 1) {
Evan Cheng388df622009-02-03 10:05:09 +000013282 APInt UndefElts(VectorWidth, 0);
13283 APInt DemandedMask(VectorWidth, 1 << IndexVal);
Chris Lattner867b99f2006-10-05 06:55:50 +000013284 if (Value *V = SimplifyDemandedVectorElts(EI.getOperand(0),
Evan Cheng388df622009-02-03 10:05:09 +000013285 DemandedMask, UndefElts)) {
Chris Lattner867b99f2006-10-05 06:55:50 +000013286 EI.setOperand(0, V);
13287 return &EI;
13288 }
13289 }
13290
Owen Andersond672ecb2009-07-03 00:17:18 +000013291 if (Value *Elt = FindScalarElement(EI.getOperand(0), IndexVal, Context))
Chris Lattner6e6b0da2006-03-31 23:01:56 +000013292 return ReplaceInstUsesWith(EI, Elt);
Chris Lattnerb7300fa2007-04-14 23:02:14 +000013293
13294 // If the this extractelement is directly using a bitcast from a vector of
13295 // the same number of elements, see if we can find the source element from
13296 // it. In this case, we will end up needing to bitcast the scalars.
13297 if (BitCastInst *BCI = dyn_cast<BitCastInst>(EI.getOperand(0))) {
13298 if (const VectorType *VT =
13299 dyn_cast<VectorType>(BCI->getOperand(0)->getType()))
13300 if (VT->getNumElements() == VectorWidth)
Owen Andersond672ecb2009-07-03 00:17:18 +000013301 if (Value *Elt = FindScalarElement(BCI->getOperand(0),
13302 IndexVal, Context))
Chris Lattnerb7300fa2007-04-14 23:02:14 +000013303 return new BitCastInst(Elt, EI.getType());
13304 }
Chris Lattner389a6f52006-04-10 23:06:36 +000013305 }
Chris Lattner6e6b0da2006-03-31 23:01:56 +000013306
Chris Lattner73fa49d2006-05-25 22:53:38 +000013307 if (Instruction *I = dyn_cast<Instruction>(EI.getOperand(0))) {
Chris Lattner275a6d62009-09-08 18:48:01 +000013308 // Push extractelement into predecessor operation if legal and
13309 // profitable to do so
13310 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) {
13311 if (I->hasOneUse() &&
13312 CheapToScalarize(BO, isa<ConstantInt>(EI.getOperand(1)))) {
13313 Value *newEI0 =
13314 Builder->CreateExtractElement(BO->getOperand(0), EI.getOperand(1),
13315 EI.getName()+".lhs");
13316 Value *newEI1 =
13317 Builder->CreateExtractElement(BO->getOperand(1), EI.getOperand(1),
13318 EI.getName()+".rhs");
13319 return BinaryOperator::Create(BO->getOpcode(), newEI0, newEI1);
Chris Lattner73fa49d2006-05-25 22:53:38 +000013320 }
Chris Lattner275a6d62009-09-08 18:48:01 +000013321 } else if (InsertElementInst *IE = dyn_cast<InsertElementInst>(I)) {
Chris Lattner73fa49d2006-05-25 22:53:38 +000013322 // Extracting the inserted element?
13323 if (IE->getOperand(2) == EI.getOperand(1))
13324 return ReplaceInstUsesWith(EI, IE->getOperand(1));
13325 // If the inserted and extracted elements are constants, they must not
13326 // be the same value, extract from the pre-inserted value instead.
Chris Lattner08142f22009-08-30 19:47:22 +000013327 if (isa<Constant>(IE->getOperand(2)) && isa<Constant>(EI.getOperand(1))) {
Chris Lattner3c4e38e2009-08-30 06:27:41 +000013328 Worklist.AddValue(EI.getOperand(0));
Chris Lattner73fa49d2006-05-25 22:53:38 +000013329 EI.setOperand(0, IE->getOperand(0));
13330 return &EI;
13331 }
13332 } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(I)) {
13333 // If this is extracting an element from a shufflevector, figure out where
13334 // it came from and extract from the appropriate input element instead.
Reid Spencerb83eb642006-10-20 07:07:24 +000013335 if (ConstantInt *Elt = dyn_cast<ConstantInt>(EI.getOperand(1))) {
13336 unsigned SrcIdx = getShuffleMask(SVI)[Elt->getZExtValue()];
Chris Lattner863bcff2006-05-25 23:48:38 +000013337 Value *Src;
Mon P Wangaeb06d22008-11-10 04:46:22 +000013338 unsigned LHSWidth =
13339 cast<VectorType>(SVI->getOperand(0)->getType())->getNumElements();
13340
13341 if (SrcIdx < LHSWidth)
Chris Lattner863bcff2006-05-25 23:48:38 +000013342 Src = SVI->getOperand(0);
Mon P Wangaeb06d22008-11-10 04:46:22 +000013343 else if (SrcIdx < LHSWidth*2) {
13344 SrcIdx -= LHSWidth;
Chris Lattner863bcff2006-05-25 23:48:38 +000013345 Src = SVI->getOperand(1);
13346 } else {
Owen Anderson9e9a0d52009-07-30 23:03:37 +000013347 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
Chris Lattnerdf084ff2006-03-30 22:02:40 +000013348 }
Eric Christophera3500da2009-07-25 02:28:41 +000013349 return ExtractElementInst::Create(Src,
Chris Lattner08142f22009-08-30 19:47:22 +000013350 ConstantInt::get(Type::getInt32Ty(*Context), SrcIdx,
13351 false));
Robert Bocchino1d7456d2006-01-13 22:48:06 +000013352 }
13353 }
Eli Friedman2451a642009-07-18 23:06:53 +000013354 // FIXME: Canonicalize extractelement(bitcast) -> bitcast(extractelement)
Chris Lattner73fa49d2006-05-25 22:53:38 +000013355 }
Robert Bocchino1d7456d2006-01-13 22:48:06 +000013356 return 0;
13357}
13358
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000013359/// CollectSingleShuffleElements - If V is a shuffle of values that ONLY returns
13360/// elements from either LHS or RHS, return the shuffle mask and true.
13361/// Otherwise, return false.
13362static bool CollectSingleShuffleElements(Value *V, Value *LHS, Value *RHS,
Owen Andersond672ecb2009-07-03 00:17:18 +000013363 std::vector<Constant*> &Mask,
Owen Anderson07cf79e2009-07-06 23:00:19 +000013364 LLVMContext *Context) {
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000013365 assert(V->getType() == LHS->getType() && V->getType() == RHS->getType() &&
13366 "Invalid CollectSingleShuffleElements");
Reid Spencer9d6565a2007-02-15 02:26:10 +000013367 unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000013368
13369 if (isa<UndefValue>(V)) {
Owen Anderson1d0be152009-08-13 21:58:54 +000013370 Mask.assign(NumElts, UndefValue::get(Type::getInt32Ty(*Context)));
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000013371 return true;
13372 } else if (V == LHS) {
13373 for (unsigned i = 0; i != NumElts; ++i)
Owen Anderson1d0be152009-08-13 21:58:54 +000013374 Mask.push_back(ConstantInt::get(Type::getInt32Ty(*Context), i));
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000013375 return true;
13376 } else if (V == RHS) {
13377 for (unsigned i = 0; i != NumElts; ++i)
Owen Anderson1d0be152009-08-13 21:58:54 +000013378 Mask.push_back(ConstantInt::get(Type::getInt32Ty(*Context), i+NumElts));
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000013379 return true;
13380 } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
13381 // If this is an insert of an extract from some other vector, include it.
13382 Value *VecOp = IEI->getOperand(0);
13383 Value *ScalarOp = IEI->getOperand(1);
13384 Value *IdxOp = IEI->getOperand(2);
13385
Chris Lattnerd929f062006-04-27 21:14:21 +000013386 if (!isa<ConstantInt>(IdxOp))
13387 return false;
Reid Spencerb83eb642006-10-20 07:07:24 +000013388 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
Chris Lattnerd929f062006-04-27 21:14:21 +000013389
13390 if (isa<UndefValue>(ScalarOp)) { // inserting undef into vector.
13391 // Okay, we can handle this if the vector we are insertinting into is
13392 // transitively ok.
Owen Andersond672ecb2009-07-03 00:17:18 +000013393 if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask, Context)) {
Chris Lattnerd929f062006-04-27 21:14:21 +000013394 // If so, update the mask to reflect the inserted undef.
Owen Anderson1d0be152009-08-13 21:58:54 +000013395 Mask[InsertedIdx] = UndefValue::get(Type::getInt32Ty(*Context));
Chris Lattnerd929f062006-04-27 21:14:21 +000013396 return true;
13397 }
13398 } else if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)){
13399 if (isa<ConstantInt>(EI->getOperand(1)) &&
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000013400 EI->getOperand(0)->getType() == V->getType()) {
13401 unsigned ExtractedIdx =
Reid Spencerb83eb642006-10-20 07:07:24 +000013402 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000013403
13404 // This must be extracting from either LHS or RHS.
13405 if (EI->getOperand(0) == LHS || EI->getOperand(0) == RHS) {
13406 // Okay, we can handle this if the vector we are insertinting into is
13407 // transitively ok.
Owen Andersond672ecb2009-07-03 00:17:18 +000013408 if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask, Context)) {
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000013409 // If so, update the mask to reflect the inserted value.
13410 if (EI->getOperand(0) == LHS) {
Mon P Wang4f5ca2c2008-08-20 02:23:25 +000013411 Mask[InsertedIdx % NumElts] =
Owen Anderson1d0be152009-08-13 21:58:54 +000013412 ConstantInt::get(Type::getInt32Ty(*Context), ExtractedIdx);
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000013413 } else {
13414 assert(EI->getOperand(0) == RHS);
Mon P Wang4f5ca2c2008-08-20 02:23:25 +000013415 Mask[InsertedIdx % NumElts] =
Owen Anderson1d0be152009-08-13 21:58:54 +000013416 ConstantInt::get(Type::getInt32Ty(*Context), ExtractedIdx+NumElts);
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000013417
13418 }
13419 return true;
13420 }
13421 }
13422 }
13423 }
13424 }
13425 // TODO: Handle shufflevector here!
13426
13427 return false;
13428}
13429
13430/// CollectShuffleElements - We are building a shuffle of V, using RHS as the
13431/// RHS of the shuffle instruction, if it is not null. Return a shuffle mask
13432/// that computes V and the LHS value of the shuffle.
Chris Lattnerefb47352006-04-15 01:39:45 +000013433static Value *CollectShuffleElements(Value *V, std::vector<Constant*> &Mask,
Owen Anderson07cf79e2009-07-06 23:00:19 +000013434 Value *&RHS, LLVMContext *Context) {
Reid Spencer9d6565a2007-02-15 02:26:10 +000013435 assert(isa<VectorType>(V->getType()) &&
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000013436 (RHS == 0 || V->getType() == RHS->getType()) &&
Chris Lattnerefb47352006-04-15 01:39:45 +000013437 "Invalid shuffle!");
Reid Spencer9d6565a2007-02-15 02:26:10 +000013438 unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
Chris Lattnerefb47352006-04-15 01:39:45 +000013439
13440 if (isa<UndefValue>(V)) {
Owen Anderson1d0be152009-08-13 21:58:54 +000013441 Mask.assign(NumElts, UndefValue::get(Type::getInt32Ty(*Context)));
Chris Lattnerefb47352006-04-15 01:39:45 +000013442 return V;
13443 } else if (isa<ConstantAggregateZero>(V)) {
Owen Anderson1d0be152009-08-13 21:58:54 +000013444 Mask.assign(NumElts, ConstantInt::get(Type::getInt32Ty(*Context), 0));
Chris Lattnerefb47352006-04-15 01:39:45 +000013445 return V;
13446 } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
13447 // If this is an insert of an extract from some other vector, include it.
13448 Value *VecOp = IEI->getOperand(0);
13449 Value *ScalarOp = IEI->getOperand(1);
13450 Value *IdxOp = IEI->getOperand(2);
13451
13452 if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
13453 if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
13454 EI->getOperand(0)->getType() == V->getType()) {
13455 unsigned ExtractedIdx =
Reid Spencerb83eb642006-10-20 07:07:24 +000013456 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
13457 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
Chris Lattnerefb47352006-04-15 01:39:45 +000013458
13459 // Either the extracted from or inserted into vector must be RHSVec,
13460 // otherwise we'd end up with a shuffle of three inputs.
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000013461 if (EI->getOperand(0) == RHS || RHS == 0) {
13462 RHS = EI->getOperand(0);
Owen Andersond672ecb2009-07-03 00:17:18 +000013463 Value *V = CollectShuffleElements(VecOp, Mask, RHS, Context);
Mon P Wang4f5ca2c2008-08-20 02:23:25 +000013464 Mask[InsertedIdx % NumElts] =
Owen Anderson1d0be152009-08-13 21:58:54 +000013465 ConstantInt::get(Type::getInt32Ty(*Context), NumElts+ExtractedIdx);
Chris Lattnerefb47352006-04-15 01:39:45 +000013466 return V;
13467 }
13468
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000013469 if (VecOp == RHS) {
Owen Andersond672ecb2009-07-03 00:17:18 +000013470 Value *V = CollectShuffleElements(EI->getOperand(0), Mask,
13471 RHS, Context);
Chris Lattnerefb47352006-04-15 01:39:45 +000013472 // Everything but the extracted element is replaced with the RHS.
13473 for (unsigned i = 0; i != NumElts; ++i) {
13474 if (i != InsertedIdx)
Owen Anderson1d0be152009-08-13 21:58:54 +000013475 Mask[i] = ConstantInt::get(Type::getInt32Ty(*Context), NumElts+i);
Chris Lattnerefb47352006-04-15 01:39:45 +000013476 }
13477 return V;
13478 }
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000013479
13480 // If this insertelement is a chain that comes from exactly these two
13481 // vectors, return the vector and the effective shuffle.
Owen Andersond672ecb2009-07-03 00:17:18 +000013482 if (CollectSingleShuffleElements(IEI, EI->getOperand(0), RHS, Mask,
13483 Context))
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000013484 return EI->getOperand(0);
13485
Chris Lattnerefb47352006-04-15 01:39:45 +000013486 }
13487 }
13488 }
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000013489 // TODO: Handle shufflevector here!
Chris Lattnerefb47352006-04-15 01:39:45 +000013490
13491 // Otherwise, can't do anything fancy. Return an identity vector.
13492 for (unsigned i = 0; i != NumElts; ++i)
Owen Anderson1d0be152009-08-13 21:58:54 +000013493 Mask.push_back(ConstantInt::get(Type::getInt32Ty(*Context), i));
Chris Lattnerefb47352006-04-15 01:39:45 +000013494 return V;
13495}
13496
13497Instruction *InstCombiner::visitInsertElementInst(InsertElementInst &IE) {
13498 Value *VecOp = IE.getOperand(0);
13499 Value *ScalarOp = IE.getOperand(1);
13500 Value *IdxOp = IE.getOperand(2);
13501
Chris Lattner599ded12007-04-09 01:11:16 +000013502 // Inserting an undef or into an undefined place, remove this.
13503 if (isa<UndefValue>(ScalarOp) || isa<UndefValue>(IdxOp))
13504 ReplaceInstUsesWith(IE, VecOp);
Eli Friedman76e7ba82009-07-18 19:04:16 +000013505
Chris Lattnerefb47352006-04-15 01:39:45 +000013506 // If the inserted element was extracted from some other vector, and if the
13507 // indexes are constant, try to turn this into a shufflevector operation.
13508 if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
13509 if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
13510 EI->getOperand(0)->getType() == IE.getType()) {
Eli Friedman76e7ba82009-07-18 19:04:16 +000013511 unsigned NumVectorElts = IE.getType()->getNumElements();
Chris Lattnere34e9a22007-04-14 23:32:02 +000013512 unsigned ExtractedIdx =
13513 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
Reid Spencerb83eb642006-10-20 07:07:24 +000013514 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
Chris Lattnerefb47352006-04-15 01:39:45 +000013515
13516 if (ExtractedIdx >= NumVectorElts) // Out of range extract.
13517 return ReplaceInstUsesWith(IE, VecOp);
13518
13519 if (InsertedIdx >= NumVectorElts) // Out of range insert.
Owen Anderson9e9a0d52009-07-30 23:03:37 +000013520 return ReplaceInstUsesWith(IE, UndefValue::get(IE.getType()));
Chris Lattnerefb47352006-04-15 01:39:45 +000013521
13522 // If we are extracting a value from a vector, then inserting it right
13523 // back into the same place, just use the input vector.
13524 if (EI->getOperand(0) == VecOp && ExtractedIdx == InsertedIdx)
13525 return ReplaceInstUsesWith(IE, VecOp);
13526
Chris Lattnerefb47352006-04-15 01:39:45 +000013527 // If this insertelement isn't used by some other insertelement, turn it
13528 // (and any insertelements it points to), into one big shuffle.
13529 if (!IE.hasOneUse() || !isa<InsertElementInst>(IE.use_back())) {
13530 std::vector<Constant*> Mask;
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000013531 Value *RHS = 0;
Owen Andersond672ecb2009-07-03 00:17:18 +000013532 Value *LHS = CollectShuffleElements(&IE, Mask, RHS, Context);
Owen Anderson9e9a0d52009-07-30 23:03:37 +000013533 if (RHS == 0) RHS = UndefValue::get(LHS->getType());
Chris Lattner7f6cc0c2006-04-16 00:51:47 +000013534 // We now have a shuffle of LHS, RHS, Mask.
Owen Andersond672ecb2009-07-03 00:17:18 +000013535 return new ShuffleVectorInst(LHS, RHS,
Owen Andersonaf7ec972009-07-28 21:19:26 +000013536 ConstantVector::get(Mask));
Chris Lattnerefb47352006-04-15 01:39:45 +000013537 }
13538 }
13539 }
13540
Eli Friedmanb9a4cac2009-06-06 20:08:03 +000013541 unsigned VWidth = cast<VectorType>(VecOp->getType())->getNumElements();
13542 APInt UndefElts(VWidth, 0);
13543 APInt AllOnesEltMask(APInt::getAllOnesValue(VWidth));
13544 if (SimplifyDemandedVectorElts(&IE, AllOnesEltMask, UndefElts))
13545 return &IE;
13546
Chris Lattnerefb47352006-04-15 01:39:45 +000013547 return 0;
13548}
13549
13550
Chris Lattnera844fc4c2006-04-10 22:45:52 +000013551Instruction *InstCombiner::visitShuffleVectorInst(ShuffleVectorInst &SVI) {
13552 Value *LHS = SVI.getOperand(0);
13553 Value *RHS = SVI.getOperand(1);
Chris Lattner863bcff2006-05-25 23:48:38 +000013554 std::vector<unsigned> Mask = getShuffleMask(&SVI);
Chris Lattnera844fc4c2006-04-10 22:45:52 +000013555
13556 bool MadeChange = false;
Mon P Wangaeb06d22008-11-10 04:46:22 +000013557
Chris Lattner867b99f2006-10-05 06:55:50 +000013558 // Undefined shuffle mask -> undefined value.
Chris Lattner863bcff2006-05-25 23:48:38 +000013559 if (isa<UndefValue>(SVI.getOperand(2)))
Owen Anderson9e9a0d52009-07-30 23:03:37 +000013560 return ReplaceInstUsesWith(SVI, UndefValue::get(SVI.getType()));
Dan Gohman488fbfc2008-09-09 18:11:14 +000013561
Dan Gohman488fbfc2008-09-09 18:11:14 +000013562 unsigned VWidth = cast<VectorType>(SVI.getType())->getNumElements();
Mon P Wangaeb06d22008-11-10 04:46:22 +000013563
13564 if (VWidth != cast<VectorType>(LHS->getType())->getNumElements())
13565 return 0;
13566
Evan Cheng388df622009-02-03 10:05:09 +000013567 APInt UndefElts(VWidth, 0);
13568 APInt AllOnesEltMask(APInt::getAllOnesValue(VWidth));
13569 if (SimplifyDemandedVectorElts(&SVI, AllOnesEltMask, UndefElts)) {
Dan Gohman3139ff82008-09-11 22:47:57 +000013570 LHS = SVI.getOperand(0);
13571 RHS = SVI.getOperand(1);
Dan Gohman488fbfc2008-09-09 18:11:14 +000013572 MadeChange = true;
Dan Gohman3139ff82008-09-11 22:47:57 +000013573 }
Chris Lattnerefb47352006-04-15 01:39:45 +000013574
Chris Lattner863bcff2006-05-25 23:48:38 +000013575 // Canonicalize shuffle(x ,x,mask) -> shuffle(x, undef,mask')
13576 // Canonicalize shuffle(undef,x,mask) -> shuffle(x, undef,mask').
13577 if (LHS == RHS || isa<UndefValue>(LHS)) {
13578 if (isa<UndefValue>(LHS) && LHS == RHS) {
Chris Lattnera844fc4c2006-04-10 22:45:52 +000013579 // shuffle(undef,undef,mask) -> undef.
13580 return ReplaceInstUsesWith(SVI, LHS);
13581 }
13582
Chris Lattner863bcff2006-05-25 23:48:38 +000013583 // Remap any references to RHS to use LHS.
13584 std::vector<Constant*> Elts;
13585 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
Chris Lattner7b2e27922006-05-26 00:29:06 +000013586 if (Mask[i] >= 2*e)
Owen Anderson1d0be152009-08-13 21:58:54 +000013587 Elts.push_back(UndefValue::get(Type::getInt32Ty(*Context)));
Chris Lattner7b2e27922006-05-26 00:29:06 +000013588 else {
13589 if ((Mask[i] >= e && isa<UndefValue>(RHS)) ||
Dan Gohman4ce96272008-08-06 18:17:32 +000013590 (Mask[i] < e && isa<UndefValue>(LHS))) {
Chris Lattner7b2e27922006-05-26 00:29:06 +000013591 Mask[i] = 2*e; // Turn into undef.
Owen Anderson1d0be152009-08-13 21:58:54 +000013592 Elts.push_back(UndefValue::get(Type::getInt32Ty(*Context)));
Dan Gohman4ce96272008-08-06 18:17:32 +000013593 } else {
Mon P Wang4f5ca2c2008-08-20 02:23:25 +000013594 Mask[i] = Mask[i] % e; // Force to LHS.
Owen Anderson1d0be152009-08-13 21:58:54 +000013595 Elts.push_back(ConstantInt::get(Type::getInt32Ty(*Context), Mask[i]));
Dan Gohman4ce96272008-08-06 18:17:32 +000013596 }
Chris Lattner7b2e27922006-05-26 00:29:06 +000013597 }
Chris Lattnera844fc4c2006-04-10 22:45:52 +000013598 }
Chris Lattner863bcff2006-05-25 23:48:38 +000013599 SVI.setOperand(0, SVI.getOperand(1));
Owen Anderson9e9a0d52009-07-30 23:03:37 +000013600 SVI.setOperand(1, UndefValue::get(RHS->getType()));
Owen Andersonaf7ec972009-07-28 21:19:26 +000013601 SVI.setOperand(2, ConstantVector::get(Elts));
Chris Lattner7b2e27922006-05-26 00:29:06 +000013602 LHS = SVI.getOperand(0);
13603 RHS = SVI.getOperand(1);
Chris Lattnera844fc4c2006-04-10 22:45:52 +000013604 MadeChange = true;
13605 }
13606
Chris Lattner7b2e27922006-05-26 00:29:06 +000013607 // Analyze the shuffle, are the LHS or RHS and identity shuffles?
Chris Lattner863bcff2006-05-25 23:48:38 +000013608 bool isLHSID = true, isRHSID = true;
Chris Lattner706126d2006-04-16 00:03:56 +000013609
Chris Lattner863bcff2006-05-25 23:48:38 +000013610 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
13611 if (Mask[i] >= e*2) continue; // Ignore undef values.
13612 // Is this an identity shuffle of the LHS value?
13613 isLHSID &= (Mask[i] == i);
13614
13615 // Is this an identity shuffle of the RHS value?
13616 isRHSID &= (Mask[i]-e == i);
Chris Lattner706126d2006-04-16 00:03:56 +000013617 }
Chris Lattnera844fc4c2006-04-10 22:45:52 +000013618
Chris Lattner863bcff2006-05-25 23:48:38 +000013619 // Eliminate identity shuffles.
13620 if (isLHSID) return ReplaceInstUsesWith(SVI, LHS);
13621 if (isRHSID) return ReplaceInstUsesWith(SVI, RHS);
Chris Lattnera844fc4c2006-04-10 22:45:52 +000013622
Chris Lattner7b2e27922006-05-26 00:29:06 +000013623 // If the LHS is a shufflevector itself, see if we can combine it with this
13624 // one without producing an unusual shuffle. Here we are really conservative:
13625 // we are absolutely afraid of producing a shuffle mask not in the input
13626 // program, because the code gen may not be smart enough to turn a merged
13627 // shuffle into two specific shuffles: it may produce worse code. As such,
13628 // we only merge two shuffles if the result is one of the two input shuffle
13629 // masks. In this case, merging the shuffles just removes one instruction,
13630 // which we know is safe. This is good for things like turning:
13631 // (splat(splat)) -> splat.
13632 if (ShuffleVectorInst *LHSSVI = dyn_cast<ShuffleVectorInst>(LHS)) {
13633 if (isa<UndefValue>(RHS)) {
13634 std::vector<unsigned> LHSMask = getShuffleMask(LHSSVI);
13635
David Greenef941d292009-11-16 21:52:23 +000013636 if (LHSMask.size() == Mask.size()) {
13637 std::vector<unsigned> NewMask;
13638 for (unsigned i = 0, e = Mask.size(); i != e; ++i)
Duncan Sands76700ba2009-11-20 13:19:51 +000013639 if (Mask[i] >= e)
David Greenef941d292009-11-16 21:52:23 +000013640 NewMask.push_back(2*e);
13641 else
13642 NewMask.push_back(LHSMask[Mask[i]]);
Chris Lattner7b2e27922006-05-26 00:29:06 +000013643
David Greenef941d292009-11-16 21:52:23 +000013644 // If the result mask is equal to the src shuffle or this
13645 // shuffle mask, do the replacement.
13646 if (NewMask == LHSMask || NewMask == Mask) {
13647 unsigned LHSInNElts =
13648 cast<VectorType>(LHSSVI->getOperand(0)->getType())->
13649 getNumElements();
13650 std::vector<Constant*> Elts;
13651 for (unsigned i = 0, e = NewMask.size(); i != e; ++i) {
13652 if (NewMask[i] >= LHSInNElts*2) {
13653 Elts.push_back(UndefValue::get(Type::getInt32Ty(*Context)));
13654 } else {
13655 Elts.push_back(ConstantInt::get(Type::getInt32Ty(*Context),
13656 NewMask[i]));
13657 }
Chris Lattner7b2e27922006-05-26 00:29:06 +000013658 }
David Greenef941d292009-11-16 21:52:23 +000013659 return new ShuffleVectorInst(LHSSVI->getOperand(0),
13660 LHSSVI->getOperand(1),
13661 ConstantVector::get(Elts));
Chris Lattner7b2e27922006-05-26 00:29:06 +000013662 }
Chris Lattner7b2e27922006-05-26 00:29:06 +000013663 }
13664 }
13665 }
Chris Lattnerc5eff442007-01-30 22:32:46 +000013666
Chris Lattnera844fc4c2006-04-10 22:45:52 +000013667 return MadeChange ? &SVI : 0;
13668}
13669
13670
Robert Bocchino1d7456d2006-01-13 22:48:06 +000013671
Chris Lattnerea1c4542004-12-08 23:43:58 +000013672
13673/// TryToSinkInstruction - Try to move the specified instruction from its
13674/// current block into the beginning of DestBlock, which can only happen if it's
13675/// safe to move the instruction past all of the instructions between it and the
13676/// end of its block.
13677static bool TryToSinkInstruction(Instruction *I, BasicBlock *DestBlock) {
13678 assert(I->hasOneUse() && "Invariants didn't hold!");
13679
Chris Lattner108e9022005-10-27 17:13:11 +000013680 // Cannot move control-flow-involving, volatile loads, vaarg, etc.
Duncan Sands7af1c782009-05-06 06:49:50 +000013681 if (isa<PHINode>(I) || I->mayHaveSideEffects() || isa<TerminatorInst>(I))
Chris Lattnerbfc538c2008-05-09 15:07:33 +000013682 return false;
Misha Brukmanfd939082005-04-21 23:48:37 +000013683
Chris Lattnerea1c4542004-12-08 23:43:58 +000013684 // Do not sink alloca instructions out of the entry block.
Dan Gohmanecb7a772007-03-22 16:38:57 +000013685 if (isa<AllocaInst>(I) && I->getParent() ==
13686 &DestBlock->getParent()->getEntryBlock())
Chris Lattnerea1c4542004-12-08 23:43:58 +000013687 return false;
13688
Chris Lattner96a52a62004-12-09 07:14:34 +000013689 // We can only sink load instructions if there is nothing between the load and
13690 // the end of block that could change the value.
Chris Lattner2539e332008-05-08 17:37:37 +000013691 if (I->mayReadFromMemory()) {
13692 for (BasicBlock::iterator Scan = I, E = I->getParent()->end();
Chris Lattner96a52a62004-12-09 07:14:34 +000013693 Scan != E; ++Scan)
13694 if (Scan->mayWriteToMemory())
13695 return false;
Chris Lattner96a52a62004-12-09 07:14:34 +000013696 }
Chris Lattnerea1c4542004-12-08 23:43:58 +000013697
Dan Gohman02dea8b2008-05-23 21:05:58 +000013698 BasicBlock::iterator InsertPos = DestBlock->getFirstNonPHI();
Chris Lattnerea1c4542004-12-08 23:43:58 +000013699
Dale Johannesenbd8e6502009-03-03 01:09:07 +000013700 CopyPrecedingStopPoint(I, InsertPos);
Chris Lattner4bc5f802005-08-08 19:11:57 +000013701 I->moveBefore(InsertPos);
Chris Lattnerea1c4542004-12-08 23:43:58 +000013702 ++NumSunkInst;
13703 return true;
13704}
13705
Chris Lattnerf4f5a772006-05-10 19:00:36 +000013706
13707/// AddReachableCodeToWorklist - Walk the function in depth-first order, adding
13708/// all reachable code to the worklist.
13709///
13710/// This has a couple of tricks to make the code faster and more powerful. In
13711/// particular, we constant fold and DCE instructions as we go, to avoid adding
13712/// them to the worklist (this significantly speeds up instcombine on code where
13713/// many instructions are dead or constant). Additionally, if we find a branch
13714/// whose condition is a known constant, we only visit the reachable successors.
13715///
Chris Lattner2ee743b2009-10-15 04:59:28 +000013716static bool AddReachableCodeToWorklist(BasicBlock *BB,
Chris Lattner1f87a582007-02-15 19:41:52 +000013717 SmallPtrSet<BasicBlock*, 64> &Visited,
Chris Lattnerdbab3862007-03-02 21:28:56 +000013718 InstCombiner &IC,
Chris Lattner8c8c66a2006-05-11 17:11:52 +000013719 const TargetData *TD) {
Chris Lattner2ee743b2009-10-15 04:59:28 +000013720 bool MadeIRChange = false;
Chris Lattner2806dff2008-08-15 04:03:01 +000013721 SmallVector<BasicBlock*, 256> Worklist;
Chris Lattner2c7718a2007-03-23 19:17:18 +000013722 Worklist.push_back(BB);
Chris Lattner67f7d542009-10-12 03:58:40 +000013723
13724 std::vector<Instruction*> InstrsForInstCombineWorklist;
13725 InstrsForInstCombineWorklist.reserve(128);
Chris Lattnerf4f5a772006-05-10 19:00:36 +000013726
Chris Lattner2ee743b2009-10-15 04:59:28 +000013727 SmallPtrSet<ConstantExpr*, 64> FoldedConstants;
13728
Chris Lattner2c7718a2007-03-23 19:17:18 +000013729 while (!Worklist.empty()) {
13730 BB = Worklist.back();
13731 Worklist.pop_back();
13732
13733 // We have now visited this block! If we've already been here, ignore it.
13734 if (!Visited.insert(BB)) continue;
Devang Patel7fe1dec2008-11-19 18:56:50 +000013735
Chris Lattner2c7718a2007-03-23 19:17:18 +000013736 for (BasicBlock::iterator BBI = BB->begin(), E = BB->end(); BBI != E; ) {
13737 Instruction *Inst = BBI++;
Chris Lattnerf4f5a772006-05-10 19:00:36 +000013738
Chris Lattner2c7718a2007-03-23 19:17:18 +000013739 // DCE instruction if trivially dead.
13740 if (isInstructionTriviallyDead(Inst)) {
13741 ++NumDeadInst;
Chris Lattnerbdff5482009-08-23 04:37:46 +000013742 DEBUG(errs() << "IC: DCE: " << *Inst << '\n');
Chris Lattner2c7718a2007-03-23 19:17:18 +000013743 Inst->eraseFromParent();
13744 continue;
13745 }
13746
13747 // ConstantProp instruction if trivially constant.
Chris Lattnere2cc1ad2009-10-15 04:13:44 +000013748 if (!Inst->use_empty() && isa<Constant>(Inst->getOperand(0)))
Chris Lattner7b550cc2009-11-06 04:27:31 +000013749 if (Constant *C = ConstantFoldInstruction(Inst, TD)) {
Chris Lattnere2cc1ad2009-10-15 04:13:44 +000013750 DEBUG(errs() << "IC: ConstFold to: " << *C << " from: "
13751 << *Inst << '\n');
13752 Inst->replaceAllUsesWith(C);
13753 ++NumConstProp;
13754 Inst->eraseFromParent();
13755 continue;
13756 }
Chris Lattner2ee743b2009-10-15 04:59:28 +000013757
13758
13759
13760 if (TD) {
13761 // See if we can constant fold its operands.
13762 for (User::op_iterator i = Inst->op_begin(), e = Inst->op_end();
13763 i != e; ++i) {
13764 ConstantExpr *CE = dyn_cast<ConstantExpr>(i);
13765 if (CE == 0) continue;
13766
13767 // If we already folded this constant, don't try again.
13768 if (!FoldedConstants.insert(CE))
13769 continue;
13770
Chris Lattner7b550cc2009-11-06 04:27:31 +000013771 Constant *NewC = ConstantFoldConstantExpression(CE, TD);
Chris Lattner2ee743b2009-10-15 04:59:28 +000013772 if (NewC && NewC != CE) {
13773 *i = NewC;
13774 MadeIRChange = true;
13775 }
13776 }
13777 }
13778
Devang Patel7fe1dec2008-11-19 18:56:50 +000013779
Chris Lattner67f7d542009-10-12 03:58:40 +000013780 InstrsForInstCombineWorklist.push_back(Inst);
Chris Lattnerf4f5a772006-05-10 19:00:36 +000013781 }
Chris Lattner2c7718a2007-03-23 19:17:18 +000013782
13783 // Recursively visit successors. If this is a branch or switch on a
13784 // constant, only visit the reachable successor.
13785 TerminatorInst *TI = BB->getTerminator();
13786 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
13787 if (BI->isConditional() && isa<ConstantInt>(BI->getCondition())) {
13788 bool CondVal = cast<ConstantInt>(BI->getCondition())->getZExtValue();
Nick Lewycky91436992008-03-09 08:50:23 +000013789 BasicBlock *ReachableBB = BI->getSuccessor(!CondVal);
Nick Lewycky280a6e62008-04-25 16:53:59 +000013790 Worklist.push_back(ReachableBB);
Chris Lattner2c7718a2007-03-23 19:17:18 +000013791 continue;
13792 }
13793 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
13794 if (ConstantInt *Cond = dyn_cast<ConstantInt>(SI->getCondition())) {
13795 // See if this is an explicit destination.
13796 for (unsigned i = 1, e = SI->getNumSuccessors(); i != e; ++i)
13797 if (SI->getCaseValue(i) == Cond) {
Nick Lewycky91436992008-03-09 08:50:23 +000013798 BasicBlock *ReachableBB = SI->getSuccessor(i);
Nick Lewycky280a6e62008-04-25 16:53:59 +000013799 Worklist.push_back(ReachableBB);
Chris Lattner2c7718a2007-03-23 19:17:18 +000013800 continue;
13801 }
13802
13803 // Otherwise it is the default destination.
13804 Worklist.push_back(SI->getSuccessor(0));
13805 continue;
13806 }
13807 }
13808
13809 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
13810 Worklist.push_back(TI->getSuccessor(i));
Chris Lattnerf4f5a772006-05-10 19:00:36 +000013811 }
Chris Lattner67f7d542009-10-12 03:58:40 +000013812
13813 // Once we've found all of the instructions to add to instcombine's worklist,
13814 // add them in reverse order. This way instcombine will visit from the top
13815 // of the function down. This jives well with the way that it adds all uses
13816 // of instructions to the worklist after doing a transformation, thus avoiding
13817 // some N^2 behavior in pathological cases.
13818 IC.Worklist.AddInitialGroup(&InstrsForInstCombineWorklist[0],
13819 InstrsForInstCombineWorklist.size());
Chris Lattner2ee743b2009-10-15 04:59:28 +000013820
13821 return MadeIRChange;
Chris Lattnerf4f5a772006-05-10 19:00:36 +000013822}
13823
Chris Lattnerec9c3582007-03-03 02:04:50 +000013824bool InstCombiner::DoOneIteration(Function &F, unsigned Iteration) {
Chris Lattnerb0b822c2009-08-31 06:57:37 +000013825 MadeIRChange = false;
Chris Lattnerec9c3582007-03-03 02:04:50 +000013826
Daniel Dunbarce63ffb2009-07-25 00:23:56 +000013827 DEBUG(errs() << "\n\nINSTCOMBINE ITERATION #" << Iteration << " on "
13828 << F.getNameStr() << "\n");
Chris Lattner8a2a3112001-12-14 16:52:21 +000013829
Chris Lattnerb3d59702005-07-07 20:40:38 +000013830 {
Chris Lattnerf4f5a772006-05-10 19:00:36 +000013831 // Do a depth-first traversal of the function, populate the worklist with
13832 // the reachable instructions. Ignore blocks that are not reachable. Keep
13833 // track of which blocks we visit.
Chris Lattner1f87a582007-02-15 19:41:52 +000013834 SmallPtrSet<BasicBlock*, 64> Visited;
Chris Lattner2ee743b2009-10-15 04:59:28 +000013835 MadeIRChange |= AddReachableCodeToWorklist(F.begin(), Visited, *this, TD);
Jeff Cohen00b168892005-07-27 06:12:32 +000013836
Chris Lattnerb3d59702005-07-07 20:40:38 +000013837 // Do a quick scan over the function. If we find any blocks that are
13838 // unreachable, remove any instructions inside of them. This prevents
13839 // the instcombine code from having to deal with some bad special cases.
13840 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
13841 if (!Visited.count(BB)) {
13842 Instruction *Term = BB->getTerminator();
13843 while (Term != BB->begin()) { // Remove instrs bottom-up
13844 BasicBlock::iterator I = Term; --I;
Chris Lattner6ffe5512004-04-27 15:13:33 +000013845
Chris Lattnerbdff5482009-08-23 04:37:46 +000013846 DEBUG(errs() << "IC: DCE: " << *I << '\n');
Dale Johannesenff278b12009-03-10 21:19:49 +000013847 // A debug intrinsic shouldn't force another iteration if we weren't
13848 // going to do one without it.
13849 if (!isa<DbgInfoIntrinsic>(I)) {
13850 ++NumDeadInst;
Chris Lattnerb0b822c2009-08-31 06:57:37 +000013851 MadeIRChange = true;
Dale Johannesenff278b12009-03-10 21:19:49 +000013852 }
Devang Patel228ebd02009-10-13 22:56:32 +000013853
Devang Patel228ebd02009-10-13 22:56:32 +000013854 // If I is not void type then replaceAllUsesWith undef.
13855 // This allows ValueHandlers and custom metadata to adjust itself.
Devang Patel9674d152009-10-14 17:29:00 +000013856 if (!I->getType()->isVoidTy())
Devang Patel228ebd02009-10-13 22:56:32 +000013857 I->replaceAllUsesWith(UndefValue::get(I->getType()));
Chris Lattnerb3d59702005-07-07 20:40:38 +000013858 I->eraseFromParent();
13859 }
13860 }
13861 }
Chris Lattner8a2a3112001-12-14 16:52:21 +000013862
Chris Lattner873ff012009-08-30 05:55:36 +000013863 while (!Worklist.isEmpty()) {
13864 Instruction *I = Worklist.RemoveOne();
Chris Lattnerdbab3862007-03-02 21:28:56 +000013865 if (I == 0) continue; // skip null values.
Chris Lattner8a2a3112001-12-14 16:52:21 +000013866
Chris Lattner8c8c66a2006-05-11 17:11:52 +000013867 // Check to see if we can DCE the instruction.
Chris Lattner62b14df2002-09-02 04:59:56 +000013868 if (isInstructionTriviallyDead(I)) {
Chris Lattnerbdff5482009-08-23 04:37:46 +000013869 DEBUG(errs() << "IC: DCE: " << *I << '\n');
Chris Lattner7a1e9242009-08-30 06:13:40 +000013870 EraseInstFromFunction(*I);
13871 ++NumDeadInst;
Chris Lattnerb0b822c2009-08-31 06:57:37 +000013872 MadeIRChange = true;
Chris Lattner4bb7c022003-10-06 17:11:01 +000013873 continue;
13874 }
Chris Lattner62b14df2002-09-02 04:59:56 +000013875
Chris Lattner8c8c66a2006-05-11 17:11:52 +000013876 // Instruction isn't dead, see if we can constant propagate it.
Chris Lattnere2cc1ad2009-10-15 04:13:44 +000013877 if (!I->use_empty() && isa<Constant>(I->getOperand(0)))
Chris Lattner7b550cc2009-11-06 04:27:31 +000013878 if (Constant *C = ConstantFoldInstruction(I, TD)) {
Chris Lattnere2cc1ad2009-10-15 04:13:44 +000013879 DEBUG(errs() << "IC: ConstFold to: " << *C << " from: " << *I << '\n');
Chris Lattnerad5fec12005-01-28 19:32:01 +000013880
Chris Lattnere2cc1ad2009-10-15 04:13:44 +000013881 // Add operands to the worklist.
13882 ReplaceInstUsesWith(*I, C);
13883 ++NumConstProp;
13884 EraseInstFromFunction(*I);
13885 MadeIRChange = true;
13886 continue;
13887 }
Chris Lattner4bb7c022003-10-06 17:11:01 +000013888
Chris Lattnerea1c4542004-12-08 23:43:58 +000013889 // See if we can trivially sink this instruction to a successor basic block.
Dan Gohmanfc74abf2008-07-23 00:34:11 +000013890 if (I->hasOneUse()) {
Chris Lattnerea1c4542004-12-08 23:43:58 +000013891 BasicBlock *BB = I->getParent();
Chris Lattner8db2cd12009-10-14 15:21:58 +000013892 Instruction *UserInst = cast<Instruction>(I->use_back());
13893 BasicBlock *UserParent;
13894
13895 // Get the block the use occurs in.
13896 if (PHINode *PN = dyn_cast<PHINode>(UserInst))
13897 UserParent = PN->getIncomingBlock(I->use_begin().getUse());
13898 else
13899 UserParent = UserInst->getParent();
13900
Chris Lattnerea1c4542004-12-08 23:43:58 +000013901 if (UserParent != BB) {
13902 bool UserIsSuccessor = false;
13903 // See if the user is one of our successors.
13904 for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI)
13905 if (*SI == UserParent) {
13906 UserIsSuccessor = true;
13907 break;
13908 }
13909
13910 // If the user is one of our immediate successors, and if that successor
13911 // only has us as a predecessors (we'd have to split the critical edge
13912 // otherwise), we can keep going.
Chris Lattner8db2cd12009-10-14 15:21:58 +000013913 if (UserIsSuccessor && UserParent->getSinglePredecessor())
Chris Lattnerea1c4542004-12-08 23:43:58 +000013914 // Okay, the CFG is simple enough, try to sink this instruction.
Chris Lattnerb0b822c2009-08-31 06:57:37 +000013915 MadeIRChange |= TryToSinkInstruction(I, UserParent);
Chris Lattnerea1c4542004-12-08 23:43:58 +000013916 }
13917 }
13918
Chris Lattner74381062009-08-30 07:44:24 +000013919 // Now that we have an instruction, try combining it to simplify it.
13920 Builder->SetInsertPoint(I->getParent(), I);
13921
Reid Spencera9b81012007-03-26 17:44:01 +000013922#ifndef NDEBUG
13923 std::string OrigI;
13924#endif
Chris Lattnerbdff5482009-08-23 04:37:46 +000013925 DEBUG(raw_string_ostream SS(OrigI); I->print(SS); OrigI = SS.str(););
Jeffrey Yasskin43069632009-10-08 00:12:24 +000013926 DEBUG(errs() << "IC: Visiting: " << OrigI << '\n');
13927
Chris Lattner90ac28c2002-08-02 19:29:35 +000013928 if (Instruction *Result = visit(*I)) {
Chris Lattner3dec1f22002-05-10 15:38:35 +000013929 ++NumCombined;
Chris Lattnerdd841ae2002-04-18 17:39:14 +000013930 // Should we replace the old instruction with a new one?
Chris Lattnerb3bc8fa2002-05-14 15:24:07 +000013931 if (Result != I) {
Chris Lattnerbdff5482009-08-23 04:37:46 +000013932 DEBUG(errs() << "IC: Old = " << *I << '\n'
13933 << " New = " << *Result << '\n');
Chris Lattner0cea42a2004-03-13 23:54:27 +000013934
Chris Lattnerf523d062004-06-09 05:08:07 +000013935 // Everything uses the new instruction now.
13936 I->replaceAllUsesWith(Result);
13937
13938 // Push the new instruction and any users onto the worklist.
Chris Lattner7a1e9242009-08-30 06:13:40 +000013939 Worklist.Add(Result);
Chris Lattnere5ecdb52009-08-30 06:22:51 +000013940 Worklist.AddUsersToWorkList(*Result);
Chris Lattner4bb7c022003-10-06 17:11:01 +000013941
Chris Lattner6934a042007-02-11 01:23:03 +000013942 // Move the name to the new instruction first.
13943 Result->takeName(I);
Chris Lattner4bb7c022003-10-06 17:11:01 +000013944
13945 // Insert the new instruction into the basic block...
13946 BasicBlock *InstParent = I->getParent();
Chris Lattnerbac32862004-11-14 19:13:23 +000013947 BasicBlock::iterator InsertPos = I;
13948
13949 if (!isa<PHINode>(Result)) // If combining a PHI, don't insert
13950 while (isa<PHINode>(InsertPos)) // middle of a block of PHIs.
13951 ++InsertPos;
13952
13953 InstParent->getInstList().insert(InsertPos, Result);
Chris Lattner4bb7c022003-10-06 17:11:01 +000013954
Chris Lattner7a1e9242009-08-30 06:13:40 +000013955 EraseInstFromFunction(*I);
Chris Lattner7e708292002-06-25 16:13:24 +000013956 } else {
Evan Chengc7baf682007-03-27 16:44:48 +000013957#ifndef NDEBUG
Chris Lattnerbdff5482009-08-23 04:37:46 +000013958 DEBUG(errs() << "IC: Mod = " << OrigI << '\n'
13959 << " New = " << *I << '\n');
Evan Chengc7baf682007-03-27 16:44:48 +000013960#endif
Chris Lattner0cea42a2004-03-13 23:54:27 +000013961
Chris Lattner90ac28c2002-08-02 19:29:35 +000013962 // If the instruction was modified, it's possible that it is now dead.
13963 // if so, remove it.
Chris Lattner00d51312004-05-01 23:27:23 +000013964 if (isInstructionTriviallyDead(I)) {
Chris Lattner7a1e9242009-08-30 06:13:40 +000013965 EraseInstFromFunction(*I);
Chris Lattnerf523d062004-06-09 05:08:07 +000013966 } else {
Chris Lattner7a1e9242009-08-30 06:13:40 +000013967 Worklist.Add(I);
Chris Lattnere5ecdb52009-08-30 06:22:51 +000013968 Worklist.AddUsersToWorkList(*I);
Chris Lattner90ac28c2002-08-02 19:29:35 +000013969 }
Chris Lattnerb3bc8fa2002-05-14 15:24:07 +000013970 }
Chris Lattnerb0b822c2009-08-31 06:57:37 +000013971 MadeIRChange = true;
Chris Lattner8a2a3112001-12-14 16:52:21 +000013972 }
13973 }
13974
Chris Lattner873ff012009-08-30 05:55:36 +000013975 Worklist.Zap();
Chris Lattnerb0b822c2009-08-31 06:57:37 +000013976 return MadeIRChange;
Chris Lattnerbd0ef772002-02-26 21:46:54 +000013977}
13978
Chris Lattnerec9c3582007-03-03 02:04:50 +000013979
13980bool InstCombiner::runOnFunction(Function &F) {
Chris Lattnerf964f322007-03-04 04:27:24 +000013981 MustPreserveLCSSA = mustPreserveAnalysisID(LCSSAID);
Owen Andersone922c022009-07-22 00:24:57 +000013982 Context = &F.getContext();
Chris Lattnere2cc1ad2009-10-15 04:13:44 +000013983 TD = getAnalysisIfAvailable<TargetData>();
13984
Chris Lattner74381062009-08-30 07:44:24 +000013985
13986 /// Builder - This is an IRBuilder that automatically inserts new
13987 /// instructions into the worklist when they are created.
Chris Lattnere2cc1ad2009-10-15 04:13:44 +000013988 IRBuilder<true, TargetFolder, InstCombineIRInserter>
Chris Lattnerf55eeb92009-11-06 05:59:53 +000013989 TheBuilder(F.getContext(), TargetFolder(TD),
Chris Lattner74381062009-08-30 07:44:24 +000013990 InstCombineIRInserter(Worklist));
13991 Builder = &TheBuilder;
13992
Chris Lattnerec9c3582007-03-03 02:04:50 +000013993 bool EverMadeChange = false;
13994
13995 // Iterate while there is work to do.
13996 unsigned Iteration = 0;
Bill Wendlinga6c31122008-05-14 22:45:20 +000013997 while (DoOneIteration(F, Iteration++))
Chris Lattnerec9c3582007-03-03 02:04:50 +000013998 EverMadeChange = true;
Chris Lattner74381062009-08-30 07:44:24 +000013999
14000 Builder = 0;
Chris Lattnerec9c3582007-03-03 02:04:50 +000014001 return EverMadeChange;
14002}
14003
Brian Gaeke96d4bf72004-07-27 17:43:21 +000014004FunctionPass *llvm::createInstructionCombiningPass() {
Chris Lattnerdd841ae2002-04-18 17:39:14 +000014005 return new InstCombiner();
Chris Lattnerbd0ef772002-02-26 21:46:54 +000014006}