blob: 5a6077a3ca14cc3fd60f6fc805755ed7b0bdba0d [file] [log] [blame]
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001//===-- DAGCombiner.cpp - Implement a DAG node combiner -------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner081ce942007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This pass combines dag nodes to form fewer, simpler DAG nodes. It can be run
11// both before and after the DAG is legalized.
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012//
13//===----------------------------------------------------------------------===//
14
15#define DEBUG_TYPE "dagcombine"
16#include "llvm/CodeGen/SelectionDAG.h"
Chris Lattner4e137af2008-01-25 07:20:16 +000017#include "llvm/CodeGen/MachineFunction.h"
18#include "llvm/CodeGen/MachineFrameInfo.h"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000019#include "llvm/Analysis/AliasAnalysis.h"
20#include "llvm/Target/TargetData.h"
Chris Lattner1e3362f2008-01-26 19:45:50 +000021#include "llvm/Target/TargetFrameInfo.h"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000022#include "llvm/Target/TargetLowering.h"
23#include "llvm/Target/TargetMachine.h"
24#include "llvm/Target/TargetOptions.h"
25#include "llvm/ADT/SmallPtrSet.h"
26#include "llvm/ADT/Statistic.h"
27#include "llvm/Support/Compiler.h"
28#include "llvm/Support/CommandLine.h"
29#include "llvm/Support/Debug.h"
30#include "llvm/Support/MathExtras.h"
31#include <algorithm>
32using namespace llvm;
33
34STATISTIC(NodesCombined , "Number of dag nodes combined");
35STATISTIC(PreIndexedNodes , "Number of pre-indexed nodes created");
36STATISTIC(PostIndexedNodes, "Number of post-indexed nodes created");
37
38namespace {
39#ifndef NDEBUG
40 static cl::opt<bool>
41 ViewDAGCombine1("view-dag-combine1-dags", cl::Hidden,
42 cl::desc("Pop up a window to show dags before the first "
43 "dag combine pass"));
44 static cl::opt<bool>
45 ViewDAGCombine2("view-dag-combine2-dags", cl::Hidden,
46 cl::desc("Pop up a window to show dags before the second "
47 "dag combine pass"));
48#else
49 static const bool ViewDAGCombine1 = false;
50 static const bool ViewDAGCombine2 = false;
51#endif
52
53 static cl::opt<bool>
54 CombinerAA("combiner-alias-analysis", cl::Hidden,
55 cl::desc("Turn on alias analysis during testing"));
56
57 static cl::opt<bool>
58 CombinerGlobalAA("combiner-global-alias-analysis", cl::Hidden,
59 cl::desc("Include global information in alias analysis"));
60
61//------------------------------ DAGCombiner ---------------------------------//
62
63 class VISIBILITY_HIDDEN DAGCombiner {
64 SelectionDAG &DAG;
65 TargetLowering &TLI;
66 bool AfterLegalize;
67
68 // Worklist of all of the nodes that need to be simplified.
69 std::vector<SDNode*> WorkList;
70
71 // AA - Used for DAG load/store alias analysis.
72 AliasAnalysis &AA;
73
74 /// AddUsersToWorkList - When an instruction is simplified, add all users of
75 /// the instruction to the work lists because they might get more simplified
76 /// now.
77 ///
78 void AddUsersToWorkList(SDNode *N) {
79 for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
80 UI != UE; ++UI)
81 AddToWorkList(*UI);
82 }
83
Dan Gohman6c89ea72007-10-08 17:57:15 +000084 /// visit - call the node-specific routine that knows how to fold each
85 /// particular type of node.
86 SDOperand visit(SDNode *N);
87
Dan Gohmanf17a25c2007-07-18 16:29:46 +000088 public:
89 /// AddToWorkList - Add to the work list making sure it's instance is at the
90 /// the back (next to be processed.)
91 void AddToWorkList(SDNode *N) {
92 removeFromWorkList(N);
93 WorkList.push_back(N);
94 }
95
Chris Lattner7bcb18f2008-02-03 06:49:24 +000096 /// removeFromWorkList - remove all instances of N from the worklist.
97 ///
98 void removeFromWorkList(SDNode *N) {
99 WorkList.erase(std::remove(WorkList.begin(), WorkList.end(), N),
100 WorkList.end());
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000101 }
102
Chris Lattner7bcb18f2008-02-03 06:49:24 +0000103 SDOperand CombineTo(SDNode *N, const SDOperand *To, unsigned NumTo,
104 bool AddTo = true);
105
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000106 SDOperand CombineTo(SDNode *N, SDOperand Res, bool AddTo = true) {
107 return CombineTo(N, &Res, 1, AddTo);
108 }
109
110 SDOperand CombineTo(SDNode *N, SDOperand Res0, SDOperand Res1,
111 bool AddTo = true) {
112 SDOperand To[] = { Res0, Res1 };
113 return CombineTo(N, To, 2, AddTo);
114 }
Chris Lattner5872a362008-01-17 07:00:52 +0000115
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000116 private:
117
118 /// SimplifyDemandedBits - Check the specified integer node value to see if
119 /// it can be simplified or if things it uses can be simplified by bit
120 /// propagation. If so, return true.
Dan Gohman11607792008-02-27 00:25:32 +0000121 bool SimplifyDemandedBits(SDOperand Op) {
122 APInt Demanded = APInt::getAllOnesValue(Op.getValueSizeInBits());
123 return SimplifyDemandedBits(Op, Demanded);
124 }
125
126 bool SimplifyDemandedBits(SDOperand Op, const APInt &Demanded);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000127
128 bool CombineToPreIndexedLoadStore(SDNode *N);
129 bool CombineToPostIndexedLoadStore(SDNode *N);
130
131
Dan Gohman6c89ea72007-10-08 17:57:15 +0000132 /// combine - call the node-specific routine that knows how to fold each
133 /// particular type of node. If that doesn't do anything, try the
134 /// target-specific DAG combines.
135 SDOperand combine(SDNode *N);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000136
137 // Visitation implementation - Implement dag node combining for different
138 // node types. The semantics are as follows:
139 // Return Value:
140 // SDOperand.Val == 0 - No change was made
141 // SDOperand.Val == N - N was replaced, is dead, and is already handled.
142 // otherwise - N should be replaced by the returned Operand.
143 //
144 SDOperand visitTokenFactor(SDNode *N);
Chris Lattnerf32fa7f2008-02-13 07:25:05 +0000145 SDOperand visitMERGE_VALUES(SDNode *N);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000146 SDOperand visitADD(SDNode *N);
147 SDOperand visitSUB(SDNode *N);
148 SDOperand visitADDC(SDNode *N);
149 SDOperand visitADDE(SDNode *N);
150 SDOperand visitMUL(SDNode *N);
151 SDOperand visitSDIV(SDNode *N);
152 SDOperand visitUDIV(SDNode *N);
153 SDOperand visitSREM(SDNode *N);
154 SDOperand visitUREM(SDNode *N);
155 SDOperand visitMULHU(SDNode *N);
156 SDOperand visitMULHS(SDNode *N);
Dan Gohman6c89ea72007-10-08 17:57:15 +0000157 SDOperand visitSMUL_LOHI(SDNode *N);
158 SDOperand visitUMUL_LOHI(SDNode *N);
159 SDOperand visitSDIVREM(SDNode *N);
160 SDOperand visitUDIVREM(SDNode *N);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000161 SDOperand visitAND(SDNode *N);
162 SDOperand visitOR(SDNode *N);
163 SDOperand visitXOR(SDNode *N);
164 SDOperand SimplifyVBinOp(SDNode *N);
165 SDOperand visitSHL(SDNode *N);
166 SDOperand visitSRA(SDNode *N);
167 SDOperand visitSRL(SDNode *N);
168 SDOperand visitCTLZ(SDNode *N);
169 SDOperand visitCTTZ(SDNode *N);
170 SDOperand visitCTPOP(SDNode *N);
171 SDOperand visitSELECT(SDNode *N);
172 SDOperand visitSELECT_CC(SDNode *N);
173 SDOperand visitSETCC(SDNode *N);
174 SDOperand visitSIGN_EXTEND(SDNode *N);
175 SDOperand visitZERO_EXTEND(SDNode *N);
176 SDOperand visitANY_EXTEND(SDNode *N);
177 SDOperand visitSIGN_EXTEND_INREG(SDNode *N);
178 SDOperand visitTRUNCATE(SDNode *N);
179 SDOperand visitBIT_CONVERT(SDNode *N);
180 SDOperand visitFADD(SDNode *N);
181 SDOperand visitFSUB(SDNode *N);
182 SDOperand visitFMUL(SDNode *N);
183 SDOperand visitFDIV(SDNode *N);
184 SDOperand visitFREM(SDNode *N);
185 SDOperand visitFCOPYSIGN(SDNode *N);
186 SDOperand visitSINT_TO_FP(SDNode *N);
187 SDOperand visitUINT_TO_FP(SDNode *N);
188 SDOperand visitFP_TO_SINT(SDNode *N);
189 SDOperand visitFP_TO_UINT(SDNode *N);
190 SDOperand visitFP_ROUND(SDNode *N);
191 SDOperand visitFP_ROUND_INREG(SDNode *N);
192 SDOperand visitFP_EXTEND(SDNode *N);
193 SDOperand visitFNEG(SDNode *N);
194 SDOperand visitFABS(SDNode *N);
195 SDOperand visitBRCOND(SDNode *N);
196 SDOperand visitBR_CC(SDNode *N);
197 SDOperand visitLOAD(SDNode *N);
198 SDOperand visitSTORE(SDNode *N);
199 SDOperand visitINSERT_VECTOR_ELT(SDNode *N);
Evan Chengd7ba7ed2007-10-06 08:19:55 +0000200 SDOperand visitEXTRACT_VECTOR_ELT(SDNode *N);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000201 SDOperand visitBUILD_VECTOR(SDNode *N);
202 SDOperand visitCONCAT_VECTORS(SDNode *N);
203 SDOperand visitVECTOR_SHUFFLE(SDNode *N);
204
205 SDOperand XformToShuffleWithZero(SDNode *N);
206 SDOperand ReassociateOps(unsigned Opc, SDOperand LHS, SDOperand RHS);
207
Chris Lattner91ed3c32007-12-06 07:33:36 +0000208 SDOperand visitShiftByConstant(SDNode *N, unsigned Amt);
209
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000210 bool SimplifySelectOps(SDNode *SELECT, SDOperand LHS, SDOperand RHS);
211 SDOperand SimplifyBinOpWithSameOpcodeHands(SDNode *N);
212 SDOperand SimplifySelect(SDOperand N0, SDOperand N1, SDOperand N2);
213 SDOperand SimplifySelectCC(SDOperand N0, SDOperand N1, SDOperand N2,
214 SDOperand N3, ISD::CondCode CC,
215 bool NotExtCompare = false);
216 SDOperand SimplifySetCC(MVT::ValueType VT, SDOperand N0, SDOperand N1,
217 ISD::CondCode Cond, bool foldBooleans = true);
Chris Lattner4a7c8452008-01-26 01:09:19 +0000218 SDOperand SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp,
219 unsigned HiOp);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000220 SDOperand ConstantFoldBIT_CONVERTofBUILD_VECTOR(SDNode *, MVT::ValueType);
221 SDOperand BuildSDIV(SDNode *N);
222 SDOperand BuildUDIV(SDNode *N);
223 SDNode *MatchRotate(SDOperand LHS, SDOperand RHS);
224 SDOperand ReduceLoadWidth(SDNode *N);
225
Dan Gohman07961cd2008-02-25 21:11:39 +0000226 SDOperand GetDemandedBits(SDOperand V, const APInt &Mask);
Chris Lattnere8671c52007-10-13 06:35:54 +0000227
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000228 /// GatherAllAliases - Walk up chain skipping non-aliasing memory nodes,
229 /// looking for aliasing nodes and adding them to the Aliases vector.
230 void GatherAllAliases(SDNode *N, SDOperand OriginalChain,
231 SmallVector<SDOperand, 8> &Aliases);
232
233 /// isAlias - Return true if there is any possibility that the two addresses
234 /// overlap.
235 bool isAlias(SDOperand Ptr1, int64_t Size1,
236 const Value *SrcValue1, int SrcValueOffset1,
237 SDOperand Ptr2, int64_t Size2,
238 const Value *SrcValue2, int SrcValueOffset2);
239
240 /// FindAliasInfo - Extracts the relevant alias information from the memory
241 /// node. Returns true if the operand was a load.
242 bool FindAliasInfo(SDNode *N,
243 SDOperand &Ptr, int64_t &Size,
244 const Value *&SrcValue, int &SrcValueOffset);
245
246 /// FindBetterChain - Walk up chain skipping non-aliasing memory nodes,
247 /// looking for a better chain (aliasing node.)
248 SDOperand FindBetterChain(SDNode *N, SDOperand Chain);
249
250public:
251 DAGCombiner(SelectionDAG &D, AliasAnalysis &A)
252 : DAG(D),
253 TLI(D.getTargetLoweringInfo()),
254 AfterLegalize(false),
255 AA(A) {}
256
257 /// Run - runs the dag combiner on all nodes in the work list
258 void Run(bool RunningAfterLegalize);
259 };
260}
261
Chris Lattner7bcb18f2008-02-03 06:49:24 +0000262
263namespace {
264/// WorkListRemover - This class is a DAGUpdateListener that removes any deleted
265/// nodes from the worklist.
266class VISIBILITY_HIDDEN WorkListRemover :
267 public SelectionDAG::DAGUpdateListener {
268 DAGCombiner &DC;
269public:
Dan Gohmana789bff2008-02-20 16:44:09 +0000270 explicit WorkListRemover(DAGCombiner &dc) : DC(dc) {}
Chris Lattner7bcb18f2008-02-03 06:49:24 +0000271
272 virtual void NodeDeleted(SDNode *N) {
Chris Lattner7bcb18f2008-02-03 06:49:24 +0000273 DC.removeFromWorkList(N);
274 }
275
276 virtual void NodeUpdated(SDNode *N) {
277 // Ignore updates.
278 }
279};
280}
281
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000282//===----------------------------------------------------------------------===//
283// TargetLowering::DAGCombinerInfo implementation
284//===----------------------------------------------------------------------===//
285
286void TargetLowering::DAGCombinerInfo::AddToWorklist(SDNode *N) {
287 ((DAGCombiner*)DC)->AddToWorkList(N);
288}
289
290SDOperand TargetLowering::DAGCombinerInfo::
291CombineTo(SDNode *N, const std::vector<SDOperand> &To) {
292 return ((DAGCombiner*)DC)->CombineTo(N, &To[0], To.size());
293}
294
295SDOperand TargetLowering::DAGCombinerInfo::
296CombineTo(SDNode *N, SDOperand Res) {
297 return ((DAGCombiner*)DC)->CombineTo(N, Res);
298}
299
300
301SDOperand TargetLowering::DAGCombinerInfo::
302CombineTo(SDNode *N, SDOperand Res0, SDOperand Res1) {
303 return ((DAGCombiner*)DC)->CombineTo(N, Res0, Res1);
304}
305
306
307//===----------------------------------------------------------------------===//
308// Helper Functions
309//===----------------------------------------------------------------------===//
310
311/// isNegatibleForFree - Return 1 if we can compute the negated form of the
312/// specified expression for the same cost as the expression itself, or 2 if we
313/// can compute the negated form more cheaply than the expression itself.
Chris Lattnere0992b82008-02-26 07:04:54 +0000314static char isNegatibleForFree(SDOperand Op, bool AfterLegalize,
315 unsigned Depth = 0) {
Dale Johannesenb89072e2007-10-16 23:38:29 +0000316 // No compile time optimizations on this type.
317 if (Op.getValueType() == MVT::ppcf128)
318 return 0;
319
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000320 // fneg is removable even if it has multiple uses.
321 if (Op.getOpcode() == ISD::FNEG) return 2;
322
323 // Don't allow anything with multiple uses.
324 if (!Op.hasOneUse()) return 0;
325
326 // Don't recurse exponentially.
327 if (Depth > 6) return 0;
328
329 switch (Op.getOpcode()) {
330 default: return false;
331 case ISD::ConstantFP:
Chris Lattnere0992b82008-02-26 07:04:54 +0000332 // Don't invert constant FP values after legalize. The negated constant
333 // isn't necessarily legal.
334 return AfterLegalize ? 0 : 1;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000335 case ISD::FADD:
336 // FIXME: determine better conditions for this xform.
337 if (!UnsafeFPMath) return 0;
338
339 // -(A+B) -> -A - B
Chris Lattnere0992b82008-02-26 07:04:54 +0000340 if (char V = isNegatibleForFree(Op.getOperand(0), AfterLegalize, Depth+1))
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000341 return V;
342 // -(A+B) -> -B - A
Chris Lattnere0992b82008-02-26 07:04:54 +0000343 return isNegatibleForFree(Op.getOperand(1), AfterLegalize, Depth+1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000344 case ISD::FSUB:
345 // We can't turn -(A-B) into B-A when we honor signed zeros.
346 if (!UnsafeFPMath) return 0;
347
348 // -(A-B) -> B-A
349 return 1;
350
351 case ISD::FMUL:
352 case ISD::FDIV:
353 if (HonorSignDependentRoundingFPMath()) return 0;
354
355 // -(X*Y) -> (-X * Y) or (X*-Y)
Chris Lattnere0992b82008-02-26 07:04:54 +0000356 if (char V = isNegatibleForFree(Op.getOperand(0), AfterLegalize, Depth+1))
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000357 return V;
358
Chris Lattnere0992b82008-02-26 07:04:54 +0000359 return isNegatibleForFree(Op.getOperand(1), AfterLegalize, Depth+1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000360
361 case ISD::FP_EXTEND:
362 case ISD::FP_ROUND:
363 case ISD::FSIN:
Chris Lattnere0992b82008-02-26 07:04:54 +0000364 return isNegatibleForFree(Op.getOperand(0), AfterLegalize, Depth+1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000365 }
366}
367
368/// GetNegatedExpression - If isNegatibleForFree returns true, this function
369/// returns the newly negated expression.
370static SDOperand GetNegatedExpression(SDOperand Op, SelectionDAG &DAG,
Chris Lattnere0992b82008-02-26 07:04:54 +0000371 bool AfterLegalize, unsigned Depth = 0) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000372 // fneg is removable even if it has multiple uses.
373 if (Op.getOpcode() == ISD::FNEG) return Op.getOperand(0);
374
375 // Don't allow anything with multiple uses.
376 assert(Op.hasOneUse() && "Unknown reuse!");
377
378 assert(Depth <= 6 && "GetNegatedExpression doesn't match isNegatibleForFree");
379 switch (Op.getOpcode()) {
380 default: assert(0 && "Unknown code");
Dale Johannesen7604c1b2007-08-31 23:34:27 +0000381 case ISD::ConstantFP: {
382 APFloat V = cast<ConstantFPSDNode>(Op)->getValueAPF();
383 V.changeSign();
384 return DAG.getConstantFP(V, Op.getValueType());
385 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000386 case ISD::FADD:
387 // FIXME: determine better conditions for this xform.
388 assert(UnsafeFPMath);
389
390 // -(A+B) -> -A - B
Chris Lattnere0992b82008-02-26 07:04:54 +0000391 if (isNegatibleForFree(Op.getOperand(0), AfterLegalize, Depth+1))
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000392 return DAG.getNode(ISD::FSUB, Op.getValueType(),
Chris Lattnere0992b82008-02-26 07:04:54 +0000393 GetNegatedExpression(Op.getOperand(0), DAG,
394 AfterLegalize, Depth+1),
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000395 Op.getOperand(1));
396 // -(A+B) -> -B - A
397 return DAG.getNode(ISD::FSUB, Op.getValueType(),
Chris Lattnere0992b82008-02-26 07:04:54 +0000398 GetNegatedExpression(Op.getOperand(1), DAG,
399 AfterLegalize, Depth+1),
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000400 Op.getOperand(0));
401 case ISD::FSUB:
402 // We can't turn -(A-B) into B-A when we honor signed zeros.
403 assert(UnsafeFPMath);
404
405 // -(0-B) -> B
406 if (ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(Op.getOperand(0)))
Dale Johannesen7604c1b2007-08-31 23:34:27 +0000407 if (N0CFP->getValueAPF().isZero())
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000408 return Op.getOperand(1);
409
410 // -(A-B) -> B-A
411 return DAG.getNode(ISD::FSUB, Op.getValueType(), Op.getOperand(1),
412 Op.getOperand(0));
413
414 case ISD::FMUL:
415 case ISD::FDIV:
416 assert(!HonorSignDependentRoundingFPMath());
417
418 // -(X*Y) -> -X * Y
Chris Lattner46360032008-02-26 17:09:59 +0000419 if (isNegatibleForFree(Op.getOperand(0), AfterLegalize, Depth+1))
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000420 return DAG.getNode(Op.getOpcode(), Op.getValueType(),
Chris Lattnere0992b82008-02-26 07:04:54 +0000421 GetNegatedExpression(Op.getOperand(0), DAG,
422 AfterLegalize, Depth+1),
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000423 Op.getOperand(1));
424
425 // -(X*Y) -> X * -Y
426 return DAG.getNode(Op.getOpcode(), Op.getValueType(),
427 Op.getOperand(0),
Chris Lattnere0992b82008-02-26 07:04:54 +0000428 GetNegatedExpression(Op.getOperand(1), DAG,
429 AfterLegalize, Depth+1));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000430
431 case ISD::FP_EXTEND:
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000432 case ISD::FSIN:
433 return DAG.getNode(Op.getOpcode(), Op.getValueType(),
Chris Lattnere0992b82008-02-26 07:04:54 +0000434 GetNegatedExpression(Op.getOperand(0), DAG,
435 AfterLegalize, Depth+1));
Chris Lattner5872a362008-01-17 07:00:52 +0000436 case ISD::FP_ROUND:
437 return DAG.getNode(ISD::FP_ROUND, Op.getValueType(),
Chris Lattnere0992b82008-02-26 07:04:54 +0000438 GetNegatedExpression(Op.getOperand(0), DAG,
439 AfterLegalize, Depth+1),
Chris Lattner5872a362008-01-17 07:00:52 +0000440 Op.getOperand(1));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000441 }
442}
443
444
445// isSetCCEquivalent - Return true if this node is a setcc, or is a select_cc
446// that selects between the values 1 and 0, making it equivalent to a setcc.
447// Also, set the incoming LHS, RHS, and CC references to the appropriate
448// nodes based on the type of node we are checking. This simplifies life a
449// bit for the callers.
450static bool isSetCCEquivalent(SDOperand N, SDOperand &LHS, SDOperand &RHS,
451 SDOperand &CC) {
452 if (N.getOpcode() == ISD::SETCC) {
453 LHS = N.getOperand(0);
454 RHS = N.getOperand(1);
455 CC = N.getOperand(2);
456 return true;
457 }
458 if (N.getOpcode() == ISD::SELECT_CC &&
459 N.getOperand(2).getOpcode() == ISD::Constant &&
460 N.getOperand(3).getOpcode() == ISD::Constant &&
461 cast<ConstantSDNode>(N.getOperand(2))->getValue() == 1 &&
462 cast<ConstantSDNode>(N.getOperand(3))->isNullValue()) {
463 LHS = N.getOperand(0);
464 RHS = N.getOperand(1);
465 CC = N.getOperand(4);
466 return true;
467 }
468 return false;
469}
470
471// isOneUseSetCC - Return true if this is a SetCC-equivalent operation with only
472// one use. If this is true, it allows the users to invert the operation for
473// free when it is profitable to do so.
474static bool isOneUseSetCC(SDOperand N) {
475 SDOperand N0, N1, N2;
476 if (isSetCCEquivalent(N, N0, N1, N2) && N.Val->hasOneUse())
477 return true;
478 return false;
479}
480
481SDOperand DAGCombiner::ReassociateOps(unsigned Opc, SDOperand N0, SDOperand N1){
482 MVT::ValueType VT = N0.getValueType();
483 // reassoc. (op (op x, c1), y) -> (op (op x, y), c1) iff x+c1 has one use
484 // reassoc. (op (op x, c1), c2) -> (op x, (op c1, c2))
485 if (N0.getOpcode() == Opc && isa<ConstantSDNode>(N0.getOperand(1))) {
486 if (isa<ConstantSDNode>(N1)) {
487 SDOperand OpNode = DAG.getNode(Opc, VT, N0.getOperand(1), N1);
488 AddToWorkList(OpNode.Val);
489 return DAG.getNode(Opc, VT, OpNode, N0.getOperand(0));
490 } else if (N0.hasOneUse()) {
491 SDOperand OpNode = DAG.getNode(Opc, VT, N0.getOperand(0), N1);
492 AddToWorkList(OpNode.Val);
493 return DAG.getNode(Opc, VT, OpNode, N0.getOperand(1));
494 }
495 }
496 // reassoc. (op y, (op x, c1)) -> (op (op x, y), c1) iff x+c1 has one use
497 // reassoc. (op c2, (op x, c1)) -> (op x, (op c1, c2))
498 if (N1.getOpcode() == Opc && isa<ConstantSDNode>(N1.getOperand(1))) {
499 if (isa<ConstantSDNode>(N0)) {
500 SDOperand OpNode = DAG.getNode(Opc, VT, N1.getOperand(1), N0);
501 AddToWorkList(OpNode.Val);
502 return DAG.getNode(Opc, VT, OpNode, N1.getOperand(0));
503 } else if (N1.hasOneUse()) {
504 SDOperand OpNode = DAG.getNode(Opc, VT, N1.getOperand(0), N0);
505 AddToWorkList(OpNode.Val);
506 return DAG.getNode(Opc, VT, OpNode, N1.getOperand(1));
507 }
508 }
509 return SDOperand();
510}
511
Chris Lattner7bcb18f2008-02-03 06:49:24 +0000512SDOperand DAGCombiner::CombineTo(SDNode *N, const SDOperand *To, unsigned NumTo,
513 bool AddTo) {
514 assert(N->getNumValues() == NumTo && "Broken CombineTo call!");
515 ++NodesCombined;
516 DOUT << "\nReplacing.1 "; DEBUG(N->dump(&DAG));
517 DOUT << "\nWith: "; DEBUG(To[0].Val->dump(&DAG));
518 DOUT << " and " << NumTo-1 << " other values\n";
519 WorkListRemover DeadNodes(*this);
520 DAG.ReplaceAllUsesWith(N, To, &DeadNodes);
521
522 if (AddTo) {
523 // Push the new nodes and any users onto the worklist
524 for (unsigned i = 0, e = NumTo; i != e; ++i) {
525 AddToWorkList(To[i].Val);
526 AddUsersToWorkList(To[i].Val);
527 }
528 }
529
530 // Nodes can be reintroduced into the worklist. Make sure we do not
531 // process a node that has been replaced.
532 removeFromWorkList(N);
533
534 // Finally, since the node is now dead, remove it from the graph.
535 DAG.DeleteNode(N);
536 return SDOperand(N, 0);
537}
538
539/// SimplifyDemandedBits - Check the specified integer node value to see if
540/// it can be simplified or if things it uses can be simplified by bit
541/// propagation. If so, return true.
Dan Gohman11607792008-02-27 00:25:32 +0000542bool DAGCombiner::SimplifyDemandedBits(SDOperand Op, const APInt &Demanded) {
Chris Lattner7bcb18f2008-02-03 06:49:24 +0000543 TargetLowering::TargetLoweringOpt TLO(DAG, AfterLegalize);
Dan Gohman11607792008-02-27 00:25:32 +0000544 APInt KnownZero, KnownOne;
Chris Lattner7bcb18f2008-02-03 06:49:24 +0000545 if (!TLI.SimplifyDemandedBits(Op, Demanded, KnownZero, KnownOne, TLO))
546 return false;
547
548 // Revisit the node.
549 AddToWorkList(Op.Val);
550
551 // Replace the old value with the new one.
552 ++NodesCombined;
553 DOUT << "\nReplacing.2 "; DEBUG(TLO.Old.Val->dump(&DAG));
554 DOUT << "\nWith: "; DEBUG(TLO.New.Val->dump(&DAG));
555 DOUT << '\n';
556
557 // Replace all uses. If any nodes become isomorphic to other nodes and
558 // are deleted, make sure to remove them from our worklist.
559 WorkListRemover DeadNodes(*this);
560 DAG.ReplaceAllUsesOfValueWith(TLO.Old, TLO.New, &DeadNodes);
561
562 // Push the new node and any (possibly new) users onto the worklist.
563 AddToWorkList(TLO.New.Val);
564 AddUsersToWorkList(TLO.New.Val);
565
566 // Finally, if the node is now dead, remove it from the graph. The node
567 // may not be dead if the replacement process recursively simplified to
568 // something else needing this node.
569 if (TLO.Old.Val->use_empty()) {
570 removeFromWorkList(TLO.Old.Val);
571
572 // If the operands of this node are only used by the node, they will now
573 // be dead. Make sure to visit them first to delete dead nodes early.
574 for (unsigned i = 0, e = TLO.Old.Val->getNumOperands(); i != e; ++i)
575 if (TLO.Old.Val->getOperand(i).Val->hasOneUse())
576 AddToWorkList(TLO.Old.Val->getOperand(i).Val);
577
578 DAG.DeleteNode(TLO.Old.Val);
579 }
580 return true;
581}
582
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000583//===----------------------------------------------------------------------===//
584// Main DAG Combiner implementation
585//===----------------------------------------------------------------------===//
586
587void DAGCombiner::Run(bool RunningAfterLegalize) {
588 // set the instance variable, so that the various visit routines may use it.
589 AfterLegalize = RunningAfterLegalize;
590
591 // Add all the dag nodes to the worklist.
592 for (SelectionDAG::allnodes_iterator I = DAG.allnodes_begin(),
593 E = DAG.allnodes_end(); I != E; ++I)
594 WorkList.push_back(I);
595
596 // Create a dummy node (which is not added to allnodes), that adds a reference
597 // to the root node, preventing it from being deleted, and tracking any
598 // changes of the root.
599 HandleSDNode Dummy(DAG.getRoot());
600
601 // The root of the dag may dangle to deleted nodes until the dag combiner is
602 // done. Set it to null to avoid confusion.
603 DAG.setRoot(SDOperand());
604
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000605 // while the worklist isn't empty, inspect the node on the end of it and
606 // try and combine it.
607 while (!WorkList.empty()) {
608 SDNode *N = WorkList.back();
609 WorkList.pop_back();
610
611 // If N has no uses, it is dead. Make sure to revisit all N's operands once
612 // N is deleted from the DAG, since they too may now be dead or may have a
613 // reduced number of uses, allowing other xforms.
614 if (N->use_empty() && N != &Dummy) {
615 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
616 AddToWorkList(N->getOperand(i).Val);
617
618 DAG.DeleteNode(N);
619 continue;
620 }
621
Dan Gohman6c89ea72007-10-08 17:57:15 +0000622 SDOperand RV = combine(N);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000623
Chris Lattner20e53902008-01-25 23:34:24 +0000624 if (RV.Val == 0)
625 continue;
626
627 ++NodesCombined;
Chris Lattner4a7c8452008-01-26 01:09:19 +0000628
Chris Lattner20e53902008-01-25 23:34:24 +0000629 // If we get back the same node we passed in, rather than a new node or
630 // zero, we know that the node must have defined multiple values and
631 // CombineTo was used. Since CombineTo takes care of the worklist
632 // mechanics for us, we have no work to do in this case.
633 if (RV.Val == N)
634 continue;
635
636 assert(N->getOpcode() != ISD::DELETED_NODE &&
637 RV.Val->getOpcode() != ISD::DELETED_NODE &&
638 "Node was deleted but visit returned new node!");
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000639
Chris Lattner20e53902008-01-25 23:34:24 +0000640 DOUT << "\nReplacing.3 "; DEBUG(N->dump(&DAG));
641 DOUT << "\nWith: "; DEBUG(RV.Val->dump(&DAG));
642 DOUT << '\n';
Chris Lattner7bcb18f2008-02-03 06:49:24 +0000643 WorkListRemover DeadNodes(*this);
Chris Lattner20e53902008-01-25 23:34:24 +0000644 if (N->getNumValues() == RV.Val->getNumValues())
Chris Lattner7bcb18f2008-02-03 06:49:24 +0000645 DAG.ReplaceAllUsesWith(N, RV.Val, &DeadNodes);
Chris Lattner20e53902008-01-25 23:34:24 +0000646 else {
Chris Lattner4a7c8452008-01-26 01:09:19 +0000647 assert(N->getValueType(0) == RV.getValueType() &&
648 N->getNumValues() == 1 && "Type mismatch");
Chris Lattner20e53902008-01-25 23:34:24 +0000649 SDOperand OpV = RV;
Chris Lattner7bcb18f2008-02-03 06:49:24 +0000650 DAG.ReplaceAllUsesWith(N, &OpV, &DeadNodes);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000651 }
Chris Lattner20e53902008-01-25 23:34:24 +0000652
653 // Push the new node and any users onto the worklist
654 AddToWorkList(RV.Val);
655 AddUsersToWorkList(RV.Val);
656
657 // Add any uses of the old node to the worklist in case this node is the
658 // last one that uses them. They may become dead after this node is
659 // deleted.
660 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
661 AddToWorkList(N->getOperand(i).Val);
662
663 // Nodes can be reintroduced into the worklist. Make sure we do not
664 // process a node that has been replaced.
665 removeFromWorkList(N);
Chris Lattner20e53902008-01-25 23:34:24 +0000666
667 // Finally, since the node is now dead, remove it from the graph.
668 DAG.DeleteNode(N);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000669 }
670
671 // If the root changed (e.g. it was a dead load, update the root).
672 DAG.setRoot(Dummy.getValue());
673}
674
675SDOperand DAGCombiner::visit(SDNode *N) {
676 switch(N->getOpcode()) {
677 default: break;
678 case ISD::TokenFactor: return visitTokenFactor(N);
Chris Lattnerf32fa7f2008-02-13 07:25:05 +0000679 case ISD::MERGE_VALUES: return visitMERGE_VALUES(N);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000680 case ISD::ADD: return visitADD(N);
681 case ISD::SUB: return visitSUB(N);
682 case ISD::ADDC: return visitADDC(N);
683 case ISD::ADDE: return visitADDE(N);
684 case ISD::MUL: return visitMUL(N);
685 case ISD::SDIV: return visitSDIV(N);
686 case ISD::UDIV: return visitUDIV(N);
687 case ISD::SREM: return visitSREM(N);
688 case ISD::UREM: return visitUREM(N);
689 case ISD::MULHU: return visitMULHU(N);
690 case ISD::MULHS: return visitMULHS(N);
Dan Gohman6c89ea72007-10-08 17:57:15 +0000691 case ISD::SMUL_LOHI: return visitSMUL_LOHI(N);
692 case ISD::UMUL_LOHI: return visitUMUL_LOHI(N);
693 case ISD::SDIVREM: return visitSDIVREM(N);
694 case ISD::UDIVREM: return visitUDIVREM(N);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000695 case ISD::AND: return visitAND(N);
696 case ISD::OR: return visitOR(N);
697 case ISD::XOR: return visitXOR(N);
698 case ISD::SHL: return visitSHL(N);
699 case ISD::SRA: return visitSRA(N);
700 case ISD::SRL: return visitSRL(N);
701 case ISD::CTLZ: return visitCTLZ(N);
702 case ISD::CTTZ: return visitCTTZ(N);
703 case ISD::CTPOP: return visitCTPOP(N);
704 case ISD::SELECT: return visitSELECT(N);
705 case ISD::SELECT_CC: return visitSELECT_CC(N);
706 case ISD::SETCC: return visitSETCC(N);
707 case ISD::SIGN_EXTEND: return visitSIGN_EXTEND(N);
708 case ISD::ZERO_EXTEND: return visitZERO_EXTEND(N);
709 case ISD::ANY_EXTEND: return visitANY_EXTEND(N);
710 case ISD::SIGN_EXTEND_INREG: return visitSIGN_EXTEND_INREG(N);
711 case ISD::TRUNCATE: return visitTRUNCATE(N);
712 case ISD::BIT_CONVERT: return visitBIT_CONVERT(N);
713 case ISD::FADD: return visitFADD(N);
714 case ISD::FSUB: return visitFSUB(N);
715 case ISD::FMUL: return visitFMUL(N);
716 case ISD::FDIV: return visitFDIV(N);
717 case ISD::FREM: return visitFREM(N);
718 case ISD::FCOPYSIGN: return visitFCOPYSIGN(N);
719 case ISD::SINT_TO_FP: return visitSINT_TO_FP(N);
720 case ISD::UINT_TO_FP: return visitUINT_TO_FP(N);
721 case ISD::FP_TO_SINT: return visitFP_TO_SINT(N);
722 case ISD::FP_TO_UINT: return visitFP_TO_UINT(N);
723 case ISD::FP_ROUND: return visitFP_ROUND(N);
724 case ISD::FP_ROUND_INREG: return visitFP_ROUND_INREG(N);
725 case ISD::FP_EXTEND: return visitFP_EXTEND(N);
726 case ISD::FNEG: return visitFNEG(N);
727 case ISD::FABS: return visitFABS(N);
728 case ISD::BRCOND: return visitBRCOND(N);
729 case ISD::BR_CC: return visitBR_CC(N);
730 case ISD::LOAD: return visitLOAD(N);
731 case ISD::STORE: return visitSTORE(N);
732 case ISD::INSERT_VECTOR_ELT: return visitINSERT_VECTOR_ELT(N);
Evan Chengd7ba7ed2007-10-06 08:19:55 +0000733 case ISD::EXTRACT_VECTOR_ELT: return visitEXTRACT_VECTOR_ELT(N);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000734 case ISD::BUILD_VECTOR: return visitBUILD_VECTOR(N);
735 case ISD::CONCAT_VECTORS: return visitCONCAT_VECTORS(N);
736 case ISD::VECTOR_SHUFFLE: return visitVECTOR_SHUFFLE(N);
737 }
738 return SDOperand();
739}
740
Dan Gohman6c89ea72007-10-08 17:57:15 +0000741SDOperand DAGCombiner::combine(SDNode *N) {
742
743 SDOperand RV = visit(N);
744
745 // If nothing happened, try a target-specific DAG combine.
746 if (RV.Val == 0) {
747 assert(N->getOpcode() != ISD::DELETED_NODE &&
748 "Node was deleted but visit returned NULL!");
749
750 if (N->getOpcode() >= ISD::BUILTIN_OP_END ||
751 TLI.hasTargetDAGCombine((ISD::NodeType)N->getOpcode())) {
752
753 // Expose the DAG combiner to the target combiner impls.
754 TargetLowering::DAGCombinerInfo
755 DagCombineInfo(DAG, !AfterLegalize, false, this);
756
757 RV = TLI.PerformDAGCombine(N, DagCombineInfo);
758 }
759 }
760
761 return RV;
762}
763
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000764/// getInputChainForNode - Given a node, return its input chain if it has one,
765/// otherwise return a null sd operand.
766static SDOperand getInputChainForNode(SDNode *N) {
767 if (unsigned NumOps = N->getNumOperands()) {
768 if (N->getOperand(0).getValueType() == MVT::Other)
769 return N->getOperand(0);
770 else if (N->getOperand(NumOps-1).getValueType() == MVT::Other)
771 return N->getOperand(NumOps-1);
772 for (unsigned i = 1; i < NumOps-1; ++i)
773 if (N->getOperand(i).getValueType() == MVT::Other)
774 return N->getOperand(i);
775 }
776 return SDOperand(0, 0);
777}
778
779SDOperand DAGCombiner::visitTokenFactor(SDNode *N) {
780 // If N has two operands, where one has an input chain equal to the other,
781 // the 'other' chain is redundant.
782 if (N->getNumOperands() == 2) {
783 if (getInputChainForNode(N->getOperand(0).Val) == N->getOperand(1))
784 return N->getOperand(0);
785 if (getInputChainForNode(N->getOperand(1).Val) == N->getOperand(0))
786 return N->getOperand(1);
787 }
788
789 SmallVector<SDNode *, 8> TFs; // List of token factors to visit.
790 SmallVector<SDOperand, 8> Ops; // Ops for replacing token factor.
791 SmallPtrSet<SDNode*, 16> SeenOps;
792 bool Changed = false; // If we should replace this token factor.
793
794 // Start out with this token factor.
795 TFs.push_back(N);
796
797 // Iterate through token factors. The TFs grows when new token factors are
798 // encountered.
799 for (unsigned i = 0; i < TFs.size(); ++i) {
800 SDNode *TF = TFs[i];
801
802 // Check each of the operands.
803 for (unsigned i = 0, ie = TF->getNumOperands(); i != ie; ++i) {
804 SDOperand Op = TF->getOperand(i);
805
806 switch (Op.getOpcode()) {
807 case ISD::EntryToken:
808 // Entry tokens don't need to be added to the list. They are
809 // rededundant.
810 Changed = true;
811 break;
812
813 case ISD::TokenFactor:
814 if ((CombinerAA || Op.hasOneUse()) &&
815 std::find(TFs.begin(), TFs.end(), Op.Val) == TFs.end()) {
816 // Queue up for processing.
817 TFs.push_back(Op.Val);
818 // Clean up in case the token factor is removed.
819 AddToWorkList(Op.Val);
820 Changed = true;
821 break;
822 }
823 // Fall thru
824
825 default:
826 // Only add if it isn't already in the list.
827 if (SeenOps.insert(Op.Val))
828 Ops.push_back(Op);
829 else
830 Changed = true;
831 break;
832 }
833 }
834 }
835
836 SDOperand Result;
837
838 // If we've change things around then replace token factor.
839 if (Changed) {
Dan Gohman301f4052008-01-29 13:02:09 +0000840 if (Ops.empty()) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000841 // The entry token is the only possible outcome.
842 Result = DAG.getEntryNode();
843 } else {
844 // New and improved token factor.
845 Result = DAG.getNode(ISD::TokenFactor, MVT::Other, &Ops[0], Ops.size());
846 }
847
848 // Don't add users to work list.
849 return CombineTo(N, Result, false);
850 }
851
852 return Result;
853}
854
Chris Lattnerf32fa7f2008-02-13 07:25:05 +0000855/// MERGE_VALUES can always be eliminated.
856SDOperand DAGCombiner::visitMERGE_VALUES(SDNode *N) {
857 WorkListRemover DeadNodes(*this);
858 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
859 DAG.ReplaceAllUsesOfValueWith(SDOperand(N, i), N->getOperand(i),
860 &DeadNodes);
861 removeFromWorkList(N);
862 DAG.DeleteNode(N);
863 return SDOperand(N, 0); // Return N so it doesn't get rechecked!
864}
865
866
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000867static
868SDOperand combineShlAddConstant(SDOperand N0, SDOperand N1, SelectionDAG &DAG) {
869 MVT::ValueType VT = N0.getValueType();
870 SDOperand N00 = N0.getOperand(0);
871 SDOperand N01 = N0.getOperand(1);
872 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N01);
873 if (N01C && N00.getOpcode() == ISD::ADD && N00.Val->hasOneUse() &&
874 isa<ConstantSDNode>(N00.getOperand(1))) {
875 N0 = DAG.getNode(ISD::ADD, VT,
876 DAG.getNode(ISD::SHL, VT, N00.getOperand(0), N01),
877 DAG.getNode(ISD::SHL, VT, N00.getOperand(1), N01));
878 return DAG.getNode(ISD::ADD, VT, N0, N1);
879 }
880 return SDOperand();
881}
882
883static
884SDOperand combineSelectAndUse(SDNode *N, SDOperand Slct, SDOperand OtherOp,
885 SelectionDAG &DAG) {
886 MVT::ValueType VT = N->getValueType(0);
887 unsigned Opc = N->getOpcode();
888 bool isSlctCC = Slct.getOpcode() == ISD::SELECT_CC;
889 SDOperand LHS = isSlctCC ? Slct.getOperand(2) : Slct.getOperand(1);
890 SDOperand RHS = isSlctCC ? Slct.getOperand(3) : Slct.getOperand(2);
891 ISD::CondCode CC = ISD::SETCC_INVALID;
892 if (isSlctCC)
893 CC = cast<CondCodeSDNode>(Slct.getOperand(4))->get();
894 else {
895 SDOperand CCOp = Slct.getOperand(0);
896 if (CCOp.getOpcode() == ISD::SETCC)
897 CC = cast<CondCodeSDNode>(CCOp.getOperand(2))->get();
898 }
899
900 bool DoXform = false;
901 bool InvCC = false;
902 assert ((Opc == ISD::ADD || (Opc == ISD::SUB && Slct == N->getOperand(1))) &&
903 "Bad input!");
904 if (LHS.getOpcode() == ISD::Constant &&
905 cast<ConstantSDNode>(LHS)->isNullValue())
906 DoXform = true;
907 else if (CC != ISD::SETCC_INVALID &&
908 RHS.getOpcode() == ISD::Constant &&
909 cast<ConstantSDNode>(RHS)->isNullValue()) {
910 std::swap(LHS, RHS);
Chris Lattner667f9c12008-01-17 07:20:38 +0000911 SDOperand Op0 = Slct.getOperand(0);
912 bool isInt = MVT::isInteger(isSlctCC ? Op0.getValueType()
913 : Op0.getOperand(0).getValueType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000914 CC = ISD::getSetCCInverse(CC, isInt);
915 DoXform = true;
916 InvCC = true;
917 }
918
919 if (DoXform) {
920 SDOperand Result = DAG.getNode(Opc, VT, OtherOp, RHS);
921 if (isSlctCC)
922 return DAG.getSelectCC(OtherOp, Result,
923 Slct.getOperand(0), Slct.getOperand(1), CC);
924 SDOperand CCOp = Slct.getOperand(0);
925 if (InvCC)
926 CCOp = DAG.getSetCC(CCOp.getValueType(), CCOp.getOperand(0),
927 CCOp.getOperand(1), CC);
928 return DAG.getNode(ISD::SELECT, VT, CCOp, OtherOp, Result);
929 }
930 return SDOperand();
931}
932
933SDOperand DAGCombiner::visitADD(SDNode *N) {
934 SDOperand N0 = N->getOperand(0);
935 SDOperand N1 = N->getOperand(1);
936 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
937 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
938 MVT::ValueType VT = N0.getValueType();
939
940 // fold vector ops
941 if (MVT::isVector(VT)) {
942 SDOperand FoldedVOp = SimplifyVBinOp(N);
943 if (FoldedVOp.Val) return FoldedVOp;
944 }
945
946 // fold (add x, undef) -> undef
947 if (N0.getOpcode() == ISD::UNDEF)
948 return N0;
949 if (N1.getOpcode() == ISD::UNDEF)
950 return N1;
951 // fold (add c1, c2) -> c1+c2
952 if (N0C && N1C)
Bill Wendlinge58f7b82008-02-10 08:10:24 +0000953 return DAG.getConstant(N0C->getValue() + N1C->getValue(), VT);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000954 // canonicalize constant to RHS
955 if (N0C && !N1C)
956 return DAG.getNode(ISD::ADD, VT, N1, N0);
957 // fold (add x, 0) -> x
958 if (N1C && N1C->isNullValue())
959 return N0;
960 // fold ((c1-A)+c2) -> (c1+c2)-A
961 if (N1C && N0.getOpcode() == ISD::SUB)
962 if (ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getOperand(0)))
963 return DAG.getNode(ISD::SUB, VT,
964 DAG.getConstant(N1C->getValue()+N0C->getValue(), VT),
965 N0.getOperand(1));
966 // reassociate add
967 SDOperand RADD = ReassociateOps(ISD::ADD, N0, N1);
968 if (RADD.Val != 0)
969 return RADD;
970 // fold ((0-A) + B) -> B-A
971 if (N0.getOpcode() == ISD::SUB && isa<ConstantSDNode>(N0.getOperand(0)) &&
972 cast<ConstantSDNode>(N0.getOperand(0))->isNullValue())
973 return DAG.getNode(ISD::SUB, VT, N1, N0.getOperand(1));
974 // fold (A + (0-B)) -> A-B
975 if (N1.getOpcode() == ISD::SUB && isa<ConstantSDNode>(N1.getOperand(0)) &&
976 cast<ConstantSDNode>(N1.getOperand(0))->isNullValue())
977 return DAG.getNode(ISD::SUB, VT, N0, N1.getOperand(1));
978 // fold (A+(B-A)) -> B
979 if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(1))
980 return N1.getOperand(0);
981
982 if (!MVT::isVector(VT) && SimplifyDemandedBits(SDOperand(N, 0)))
983 return SDOperand(N, 0);
984
985 // fold (a+b) -> (a|b) iff a and b share no bits.
986 if (MVT::isInteger(VT) && !MVT::isVector(VT)) {
Dan Gohmanbea075f2008-02-20 16:33:30 +0000987 APInt LHSZero, LHSOne;
988 APInt RHSZero, RHSOne;
989 APInt Mask = APInt::getAllOnesValue(MVT::getSizeInBits(VT));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000990 DAG.ComputeMaskedBits(N0, Mask, LHSZero, LHSOne);
Dan Gohmanbea075f2008-02-20 16:33:30 +0000991 if (LHSZero.getBoolValue()) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000992 DAG.ComputeMaskedBits(N1, Mask, RHSZero, RHSOne);
993
994 // If all possibly-set bits on the LHS are clear on the RHS, return an OR.
995 // If all possibly-set bits on the RHS are clear on the LHS, return an OR.
996 if ((RHSZero & (~LHSZero & Mask)) == (~LHSZero & Mask) ||
997 (LHSZero & (~RHSZero & Mask)) == (~RHSZero & Mask))
998 return DAG.getNode(ISD::OR, VT, N0, N1);
999 }
1000 }
1001
1002 // fold (add (shl (add x, c1), c2), ) -> (add (add (shl x, c2), c1<<c2), )
1003 if (N0.getOpcode() == ISD::SHL && N0.Val->hasOneUse()) {
1004 SDOperand Result = combineShlAddConstant(N0, N1, DAG);
1005 if (Result.Val) return Result;
1006 }
1007 if (N1.getOpcode() == ISD::SHL && N1.Val->hasOneUse()) {
1008 SDOperand Result = combineShlAddConstant(N1, N0, DAG);
1009 if (Result.Val) return Result;
1010 }
1011
1012 // fold (add (select cc, 0, c), x) -> (select cc, x, (add, x, c))
1013 if (N0.getOpcode() == ISD::SELECT && N0.Val->hasOneUse()) {
1014 SDOperand Result = combineSelectAndUse(N, N0, N1, DAG);
1015 if (Result.Val) return Result;
1016 }
1017 if (N1.getOpcode() == ISD::SELECT && N1.Val->hasOneUse()) {
1018 SDOperand Result = combineSelectAndUse(N, N1, N0, DAG);
1019 if (Result.Val) return Result;
1020 }
1021
1022 return SDOperand();
1023}
1024
1025SDOperand DAGCombiner::visitADDC(SDNode *N) {
1026 SDOperand N0 = N->getOperand(0);
1027 SDOperand N1 = N->getOperand(1);
1028 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1029 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1030 MVT::ValueType VT = N0.getValueType();
1031
1032 // If the flag result is dead, turn this into an ADD.
1033 if (N->hasNUsesOfValue(0, 1))
1034 return CombineTo(N, DAG.getNode(ISD::ADD, VT, N1, N0),
1035 DAG.getNode(ISD::CARRY_FALSE, MVT::Flag));
1036
1037 // canonicalize constant to RHS.
1038 if (N0C && !N1C) {
1039 SDOperand Ops[] = { N1, N0 };
1040 return DAG.getNode(ISD::ADDC, N->getVTList(), Ops, 2);
1041 }
1042
1043 // fold (addc x, 0) -> x + no carry out
1044 if (N1C && N1C->isNullValue())
1045 return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE, MVT::Flag));
1046
1047 // fold (addc a, b) -> (or a, b), CARRY_FALSE iff a and b share no bits.
Dan Gohmanbea075f2008-02-20 16:33:30 +00001048 APInt LHSZero, LHSOne;
1049 APInt RHSZero, RHSOne;
1050 APInt Mask = APInt::getAllOnesValue(MVT::getSizeInBits(VT));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001051 DAG.ComputeMaskedBits(N0, Mask, LHSZero, LHSOne);
Dan Gohmanbea075f2008-02-20 16:33:30 +00001052 if (LHSZero.getBoolValue()) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001053 DAG.ComputeMaskedBits(N1, Mask, RHSZero, RHSOne);
1054
1055 // If all possibly-set bits on the LHS are clear on the RHS, return an OR.
1056 // If all possibly-set bits on the RHS are clear on the LHS, return an OR.
1057 if ((RHSZero & (~LHSZero & Mask)) == (~LHSZero & Mask) ||
1058 (LHSZero & (~RHSZero & Mask)) == (~RHSZero & Mask))
1059 return CombineTo(N, DAG.getNode(ISD::OR, VT, N0, N1),
1060 DAG.getNode(ISD::CARRY_FALSE, MVT::Flag));
1061 }
1062
1063 return SDOperand();
1064}
1065
1066SDOperand DAGCombiner::visitADDE(SDNode *N) {
1067 SDOperand N0 = N->getOperand(0);
1068 SDOperand N1 = N->getOperand(1);
1069 SDOperand CarryIn = N->getOperand(2);
1070 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1071 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1072 //MVT::ValueType VT = N0.getValueType();
1073
1074 // canonicalize constant to RHS
1075 if (N0C && !N1C) {
1076 SDOperand Ops[] = { N1, N0, CarryIn };
1077 return DAG.getNode(ISD::ADDE, N->getVTList(), Ops, 3);
1078 }
1079
1080 // fold (adde x, y, false) -> (addc x, y)
1081 if (CarryIn.getOpcode() == ISD::CARRY_FALSE) {
1082 SDOperand Ops[] = { N1, N0 };
1083 return DAG.getNode(ISD::ADDC, N->getVTList(), Ops, 2);
1084 }
1085
1086 return SDOperand();
1087}
1088
1089
1090
1091SDOperand DAGCombiner::visitSUB(SDNode *N) {
1092 SDOperand N0 = N->getOperand(0);
1093 SDOperand N1 = N->getOperand(1);
1094 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.Val);
1095 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.Val);
1096 MVT::ValueType VT = N0.getValueType();
1097
1098 // fold vector ops
1099 if (MVT::isVector(VT)) {
1100 SDOperand FoldedVOp = SimplifyVBinOp(N);
1101 if (FoldedVOp.Val) return FoldedVOp;
1102 }
1103
1104 // fold (sub x, x) -> 0
Evan Chengba0f30f2008-03-10 07:59:01 +00001105 if (N0 == N1) {
Evan Cheng74b7f7b2008-03-12 02:05:05 +00001106 if (AfterLegalize && ISD::isBuildVectorAllZeros(N0.Val))
Evan Chengcf31b8d2008-03-10 19:58:22 +00001107 // For example, zero vectors might be normalized to a particular vector
1108 // type to ensure they are CSE'd. Avoid issuing zero vector nodes of
1109 // *unexpected* type after legalization.
Evan Cheng86280672008-03-10 07:19:13 +00001110 return N0;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001111 return DAG.getConstant(0, N->getValueType(0));
Evan Chengba0f30f2008-03-10 07:59:01 +00001112 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001113 // fold (sub c1, c2) -> c1-c2
1114 if (N0C && N1C)
1115 return DAG.getNode(ISD::SUB, VT, N0, N1);
1116 // fold (sub x, c) -> (add x, -c)
1117 if (N1C)
1118 return DAG.getNode(ISD::ADD, VT, N0, DAG.getConstant(-N1C->getValue(), VT));
1119 // fold (A+B)-A -> B
1120 if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1)
1121 return N0.getOperand(1);
1122 // fold (A+B)-B -> A
1123 if (N0.getOpcode() == ISD::ADD && N0.getOperand(1) == N1)
1124 return N0.getOperand(0);
1125 // fold (sub x, (select cc, 0, c)) -> (select cc, x, (sub, x, c))
1126 if (N1.getOpcode() == ISD::SELECT && N1.Val->hasOneUse()) {
1127 SDOperand Result = combineSelectAndUse(N, N1, N0, DAG);
1128 if (Result.Val) return Result;
1129 }
1130 // If either operand of a sub is undef, the result is undef
1131 if (N0.getOpcode() == ISD::UNDEF)
1132 return N0;
1133 if (N1.getOpcode() == ISD::UNDEF)
1134 return N1;
1135
1136 return SDOperand();
1137}
1138
1139SDOperand DAGCombiner::visitMUL(SDNode *N) {
1140 SDOperand N0 = N->getOperand(0);
1141 SDOperand N1 = N->getOperand(1);
1142 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1143 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1144 MVT::ValueType VT = N0.getValueType();
1145
1146 // fold vector ops
1147 if (MVT::isVector(VT)) {
1148 SDOperand FoldedVOp = SimplifyVBinOp(N);
1149 if (FoldedVOp.Val) return FoldedVOp;
1150 }
1151
1152 // fold (mul x, undef) -> 0
1153 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
1154 return DAG.getConstant(0, VT);
1155 // fold (mul c1, c2) -> c1*c2
1156 if (N0C && N1C)
1157 return DAG.getNode(ISD::MUL, VT, N0, N1);
1158 // canonicalize constant to RHS
1159 if (N0C && !N1C)
1160 return DAG.getNode(ISD::MUL, VT, N1, N0);
1161 // fold (mul x, 0) -> 0
1162 if (N1C && N1C->isNullValue())
1163 return N1;
1164 // fold (mul x, -1) -> 0-x
1165 if (N1C && N1C->isAllOnesValue())
1166 return DAG.getNode(ISD::SUB, VT, DAG.getConstant(0, VT), N0);
1167 // fold (mul x, (1 << c)) -> x << c
1168 if (N1C && isPowerOf2_64(N1C->getValue()))
1169 return DAG.getNode(ISD::SHL, VT, N0,
1170 DAG.getConstant(Log2_64(N1C->getValue()),
1171 TLI.getShiftAmountTy()));
1172 // fold (mul x, -(1 << c)) -> -(x << c) or (-x) << c
1173 if (N1C && isPowerOf2_64(-N1C->getSignExtended())) {
1174 // FIXME: If the input is something that is easily negated (e.g. a
1175 // single-use add), we should put the negate there.
1176 return DAG.getNode(ISD::SUB, VT, DAG.getConstant(0, VT),
1177 DAG.getNode(ISD::SHL, VT, N0,
1178 DAG.getConstant(Log2_64(-N1C->getSignExtended()),
1179 TLI.getShiftAmountTy())));
1180 }
1181
1182 // (mul (shl X, c1), c2) -> (mul X, c2 << c1)
1183 if (N1C && N0.getOpcode() == ISD::SHL &&
1184 isa<ConstantSDNode>(N0.getOperand(1))) {
1185 SDOperand C3 = DAG.getNode(ISD::SHL, VT, N1, N0.getOperand(1));
1186 AddToWorkList(C3.Val);
1187 return DAG.getNode(ISD::MUL, VT, N0.getOperand(0), C3);
1188 }
1189
1190 // Change (mul (shl X, C), Y) -> (shl (mul X, Y), C) when the shift has one
1191 // use.
1192 {
1193 SDOperand Sh(0,0), Y(0,0);
1194 // Check for both (mul (shl X, C), Y) and (mul Y, (shl X, C)).
1195 if (N0.getOpcode() == ISD::SHL && isa<ConstantSDNode>(N0.getOperand(1)) &&
1196 N0.Val->hasOneUse()) {
1197 Sh = N0; Y = N1;
1198 } else if (N1.getOpcode() == ISD::SHL &&
1199 isa<ConstantSDNode>(N1.getOperand(1)) && N1.Val->hasOneUse()) {
1200 Sh = N1; Y = N0;
1201 }
1202 if (Sh.Val) {
1203 SDOperand Mul = DAG.getNode(ISD::MUL, VT, Sh.getOperand(0), Y);
1204 return DAG.getNode(ISD::SHL, VT, Mul, Sh.getOperand(1));
1205 }
1206 }
1207 // fold (mul (add x, c1), c2) -> (add (mul x, c2), c1*c2)
1208 if (N1C && N0.getOpcode() == ISD::ADD && N0.Val->hasOneUse() &&
1209 isa<ConstantSDNode>(N0.getOperand(1))) {
1210 return DAG.getNode(ISD::ADD, VT,
1211 DAG.getNode(ISD::MUL, VT, N0.getOperand(0), N1),
1212 DAG.getNode(ISD::MUL, VT, N0.getOperand(1), N1));
1213 }
1214
1215 // reassociate mul
1216 SDOperand RMUL = ReassociateOps(ISD::MUL, N0, N1);
1217 if (RMUL.Val != 0)
1218 return RMUL;
1219
1220 return SDOperand();
1221}
1222
1223SDOperand DAGCombiner::visitSDIV(SDNode *N) {
1224 SDOperand N0 = N->getOperand(0);
1225 SDOperand N1 = N->getOperand(1);
1226 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.Val);
1227 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.Val);
1228 MVT::ValueType VT = N->getValueType(0);
1229
1230 // fold vector ops
1231 if (MVT::isVector(VT)) {
1232 SDOperand FoldedVOp = SimplifyVBinOp(N);
1233 if (FoldedVOp.Val) return FoldedVOp;
1234 }
1235
1236 // fold (sdiv c1, c2) -> c1/c2
1237 if (N0C && N1C && !N1C->isNullValue())
1238 return DAG.getNode(ISD::SDIV, VT, N0, N1);
1239 // fold (sdiv X, 1) -> X
1240 if (N1C && N1C->getSignExtended() == 1LL)
1241 return N0;
1242 // fold (sdiv X, -1) -> 0-X
1243 if (N1C && N1C->isAllOnesValue())
1244 return DAG.getNode(ISD::SUB, VT, DAG.getConstant(0, VT), N0);
1245 // If we know the sign bits of both operands are zero, strength reduce to a
1246 // udiv instead. Handles (X&15) /s 4 -> X&15 >> 2
Chris Lattner336672f2008-01-27 23:32:17 +00001247 if (!MVT::isVector(VT)) {
Dan Gohman07961cd2008-02-25 21:11:39 +00001248 if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
Chris Lattner336672f2008-01-27 23:32:17 +00001249 return DAG.getNode(ISD::UDIV, N1.getValueType(), N0, N1);
1250 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001251 // fold (sdiv X, pow2) -> simple ops after legalize
1252 if (N1C && N1C->getValue() && !TLI.isIntDivCheap() &&
1253 (isPowerOf2_64(N1C->getSignExtended()) ||
1254 isPowerOf2_64(-N1C->getSignExtended()))) {
1255 // If dividing by powers of two is cheap, then don't perform the following
1256 // fold.
1257 if (TLI.isPow2DivCheap())
1258 return SDOperand();
1259 int64_t pow2 = N1C->getSignExtended();
1260 int64_t abs2 = pow2 > 0 ? pow2 : -pow2;
1261 unsigned lg2 = Log2_64(abs2);
1262 // Splat the sign bit into the register
1263 SDOperand SGN = DAG.getNode(ISD::SRA, VT, N0,
1264 DAG.getConstant(MVT::getSizeInBits(VT)-1,
1265 TLI.getShiftAmountTy()));
1266 AddToWorkList(SGN.Val);
1267 // Add (N0 < 0) ? abs2 - 1 : 0;
1268 SDOperand SRL = DAG.getNode(ISD::SRL, VT, SGN,
1269 DAG.getConstant(MVT::getSizeInBits(VT)-lg2,
1270 TLI.getShiftAmountTy()));
1271 SDOperand ADD = DAG.getNode(ISD::ADD, VT, N0, SRL);
1272 AddToWorkList(SRL.Val);
1273 AddToWorkList(ADD.Val); // Divide by pow2
1274 SDOperand SRA = DAG.getNode(ISD::SRA, VT, ADD,
1275 DAG.getConstant(lg2, TLI.getShiftAmountTy()));
1276 // If we're dividing by a positive value, we're done. Otherwise, we must
1277 // negate the result.
1278 if (pow2 > 0)
1279 return SRA;
1280 AddToWorkList(SRA.Val);
1281 return DAG.getNode(ISD::SUB, VT, DAG.getConstant(0, VT), SRA);
1282 }
1283 // if integer divide is expensive and we satisfy the requirements, emit an
1284 // alternate sequence.
1285 if (N1C && (N1C->getSignExtended() < -1 || N1C->getSignExtended() > 1) &&
1286 !TLI.isIntDivCheap()) {
1287 SDOperand Op = BuildSDIV(N);
1288 if (Op.Val) return Op;
1289 }
1290
1291 // undef / X -> 0
1292 if (N0.getOpcode() == ISD::UNDEF)
1293 return DAG.getConstant(0, VT);
1294 // X / undef -> undef
1295 if (N1.getOpcode() == ISD::UNDEF)
1296 return N1;
1297
1298 return SDOperand();
1299}
1300
1301SDOperand DAGCombiner::visitUDIV(SDNode *N) {
1302 SDOperand N0 = N->getOperand(0);
1303 SDOperand N1 = N->getOperand(1);
1304 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.Val);
1305 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.Val);
1306 MVT::ValueType VT = N->getValueType(0);
1307
1308 // fold vector ops
1309 if (MVT::isVector(VT)) {
1310 SDOperand FoldedVOp = SimplifyVBinOp(N);
1311 if (FoldedVOp.Val) return FoldedVOp;
1312 }
1313
1314 // fold (udiv c1, c2) -> c1/c2
1315 if (N0C && N1C && !N1C->isNullValue())
1316 return DAG.getNode(ISD::UDIV, VT, N0, N1);
1317 // fold (udiv x, (1 << c)) -> x >>u c
1318 if (N1C && isPowerOf2_64(N1C->getValue()))
1319 return DAG.getNode(ISD::SRL, VT, N0,
1320 DAG.getConstant(Log2_64(N1C->getValue()),
1321 TLI.getShiftAmountTy()));
1322 // fold (udiv x, (shl c, y)) -> x >>u (log2(c)+y) iff c is power of 2
1323 if (N1.getOpcode() == ISD::SHL) {
1324 if (ConstantSDNode *SHC = dyn_cast<ConstantSDNode>(N1.getOperand(0))) {
1325 if (isPowerOf2_64(SHC->getValue())) {
1326 MVT::ValueType ADDVT = N1.getOperand(1).getValueType();
1327 SDOperand Add = DAG.getNode(ISD::ADD, ADDVT, N1.getOperand(1),
1328 DAG.getConstant(Log2_64(SHC->getValue()),
1329 ADDVT));
1330 AddToWorkList(Add.Val);
1331 return DAG.getNode(ISD::SRL, VT, N0, Add);
1332 }
1333 }
1334 }
1335 // fold (udiv x, c) -> alternate
1336 if (N1C && N1C->getValue() && !TLI.isIntDivCheap()) {
1337 SDOperand Op = BuildUDIV(N);
1338 if (Op.Val) return Op;
1339 }
1340
1341 // undef / X -> 0
1342 if (N0.getOpcode() == ISD::UNDEF)
1343 return DAG.getConstant(0, VT);
1344 // X / undef -> undef
1345 if (N1.getOpcode() == ISD::UNDEF)
1346 return N1;
1347
1348 return SDOperand();
1349}
1350
1351SDOperand DAGCombiner::visitSREM(SDNode *N) {
1352 SDOperand N0 = N->getOperand(0);
1353 SDOperand N1 = N->getOperand(1);
1354 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1355 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1356 MVT::ValueType VT = N->getValueType(0);
1357
1358 // fold (srem c1, c2) -> c1%c2
1359 if (N0C && N1C && !N1C->isNullValue())
1360 return DAG.getNode(ISD::SREM, VT, N0, N1);
1361 // If we know the sign bits of both operands are zero, strength reduce to a
1362 // urem instead. Handles (X & 0x0FFFFFFF) %s 16 -> X&15
Chris Lattnerce602f52008-01-27 23:21:58 +00001363 if (!MVT::isVector(VT)) {
Dan Gohman07961cd2008-02-25 21:11:39 +00001364 if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
Chris Lattnerce602f52008-01-27 23:21:58 +00001365 return DAG.getNode(ISD::UREM, VT, N0, N1);
1366 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001367
Dan Gohmanfdb31f12007-11-26 23:46:11 +00001368 // If X/C can be simplified by the division-by-constant logic, lower
1369 // X%C to the equivalent of X-X/C*C.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001370 if (N1C && !N1C->isNullValue()) {
1371 SDOperand Div = DAG.getNode(ISD::SDIV, VT, N0, N1);
Chris Lattner4a7c8452008-01-26 01:09:19 +00001372 AddToWorkList(Div.Val);
Dan Gohmanfdb31f12007-11-26 23:46:11 +00001373 SDOperand OptimizedDiv = combine(Div.Val);
1374 if (OptimizedDiv.Val && OptimizedDiv.Val != Div.Val) {
1375 SDOperand Mul = DAG.getNode(ISD::MUL, VT, OptimizedDiv, N1);
1376 SDOperand Sub = DAG.getNode(ISD::SUB, VT, N0, Mul);
1377 AddToWorkList(Mul.Val);
1378 return Sub;
1379 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001380 }
1381
1382 // undef % X -> 0
1383 if (N0.getOpcode() == ISD::UNDEF)
1384 return DAG.getConstant(0, VT);
1385 // X % undef -> undef
1386 if (N1.getOpcode() == ISD::UNDEF)
1387 return N1;
1388
1389 return SDOperand();
1390}
1391
1392SDOperand DAGCombiner::visitUREM(SDNode *N) {
1393 SDOperand N0 = N->getOperand(0);
1394 SDOperand N1 = N->getOperand(1);
1395 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1396 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1397 MVT::ValueType VT = N->getValueType(0);
1398
1399 // fold (urem c1, c2) -> c1%c2
1400 if (N0C && N1C && !N1C->isNullValue())
1401 return DAG.getNode(ISD::UREM, VT, N0, N1);
1402 // fold (urem x, pow2) -> (and x, pow2-1)
1403 if (N1C && !N1C->isNullValue() && isPowerOf2_64(N1C->getValue()))
1404 return DAG.getNode(ISD::AND, VT, N0, DAG.getConstant(N1C->getValue()-1,VT));
1405 // fold (urem x, (shl pow2, y)) -> (and x, (add (shl pow2, y), -1))
1406 if (N1.getOpcode() == ISD::SHL) {
1407 if (ConstantSDNode *SHC = dyn_cast<ConstantSDNode>(N1.getOperand(0))) {
1408 if (isPowerOf2_64(SHC->getValue())) {
1409 SDOperand Add = DAG.getNode(ISD::ADD, VT, N1,DAG.getConstant(~0ULL,VT));
1410 AddToWorkList(Add.Val);
1411 return DAG.getNode(ISD::AND, VT, N0, Add);
1412 }
1413 }
1414 }
1415
Dan Gohmanfdb31f12007-11-26 23:46:11 +00001416 // If X/C can be simplified by the division-by-constant logic, lower
1417 // X%C to the equivalent of X-X/C*C.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001418 if (N1C && !N1C->isNullValue()) {
1419 SDOperand Div = DAG.getNode(ISD::UDIV, VT, N0, N1);
Dan Gohmanfdb31f12007-11-26 23:46:11 +00001420 SDOperand OptimizedDiv = combine(Div.Val);
1421 if (OptimizedDiv.Val && OptimizedDiv.Val != Div.Val) {
1422 SDOperand Mul = DAG.getNode(ISD::MUL, VT, OptimizedDiv, N1);
1423 SDOperand Sub = DAG.getNode(ISD::SUB, VT, N0, Mul);
1424 AddToWorkList(Mul.Val);
1425 return Sub;
1426 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001427 }
1428
1429 // undef % X -> 0
1430 if (N0.getOpcode() == ISD::UNDEF)
1431 return DAG.getConstant(0, VT);
1432 // X % undef -> undef
1433 if (N1.getOpcode() == ISD::UNDEF)
1434 return N1;
1435
1436 return SDOperand();
1437}
1438
1439SDOperand DAGCombiner::visitMULHS(SDNode *N) {
1440 SDOperand N0 = N->getOperand(0);
1441 SDOperand N1 = N->getOperand(1);
1442 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1443 MVT::ValueType VT = N->getValueType(0);
1444
1445 // fold (mulhs x, 0) -> 0
1446 if (N1C && N1C->isNullValue())
1447 return N1;
1448 // fold (mulhs x, 1) -> (sra x, size(x)-1)
1449 if (N1C && N1C->getValue() == 1)
1450 return DAG.getNode(ISD::SRA, N0.getValueType(), N0,
1451 DAG.getConstant(MVT::getSizeInBits(N0.getValueType())-1,
1452 TLI.getShiftAmountTy()));
1453 // fold (mulhs x, undef) -> 0
1454 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
1455 return DAG.getConstant(0, VT);
1456
1457 return SDOperand();
1458}
1459
1460SDOperand DAGCombiner::visitMULHU(SDNode *N) {
1461 SDOperand N0 = N->getOperand(0);
1462 SDOperand N1 = N->getOperand(1);
1463 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1464 MVT::ValueType VT = N->getValueType(0);
1465
1466 // fold (mulhu x, 0) -> 0
1467 if (N1C && N1C->isNullValue())
1468 return N1;
1469 // fold (mulhu x, 1) -> 0
1470 if (N1C && N1C->getValue() == 1)
1471 return DAG.getConstant(0, N0.getValueType());
1472 // fold (mulhu x, undef) -> 0
1473 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
1474 return DAG.getConstant(0, VT);
1475
1476 return SDOperand();
1477}
1478
Dan Gohman6c89ea72007-10-08 17:57:15 +00001479/// SimplifyNodeWithTwoResults - Perform optimizations common to nodes that
1480/// compute two values. LoOp and HiOp give the opcodes for the two computations
1481/// that are being performed. Return true if a simplification was made.
1482///
Chris Lattner4a7c8452008-01-26 01:09:19 +00001483SDOperand DAGCombiner::SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp,
1484 unsigned HiOp) {
Dan Gohman6c89ea72007-10-08 17:57:15 +00001485 // If the high half is not needed, just compute the low half.
Evan Chengddfa8c72007-11-08 09:25:29 +00001486 bool HiExists = N->hasAnyUseOfValue(1);
1487 if (!HiExists &&
Dan Gohman6c89ea72007-10-08 17:57:15 +00001488 (!AfterLegalize ||
1489 TLI.isOperationLegal(LoOp, N->getValueType(0)))) {
Chris Lattner4a7c8452008-01-26 01:09:19 +00001490 SDOperand Res = DAG.getNode(LoOp, N->getValueType(0), N->op_begin(),
1491 N->getNumOperands());
1492 return CombineTo(N, Res, Res);
Dan Gohman6c89ea72007-10-08 17:57:15 +00001493 }
1494
1495 // If the low half is not needed, just compute the high half.
Evan Chengddfa8c72007-11-08 09:25:29 +00001496 bool LoExists = N->hasAnyUseOfValue(0);
1497 if (!LoExists &&
Dan Gohman6c89ea72007-10-08 17:57:15 +00001498 (!AfterLegalize ||
1499 TLI.isOperationLegal(HiOp, N->getValueType(1)))) {
Chris Lattner4a7c8452008-01-26 01:09:19 +00001500 SDOperand Res = DAG.getNode(HiOp, N->getValueType(1), N->op_begin(),
1501 N->getNumOperands());
1502 return CombineTo(N, Res, Res);
Dan Gohman6c89ea72007-10-08 17:57:15 +00001503 }
1504
Evan Chengddfa8c72007-11-08 09:25:29 +00001505 // If both halves are used, return as it is.
1506 if (LoExists && HiExists)
Chris Lattner4a7c8452008-01-26 01:09:19 +00001507 return SDOperand();
Evan Chengddfa8c72007-11-08 09:25:29 +00001508
1509 // If the two computed results can be simplified separately, separate them.
Evan Chengddfa8c72007-11-08 09:25:29 +00001510 if (LoExists) {
1511 SDOperand Lo = DAG.getNode(LoOp, N->getValueType(0),
1512 N->op_begin(), N->getNumOperands());
Chris Lattner4a7c8452008-01-26 01:09:19 +00001513 AddToWorkList(Lo.Val);
Evan Chengddfa8c72007-11-08 09:25:29 +00001514 SDOperand LoOpt = combine(Lo.Val);
Chris Lattner4a7c8452008-01-26 01:09:19 +00001515 if (LoOpt.Val && LoOpt.Val != Lo.Val &&
1516 TLI.isOperationLegal(LoOpt.getOpcode(), LoOpt.getValueType()))
1517 return CombineTo(N, LoOpt, LoOpt);
Dan Gohman6c89ea72007-10-08 17:57:15 +00001518 }
1519
Evan Chengddfa8c72007-11-08 09:25:29 +00001520 if (HiExists) {
1521 SDOperand Hi = DAG.getNode(HiOp, N->getValueType(1),
1522 N->op_begin(), N->getNumOperands());
Chris Lattner4a7c8452008-01-26 01:09:19 +00001523 AddToWorkList(Hi.Val);
Evan Chengddfa8c72007-11-08 09:25:29 +00001524 SDOperand HiOpt = combine(Hi.Val);
1525 if (HiOpt.Val && HiOpt != Hi &&
Chris Lattner4a7c8452008-01-26 01:09:19 +00001526 TLI.isOperationLegal(HiOpt.getOpcode(), HiOpt.getValueType()))
1527 return CombineTo(N, HiOpt, HiOpt);
Evan Chengddfa8c72007-11-08 09:25:29 +00001528 }
Chris Lattner4a7c8452008-01-26 01:09:19 +00001529 return SDOperand();
Dan Gohman6c89ea72007-10-08 17:57:15 +00001530}
1531
1532SDOperand DAGCombiner::visitSMUL_LOHI(SDNode *N) {
Chris Lattner4a7c8452008-01-26 01:09:19 +00001533 SDOperand Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHS);
1534 if (Res.Val) return Res;
Dan Gohman6c89ea72007-10-08 17:57:15 +00001535
1536 return SDOperand();
1537}
1538
1539SDOperand DAGCombiner::visitUMUL_LOHI(SDNode *N) {
Chris Lattner4a7c8452008-01-26 01:09:19 +00001540 SDOperand Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHU);
1541 if (Res.Val) return Res;
Dan Gohman6c89ea72007-10-08 17:57:15 +00001542
1543 return SDOperand();
1544}
1545
1546SDOperand DAGCombiner::visitSDIVREM(SDNode *N) {
Chris Lattner4a7c8452008-01-26 01:09:19 +00001547 SDOperand Res = SimplifyNodeWithTwoResults(N, ISD::SDIV, ISD::SREM);
1548 if (Res.Val) return Res;
Dan Gohman6c89ea72007-10-08 17:57:15 +00001549
1550 return SDOperand();
1551}
1552
1553SDOperand DAGCombiner::visitUDIVREM(SDNode *N) {
Chris Lattner4a7c8452008-01-26 01:09:19 +00001554 SDOperand Res = SimplifyNodeWithTwoResults(N, ISD::UDIV, ISD::UREM);
1555 if (Res.Val) return Res;
Dan Gohman6c89ea72007-10-08 17:57:15 +00001556
1557 return SDOperand();
1558}
1559
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001560/// SimplifyBinOpWithSameOpcodeHands - If this is a binary operator with
1561/// two operands of the same opcode, try to simplify it.
1562SDOperand DAGCombiner::SimplifyBinOpWithSameOpcodeHands(SDNode *N) {
1563 SDOperand N0 = N->getOperand(0), N1 = N->getOperand(1);
1564 MVT::ValueType VT = N0.getValueType();
1565 assert(N0.getOpcode() == N1.getOpcode() && "Bad input!");
1566
1567 // For each of OP in AND/OR/XOR:
1568 // fold (OP (zext x), (zext y)) -> (zext (OP x, y))
1569 // fold (OP (sext x), (sext y)) -> (sext (OP x, y))
1570 // fold (OP (aext x), (aext y)) -> (aext (OP x, y))
1571 // fold (OP (trunc x), (trunc y)) -> (trunc (OP x, y))
1572 if ((N0.getOpcode() == ISD::ZERO_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND||
1573 N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::TRUNCATE) &&
1574 N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType()) {
1575 SDOperand ORNode = DAG.getNode(N->getOpcode(),
1576 N0.getOperand(0).getValueType(),
1577 N0.getOperand(0), N1.getOperand(0));
1578 AddToWorkList(ORNode.Val);
1579 return DAG.getNode(N0.getOpcode(), VT, ORNode);
1580 }
1581
1582 // For each of OP in SHL/SRL/SRA/AND...
1583 // fold (and (OP x, z), (OP y, z)) -> (OP (and x, y), z)
1584 // fold (or (OP x, z), (OP y, z)) -> (OP (or x, y), z)
1585 // fold (xor (OP x, z), (OP y, z)) -> (OP (xor x, y), z)
1586 if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL ||
1587 N0.getOpcode() == ISD::SRA || N0.getOpcode() == ISD::AND) &&
1588 N0.getOperand(1) == N1.getOperand(1)) {
1589 SDOperand ORNode = DAG.getNode(N->getOpcode(),
1590 N0.getOperand(0).getValueType(),
1591 N0.getOperand(0), N1.getOperand(0));
1592 AddToWorkList(ORNode.Val);
1593 return DAG.getNode(N0.getOpcode(), VT, ORNode, N0.getOperand(1));
1594 }
1595
1596 return SDOperand();
1597}
1598
1599SDOperand DAGCombiner::visitAND(SDNode *N) {
1600 SDOperand N0 = N->getOperand(0);
1601 SDOperand N1 = N->getOperand(1);
1602 SDOperand LL, LR, RL, RR, CC0, CC1;
1603 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1604 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1605 MVT::ValueType VT = N1.getValueType();
Dan Gohman07961cd2008-02-25 21:11:39 +00001606 unsigned BitWidth = MVT::getSizeInBits(VT);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001607
1608 // fold vector ops
1609 if (MVT::isVector(VT)) {
1610 SDOperand FoldedVOp = SimplifyVBinOp(N);
1611 if (FoldedVOp.Val) return FoldedVOp;
1612 }
1613
1614 // fold (and x, undef) -> 0
1615 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
1616 return DAG.getConstant(0, VT);
1617 // fold (and c1, c2) -> c1&c2
1618 if (N0C && N1C)
1619 return DAG.getNode(ISD::AND, VT, N0, N1);
1620 // canonicalize constant to RHS
1621 if (N0C && !N1C)
1622 return DAG.getNode(ISD::AND, VT, N1, N0);
1623 // fold (and x, -1) -> x
1624 if (N1C && N1C->isAllOnesValue())
1625 return N0;
1626 // if (and x, c) is known to be zero, return 0
Dan Gohman07961cd2008-02-25 21:11:39 +00001627 if (N1C && DAG.MaskedValueIsZero(SDOperand(N, 0),
1628 APInt::getAllOnesValue(BitWidth)))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001629 return DAG.getConstant(0, VT);
1630 // reassociate and
1631 SDOperand RAND = ReassociateOps(ISD::AND, N0, N1);
1632 if (RAND.Val != 0)
1633 return RAND;
1634 // fold (and (or x, 0xFFFF), 0xFF) -> 0xFF
1635 if (N1C && N0.getOpcode() == ISD::OR)
1636 if (ConstantSDNode *ORI = dyn_cast<ConstantSDNode>(N0.getOperand(1)))
1637 if ((ORI->getValue() & N1C->getValue()) == N1C->getValue())
1638 return N1;
1639 // fold (and (any_ext V), c) -> (zero_ext V) if 'and' only clears top bits.
1640 if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
Dan Gohman07961cd2008-02-25 21:11:39 +00001641 SDOperand N0Op0 = N0.getOperand(0);
1642 APInt Mask = ~N1C->getAPIntValue();
1643 Mask.trunc(N0Op0.getValueSizeInBits());
1644 if (DAG.MaskedValueIsZero(N0Op0, Mask)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001645 SDOperand Zext = DAG.getNode(ISD::ZERO_EXTEND, N0.getValueType(),
Dan Gohman07961cd2008-02-25 21:11:39 +00001646 N0Op0);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001647
1648 // Replace uses of the AND with uses of the Zero extend node.
1649 CombineTo(N, Zext);
1650
1651 // We actually want to replace all uses of the any_extend with the
1652 // zero_extend, to avoid duplicating things. This will later cause this
1653 // AND to be folded.
1654 CombineTo(N0.Val, Zext);
1655 return SDOperand(N, 0); // Return N so it doesn't get rechecked!
1656 }
1657 }
1658 // fold (and (setcc x), (setcc y)) -> (setcc (and x, y))
1659 if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){
1660 ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get();
1661 ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get();
1662
1663 if (LR == RR && isa<ConstantSDNode>(LR) && Op0 == Op1 &&
1664 MVT::isInteger(LL.getValueType())) {
1665 // fold (X == 0) & (Y == 0) -> (X|Y == 0)
1666 if (cast<ConstantSDNode>(LR)->getValue() == 0 && Op1 == ISD::SETEQ) {
1667 SDOperand ORNode = DAG.getNode(ISD::OR, LR.getValueType(), LL, RL);
1668 AddToWorkList(ORNode.Val);
1669 return DAG.getSetCC(VT, ORNode, LR, Op1);
1670 }
1671 // fold (X == -1) & (Y == -1) -> (X&Y == -1)
1672 if (cast<ConstantSDNode>(LR)->isAllOnesValue() && Op1 == ISD::SETEQ) {
1673 SDOperand ANDNode = DAG.getNode(ISD::AND, LR.getValueType(), LL, RL);
1674 AddToWorkList(ANDNode.Val);
1675 return DAG.getSetCC(VT, ANDNode, LR, Op1);
1676 }
1677 // fold (X > -1) & (Y > -1) -> (X|Y > -1)
1678 if (cast<ConstantSDNode>(LR)->isAllOnesValue() && Op1 == ISD::SETGT) {
1679 SDOperand ORNode = DAG.getNode(ISD::OR, LR.getValueType(), LL, RL);
1680 AddToWorkList(ORNode.Val);
1681 return DAG.getSetCC(VT, ORNode, LR, Op1);
1682 }
1683 }
1684 // canonicalize equivalent to ll == rl
1685 if (LL == RR && LR == RL) {
1686 Op1 = ISD::getSetCCSwappedOperands(Op1);
1687 std::swap(RL, RR);
1688 }
1689 if (LL == RL && LR == RR) {
1690 bool isInteger = MVT::isInteger(LL.getValueType());
1691 ISD::CondCode Result = ISD::getSetCCAndOperation(Op0, Op1, isInteger);
1692 if (Result != ISD::SETCC_INVALID)
1693 return DAG.getSetCC(N0.getValueType(), LL, LR, Result);
1694 }
1695 }
1696
1697 // Simplify: and (op x...), (op y...) -> (op (and x, y))
1698 if (N0.getOpcode() == N1.getOpcode()) {
1699 SDOperand Tmp = SimplifyBinOpWithSameOpcodeHands(N);
1700 if (Tmp.Val) return Tmp;
1701 }
1702
1703 // fold (and (sign_extend_inreg x, i16 to i32), 1) -> (and x, 1)
1704 // fold (and (sra)) -> (and (srl)) when possible.
1705 if (!MVT::isVector(VT) &&
1706 SimplifyDemandedBits(SDOperand(N, 0)))
1707 return SDOperand(N, 0);
1708 // fold (zext_inreg (extload x)) -> (zextload x)
1709 if (ISD::isEXTLoad(N0.Val) && ISD::isUNINDEXEDLoad(N0.Val)) {
1710 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
Dan Gohman9a4c92c2008-01-30 00:15:11 +00001711 MVT::ValueType EVT = LN0->getMemoryVT();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001712 // If we zero all the possible extended bits, then we can turn this into
1713 // a zextload if we are running before legalize or the operation is legal.
Dan Gohman07961cd2008-02-25 21:11:39 +00001714 unsigned BitWidth = N1.getValueSizeInBits();
1715 if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth,
1716 BitWidth - MVT::getSizeInBits(EVT))) &&
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001717 (!AfterLegalize || TLI.isLoadXLegal(ISD::ZEXTLOAD, EVT))) {
1718 SDOperand ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, VT, LN0->getChain(),
1719 LN0->getBasePtr(), LN0->getSrcValue(),
1720 LN0->getSrcValueOffset(), EVT,
1721 LN0->isVolatile(),
1722 LN0->getAlignment());
1723 AddToWorkList(N);
1724 CombineTo(N0.Val, ExtLoad, ExtLoad.getValue(1));
1725 return SDOperand(N, 0); // Return N so it doesn't get rechecked!
1726 }
1727 }
1728 // fold (zext_inreg (sextload x)) -> (zextload x) iff load has one use
1729 if (ISD::isSEXTLoad(N0.Val) && ISD::isUNINDEXEDLoad(N0.Val) &&
1730 N0.hasOneUse()) {
1731 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
Dan Gohman9a4c92c2008-01-30 00:15:11 +00001732 MVT::ValueType EVT = LN0->getMemoryVT();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001733 // If we zero all the possible extended bits, then we can turn this into
1734 // a zextload if we are running before legalize or the operation is legal.
Dan Gohman07961cd2008-02-25 21:11:39 +00001735 unsigned BitWidth = N1.getValueSizeInBits();
1736 if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth,
1737 BitWidth - MVT::getSizeInBits(EVT))) &&
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001738 (!AfterLegalize || TLI.isLoadXLegal(ISD::ZEXTLOAD, EVT))) {
1739 SDOperand ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, VT, LN0->getChain(),
1740 LN0->getBasePtr(), LN0->getSrcValue(),
1741 LN0->getSrcValueOffset(), EVT,
1742 LN0->isVolatile(),
1743 LN0->getAlignment());
1744 AddToWorkList(N);
1745 CombineTo(N0.Val, ExtLoad, ExtLoad.getValue(1));
1746 return SDOperand(N, 0); // Return N so it doesn't get rechecked!
1747 }
1748 }
1749
1750 // fold (and (load x), 255) -> (zextload x, i8)
1751 // fold (and (extload x, i16), 255) -> (zextload x, i8)
1752 if (N1C && N0.getOpcode() == ISD::LOAD) {
1753 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
1754 if (LN0->getExtensionType() != ISD::SEXTLOAD &&
Chris Lattner3bc08502008-01-17 19:59:44 +00001755 LN0->isUnindexed() && N0.hasOneUse()) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001756 MVT::ValueType EVT, LoadedVT;
1757 if (N1C->getValue() == 255)
1758 EVT = MVT::i8;
1759 else if (N1C->getValue() == 65535)
1760 EVT = MVT::i16;
1761 else if (N1C->getValue() == ~0U)
1762 EVT = MVT::i32;
1763 else
1764 EVT = MVT::Other;
1765
Dan Gohman9a4c92c2008-01-30 00:15:11 +00001766 LoadedVT = LN0->getMemoryVT();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001767 if (EVT != MVT::Other && LoadedVT > EVT &&
1768 (!AfterLegalize || TLI.isLoadXLegal(ISD::ZEXTLOAD, EVT))) {
1769 MVT::ValueType PtrType = N0.getOperand(1).getValueType();
1770 // For big endian targets, we need to add an offset to the pointer to
1771 // load the correct bytes. For little endian systems, we merely need to
1772 // read fewer bytes from the same pointer.
Duncan Sands4f18d4f2007-11-09 08:57:19 +00001773 unsigned LVTStoreBytes = MVT::getStoreSizeInBits(LoadedVT)/8;
1774 unsigned EVTStoreBytes = MVT::getStoreSizeInBits(EVT)/8;
1775 unsigned PtrOff = LVTStoreBytes - EVTStoreBytes;
Duncan Sandsa3691432007-10-28 12:59:45 +00001776 unsigned Alignment = LN0->getAlignment();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001777 SDOperand NewPtr = LN0->getBasePtr();
Duncan Sands9ff8fbf2008-02-11 10:37:04 +00001778 if (TLI.isBigEndian()) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001779 NewPtr = DAG.getNode(ISD::ADD, PtrType, NewPtr,
1780 DAG.getConstant(PtrOff, PtrType));
Duncan Sandsa3691432007-10-28 12:59:45 +00001781 Alignment = MinAlign(Alignment, PtrOff);
1782 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001783 AddToWorkList(NewPtr.Val);
1784 SDOperand Load =
1785 DAG.getExtLoad(ISD::ZEXTLOAD, VT, LN0->getChain(), NewPtr,
1786 LN0->getSrcValue(), LN0->getSrcValueOffset(), EVT,
Duncan Sandsa3691432007-10-28 12:59:45 +00001787 LN0->isVolatile(), Alignment);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001788 AddToWorkList(N);
1789 CombineTo(N0.Val, Load, Load.getValue(1));
1790 return SDOperand(N, 0); // Return N so it doesn't get rechecked!
1791 }
1792 }
1793 }
1794
1795 return SDOperand();
1796}
1797
1798SDOperand DAGCombiner::visitOR(SDNode *N) {
1799 SDOperand N0 = N->getOperand(0);
1800 SDOperand N1 = N->getOperand(1);
1801 SDOperand LL, LR, RL, RR, CC0, CC1;
1802 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1803 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1804 MVT::ValueType VT = N1.getValueType();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001805
1806 // fold vector ops
1807 if (MVT::isVector(VT)) {
1808 SDOperand FoldedVOp = SimplifyVBinOp(N);
1809 if (FoldedVOp.Val) return FoldedVOp;
1810 }
1811
1812 // fold (or x, undef) -> -1
1813 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
1814 return DAG.getConstant(~0ULL, VT);
1815 // fold (or c1, c2) -> c1|c2
1816 if (N0C && N1C)
1817 return DAG.getNode(ISD::OR, VT, N0, N1);
1818 // canonicalize constant to RHS
1819 if (N0C && !N1C)
1820 return DAG.getNode(ISD::OR, VT, N1, N0);
1821 // fold (or x, 0) -> x
1822 if (N1C && N1C->isNullValue())
1823 return N0;
1824 // fold (or x, -1) -> -1
1825 if (N1C && N1C->isAllOnesValue())
1826 return N1;
1827 // fold (or x, c) -> c iff (x & ~c) == 0
Dan Gohman07961cd2008-02-25 21:11:39 +00001828 if (N1C && DAG.MaskedValueIsZero(N0, ~N1C->getAPIntValue()))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001829 return N1;
1830 // reassociate or
1831 SDOperand ROR = ReassociateOps(ISD::OR, N0, N1);
1832 if (ROR.Val != 0)
1833 return ROR;
1834 // Canonicalize (or (and X, c1), c2) -> (and (or X, c2), c1|c2)
1835 if (N1C && N0.getOpcode() == ISD::AND && N0.Val->hasOneUse() &&
1836 isa<ConstantSDNode>(N0.getOperand(1))) {
1837 ConstantSDNode *C1 = cast<ConstantSDNode>(N0.getOperand(1));
1838 return DAG.getNode(ISD::AND, VT, DAG.getNode(ISD::OR, VT, N0.getOperand(0),
1839 N1),
1840 DAG.getConstant(N1C->getValue() | C1->getValue(), VT));
1841 }
1842 // fold (or (setcc x), (setcc y)) -> (setcc (or x, y))
1843 if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){
1844 ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get();
1845 ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get();
1846
1847 if (LR == RR && isa<ConstantSDNode>(LR) && Op0 == Op1 &&
1848 MVT::isInteger(LL.getValueType())) {
1849 // fold (X != 0) | (Y != 0) -> (X|Y != 0)
1850 // fold (X < 0) | (Y < 0) -> (X|Y < 0)
1851 if (cast<ConstantSDNode>(LR)->getValue() == 0 &&
1852 (Op1 == ISD::SETNE || Op1 == ISD::SETLT)) {
1853 SDOperand ORNode = DAG.getNode(ISD::OR, LR.getValueType(), LL, RL);
1854 AddToWorkList(ORNode.Val);
1855 return DAG.getSetCC(VT, ORNode, LR, Op1);
1856 }
1857 // fold (X != -1) | (Y != -1) -> (X&Y != -1)
1858 // fold (X > -1) | (Y > -1) -> (X&Y > -1)
1859 if (cast<ConstantSDNode>(LR)->isAllOnesValue() &&
1860 (Op1 == ISD::SETNE || Op1 == ISD::SETGT)) {
1861 SDOperand ANDNode = DAG.getNode(ISD::AND, LR.getValueType(), LL, RL);
1862 AddToWorkList(ANDNode.Val);
1863 return DAG.getSetCC(VT, ANDNode, LR, Op1);
1864 }
1865 }
1866 // canonicalize equivalent to ll == rl
1867 if (LL == RR && LR == RL) {
1868 Op1 = ISD::getSetCCSwappedOperands(Op1);
1869 std::swap(RL, RR);
1870 }
1871 if (LL == RL && LR == RR) {
1872 bool isInteger = MVT::isInteger(LL.getValueType());
1873 ISD::CondCode Result = ISD::getSetCCOrOperation(Op0, Op1, isInteger);
1874 if (Result != ISD::SETCC_INVALID)
1875 return DAG.getSetCC(N0.getValueType(), LL, LR, Result);
1876 }
1877 }
1878
1879 // Simplify: or (op x...), (op y...) -> (op (or x, y))
1880 if (N0.getOpcode() == N1.getOpcode()) {
1881 SDOperand Tmp = SimplifyBinOpWithSameOpcodeHands(N);
1882 if (Tmp.Val) return Tmp;
1883 }
1884
1885 // (X & C1) | (Y & C2) -> (X|Y) & C3 if possible.
1886 if (N0.getOpcode() == ISD::AND &&
1887 N1.getOpcode() == ISD::AND &&
1888 N0.getOperand(1).getOpcode() == ISD::Constant &&
1889 N1.getOperand(1).getOpcode() == ISD::Constant &&
1890 // Don't increase # computations.
1891 (N0.Val->hasOneUse() || N1.Val->hasOneUse())) {
1892 // We can only do this xform if we know that bits from X that are set in C2
1893 // but not in C1 are already zero. Likewise for Y.
Dan Gohman07961cd2008-02-25 21:11:39 +00001894 const APInt &LHSMask =
1895 cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
1896 const APInt &RHSMask =
1897 cast<ConstantSDNode>(N1.getOperand(1))->getAPIntValue();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001898
1899 if (DAG.MaskedValueIsZero(N0.getOperand(0), RHSMask&~LHSMask) &&
1900 DAG.MaskedValueIsZero(N1.getOperand(0), LHSMask&~RHSMask)) {
1901 SDOperand X =DAG.getNode(ISD::OR, VT, N0.getOperand(0), N1.getOperand(0));
1902 return DAG.getNode(ISD::AND, VT, X, DAG.getConstant(LHSMask|RHSMask, VT));
1903 }
1904 }
1905
1906
1907 // See if this is some rotate idiom.
1908 if (SDNode *Rot = MatchRotate(N0, N1))
1909 return SDOperand(Rot, 0);
1910
1911 return SDOperand();
1912}
1913
1914
1915/// MatchRotateHalf - Match "(X shl/srl V1) & V2" where V2 may not be present.
1916static bool MatchRotateHalf(SDOperand Op, SDOperand &Shift, SDOperand &Mask) {
1917 if (Op.getOpcode() == ISD::AND) {
1918 if (isa<ConstantSDNode>(Op.getOperand(1))) {
1919 Mask = Op.getOperand(1);
1920 Op = Op.getOperand(0);
1921 } else {
1922 return false;
1923 }
1924 }
1925
1926 if (Op.getOpcode() == ISD::SRL || Op.getOpcode() == ISD::SHL) {
1927 Shift = Op;
1928 return true;
1929 }
1930 return false;
1931}
1932
1933
1934// MatchRotate - Handle an 'or' of two operands. If this is one of the many
1935// idioms for rotate, and if the target supports rotation instructions, generate
1936// a rot[lr].
1937SDNode *DAGCombiner::MatchRotate(SDOperand LHS, SDOperand RHS) {
1938 // Must be a legal type. Expanded an promoted things won't work with rotates.
1939 MVT::ValueType VT = LHS.getValueType();
1940 if (!TLI.isTypeLegal(VT)) return 0;
1941
1942 // The target must have at least one rotate flavor.
1943 bool HasROTL = TLI.isOperationLegal(ISD::ROTL, VT);
1944 bool HasROTR = TLI.isOperationLegal(ISD::ROTR, VT);
1945 if (!HasROTL && !HasROTR) return 0;
1946
1947 // Match "(X shl/srl V1) & V2" where V2 may not be present.
1948 SDOperand LHSShift; // The shift.
1949 SDOperand LHSMask; // AND value if any.
1950 if (!MatchRotateHalf(LHS, LHSShift, LHSMask))
1951 return 0; // Not part of a rotate.
1952
1953 SDOperand RHSShift; // The shift.
1954 SDOperand RHSMask; // AND value if any.
1955 if (!MatchRotateHalf(RHS, RHSShift, RHSMask))
1956 return 0; // Not part of a rotate.
1957
1958 if (LHSShift.getOperand(0) != RHSShift.getOperand(0))
1959 return 0; // Not shifting the same value.
1960
1961 if (LHSShift.getOpcode() == RHSShift.getOpcode())
1962 return 0; // Shifts must disagree.
1963
1964 // Canonicalize shl to left side in a shl/srl pair.
1965 if (RHSShift.getOpcode() == ISD::SHL) {
1966 std::swap(LHS, RHS);
1967 std::swap(LHSShift, RHSShift);
1968 std::swap(LHSMask , RHSMask );
1969 }
1970
1971 unsigned OpSizeInBits = MVT::getSizeInBits(VT);
1972 SDOperand LHSShiftArg = LHSShift.getOperand(0);
1973 SDOperand LHSShiftAmt = LHSShift.getOperand(1);
1974 SDOperand RHSShiftAmt = RHSShift.getOperand(1);
1975
1976 // fold (or (shl x, C1), (srl x, C2)) -> (rotl x, C1)
1977 // fold (or (shl x, C1), (srl x, C2)) -> (rotr x, C2)
1978 if (LHSShiftAmt.getOpcode() == ISD::Constant &&
1979 RHSShiftAmt.getOpcode() == ISD::Constant) {
1980 uint64_t LShVal = cast<ConstantSDNode>(LHSShiftAmt)->getValue();
1981 uint64_t RShVal = cast<ConstantSDNode>(RHSShiftAmt)->getValue();
1982 if ((LShVal + RShVal) != OpSizeInBits)
1983 return 0;
1984
1985 SDOperand Rot;
1986 if (HasROTL)
1987 Rot = DAG.getNode(ISD::ROTL, VT, LHSShiftArg, LHSShiftAmt);
1988 else
1989 Rot = DAG.getNode(ISD::ROTR, VT, LHSShiftArg, RHSShiftAmt);
1990
1991 // If there is an AND of either shifted operand, apply it to the result.
1992 if (LHSMask.Val || RHSMask.Val) {
Dan Gohmand047c3e2008-03-03 23:51:38 +00001993 APInt Mask = APInt::getAllOnesValue(OpSizeInBits);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001994
1995 if (LHSMask.Val) {
Dan Gohmand047c3e2008-03-03 23:51:38 +00001996 APInt RHSBits = APInt::getLowBitsSet(OpSizeInBits, LShVal);
1997 Mask &= cast<ConstantSDNode>(LHSMask)->getAPIntValue() | RHSBits;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001998 }
1999 if (RHSMask.Val) {
Dan Gohmand047c3e2008-03-03 23:51:38 +00002000 APInt LHSBits = APInt::getHighBitsSet(OpSizeInBits, RShVal);
2001 Mask &= cast<ConstantSDNode>(RHSMask)->getAPIntValue() | LHSBits;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002002 }
2003
2004 Rot = DAG.getNode(ISD::AND, VT, Rot, DAG.getConstant(Mask, VT));
2005 }
2006
2007 return Rot.Val;
2008 }
2009
2010 // If there is a mask here, and we have a variable shift, we can't be sure
2011 // that we're masking out the right stuff.
2012 if (LHSMask.Val || RHSMask.Val)
2013 return 0;
2014
2015 // fold (or (shl x, y), (srl x, (sub 32, y))) -> (rotl x, y)
2016 // fold (or (shl x, y), (srl x, (sub 32, y))) -> (rotr x, (sub 32, y))
2017 if (RHSShiftAmt.getOpcode() == ISD::SUB &&
2018 LHSShiftAmt == RHSShiftAmt.getOperand(1)) {
2019 if (ConstantSDNode *SUBC =
2020 dyn_cast<ConstantSDNode>(RHSShiftAmt.getOperand(0))) {
Anton Korobeynikov53422f62008-02-20 11:10:28 +00002021 if (SUBC->getValue() == OpSizeInBits) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002022 if (HasROTL)
2023 return DAG.getNode(ISD::ROTL, VT, LHSShiftArg, LHSShiftAmt).Val;
2024 else
2025 return DAG.getNode(ISD::ROTR, VT, LHSShiftArg, RHSShiftAmt).Val;
Anton Korobeynikov53422f62008-02-20 11:10:28 +00002026 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002027 }
2028 }
2029
2030 // fold (or (shl x, (sub 32, y)), (srl x, r)) -> (rotr x, y)
2031 // fold (or (shl x, (sub 32, y)), (srl x, r)) -> (rotl x, (sub 32, y))
2032 if (LHSShiftAmt.getOpcode() == ISD::SUB &&
2033 RHSShiftAmt == LHSShiftAmt.getOperand(1)) {
2034 if (ConstantSDNode *SUBC =
2035 dyn_cast<ConstantSDNode>(LHSShiftAmt.getOperand(0))) {
Anton Korobeynikov53422f62008-02-20 11:10:28 +00002036 if (SUBC->getValue() == OpSizeInBits) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002037 if (HasROTL)
2038 return DAG.getNode(ISD::ROTL, VT, LHSShiftArg, LHSShiftAmt).Val;
2039 else
2040 return DAG.getNode(ISD::ROTR, VT, LHSShiftArg, RHSShiftAmt).Val;
Anton Korobeynikov53422f62008-02-20 11:10:28 +00002041 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002042 }
2043 }
2044
2045 // Look for sign/zext/any-extended cases:
2046 if ((LHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND
2047 || LHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND
2048 || LHSShiftAmt.getOpcode() == ISD::ANY_EXTEND) &&
2049 (RHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND
2050 || RHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND
2051 || RHSShiftAmt.getOpcode() == ISD::ANY_EXTEND)) {
2052 SDOperand LExtOp0 = LHSShiftAmt.getOperand(0);
2053 SDOperand RExtOp0 = RHSShiftAmt.getOperand(0);
2054 if (RExtOp0.getOpcode() == ISD::SUB &&
2055 RExtOp0.getOperand(1) == LExtOp0) {
2056 // fold (or (shl x, (*ext y)), (srl x, (*ext (sub 32, y)))) ->
2057 // (rotr x, y)
2058 // fold (or (shl x, (*ext y)), (srl x, (*ext (sub 32, y)))) ->
2059 // (rotl x, (sub 32, y))
2060 if (ConstantSDNode *SUBC = cast<ConstantSDNode>(RExtOp0.getOperand(0))) {
2061 if (SUBC->getValue() == OpSizeInBits) {
2062 if (HasROTL)
2063 return DAG.getNode(ISD::ROTL, VT, LHSShiftArg, LHSShiftAmt).Val;
2064 else
2065 return DAG.getNode(ISD::ROTR, VT, LHSShiftArg, RHSShiftAmt).Val;
2066 }
2067 }
2068 } else if (LExtOp0.getOpcode() == ISD::SUB &&
2069 RExtOp0 == LExtOp0.getOperand(1)) {
2070 // fold (or (shl x, (*ext (sub 32, y))), (srl x, (*ext r))) ->
2071 // (rotl x, y)
2072 // fold (or (shl x, (*ext (sub 32, y))), (srl x, (*ext r))) ->
2073 // (rotr x, (sub 32, y))
2074 if (ConstantSDNode *SUBC = cast<ConstantSDNode>(LExtOp0.getOperand(0))) {
2075 if (SUBC->getValue() == OpSizeInBits) {
2076 if (HasROTL)
2077 return DAG.getNode(ISD::ROTL, VT, LHSShiftArg, RHSShiftAmt).Val;
2078 else
2079 return DAG.getNode(ISD::ROTL, VT, LHSShiftArg, LHSShiftAmt).Val;
2080 }
2081 }
2082 }
2083 }
2084
2085 return 0;
2086}
2087
2088
2089SDOperand DAGCombiner::visitXOR(SDNode *N) {
2090 SDOperand N0 = N->getOperand(0);
2091 SDOperand N1 = N->getOperand(1);
2092 SDOperand LHS, RHS, CC;
2093 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
2094 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2095 MVT::ValueType VT = N0.getValueType();
2096
2097 // fold vector ops
2098 if (MVT::isVector(VT)) {
2099 SDOperand FoldedVOp = SimplifyVBinOp(N);
2100 if (FoldedVOp.Val) return FoldedVOp;
2101 }
2102
2103 // fold (xor x, undef) -> undef
2104 if (N0.getOpcode() == ISD::UNDEF)
2105 return N0;
2106 if (N1.getOpcode() == ISD::UNDEF)
2107 return N1;
2108 // fold (xor c1, c2) -> c1^c2
2109 if (N0C && N1C)
2110 return DAG.getNode(ISD::XOR, VT, N0, N1);
2111 // canonicalize constant to RHS
2112 if (N0C && !N1C)
2113 return DAG.getNode(ISD::XOR, VT, N1, N0);
2114 // fold (xor x, 0) -> x
2115 if (N1C && N1C->isNullValue())
2116 return N0;
2117 // reassociate xor
2118 SDOperand RXOR = ReassociateOps(ISD::XOR, N0, N1);
2119 if (RXOR.Val != 0)
2120 return RXOR;
2121 // fold !(x cc y) -> (x !cc y)
2122 if (N1C && N1C->getValue() == 1 && isSetCCEquivalent(N0, LHS, RHS, CC)) {
2123 bool isInt = MVT::isInteger(LHS.getValueType());
2124 ISD::CondCode NotCC = ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(),
2125 isInt);
2126 if (N0.getOpcode() == ISD::SETCC)
2127 return DAG.getSetCC(VT, LHS, RHS, NotCC);
2128 if (N0.getOpcode() == ISD::SELECT_CC)
2129 return DAG.getSelectCC(LHS, RHS, N0.getOperand(2),N0.getOperand(3),NotCC);
2130 assert(0 && "Unhandled SetCC Equivalent!");
2131 abort();
2132 }
Chris Lattnere27cd502007-09-10 21:39:07 +00002133 // fold (not (zext (setcc x, y))) -> (zext (not (setcc x, y)))
2134 if (N1C && N1C->getValue() == 1 && N0.getOpcode() == ISD::ZERO_EXTEND &&
2135 N0.Val->hasOneUse() && isSetCCEquivalent(N0.getOperand(0), LHS, RHS, CC)){
2136 SDOperand V = N0.getOperand(0);
2137 V = DAG.getNode(ISD::XOR, V.getValueType(), V,
Duncan Sandsbed21472007-10-10 09:54:50 +00002138 DAG.getConstant(1, V.getValueType()));
Chris Lattnere27cd502007-09-10 21:39:07 +00002139 AddToWorkList(V.Val);
2140 return DAG.getNode(ISD::ZERO_EXTEND, VT, V);
2141 }
2142
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002143 // fold !(x or y) -> (!x and !y) iff x or y are setcc
2144 if (N1C && N1C->getValue() == 1 && VT == MVT::i1 &&
2145 (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
2146 SDOperand LHS = N0.getOperand(0), RHS = N0.getOperand(1);
2147 if (isOneUseSetCC(RHS) || isOneUseSetCC(LHS)) {
2148 unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
2149 LHS = DAG.getNode(ISD::XOR, VT, LHS, N1); // RHS = ~LHS
2150 RHS = DAG.getNode(ISD::XOR, VT, RHS, N1); // RHS = ~RHS
2151 AddToWorkList(LHS.Val); AddToWorkList(RHS.Val);
2152 return DAG.getNode(NewOpcode, VT, LHS, RHS);
2153 }
2154 }
2155 // fold !(x or y) -> (!x and !y) iff x or y are constants
2156 if (N1C && N1C->isAllOnesValue() &&
2157 (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
2158 SDOperand LHS = N0.getOperand(0), RHS = N0.getOperand(1);
2159 if (isa<ConstantSDNode>(RHS) || isa<ConstantSDNode>(LHS)) {
2160 unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
2161 LHS = DAG.getNode(ISD::XOR, VT, LHS, N1); // RHS = ~LHS
2162 RHS = DAG.getNode(ISD::XOR, VT, RHS, N1); // RHS = ~RHS
2163 AddToWorkList(LHS.Val); AddToWorkList(RHS.Val);
2164 return DAG.getNode(NewOpcode, VT, LHS, RHS);
2165 }
2166 }
2167 // fold (xor (xor x, c1), c2) -> (xor x, c1^c2)
2168 if (N1C && N0.getOpcode() == ISD::XOR) {
2169 ConstantSDNode *N00C = dyn_cast<ConstantSDNode>(N0.getOperand(0));
2170 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
2171 if (N00C)
2172 return DAG.getNode(ISD::XOR, VT, N0.getOperand(1),
2173 DAG.getConstant(N1C->getValue()^N00C->getValue(), VT));
2174 if (N01C)
2175 return DAG.getNode(ISD::XOR, VT, N0.getOperand(0),
2176 DAG.getConstant(N1C->getValue()^N01C->getValue(), VT));
2177 }
2178 // fold (xor x, x) -> 0
2179 if (N0 == N1) {
2180 if (!MVT::isVector(VT)) {
2181 return DAG.getConstant(0, VT);
2182 } else if (!AfterLegalize || TLI.isOperationLegal(ISD::BUILD_VECTOR, VT)) {
2183 // Produce a vector of zeros.
2184 SDOperand El = DAG.getConstant(0, MVT::getVectorElementType(VT));
2185 std::vector<SDOperand> Ops(MVT::getVectorNumElements(VT), El);
2186 return DAG.getNode(ISD::BUILD_VECTOR, VT, &Ops[0], Ops.size());
2187 }
2188 }
2189
2190 // Simplify: xor (op x...), (op y...) -> (op (xor x, y))
2191 if (N0.getOpcode() == N1.getOpcode()) {
2192 SDOperand Tmp = SimplifyBinOpWithSameOpcodeHands(N);
2193 if (Tmp.Val) return Tmp;
2194 }
2195
2196 // Simplify the expression using non-local knowledge.
2197 if (!MVT::isVector(VT) &&
2198 SimplifyDemandedBits(SDOperand(N, 0)))
2199 return SDOperand(N, 0);
2200
2201 return SDOperand();
2202}
2203
Chris Lattner91ed3c32007-12-06 07:33:36 +00002204/// visitShiftByConstant - Handle transforms common to the three shifts, when
2205/// the shift amount is a constant.
2206SDOperand DAGCombiner::visitShiftByConstant(SDNode *N, unsigned Amt) {
2207 SDNode *LHS = N->getOperand(0).Val;
2208 if (!LHS->hasOneUse()) return SDOperand();
2209
2210 // We want to pull some binops through shifts, so that we have (and (shift))
2211 // instead of (shift (and)), likewise for add, or, xor, etc. This sort of
2212 // thing happens with address calculations, so it's important to canonicalize
2213 // it.
2214 bool HighBitSet = false; // Can we transform this if the high bit is set?
2215
2216 switch (LHS->getOpcode()) {
2217 default: return SDOperand();
2218 case ISD::OR:
2219 case ISD::XOR:
2220 HighBitSet = false; // We can only transform sra if the high bit is clear.
2221 break;
2222 case ISD::AND:
2223 HighBitSet = true; // We can only transform sra if the high bit is set.
2224 break;
2225 case ISD::ADD:
2226 if (N->getOpcode() != ISD::SHL)
2227 return SDOperand(); // only shl(add) not sr[al](add).
2228 HighBitSet = false; // We can only transform sra if the high bit is clear.
2229 break;
2230 }
2231
2232 // We require the RHS of the binop to be a constant as well.
2233 ConstantSDNode *BinOpCst = dyn_cast<ConstantSDNode>(LHS->getOperand(1));
2234 if (!BinOpCst) return SDOperand();
2235
Chris Lattnerdcd19762007-12-06 07:47:55 +00002236
2237 // FIXME: disable this for unless the input to the binop is a shift by a
2238 // constant. If it is not a shift, it pessimizes some common cases like:
2239 //
2240 //void foo(int *X, int i) { X[i & 1235] = 1; }
2241 //int bar(int *X, int i) { return X[i & 255]; }
2242 SDNode *BinOpLHSVal = LHS->getOperand(0).Val;
2243 if ((BinOpLHSVal->getOpcode() != ISD::SHL &&
2244 BinOpLHSVal->getOpcode() != ISD::SRA &&
2245 BinOpLHSVal->getOpcode() != ISD::SRL) ||
2246 !isa<ConstantSDNode>(BinOpLHSVal->getOperand(1)))
2247 return SDOperand();
2248
Chris Lattner91ed3c32007-12-06 07:33:36 +00002249 MVT::ValueType VT = N->getValueType(0);
2250
2251 // If this is a signed shift right, and the high bit is modified
2252 // by the logical operation, do not perform the transformation.
2253 // The highBitSet boolean indicates the value of the high bit of
2254 // the constant which would cause it to be modified for this
2255 // operation.
2256 if (N->getOpcode() == ISD::SRA) {
Dan Gohmand047c3e2008-03-03 23:51:38 +00002257 bool BinOpRHSSignSet = BinOpCst->getAPIntValue().isNegative();
2258 if (BinOpRHSSignSet != HighBitSet)
Chris Lattner91ed3c32007-12-06 07:33:36 +00002259 return SDOperand();
2260 }
2261
2262 // Fold the constants, shifting the binop RHS by the shift amount.
2263 SDOperand NewRHS = DAG.getNode(N->getOpcode(), N->getValueType(0),
2264 LHS->getOperand(1), N->getOperand(1));
2265
2266 // Create the new shift.
2267 SDOperand NewShift = DAG.getNode(N->getOpcode(), VT, LHS->getOperand(0),
2268 N->getOperand(1));
2269
2270 // Create the new binop.
2271 return DAG.getNode(LHS->getOpcode(), VT, NewShift, NewRHS);
2272}
2273
2274
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002275SDOperand DAGCombiner::visitSHL(SDNode *N) {
2276 SDOperand N0 = N->getOperand(0);
2277 SDOperand N1 = N->getOperand(1);
2278 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
2279 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2280 MVT::ValueType VT = N0.getValueType();
2281 unsigned OpSizeInBits = MVT::getSizeInBits(VT);
2282
2283 // fold (shl c1, c2) -> c1<<c2
2284 if (N0C && N1C)
2285 return DAG.getNode(ISD::SHL, VT, N0, N1);
2286 // fold (shl 0, x) -> 0
2287 if (N0C && N0C->isNullValue())
2288 return N0;
2289 // fold (shl x, c >= size(x)) -> undef
2290 if (N1C && N1C->getValue() >= OpSizeInBits)
2291 return DAG.getNode(ISD::UNDEF, VT);
2292 // fold (shl x, 0) -> x
2293 if (N1C && N1C->isNullValue())
2294 return N0;
2295 // if (shl x, c) is known to be zero, return 0
Dan Gohman07961cd2008-02-25 21:11:39 +00002296 if (DAG.MaskedValueIsZero(SDOperand(N, 0),
2297 APInt::getAllOnesValue(MVT::getSizeInBits(VT))))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002298 return DAG.getConstant(0, VT);
2299 if (N1C && SimplifyDemandedBits(SDOperand(N, 0)))
2300 return SDOperand(N, 0);
2301 // fold (shl (shl x, c1), c2) -> 0 or (shl x, c1+c2)
2302 if (N1C && N0.getOpcode() == ISD::SHL &&
2303 N0.getOperand(1).getOpcode() == ISD::Constant) {
2304 uint64_t c1 = cast<ConstantSDNode>(N0.getOperand(1))->getValue();
2305 uint64_t c2 = N1C->getValue();
2306 if (c1 + c2 > OpSizeInBits)
2307 return DAG.getConstant(0, VT);
2308 return DAG.getNode(ISD::SHL, VT, N0.getOperand(0),
2309 DAG.getConstant(c1 + c2, N1.getValueType()));
2310 }
2311 // fold (shl (srl x, c1), c2) -> (shl (and x, -1 << c1), c2-c1) or
2312 // (srl (and x, -1 << c1), c1-c2)
2313 if (N1C && N0.getOpcode() == ISD::SRL &&
2314 N0.getOperand(1).getOpcode() == ISD::Constant) {
2315 uint64_t c1 = cast<ConstantSDNode>(N0.getOperand(1))->getValue();
2316 uint64_t c2 = N1C->getValue();
2317 SDOperand Mask = DAG.getNode(ISD::AND, VT, N0.getOperand(0),
2318 DAG.getConstant(~0ULL << c1, VT));
2319 if (c2 > c1)
2320 return DAG.getNode(ISD::SHL, VT, Mask,
2321 DAG.getConstant(c2-c1, N1.getValueType()));
2322 else
2323 return DAG.getNode(ISD::SRL, VT, Mask,
2324 DAG.getConstant(c1-c2, N1.getValueType()));
2325 }
2326 // fold (shl (sra x, c1), c1) -> (and x, -1 << c1)
2327 if (N1C && N0.getOpcode() == ISD::SRA && N1 == N0.getOperand(1))
2328 return DAG.getNode(ISD::AND, VT, N0.getOperand(0),
2329 DAG.getConstant(~0ULL << N1C->getValue(), VT));
Chris Lattner91ed3c32007-12-06 07:33:36 +00002330
2331 return N1C ? visitShiftByConstant(N, N1C->getValue()) : SDOperand();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002332}
2333
2334SDOperand DAGCombiner::visitSRA(SDNode *N) {
2335 SDOperand N0 = N->getOperand(0);
2336 SDOperand N1 = N->getOperand(1);
2337 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
2338 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2339 MVT::ValueType VT = N0.getValueType();
2340
2341 // fold (sra c1, c2) -> c1>>c2
2342 if (N0C && N1C)
2343 return DAG.getNode(ISD::SRA, VT, N0, N1);
2344 // fold (sra 0, x) -> 0
2345 if (N0C && N0C->isNullValue())
2346 return N0;
2347 // fold (sra -1, x) -> -1
2348 if (N0C && N0C->isAllOnesValue())
2349 return N0;
2350 // fold (sra x, c >= size(x)) -> undef
2351 if (N1C && N1C->getValue() >= MVT::getSizeInBits(VT))
2352 return DAG.getNode(ISD::UNDEF, VT);
2353 // fold (sra x, 0) -> x
2354 if (N1C && N1C->isNullValue())
2355 return N0;
2356 // fold (sra (shl x, c1), c1) -> sext_inreg for some c1 and target supports
2357 // sext_inreg.
2358 if (N1C && N0.getOpcode() == ISD::SHL && N1 == N0.getOperand(1)) {
2359 unsigned LowBits = MVT::getSizeInBits(VT) - (unsigned)N1C->getValue();
2360 MVT::ValueType EVT;
2361 switch (LowBits) {
2362 default: EVT = MVT::Other; break;
2363 case 1: EVT = MVT::i1; break;
2364 case 8: EVT = MVT::i8; break;
2365 case 16: EVT = MVT::i16; break;
2366 case 32: EVT = MVT::i32; break;
2367 }
2368 if (EVT > MVT::Other && TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, EVT))
2369 return DAG.getNode(ISD::SIGN_EXTEND_INREG, VT, N0.getOperand(0),
2370 DAG.getValueType(EVT));
2371 }
2372
2373 // fold (sra (sra x, c1), c2) -> (sra x, c1+c2)
2374 if (N1C && N0.getOpcode() == ISD::SRA) {
2375 if (ConstantSDNode *C1 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
2376 unsigned Sum = N1C->getValue() + C1->getValue();
2377 if (Sum >= MVT::getSizeInBits(VT)) Sum = MVT::getSizeInBits(VT)-1;
2378 return DAG.getNode(ISD::SRA, VT, N0.getOperand(0),
2379 DAG.getConstant(Sum, N1C->getValueType(0)));
2380 }
2381 }
2382
2383 // Simplify, based on bits shifted out of the LHS.
2384 if (N1C && SimplifyDemandedBits(SDOperand(N, 0)))
2385 return SDOperand(N, 0);
2386
2387
2388 // If the sign bit is known to be zero, switch this to a SRL.
Dan Gohman07961cd2008-02-25 21:11:39 +00002389 if (DAG.SignBitIsZero(N0))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002390 return DAG.getNode(ISD::SRL, VT, N0, N1);
Chris Lattner91ed3c32007-12-06 07:33:36 +00002391
2392 return N1C ? visitShiftByConstant(N, N1C->getValue()) : SDOperand();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002393}
2394
2395SDOperand DAGCombiner::visitSRL(SDNode *N) {
2396 SDOperand N0 = N->getOperand(0);
2397 SDOperand N1 = N->getOperand(1);
2398 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
2399 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2400 MVT::ValueType VT = N0.getValueType();
2401 unsigned OpSizeInBits = MVT::getSizeInBits(VT);
2402
2403 // fold (srl c1, c2) -> c1 >>u c2
2404 if (N0C && N1C)
2405 return DAG.getNode(ISD::SRL, VT, N0, N1);
2406 // fold (srl 0, x) -> 0
2407 if (N0C && N0C->isNullValue())
2408 return N0;
2409 // fold (srl x, c >= size(x)) -> undef
2410 if (N1C && N1C->getValue() >= OpSizeInBits)
2411 return DAG.getNode(ISD::UNDEF, VT);
2412 // fold (srl x, 0) -> x
2413 if (N1C && N1C->isNullValue())
2414 return N0;
2415 // if (srl x, c) is known to be zero, return 0
Dan Gohman07961cd2008-02-25 21:11:39 +00002416 if (N1C && DAG.MaskedValueIsZero(SDOperand(N, 0),
2417 APInt::getAllOnesValue(OpSizeInBits)))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002418 return DAG.getConstant(0, VT);
2419
2420 // fold (srl (srl x, c1), c2) -> 0 or (srl x, c1+c2)
2421 if (N1C && N0.getOpcode() == ISD::SRL &&
2422 N0.getOperand(1).getOpcode() == ISD::Constant) {
2423 uint64_t c1 = cast<ConstantSDNode>(N0.getOperand(1))->getValue();
2424 uint64_t c2 = N1C->getValue();
2425 if (c1 + c2 > OpSizeInBits)
2426 return DAG.getConstant(0, VT);
2427 return DAG.getNode(ISD::SRL, VT, N0.getOperand(0),
2428 DAG.getConstant(c1 + c2, N1.getValueType()));
2429 }
2430
2431 // fold (srl (anyextend x), c) -> (anyextend (srl x, c))
2432 if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
2433 // Shifting in all undef bits?
2434 MVT::ValueType SmallVT = N0.getOperand(0).getValueType();
2435 if (N1C->getValue() >= MVT::getSizeInBits(SmallVT))
2436 return DAG.getNode(ISD::UNDEF, VT);
2437
2438 SDOperand SmallShift = DAG.getNode(ISD::SRL, SmallVT, N0.getOperand(0), N1);
2439 AddToWorkList(SmallShift.Val);
2440 return DAG.getNode(ISD::ANY_EXTEND, VT, SmallShift);
2441 }
2442
2443 // fold (srl (sra X, Y), 31) -> (srl X, 31). This srl only looks at the sign
2444 // bit, which is unmodified by sra.
2445 if (N1C && N1C->getValue()+1 == MVT::getSizeInBits(VT)) {
2446 if (N0.getOpcode() == ISD::SRA)
2447 return DAG.getNode(ISD::SRL, VT, N0.getOperand(0), N1);
2448 }
2449
2450 // fold (srl (ctlz x), "5") -> x iff x has one bit set (the low bit).
2451 if (N1C && N0.getOpcode() == ISD::CTLZ &&
2452 N1C->getValue() == Log2_32(MVT::getSizeInBits(VT))) {
Dan Gohmanbea075f2008-02-20 16:33:30 +00002453 APInt KnownZero, KnownOne;
2454 APInt Mask = APInt::getAllOnesValue(MVT::getSizeInBits(VT));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002455 DAG.ComputeMaskedBits(N0.getOperand(0), Mask, KnownZero, KnownOne);
2456
2457 // If any of the input bits are KnownOne, then the input couldn't be all
2458 // zeros, thus the result of the srl will always be zero.
Dan Gohmanbea075f2008-02-20 16:33:30 +00002459 if (KnownOne.getBoolValue()) return DAG.getConstant(0, VT);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002460
2461 // If all of the bits input the to ctlz node are known to be zero, then
2462 // the result of the ctlz is "32" and the result of the shift is one.
Dan Gohmanbea075f2008-02-20 16:33:30 +00002463 APInt UnknownBits = ~KnownZero & Mask;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002464 if (UnknownBits == 0) return DAG.getConstant(1, VT);
2465
2466 // Otherwise, check to see if there is exactly one bit input to the ctlz.
2467 if ((UnknownBits & (UnknownBits-1)) == 0) {
2468 // Okay, we know that only that the single bit specified by UnknownBits
2469 // could be set on input to the CTLZ node. If this bit is set, the SRL
2470 // will return 0, if it is clear, it returns 1. Change the CTLZ/SRL pair
2471 // to an SRL,XOR pair, which is likely to simplify more.
Dan Gohmanbea075f2008-02-20 16:33:30 +00002472 unsigned ShAmt = UnknownBits.countTrailingZeros();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002473 SDOperand Op = N0.getOperand(0);
2474 if (ShAmt) {
2475 Op = DAG.getNode(ISD::SRL, VT, Op,
2476 DAG.getConstant(ShAmt, TLI.getShiftAmountTy()));
2477 AddToWorkList(Op.Val);
2478 }
2479 return DAG.getNode(ISD::XOR, VT, Op, DAG.getConstant(1, VT));
2480 }
2481 }
2482
2483 // fold operands of srl based on knowledge that the low bits are not
2484 // demanded.
2485 if (N1C && SimplifyDemandedBits(SDOperand(N, 0)))
2486 return SDOperand(N, 0);
2487
Chris Lattner91ed3c32007-12-06 07:33:36 +00002488 return N1C ? visitShiftByConstant(N, N1C->getValue()) : SDOperand();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002489}
2490
2491SDOperand DAGCombiner::visitCTLZ(SDNode *N) {
2492 SDOperand N0 = N->getOperand(0);
2493 MVT::ValueType VT = N->getValueType(0);
2494
2495 // fold (ctlz c1) -> c2
2496 if (isa<ConstantSDNode>(N0))
2497 return DAG.getNode(ISD::CTLZ, VT, N0);
2498 return SDOperand();
2499}
2500
2501SDOperand DAGCombiner::visitCTTZ(SDNode *N) {
2502 SDOperand N0 = N->getOperand(0);
2503 MVT::ValueType VT = N->getValueType(0);
2504
2505 // fold (cttz c1) -> c2
2506 if (isa<ConstantSDNode>(N0))
2507 return DAG.getNode(ISD::CTTZ, VT, N0);
2508 return SDOperand();
2509}
2510
2511SDOperand DAGCombiner::visitCTPOP(SDNode *N) {
2512 SDOperand N0 = N->getOperand(0);
2513 MVT::ValueType VT = N->getValueType(0);
2514
2515 // fold (ctpop c1) -> c2
2516 if (isa<ConstantSDNode>(N0))
2517 return DAG.getNode(ISD::CTPOP, VT, N0);
2518 return SDOperand();
2519}
2520
2521SDOperand DAGCombiner::visitSELECT(SDNode *N) {
2522 SDOperand N0 = N->getOperand(0);
2523 SDOperand N1 = N->getOperand(1);
2524 SDOperand N2 = N->getOperand(2);
2525 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
2526 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2527 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2);
2528 MVT::ValueType VT = N->getValueType(0);
Evan Chengff601dc2007-08-18 05:57:05 +00002529 MVT::ValueType VT0 = N0.getValueType();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002530
2531 // fold select C, X, X -> X
2532 if (N1 == N2)
2533 return N1;
2534 // fold select true, X, Y -> X
2535 if (N0C && !N0C->isNullValue())
2536 return N1;
2537 // fold select false, X, Y -> Y
2538 if (N0C && N0C->isNullValue())
2539 return N2;
2540 // fold select C, 1, X -> C | X
2541 if (MVT::i1 == VT && N1C && N1C->getValue() == 1)
2542 return DAG.getNode(ISD::OR, VT, N0, N2);
Evan Chengff601dc2007-08-18 05:57:05 +00002543 // fold select C, 0, 1 -> ~C
2544 if (MVT::isInteger(VT) && MVT::isInteger(VT0) &&
2545 N1C && N2C && N1C->isNullValue() && N2C->getValue() == 1) {
2546 SDOperand XORNode = DAG.getNode(ISD::XOR, VT0, N0, DAG.getConstant(1, VT0));
2547 if (VT == VT0)
2548 return XORNode;
2549 AddToWorkList(XORNode.Val);
2550 if (MVT::getSizeInBits(VT) > MVT::getSizeInBits(VT0))
2551 return DAG.getNode(ISD::ZERO_EXTEND, VT, XORNode);
2552 return DAG.getNode(ISD::TRUNCATE, VT, XORNode);
2553 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002554 // fold select C, 0, X -> ~C & X
Dale Johannesen53e0ad72007-12-06 17:53:31 +00002555 if (VT == VT0 && VT == MVT::i1 && N1C && N1C->isNullValue()) {
2556 SDOperand XORNode = DAG.getNode(ISD::XOR, VT, N0, DAG.getConstant(1, VT));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002557 AddToWorkList(XORNode.Val);
2558 return DAG.getNode(ISD::AND, VT, XORNode, N2);
2559 }
2560 // fold select C, X, 1 -> ~C | X
Dale Johannesen53e0ad72007-12-06 17:53:31 +00002561 if (VT == VT0 && VT == MVT::i1 && N2C && N2C->getValue() == 1) {
2562 SDOperand XORNode = DAG.getNode(ISD::XOR, VT, N0, DAG.getConstant(1, VT));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002563 AddToWorkList(XORNode.Val);
2564 return DAG.getNode(ISD::OR, VT, XORNode, N1);
2565 }
2566 // fold select C, X, 0 -> C & X
2567 // FIXME: this should check for C type == X type, not i1?
2568 if (MVT::i1 == VT && N2C && N2C->isNullValue())
2569 return DAG.getNode(ISD::AND, VT, N0, N1);
2570 // fold X ? X : Y --> X ? 1 : Y --> X | Y
2571 if (MVT::i1 == VT && N0 == N1)
2572 return DAG.getNode(ISD::OR, VT, N0, N2);
2573 // fold X ? Y : X --> X ? Y : 0 --> X & Y
2574 if (MVT::i1 == VT && N0 == N2)
2575 return DAG.getNode(ISD::AND, VT, N0, N1);
2576
2577 // If we can fold this based on the true/false value, do so.
2578 if (SimplifySelectOps(N, N1, N2))
2579 return SDOperand(N, 0); // Don't revisit N.
2580
2581 // fold selects based on a setcc into other things, such as min/max/abs
Anton Korobeynikov53422f62008-02-20 11:10:28 +00002582 if (N0.getOpcode() == ISD::SETCC) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002583 // FIXME:
2584 // Check against MVT::Other for SELECT_CC, which is a workaround for targets
2585 // having to say they don't support SELECT_CC on every type the DAG knows
2586 // about, since there is no way to mark an opcode illegal at all value types
2587 if (TLI.isOperationLegal(ISD::SELECT_CC, MVT::Other))
2588 return DAG.getNode(ISD::SELECT_CC, VT, N0.getOperand(0), N0.getOperand(1),
2589 N1, N2, N0.getOperand(2));
2590 else
2591 return SimplifySelect(N0, N1, N2);
Anton Korobeynikov53422f62008-02-20 11:10:28 +00002592 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002593 return SDOperand();
2594}
2595
2596SDOperand DAGCombiner::visitSELECT_CC(SDNode *N) {
2597 SDOperand N0 = N->getOperand(0);
2598 SDOperand N1 = N->getOperand(1);
2599 SDOperand N2 = N->getOperand(2);
2600 SDOperand N3 = N->getOperand(3);
2601 SDOperand N4 = N->getOperand(4);
2602 ISD::CondCode CC = cast<CondCodeSDNode>(N4)->get();
2603
2604 // fold select_cc lhs, rhs, x, x, cc -> x
2605 if (N2 == N3)
2606 return N2;
2607
2608 // Determine if the condition we're dealing with is constant
Scott Michel502151f2008-03-10 15:42:14 +00002609 SDOperand SCC = SimplifySetCC(TLI.getSetCCResultType(N0), N0, N1, CC, false);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002610 if (SCC.Val) AddToWorkList(SCC.Val);
2611
2612 if (ConstantSDNode *SCCC = dyn_cast_or_null<ConstantSDNode>(SCC.Val)) {
2613 if (SCCC->getValue())
2614 return N2; // cond always true -> true val
2615 else
2616 return N3; // cond always false -> false val
2617 }
2618
2619 // Fold to a simpler select_cc
2620 if (SCC.Val && SCC.getOpcode() == ISD::SETCC)
2621 return DAG.getNode(ISD::SELECT_CC, N2.getValueType(),
2622 SCC.getOperand(0), SCC.getOperand(1), N2, N3,
2623 SCC.getOperand(2));
2624
2625 // If we can fold this based on the true/false value, do so.
2626 if (SimplifySelectOps(N, N2, N3))
2627 return SDOperand(N, 0); // Don't revisit N.
2628
2629 // fold select_cc into other things, such as min/max/abs
2630 return SimplifySelectCC(N0, N1, N2, N3, CC);
2631}
2632
2633SDOperand DAGCombiner::visitSETCC(SDNode *N) {
2634 return SimplifySetCC(N->getValueType(0), N->getOperand(0), N->getOperand(1),
2635 cast<CondCodeSDNode>(N->getOperand(2))->get());
2636}
2637
Evan Cheng9decb332007-10-29 19:58:20 +00002638// ExtendUsesToFormExtLoad - Trying to extend uses of a load to enable this:
2639// "fold ({s|z}ext (load x)) -> ({s|z}ext (truncate ({s|z}extload x)))"
2640// transformation. Returns true if extension are possible and the above
2641// mentioned transformation is profitable.
2642static bool ExtendUsesToFormExtLoad(SDNode *N, SDOperand N0,
2643 unsigned ExtOpc,
2644 SmallVector<SDNode*, 4> &ExtendNodes,
2645 TargetLowering &TLI) {
2646 bool HasCopyToRegUses = false;
2647 bool isTruncFree = TLI.isTruncateFree(N->getValueType(0), N0.getValueType());
2648 for (SDNode::use_iterator UI = N0.Val->use_begin(), UE = N0.Val->use_end();
2649 UI != UE; ++UI) {
2650 SDNode *User = *UI;
2651 if (User == N)
2652 continue;
2653 // FIXME: Only extend SETCC N, N and SETCC N, c for now.
2654 if (User->getOpcode() == ISD::SETCC) {
2655 ISD::CondCode CC = cast<CondCodeSDNode>(User->getOperand(2))->get();
2656 if (ExtOpc == ISD::ZERO_EXTEND && ISD::isSignedIntSetCC(CC))
2657 // Sign bits will be lost after a zext.
2658 return false;
2659 bool Add = false;
2660 for (unsigned i = 0; i != 2; ++i) {
2661 SDOperand UseOp = User->getOperand(i);
2662 if (UseOp == N0)
2663 continue;
2664 if (!isa<ConstantSDNode>(UseOp))
2665 return false;
2666 Add = true;
2667 }
2668 if (Add)
2669 ExtendNodes.push_back(User);
2670 } else {
2671 for (unsigned i = 0, e = User->getNumOperands(); i != e; ++i) {
2672 SDOperand UseOp = User->getOperand(i);
2673 if (UseOp == N0) {
2674 // If truncate from extended type to original load type is free
2675 // on this target, then it's ok to extend a CopyToReg.
2676 if (isTruncFree && User->getOpcode() == ISD::CopyToReg)
2677 HasCopyToRegUses = true;
2678 else
2679 return false;
2680 }
2681 }
2682 }
2683 }
2684
2685 if (HasCopyToRegUses) {
2686 bool BothLiveOut = false;
2687 for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
2688 UI != UE; ++UI) {
2689 SDNode *User = *UI;
2690 for (unsigned i = 0, e = User->getNumOperands(); i != e; ++i) {
2691 SDOperand UseOp = User->getOperand(i);
2692 if (UseOp.Val == N && UseOp.ResNo == 0) {
2693 BothLiveOut = true;
2694 break;
2695 }
2696 }
2697 }
2698 if (BothLiveOut)
2699 // Both unextended and extended values are live out. There had better be
2700 // good a reason for the transformation.
2701 return ExtendNodes.size();
2702 }
2703 return true;
2704}
2705
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002706SDOperand DAGCombiner::visitSIGN_EXTEND(SDNode *N) {
2707 SDOperand N0 = N->getOperand(0);
2708 MVT::ValueType VT = N->getValueType(0);
2709
2710 // fold (sext c1) -> c1
2711 if (isa<ConstantSDNode>(N0))
2712 return DAG.getNode(ISD::SIGN_EXTEND, VT, N0);
2713
2714 // fold (sext (sext x)) -> (sext x)
2715 // fold (sext (aext x)) -> (sext x)
2716 if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
2717 return DAG.getNode(ISD::SIGN_EXTEND, VT, N0.getOperand(0));
2718
2719 // fold (sext (truncate (load x))) -> (sext (smaller load x))
2720 // fold (sext (truncate (srl (load x), c))) -> (sext (smaller load (x+c/n)))
2721 if (N0.getOpcode() == ISD::TRUNCATE) {
2722 SDOperand NarrowLoad = ReduceLoadWidth(N0.Val);
2723 if (NarrowLoad.Val) {
2724 if (NarrowLoad.Val != N0.Val)
2725 CombineTo(N0.Val, NarrowLoad);
2726 return DAG.getNode(ISD::SIGN_EXTEND, VT, NarrowLoad);
2727 }
2728 }
2729
2730 // See if the value being truncated is already sign extended. If so, just
2731 // eliminate the trunc/sext pair.
2732 if (N0.getOpcode() == ISD::TRUNCATE) {
2733 SDOperand Op = N0.getOperand(0);
2734 unsigned OpBits = MVT::getSizeInBits(Op.getValueType());
2735 unsigned MidBits = MVT::getSizeInBits(N0.getValueType());
2736 unsigned DestBits = MVT::getSizeInBits(VT);
2737 unsigned NumSignBits = DAG.ComputeNumSignBits(Op);
2738
2739 if (OpBits == DestBits) {
2740 // Op is i32, Mid is i8, and Dest is i32. If Op has more than 24 sign
2741 // bits, it is already ready.
2742 if (NumSignBits > DestBits-MidBits)
2743 return Op;
2744 } else if (OpBits < DestBits) {
2745 // Op is i32, Mid is i8, and Dest is i64. If Op has more than 24 sign
2746 // bits, just sext from i32.
2747 if (NumSignBits > OpBits-MidBits)
2748 return DAG.getNode(ISD::SIGN_EXTEND, VT, Op);
2749 } else {
2750 // Op is i64, Mid is i8, and Dest is i32. If Op has more than 56 sign
2751 // bits, just truncate to i32.
2752 if (NumSignBits > OpBits-MidBits)
2753 return DAG.getNode(ISD::TRUNCATE, VT, Op);
2754 }
2755
2756 // fold (sext (truncate x)) -> (sextinreg x).
2757 if (!AfterLegalize || TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG,
2758 N0.getValueType())) {
2759 if (Op.getValueType() < VT)
2760 Op = DAG.getNode(ISD::ANY_EXTEND, VT, Op);
2761 else if (Op.getValueType() > VT)
2762 Op = DAG.getNode(ISD::TRUNCATE, VT, Op);
2763 return DAG.getNode(ISD::SIGN_EXTEND_INREG, VT, Op,
2764 DAG.getValueType(N0.getValueType()));
2765 }
2766 }
2767
2768 // fold (sext (load x)) -> (sext (truncate (sextload x)))
Evan Cheng9decb332007-10-29 19:58:20 +00002769 if (ISD::isNON_EXTLoad(N0.Val) &&
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002770 (!AfterLegalize||TLI.isLoadXLegal(ISD::SEXTLOAD, N0.getValueType()))){
Evan Cheng9decb332007-10-29 19:58:20 +00002771 bool DoXform = true;
2772 SmallVector<SDNode*, 4> SetCCs;
2773 if (!N0.hasOneUse())
2774 DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::SIGN_EXTEND, SetCCs, TLI);
2775 if (DoXform) {
2776 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
2777 SDOperand ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, VT, LN0->getChain(),
2778 LN0->getBasePtr(), LN0->getSrcValue(),
2779 LN0->getSrcValueOffset(),
2780 N0.getValueType(),
2781 LN0->isVolatile(),
2782 LN0->getAlignment());
2783 CombineTo(N, ExtLoad);
2784 SDOperand Trunc = DAG.getNode(ISD::TRUNCATE, N0.getValueType(), ExtLoad);
2785 CombineTo(N0.Val, Trunc, ExtLoad.getValue(1));
2786 // Extend SetCC uses if necessary.
2787 for (unsigned i = 0, e = SetCCs.size(); i != e; ++i) {
2788 SDNode *SetCC = SetCCs[i];
2789 SmallVector<SDOperand, 4> Ops;
2790 for (unsigned j = 0; j != 2; ++j) {
2791 SDOperand SOp = SetCC->getOperand(j);
2792 if (SOp == Trunc)
2793 Ops.push_back(ExtLoad);
2794 else
2795 Ops.push_back(DAG.getNode(ISD::SIGN_EXTEND, VT, SOp));
2796 }
2797 Ops.push_back(SetCC->getOperand(2));
2798 CombineTo(SetCC, DAG.getNode(ISD::SETCC, SetCC->getValueType(0),
2799 &Ops[0], Ops.size()));
2800 }
2801 return SDOperand(N, 0); // Return N so it doesn't get rechecked!
2802 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002803 }
2804
2805 // fold (sext (sextload x)) -> (sext (truncate (sextload x)))
2806 // fold (sext ( extload x)) -> (sext (truncate (sextload x)))
2807 if ((ISD::isSEXTLoad(N0.Val) || ISD::isEXTLoad(N0.Val)) &&
2808 ISD::isUNINDEXEDLoad(N0.Val) && N0.hasOneUse()) {
2809 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
Dan Gohman9a4c92c2008-01-30 00:15:11 +00002810 MVT::ValueType EVT = LN0->getMemoryVT();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002811 if (!AfterLegalize || TLI.isLoadXLegal(ISD::SEXTLOAD, EVT)) {
2812 SDOperand ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, VT, LN0->getChain(),
2813 LN0->getBasePtr(), LN0->getSrcValue(),
2814 LN0->getSrcValueOffset(), EVT,
2815 LN0->isVolatile(),
2816 LN0->getAlignment());
2817 CombineTo(N, ExtLoad);
2818 CombineTo(N0.Val, DAG.getNode(ISD::TRUNCATE, N0.getValueType(), ExtLoad),
2819 ExtLoad.getValue(1));
2820 return SDOperand(N, 0); // Return N so it doesn't get rechecked!
2821 }
2822 }
2823
2824 // sext(setcc x,y,cc) -> select_cc x, y, -1, 0, cc
2825 if (N0.getOpcode() == ISD::SETCC) {
2826 SDOperand SCC =
2827 SimplifySelectCC(N0.getOperand(0), N0.getOperand(1),
2828 DAG.getConstant(~0ULL, VT), DAG.getConstant(0, VT),
2829 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
2830 if (SCC.Val) return SCC;
2831 }
2832
2833 return SDOperand();
2834}
2835
2836SDOperand DAGCombiner::visitZERO_EXTEND(SDNode *N) {
2837 SDOperand N0 = N->getOperand(0);
2838 MVT::ValueType VT = N->getValueType(0);
2839
2840 // fold (zext c1) -> c1
2841 if (isa<ConstantSDNode>(N0))
2842 return DAG.getNode(ISD::ZERO_EXTEND, VT, N0);
2843 // fold (zext (zext x)) -> (zext x)
2844 // fold (zext (aext x)) -> (zext x)
2845 if (N0.getOpcode() == ISD::ZERO_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
2846 return DAG.getNode(ISD::ZERO_EXTEND, VT, N0.getOperand(0));
2847
2848 // fold (zext (truncate (load x))) -> (zext (smaller load x))
2849 // fold (zext (truncate (srl (load x), c))) -> (zext (small load (x+c/n)))
2850 if (N0.getOpcode() == ISD::TRUNCATE) {
2851 SDOperand NarrowLoad = ReduceLoadWidth(N0.Val);
2852 if (NarrowLoad.Val) {
2853 if (NarrowLoad.Val != N0.Val)
2854 CombineTo(N0.Val, NarrowLoad);
2855 return DAG.getNode(ISD::ZERO_EXTEND, VT, NarrowLoad);
2856 }
2857 }
2858
2859 // fold (zext (truncate x)) -> (and x, mask)
2860 if (N0.getOpcode() == ISD::TRUNCATE &&
2861 (!AfterLegalize || TLI.isOperationLegal(ISD::AND, VT))) {
2862 SDOperand Op = N0.getOperand(0);
2863 if (Op.getValueType() < VT) {
2864 Op = DAG.getNode(ISD::ANY_EXTEND, VT, Op);
2865 } else if (Op.getValueType() > VT) {
2866 Op = DAG.getNode(ISD::TRUNCATE, VT, Op);
2867 }
2868 return DAG.getZeroExtendInReg(Op, N0.getValueType());
2869 }
2870
2871 // fold (zext (and (trunc x), cst)) -> (and x, cst).
2872 if (N0.getOpcode() == ISD::AND &&
2873 N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
2874 N0.getOperand(1).getOpcode() == ISD::Constant) {
2875 SDOperand X = N0.getOperand(0).getOperand(0);
2876 if (X.getValueType() < VT) {
2877 X = DAG.getNode(ISD::ANY_EXTEND, VT, X);
2878 } else if (X.getValueType() > VT) {
2879 X = DAG.getNode(ISD::TRUNCATE, VT, X);
2880 }
Dan Gohmand047c3e2008-03-03 23:51:38 +00002881 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
2882 Mask.zext(MVT::getSizeInBits(VT));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002883 return DAG.getNode(ISD::AND, VT, X, DAG.getConstant(Mask, VT));
2884 }
2885
2886 // fold (zext (load x)) -> (zext (truncate (zextload x)))
Evan Cheng9decb332007-10-29 19:58:20 +00002887 if (ISD::isNON_EXTLoad(N0.Val) &&
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002888 (!AfterLegalize||TLI.isLoadXLegal(ISD::ZEXTLOAD, N0.getValueType()))) {
Evan Cheng9decb332007-10-29 19:58:20 +00002889 bool DoXform = true;
2890 SmallVector<SDNode*, 4> SetCCs;
2891 if (!N0.hasOneUse())
2892 DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ZERO_EXTEND, SetCCs, TLI);
2893 if (DoXform) {
2894 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
2895 SDOperand ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, VT, LN0->getChain(),
2896 LN0->getBasePtr(), LN0->getSrcValue(),
2897 LN0->getSrcValueOffset(),
2898 N0.getValueType(),
2899 LN0->isVolatile(),
2900 LN0->getAlignment());
2901 CombineTo(N, ExtLoad);
2902 SDOperand Trunc = DAG.getNode(ISD::TRUNCATE, N0.getValueType(), ExtLoad);
2903 CombineTo(N0.Val, Trunc, ExtLoad.getValue(1));
2904 // Extend SetCC uses if necessary.
2905 for (unsigned i = 0, e = SetCCs.size(); i != e; ++i) {
2906 SDNode *SetCC = SetCCs[i];
2907 SmallVector<SDOperand, 4> Ops;
2908 for (unsigned j = 0; j != 2; ++j) {
2909 SDOperand SOp = SetCC->getOperand(j);
2910 if (SOp == Trunc)
2911 Ops.push_back(ExtLoad);
2912 else
Evan Cheng06aaf4c2007-10-30 20:11:21 +00002913 Ops.push_back(DAG.getNode(ISD::ZERO_EXTEND, VT, SOp));
Evan Cheng9decb332007-10-29 19:58:20 +00002914 }
2915 Ops.push_back(SetCC->getOperand(2));
2916 CombineTo(SetCC, DAG.getNode(ISD::SETCC, SetCC->getValueType(0),
2917 &Ops[0], Ops.size()));
2918 }
2919 return SDOperand(N, 0); // Return N so it doesn't get rechecked!
2920 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002921 }
2922
2923 // fold (zext (zextload x)) -> (zext (truncate (zextload x)))
2924 // fold (zext ( extload x)) -> (zext (truncate (zextload x)))
2925 if ((ISD::isZEXTLoad(N0.Val) || ISD::isEXTLoad(N0.Val)) &&
2926 ISD::isUNINDEXEDLoad(N0.Val) && N0.hasOneUse()) {
2927 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
Dan Gohman9a4c92c2008-01-30 00:15:11 +00002928 MVT::ValueType EVT = LN0->getMemoryVT();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002929 SDOperand ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, VT, LN0->getChain(),
2930 LN0->getBasePtr(), LN0->getSrcValue(),
2931 LN0->getSrcValueOffset(), EVT,
2932 LN0->isVolatile(),
2933 LN0->getAlignment());
2934 CombineTo(N, ExtLoad);
2935 CombineTo(N0.Val, DAG.getNode(ISD::TRUNCATE, N0.getValueType(), ExtLoad),
2936 ExtLoad.getValue(1));
2937 return SDOperand(N, 0); // Return N so it doesn't get rechecked!
2938 }
2939
2940 // zext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
2941 if (N0.getOpcode() == ISD::SETCC) {
2942 SDOperand SCC =
2943 SimplifySelectCC(N0.getOperand(0), N0.getOperand(1),
2944 DAG.getConstant(1, VT), DAG.getConstant(0, VT),
2945 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
2946 if (SCC.Val) return SCC;
2947 }
2948
2949 return SDOperand();
2950}
2951
2952SDOperand DAGCombiner::visitANY_EXTEND(SDNode *N) {
2953 SDOperand N0 = N->getOperand(0);
2954 MVT::ValueType VT = N->getValueType(0);
2955
2956 // fold (aext c1) -> c1
2957 if (isa<ConstantSDNode>(N0))
2958 return DAG.getNode(ISD::ANY_EXTEND, VT, N0);
2959 // fold (aext (aext x)) -> (aext x)
2960 // fold (aext (zext x)) -> (zext x)
2961 // fold (aext (sext x)) -> (sext x)
2962 if (N0.getOpcode() == ISD::ANY_EXTEND ||
2963 N0.getOpcode() == ISD::ZERO_EXTEND ||
2964 N0.getOpcode() == ISD::SIGN_EXTEND)
2965 return DAG.getNode(N0.getOpcode(), VT, N0.getOperand(0));
2966
2967 // fold (aext (truncate (load x))) -> (aext (smaller load x))
2968 // fold (aext (truncate (srl (load x), c))) -> (aext (small load (x+c/n)))
2969 if (N0.getOpcode() == ISD::TRUNCATE) {
2970 SDOperand NarrowLoad = ReduceLoadWidth(N0.Val);
2971 if (NarrowLoad.Val) {
2972 if (NarrowLoad.Val != N0.Val)
2973 CombineTo(N0.Val, NarrowLoad);
2974 return DAG.getNode(ISD::ANY_EXTEND, VT, NarrowLoad);
2975 }
2976 }
2977
2978 // fold (aext (truncate x))
2979 if (N0.getOpcode() == ISD::TRUNCATE) {
2980 SDOperand TruncOp = N0.getOperand(0);
2981 if (TruncOp.getValueType() == VT)
2982 return TruncOp; // x iff x size == zext size.
2983 if (TruncOp.getValueType() > VT)
2984 return DAG.getNode(ISD::TRUNCATE, VT, TruncOp);
2985 return DAG.getNode(ISD::ANY_EXTEND, VT, TruncOp);
2986 }
2987
2988 // fold (aext (and (trunc x), cst)) -> (and x, cst).
2989 if (N0.getOpcode() == ISD::AND &&
2990 N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
2991 N0.getOperand(1).getOpcode() == ISD::Constant) {
2992 SDOperand X = N0.getOperand(0).getOperand(0);
2993 if (X.getValueType() < VT) {
2994 X = DAG.getNode(ISD::ANY_EXTEND, VT, X);
2995 } else if (X.getValueType() > VT) {
2996 X = DAG.getNode(ISD::TRUNCATE, VT, X);
2997 }
Dan Gohmand047c3e2008-03-03 23:51:38 +00002998 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
2999 Mask.zext(MVT::getSizeInBits(VT));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003000 return DAG.getNode(ISD::AND, VT, X, DAG.getConstant(Mask, VT));
3001 }
3002
3003 // fold (aext (load x)) -> (aext (truncate (extload x)))
3004 if (ISD::isNON_EXTLoad(N0.Val) && N0.hasOneUse() &&
3005 (!AfterLegalize||TLI.isLoadXLegal(ISD::EXTLOAD, N0.getValueType()))) {
3006 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
3007 SDOperand ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, VT, LN0->getChain(),
3008 LN0->getBasePtr(), LN0->getSrcValue(),
3009 LN0->getSrcValueOffset(),
3010 N0.getValueType(),
3011 LN0->isVolatile(),
3012 LN0->getAlignment());
3013 CombineTo(N, ExtLoad);
3014 CombineTo(N0.Val, DAG.getNode(ISD::TRUNCATE, N0.getValueType(), ExtLoad),
3015 ExtLoad.getValue(1));
3016 return SDOperand(N, 0); // Return N so it doesn't get rechecked!
3017 }
3018
3019 // fold (aext (zextload x)) -> (aext (truncate (zextload x)))
3020 // fold (aext (sextload x)) -> (aext (truncate (sextload x)))
3021 // fold (aext ( extload x)) -> (aext (truncate (extload x)))
3022 if (N0.getOpcode() == ISD::LOAD &&
3023 !ISD::isNON_EXTLoad(N0.Val) && ISD::isUNINDEXEDLoad(N0.Val) &&
3024 N0.hasOneUse()) {
3025 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
Dan Gohman9a4c92c2008-01-30 00:15:11 +00003026 MVT::ValueType EVT = LN0->getMemoryVT();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003027 SDOperand ExtLoad = DAG.getExtLoad(LN0->getExtensionType(), VT,
3028 LN0->getChain(), LN0->getBasePtr(),
3029 LN0->getSrcValue(),
3030 LN0->getSrcValueOffset(), EVT,
3031 LN0->isVolatile(),
3032 LN0->getAlignment());
3033 CombineTo(N, ExtLoad);
3034 CombineTo(N0.Val, DAG.getNode(ISD::TRUNCATE, N0.getValueType(), ExtLoad),
3035 ExtLoad.getValue(1));
3036 return SDOperand(N, 0); // Return N so it doesn't get rechecked!
3037 }
3038
3039 // aext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
3040 if (N0.getOpcode() == ISD::SETCC) {
3041 SDOperand SCC =
3042 SimplifySelectCC(N0.getOperand(0), N0.getOperand(1),
3043 DAG.getConstant(1, VT), DAG.getConstant(0, VT),
3044 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
3045 if (SCC.Val)
3046 return SCC;
3047 }
3048
3049 return SDOperand();
3050}
3051
Chris Lattnere8671c52007-10-13 06:35:54 +00003052/// GetDemandedBits - See if the specified operand can be simplified with the
3053/// knowledge that only the bits specified by Mask are used. If so, return the
3054/// simpler operand, otherwise return a null SDOperand.
Dan Gohman07961cd2008-02-25 21:11:39 +00003055SDOperand DAGCombiner::GetDemandedBits(SDOperand V, const APInt &Mask) {
Chris Lattnere8671c52007-10-13 06:35:54 +00003056 switch (V.getOpcode()) {
3057 default: break;
3058 case ISD::OR:
3059 case ISD::XOR:
3060 // If the LHS or RHS don't contribute bits to the or, drop them.
3061 if (DAG.MaskedValueIsZero(V.getOperand(0), Mask))
3062 return V.getOperand(1);
3063 if (DAG.MaskedValueIsZero(V.getOperand(1), Mask))
3064 return V.getOperand(0);
3065 break;
Chris Lattnerb77ea552007-10-13 06:58:48 +00003066 case ISD::SRL:
3067 // Only look at single-use SRLs.
3068 if (!V.Val->hasOneUse())
3069 break;
3070 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(V.getOperand(1))) {
3071 // See if we can recursively simplify the LHS.
3072 unsigned Amt = RHSC->getValue();
Dan Gohman07961cd2008-02-25 21:11:39 +00003073 APInt NewMask = Mask << Amt;
3074 SDOperand SimplifyLHS = GetDemandedBits(V.getOperand(0), NewMask);
Chris Lattnerb77ea552007-10-13 06:58:48 +00003075 if (SimplifyLHS.Val) {
3076 return DAG.getNode(ISD::SRL, V.getValueType(),
3077 SimplifyLHS, V.getOperand(1));
3078 }
3079 }
Chris Lattnere8671c52007-10-13 06:35:54 +00003080 }
3081 return SDOperand();
3082}
3083
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003084/// ReduceLoadWidth - If the result of a wider load is shifted to right of N
3085/// bits and then truncated to a narrower type and where N is a multiple
3086/// of number of bits of the narrower type, transform it to a narrower load
3087/// from address + N / num of bits of new type. If the result is to be
3088/// extended, also fold the extension to form a extending load.
3089SDOperand DAGCombiner::ReduceLoadWidth(SDNode *N) {
3090 unsigned Opc = N->getOpcode();
3091 ISD::LoadExtType ExtType = ISD::NON_EXTLOAD;
3092 SDOperand N0 = N->getOperand(0);
3093 MVT::ValueType VT = N->getValueType(0);
3094 MVT::ValueType EVT = N->getValueType(0);
3095
3096 // Special case: SIGN_EXTEND_INREG is basically truncating to EVT then
3097 // extended to VT.
3098 if (Opc == ISD::SIGN_EXTEND_INREG) {
3099 ExtType = ISD::SEXTLOAD;
3100 EVT = cast<VTSDNode>(N->getOperand(1))->getVT();
3101 if (AfterLegalize && !TLI.isLoadXLegal(ISD::SEXTLOAD, EVT))
3102 return SDOperand();
3103 }
3104
3105 unsigned EVTBits = MVT::getSizeInBits(EVT);
3106 unsigned ShAmt = 0;
3107 bool CombineSRL = false;
3108 if (N0.getOpcode() == ISD::SRL && N0.hasOneUse()) {
3109 if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
3110 ShAmt = N01->getValue();
3111 // Is the shift amount a multiple of size of VT?
3112 if ((ShAmt & (EVTBits-1)) == 0) {
3113 N0 = N0.getOperand(0);
3114 if (MVT::getSizeInBits(N0.getValueType()) <= EVTBits)
3115 return SDOperand();
3116 CombineSRL = true;
3117 }
3118 }
3119 }
3120
3121 if (ISD::isNON_EXTLoad(N0.Val) && N0.hasOneUse() &&
3122 // Do not allow folding to i1 here. i1 is implicitly stored in memory in
3123 // zero extended form: by shrinking the load, we lose track of the fact
3124 // that it is already zero extended.
3125 // FIXME: This should be reevaluated.
3126 VT != MVT::i1) {
3127 assert(MVT::getSizeInBits(N0.getValueType()) > EVTBits &&
3128 "Cannot truncate to larger type!");
3129 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
3130 MVT::ValueType PtrType = N0.getOperand(1).getValueType();
3131 // For big endian targets, we need to adjust the offset to the pointer to
3132 // load the correct bytes.
Duncan Sands9ff8fbf2008-02-11 10:37:04 +00003133 if (TLI.isBigEndian()) {
Duncan Sands4f18d4f2007-11-09 08:57:19 +00003134 unsigned LVTStoreBits = MVT::getStoreSizeInBits(N0.getValueType());
3135 unsigned EVTStoreBits = MVT::getStoreSizeInBits(EVT);
3136 ShAmt = LVTStoreBits - EVTStoreBits - ShAmt;
3137 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003138 uint64_t PtrOff = ShAmt / 8;
Duncan Sandsa3691432007-10-28 12:59:45 +00003139 unsigned NewAlign = MinAlign(LN0->getAlignment(), PtrOff);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003140 SDOperand NewPtr = DAG.getNode(ISD::ADD, PtrType, LN0->getBasePtr(),
3141 DAG.getConstant(PtrOff, PtrType));
3142 AddToWorkList(NewPtr.Val);
3143 SDOperand Load = (ExtType == ISD::NON_EXTLOAD)
3144 ? DAG.getLoad(VT, LN0->getChain(), NewPtr,
3145 LN0->getSrcValue(), LN0->getSrcValueOffset(),
Duncan Sandsa3691432007-10-28 12:59:45 +00003146 LN0->isVolatile(), NewAlign)
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003147 : DAG.getExtLoad(ExtType, VT, LN0->getChain(), NewPtr,
3148 LN0->getSrcValue(), LN0->getSrcValueOffset(), EVT,
Duncan Sandsa3691432007-10-28 12:59:45 +00003149 LN0->isVolatile(), NewAlign);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003150 AddToWorkList(N);
3151 if (CombineSRL) {
Chris Lattner7bcb18f2008-02-03 06:49:24 +00003152 WorkListRemover DeadNodes(*this);
3153 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1),
3154 &DeadNodes);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003155 CombineTo(N->getOperand(0).Val, Load);
3156 } else
3157 CombineTo(N0.Val, Load, Load.getValue(1));
3158 if (ShAmt) {
3159 if (Opc == ISD::SIGN_EXTEND_INREG)
3160 return DAG.getNode(Opc, VT, Load, N->getOperand(1));
3161 else
3162 return DAG.getNode(Opc, VT, Load);
3163 }
3164 return SDOperand(N, 0); // Return N so it doesn't get rechecked!
3165 }
3166
3167 return SDOperand();
3168}
3169
3170
3171SDOperand DAGCombiner::visitSIGN_EXTEND_INREG(SDNode *N) {
3172 SDOperand N0 = N->getOperand(0);
3173 SDOperand N1 = N->getOperand(1);
3174 MVT::ValueType VT = N->getValueType(0);
3175 MVT::ValueType EVT = cast<VTSDNode>(N1)->getVT();
Dan Gohman07961cd2008-02-25 21:11:39 +00003176 unsigned VTBits = MVT::getSizeInBits(VT);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003177 unsigned EVTBits = MVT::getSizeInBits(EVT);
3178
3179 // fold (sext_in_reg c1) -> c1
3180 if (isa<ConstantSDNode>(N0) || N0.getOpcode() == ISD::UNDEF)
3181 return DAG.getNode(ISD::SIGN_EXTEND_INREG, VT, N0, N1);
3182
3183 // If the input is already sign extended, just drop the extension.
3184 if (DAG.ComputeNumSignBits(N0) >= MVT::getSizeInBits(VT)-EVTBits+1)
3185 return N0;
3186
3187 // fold (sext_in_reg (sext_in_reg x, VT2), VT1) -> (sext_in_reg x, minVT) pt2
3188 if (N0.getOpcode() == ISD::SIGN_EXTEND_INREG &&
3189 EVT < cast<VTSDNode>(N0.getOperand(1))->getVT()) {
3190 return DAG.getNode(ISD::SIGN_EXTEND_INREG, VT, N0.getOperand(0), N1);
3191 }
3192
3193 // fold (sext_in_reg x) -> (zext_in_reg x) if the sign bit is known zero.
Dan Gohman07961cd2008-02-25 21:11:39 +00003194 if (DAG.MaskedValueIsZero(N0, APInt::getBitsSet(VTBits, EVTBits-1, EVTBits)))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003195 return DAG.getZeroExtendInReg(N0, EVT);
3196
3197 // fold operands of sext_in_reg based on knowledge that the top bits are not
3198 // demanded.
3199 if (SimplifyDemandedBits(SDOperand(N, 0)))
3200 return SDOperand(N, 0);
3201
3202 // fold (sext_in_reg (load x)) -> (smaller sextload x)
3203 // fold (sext_in_reg (srl (load x), c)) -> (smaller sextload (x+c/evtbits))
3204 SDOperand NarrowLoad = ReduceLoadWidth(N);
3205 if (NarrowLoad.Val)
3206 return NarrowLoad;
3207
3208 // fold (sext_in_reg (srl X, 24), i8) -> sra X, 24
3209 // fold (sext_in_reg (srl X, 23), i8) -> sra X, 23 iff possible.
3210 // We already fold "(sext_in_reg (srl X, 25), i8) -> srl X, 25" above.
3211 if (N0.getOpcode() == ISD::SRL) {
3212 if (ConstantSDNode *ShAmt = dyn_cast<ConstantSDNode>(N0.getOperand(1)))
3213 if (ShAmt->getValue()+EVTBits <= MVT::getSizeInBits(VT)) {
3214 // We can turn this into an SRA iff the input to the SRL is already sign
3215 // extended enough.
3216 unsigned InSignBits = DAG.ComputeNumSignBits(N0.getOperand(0));
3217 if (MVT::getSizeInBits(VT)-(ShAmt->getValue()+EVTBits) < InSignBits)
3218 return DAG.getNode(ISD::SRA, VT, N0.getOperand(0), N0.getOperand(1));
3219 }
3220 }
3221
3222 // fold (sext_inreg (extload x)) -> (sextload x)
3223 if (ISD::isEXTLoad(N0.Val) &&
3224 ISD::isUNINDEXEDLoad(N0.Val) &&
Dan Gohman9a4c92c2008-01-30 00:15:11 +00003225 EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003226 (!AfterLegalize || TLI.isLoadXLegal(ISD::SEXTLOAD, EVT))) {
3227 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
3228 SDOperand ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, VT, LN0->getChain(),
3229 LN0->getBasePtr(), LN0->getSrcValue(),
3230 LN0->getSrcValueOffset(), EVT,
3231 LN0->isVolatile(),
3232 LN0->getAlignment());
3233 CombineTo(N, ExtLoad);
3234 CombineTo(N0.Val, ExtLoad, ExtLoad.getValue(1));
3235 return SDOperand(N, 0); // Return N so it doesn't get rechecked!
3236 }
3237 // fold (sext_inreg (zextload x)) -> (sextload x) iff load has one use
3238 if (ISD::isZEXTLoad(N0.Val) && ISD::isUNINDEXEDLoad(N0.Val) &&
3239 N0.hasOneUse() &&
Dan Gohman9a4c92c2008-01-30 00:15:11 +00003240 EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003241 (!AfterLegalize || TLI.isLoadXLegal(ISD::SEXTLOAD, EVT))) {
3242 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
3243 SDOperand ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, VT, LN0->getChain(),
3244 LN0->getBasePtr(), LN0->getSrcValue(),
3245 LN0->getSrcValueOffset(), EVT,
3246 LN0->isVolatile(),
3247 LN0->getAlignment());
3248 CombineTo(N, ExtLoad);
3249 CombineTo(N0.Val, ExtLoad, ExtLoad.getValue(1));
3250 return SDOperand(N, 0); // Return N so it doesn't get rechecked!
3251 }
3252 return SDOperand();
3253}
3254
3255SDOperand DAGCombiner::visitTRUNCATE(SDNode *N) {
3256 SDOperand N0 = N->getOperand(0);
3257 MVT::ValueType VT = N->getValueType(0);
3258
3259 // noop truncate
3260 if (N0.getValueType() == N->getValueType(0))
3261 return N0;
3262 // fold (truncate c1) -> c1
3263 if (isa<ConstantSDNode>(N0))
3264 return DAG.getNode(ISD::TRUNCATE, VT, N0);
3265 // fold (truncate (truncate x)) -> (truncate x)
3266 if (N0.getOpcode() == ISD::TRUNCATE)
3267 return DAG.getNode(ISD::TRUNCATE, VT, N0.getOperand(0));
3268 // fold (truncate (ext x)) -> (ext x) or (truncate x) or x
3269 if (N0.getOpcode() == ISD::ZERO_EXTEND || N0.getOpcode() == ISD::SIGN_EXTEND||
3270 N0.getOpcode() == ISD::ANY_EXTEND) {
3271 if (N0.getOperand(0).getValueType() < VT)
3272 // if the source is smaller than the dest, we still need an extend
3273 return DAG.getNode(N0.getOpcode(), VT, N0.getOperand(0));
3274 else if (N0.getOperand(0).getValueType() > VT)
3275 // if the source is larger than the dest, than we just need the truncate
3276 return DAG.getNode(ISD::TRUNCATE, VT, N0.getOperand(0));
3277 else
3278 // if the source and dest are the same type, we can drop both the extend
3279 // and the truncate
3280 return N0.getOperand(0);
3281 }
3282
Chris Lattnere8671c52007-10-13 06:35:54 +00003283 // See if we can simplify the input to this truncate through knowledge that
3284 // only the low bits are being used. For example "trunc (or (shl x, 8), y)"
3285 // -> trunc y
Dan Gohman07961cd2008-02-25 21:11:39 +00003286 SDOperand Shorter =
3287 GetDemandedBits(N0, APInt::getLowBitsSet(N0.getValueSizeInBits(),
3288 MVT::getSizeInBits(VT)));
Chris Lattnere8671c52007-10-13 06:35:54 +00003289 if (Shorter.Val)
3290 return DAG.getNode(ISD::TRUNCATE, VT, Shorter);
3291
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003292 // fold (truncate (load x)) -> (smaller load x)
3293 // fold (truncate (srl (load x), c)) -> (smaller load (x+c/evtbits))
3294 return ReduceLoadWidth(N);
3295}
3296
3297SDOperand DAGCombiner::visitBIT_CONVERT(SDNode *N) {
3298 SDOperand N0 = N->getOperand(0);
3299 MVT::ValueType VT = N->getValueType(0);
3300
3301 // If the input is a BUILD_VECTOR with all constant elements, fold this now.
3302 // Only do this before legalize, since afterward the target may be depending
3303 // on the bitconvert.
3304 // First check to see if this is all constant.
3305 if (!AfterLegalize &&
3306 N0.getOpcode() == ISD::BUILD_VECTOR && N0.Val->hasOneUse() &&
3307 MVT::isVector(VT)) {
3308 bool isSimple = true;
3309 for (unsigned i = 0, e = N0.getNumOperands(); i != e; ++i)
3310 if (N0.getOperand(i).getOpcode() != ISD::UNDEF &&
3311 N0.getOperand(i).getOpcode() != ISD::Constant &&
3312 N0.getOperand(i).getOpcode() != ISD::ConstantFP) {
3313 isSimple = false;
3314 break;
3315 }
3316
3317 MVT::ValueType DestEltVT = MVT::getVectorElementType(N->getValueType(0));
3318 assert(!MVT::isVector(DestEltVT) &&
3319 "Element type of vector ValueType must not be vector!");
3320 if (isSimple) {
3321 return ConstantFoldBIT_CONVERTofBUILD_VECTOR(N0.Val, DestEltVT);
3322 }
3323 }
3324
3325 // If the input is a constant, let getNode() fold it.
3326 if (isa<ConstantSDNode>(N0) || isa<ConstantFPSDNode>(N0)) {
3327 SDOperand Res = DAG.getNode(ISD::BIT_CONVERT, VT, N0);
3328 if (Res.Val != N) return Res;
3329 }
3330
3331 if (N0.getOpcode() == ISD::BIT_CONVERT) // conv(conv(x,t1),t2) -> conv(x,t2)
3332 return DAG.getNode(ISD::BIT_CONVERT, VT, N0.getOperand(0));
3333
3334 // fold (conv (load x)) -> (load (conv*)x)
Evan Chengd7ba7ed2007-10-06 08:19:55 +00003335 // If the resultant load doesn't need a higher alignment than the original!
3336 if (ISD::isNormalLoad(N0.Val) && N0.hasOneUse() &&
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003337 TLI.isOperationLegal(ISD::LOAD, VT)) {
3338 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
3339 unsigned Align = TLI.getTargetMachine().getTargetData()->
3340 getABITypeAlignment(MVT::getTypeForValueType(VT));
3341 unsigned OrigAlign = LN0->getAlignment();
3342 if (Align <= OrigAlign) {
3343 SDOperand Load = DAG.getLoad(VT, LN0->getChain(), LN0->getBasePtr(),
3344 LN0->getSrcValue(), LN0->getSrcValueOffset(),
3345 LN0->isVolatile(), Align);
3346 AddToWorkList(N);
3347 CombineTo(N0.Val, DAG.getNode(ISD::BIT_CONVERT, N0.getValueType(), Load),
3348 Load.getValue(1));
3349 return Load;
3350 }
3351 }
3352
Chris Lattneref26cbc2008-01-27 17:42:27 +00003353 // Fold bitconvert(fneg(x)) -> xor(bitconvert(x), signbit)
3354 // Fold bitconvert(fabs(x)) -> and(bitconvert(x), ~signbit)
3355 // This often reduces constant pool loads.
3356 if ((N0.getOpcode() == ISD::FNEG || N0.getOpcode() == ISD::FABS) &&
3357 N0.Val->hasOneUse() && MVT::isInteger(VT) && !MVT::isVector(VT)) {
3358 SDOperand NewConv = DAG.getNode(ISD::BIT_CONVERT, VT, N0.getOperand(0));
3359 AddToWorkList(NewConv.Val);
3360
Dan Gohmand047c3e2008-03-03 23:51:38 +00003361 APInt SignBit = APInt::getSignBit(MVT::getSizeInBits(VT));
Chris Lattneref26cbc2008-01-27 17:42:27 +00003362 if (N0.getOpcode() == ISD::FNEG)
3363 return DAG.getNode(ISD::XOR, VT, NewConv, DAG.getConstant(SignBit, VT));
3364 assert(N0.getOpcode() == ISD::FABS);
3365 return DAG.getNode(ISD::AND, VT, NewConv, DAG.getConstant(~SignBit, VT));
3366 }
3367
3368 // Fold bitconvert(fcopysign(cst, x)) -> bitconvert(x)&sign | cst&~sign'
3369 // Note that we don't handle copysign(x,cst) because this can always be folded
3370 // to an fneg or fabs.
3371 if (N0.getOpcode() == ISD::FCOPYSIGN && N0.Val->hasOneUse() &&
Chris Lattner336672f2008-01-27 23:32:17 +00003372 isa<ConstantFPSDNode>(N0.getOperand(0)) &&
3373 MVT::isInteger(VT) && !MVT::isVector(VT)) {
Chris Lattneref26cbc2008-01-27 17:42:27 +00003374 unsigned OrigXWidth = MVT::getSizeInBits(N0.getOperand(1).getValueType());
3375 SDOperand X = DAG.getNode(ISD::BIT_CONVERT, MVT::getIntegerType(OrigXWidth),
3376 N0.getOperand(1));
3377 AddToWorkList(X.Val);
3378
3379 // If X has a different width than the result/lhs, sext it or truncate it.
3380 unsigned VTWidth = MVT::getSizeInBits(VT);
3381 if (OrigXWidth < VTWidth) {
3382 X = DAG.getNode(ISD::SIGN_EXTEND, VT, X);
3383 AddToWorkList(X.Val);
3384 } else if (OrigXWidth > VTWidth) {
3385 // To get the sign bit in the right place, we have to shift it right
3386 // before truncating.
3387 X = DAG.getNode(ISD::SRL, X.getValueType(), X,
3388 DAG.getConstant(OrigXWidth-VTWidth, X.getValueType()));
3389 AddToWorkList(X.Val);
3390 X = DAG.getNode(ISD::TRUNCATE, VT, X);
3391 AddToWorkList(X.Val);
3392 }
3393
Dan Gohmand047c3e2008-03-03 23:51:38 +00003394 APInt SignBit = APInt::getSignBit(MVT::getSizeInBits(VT));
Chris Lattneref26cbc2008-01-27 17:42:27 +00003395 X = DAG.getNode(ISD::AND, VT, X, DAG.getConstant(SignBit, VT));
3396 AddToWorkList(X.Val);
3397
3398 SDOperand Cst = DAG.getNode(ISD::BIT_CONVERT, VT, N0.getOperand(0));
3399 Cst = DAG.getNode(ISD::AND, VT, Cst, DAG.getConstant(~SignBit, VT));
3400 AddToWorkList(Cst.Val);
3401
3402 return DAG.getNode(ISD::OR, VT, X, Cst);
3403 }
3404
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003405 return SDOperand();
3406}
3407
3408/// ConstantFoldBIT_CONVERTofBUILD_VECTOR - We know that BV is a build_vector
3409/// node with Constant, ConstantFP or Undef operands. DstEltVT indicates the
3410/// destination element value type.
3411SDOperand DAGCombiner::
3412ConstantFoldBIT_CONVERTofBUILD_VECTOR(SDNode *BV, MVT::ValueType DstEltVT) {
3413 MVT::ValueType SrcEltVT = BV->getOperand(0).getValueType();
3414
3415 // If this is already the right type, we're done.
3416 if (SrcEltVT == DstEltVT) return SDOperand(BV, 0);
3417
3418 unsigned SrcBitSize = MVT::getSizeInBits(SrcEltVT);
3419 unsigned DstBitSize = MVT::getSizeInBits(DstEltVT);
3420
3421 // If this is a conversion of N elements of one type to N elements of another
3422 // type, convert each element. This handles FP<->INT cases.
3423 if (SrcBitSize == DstBitSize) {
3424 SmallVector<SDOperand, 8> Ops;
3425 for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) {
3426 Ops.push_back(DAG.getNode(ISD::BIT_CONVERT, DstEltVT, BV->getOperand(i)));
3427 AddToWorkList(Ops.back().Val);
3428 }
3429 MVT::ValueType VT =
3430 MVT::getVectorType(DstEltVT,
3431 MVT::getVectorNumElements(BV->getValueType(0)));
3432 return DAG.getNode(ISD::BUILD_VECTOR, VT, &Ops[0], Ops.size());
3433 }
3434
3435 // Otherwise, we're growing or shrinking the elements. To avoid having to
3436 // handle annoying details of growing/shrinking FP values, we convert them to
3437 // int first.
3438 if (MVT::isFloatingPoint(SrcEltVT)) {
3439 // Convert the input float vector to a int vector where the elements are the
3440 // same sizes.
3441 assert((SrcEltVT == MVT::f32 || SrcEltVT == MVT::f64) && "Unknown FP VT!");
3442 MVT::ValueType IntVT = SrcEltVT == MVT::f32 ? MVT::i32 : MVT::i64;
3443 BV = ConstantFoldBIT_CONVERTofBUILD_VECTOR(BV, IntVT).Val;
3444 SrcEltVT = IntVT;
3445 }
3446
3447 // Now we know the input is an integer vector. If the output is a FP type,
3448 // convert to integer first, then to FP of the right size.
3449 if (MVT::isFloatingPoint(DstEltVT)) {
3450 assert((DstEltVT == MVT::f32 || DstEltVT == MVT::f64) && "Unknown FP VT!");
3451 MVT::ValueType TmpVT = DstEltVT == MVT::f32 ? MVT::i32 : MVT::i64;
3452 SDNode *Tmp = ConstantFoldBIT_CONVERTofBUILD_VECTOR(BV, TmpVT).Val;
3453
3454 // Next, convert to FP elements of the same size.
3455 return ConstantFoldBIT_CONVERTofBUILD_VECTOR(Tmp, DstEltVT);
3456 }
3457
3458 // Okay, we know the src/dst types are both integers of differing types.
3459 // Handling growing first.
3460 assert(MVT::isInteger(SrcEltVT) && MVT::isInteger(DstEltVT));
3461 if (SrcBitSize < DstBitSize) {
3462 unsigned NumInputsPerOutput = DstBitSize/SrcBitSize;
3463
3464 SmallVector<SDOperand, 8> Ops;
3465 for (unsigned i = 0, e = BV->getNumOperands(); i != e;
3466 i += NumInputsPerOutput) {
3467 bool isLE = TLI.isLittleEndian();
Dan Gohmand047c3e2008-03-03 23:51:38 +00003468 APInt NewBits = APInt(DstBitSize, 0);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003469 bool EltIsUndef = true;
3470 for (unsigned j = 0; j != NumInputsPerOutput; ++j) {
3471 // Shift the previously computed bits over.
3472 NewBits <<= SrcBitSize;
3473 SDOperand Op = BV->getOperand(i+ (isLE ? (NumInputsPerOutput-j-1) : j));
3474 if (Op.getOpcode() == ISD::UNDEF) continue;
3475 EltIsUndef = false;
3476
Dan Gohmand047c3e2008-03-03 23:51:38 +00003477 NewBits |=
3478 APInt(cast<ConstantSDNode>(Op)->getAPIntValue()).zext(DstBitSize);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003479 }
3480
3481 if (EltIsUndef)
3482 Ops.push_back(DAG.getNode(ISD::UNDEF, DstEltVT));
3483 else
3484 Ops.push_back(DAG.getConstant(NewBits, DstEltVT));
3485 }
3486
Evan Chengd1045a62008-02-18 23:04:32 +00003487 MVT::ValueType VT = MVT::getVectorType(DstEltVT, Ops.size());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003488 return DAG.getNode(ISD::BUILD_VECTOR, VT, &Ops[0], Ops.size());
3489 }
3490
3491 // Finally, this must be the case where we are shrinking elements: each input
3492 // turns into multiple outputs.
Evan Chengd1045a62008-02-18 23:04:32 +00003493 bool isS2V = ISD::isScalarToVector(BV);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003494 unsigned NumOutputsPerInput = SrcBitSize/DstBitSize;
Evan Chengd1045a62008-02-18 23:04:32 +00003495 MVT::ValueType VT = MVT::getVectorType(DstEltVT,
3496 NumOutputsPerInput * BV->getNumOperands());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003497 SmallVector<SDOperand, 8> Ops;
3498 for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) {
3499 if (BV->getOperand(i).getOpcode() == ISD::UNDEF) {
3500 for (unsigned j = 0; j != NumOutputsPerInput; ++j)
3501 Ops.push_back(DAG.getNode(ISD::UNDEF, DstEltVT));
3502 continue;
3503 }
Dan Gohmand047c3e2008-03-03 23:51:38 +00003504 APInt OpVal = cast<ConstantSDNode>(BV->getOperand(i))->getAPIntValue();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003505 for (unsigned j = 0; j != NumOutputsPerInput; ++j) {
Dan Gohmand047c3e2008-03-03 23:51:38 +00003506 APInt ThisVal = APInt(OpVal).trunc(DstBitSize);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003507 Ops.push_back(DAG.getConstant(ThisVal, DstEltVT));
Dan Gohmand047c3e2008-03-03 23:51:38 +00003508 if (isS2V && i == 0 && j == 0 && APInt(ThisVal).zext(SrcBitSize) == OpVal)
Evan Chengd1045a62008-02-18 23:04:32 +00003509 // Simply turn this into a SCALAR_TO_VECTOR of the new type.
3510 return DAG.getNode(ISD::SCALAR_TO_VECTOR, VT, Ops[0]);
Dan Gohmand047c3e2008-03-03 23:51:38 +00003511 OpVal = OpVal.lshr(DstBitSize);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003512 }
3513
3514 // For big endian targets, swap the order of the pieces of each element.
Duncan Sands9ff8fbf2008-02-11 10:37:04 +00003515 if (TLI.isBigEndian())
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003516 std::reverse(Ops.end()-NumOutputsPerInput, Ops.end());
3517 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003518 return DAG.getNode(ISD::BUILD_VECTOR, VT, &Ops[0], Ops.size());
3519}
3520
3521
3522
3523SDOperand DAGCombiner::visitFADD(SDNode *N) {
3524 SDOperand N0 = N->getOperand(0);
3525 SDOperand N1 = N->getOperand(1);
3526 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
3527 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
3528 MVT::ValueType VT = N->getValueType(0);
3529
3530 // fold vector ops
3531 if (MVT::isVector(VT)) {
3532 SDOperand FoldedVOp = SimplifyVBinOp(N);
3533 if (FoldedVOp.Val) return FoldedVOp;
3534 }
3535
3536 // fold (fadd c1, c2) -> c1+c2
Dale Johannesenb89072e2007-10-16 23:38:29 +00003537 if (N0CFP && N1CFP && VT != MVT::ppcf128)
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003538 return DAG.getNode(ISD::FADD, VT, N0, N1);
3539 // canonicalize constant to RHS
3540 if (N0CFP && !N1CFP)
3541 return DAG.getNode(ISD::FADD, VT, N1, N0);
3542 // fold (A + (-B)) -> A-B
Chris Lattnere0992b82008-02-26 07:04:54 +00003543 if (isNegatibleForFree(N1, AfterLegalize) == 2)
3544 return DAG.getNode(ISD::FSUB, VT, N0,
3545 GetNegatedExpression(N1, DAG, AfterLegalize));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003546 // fold ((-A) + B) -> B-A
Chris Lattnere0992b82008-02-26 07:04:54 +00003547 if (isNegatibleForFree(N0, AfterLegalize) == 2)
3548 return DAG.getNode(ISD::FSUB, VT, N1,
3549 GetNegatedExpression(N0, DAG, AfterLegalize));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003550
3551 // If allowed, fold (fadd (fadd x, c1), c2) -> (fadd x, (fadd c1, c2))
3552 if (UnsafeFPMath && N1CFP && N0.getOpcode() == ISD::FADD &&
3553 N0.Val->hasOneUse() && isa<ConstantFPSDNode>(N0.getOperand(1)))
3554 return DAG.getNode(ISD::FADD, VT, N0.getOperand(0),
3555 DAG.getNode(ISD::FADD, VT, N0.getOperand(1), N1));
3556
3557 return SDOperand();
3558}
3559
3560SDOperand DAGCombiner::visitFSUB(SDNode *N) {
3561 SDOperand N0 = N->getOperand(0);
3562 SDOperand N1 = N->getOperand(1);
3563 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
3564 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
3565 MVT::ValueType VT = N->getValueType(0);
3566
3567 // fold vector ops
3568 if (MVT::isVector(VT)) {
3569 SDOperand FoldedVOp = SimplifyVBinOp(N);
3570 if (FoldedVOp.Val) return FoldedVOp;
3571 }
3572
3573 // fold (fsub c1, c2) -> c1-c2
Dale Johannesenb89072e2007-10-16 23:38:29 +00003574 if (N0CFP && N1CFP && VT != MVT::ppcf128)
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003575 return DAG.getNode(ISD::FSUB, VT, N0, N1);
3576 // fold (0-B) -> -B
Dale Johannesen7604c1b2007-08-31 23:34:27 +00003577 if (UnsafeFPMath && N0CFP && N0CFP->getValueAPF().isZero()) {
Chris Lattnere0992b82008-02-26 07:04:54 +00003578 if (isNegatibleForFree(N1, AfterLegalize))
3579 return GetNegatedExpression(N1, DAG, AfterLegalize);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003580 return DAG.getNode(ISD::FNEG, VT, N1);
3581 }
3582 // fold (A-(-B)) -> A+B
Chris Lattnere0992b82008-02-26 07:04:54 +00003583 if (isNegatibleForFree(N1, AfterLegalize))
3584 return DAG.getNode(ISD::FADD, VT, N0,
3585 GetNegatedExpression(N1, DAG, AfterLegalize));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003586
3587 return SDOperand();
3588}
3589
3590SDOperand DAGCombiner::visitFMUL(SDNode *N) {
3591 SDOperand N0 = N->getOperand(0);
3592 SDOperand N1 = N->getOperand(1);
3593 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
3594 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
3595 MVT::ValueType VT = N->getValueType(0);
3596
3597 // fold vector ops
3598 if (MVT::isVector(VT)) {
3599 SDOperand FoldedVOp = SimplifyVBinOp(N);
3600 if (FoldedVOp.Val) return FoldedVOp;
3601 }
3602
3603 // fold (fmul c1, c2) -> c1*c2
Dale Johannesenb89072e2007-10-16 23:38:29 +00003604 if (N0CFP && N1CFP && VT != MVT::ppcf128)
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003605 return DAG.getNode(ISD::FMUL, VT, N0, N1);
3606 // canonicalize constant to RHS
3607 if (N0CFP && !N1CFP)
3608 return DAG.getNode(ISD::FMUL, VT, N1, N0);
3609 // fold (fmul X, 2.0) -> (fadd X, X)
3610 if (N1CFP && N1CFP->isExactlyValue(+2.0))
3611 return DAG.getNode(ISD::FADD, VT, N0, N0);
3612 // fold (fmul X, -1.0) -> (fneg X)
3613 if (N1CFP && N1CFP->isExactlyValue(-1.0))
3614 return DAG.getNode(ISD::FNEG, VT, N0);
3615
3616 // -X * -Y -> X*Y
Chris Lattnere0992b82008-02-26 07:04:54 +00003617 if (char LHSNeg = isNegatibleForFree(N0, AfterLegalize)) {
3618 if (char RHSNeg = isNegatibleForFree(N1, AfterLegalize)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003619 // Both can be negated for free, check to see if at least one is cheaper
3620 // negated.
3621 if (LHSNeg == 2 || RHSNeg == 2)
Chris Lattnere0992b82008-02-26 07:04:54 +00003622 return DAG.getNode(ISD::FMUL, VT,
3623 GetNegatedExpression(N0, DAG, AfterLegalize),
3624 GetNegatedExpression(N1, DAG, AfterLegalize));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003625 }
3626 }
3627
3628 // If allowed, fold (fmul (fmul x, c1), c2) -> (fmul x, (fmul c1, c2))
3629 if (UnsafeFPMath && N1CFP && N0.getOpcode() == ISD::FMUL &&
3630 N0.Val->hasOneUse() && isa<ConstantFPSDNode>(N0.getOperand(1)))
3631 return DAG.getNode(ISD::FMUL, VT, N0.getOperand(0),
3632 DAG.getNode(ISD::FMUL, VT, N0.getOperand(1), N1));
3633
3634 return SDOperand();
3635}
3636
3637SDOperand DAGCombiner::visitFDIV(SDNode *N) {
3638 SDOperand N0 = N->getOperand(0);
3639 SDOperand N1 = N->getOperand(1);
3640 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
3641 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
3642 MVT::ValueType VT = N->getValueType(0);
3643
3644 // fold vector ops
3645 if (MVT::isVector(VT)) {
3646 SDOperand FoldedVOp = SimplifyVBinOp(N);
3647 if (FoldedVOp.Val) return FoldedVOp;
3648 }
3649
3650 // fold (fdiv c1, c2) -> c1/c2
Dale Johannesenb89072e2007-10-16 23:38:29 +00003651 if (N0CFP && N1CFP && VT != MVT::ppcf128)
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003652 return DAG.getNode(ISD::FDIV, VT, N0, N1);
3653
3654
3655 // -X / -Y -> X*Y
Chris Lattnere0992b82008-02-26 07:04:54 +00003656 if (char LHSNeg = isNegatibleForFree(N0, AfterLegalize)) {
3657 if (char RHSNeg = isNegatibleForFree(N1, AfterLegalize)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003658 // Both can be negated for free, check to see if at least one is cheaper
3659 // negated.
3660 if (LHSNeg == 2 || RHSNeg == 2)
Chris Lattnere0992b82008-02-26 07:04:54 +00003661 return DAG.getNode(ISD::FDIV, VT,
3662 GetNegatedExpression(N0, DAG, AfterLegalize),
3663 GetNegatedExpression(N1, DAG, AfterLegalize));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003664 }
3665 }
3666
3667 return SDOperand();
3668}
3669
3670SDOperand DAGCombiner::visitFREM(SDNode *N) {
3671 SDOperand N0 = N->getOperand(0);
3672 SDOperand N1 = N->getOperand(1);
3673 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
3674 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
3675 MVT::ValueType VT = N->getValueType(0);
3676
3677 // fold (frem c1, c2) -> fmod(c1,c2)
Dale Johannesenb89072e2007-10-16 23:38:29 +00003678 if (N0CFP && N1CFP && VT != MVT::ppcf128)
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003679 return DAG.getNode(ISD::FREM, VT, N0, N1);
3680
3681 return SDOperand();
3682}
3683
3684SDOperand DAGCombiner::visitFCOPYSIGN(SDNode *N) {
3685 SDOperand N0 = N->getOperand(0);
3686 SDOperand N1 = N->getOperand(1);
3687 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
3688 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
3689 MVT::ValueType VT = N->getValueType(0);
3690
Dale Johannesenb89072e2007-10-16 23:38:29 +00003691 if (N0CFP && N1CFP && VT != MVT::ppcf128) // Constant fold
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003692 return DAG.getNode(ISD::FCOPYSIGN, VT, N0, N1);
3693
3694 if (N1CFP) {
Dale Johannesenc53301c2007-08-26 01:18:27 +00003695 const APFloat& V = N1CFP->getValueAPF();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003696 // copysign(x, c1) -> fabs(x) iff ispos(c1)
3697 // copysign(x, c1) -> fneg(fabs(x)) iff isneg(c1)
Dale Johannesen7f2c1d12007-08-25 22:10:57 +00003698 if (!V.isNegative())
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003699 return DAG.getNode(ISD::FABS, VT, N0);
3700 else
3701 return DAG.getNode(ISD::FNEG, VT, DAG.getNode(ISD::FABS, VT, N0));
3702 }
3703
3704 // copysign(fabs(x), y) -> copysign(x, y)
3705 // copysign(fneg(x), y) -> copysign(x, y)
3706 // copysign(copysign(x,z), y) -> copysign(x, y)
3707 if (N0.getOpcode() == ISD::FABS || N0.getOpcode() == ISD::FNEG ||
3708 N0.getOpcode() == ISD::FCOPYSIGN)
3709 return DAG.getNode(ISD::FCOPYSIGN, VT, N0.getOperand(0), N1);
3710
3711 // copysign(x, abs(y)) -> abs(x)
3712 if (N1.getOpcode() == ISD::FABS)
3713 return DAG.getNode(ISD::FABS, VT, N0);
3714
3715 // copysign(x, copysign(y,z)) -> copysign(x, z)
3716 if (N1.getOpcode() == ISD::FCOPYSIGN)
3717 return DAG.getNode(ISD::FCOPYSIGN, VT, N0, N1.getOperand(1));
3718
3719 // copysign(x, fp_extend(y)) -> copysign(x, y)
3720 // copysign(x, fp_round(y)) -> copysign(x, y)
3721 if (N1.getOpcode() == ISD::FP_EXTEND || N1.getOpcode() == ISD::FP_ROUND)
3722 return DAG.getNode(ISD::FCOPYSIGN, VT, N0, N1.getOperand(0));
3723
3724 return SDOperand();
3725}
3726
3727
3728
3729SDOperand DAGCombiner::visitSINT_TO_FP(SDNode *N) {
3730 SDOperand N0 = N->getOperand(0);
3731 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
3732 MVT::ValueType VT = N->getValueType(0);
3733
3734 // fold (sint_to_fp c1) -> c1fp
Dale Johannesenb89072e2007-10-16 23:38:29 +00003735 if (N0C && N0.getValueType() != MVT::ppcf128)
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003736 return DAG.getNode(ISD::SINT_TO_FP, VT, N0);
3737 return SDOperand();
3738}
3739
3740SDOperand DAGCombiner::visitUINT_TO_FP(SDNode *N) {
3741 SDOperand N0 = N->getOperand(0);
3742 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
3743 MVT::ValueType VT = N->getValueType(0);
3744
3745 // fold (uint_to_fp c1) -> c1fp
Dale Johannesenb89072e2007-10-16 23:38:29 +00003746 if (N0C && N0.getValueType() != MVT::ppcf128)
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003747 return DAG.getNode(ISD::UINT_TO_FP, VT, N0);
3748 return SDOperand();
3749}
3750
3751SDOperand DAGCombiner::visitFP_TO_SINT(SDNode *N) {
3752 SDOperand N0 = N->getOperand(0);
3753 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
3754 MVT::ValueType VT = N->getValueType(0);
3755
3756 // fold (fp_to_sint c1fp) -> c1
3757 if (N0CFP)
3758 return DAG.getNode(ISD::FP_TO_SINT, VT, N0);
3759 return SDOperand();
3760}
3761
3762SDOperand DAGCombiner::visitFP_TO_UINT(SDNode *N) {
3763 SDOperand N0 = N->getOperand(0);
3764 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
3765 MVT::ValueType VT = N->getValueType(0);
3766
3767 // fold (fp_to_uint c1fp) -> c1
Dale Johannesenb89072e2007-10-16 23:38:29 +00003768 if (N0CFP && VT != MVT::ppcf128)
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003769 return DAG.getNode(ISD::FP_TO_UINT, VT, N0);
3770 return SDOperand();
3771}
3772
3773SDOperand DAGCombiner::visitFP_ROUND(SDNode *N) {
3774 SDOperand N0 = N->getOperand(0);
Chris Lattner5872a362008-01-17 07:00:52 +00003775 SDOperand N1 = N->getOperand(1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003776 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
3777 MVT::ValueType VT = N->getValueType(0);
3778
3779 // fold (fp_round c1fp) -> c1fp
Dale Johannesenb89072e2007-10-16 23:38:29 +00003780 if (N0CFP && N0.getValueType() != MVT::ppcf128)
Chris Lattner5872a362008-01-17 07:00:52 +00003781 return DAG.getNode(ISD::FP_ROUND, VT, N0, N1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003782
3783 // fold (fp_round (fp_extend x)) -> x
3784 if (N0.getOpcode() == ISD::FP_EXTEND && VT == N0.getOperand(0).getValueType())
3785 return N0.getOperand(0);
3786
Chris Lattner7afb8552008-01-24 06:45:35 +00003787 // fold (fp_round (fp_round x)) -> (fp_round x)
3788 if (N0.getOpcode() == ISD::FP_ROUND) {
3789 // This is a value preserving truncation if both round's are.
3790 bool IsTrunc = N->getConstantOperandVal(1) == 1 &&
3791 N0.Val->getConstantOperandVal(1) == 1;
3792 return DAG.getNode(ISD::FP_ROUND, VT, N0.getOperand(0),
3793 DAG.getIntPtrConstant(IsTrunc));
3794 }
3795
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003796 // fold (fp_round (copysign X, Y)) -> (copysign (fp_round X), Y)
3797 if (N0.getOpcode() == ISD::FCOPYSIGN && N0.Val->hasOneUse()) {
Chris Lattner5872a362008-01-17 07:00:52 +00003798 SDOperand Tmp = DAG.getNode(ISD::FP_ROUND, VT, N0.getOperand(0), N1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003799 AddToWorkList(Tmp.Val);
3800 return DAG.getNode(ISD::FCOPYSIGN, VT, Tmp, N0.getOperand(1));
3801 }
3802
3803 return SDOperand();
3804}
3805
3806SDOperand DAGCombiner::visitFP_ROUND_INREG(SDNode *N) {
3807 SDOperand N0 = N->getOperand(0);
3808 MVT::ValueType VT = N->getValueType(0);
3809 MVT::ValueType EVT = cast<VTSDNode>(N->getOperand(1))->getVT();
3810 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
3811
3812 // fold (fp_round_inreg c1fp) -> c1fp
3813 if (N0CFP) {
Dale Johannesen7604c1b2007-08-31 23:34:27 +00003814 SDOperand Round = DAG.getConstantFP(N0CFP->getValueAPF(), EVT);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003815 return DAG.getNode(ISD::FP_EXTEND, VT, Round);
3816 }
3817 return SDOperand();
3818}
3819
3820SDOperand DAGCombiner::visitFP_EXTEND(SDNode *N) {
3821 SDOperand N0 = N->getOperand(0);
3822 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
3823 MVT::ValueType VT = N->getValueType(0);
3824
Chris Lattner6f981fc2007-12-29 06:55:23 +00003825 // If this is fp_round(fpextend), don't fold it, allow ourselves to be folded.
3826 if (N->hasOneUse() && (*N->use_begin())->getOpcode() == ISD::FP_ROUND)
3827 return SDOperand();
Chris Lattner5872a362008-01-17 07:00:52 +00003828
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003829 // fold (fp_extend c1fp) -> c1fp
Dale Johannesenb89072e2007-10-16 23:38:29 +00003830 if (N0CFP && VT != MVT::ppcf128)
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003831 return DAG.getNode(ISD::FP_EXTEND, VT, N0);
Chris Lattner5872a362008-01-17 07:00:52 +00003832
3833 // Turn fp_extend(fp_round(X, 1)) -> x since the fp_round doesn't affect the
3834 // value of X.
3835 if (N0.getOpcode() == ISD::FP_ROUND && N0.Val->getConstantOperandVal(1) == 1){
3836 SDOperand In = N0.getOperand(0);
3837 if (In.getValueType() == VT) return In;
3838 if (VT < In.getValueType())
3839 return DAG.getNode(ISD::FP_ROUND, VT, In, N0.getOperand(1));
3840 return DAG.getNode(ISD::FP_EXTEND, VT, In);
3841 }
3842
3843 // fold (fpext (load x)) -> (fpext (fptrunc (extload x)))
Dale Johannesen2550e3a2007-10-19 20:29:00 +00003844 if (ISD::isNON_EXTLoad(N0.Val) && N0.hasOneUse() &&
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003845 (!AfterLegalize||TLI.isLoadXLegal(ISD::EXTLOAD, N0.getValueType()))) {
3846 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
3847 SDOperand ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, VT, LN0->getChain(),
3848 LN0->getBasePtr(), LN0->getSrcValue(),
3849 LN0->getSrcValueOffset(),
3850 N0.getValueType(),
3851 LN0->isVolatile(),
3852 LN0->getAlignment());
3853 CombineTo(N, ExtLoad);
Chris Lattner5872a362008-01-17 07:00:52 +00003854 CombineTo(N0.Val, DAG.getNode(ISD::FP_ROUND, N0.getValueType(), ExtLoad,
3855 DAG.getIntPtrConstant(1)),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003856 ExtLoad.getValue(1));
3857 return SDOperand(N, 0); // Return N so it doesn't get rechecked!
3858 }
3859
3860
3861 return SDOperand();
3862}
3863
3864SDOperand DAGCombiner::visitFNEG(SDNode *N) {
3865 SDOperand N0 = N->getOperand(0);
3866
Chris Lattnere0992b82008-02-26 07:04:54 +00003867 if (isNegatibleForFree(N0, AfterLegalize))
3868 return GetNegatedExpression(N0, DAG, AfterLegalize);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003869
Chris Lattneref26cbc2008-01-27 17:42:27 +00003870 // Transform fneg(bitconvert(x)) -> bitconvert(x^sign) to avoid loading
3871 // constant pool values.
Chris Lattner336672f2008-01-27 23:32:17 +00003872 if (N0.getOpcode() == ISD::BIT_CONVERT && N0.Val->hasOneUse() &&
3873 MVT::isInteger(N0.getOperand(0).getValueType()) &&
3874 !MVT::isVector(N0.getOperand(0).getValueType())) {
Chris Lattneref26cbc2008-01-27 17:42:27 +00003875 SDOperand Int = N0.getOperand(0);
3876 MVT::ValueType IntVT = Int.getValueType();
3877 if (MVT::isInteger(IntVT) && !MVT::isVector(IntVT)) {
3878 Int = DAG.getNode(ISD::XOR, IntVT, Int,
3879 DAG.getConstant(MVT::getIntVTSignBit(IntVT), IntVT));
3880 AddToWorkList(Int.Val);
3881 return DAG.getNode(ISD::BIT_CONVERT, N->getValueType(0), Int);
3882 }
3883 }
3884
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003885 return SDOperand();
3886}
3887
3888SDOperand DAGCombiner::visitFABS(SDNode *N) {
3889 SDOperand N0 = N->getOperand(0);
3890 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
3891 MVT::ValueType VT = N->getValueType(0);
3892
3893 // fold (fabs c1) -> fabs(c1)
Dale Johannesenb89072e2007-10-16 23:38:29 +00003894 if (N0CFP && VT != MVT::ppcf128)
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003895 return DAG.getNode(ISD::FABS, VT, N0);
3896 // fold (fabs (fabs x)) -> (fabs x)
3897 if (N0.getOpcode() == ISD::FABS)
3898 return N->getOperand(0);
3899 // fold (fabs (fneg x)) -> (fabs x)
3900 // fold (fabs (fcopysign x, y)) -> (fabs x)
3901 if (N0.getOpcode() == ISD::FNEG || N0.getOpcode() == ISD::FCOPYSIGN)
3902 return DAG.getNode(ISD::FABS, VT, N0.getOperand(0));
3903
Chris Lattneref26cbc2008-01-27 17:42:27 +00003904 // Transform fabs(bitconvert(x)) -> bitconvert(x&~sign) to avoid loading
3905 // constant pool values.
Chris Lattner336672f2008-01-27 23:32:17 +00003906 if (N0.getOpcode() == ISD::BIT_CONVERT && N0.Val->hasOneUse() &&
3907 MVT::isInteger(N0.getOperand(0).getValueType()) &&
3908 !MVT::isVector(N0.getOperand(0).getValueType())) {
Chris Lattneref26cbc2008-01-27 17:42:27 +00003909 SDOperand Int = N0.getOperand(0);
3910 MVT::ValueType IntVT = Int.getValueType();
3911 if (MVT::isInteger(IntVT) && !MVT::isVector(IntVT)) {
3912 Int = DAG.getNode(ISD::AND, IntVT, Int,
3913 DAG.getConstant(~MVT::getIntVTSignBit(IntVT), IntVT));
3914 AddToWorkList(Int.Val);
3915 return DAG.getNode(ISD::BIT_CONVERT, N->getValueType(0), Int);
3916 }
3917 }
3918
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003919 return SDOperand();
3920}
3921
3922SDOperand DAGCombiner::visitBRCOND(SDNode *N) {
3923 SDOperand Chain = N->getOperand(0);
3924 SDOperand N1 = N->getOperand(1);
3925 SDOperand N2 = N->getOperand(2);
3926 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
3927
3928 // never taken branch, fold to chain
3929 if (N1C && N1C->isNullValue())
3930 return Chain;
3931 // unconditional branch
3932 if (N1C && N1C->getValue() == 1)
3933 return DAG.getNode(ISD::BR, MVT::Other, Chain, N2);
3934 // fold a brcond with a setcc condition into a BR_CC node if BR_CC is legal
3935 // on the target.
3936 if (N1.getOpcode() == ISD::SETCC &&
3937 TLI.isOperationLegal(ISD::BR_CC, MVT::Other)) {
3938 return DAG.getNode(ISD::BR_CC, MVT::Other, Chain, N1.getOperand(2),
3939 N1.getOperand(0), N1.getOperand(1), N2);
3940 }
3941 return SDOperand();
3942}
3943
3944// Operand List for BR_CC: Chain, CondCC, CondLHS, CondRHS, DestBB.
3945//
3946SDOperand DAGCombiner::visitBR_CC(SDNode *N) {
3947 CondCodeSDNode *CC = cast<CondCodeSDNode>(N->getOperand(1));
3948 SDOperand CondLHS = N->getOperand(2), CondRHS = N->getOperand(3);
3949
3950 // Use SimplifySetCC to simplify SETCC's.
3951 SDOperand Simp = SimplifySetCC(MVT::i1, CondLHS, CondRHS, CC->get(), false);
3952 if (Simp.Val) AddToWorkList(Simp.Val);
3953
3954 ConstantSDNode *SCCC = dyn_cast_or_null<ConstantSDNode>(Simp.Val);
3955
3956 // fold br_cc true, dest -> br dest (unconditional branch)
3957 if (SCCC && SCCC->getValue())
3958 return DAG.getNode(ISD::BR, MVT::Other, N->getOperand(0),
3959 N->getOperand(4));
3960 // fold br_cc false, dest -> unconditional fall through
3961 if (SCCC && SCCC->isNullValue())
3962 return N->getOperand(0);
3963
3964 // fold to a simpler setcc
3965 if (Simp.Val && Simp.getOpcode() == ISD::SETCC)
3966 return DAG.getNode(ISD::BR_CC, MVT::Other, N->getOperand(0),
3967 Simp.getOperand(2), Simp.getOperand(0),
3968 Simp.getOperand(1), N->getOperand(4));
3969 return SDOperand();
3970}
3971
3972
3973/// CombineToPreIndexedLoadStore - Try turning a load / store and a
3974/// pre-indexed load / store when the base pointer is a add or subtract
3975/// and it has other uses besides the load / store. After the
3976/// transformation, the new indexed load / store has effectively folded
3977/// the add / subtract in and all of its other uses are redirected to the
3978/// new load / store.
3979bool DAGCombiner::CombineToPreIndexedLoadStore(SDNode *N) {
3980 if (!AfterLegalize)
3981 return false;
3982
3983 bool isLoad = true;
3984 SDOperand Ptr;
3985 MVT::ValueType VT;
3986 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
Chris Lattner3bc08502008-01-17 19:59:44 +00003987 if (LD->isIndexed())
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003988 return false;
Dan Gohman9a4c92c2008-01-30 00:15:11 +00003989 VT = LD->getMemoryVT();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003990 if (!TLI.isIndexedLoadLegal(ISD::PRE_INC, VT) &&
3991 !TLI.isIndexedLoadLegal(ISD::PRE_DEC, VT))
3992 return false;
3993 Ptr = LD->getBasePtr();
3994 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
Chris Lattner3bc08502008-01-17 19:59:44 +00003995 if (ST->isIndexed())
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003996 return false;
Dan Gohman9a4c92c2008-01-30 00:15:11 +00003997 VT = ST->getMemoryVT();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003998 if (!TLI.isIndexedStoreLegal(ISD::PRE_INC, VT) &&
3999 !TLI.isIndexedStoreLegal(ISD::PRE_DEC, VT))
4000 return false;
4001 Ptr = ST->getBasePtr();
4002 isLoad = false;
4003 } else
4004 return false;
4005
4006 // If the pointer is not an add/sub, or if it doesn't have multiple uses, bail
4007 // out. There is no reason to make this a preinc/predec.
4008 if ((Ptr.getOpcode() != ISD::ADD && Ptr.getOpcode() != ISD::SUB) ||
4009 Ptr.Val->hasOneUse())
4010 return false;
4011
4012 // Ask the target to do addressing mode selection.
4013 SDOperand BasePtr;
4014 SDOperand Offset;
4015 ISD::MemIndexedMode AM = ISD::UNINDEXED;
4016 if (!TLI.getPreIndexedAddressParts(N, BasePtr, Offset, AM, DAG))
4017 return false;
4018 // Don't create a indexed load / store with zero offset.
4019 if (isa<ConstantSDNode>(Offset) &&
4020 cast<ConstantSDNode>(Offset)->getValue() == 0)
4021 return false;
4022
4023 // Try turning it into a pre-indexed load / store except when:
4024 // 1) The new base ptr is a frame index.
4025 // 2) If N is a store and the new base ptr is either the same as or is a
4026 // predecessor of the value being stored.
4027 // 3) Another use of old base ptr is a predecessor of N. If ptr is folded
4028 // that would create a cycle.
4029 // 4) All uses are load / store ops that use it as old base ptr.
4030
4031 // Check #1. Preinc'ing a frame index would require copying the stack pointer
4032 // (plus the implicit offset) to a register to preinc anyway.
4033 if (isa<FrameIndexSDNode>(BasePtr))
4034 return false;
4035
4036 // Check #2.
4037 if (!isLoad) {
4038 SDOperand Val = cast<StoreSDNode>(N)->getValue();
Evan Chengd9387682008-03-04 00:41:45 +00004039 if (Val == BasePtr || BasePtr.Val->isPredecessorOf(Val.Val))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004040 return false;
4041 }
4042
4043 // Now check for #3 and #4.
4044 bool RealUse = false;
4045 for (SDNode::use_iterator I = Ptr.Val->use_begin(),
4046 E = Ptr.Val->use_end(); I != E; ++I) {
4047 SDNode *Use = *I;
4048 if (Use == N)
4049 continue;
Evan Chengd9387682008-03-04 00:41:45 +00004050 if (Use->isPredecessorOf(N))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004051 return false;
4052
4053 if (!((Use->getOpcode() == ISD::LOAD &&
4054 cast<LoadSDNode>(Use)->getBasePtr() == Ptr) ||
Anton Korobeynikov53422f62008-02-20 11:10:28 +00004055 (Use->getOpcode() == ISD::STORE &&
4056 cast<StoreSDNode>(Use)->getBasePtr() == Ptr)))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004057 RealUse = true;
4058 }
4059 if (!RealUse)
4060 return false;
4061
4062 SDOperand Result;
4063 if (isLoad)
4064 Result = DAG.getIndexedLoad(SDOperand(N,0), BasePtr, Offset, AM);
4065 else
4066 Result = DAG.getIndexedStore(SDOperand(N,0), BasePtr, Offset, AM);
4067 ++PreIndexedNodes;
4068 ++NodesCombined;
4069 DOUT << "\nReplacing.4 "; DEBUG(N->dump(&DAG));
4070 DOUT << "\nWith: "; DEBUG(Result.Val->dump(&DAG));
4071 DOUT << '\n';
Chris Lattner7bcb18f2008-02-03 06:49:24 +00004072 WorkListRemover DeadNodes(*this);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004073 if (isLoad) {
4074 DAG.ReplaceAllUsesOfValueWith(SDOperand(N, 0), Result.getValue(0),
Chris Lattner7bcb18f2008-02-03 06:49:24 +00004075 &DeadNodes);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004076 DAG.ReplaceAllUsesOfValueWith(SDOperand(N, 1), Result.getValue(2),
Chris Lattner7bcb18f2008-02-03 06:49:24 +00004077 &DeadNodes);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004078 } else {
4079 DAG.ReplaceAllUsesOfValueWith(SDOperand(N, 0), Result.getValue(1),
Chris Lattner7bcb18f2008-02-03 06:49:24 +00004080 &DeadNodes);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004081 }
4082
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004083 // Finally, since the node is now dead, remove it from the graph.
4084 DAG.DeleteNode(N);
4085
4086 // Replace the uses of Ptr with uses of the updated base value.
4087 DAG.ReplaceAllUsesOfValueWith(Ptr, Result.getValue(isLoad ? 1 : 0),
Chris Lattner7bcb18f2008-02-03 06:49:24 +00004088 &DeadNodes);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004089 removeFromWorkList(Ptr.Val);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004090 DAG.DeleteNode(Ptr.Val);
4091
4092 return true;
4093}
4094
4095/// CombineToPostIndexedLoadStore - Try combine a load / store with a
4096/// add / sub of the base pointer node into a post-indexed load / store.
4097/// The transformation folded the add / subtract into the new indexed
4098/// load / store effectively and all of its uses are redirected to the
4099/// new load / store.
4100bool DAGCombiner::CombineToPostIndexedLoadStore(SDNode *N) {
4101 if (!AfterLegalize)
4102 return false;
4103
4104 bool isLoad = true;
4105 SDOperand Ptr;
4106 MVT::ValueType VT;
4107 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
Chris Lattner3bc08502008-01-17 19:59:44 +00004108 if (LD->isIndexed())
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004109 return false;
Dan Gohman9a4c92c2008-01-30 00:15:11 +00004110 VT = LD->getMemoryVT();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004111 if (!TLI.isIndexedLoadLegal(ISD::POST_INC, VT) &&
4112 !TLI.isIndexedLoadLegal(ISD::POST_DEC, VT))
4113 return false;
4114 Ptr = LD->getBasePtr();
4115 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
Chris Lattner3bc08502008-01-17 19:59:44 +00004116 if (ST->isIndexed())
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004117 return false;
Dan Gohman9a4c92c2008-01-30 00:15:11 +00004118 VT = ST->getMemoryVT();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004119 if (!TLI.isIndexedStoreLegal(ISD::POST_INC, VT) &&
4120 !TLI.isIndexedStoreLegal(ISD::POST_DEC, VT))
4121 return false;
4122 Ptr = ST->getBasePtr();
4123 isLoad = false;
4124 } else
4125 return false;
4126
4127 if (Ptr.Val->hasOneUse())
4128 return false;
4129
4130 for (SDNode::use_iterator I = Ptr.Val->use_begin(),
4131 E = Ptr.Val->use_end(); I != E; ++I) {
4132 SDNode *Op = *I;
4133 if (Op == N ||
4134 (Op->getOpcode() != ISD::ADD && Op->getOpcode() != ISD::SUB))
4135 continue;
4136
4137 SDOperand BasePtr;
4138 SDOperand Offset;
4139 ISD::MemIndexedMode AM = ISD::UNINDEXED;
4140 if (TLI.getPostIndexedAddressParts(N, Op, BasePtr, Offset, AM, DAG)) {
4141 if (Ptr == Offset)
4142 std::swap(BasePtr, Offset);
4143 if (Ptr != BasePtr)
4144 continue;
4145 // Don't create a indexed load / store with zero offset.
4146 if (isa<ConstantSDNode>(Offset) &&
4147 cast<ConstantSDNode>(Offset)->getValue() == 0)
4148 continue;
4149
4150 // Try turning it into a post-indexed load / store except when
4151 // 1) All uses are load / store ops that use it as base ptr.
4152 // 2) Op must be independent of N, i.e. Op is neither a predecessor
4153 // nor a successor of N. Otherwise, if Op is folded that would
4154 // create a cycle.
4155
4156 // Check for #1.
4157 bool TryNext = false;
4158 for (SDNode::use_iterator II = BasePtr.Val->use_begin(),
4159 EE = BasePtr.Val->use_end(); II != EE; ++II) {
4160 SDNode *Use = *II;
4161 if (Use == Ptr.Val)
4162 continue;
4163
4164 // If all the uses are load / store addresses, then don't do the
4165 // transformation.
4166 if (Use->getOpcode() == ISD::ADD || Use->getOpcode() == ISD::SUB){
4167 bool RealUse = false;
4168 for (SDNode::use_iterator III = Use->use_begin(),
4169 EEE = Use->use_end(); III != EEE; ++III) {
4170 SDNode *UseUse = *III;
4171 if (!((UseUse->getOpcode() == ISD::LOAD &&
4172 cast<LoadSDNode>(UseUse)->getBasePtr().Val == Use) ||
Anton Korobeynikov53422f62008-02-20 11:10:28 +00004173 (UseUse->getOpcode() == ISD::STORE &&
4174 cast<StoreSDNode>(UseUse)->getBasePtr().Val == Use)))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004175 RealUse = true;
4176 }
4177
4178 if (!RealUse) {
4179 TryNext = true;
4180 break;
4181 }
4182 }
4183 }
4184 if (TryNext)
4185 continue;
4186
4187 // Check for #2
Evan Chengd9387682008-03-04 00:41:45 +00004188 if (!Op->isPredecessorOf(N) && !N->isPredecessorOf(Op)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004189 SDOperand Result = isLoad
4190 ? DAG.getIndexedLoad(SDOperand(N,0), BasePtr, Offset, AM)
4191 : DAG.getIndexedStore(SDOperand(N,0), BasePtr, Offset, AM);
4192 ++PostIndexedNodes;
4193 ++NodesCombined;
4194 DOUT << "\nReplacing.5 "; DEBUG(N->dump(&DAG));
4195 DOUT << "\nWith: "; DEBUG(Result.Val->dump(&DAG));
4196 DOUT << '\n';
Chris Lattner7bcb18f2008-02-03 06:49:24 +00004197 WorkListRemover DeadNodes(*this);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004198 if (isLoad) {
4199 DAG.ReplaceAllUsesOfValueWith(SDOperand(N, 0), Result.getValue(0),
Chris Lattner7bcb18f2008-02-03 06:49:24 +00004200 &DeadNodes);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004201 DAG.ReplaceAllUsesOfValueWith(SDOperand(N, 1), Result.getValue(2),
Chris Lattner7bcb18f2008-02-03 06:49:24 +00004202 &DeadNodes);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004203 } else {
4204 DAG.ReplaceAllUsesOfValueWith(SDOperand(N, 0), Result.getValue(1),
Chris Lattner7bcb18f2008-02-03 06:49:24 +00004205 &DeadNodes);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004206 }
4207
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004208 // Finally, since the node is now dead, remove it from the graph.
4209 DAG.DeleteNode(N);
4210
4211 // Replace the uses of Use with uses of the updated base value.
4212 DAG.ReplaceAllUsesOfValueWith(SDOperand(Op, 0),
4213 Result.getValue(isLoad ? 1 : 0),
Chris Lattner7bcb18f2008-02-03 06:49:24 +00004214 &DeadNodes);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004215 removeFromWorkList(Op);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004216 DAG.DeleteNode(Op);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004217 return true;
4218 }
4219 }
4220 }
4221 return false;
4222}
4223
Chris Lattner4e137af2008-01-25 07:20:16 +00004224/// InferAlignment - If we can infer some alignment information from this
4225/// pointer, return it.
4226static unsigned InferAlignment(SDOperand Ptr, SelectionDAG &DAG) {
4227 // If this is a direct reference to a stack slot, use information about the
4228 // stack slot's alignment.
Chris Lattner1e3362f2008-01-26 19:45:50 +00004229 int FrameIdx = 1 << 31;
4230 int64_t FrameOffset = 0;
Chris Lattner4e137af2008-01-25 07:20:16 +00004231 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Ptr)) {
Chris Lattner1e3362f2008-01-26 19:45:50 +00004232 FrameIdx = FI->getIndex();
4233 } else if (Ptr.getOpcode() == ISD::ADD &&
4234 isa<ConstantSDNode>(Ptr.getOperand(1)) &&
4235 isa<FrameIndexSDNode>(Ptr.getOperand(0))) {
4236 FrameIdx = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
4237 FrameOffset = Ptr.getConstantOperandVal(1);
Chris Lattner4e137af2008-01-25 07:20:16 +00004238 }
Chris Lattner1e3362f2008-01-26 19:45:50 +00004239
4240 if (FrameIdx != (1 << 31)) {
4241 // FIXME: Handle FI+CST.
4242 const MachineFrameInfo &MFI = *DAG.getMachineFunction().getFrameInfo();
4243 if (MFI.isFixedObjectIndex(FrameIdx)) {
4244 int64_t ObjectOffset = MFI.getObjectOffset(FrameIdx);
4245
4246 // The alignment of the frame index can be determined from its offset from
4247 // the incoming frame position. If the frame object is at offset 32 and
4248 // the stack is guaranteed to be 16-byte aligned, then we know that the
4249 // object is 16-byte aligned.
4250 unsigned StackAlign = DAG.getTarget().getFrameInfo()->getStackAlignment();
4251 unsigned Align = MinAlign(ObjectOffset, StackAlign);
4252
4253 // Finally, the frame object itself may have a known alignment. Factor
4254 // the alignment + offset into a new alignment. For example, if we know
4255 // the FI is 8 byte aligned, but the pointer is 4 off, we really have a
4256 // 4-byte alignment of the resultant pointer. Likewise align 4 + 4-byte
4257 // offset = 4-byte alignment, align 4 + 1-byte offset = align 1, etc.
4258 unsigned FIInfoAlign = MinAlign(MFI.getObjectAlignment(FrameIdx),
4259 FrameOffset);
4260 return std::max(Align, FIInfoAlign);
4261 }
4262 }
Chris Lattner4e137af2008-01-25 07:20:16 +00004263
4264 return 0;
4265}
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004266
4267SDOperand DAGCombiner::visitLOAD(SDNode *N) {
4268 LoadSDNode *LD = cast<LoadSDNode>(N);
4269 SDOperand Chain = LD->getChain();
4270 SDOperand Ptr = LD->getBasePtr();
Chris Lattner4e137af2008-01-25 07:20:16 +00004271
4272 // Try to infer better alignment information than the load already has.
4273 if (LD->isUnindexed()) {
4274 if (unsigned Align = InferAlignment(Ptr, DAG)) {
4275 if (Align > LD->getAlignment())
4276 return DAG.getExtLoad(LD->getExtensionType(), LD->getValueType(0),
4277 Chain, Ptr, LD->getSrcValue(),
Dan Gohman9a4c92c2008-01-30 00:15:11 +00004278 LD->getSrcValueOffset(), LD->getMemoryVT(),
Chris Lattner4e137af2008-01-25 07:20:16 +00004279 LD->isVolatile(), Align);
4280 }
4281 }
4282
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004283
4284 // If load is not volatile and there are no uses of the loaded value (and
4285 // the updated indexed value in case of indexed loads), change uses of the
4286 // chain value into uses of the chain input (i.e. delete the dead load).
4287 if (!LD->isVolatile()) {
4288 if (N->getValueType(1) == MVT::Other) {
4289 // Unindexed loads.
Evan Chenge8b886a2008-01-16 23:11:54 +00004290 if (N->hasNUsesOfValue(0, 0)) {
4291 // It's not safe to use the two value CombineTo variant here. e.g.
4292 // v1, chain2 = load chain1, loc
4293 // v2, chain3 = load chain2, loc
4294 // v3 = add v2, c
Chris Lattnerbb67c192008-01-24 07:57:06 +00004295 // Now we replace use of chain2 with chain1. This makes the second load
4296 // isomorphic to the one we are deleting, and thus makes this load live.
Evan Chenge8b886a2008-01-16 23:11:54 +00004297 DOUT << "\nReplacing.6 "; DEBUG(N->dump(&DAG));
Chris Lattnerbb67c192008-01-24 07:57:06 +00004298 DOUT << "\nWith chain: "; DEBUG(Chain.Val->dump(&DAG));
4299 DOUT << "\n";
Chris Lattner7bcb18f2008-02-03 06:49:24 +00004300 WorkListRemover DeadNodes(*this);
4301 DAG.ReplaceAllUsesOfValueWith(SDOperand(N, 1), Chain, &DeadNodes);
Chris Lattnerbb67c192008-01-24 07:57:06 +00004302 if (N->use_empty()) {
4303 removeFromWorkList(N);
4304 DAG.DeleteNode(N);
4305 }
Evan Chenge8b886a2008-01-16 23:11:54 +00004306 return SDOperand(N, 0); // Return N so it doesn't get rechecked!
4307 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004308 } else {
4309 // Indexed loads.
4310 assert(N->getValueType(2) == MVT::Other && "Malformed indexed loads?");
4311 if (N->hasNUsesOfValue(0, 0) && N->hasNUsesOfValue(0, 1)) {
Evan Chenge8b886a2008-01-16 23:11:54 +00004312 SDOperand Undef = DAG.getNode(ISD::UNDEF, N->getValueType(0));
4313 DOUT << "\nReplacing.6 "; DEBUG(N->dump(&DAG));
4314 DOUT << "\nWith: "; DEBUG(Undef.Val->dump(&DAG));
4315 DOUT << " and 2 other values\n";
Chris Lattner7bcb18f2008-02-03 06:49:24 +00004316 WorkListRemover DeadNodes(*this);
4317 DAG.ReplaceAllUsesOfValueWith(SDOperand(N, 0), Undef, &DeadNodes);
Evan Chenge8b886a2008-01-16 23:11:54 +00004318 DAG.ReplaceAllUsesOfValueWith(SDOperand(N, 1),
Chris Lattner667f9c12008-01-17 07:20:38 +00004319 DAG.getNode(ISD::UNDEF, N->getValueType(1)),
Chris Lattner7bcb18f2008-02-03 06:49:24 +00004320 &DeadNodes);
4321 DAG.ReplaceAllUsesOfValueWith(SDOperand(N, 2), Chain, &DeadNodes);
Evan Chenge8b886a2008-01-16 23:11:54 +00004322 removeFromWorkList(N);
Evan Chenge8b886a2008-01-16 23:11:54 +00004323 DAG.DeleteNode(N);
4324 return SDOperand(N, 0); // Return N so it doesn't get rechecked!
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004325 }
4326 }
4327 }
4328
4329 // If this load is directly stored, replace the load value with the stored
4330 // value.
4331 // TODO: Handle store large -> read small portion.
4332 // TODO: Handle TRUNCSTORE/LOADEXT
4333 if (LD->getExtensionType() == ISD::NON_EXTLOAD) {
4334 if (ISD::isNON_TRUNCStore(Chain.Val)) {
4335 StoreSDNode *PrevST = cast<StoreSDNode>(Chain);
4336 if (PrevST->getBasePtr() == Ptr &&
4337 PrevST->getValue().getValueType() == N->getValueType(0))
4338 return CombineTo(N, Chain.getOperand(1), Chain);
4339 }
4340 }
4341
4342 if (CombinerAA) {
4343 // Walk up chain skipping non-aliasing memory nodes.
4344 SDOperand BetterChain = FindBetterChain(N, Chain);
4345
4346 // If there is a better chain.
4347 if (Chain != BetterChain) {
4348 SDOperand ReplLoad;
4349
4350 // Replace the chain to void dependency.
4351 if (LD->getExtensionType() == ISD::NON_EXTLOAD) {
4352 ReplLoad = DAG.getLoad(N->getValueType(0), BetterChain, Ptr,
Duncan Sandsa3691432007-10-28 12:59:45 +00004353 LD->getSrcValue(), LD->getSrcValueOffset(),
4354 LD->isVolatile(), LD->getAlignment());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004355 } else {
4356 ReplLoad = DAG.getExtLoad(LD->getExtensionType(),
4357 LD->getValueType(0),
4358 BetterChain, Ptr, LD->getSrcValue(),
4359 LD->getSrcValueOffset(),
Dan Gohman9a4c92c2008-01-30 00:15:11 +00004360 LD->getMemoryVT(),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004361 LD->isVolatile(),
4362 LD->getAlignment());
4363 }
4364
4365 // Create token factor to keep old chain connected.
4366 SDOperand Token = DAG.getNode(ISD::TokenFactor, MVT::Other,
4367 Chain, ReplLoad.getValue(1));
4368
4369 // Replace uses with load result and token factor. Don't add users
4370 // to work list.
4371 return CombineTo(N, ReplLoad.getValue(0), Token, false);
4372 }
4373 }
4374
4375 // Try transforming N to an indexed load.
4376 if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
4377 return SDOperand(N, 0);
4378
4379 return SDOperand();
4380}
4381
Chris Lattner2e023772008-01-08 23:08:06 +00004382
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004383SDOperand DAGCombiner::visitSTORE(SDNode *N) {
4384 StoreSDNode *ST = cast<StoreSDNode>(N);
4385 SDOperand Chain = ST->getChain();
4386 SDOperand Value = ST->getValue();
4387 SDOperand Ptr = ST->getBasePtr();
4388
Chris Lattner4e137af2008-01-25 07:20:16 +00004389 // Try to infer better alignment information than the store already has.
4390 if (ST->isUnindexed()) {
4391 if (unsigned Align = InferAlignment(Ptr, DAG)) {
4392 if (Align > ST->getAlignment())
4393 return DAG.getTruncStore(Chain, Value, Ptr, ST->getSrcValue(),
Dan Gohman9a4c92c2008-01-30 00:15:11 +00004394 ST->getSrcValueOffset(), ST->getMemoryVT(),
Chris Lattner4e137af2008-01-25 07:20:16 +00004395 ST->isVolatile(), Align);
4396 }
4397 }
4398
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004399 // If this is a store of a bit convert, store the input value if the
4400 // resultant store does not need a higher alignment than the original.
4401 if (Value.getOpcode() == ISD::BIT_CONVERT && !ST->isTruncatingStore() &&
Chris Lattner3bc08502008-01-17 19:59:44 +00004402 ST->isUnindexed()) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004403 unsigned Align = ST->getAlignment();
4404 MVT::ValueType SVT = Value.getOperand(0).getValueType();
4405 unsigned OrigAlign = TLI.getTargetMachine().getTargetData()->
4406 getABITypeAlignment(MVT::getTypeForValueType(SVT));
4407 if (Align <= OrigAlign && TLI.isOperationLegal(ISD::STORE, SVT))
4408 return DAG.getStore(Chain, Value.getOperand(0), Ptr, ST->getSrcValue(),
4409 ST->getSrcValueOffset(), ST->isVolatile(), Align);
4410 }
4411
4412 // Turn 'store float 1.0, Ptr' -> 'store int 0x12345678, Ptr'
4413 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Value)) {
4414 if (Value.getOpcode() != ISD::TargetConstantFP) {
4415 SDOperand Tmp;
4416 switch (CFP->getValueType(0)) {
4417 default: assert(0 && "Unknown FP type");
Dale Johannesen1b4181d2007-09-18 18:36:59 +00004418 case MVT::f80: // We don't do this for these yet.
4419 case MVT::f128:
4420 case MVT::ppcf128:
4421 break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004422 case MVT::f32:
4423 if (!AfterLegalize || TLI.isTypeLegal(MVT::i32)) {
Dale Johannesenfbd9cda2007-09-12 03:30:33 +00004424 Tmp = DAG.getConstant((uint32_t)CFP->getValueAPF().
4425 convertToAPInt().getZExtValue(), MVT::i32);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004426 return DAG.getStore(Chain, Tmp, Ptr, ST->getSrcValue(),
4427 ST->getSrcValueOffset(), ST->isVolatile(),
4428 ST->getAlignment());
4429 }
4430 break;
4431 case MVT::f64:
4432 if (!AfterLegalize || TLI.isTypeLegal(MVT::i64)) {
Dale Johannesenfbd9cda2007-09-12 03:30:33 +00004433 Tmp = DAG.getConstant(CFP->getValueAPF().convertToAPInt().
4434 getZExtValue(), MVT::i64);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004435 return DAG.getStore(Chain, Tmp, Ptr, ST->getSrcValue(),
4436 ST->getSrcValueOffset(), ST->isVolatile(),
4437 ST->getAlignment());
4438 } else if (TLI.isTypeLegal(MVT::i32)) {
Duncan Sandsa3691432007-10-28 12:59:45 +00004439 // Many FP stores are not made apparent until after legalize, e.g. for
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004440 // argument passing. Since this is so common, custom legalize the
4441 // 64-bit integer store into two 32-bit stores.
Dale Johannesenfbd9cda2007-09-12 03:30:33 +00004442 uint64_t Val = CFP->getValueAPF().convertToAPInt().getZExtValue();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004443 SDOperand Lo = DAG.getConstant(Val & 0xFFFFFFFF, MVT::i32);
4444 SDOperand Hi = DAG.getConstant(Val >> 32, MVT::i32);
Duncan Sands9ff8fbf2008-02-11 10:37:04 +00004445 if (TLI.isBigEndian()) std::swap(Lo, Hi);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004446
4447 int SVOffset = ST->getSrcValueOffset();
4448 unsigned Alignment = ST->getAlignment();
4449 bool isVolatile = ST->isVolatile();
4450
4451 SDOperand St0 = DAG.getStore(Chain, Lo, Ptr, ST->getSrcValue(),
4452 ST->getSrcValueOffset(),
4453 isVolatile, ST->getAlignment());
4454 Ptr = DAG.getNode(ISD::ADD, Ptr.getValueType(), Ptr,
4455 DAG.getConstant(4, Ptr.getValueType()));
4456 SVOffset += 4;
Duncan Sandsa3691432007-10-28 12:59:45 +00004457 Alignment = MinAlign(Alignment, 4U);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004458 SDOperand St1 = DAG.getStore(Chain, Hi, Ptr, ST->getSrcValue(),
4459 SVOffset, isVolatile, Alignment);
4460 return DAG.getNode(ISD::TokenFactor, MVT::Other, St0, St1);
4461 }
4462 break;
4463 }
4464 }
4465 }
4466
4467 if (CombinerAA) {
4468 // Walk up chain skipping non-aliasing memory nodes.
4469 SDOperand BetterChain = FindBetterChain(N, Chain);
4470
4471 // If there is a better chain.
4472 if (Chain != BetterChain) {
4473 // Replace the chain to avoid dependency.
4474 SDOperand ReplStore;
4475 if (ST->isTruncatingStore()) {
4476 ReplStore = DAG.getTruncStore(BetterChain, Value, Ptr,
Chris Lattner667f9c12008-01-17 07:20:38 +00004477 ST->getSrcValue(),ST->getSrcValueOffset(),
Dan Gohman9a4c92c2008-01-30 00:15:11 +00004478 ST->getMemoryVT(),
Chris Lattner667f9c12008-01-17 07:20:38 +00004479 ST->isVolatile(), ST->getAlignment());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004480 } else {
4481 ReplStore = DAG.getStore(BetterChain, Value, Ptr,
Chris Lattner667f9c12008-01-17 07:20:38 +00004482 ST->getSrcValue(), ST->getSrcValueOffset(),
4483 ST->isVolatile(), ST->getAlignment());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004484 }
4485
4486 // Create token to keep both nodes around.
4487 SDOperand Token =
4488 DAG.getNode(ISD::TokenFactor, MVT::Other, Chain, ReplStore);
4489
4490 // Don't add users to work list.
4491 return CombineTo(N, Token, false);
4492 }
4493 }
4494
4495 // Try transforming N to an indexed store.
4496 if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
4497 return SDOperand(N, 0);
4498
Chris Lattner447d8e82007-12-29 06:26:16 +00004499 // FIXME: is there such a thing as a truncating indexed store?
Chris Lattner3bc08502008-01-17 19:59:44 +00004500 if (ST->isTruncatingStore() && ST->isUnindexed() &&
Chris Lattnere8671c52007-10-13 06:35:54 +00004501 MVT::isInteger(Value.getValueType())) {
4502 // See if we can simplify the input to this truncstore with knowledge that
4503 // only the low bits are being used. For example:
4504 // "truncstore (or (shl x, 8), y), i8" -> "truncstore y, i8"
4505 SDOperand Shorter =
Dan Gohman07961cd2008-02-25 21:11:39 +00004506 GetDemandedBits(Value,
4507 APInt::getLowBitsSet(Value.getValueSizeInBits(),
4508 MVT::getSizeInBits(ST->getMemoryVT())));
Chris Lattnere8671c52007-10-13 06:35:54 +00004509 AddToWorkList(Value.Val);
4510 if (Shorter.Val)
4511 return DAG.getTruncStore(Chain, Shorter, Ptr, ST->getSrcValue(),
Dan Gohman9a4c92c2008-01-30 00:15:11 +00004512 ST->getSrcValueOffset(), ST->getMemoryVT(),
Chris Lattnere8671c52007-10-13 06:35:54 +00004513 ST->isVolatile(), ST->getAlignment());
Chris Lattnerb77ea552007-10-13 06:58:48 +00004514
4515 // Otherwise, see if we can simplify the operation with
4516 // SimplifyDemandedBits, which only works if the value has a single use.
Dan Gohman11607792008-02-27 00:25:32 +00004517 if (SimplifyDemandedBits(Value,
4518 APInt::getLowBitsSet(
4519 Value.getValueSizeInBits(),
4520 MVT::getSizeInBits(ST->getMemoryVT()))))
Chris Lattnerb77ea552007-10-13 06:58:48 +00004521 return SDOperand(N, 0);
Chris Lattnere8671c52007-10-13 06:35:54 +00004522 }
4523
Chris Lattner447d8e82007-12-29 06:26:16 +00004524 // If this is a load followed by a store to the same location, then the store
4525 // is dead/noop.
4526 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Value)) {
Dan Gohman9a4c92c2008-01-30 00:15:11 +00004527 if (Ld->getBasePtr() == Ptr && ST->getMemoryVT() == Ld->getMemoryVT() &&
Chris Lattner3bc08502008-01-17 19:59:44 +00004528 ST->isUnindexed() && !ST->isVolatile() &&
Chris Lattner2e023772008-01-08 23:08:06 +00004529 // There can't be any side effects between the load and store, such as
4530 // a call or store.
Chris Lattner10d94f92008-01-16 05:49:24 +00004531 Chain.reachesChainWithoutSideEffects(SDOperand(Ld, 1))) {
Chris Lattner447d8e82007-12-29 06:26:16 +00004532 // The store is dead, remove it.
4533 return Chain;
4534 }
4535 }
4536
Chris Lattner3bc08502008-01-17 19:59:44 +00004537 // If this is an FP_ROUND or TRUNC followed by a store, fold this into a
4538 // truncating store. We can do this even if this is already a truncstore.
4539 if ((Value.getOpcode() == ISD::FP_ROUND || Value.getOpcode() == ISD::TRUNCATE)
4540 && TLI.isTypeLegal(Value.getOperand(0).getValueType()) &&
4541 Value.Val->hasOneUse() && ST->isUnindexed() &&
4542 TLI.isTruncStoreLegal(Value.getOperand(0).getValueType(),
Dan Gohman9a4c92c2008-01-30 00:15:11 +00004543 ST->getMemoryVT())) {
Chris Lattner3bc08502008-01-17 19:59:44 +00004544 return DAG.getTruncStore(Chain, Value.getOperand(0), Ptr, ST->getSrcValue(),
Dan Gohman9a4c92c2008-01-30 00:15:11 +00004545 ST->getSrcValueOffset(), ST->getMemoryVT(),
Chris Lattner3bc08502008-01-17 19:59:44 +00004546 ST->isVolatile(), ST->getAlignment());
4547 }
4548
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004549 return SDOperand();
4550}
4551
4552SDOperand DAGCombiner::visitINSERT_VECTOR_ELT(SDNode *N) {
4553 SDOperand InVec = N->getOperand(0);
4554 SDOperand InVal = N->getOperand(1);
4555 SDOperand EltNo = N->getOperand(2);
4556
4557 // If the invec is a BUILD_VECTOR and if EltNo is a constant, build a new
4558 // vector with the inserted element.
4559 if (InVec.getOpcode() == ISD::BUILD_VECTOR && isa<ConstantSDNode>(EltNo)) {
4560 unsigned Elt = cast<ConstantSDNode>(EltNo)->getValue();
4561 SmallVector<SDOperand, 8> Ops(InVec.Val->op_begin(), InVec.Val->op_end());
4562 if (Elt < Ops.size())
4563 Ops[Elt] = InVal;
4564 return DAG.getNode(ISD::BUILD_VECTOR, InVec.getValueType(),
4565 &Ops[0], Ops.size());
4566 }
4567
4568 return SDOperand();
4569}
4570
Evan Chengd7ba7ed2007-10-06 08:19:55 +00004571SDOperand DAGCombiner::visitEXTRACT_VECTOR_ELT(SDNode *N) {
4572 SDOperand InVec = N->getOperand(0);
4573 SDOperand EltNo = N->getOperand(1);
4574
4575 // (vextract (v4f32 s2v (f32 load $addr)), 0) -> (f32 load $addr)
4576 // (vextract (v4i32 bc (v4f32 s2v (f32 load $addr))), 0) -> (i32 load $addr)
4577 if (isa<ConstantSDNode>(EltNo)) {
4578 unsigned Elt = cast<ConstantSDNode>(EltNo)->getValue();
4579 bool NewLoad = false;
4580 if (Elt == 0) {
4581 MVT::ValueType VT = InVec.getValueType();
4582 MVT::ValueType EVT = MVT::getVectorElementType(VT);
4583 MVT::ValueType LVT = EVT;
4584 unsigned NumElts = MVT::getVectorNumElements(VT);
4585 if (InVec.getOpcode() == ISD::BIT_CONVERT) {
4586 MVT::ValueType BCVT = InVec.getOperand(0).getValueType();
Dan Gohmana3591d92007-10-29 20:44:42 +00004587 if (!MVT::isVector(BCVT) ||
4588 NumElts != MVT::getVectorNumElements(BCVT))
Evan Chengd7ba7ed2007-10-06 08:19:55 +00004589 return SDOperand();
4590 InVec = InVec.getOperand(0);
4591 EVT = MVT::getVectorElementType(BCVT);
4592 NewLoad = true;
4593 }
4594 if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR &&
4595 InVec.getOperand(0).getValueType() == EVT &&
4596 ISD::isNormalLoad(InVec.getOperand(0).Val) &&
4597 InVec.getOperand(0).hasOneUse()) {
4598 LoadSDNode *LN0 = cast<LoadSDNode>(InVec.getOperand(0));
4599 unsigned Align = LN0->getAlignment();
4600 if (NewLoad) {
4601 // Check the resultant load doesn't need a higher alignment than the
4602 // original load.
4603 unsigned NewAlign = TLI.getTargetMachine().getTargetData()->
4604 getABITypeAlignment(MVT::getTypeForValueType(LVT));
4605 if (!TLI.isOperationLegal(ISD::LOAD, LVT) || NewAlign > Align)
4606 return SDOperand();
4607 Align = NewAlign;
4608 }
4609
4610 return DAG.getLoad(LVT, LN0->getChain(), LN0->getBasePtr(),
4611 LN0->getSrcValue(), LN0->getSrcValueOffset(),
4612 LN0->isVolatile(), Align);
4613 }
4614 }
4615 }
4616 return SDOperand();
4617}
4618
4619
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004620SDOperand DAGCombiner::visitBUILD_VECTOR(SDNode *N) {
4621 unsigned NumInScalars = N->getNumOperands();
4622 MVT::ValueType VT = N->getValueType(0);
4623 unsigned NumElts = MVT::getVectorNumElements(VT);
4624 MVT::ValueType EltType = MVT::getVectorElementType(VT);
4625
4626 // Check to see if this is a BUILD_VECTOR of a bunch of EXTRACT_VECTOR_ELT
4627 // operations. If so, and if the EXTRACT_VECTOR_ELT vector inputs come from
4628 // at most two distinct vectors, turn this into a shuffle node.
4629 SDOperand VecIn1, VecIn2;
4630 for (unsigned i = 0; i != NumInScalars; ++i) {
4631 // Ignore undef inputs.
4632 if (N->getOperand(i).getOpcode() == ISD::UNDEF) continue;
4633
4634 // If this input is something other than a EXTRACT_VECTOR_ELT with a
4635 // constant index, bail out.
4636 if (N->getOperand(i).getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
4637 !isa<ConstantSDNode>(N->getOperand(i).getOperand(1))) {
4638 VecIn1 = VecIn2 = SDOperand(0, 0);
4639 break;
4640 }
4641
4642 // If the input vector type disagrees with the result of the build_vector,
4643 // we can't make a shuffle.
4644 SDOperand ExtractedFromVec = N->getOperand(i).getOperand(0);
4645 if (ExtractedFromVec.getValueType() != VT) {
4646 VecIn1 = VecIn2 = SDOperand(0, 0);
4647 break;
4648 }
4649
4650 // Otherwise, remember this. We allow up to two distinct input vectors.
4651 if (ExtractedFromVec == VecIn1 || ExtractedFromVec == VecIn2)
4652 continue;
4653
4654 if (VecIn1.Val == 0) {
4655 VecIn1 = ExtractedFromVec;
4656 } else if (VecIn2.Val == 0) {
4657 VecIn2 = ExtractedFromVec;
4658 } else {
4659 // Too many inputs.
4660 VecIn1 = VecIn2 = SDOperand(0, 0);
4661 break;
4662 }
4663 }
4664
4665 // If everything is good, we can make a shuffle operation.
4666 if (VecIn1.Val) {
4667 SmallVector<SDOperand, 8> BuildVecIndices;
4668 for (unsigned i = 0; i != NumInScalars; ++i) {
4669 if (N->getOperand(i).getOpcode() == ISD::UNDEF) {
4670 BuildVecIndices.push_back(DAG.getNode(ISD::UNDEF, TLI.getPointerTy()));
4671 continue;
4672 }
4673
4674 SDOperand Extract = N->getOperand(i);
4675
4676 // If extracting from the first vector, just use the index directly.
4677 if (Extract.getOperand(0) == VecIn1) {
4678 BuildVecIndices.push_back(Extract.getOperand(1));
4679 continue;
4680 }
4681
4682 // Otherwise, use InIdx + VecSize
4683 unsigned Idx = cast<ConstantSDNode>(Extract.getOperand(1))->getValue();
Chris Lattner5872a362008-01-17 07:00:52 +00004684 BuildVecIndices.push_back(DAG.getIntPtrConstant(Idx+NumInScalars));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004685 }
4686
4687 // Add count and size info.
Chris Lattner5872a362008-01-17 07:00:52 +00004688 MVT::ValueType BuildVecVT = MVT::getVectorType(TLI.getPointerTy(), NumElts);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004689
4690 // Return the new VECTOR_SHUFFLE node.
4691 SDOperand Ops[5];
4692 Ops[0] = VecIn1;
4693 if (VecIn2.Val) {
4694 Ops[1] = VecIn2;
4695 } else {
4696 // Use an undef build_vector as input for the second operand.
4697 std::vector<SDOperand> UnOps(NumInScalars,
4698 DAG.getNode(ISD::UNDEF,
4699 EltType));
4700 Ops[1] = DAG.getNode(ISD::BUILD_VECTOR, VT,
4701 &UnOps[0], UnOps.size());
4702 AddToWorkList(Ops[1].Val);
4703 }
4704 Ops[2] = DAG.getNode(ISD::BUILD_VECTOR, BuildVecVT,
4705 &BuildVecIndices[0], BuildVecIndices.size());
4706 return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, Ops, 3);
4707 }
4708
4709 return SDOperand();
4710}
4711
4712SDOperand DAGCombiner::visitCONCAT_VECTORS(SDNode *N) {
4713 // TODO: Check to see if this is a CONCAT_VECTORS of a bunch of
4714 // EXTRACT_SUBVECTOR operations. If so, and if the EXTRACT_SUBVECTOR vector
4715 // inputs come from at most two distinct vectors, turn this into a shuffle
4716 // node.
4717
4718 // If we only have one input vector, we don't need to do any concatenation.
4719 if (N->getNumOperands() == 1) {
4720 return N->getOperand(0);
4721 }
4722
4723 return SDOperand();
4724}
4725
4726SDOperand DAGCombiner::visitVECTOR_SHUFFLE(SDNode *N) {
4727 SDOperand ShufMask = N->getOperand(2);
4728 unsigned NumElts = ShufMask.getNumOperands();
4729
4730 // If the shuffle mask is an identity operation on the LHS, return the LHS.
4731 bool isIdentity = true;
4732 for (unsigned i = 0; i != NumElts; ++i) {
4733 if (ShufMask.getOperand(i).getOpcode() != ISD::UNDEF &&
4734 cast<ConstantSDNode>(ShufMask.getOperand(i))->getValue() != i) {
4735 isIdentity = false;
4736 break;
4737 }
4738 }
4739 if (isIdentity) return N->getOperand(0);
4740
4741 // If the shuffle mask is an identity operation on the RHS, return the RHS.
4742 isIdentity = true;
4743 for (unsigned i = 0; i != NumElts; ++i) {
4744 if (ShufMask.getOperand(i).getOpcode() != ISD::UNDEF &&
4745 cast<ConstantSDNode>(ShufMask.getOperand(i))->getValue() != i+NumElts) {
4746 isIdentity = false;
4747 break;
4748 }
4749 }
4750 if (isIdentity) return N->getOperand(1);
4751
4752 // Check if the shuffle is a unary shuffle, i.e. one of the vectors is not
4753 // needed at all.
4754 bool isUnary = true;
4755 bool isSplat = true;
4756 int VecNum = -1;
4757 unsigned BaseIdx = 0;
4758 for (unsigned i = 0; i != NumElts; ++i)
4759 if (ShufMask.getOperand(i).getOpcode() != ISD::UNDEF) {
4760 unsigned Idx = cast<ConstantSDNode>(ShufMask.getOperand(i))->getValue();
4761 int V = (Idx < NumElts) ? 0 : 1;
4762 if (VecNum == -1) {
4763 VecNum = V;
4764 BaseIdx = Idx;
4765 } else {
4766 if (BaseIdx != Idx)
4767 isSplat = false;
4768 if (VecNum != V) {
4769 isUnary = false;
4770 break;
4771 }
4772 }
4773 }
4774
4775 SDOperand N0 = N->getOperand(0);
4776 SDOperand N1 = N->getOperand(1);
4777 // Normalize unary shuffle so the RHS is undef.
4778 if (isUnary && VecNum == 1)
4779 std::swap(N0, N1);
4780
4781 // If it is a splat, check if the argument vector is a build_vector with
4782 // all scalar elements the same.
4783 if (isSplat) {
4784 SDNode *V = N0.Val;
4785
4786 // If this is a bit convert that changes the element type of the vector but
4787 // not the number of vector elements, look through it. Be careful not to
4788 // look though conversions that change things like v4f32 to v2f64.
4789 if (V->getOpcode() == ISD::BIT_CONVERT) {
4790 SDOperand ConvInput = V->getOperand(0);
4791 if (MVT::getVectorNumElements(ConvInput.getValueType()) == NumElts)
4792 V = ConvInput.Val;
4793 }
4794
4795 if (V->getOpcode() == ISD::BUILD_VECTOR) {
4796 unsigned NumElems = V->getNumOperands();
4797 if (NumElems > BaseIdx) {
4798 SDOperand Base;
4799 bool AllSame = true;
4800 for (unsigned i = 0; i != NumElems; ++i) {
4801 if (V->getOperand(i).getOpcode() != ISD::UNDEF) {
4802 Base = V->getOperand(i);
4803 break;
4804 }
4805 }
4806 // Splat of <u, u, u, u>, return <u, u, u, u>
4807 if (!Base.Val)
4808 return N0;
4809 for (unsigned i = 0; i != NumElems; ++i) {
Evan Cheng8d68c2b2007-09-18 21:54:37 +00004810 if (V->getOperand(i) != Base) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004811 AllSame = false;
4812 break;
4813 }
4814 }
4815 // Splat of <x, x, x, x>, return <x, x, x, x>
4816 if (AllSame)
4817 return N0;
4818 }
4819 }
4820 }
4821
4822 // If it is a unary or the LHS and the RHS are the same node, turn the RHS
4823 // into an undef.
4824 if (isUnary || N0 == N1) {
4825 // Check the SHUFFLE mask, mapping any inputs from the 2nd operand into the
4826 // first operand.
4827 SmallVector<SDOperand, 8> MappedOps;
4828 for (unsigned i = 0; i != NumElts; ++i) {
4829 if (ShufMask.getOperand(i).getOpcode() == ISD::UNDEF ||
4830 cast<ConstantSDNode>(ShufMask.getOperand(i))->getValue() < NumElts) {
4831 MappedOps.push_back(ShufMask.getOperand(i));
4832 } else {
4833 unsigned NewIdx =
4834 cast<ConstantSDNode>(ShufMask.getOperand(i))->getValue() - NumElts;
4835 MappedOps.push_back(DAG.getConstant(NewIdx, MVT::i32));
4836 }
4837 }
4838 ShufMask = DAG.getNode(ISD::BUILD_VECTOR, ShufMask.getValueType(),
4839 &MappedOps[0], MappedOps.size());
4840 AddToWorkList(ShufMask.Val);
4841 return DAG.getNode(ISD::VECTOR_SHUFFLE, N->getValueType(0),
4842 N0,
4843 DAG.getNode(ISD::UNDEF, N->getValueType(0)),
4844 ShufMask);
4845 }
4846
4847 return SDOperand();
4848}
4849
4850/// XformToShuffleWithZero - Returns a vector_shuffle if it able to transform
4851/// an AND to a vector_shuffle with the destination vector and a zero vector.
4852/// e.g. AND V, <0xffffffff, 0, 0xffffffff, 0>. ==>
4853/// vector_shuffle V, Zero, <0, 4, 2, 4>
4854SDOperand DAGCombiner::XformToShuffleWithZero(SDNode *N) {
4855 SDOperand LHS = N->getOperand(0);
4856 SDOperand RHS = N->getOperand(1);
4857 if (N->getOpcode() == ISD::AND) {
4858 if (RHS.getOpcode() == ISD::BIT_CONVERT)
4859 RHS = RHS.getOperand(0);
4860 if (RHS.getOpcode() == ISD::BUILD_VECTOR) {
4861 std::vector<SDOperand> IdxOps;
4862 unsigned NumOps = RHS.getNumOperands();
4863 unsigned NumElts = NumOps;
4864 MVT::ValueType EVT = MVT::getVectorElementType(RHS.getValueType());
4865 for (unsigned i = 0; i != NumElts; ++i) {
4866 SDOperand Elt = RHS.getOperand(i);
4867 if (!isa<ConstantSDNode>(Elt))
4868 return SDOperand();
4869 else if (cast<ConstantSDNode>(Elt)->isAllOnesValue())
4870 IdxOps.push_back(DAG.getConstant(i, EVT));
4871 else if (cast<ConstantSDNode>(Elt)->isNullValue())
4872 IdxOps.push_back(DAG.getConstant(NumElts, EVT));
4873 else
4874 return SDOperand();
4875 }
4876
4877 // Let's see if the target supports this vector_shuffle.
4878 if (!TLI.isVectorClearMaskLegal(IdxOps, EVT, DAG))
4879 return SDOperand();
4880
4881 // Return the new VECTOR_SHUFFLE node.
4882 MVT::ValueType VT = MVT::getVectorType(EVT, NumElts);
4883 std::vector<SDOperand> Ops;
4884 LHS = DAG.getNode(ISD::BIT_CONVERT, VT, LHS);
4885 Ops.push_back(LHS);
4886 AddToWorkList(LHS.Val);
4887 std::vector<SDOperand> ZeroOps(NumElts, DAG.getConstant(0, EVT));
4888 Ops.push_back(DAG.getNode(ISD::BUILD_VECTOR, VT,
4889 &ZeroOps[0], ZeroOps.size()));
4890 Ops.push_back(DAG.getNode(ISD::BUILD_VECTOR, VT,
4891 &IdxOps[0], IdxOps.size()));
4892 SDOperand Result = DAG.getNode(ISD::VECTOR_SHUFFLE, VT,
4893 &Ops[0], Ops.size());
4894 if (VT != LHS.getValueType()) {
4895 Result = DAG.getNode(ISD::BIT_CONVERT, LHS.getValueType(), Result);
4896 }
4897 return Result;
4898 }
4899 }
4900 return SDOperand();
4901}
4902
4903/// SimplifyVBinOp - Visit a binary vector operation, like ADD.
4904SDOperand DAGCombiner::SimplifyVBinOp(SDNode *N) {
4905 // After legalize, the target may be depending on adds and other
4906 // binary ops to provide legal ways to construct constants or other
4907 // things. Simplifying them may result in a loss of legality.
4908 if (AfterLegalize) return SDOperand();
4909
4910 MVT::ValueType VT = N->getValueType(0);
4911 assert(MVT::isVector(VT) && "SimplifyVBinOp only works on vectors!");
4912
4913 MVT::ValueType EltType = MVT::getVectorElementType(VT);
4914 SDOperand LHS = N->getOperand(0);
4915 SDOperand RHS = N->getOperand(1);
4916 SDOperand Shuffle = XformToShuffleWithZero(N);
4917 if (Shuffle.Val) return Shuffle;
4918
4919 // If the LHS and RHS are BUILD_VECTOR nodes, see if we can constant fold
4920 // this operation.
4921 if (LHS.getOpcode() == ISD::BUILD_VECTOR &&
4922 RHS.getOpcode() == ISD::BUILD_VECTOR) {
4923 SmallVector<SDOperand, 8> Ops;
4924 for (unsigned i = 0, e = LHS.getNumOperands(); i != e; ++i) {
4925 SDOperand LHSOp = LHS.getOperand(i);
4926 SDOperand RHSOp = RHS.getOperand(i);
4927 // If these two elements can't be folded, bail out.
4928 if ((LHSOp.getOpcode() != ISD::UNDEF &&
4929 LHSOp.getOpcode() != ISD::Constant &&
4930 LHSOp.getOpcode() != ISD::ConstantFP) ||
4931 (RHSOp.getOpcode() != ISD::UNDEF &&
4932 RHSOp.getOpcode() != ISD::Constant &&
4933 RHSOp.getOpcode() != ISD::ConstantFP))
4934 break;
4935 // Can't fold divide by zero.
4936 if (N->getOpcode() == ISD::SDIV || N->getOpcode() == ISD::UDIV ||
4937 N->getOpcode() == ISD::FDIV) {
4938 if ((RHSOp.getOpcode() == ISD::Constant &&
4939 cast<ConstantSDNode>(RHSOp.Val)->isNullValue()) ||
4940 (RHSOp.getOpcode() == ISD::ConstantFP &&
Dale Johannesen7604c1b2007-08-31 23:34:27 +00004941 cast<ConstantFPSDNode>(RHSOp.Val)->getValueAPF().isZero()))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004942 break;
4943 }
4944 Ops.push_back(DAG.getNode(N->getOpcode(), EltType, LHSOp, RHSOp));
4945 AddToWorkList(Ops.back().Val);
4946 assert((Ops.back().getOpcode() == ISD::UNDEF ||
4947 Ops.back().getOpcode() == ISD::Constant ||
4948 Ops.back().getOpcode() == ISD::ConstantFP) &&
4949 "Scalar binop didn't fold!");
4950 }
4951
4952 if (Ops.size() == LHS.getNumOperands()) {
4953 MVT::ValueType VT = LHS.getValueType();
4954 return DAG.getNode(ISD::BUILD_VECTOR, VT, &Ops[0], Ops.size());
4955 }
4956 }
4957
4958 return SDOperand();
4959}
4960
4961SDOperand DAGCombiner::SimplifySelect(SDOperand N0, SDOperand N1, SDOperand N2){
4962 assert(N0.getOpcode() ==ISD::SETCC && "First argument must be a SetCC node!");
4963
4964 SDOperand SCC = SimplifySelectCC(N0.getOperand(0), N0.getOperand(1), N1, N2,
4965 cast<CondCodeSDNode>(N0.getOperand(2))->get());
4966 // If we got a simplified select_cc node back from SimplifySelectCC, then
4967 // break it down into a new SETCC node, and a new SELECT node, and then return
4968 // the SELECT node, since we were called with a SELECT node.
4969 if (SCC.Val) {
4970 // Check to see if we got a select_cc back (to turn into setcc/select).
4971 // Otherwise, just return whatever node we got back, like fabs.
4972 if (SCC.getOpcode() == ISD::SELECT_CC) {
4973 SDOperand SETCC = DAG.getNode(ISD::SETCC, N0.getValueType(),
4974 SCC.getOperand(0), SCC.getOperand(1),
4975 SCC.getOperand(4));
4976 AddToWorkList(SETCC.Val);
4977 return DAG.getNode(ISD::SELECT, SCC.getValueType(), SCC.getOperand(2),
4978 SCC.getOperand(3), SETCC);
4979 }
4980 return SCC;
4981 }
4982 return SDOperand();
4983}
4984
4985/// SimplifySelectOps - Given a SELECT or a SELECT_CC node, where LHS and RHS
4986/// are the two values being selected between, see if we can simplify the
4987/// select. Callers of this should assume that TheSelect is deleted if this
4988/// returns true. As such, they should return the appropriate thing (e.g. the
4989/// node) back to the top-level of the DAG combiner loop to avoid it being
4990/// looked at.
4991///
4992bool DAGCombiner::SimplifySelectOps(SDNode *TheSelect, SDOperand LHS,
4993 SDOperand RHS) {
4994
4995 // If this is a select from two identical things, try to pull the operation
4996 // through the select.
4997 if (LHS.getOpcode() == RHS.getOpcode() && LHS.hasOneUse() && RHS.hasOneUse()){
4998 // If this is a load and the token chain is identical, replace the select
4999 // of two loads with a load through a select of the address to load from.
5000 // This triggers in things like "select bool X, 10.0, 123.0" after the FP
5001 // constants have been dropped into the constant pool.
5002 if (LHS.getOpcode() == ISD::LOAD &&
5003 // Token chains must be identical.
5004 LHS.getOperand(0) == RHS.getOperand(0)) {
5005 LoadSDNode *LLD = cast<LoadSDNode>(LHS);
5006 LoadSDNode *RLD = cast<LoadSDNode>(RHS);
5007
5008 // If this is an EXTLOAD, the VT's must match.
Dan Gohman9a4c92c2008-01-30 00:15:11 +00005009 if (LLD->getMemoryVT() == RLD->getMemoryVT()) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005010 // FIXME: this conflates two src values, discarding one. This is not
5011 // the right thing to do, but nothing uses srcvalues now. When they do,
5012 // turn SrcValue into a list of locations.
5013 SDOperand Addr;
5014 if (TheSelect->getOpcode() == ISD::SELECT) {
5015 // Check that the condition doesn't reach either load. If so, folding
5016 // this will induce a cycle into the DAG.
Evan Chengd9387682008-03-04 00:41:45 +00005017 if (!LLD->isPredecessorOf(TheSelect->getOperand(0).Val) &&
5018 !RLD->isPredecessorOf(TheSelect->getOperand(0).Val)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005019 Addr = DAG.getNode(ISD::SELECT, LLD->getBasePtr().getValueType(),
5020 TheSelect->getOperand(0), LLD->getBasePtr(),
5021 RLD->getBasePtr());
5022 }
5023 } else {
5024 // Check that the condition doesn't reach either load. If so, folding
5025 // this will induce a cycle into the DAG.
Evan Chengd9387682008-03-04 00:41:45 +00005026 if (!LLD->isPredecessorOf(TheSelect->getOperand(0).Val) &&
5027 !RLD->isPredecessorOf(TheSelect->getOperand(0).Val) &&
5028 !LLD->isPredecessorOf(TheSelect->getOperand(1).Val) &&
5029 !RLD->isPredecessorOf(TheSelect->getOperand(1).Val)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005030 Addr = DAG.getNode(ISD::SELECT_CC, LLD->getBasePtr().getValueType(),
5031 TheSelect->getOperand(0),
5032 TheSelect->getOperand(1),
5033 LLD->getBasePtr(), RLD->getBasePtr(),
5034 TheSelect->getOperand(4));
5035 }
5036 }
5037
5038 if (Addr.Val) {
5039 SDOperand Load;
5040 if (LLD->getExtensionType() == ISD::NON_EXTLOAD)
5041 Load = DAG.getLoad(TheSelect->getValueType(0), LLD->getChain(),
5042 Addr,LLD->getSrcValue(),
5043 LLD->getSrcValueOffset(),
5044 LLD->isVolatile(),
5045 LLD->getAlignment());
5046 else {
5047 Load = DAG.getExtLoad(LLD->getExtensionType(),
5048 TheSelect->getValueType(0),
5049 LLD->getChain(), Addr, LLD->getSrcValue(),
5050 LLD->getSrcValueOffset(),
Dan Gohman9a4c92c2008-01-30 00:15:11 +00005051 LLD->getMemoryVT(),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005052 LLD->isVolatile(),
5053 LLD->getAlignment());
5054 }
5055 // Users of the select now use the result of the load.
5056 CombineTo(TheSelect, Load);
5057
5058 // Users of the old loads now use the new load's chain. We know the
5059 // old-load value is dead now.
5060 CombineTo(LHS.Val, Load.getValue(0), Load.getValue(1));
5061 CombineTo(RHS.Val, Load.getValue(0), Load.getValue(1));
5062 return true;
5063 }
5064 }
5065 }
5066 }
5067
5068 return false;
5069}
5070
5071SDOperand DAGCombiner::SimplifySelectCC(SDOperand N0, SDOperand N1,
5072 SDOperand N2, SDOperand N3,
5073 ISD::CondCode CC, bool NotExtCompare) {
5074
5075 MVT::ValueType VT = N2.getValueType();
5076 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.Val);
5077 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2.Val);
5078 ConstantSDNode *N3C = dyn_cast<ConstantSDNode>(N3.Val);
5079
5080 // Determine if the condition we're dealing with is constant
Scott Michel502151f2008-03-10 15:42:14 +00005081 SDOperand SCC = SimplifySetCC(TLI.getSetCCResultType(N0), N0, N1, CC, false);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005082 if (SCC.Val) AddToWorkList(SCC.Val);
5083 ConstantSDNode *SCCC = dyn_cast_or_null<ConstantSDNode>(SCC.Val);
5084
5085 // fold select_cc true, x, y -> x
5086 if (SCCC && SCCC->getValue())
5087 return N2;
5088 // fold select_cc false, x, y -> y
5089 if (SCCC && SCCC->getValue() == 0)
5090 return N3;
5091
5092 // Check to see if we can simplify the select into an fabs node
5093 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N1)) {
5094 // Allow either -0.0 or 0.0
Dale Johannesen7f2c1d12007-08-25 22:10:57 +00005095 if (CFP->getValueAPF().isZero()) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005096 // select (setg[te] X, +/-0.0), X, fneg(X) -> fabs
5097 if ((CC == ISD::SETGE || CC == ISD::SETGT) &&
5098 N0 == N2 && N3.getOpcode() == ISD::FNEG &&
5099 N2 == N3.getOperand(0))
5100 return DAG.getNode(ISD::FABS, VT, N0);
5101
5102 // select (setl[te] X, +/-0.0), fneg(X), X -> fabs
5103 if ((CC == ISD::SETLT || CC == ISD::SETLE) &&
5104 N0 == N3 && N2.getOpcode() == ISD::FNEG &&
5105 N2.getOperand(0) == N3)
5106 return DAG.getNode(ISD::FABS, VT, N3);
5107 }
5108 }
5109
5110 // Check to see if we can perform the "gzip trick", transforming
5111 // select_cc setlt X, 0, A, 0 -> and (sra X, size(X)-1), A
5112 if (N1C && N3C && N3C->isNullValue() && CC == ISD::SETLT &&
5113 MVT::isInteger(N0.getValueType()) &&
5114 MVT::isInteger(N2.getValueType()) &&
5115 (N1C->isNullValue() || // (a < 0) ? b : 0
5116 (N1C->getValue() == 1 && N0 == N2))) { // (a < 1) ? a : 0
5117 MVT::ValueType XType = N0.getValueType();
5118 MVT::ValueType AType = N2.getValueType();
5119 if (XType >= AType) {
5120 // and (sra X, size(X)-1, A) -> "and (srl X, C2), A" iff A is a
5121 // single-bit constant.
5122 if (N2C && ((N2C->getValue() & (N2C->getValue()-1)) == 0)) {
5123 unsigned ShCtV = Log2_64(N2C->getValue());
5124 ShCtV = MVT::getSizeInBits(XType)-ShCtV-1;
5125 SDOperand ShCt = DAG.getConstant(ShCtV, TLI.getShiftAmountTy());
5126 SDOperand Shift = DAG.getNode(ISD::SRL, XType, N0, ShCt);
5127 AddToWorkList(Shift.Val);
5128 if (XType > AType) {
5129 Shift = DAG.getNode(ISD::TRUNCATE, AType, Shift);
5130 AddToWorkList(Shift.Val);
5131 }
5132 return DAG.getNode(ISD::AND, AType, Shift, N2);
5133 }
5134 SDOperand Shift = DAG.getNode(ISD::SRA, XType, N0,
5135 DAG.getConstant(MVT::getSizeInBits(XType)-1,
5136 TLI.getShiftAmountTy()));
5137 AddToWorkList(Shift.Val);
5138 if (XType > AType) {
5139 Shift = DAG.getNode(ISD::TRUNCATE, AType, Shift);
5140 AddToWorkList(Shift.Val);
5141 }
5142 return DAG.getNode(ISD::AND, AType, Shift, N2);
5143 }
5144 }
5145
5146 // fold select C, 16, 0 -> shl C, 4
5147 if (N2C && N3C && N3C->isNullValue() && isPowerOf2_64(N2C->getValue()) &&
5148 TLI.getSetCCResultContents() == TargetLowering::ZeroOrOneSetCCResult) {
5149
5150 // If the caller doesn't want us to simplify this into a zext of a compare,
5151 // don't do it.
5152 if (NotExtCompare && N2C->getValue() == 1)
5153 return SDOperand();
5154
5155 // Get a SetCC of the condition
5156 // FIXME: Should probably make sure that setcc is legal if we ever have a
5157 // target where it isn't.
5158 SDOperand Temp, SCC;
5159 // cast from setcc result type to select result type
5160 if (AfterLegalize) {
Scott Michel502151f2008-03-10 15:42:14 +00005161 SCC = DAG.getSetCC(TLI.getSetCCResultType(N0), N0, N1, CC);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005162 if (N2.getValueType() < SCC.getValueType())
5163 Temp = DAG.getZeroExtendInReg(SCC, N2.getValueType());
5164 else
5165 Temp = DAG.getNode(ISD::ZERO_EXTEND, N2.getValueType(), SCC);
5166 } else {
5167 SCC = DAG.getSetCC(MVT::i1, N0, N1, CC);
5168 Temp = DAG.getNode(ISD::ZERO_EXTEND, N2.getValueType(), SCC);
5169 }
5170 AddToWorkList(SCC.Val);
5171 AddToWorkList(Temp.Val);
5172
5173 if (N2C->getValue() == 1)
5174 return Temp;
5175 // shl setcc result by log2 n2c
5176 return DAG.getNode(ISD::SHL, N2.getValueType(), Temp,
5177 DAG.getConstant(Log2_64(N2C->getValue()),
5178 TLI.getShiftAmountTy()));
5179 }
5180
5181 // Check to see if this is the equivalent of setcc
5182 // FIXME: Turn all of these into setcc if setcc if setcc is legal
5183 // otherwise, go ahead with the folds.
5184 if (0 && N3C && N3C->isNullValue() && N2C && (N2C->getValue() == 1ULL)) {
5185 MVT::ValueType XType = N0.getValueType();
Scott Michel502151f2008-03-10 15:42:14 +00005186 if (TLI.isOperationLegal(ISD::SETCC, TLI.getSetCCResultType(N0))) {
5187 SDOperand Res = DAG.getSetCC(TLI.getSetCCResultType(N0), N0, N1, CC);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005188 if (Res.getValueType() != VT)
5189 Res = DAG.getNode(ISD::ZERO_EXTEND, VT, Res);
5190 return Res;
5191 }
5192
5193 // seteq X, 0 -> srl (ctlz X, log2(size(X)))
5194 if (N1C && N1C->isNullValue() && CC == ISD::SETEQ &&
5195 TLI.isOperationLegal(ISD::CTLZ, XType)) {
5196 SDOperand Ctlz = DAG.getNode(ISD::CTLZ, XType, N0);
5197 return DAG.getNode(ISD::SRL, XType, Ctlz,
5198 DAG.getConstant(Log2_32(MVT::getSizeInBits(XType)),
5199 TLI.getShiftAmountTy()));
5200 }
5201 // setgt X, 0 -> srl (and (-X, ~X), size(X)-1)
5202 if (N1C && N1C->isNullValue() && CC == ISD::SETGT) {
5203 SDOperand NegN0 = DAG.getNode(ISD::SUB, XType, DAG.getConstant(0, XType),
5204 N0);
5205 SDOperand NotN0 = DAG.getNode(ISD::XOR, XType, N0,
5206 DAG.getConstant(~0ULL, XType));
5207 return DAG.getNode(ISD::SRL, XType,
5208 DAG.getNode(ISD::AND, XType, NegN0, NotN0),
5209 DAG.getConstant(MVT::getSizeInBits(XType)-1,
5210 TLI.getShiftAmountTy()));
5211 }
5212 // setgt X, -1 -> xor (srl (X, size(X)-1), 1)
5213 if (N1C && N1C->isAllOnesValue() && CC == ISD::SETGT) {
5214 SDOperand Sign = DAG.getNode(ISD::SRL, XType, N0,
5215 DAG.getConstant(MVT::getSizeInBits(XType)-1,
5216 TLI.getShiftAmountTy()));
5217 return DAG.getNode(ISD::XOR, XType, Sign, DAG.getConstant(1, XType));
5218 }
5219 }
5220
5221 // Check to see if this is an integer abs. select_cc setl[te] X, 0, -X, X ->
5222 // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
5223 if (N1C && N1C->isNullValue() && (CC == ISD::SETLT || CC == ISD::SETLE) &&
5224 N0 == N3 && N2.getOpcode() == ISD::SUB && N0 == N2.getOperand(1) &&
5225 N2.getOperand(0) == N1 && MVT::isInteger(N0.getValueType())) {
5226 MVT::ValueType XType = N0.getValueType();
5227 SDOperand Shift = DAG.getNode(ISD::SRA, XType, N0,
5228 DAG.getConstant(MVT::getSizeInBits(XType)-1,
5229 TLI.getShiftAmountTy()));
5230 SDOperand Add = DAG.getNode(ISD::ADD, XType, N0, Shift);
5231 AddToWorkList(Shift.Val);
5232 AddToWorkList(Add.Val);
5233 return DAG.getNode(ISD::XOR, XType, Add, Shift);
5234 }
5235 // Check to see if this is an integer abs. select_cc setgt X, -1, X, -X ->
5236 // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
5237 if (N1C && N1C->isAllOnesValue() && CC == ISD::SETGT &&
5238 N0 == N2 && N3.getOpcode() == ISD::SUB && N0 == N3.getOperand(1)) {
5239 if (ConstantSDNode *SubC = dyn_cast<ConstantSDNode>(N3.getOperand(0))) {
5240 MVT::ValueType XType = N0.getValueType();
5241 if (SubC->isNullValue() && MVT::isInteger(XType)) {
5242 SDOperand Shift = DAG.getNode(ISD::SRA, XType, N0,
5243 DAG.getConstant(MVT::getSizeInBits(XType)-1,
5244 TLI.getShiftAmountTy()));
5245 SDOperand Add = DAG.getNode(ISD::ADD, XType, N0, Shift);
5246 AddToWorkList(Shift.Val);
5247 AddToWorkList(Add.Val);
5248 return DAG.getNode(ISD::XOR, XType, Add, Shift);
5249 }
5250 }
5251 }
5252
5253 return SDOperand();
5254}
5255
5256/// SimplifySetCC - This is a stub for TargetLowering::SimplifySetCC.
5257SDOperand DAGCombiner::SimplifySetCC(MVT::ValueType VT, SDOperand N0,
5258 SDOperand N1, ISD::CondCode Cond,
5259 bool foldBooleans) {
5260 TargetLowering::DAGCombinerInfo
5261 DagCombineInfo(DAG, !AfterLegalize, false, this);
5262 return TLI.SimplifySetCC(VT, N0, N1, Cond, foldBooleans, DagCombineInfo);
5263}
5264
5265/// BuildSDIVSequence - Given an ISD::SDIV node expressing a divide by constant,
5266/// return a DAG expression to select that will generate the same value by
5267/// multiplying by a magic number. See:
5268/// <http://the.wall.riscom.net/books/proc/ppc/cwg/code2.html>
5269SDOperand DAGCombiner::BuildSDIV(SDNode *N) {
5270 std::vector<SDNode*> Built;
5271 SDOperand S = TLI.BuildSDIV(N, DAG, &Built);
5272
5273 for (std::vector<SDNode*>::iterator ii = Built.begin(), ee = Built.end();
5274 ii != ee; ++ii)
5275 AddToWorkList(*ii);
5276 return S;
5277}
5278
5279/// BuildUDIVSequence - Given an ISD::UDIV node expressing a divide by constant,
5280/// return a DAG expression to select that will generate the same value by
5281/// multiplying by a magic number. See:
5282/// <http://the.wall.riscom.net/books/proc/ppc/cwg/code2.html>
5283SDOperand DAGCombiner::BuildUDIV(SDNode *N) {
5284 std::vector<SDNode*> Built;
5285 SDOperand S = TLI.BuildUDIV(N, DAG, &Built);
5286
5287 for (std::vector<SDNode*>::iterator ii = Built.begin(), ee = Built.end();
5288 ii != ee; ++ii)
5289 AddToWorkList(*ii);
5290 return S;
5291}
5292
5293/// FindBaseOffset - Return true if base is known not to alias with anything
5294/// but itself. Provides base object and offset as results.
5295static bool FindBaseOffset(SDOperand Ptr, SDOperand &Base, int64_t &Offset) {
5296 // Assume it is a primitive operation.
5297 Base = Ptr; Offset = 0;
5298
5299 // If it's an adding a simple constant then integrate the offset.
5300 if (Base.getOpcode() == ISD::ADD) {
5301 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Base.getOperand(1))) {
5302 Base = Base.getOperand(0);
5303 Offset += C->getValue();
5304 }
5305 }
5306
5307 // If it's any of the following then it can't alias with anything but itself.
5308 return isa<FrameIndexSDNode>(Base) ||
5309 isa<ConstantPoolSDNode>(Base) ||
5310 isa<GlobalAddressSDNode>(Base);
5311}
5312
5313/// isAlias - Return true if there is any possibility that the two addresses
5314/// overlap.
5315bool DAGCombiner::isAlias(SDOperand Ptr1, int64_t Size1,
5316 const Value *SrcValue1, int SrcValueOffset1,
5317 SDOperand Ptr2, int64_t Size2,
5318 const Value *SrcValue2, int SrcValueOffset2)
5319{
5320 // If they are the same then they must be aliases.
5321 if (Ptr1 == Ptr2) return true;
5322
5323 // Gather base node and offset information.
5324 SDOperand Base1, Base2;
5325 int64_t Offset1, Offset2;
5326 bool KnownBase1 = FindBaseOffset(Ptr1, Base1, Offset1);
5327 bool KnownBase2 = FindBaseOffset(Ptr2, Base2, Offset2);
5328
5329 // If they have a same base address then...
5330 if (Base1 == Base2) {
5331 // Check to see if the addresses overlap.
5332 return!((Offset1 + Size1) <= Offset2 || (Offset2 + Size2) <= Offset1);
5333 }
5334
5335 // If we know both bases then they can't alias.
5336 if (KnownBase1 && KnownBase2) return false;
5337
5338 if (CombinerGlobalAA) {
5339 // Use alias analysis information.
Dan Gohmane142c2e2007-08-27 16:32:11 +00005340 int64_t MinOffset = std::min(SrcValueOffset1, SrcValueOffset2);
5341 int64_t Overlap1 = Size1 + SrcValueOffset1 - MinOffset;
5342 int64_t Overlap2 = Size2 + SrcValueOffset2 - MinOffset;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005343 AliasAnalysis::AliasResult AAResult =
5344 AA.alias(SrcValue1, Overlap1, SrcValue2, Overlap2);
5345 if (AAResult == AliasAnalysis::NoAlias)
5346 return false;
5347 }
5348
5349 // Otherwise we have to assume they alias.
5350 return true;
5351}
5352
5353/// FindAliasInfo - Extracts the relevant alias information from the memory
5354/// node. Returns true if the operand was a load.
5355bool DAGCombiner::FindAliasInfo(SDNode *N,
5356 SDOperand &Ptr, int64_t &Size,
5357 const Value *&SrcValue, int &SrcValueOffset) {
5358 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
5359 Ptr = LD->getBasePtr();
Dan Gohman9a4c92c2008-01-30 00:15:11 +00005360 Size = MVT::getSizeInBits(LD->getMemoryVT()) >> 3;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005361 SrcValue = LD->getSrcValue();
5362 SrcValueOffset = LD->getSrcValueOffset();
5363 return true;
5364 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
5365 Ptr = ST->getBasePtr();
Dan Gohman9a4c92c2008-01-30 00:15:11 +00005366 Size = MVT::getSizeInBits(ST->getMemoryVT()) >> 3;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005367 SrcValue = ST->getSrcValue();
5368 SrcValueOffset = ST->getSrcValueOffset();
5369 } else {
5370 assert(0 && "FindAliasInfo expected a memory operand");
5371 }
5372
5373 return false;
5374}
5375
5376/// GatherAllAliases - Walk up chain skipping non-aliasing memory nodes,
5377/// looking for aliasing nodes and adding them to the Aliases vector.
5378void DAGCombiner::GatherAllAliases(SDNode *N, SDOperand OriginalChain,
5379 SmallVector<SDOperand, 8> &Aliases) {
5380 SmallVector<SDOperand, 8> Chains; // List of chains to visit.
5381 std::set<SDNode *> Visited; // Visited node set.
5382
5383 // Get alias information for node.
5384 SDOperand Ptr;
5385 int64_t Size;
5386 const Value *SrcValue;
5387 int SrcValueOffset;
5388 bool IsLoad = FindAliasInfo(N, Ptr, Size, SrcValue, SrcValueOffset);
5389
5390 // Starting off.
5391 Chains.push_back(OriginalChain);
5392
5393 // Look at each chain and determine if it is an alias. If so, add it to the
5394 // aliases list. If not, then continue up the chain looking for the next
5395 // candidate.
5396 while (!Chains.empty()) {
5397 SDOperand Chain = Chains.back();
5398 Chains.pop_back();
5399
5400 // Don't bother if we've been before.
5401 if (Visited.find(Chain.Val) != Visited.end()) continue;
5402 Visited.insert(Chain.Val);
5403
5404 switch (Chain.getOpcode()) {
5405 case ISD::EntryToken:
5406 // Entry token is ideal chain operand, but handled in FindBetterChain.
5407 break;
5408
5409 case ISD::LOAD:
5410 case ISD::STORE: {
5411 // Get alias information for Chain.
5412 SDOperand OpPtr;
5413 int64_t OpSize;
5414 const Value *OpSrcValue;
5415 int OpSrcValueOffset;
5416 bool IsOpLoad = FindAliasInfo(Chain.Val, OpPtr, OpSize,
5417 OpSrcValue, OpSrcValueOffset);
5418
5419 // If chain is alias then stop here.
5420 if (!(IsLoad && IsOpLoad) &&
5421 isAlias(Ptr, Size, SrcValue, SrcValueOffset,
5422 OpPtr, OpSize, OpSrcValue, OpSrcValueOffset)) {
5423 Aliases.push_back(Chain);
5424 } else {
5425 // Look further up the chain.
5426 Chains.push_back(Chain.getOperand(0));
5427 // Clean up old chain.
5428 AddToWorkList(Chain.Val);
5429 }
5430 break;
5431 }
5432
5433 case ISD::TokenFactor:
5434 // We have to check each of the operands of the token factor, so we queue
5435 // then up. Adding the operands to the queue (stack) in reverse order
5436 // maintains the original order and increases the likelihood that getNode
5437 // will find a matching token factor (CSE.)
5438 for (unsigned n = Chain.getNumOperands(); n;)
5439 Chains.push_back(Chain.getOperand(--n));
5440 // Eliminate the token factor if we can.
5441 AddToWorkList(Chain.Val);
5442 break;
5443
5444 default:
5445 // For all other instructions we will just have to take what we can get.
5446 Aliases.push_back(Chain);
5447 break;
5448 }
5449 }
5450}
5451
5452/// FindBetterChain - Walk up chain skipping non-aliasing memory nodes, looking
5453/// for a better chain (aliasing node.)
5454SDOperand DAGCombiner::FindBetterChain(SDNode *N, SDOperand OldChain) {
5455 SmallVector<SDOperand, 8> Aliases; // Ops for replacing token factor.
5456
5457 // Accumulate all the aliases to this node.
5458 GatherAllAliases(N, OldChain, Aliases);
5459
5460 if (Aliases.size() == 0) {
5461 // If no operands then chain to entry token.
5462 return DAG.getEntryNode();
5463 } else if (Aliases.size() == 1) {
5464 // If a single operand then chain to it. We don't need to revisit it.
5465 return Aliases[0];
5466 }
5467
5468 // Construct a custom tailored token factor.
5469 SDOperand NewChain = DAG.getNode(ISD::TokenFactor, MVT::Other,
5470 &Aliases[0], Aliases.size());
5471
5472 // Make sure the old chain gets cleaned up.
5473 if (NewChain != OldChain) AddToWorkList(OldChain.Val);
5474
5475 return NewChain;
5476}
5477
5478// SelectionDAG::Combine - This is the entry point for the file.
5479//
5480void SelectionDAG::Combine(bool RunningAfterLegalize, AliasAnalysis &AA) {
5481 if (!RunningAfterLegalize && ViewDAGCombine1)
5482 viewGraph();
5483 if (RunningAfterLegalize && ViewDAGCombine2)
5484 viewGraph();
5485 /// run - This is the main entry point to this class.
5486 ///
5487 DAGCombiner(*this, AA).Run(RunningAfterLegalize);
5488}