blob: 6510a0f70d7232783afcbebaee7a5406802d0636 [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"
21#include "llvm/Target/TargetLowering.h"
22#include "llvm/Target/TargetMachine.h"
23#include "llvm/Target/TargetOptions.h"
24#include "llvm/ADT/SmallPtrSet.h"
25#include "llvm/ADT/Statistic.h"
26#include "llvm/Support/Compiler.h"
27#include "llvm/Support/CommandLine.h"
28#include "llvm/Support/Debug.h"
29#include "llvm/Support/MathExtras.h"
30#include <algorithm>
31using namespace llvm;
32
33STATISTIC(NodesCombined , "Number of dag nodes combined");
34STATISTIC(PreIndexedNodes , "Number of pre-indexed nodes created");
35STATISTIC(PostIndexedNodes, "Number of post-indexed nodes created");
36
37namespace {
38#ifndef NDEBUG
39 static cl::opt<bool>
40 ViewDAGCombine1("view-dag-combine1-dags", cl::Hidden,
41 cl::desc("Pop up a window to show dags before the first "
42 "dag combine pass"));
43 static cl::opt<bool>
44 ViewDAGCombine2("view-dag-combine2-dags", cl::Hidden,
45 cl::desc("Pop up a window to show dags before the second "
46 "dag combine pass"));
47#else
48 static const bool ViewDAGCombine1 = false;
49 static const bool ViewDAGCombine2 = false;
50#endif
51
52 static cl::opt<bool>
53 CombinerAA("combiner-alias-analysis", cl::Hidden,
54 cl::desc("Turn on alias analysis during testing"));
55
56 static cl::opt<bool>
57 CombinerGlobalAA("combiner-global-alias-analysis", cl::Hidden,
58 cl::desc("Include global information in alias analysis"));
59
60//------------------------------ DAGCombiner ---------------------------------//
61
62 class VISIBILITY_HIDDEN DAGCombiner {
63 SelectionDAG &DAG;
64 TargetLowering &TLI;
65 bool AfterLegalize;
66
67 // Worklist of all of the nodes that need to be simplified.
68 std::vector<SDNode*> WorkList;
69
70 // AA - Used for DAG load/store alias analysis.
71 AliasAnalysis &AA;
72
73 /// AddUsersToWorkList - When an instruction is simplified, add all users of
74 /// the instruction to the work lists because they might get more simplified
75 /// now.
76 ///
77 void AddUsersToWorkList(SDNode *N) {
78 for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
79 UI != UE; ++UI)
80 AddToWorkList(*UI);
81 }
82
83 /// removeFromWorkList - remove all instances of N from the worklist.
84 ///
85 void removeFromWorkList(SDNode *N) {
86 WorkList.erase(std::remove(WorkList.begin(), WorkList.end(), N),
87 WorkList.end());
88 }
89
Dan Gohman6c89ea72007-10-08 17:57:15 +000090 /// visit - call the node-specific routine that knows how to fold each
91 /// particular type of node.
92 SDOperand visit(SDNode *N);
93
Dan Gohmanf17a25c2007-07-18 16:29:46 +000094 public:
95 /// AddToWorkList - Add to the work list making sure it's instance is at the
96 /// the back (next to be processed.)
97 void AddToWorkList(SDNode *N) {
98 removeFromWorkList(N);
99 WorkList.push_back(N);
100 }
101
102 SDOperand CombineTo(SDNode *N, const SDOperand *To, unsigned NumTo,
103 bool AddTo = true) {
104 assert(N->getNumValues() == NumTo && "Broken CombineTo call!");
105 ++NodesCombined;
106 DOUT << "\nReplacing.1 "; DEBUG(N->dump(&DAG));
107 DOUT << "\nWith: "; DEBUG(To[0].Val->dump(&DAG));
108 DOUT << " and " << NumTo-1 << " other values\n";
109 std::vector<SDNode*> NowDead;
110 DAG.ReplaceAllUsesWith(N, To, &NowDead);
111
112 if (AddTo) {
113 // Push the new nodes and any users onto the worklist
114 for (unsigned i = 0, e = NumTo; i != e; ++i) {
115 AddToWorkList(To[i].Val);
116 AddUsersToWorkList(To[i].Val);
117 }
118 }
119
120 // Nodes can be reintroduced into the worklist. Make sure we do not
121 // process a node that has been replaced.
122 removeFromWorkList(N);
123 for (unsigned i = 0, e = NowDead.size(); i != e; ++i)
124 removeFromWorkList(NowDead[i]);
125
126 // Finally, since the node is now dead, remove it from the graph.
127 DAG.DeleteNode(N);
128 return SDOperand(N, 0);
129 }
130
131 SDOperand CombineTo(SDNode *N, SDOperand Res, bool AddTo = true) {
132 return CombineTo(N, &Res, 1, AddTo);
133 }
134
135 SDOperand CombineTo(SDNode *N, SDOperand Res0, SDOperand Res1,
136 bool AddTo = true) {
137 SDOperand To[] = { Res0, Res1 };
138 return CombineTo(N, To, 2, AddTo);
139 }
Chris Lattner5872a362008-01-17 07:00:52 +0000140
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000141 private:
142
143 /// SimplifyDemandedBits - Check the specified integer node value to see if
144 /// it can be simplified or if things it uses can be simplified by bit
145 /// propagation. If so, return true.
Chris Lattnerb77ea552007-10-13 06:58:48 +0000146 bool SimplifyDemandedBits(SDOperand Op, uint64_t Demanded = ~0ULL) {
Chris Lattner2f36eb92007-12-22 20:56:36 +0000147 TargetLowering::TargetLoweringOpt TLO(DAG, AfterLegalize);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000148 uint64_t KnownZero, KnownOne;
Chris Lattnerb77ea552007-10-13 06:58:48 +0000149 Demanded &= MVT::getIntVTBitMask(Op.getValueType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000150 if (!TLI.SimplifyDemandedBits(Op, Demanded, KnownZero, KnownOne, TLO))
151 return false;
152
153 // Revisit the node.
154 AddToWorkList(Op.Val);
155
156 // Replace the old value with the new one.
157 ++NodesCombined;
158 DOUT << "\nReplacing.2 "; DEBUG(TLO.Old.Val->dump(&DAG));
159 DOUT << "\nWith: "; DEBUG(TLO.New.Val->dump(&DAG));
160 DOUT << '\n';
161
162 std::vector<SDNode*> NowDead;
Chris Lattner8a258202007-10-15 06:10:22 +0000163 DAG.ReplaceAllUsesOfValueWith(TLO.Old, TLO.New, &NowDead);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000164
165 // Push the new node and any (possibly new) users onto the worklist.
166 AddToWorkList(TLO.New.Val);
167 AddUsersToWorkList(TLO.New.Val);
168
169 // Nodes can end up on the worklist more than once. Make sure we do
170 // not process a node that has been replaced.
171 for (unsigned i = 0, e = NowDead.size(); i != e; ++i)
172 removeFromWorkList(NowDead[i]);
173
174 // Finally, if the node is now dead, remove it from the graph. The node
175 // may not be dead if the replacement process recursively simplified to
176 // something else needing this node.
177 if (TLO.Old.Val->use_empty()) {
178 removeFromWorkList(TLO.Old.Val);
179
180 // If the operands of this node are only used by the node, they will now
181 // be dead. Make sure to visit them first to delete dead nodes early.
182 for (unsigned i = 0, e = TLO.Old.Val->getNumOperands(); i != e; ++i)
183 if (TLO.Old.Val->getOperand(i).Val->hasOneUse())
184 AddToWorkList(TLO.Old.Val->getOperand(i).Val);
185
186 DAG.DeleteNode(TLO.Old.Val);
187 }
188 return true;
189 }
190
191 bool CombineToPreIndexedLoadStore(SDNode *N);
192 bool CombineToPostIndexedLoadStore(SDNode *N);
193
194
Dan Gohman6c89ea72007-10-08 17:57:15 +0000195 /// combine - call the node-specific routine that knows how to fold each
196 /// particular type of node. If that doesn't do anything, try the
197 /// target-specific DAG combines.
198 SDOperand combine(SDNode *N);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000199
200 // Visitation implementation - Implement dag node combining for different
201 // node types. The semantics are as follows:
202 // Return Value:
203 // SDOperand.Val == 0 - No change was made
204 // SDOperand.Val == N - N was replaced, is dead, and is already handled.
205 // otherwise - N should be replaced by the returned Operand.
206 //
207 SDOperand visitTokenFactor(SDNode *N);
208 SDOperand visitADD(SDNode *N);
209 SDOperand visitSUB(SDNode *N);
210 SDOperand visitADDC(SDNode *N);
211 SDOperand visitADDE(SDNode *N);
212 SDOperand visitMUL(SDNode *N);
213 SDOperand visitSDIV(SDNode *N);
214 SDOperand visitUDIV(SDNode *N);
215 SDOperand visitSREM(SDNode *N);
216 SDOperand visitUREM(SDNode *N);
217 SDOperand visitMULHU(SDNode *N);
218 SDOperand visitMULHS(SDNode *N);
Dan Gohman6c89ea72007-10-08 17:57:15 +0000219 SDOperand visitSMUL_LOHI(SDNode *N);
220 SDOperand visitUMUL_LOHI(SDNode *N);
221 SDOperand visitSDIVREM(SDNode *N);
222 SDOperand visitUDIVREM(SDNode *N);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000223 SDOperand visitAND(SDNode *N);
224 SDOperand visitOR(SDNode *N);
225 SDOperand visitXOR(SDNode *N);
226 SDOperand SimplifyVBinOp(SDNode *N);
227 SDOperand visitSHL(SDNode *N);
228 SDOperand visitSRA(SDNode *N);
229 SDOperand visitSRL(SDNode *N);
230 SDOperand visitCTLZ(SDNode *N);
231 SDOperand visitCTTZ(SDNode *N);
232 SDOperand visitCTPOP(SDNode *N);
233 SDOperand visitSELECT(SDNode *N);
234 SDOperand visitSELECT_CC(SDNode *N);
235 SDOperand visitSETCC(SDNode *N);
236 SDOperand visitSIGN_EXTEND(SDNode *N);
237 SDOperand visitZERO_EXTEND(SDNode *N);
238 SDOperand visitANY_EXTEND(SDNode *N);
239 SDOperand visitSIGN_EXTEND_INREG(SDNode *N);
240 SDOperand visitTRUNCATE(SDNode *N);
241 SDOperand visitBIT_CONVERT(SDNode *N);
242 SDOperand visitFADD(SDNode *N);
243 SDOperand visitFSUB(SDNode *N);
244 SDOperand visitFMUL(SDNode *N);
245 SDOperand visitFDIV(SDNode *N);
246 SDOperand visitFREM(SDNode *N);
247 SDOperand visitFCOPYSIGN(SDNode *N);
248 SDOperand visitSINT_TO_FP(SDNode *N);
249 SDOperand visitUINT_TO_FP(SDNode *N);
250 SDOperand visitFP_TO_SINT(SDNode *N);
251 SDOperand visitFP_TO_UINT(SDNode *N);
252 SDOperand visitFP_ROUND(SDNode *N);
253 SDOperand visitFP_ROUND_INREG(SDNode *N);
254 SDOperand visitFP_EXTEND(SDNode *N);
255 SDOperand visitFNEG(SDNode *N);
256 SDOperand visitFABS(SDNode *N);
257 SDOperand visitBRCOND(SDNode *N);
258 SDOperand visitBR_CC(SDNode *N);
259 SDOperand visitLOAD(SDNode *N);
260 SDOperand visitSTORE(SDNode *N);
261 SDOperand visitINSERT_VECTOR_ELT(SDNode *N);
Evan Chengd7ba7ed2007-10-06 08:19:55 +0000262 SDOperand visitEXTRACT_VECTOR_ELT(SDNode *N);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000263 SDOperand visitBUILD_VECTOR(SDNode *N);
264 SDOperand visitCONCAT_VECTORS(SDNode *N);
265 SDOperand visitVECTOR_SHUFFLE(SDNode *N);
266
267 SDOperand XformToShuffleWithZero(SDNode *N);
268 SDOperand ReassociateOps(unsigned Opc, SDOperand LHS, SDOperand RHS);
269
Chris Lattner91ed3c32007-12-06 07:33:36 +0000270 SDOperand visitShiftByConstant(SDNode *N, unsigned Amt);
271
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000272 bool SimplifySelectOps(SDNode *SELECT, SDOperand LHS, SDOperand RHS);
273 SDOperand SimplifyBinOpWithSameOpcodeHands(SDNode *N);
274 SDOperand SimplifySelect(SDOperand N0, SDOperand N1, SDOperand N2);
275 SDOperand SimplifySelectCC(SDOperand N0, SDOperand N1, SDOperand N2,
276 SDOperand N3, ISD::CondCode CC,
277 bool NotExtCompare = false);
278 SDOperand SimplifySetCC(MVT::ValueType VT, SDOperand N0, SDOperand N1,
279 ISD::CondCode Cond, bool foldBooleans = true);
Dan Gohman6c89ea72007-10-08 17:57:15 +0000280 bool SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp, unsigned HiOp);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000281 SDOperand ConstantFoldBIT_CONVERTofBUILD_VECTOR(SDNode *, MVT::ValueType);
282 SDOperand BuildSDIV(SDNode *N);
283 SDOperand BuildUDIV(SDNode *N);
284 SDNode *MatchRotate(SDOperand LHS, SDOperand RHS);
285 SDOperand ReduceLoadWidth(SDNode *N);
286
Chris Lattnere8671c52007-10-13 06:35:54 +0000287 SDOperand GetDemandedBits(SDOperand V, uint64_t Mask);
288
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000289 /// GatherAllAliases - Walk up chain skipping non-aliasing memory nodes,
290 /// looking for aliasing nodes and adding them to the Aliases vector.
291 void GatherAllAliases(SDNode *N, SDOperand OriginalChain,
292 SmallVector<SDOperand, 8> &Aliases);
293
294 /// isAlias - Return true if there is any possibility that the two addresses
295 /// overlap.
296 bool isAlias(SDOperand Ptr1, int64_t Size1,
297 const Value *SrcValue1, int SrcValueOffset1,
298 SDOperand Ptr2, int64_t Size2,
299 const Value *SrcValue2, int SrcValueOffset2);
300
301 /// FindAliasInfo - Extracts the relevant alias information from the memory
302 /// node. Returns true if the operand was a load.
303 bool FindAliasInfo(SDNode *N,
304 SDOperand &Ptr, int64_t &Size,
305 const Value *&SrcValue, int &SrcValueOffset);
306
307 /// FindBetterChain - Walk up chain skipping non-aliasing memory nodes,
308 /// looking for a better chain (aliasing node.)
309 SDOperand FindBetterChain(SDNode *N, SDOperand Chain);
310
311public:
312 DAGCombiner(SelectionDAG &D, AliasAnalysis &A)
313 : DAG(D),
314 TLI(D.getTargetLoweringInfo()),
315 AfterLegalize(false),
316 AA(A) {}
317
318 /// Run - runs the dag combiner on all nodes in the work list
319 void Run(bool RunningAfterLegalize);
320 };
321}
322
323//===----------------------------------------------------------------------===//
324// TargetLowering::DAGCombinerInfo implementation
325//===----------------------------------------------------------------------===//
326
327void TargetLowering::DAGCombinerInfo::AddToWorklist(SDNode *N) {
328 ((DAGCombiner*)DC)->AddToWorkList(N);
329}
330
331SDOperand TargetLowering::DAGCombinerInfo::
332CombineTo(SDNode *N, const std::vector<SDOperand> &To) {
333 return ((DAGCombiner*)DC)->CombineTo(N, &To[0], To.size());
334}
335
336SDOperand TargetLowering::DAGCombinerInfo::
337CombineTo(SDNode *N, SDOperand Res) {
338 return ((DAGCombiner*)DC)->CombineTo(N, Res);
339}
340
341
342SDOperand TargetLowering::DAGCombinerInfo::
343CombineTo(SDNode *N, SDOperand Res0, SDOperand Res1) {
344 return ((DAGCombiner*)DC)->CombineTo(N, Res0, Res1);
345}
346
347
348//===----------------------------------------------------------------------===//
349// Helper Functions
350//===----------------------------------------------------------------------===//
351
352/// isNegatibleForFree - Return 1 if we can compute the negated form of the
353/// specified expression for the same cost as the expression itself, or 2 if we
354/// can compute the negated form more cheaply than the expression itself.
355static char isNegatibleForFree(SDOperand Op, unsigned Depth = 0) {
Dale Johannesenb89072e2007-10-16 23:38:29 +0000356 // No compile time optimizations on this type.
357 if (Op.getValueType() == MVT::ppcf128)
358 return 0;
359
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000360 // fneg is removable even if it has multiple uses.
361 if (Op.getOpcode() == ISD::FNEG) return 2;
362
363 // Don't allow anything with multiple uses.
364 if (!Op.hasOneUse()) return 0;
365
366 // Don't recurse exponentially.
367 if (Depth > 6) return 0;
368
369 switch (Op.getOpcode()) {
370 default: return false;
371 case ISD::ConstantFP:
372 return 1;
373 case ISD::FADD:
374 // FIXME: determine better conditions for this xform.
375 if (!UnsafeFPMath) return 0;
376
377 // -(A+B) -> -A - B
378 if (char V = isNegatibleForFree(Op.getOperand(0), Depth+1))
379 return V;
380 // -(A+B) -> -B - A
381 return isNegatibleForFree(Op.getOperand(1), Depth+1);
382 case ISD::FSUB:
383 // We can't turn -(A-B) into B-A when we honor signed zeros.
384 if (!UnsafeFPMath) return 0;
385
386 // -(A-B) -> B-A
387 return 1;
388
389 case ISD::FMUL:
390 case ISD::FDIV:
391 if (HonorSignDependentRoundingFPMath()) return 0;
392
393 // -(X*Y) -> (-X * Y) or (X*-Y)
394 if (char V = isNegatibleForFree(Op.getOperand(0), Depth+1))
395 return V;
396
397 return isNegatibleForFree(Op.getOperand(1), Depth+1);
398
399 case ISD::FP_EXTEND:
400 case ISD::FP_ROUND:
401 case ISD::FSIN:
402 return isNegatibleForFree(Op.getOperand(0), Depth+1);
403 }
404}
405
406/// GetNegatedExpression - If isNegatibleForFree returns true, this function
407/// returns the newly negated expression.
408static SDOperand GetNegatedExpression(SDOperand Op, SelectionDAG &DAG,
409 unsigned Depth = 0) {
410 // fneg is removable even if it has multiple uses.
411 if (Op.getOpcode() == ISD::FNEG) return Op.getOperand(0);
412
413 // Don't allow anything with multiple uses.
414 assert(Op.hasOneUse() && "Unknown reuse!");
415
416 assert(Depth <= 6 && "GetNegatedExpression doesn't match isNegatibleForFree");
417 switch (Op.getOpcode()) {
418 default: assert(0 && "Unknown code");
Dale Johannesen7604c1b2007-08-31 23:34:27 +0000419 case ISD::ConstantFP: {
420 APFloat V = cast<ConstantFPSDNode>(Op)->getValueAPF();
421 V.changeSign();
422 return DAG.getConstantFP(V, Op.getValueType());
423 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000424 case ISD::FADD:
425 // FIXME: determine better conditions for this xform.
426 assert(UnsafeFPMath);
427
428 // -(A+B) -> -A - B
429 if (isNegatibleForFree(Op.getOperand(0), Depth+1))
430 return DAG.getNode(ISD::FSUB, Op.getValueType(),
431 GetNegatedExpression(Op.getOperand(0), DAG, Depth+1),
432 Op.getOperand(1));
433 // -(A+B) -> -B - A
434 return DAG.getNode(ISD::FSUB, Op.getValueType(),
435 GetNegatedExpression(Op.getOperand(1), DAG, Depth+1),
436 Op.getOperand(0));
437 case ISD::FSUB:
438 // We can't turn -(A-B) into B-A when we honor signed zeros.
439 assert(UnsafeFPMath);
440
441 // -(0-B) -> B
442 if (ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(Op.getOperand(0)))
Dale Johannesen7604c1b2007-08-31 23:34:27 +0000443 if (N0CFP->getValueAPF().isZero())
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000444 return Op.getOperand(1);
445
446 // -(A-B) -> B-A
447 return DAG.getNode(ISD::FSUB, Op.getValueType(), Op.getOperand(1),
448 Op.getOperand(0));
449
450 case ISD::FMUL:
451 case ISD::FDIV:
452 assert(!HonorSignDependentRoundingFPMath());
453
454 // -(X*Y) -> -X * Y
455 if (isNegatibleForFree(Op.getOperand(0), Depth+1))
456 return DAG.getNode(Op.getOpcode(), Op.getValueType(),
457 GetNegatedExpression(Op.getOperand(0), DAG, Depth+1),
458 Op.getOperand(1));
459
460 // -(X*Y) -> X * -Y
461 return DAG.getNode(Op.getOpcode(), Op.getValueType(),
462 Op.getOperand(0),
463 GetNegatedExpression(Op.getOperand(1), DAG, Depth+1));
464
465 case ISD::FP_EXTEND:
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000466 case ISD::FSIN:
467 return DAG.getNode(Op.getOpcode(), Op.getValueType(),
468 GetNegatedExpression(Op.getOperand(0), DAG, Depth+1));
Chris Lattner5872a362008-01-17 07:00:52 +0000469 case ISD::FP_ROUND:
470 return DAG.getNode(ISD::FP_ROUND, Op.getValueType(),
471 GetNegatedExpression(Op.getOperand(0), DAG, Depth+1),
472 Op.getOperand(1));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000473 }
474}
475
476
477// isSetCCEquivalent - Return true if this node is a setcc, or is a select_cc
478// that selects between the values 1 and 0, making it equivalent to a setcc.
479// Also, set the incoming LHS, RHS, and CC references to the appropriate
480// nodes based on the type of node we are checking. This simplifies life a
481// bit for the callers.
482static bool isSetCCEquivalent(SDOperand N, SDOperand &LHS, SDOperand &RHS,
483 SDOperand &CC) {
484 if (N.getOpcode() == ISD::SETCC) {
485 LHS = N.getOperand(0);
486 RHS = N.getOperand(1);
487 CC = N.getOperand(2);
488 return true;
489 }
490 if (N.getOpcode() == ISD::SELECT_CC &&
491 N.getOperand(2).getOpcode() == ISD::Constant &&
492 N.getOperand(3).getOpcode() == ISD::Constant &&
493 cast<ConstantSDNode>(N.getOperand(2))->getValue() == 1 &&
494 cast<ConstantSDNode>(N.getOperand(3))->isNullValue()) {
495 LHS = N.getOperand(0);
496 RHS = N.getOperand(1);
497 CC = N.getOperand(4);
498 return true;
499 }
500 return false;
501}
502
503// isOneUseSetCC - Return true if this is a SetCC-equivalent operation with only
504// one use. If this is true, it allows the users to invert the operation for
505// free when it is profitable to do so.
506static bool isOneUseSetCC(SDOperand N) {
507 SDOperand N0, N1, N2;
508 if (isSetCCEquivalent(N, N0, N1, N2) && N.Val->hasOneUse())
509 return true;
510 return false;
511}
512
513SDOperand DAGCombiner::ReassociateOps(unsigned Opc, SDOperand N0, SDOperand N1){
514 MVT::ValueType VT = N0.getValueType();
515 // reassoc. (op (op x, c1), y) -> (op (op x, y), c1) iff x+c1 has one use
516 // reassoc. (op (op x, c1), c2) -> (op x, (op c1, c2))
517 if (N0.getOpcode() == Opc && isa<ConstantSDNode>(N0.getOperand(1))) {
518 if (isa<ConstantSDNode>(N1)) {
519 SDOperand OpNode = DAG.getNode(Opc, VT, N0.getOperand(1), N1);
520 AddToWorkList(OpNode.Val);
521 return DAG.getNode(Opc, VT, OpNode, N0.getOperand(0));
522 } else if (N0.hasOneUse()) {
523 SDOperand OpNode = DAG.getNode(Opc, VT, N0.getOperand(0), N1);
524 AddToWorkList(OpNode.Val);
525 return DAG.getNode(Opc, VT, OpNode, N0.getOperand(1));
526 }
527 }
528 // reassoc. (op y, (op x, c1)) -> (op (op x, y), c1) iff x+c1 has one use
529 // reassoc. (op c2, (op x, c1)) -> (op x, (op c1, c2))
530 if (N1.getOpcode() == Opc && isa<ConstantSDNode>(N1.getOperand(1))) {
531 if (isa<ConstantSDNode>(N0)) {
532 SDOperand OpNode = DAG.getNode(Opc, VT, N1.getOperand(1), N0);
533 AddToWorkList(OpNode.Val);
534 return DAG.getNode(Opc, VT, OpNode, N1.getOperand(0));
535 } else if (N1.hasOneUse()) {
536 SDOperand OpNode = DAG.getNode(Opc, VT, N1.getOperand(0), N0);
537 AddToWorkList(OpNode.Val);
538 return DAG.getNode(Opc, VT, OpNode, N1.getOperand(1));
539 }
540 }
541 return SDOperand();
542}
543
544//===----------------------------------------------------------------------===//
545// Main DAG Combiner implementation
546//===----------------------------------------------------------------------===//
547
548void DAGCombiner::Run(bool RunningAfterLegalize) {
549 // set the instance variable, so that the various visit routines may use it.
550 AfterLegalize = RunningAfterLegalize;
551
552 // Add all the dag nodes to the worklist.
553 for (SelectionDAG::allnodes_iterator I = DAG.allnodes_begin(),
554 E = DAG.allnodes_end(); I != E; ++I)
555 WorkList.push_back(I);
556
557 // Create a dummy node (which is not added to allnodes), that adds a reference
558 // to the root node, preventing it from being deleted, and tracking any
559 // changes of the root.
560 HandleSDNode Dummy(DAG.getRoot());
561
562 // The root of the dag may dangle to deleted nodes until the dag combiner is
563 // done. Set it to null to avoid confusion.
564 DAG.setRoot(SDOperand());
565
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000566 // while the worklist isn't empty, inspect the node on the end of it and
567 // try and combine it.
568 while (!WorkList.empty()) {
569 SDNode *N = WorkList.back();
570 WorkList.pop_back();
571
572 // If N has no uses, it is dead. Make sure to revisit all N's operands once
573 // N is deleted from the DAG, since they too may now be dead or may have a
574 // reduced number of uses, allowing other xforms.
575 if (N->use_empty() && N != &Dummy) {
576 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
577 AddToWorkList(N->getOperand(i).Val);
578
579 DAG.DeleteNode(N);
580 continue;
581 }
582
Dan Gohman6c89ea72007-10-08 17:57:15 +0000583 SDOperand RV = combine(N);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000584
Chris Lattner20e53902008-01-25 23:34:24 +0000585 if (RV.Val == 0)
586 continue;
587
588 ++NodesCombined;
589 // If we get back the same node we passed in, rather than a new node or
590 // zero, we know that the node must have defined multiple values and
591 // CombineTo was used. Since CombineTo takes care of the worklist
592 // mechanics for us, we have no work to do in this case.
593 if (RV.Val == N)
594 continue;
595
596 assert(N->getOpcode() != ISD::DELETED_NODE &&
597 RV.Val->getOpcode() != ISD::DELETED_NODE &&
598 "Node was deleted but visit returned new node!");
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000599
Chris Lattner20e53902008-01-25 23:34:24 +0000600 DOUT << "\nReplacing.3 "; DEBUG(N->dump(&DAG));
601 DOUT << "\nWith: "; DEBUG(RV.Val->dump(&DAG));
602 DOUT << '\n';
603 std::vector<SDNode*> NowDead;
604 if (N->getNumValues() == RV.Val->getNumValues())
605 DAG.ReplaceAllUsesWith(N, RV.Val, &NowDead);
606 else {
607 assert(N->getValueType(0) == RV.getValueType() && "Type mismatch");
608 SDOperand OpV = RV;
609 DAG.ReplaceAllUsesWith(N, &OpV, &NowDead);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000610 }
Chris Lattner20e53902008-01-25 23:34:24 +0000611
612 // Push the new node and any users onto the worklist
613 AddToWorkList(RV.Val);
614 AddUsersToWorkList(RV.Val);
615
616 // Add any uses of the old node to the worklist in case this node is the
617 // last one that uses them. They may become dead after this node is
618 // deleted.
619 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
620 AddToWorkList(N->getOperand(i).Val);
621
622 // Nodes can be reintroduced into the worklist. Make sure we do not
623 // process a node that has been replaced.
624 removeFromWorkList(N);
625 for (unsigned i = 0, e = NowDead.size(); i != e; ++i)
626 removeFromWorkList(NowDead[i]);
627
628 // Finally, since the node is now dead, remove it from the graph.
629 DAG.DeleteNode(N);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000630 }
631
632 // If the root changed (e.g. it was a dead load, update the root).
633 DAG.setRoot(Dummy.getValue());
634}
635
636SDOperand DAGCombiner::visit(SDNode *N) {
637 switch(N->getOpcode()) {
638 default: break;
639 case ISD::TokenFactor: return visitTokenFactor(N);
640 case ISD::ADD: return visitADD(N);
641 case ISD::SUB: return visitSUB(N);
642 case ISD::ADDC: return visitADDC(N);
643 case ISD::ADDE: return visitADDE(N);
644 case ISD::MUL: return visitMUL(N);
645 case ISD::SDIV: return visitSDIV(N);
646 case ISD::UDIV: return visitUDIV(N);
647 case ISD::SREM: return visitSREM(N);
648 case ISD::UREM: return visitUREM(N);
649 case ISD::MULHU: return visitMULHU(N);
650 case ISD::MULHS: return visitMULHS(N);
Dan Gohman6c89ea72007-10-08 17:57:15 +0000651 case ISD::SMUL_LOHI: return visitSMUL_LOHI(N);
652 case ISD::UMUL_LOHI: return visitUMUL_LOHI(N);
653 case ISD::SDIVREM: return visitSDIVREM(N);
654 case ISD::UDIVREM: return visitUDIVREM(N);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000655 case ISD::AND: return visitAND(N);
656 case ISD::OR: return visitOR(N);
657 case ISD::XOR: return visitXOR(N);
658 case ISD::SHL: return visitSHL(N);
659 case ISD::SRA: return visitSRA(N);
660 case ISD::SRL: return visitSRL(N);
661 case ISD::CTLZ: return visitCTLZ(N);
662 case ISD::CTTZ: return visitCTTZ(N);
663 case ISD::CTPOP: return visitCTPOP(N);
664 case ISD::SELECT: return visitSELECT(N);
665 case ISD::SELECT_CC: return visitSELECT_CC(N);
666 case ISD::SETCC: return visitSETCC(N);
667 case ISD::SIGN_EXTEND: return visitSIGN_EXTEND(N);
668 case ISD::ZERO_EXTEND: return visitZERO_EXTEND(N);
669 case ISD::ANY_EXTEND: return visitANY_EXTEND(N);
670 case ISD::SIGN_EXTEND_INREG: return visitSIGN_EXTEND_INREG(N);
671 case ISD::TRUNCATE: return visitTRUNCATE(N);
672 case ISD::BIT_CONVERT: return visitBIT_CONVERT(N);
673 case ISD::FADD: return visitFADD(N);
674 case ISD::FSUB: return visitFSUB(N);
675 case ISD::FMUL: return visitFMUL(N);
676 case ISD::FDIV: return visitFDIV(N);
677 case ISD::FREM: return visitFREM(N);
678 case ISD::FCOPYSIGN: return visitFCOPYSIGN(N);
679 case ISD::SINT_TO_FP: return visitSINT_TO_FP(N);
680 case ISD::UINT_TO_FP: return visitUINT_TO_FP(N);
681 case ISD::FP_TO_SINT: return visitFP_TO_SINT(N);
682 case ISD::FP_TO_UINT: return visitFP_TO_UINT(N);
683 case ISD::FP_ROUND: return visitFP_ROUND(N);
684 case ISD::FP_ROUND_INREG: return visitFP_ROUND_INREG(N);
685 case ISD::FP_EXTEND: return visitFP_EXTEND(N);
686 case ISD::FNEG: return visitFNEG(N);
687 case ISD::FABS: return visitFABS(N);
688 case ISD::BRCOND: return visitBRCOND(N);
689 case ISD::BR_CC: return visitBR_CC(N);
690 case ISD::LOAD: return visitLOAD(N);
691 case ISD::STORE: return visitSTORE(N);
692 case ISD::INSERT_VECTOR_ELT: return visitINSERT_VECTOR_ELT(N);
Evan Chengd7ba7ed2007-10-06 08:19:55 +0000693 case ISD::EXTRACT_VECTOR_ELT: return visitEXTRACT_VECTOR_ELT(N);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000694 case ISD::BUILD_VECTOR: return visitBUILD_VECTOR(N);
695 case ISD::CONCAT_VECTORS: return visitCONCAT_VECTORS(N);
696 case ISD::VECTOR_SHUFFLE: return visitVECTOR_SHUFFLE(N);
697 }
698 return SDOperand();
699}
700
Dan Gohman6c89ea72007-10-08 17:57:15 +0000701SDOperand DAGCombiner::combine(SDNode *N) {
702
703 SDOperand RV = visit(N);
704
705 // If nothing happened, try a target-specific DAG combine.
706 if (RV.Val == 0) {
707 assert(N->getOpcode() != ISD::DELETED_NODE &&
708 "Node was deleted but visit returned NULL!");
709
710 if (N->getOpcode() >= ISD::BUILTIN_OP_END ||
711 TLI.hasTargetDAGCombine((ISD::NodeType)N->getOpcode())) {
712
713 // Expose the DAG combiner to the target combiner impls.
714 TargetLowering::DAGCombinerInfo
715 DagCombineInfo(DAG, !AfterLegalize, false, this);
716
717 RV = TLI.PerformDAGCombine(N, DagCombineInfo);
718 }
719 }
720
721 return RV;
722}
723
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000724/// getInputChainForNode - Given a node, return its input chain if it has one,
725/// otherwise return a null sd operand.
726static SDOperand getInputChainForNode(SDNode *N) {
727 if (unsigned NumOps = N->getNumOperands()) {
728 if (N->getOperand(0).getValueType() == MVT::Other)
729 return N->getOperand(0);
730 else if (N->getOperand(NumOps-1).getValueType() == MVT::Other)
731 return N->getOperand(NumOps-1);
732 for (unsigned i = 1; i < NumOps-1; ++i)
733 if (N->getOperand(i).getValueType() == MVT::Other)
734 return N->getOperand(i);
735 }
736 return SDOperand(0, 0);
737}
738
739SDOperand DAGCombiner::visitTokenFactor(SDNode *N) {
740 // If N has two operands, where one has an input chain equal to the other,
741 // the 'other' chain is redundant.
742 if (N->getNumOperands() == 2) {
743 if (getInputChainForNode(N->getOperand(0).Val) == N->getOperand(1))
744 return N->getOperand(0);
745 if (getInputChainForNode(N->getOperand(1).Val) == N->getOperand(0))
746 return N->getOperand(1);
747 }
748
749 SmallVector<SDNode *, 8> TFs; // List of token factors to visit.
750 SmallVector<SDOperand, 8> Ops; // Ops for replacing token factor.
751 SmallPtrSet<SDNode*, 16> SeenOps;
752 bool Changed = false; // If we should replace this token factor.
753
754 // Start out with this token factor.
755 TFs.push_back(N);
756
757 // Iterate through token factors. The TFs grows when new token factors are
758 // encountered.
759 for (unsigned i = 0; i < TFs.size(); ++i) {
760 SDNode *TF = TFs[i];
761
762 // Check each of the operands.
763 for (unsigned i = 0, ie = TF->getNumOperands(); i != ie; ++i) {
764 SDOperand Op = TF->getOperand(i);
765
766 switch (Op.getOpcode()) {
767 case ISD::EntryToken:
768 // Entry tokens don't need to be added to the list. They are
769 // rededundant.
770 Changed = true;
771 break;
772
773 case ISD::TokenFactor:
774 if ((CombinerAA || Op.hasOneUse()) &&
775 std::find(TFs.begin(), TFs.end(), Op.Val) == TFs.end()) {
776 // Queue up for processing.
777 TFs.push_back(Op.Val);
778 // Clean up in case the token factor is removed.
779 AddToWorkList(Op.Val);
780 Changed = true;
781 break;
782 }
783 // Fall thru
784
785 default:
786 // Only add if it isn't already in the list.
787 if (SeenOps.insert(Op.Val))
788 Ops.push_back(Op);
789 else
790 Changed = true;
791 break;
792 }
793 }
794 }
795
796 SDOperand Result;
797
798 // If we've change things around then replace token factor.
799 if (Changed) {
800 if (Ops.size() == 0) {
801 // The entry token is the only possible outcome.
802 Result = DAG.getEntryNode();
803 } else {
804 // New and improved token factor.
805 Result = DAG.getNode(ISD::TokenFactor, MVT::Other, &Ops[0], Ops.size());
806 }
807
808 // Don't add users to work list.
809 return CombineTo(N, Result, false);
810 }
811
812 return Result;
813}
814
815static
816SDOperand combineShlAddConstant(SDOperand N0, SDOperand N1, SelectionDAG &DAG) {
817 MVT::ValueType VT = N0.getValueType();
818 SDOperand N00 = N0.getOperand(0);
819 SDOperand N01 = N0.getOperand(1);
820 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N01);
821 if (N01C && N00.getOpcode() == ISD::ADD && N00.Val->hasOneUse() &&
822 isa<ConstantSDNode>(N00.getOperand(1))) {
823 N0 = DAG.getNode(ISD::ADD, VT,
824 DAG.getNode(ISD::SHL, VT, N00.getOperand(0), N01),
825 DAG.getNode(ISD::SHL, VT, N00.getOperand(1), N01));
826 return DAG.getNode(ISD::ADD, VT, N0, N1);
827 }
828 return SDOperand();
829}
830
831static
832SDOperand combineSelectAndUse(SDNode *N, SDOperand Slct, SDOperand OtherOp,
833 SelectionDAG &DAG) {
834 MVT::ValueType VT = N->getValueType(0);
835 unsigned Opc = N->getOpcode();
836 bool isSlctCC = Slct.getOpcode() == ISD::SELECT_CC;
837 SDOperand LHS = isSlctCC ? Slct.getOperand(2) : Slct.getOperand(1);
838 SDOperand RHS = isSlctCC ? Slct.getOperand(3) : Slct.getOperand(2);
839 ISD::CondCode CC = ISD::SETCC_INVALID;
840 if (isSlctCC)
841 CC = cast<CondCodeSDNode>(Slct.getOperand(4))->get();
842 else {
843 SDOperand CCOp = Slct.getOperand(0);
844 if (CCOp.getOpcode() == ISD::SETCC)
845 CC = cast<CondCodeSDNode>(CCOp.getOperand(2))->get();
846 }
847
848 bool DoXform = false;
849 bool InvCC = false;
850 assert ((Opc == ISD::ADD || (Opc == ISD::SUB && Slct == N->getOperand(1))) &&
851 "Bad input!");
852 if (LHS.getOpcode() == ISD::Constant &&
853 cast<ConstantSDNode>(LHS)->isNullValue())
854 DoXform = true;
855 else if (CC != ISD::SETCC_INVALID &&
856 RHS.getOpcode() == ISD::Constant &&
857 cast<ConstantSDNode>(RHS)->isNullValue()) {
858 std::swap(LHS, RHS);
Chris Lattner667f9c12008-01-17 07:20:38 +0000859 SDOperand Op0 = Slct.getOperand(0);
860 bool isInt = MVT::isInteger(isSlctCC ? Op0.getValueType()
861 : Op0.getOperand(0).getValueType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000862 CC = ISD::getSetCCInverse(CC, isInt);
863 DoXform = true;
864 InvCC = true;
865 }
866
867 if (DoXform) {
868 SDOperand Result = DAG.getNode(Opc, VT, OtherOp, RHS);
869 if (isSlctCC)
870 return DAG.getSelectCC(OtherOp, Result,
871 Slct.getOperand(0), Slct.getOperand(1), CC);
872 SDOperand CCOp = Slct.getOperand(0);
873 if (InvCC)
874 CCOp = DAG.getSetCC(CCOp.getValueType(), CCOp.getOperand(0),
875 CCOp.getOperand(1), CC);
876 return DAG.getNode(ISD::SELECT, VT, CCOp, OtherOp, Result);
877 }
878 return SDOperand();
879}
880
881SDOperand DAGCombiner::visitADD(SDNode *N) {
882 SDOperand N0 = N->getOperand(0);
883 SDOperand N1 = N->getOperand(1);
884 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
885 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
886 MVT::ValueType VT = N0.getValueType();
887
888 // fold vector ops
889 if (MVT::isVector(VT)) {
890 SDOperand FoldedVOp = SimplifyVBinOp(N);
891 if (FoldedVOp.Val) return FoldedVOp;
892 }
893
894 // fold (add x, undef) -> undef
895 if (N0.getOpcode() == ISD::UNDEF)
896 return N0;
897 if (N1.getOpcode() == ISD::UNDEF)
898 return N1;
899 // fold (add c1, c2) -> c1+c2
900 if (N0C && N1C)
901 return DAG.getNode(ISD::ADD, VT, N0, N1);
902 // canonicalize constant to RHS
903 if (N0C && !N1C)
904 return DAG.getNode(ISD::ADD, VT, N1, N0);
905 // fold (add x, 0) -> x
906 if (N1C && N1C->isNullValue())
907 return N0;
908 // fold ((c1-A)+c2) -> (c1+c2)-A
909 if (N1C && N0.getOpcode() == ISD::SUB)
910 if (ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getOperand(0)))
911 return DAG.getNode(ISD::SUB, VT,
912 DAG.getConstant(N1C->getValue()+N0C->getValue(), VT),
913 N0.getOperand(1));
914 // reassociate add
915 SDOperand RADD = ReassociateOps(ISD::ADD, N0, N1);
916 if (RADD.Val != 0)
917 return RADD;
918 // fold ((0-A) + B) -> B-A
919 if (N0.getOpcode() == ISD::SUB && isa<ConstantSDNode>(N0.getOperand(0)) &&
920 cast<ConstantSDNode>(N0.getOperand(0))->isNullValue())
921 return DAG.getNode(ISD::SUB, VT, N1, N0.getOperand(1));
922 // fold (A + (0-B)) -> A-B
923 if (N1.getOpcode() == ISD::SUB && isa<ConstantSDNode>(N1.getOperand(0)) &&
924 cast<ConstantSDNode>(N1.getOperand(0))->isNullValue())
925 return DAG.getNode(ISD::SUB, VT, N0, N1.getOperand(1));
926 // fold (A+(B-A)) -> B
927 if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(1))
928 return N1.getOperand(0);
929
930 if (!MVT::isVector(VT) && SimplifyDemandedBits(SDOperand(N, 0)))
931 return SDOperand(N, 0);
932
933 // fold (a+b) -> (a|b) iff a and b share no bits.
934 if (MVT::isInteger(VT) && !MVT::isVector(VT)) {
935 uint64_t LHSZero, LHSOne;
936 uint64_t RHSZero, RHSOne;
937 uint64_t Mask = MVT::getIntVTBitMask(VT);
938 DAG.ComputeMaskedBits(N0, Mask, LHSZero, LHSOne);
939 if (LHSZero) {
940 DAG.ComputeMaskedBits(N1, Mask, RHSZero, RHSOne);
941
942 // If all possibly-set bits on the LHS are clear on the RHS, return an OR.
943 // If all possibly-set bits on the RHS are clear on the LHS, return an OR.
944 if ((RHSZero & (~LHSZero & Mask)) == (~LHSZero & Mask) ||
945 (LHSZero & (~RHSZero & Mask)) == (~RHSZero & Mask))
946 return DAG.getNode(ISD::OR, VT, N0, N1);
947 }
948 }
949
950 // fold (add (shl (add x, c1), c2), ) -> (add (add (shl x, c2), c1<<c2), )
951 if (N0.getOpcode() == ISD::SHL && N0.Val->hasOneUse()) {
952 SDOperand Result = combineShlAddConstant(N0, N1, DAG);
953 if (Result.Val) return Result;
954 }
955 if (N1.getOpcode() == ISD::SHL && N1.Val->hasOneUse()) {
956 SDOperand Result = combineShlAddConstant(N1, N0, DAG);
957 if (Result.Val) return Result;
958 }
959
960 // fold (add (select cc, 0, c), x) -> (select cc, x, (add, x, c))
961 if (N0.getOpcode() == ISD::SELECT && N0.Val->hasOneUse()) {
962 SDOperand Result = combineSelectAndUse(N, N0, N1, DAG);
963 if (Result.Val) return Result;
964 }
965 if (N1.getOpcode() == ISD::SELECT && N1.Val->hasOneUse()) {
966 SDOperand Result = combineSelectAndUse(N, N1, N0, DAG);
967 if (Result.Val) return Result;
968 }
969
970 return SDOperand();
971}
972
973SDOperand DAGCombiner::visitADDC(SDNode *N) {
974 SDOperand N0 = N->getOperand(0);
975 SDOperand N1 = N->getOperand(1);
976 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
977 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
978 MVT::ValueType VT = N0.getValueType();
979
980 // If the flag result is dead, turn this into an ADD.
981 if (N->hasNUsesOfValue(0, 1))
982 return CombineTo(N, DAG.getNode(ISD::ADD, VT, N1, N0),
983 DAG.getNode(ISD::CARRY_FALSE, MVT::Flag));
984
985 // canonicalize constant to RHS.
986 if (N0C && !N1C) {
987 SDOperand Ops[] = { N1, N0 };
988 return DAG.getNode(ISD::ADDC, N->getVTList(), Ops, 2);
989 }
990
991 // fold (addc x, 0) -> x + no carry out
992 if (N1C && N1C->isNullValue())
993 return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE, MVT::Flag));
994
995 // fold (addc a, b) -> (or a, b), CARRY_FALSE iff a and b share no bits.
996 uint64_t LHSZero, LHSOne;
997 uint64_t RHSZero, RHSOne;
998 uint64_t Mask = MVT::getIntVTBitMask(VT);
999 DAG.ComputeMaskedBits(N0, Mask, LHSZero, LHSOne);
1000 if (LHSZero) {
1001 DAG.ComputeMaskedBits(N1, Mask, RHSZero, RHSOne);
1002
1003 // If all possibly-set bits on the LHS are clear on the RHS, return an OR.
1004 // If all possibly-set bits on the RHS are clear on the LHS, return an OR.
1005 if ((RHSZero & (~LHSZero & Mask)) == (~LHSZero & Mask) ||
1006 (LHSZero & (~RHSZero & Mask)) == (~RHSZero & Mask))
1007 return CombineTo(N, DAG.getNode(ISD::OR, VT, N0, N1),
1008 DAG.getNode(ISD::CARRY_FALSE, MVT::Flag));
1009 }
1010
1011 return SDOperand();
1012}
1013
1014SDOperand DAGCombiner::visitADDE(SDNode *N) {
1015 SDOperand N0 = N->getOperand(0);
1016 SDOperand N1 = N->getOperand(1);
1017 SDOperand CarryIn = N->getOperand(2);
1018 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1019 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1020 //MVT::ValueType VT = N0.getValueType();
1021
1022 // canonicalize constant to RHS
1023 if (N0C && !N1C) {
1024 SDOperand Ops[] = { N1, N0, CarryIn };
1025 return DAG.getNode(ISD::ADDE, N->getVTList(), Ops, 3);
1026 }
1027
1028 // fold (adde x, y, false) -> (addc x, y)
1029 if (CarryIn.getOpcode() == ISD::CARRY_FALSE) {
1030 SDOperand Ops[] = { N1, N0 };
1031 return DAG.getNode(ISD::ADDC, N->getVTList(), Ops, 2);
1032 }
1033
1034 return SDOperand();
1035}
1036
1037
1038
1039SDOperand DAGCombiner::visitSUB(SDNode *N) {
1040 SDOperand N0 = N->getOperand(0);
1041 SDOperand N1 = N->getOperand(1);
1042 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.Val);
1043 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.Val);
1044 MVT::ValueType VT = N0.getValueType();
1045
1046 // fold vector ops
1047 if (MVT::isVector(VT)) {
1048 SDOperand FoldedVOp = SimplifyVBinOp(N);
1049 if (FoldedVOp.Val) return FoldedVOp;
1050 }
1051
1052 // fold (sub x, x) -> 0
1053 if (N0 == N1)
1054 return DAG.getConstant(0, N->getValueType(0));
1055 // fold (sub c1, c2) -> c1-c2
1056 if (N0C && N1C)
1057 return DAG.getNode(ISD::SUB, VT, N0, N1);
1058 // fold (sub x, c) -> (add x, -c)
1059 if (N1C)
1060 return DAG.getNode(ISD::ADD, VT, N0, DAG.getConstant(-N1C->getValue(), VT));
1061 // fold (A+B)-A -> B
1062 if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1)
1063 return N0.getOperand(1);
1064 // fold (A+B)-B -> A
1065 if (N0.getOpcode() == ISD::ADD && N0.getOperand(1) == N1)
1066 return N0.getOperand(0);
1067 // fold (sub x, (select cc, 0, c)) -> (select cc, x, (sub, x, c))
1068 if (N1.getOpcode() == ISD::SELECT && N1.Val->hasOneUse()) {
1069 SDOperand Result = combineSelectAndUse(N, N1, N0, DAG);
1070 if (Result.Val) return Result;
1071 }
1072 // If either operand of a sub is undef, the result is undef
1073 if (N0.getOpcode() == ISD::UNDEF)
1074 return N0;
1075 if (N1.getOpcode() == ISD::UNDEF)
1076 return N1;
1077
1078 return SDOperand();
1079}
1080
1081SDOperand DAGCombiner::visitMUL(SDNode *N) {
1082 SDOperand N0 = N->getOperand(0);
1083 SDOperand N1 = N->getOperand(1);
1084 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1085 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1086 MVT::ValueType VT = N0.getValueType();
1087
1088 // fold vector ops
1089 if (MVT::isVector(VT)) {
1090 SDOperand FoldedVOp = SimplifyVBinOp(N);
1091 if (FoldedVOp.Val) return FoldedVOp;
1092 }
1093
1094 // fold (mul x, undef) -> 0
1095 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
1096 return DAG.getConstant(0, VT);
1097 // fold (mul c1, c2) -> c1*c2
1098 if (N0C && N1C)
1099 return DAG.getNode(ISD::MUL, VT, N0, N1);
1100 // canonicalize constant to RHS
1101 if (N0C && !N1C)
1102 return DAG.getNode(ISD::MUL, VT, N1, N0);
1103 // fold (mul x, 0) -> 0
1104 if (N1C && N1C->isNullValue())
1105 return N1;
1106 // fold (mul x, -1) -> 0-x
1107 if (N1C && N1C->isAllOnesValue())
1108 return DAG.getNode(ISD::SUB, VT, DAG.getConstant(0, VT), N0);
1109 // fold (mul x, (1 << c)) -> x << c
1110 if (N1C && isPowerOf2_64(N1C->getValue()))
1111 return DAG.getNode(ISD::SHL, VT, N0,
1112 DAG.getConstant(Log2_64(N1C->getValue()),
1113 TLI.getShiftAmountTy()));
1114 // fold (mul x, -(1 << c)) -> -(x << c) or (-x) << c
1115 if (N1C && isPowerOf2_64(-N1C->getSignExtended())) {
1116 // FIXME: If the input is something that is easily negated (e.g. a
1117 // single-use add), we should put the negate there.
1118 return DAG.getNode(ISD::SUB, VT, DAG.getConstant(0, VT),
1119 DAG.getNode(ISD::SHL, VT, N0,
1120 DAG.getConstant(Log2_64(-N1C->getSignExtended()),
1121 TLI.getShiftAmountTy())));
1122 }
1123
1124 // (mul (shl X, c1), c2) -> (mul X, c2 << c1)
1125 if (N1C && N0.getOpcode() == ISD::SHL &&
1126 isa<ConstantSDNode>(N0.getOperand(1))) {
1127 SDOperand C3 = DAG.getNode(ISD::SHL, VT, N1, N0.getOperand(1));
1128 AddToWorkList(C3.Val);
1129 return DAG.getNode(ISD::MUL, VT, N0.getOperand(0), C3);
1130 }
1131
1132 // Change (mul (shl X, C), Y) -> (shl (mul X, Y), C) when the shift has one
1133 // use.
1134 {
1135 SDOperand Sh(0,0), Y(0,0);
1136 // Check for both (mul (shl X, C), Y) and (mul Y, (shl X, C)).
1137 if (N0.getOpcode() == ISD::SHL && isa<ConstantSDNode>(N0.getOperand(1)) &&
1138 N0.Val->hasOneUse()) {
1139 Sh = N0; Y = N1;
1140 } else if (N1.getOpcode() == ISD::SHL &&
1141 isa<ConstantSDNode>(N1.getOperand(1)) && N1.Val->hasOneUse()) {
1142 Sh = N1; Y = N0;
1143 }
1144 if (Sh.Val) {
1145 SDOperand Mul = DAG.getNode(ISD::MUL, VT, Sh.getOperand(0), Y);
1146 return DAG.getNode(ISD::SHL, VT, Mul, Sh.getOperand(1));
1147 }
1148 }
1149 // fold (mul (add x, c1), c2) -> (add (mul x, c2), c1*c2)
1150 if (N1C && N0.getOpcode() == ISD::ADD && N0.Val->hasOneUse() &&
1151 isa<ConstantSDNode>(N0.getOperand(1))) {
1152 return DAG.getNode(ISD::ADD, VT,
1153 DAG.getNode(ISD::MUL, VT, N0.getOperand(0), N1),
1154 DAG.getNode(ISD::MUL, VT, N0.getOperand(1), N1));
1155 }
1156
1157 // reassociate mul
1158 SDOperand RMUL = ReassociateOps(ISD::MUL, N0, N1);
1159 if (RMUL.Val != 0)
1160 return RMUL;
1161
1162 return SDOperand();
1163}
1164
1165SDOperand DAGCombiner::visitSDIV(SDNode *N) {
1166 SDOperand N0 = N->getOperand(0);
1167 SDOperand N1 = N->getOperand(1);
1168 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.Val);
1169 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.Val);
1170 MVT::ValueType VT = N->getValueType(0);
1171
1172 // fold vector ops
1173 if (MVT::isVector(VT)) {
1174 SDOperand FoldedVOp = SimplifyVBinOp(N);
1175 if (FoldedVOp.Val) return FoldedVOp;
1176 }
1177
1178 // fold (sdiv c1, c2) -> c1/c2
1179 if (N0C && N1C && !N1C->isNullValue())
1180 return DAG.getNode(ISD::SDIV, VT, N0, N1);
1181 // fold (sdiv X, 1) -> X
1182 if (N1C && N1C->getSignExtended() == 1LL)
1183 return N0;
1184 // fold (sdiv X, -1) -> 0-X
1185 if (N1C && N1C->isAllOnesValue())
1186 return DAG.getNode(ISD::SUB, VT, DAG.getConstant(0, VT), N0);
1187 // If we know the sign bits of both operands are zero, strength reduce to a
1188 // udiv instead. Handles (X&15) /s 4 -> X&15 >> 2
1189 uint64_t SignBit = 1ULL << (MVT::getSizeInBits(VT)-1);
1190 if (DAG.MaskedValueIsZero(N1, SignBit) &&
1191 DAG.MaskedValueIsZero(N0, SignBit))
1192 return DAG.getNode(ISD::UDIV, N1.getValueType(), N0, N1);
1193 // fold (sdiv X, pow2) -> simple ops after legalize
1194 if (N1C && N1C->getValue() && !TLI.isIntDivCheap() &&
1195 (isPowerOf2_64(N1C->getSignExtended()) ||
1196 isPowerOf2_64(-N1C->getSignExtended()))) {
1197 // If dividing by powers of two is cheap, then don't perform the following
1198 // fold.
1199 if (TLI.isPow2DivCheap())
1200 return SDOperand();
1201 int64_t pow2 = N1C->getSignExtended();
1202 int64_t abs2 = pow2 > 0 ? pow2 : -pow2;
1203 unsigned lg2 = Log2_64(abs2);
1204 // Splat the sign bit into the register
1205 SDOperand SGN = DAG.getNode(ISD::SRA, VT, N0,
1206 DAG.getConstant(MVT::getSizeInBits(VT)-1,
1207 TLI.getShiftAmountTy()));
1208 AddToWorkList(SGN.Val);
1209 // Add (N0 < 0) ? abs2 - 1 : 0;
1210 SDOperand SRL = DAG.getNode(ISD::SRL, VT, SGN,
1211 DAG.getConstant(MVT::getSizeInBits(VT)-lg2,
1212 TLI.getShiftAmountTy()));
1213 SDOperand ADD = DAG.getNode(ISD::ADD, VT, N0, SRL);
1214 AddToWorkList(SRL.Val);
1215 AddToWorkList(ADD.Val); // Divide by pow2
1216 SDOperand SRA = DAG.getNode(ISD::SRA, VT, ADD,
1217 DAG.getConstant(lg2, TLI.getShiftAmountTy()));
1218 // If we're dividing by a positive value, we're done. Otherwise, we must
1219 // negate the result.
1220 if (pow2 > 0)
1221 return SRA;
1222 AddToWorkList(SRA.Val);
1223 return DAG.getNode(ISD::SUB, VT, DAG.getConstant(0, VT), SRA);
1224 }
1225 // if integer divide is expensive and we satisfy the requirements, emit an
1226 // alternate sequence.
1227 if (N1C && (N1C->getSignExtended() < -1 || N1C->getSignExtended() > 1) &&
1228 !TLI.isIntDivCheap()) {
1229 SDOperand Op = BuildSDIV(N);
1230 if (Op.Val) return Op;
1231 }
1232
1233 // undef / X -> 0
1234 if (N0.getOpcode() == ISD::UNDEF)
1235 return DAG.getConstant(0, VT);
1236 // X / undef -> undef
1237 if (N1.getOpcode() == ISD::UNDEF)
1238 return N1;
1239
1240 return SDOperand();
1241}
1242
1243SDOperand DAGCombiner::visitUDIV(SDNode *N) {
1244 SDOperand N0 = N->getOperand(0);
1245 SDOperand N1 = N->getOperand(1);
1246 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.Val);
1247 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.Val);
1248 MVT::ValueType VT = N->getValueType(0);
1249
1250 // fold vector ops
1251 if (MVT::isVector(VT)) {
1252 SDOperand FoldedVOp = SimplifyVBinOp(N);
1253 if (FoldedVOp.Val) return FoldedVOp;
1254 }
1255
1256 // fold (udiv c1, c2) -> c1/c2
1257 if (N0C && N1C && !N1C->isNullValue())
1258 return DAG.getNode(ISD::UDIV, VT, N0, N1);
1259 // fold (udiv x, (1 << c)) -> x >>u c
1260 if (N1C && isPowerOf2_64(N1C->getValue()))
1261 return DAG.getNode(ISD::SRL, VT, N0,
1262 DAG.getConstant(Log2_64(N1C->getValue()),
1263 TLI.getShiftAmountTy()));
1264 // fold (udiv x, (shl c, y)) -> x >>u (log2(c)+y) iff c is power of 2
1265 if (N1.getOpcode() == ISD::SHL) {
1266 if (ConstantSDNode *SHC = dyn_cast<ConstantSDNode>(N1.getOperand(0))) {
1267 if (isPowerOf2_64(SHC->getValue())) {
1268 MVT::ValueType ADDVT = N1.getOperand(1).getValueType();
1269 SDOperand Add = DAG.getNode(ISD::ADD, ADDVT, N1.getOperand(1),
1270 DAG.getConstant(Log2_64(SHC->getValue()),
1271 ADDVT));
1272 AddToWorkList(Add.Val);
1273 return DAG.getNode(ISD::SRL, VT, N0, Add);
1274 }
1275 }
1276 }
1277 // fold (udiv x, c) -> alternate
1278 if (N1C && N1C->getValue() && !TLI.isIntDivCheap()) {
1279 SDOperand Op = BuildUDIV(N);
1280 if (Op.Val) return Op;
1281 }
1282
1283 // undef / X -> 0
1284 if (N0.getOpcode() == ISD::UNDEF)
1285 return DAG.getConstant(0, VT);
1286 // X / undef -> undef
1287 if (N1.getOpcode() == ISD::UNDEF)
1288 return N1;
1289
1290 return SDOperand();
1291}
1292
1293SDOperand DAGCombiner::visitSREM(SDNode *N) {
1294 SDOperand N0 = N->getOperand(0);
1295 SDOperand N1 = N->getOperand(1);
1296 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1297 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1298 MVT::ValueType VT = N->getValueType(0);
1299
1300 // fold (srem c1, c2) -> c1%c2
1301 if (N0C && N1C && !N1C->isNullValue())
1302 return DAG.getNode(ISD::SREM, VT, N0, N1);
1303 // If we know the sign bits of both operands are zero, strength reduce to a
1304 // urem instead. Handles (X & 0x0FFFFFFF) %s 16 -> X&15
1305 uint64_t SignBit = 1ULL << (MVT::getSizeInBits(VT)-1);
1306 if (DAG.MaskedValueIsZero(N1, SignBit) &&
1307 DAG.MaskedValueIsZero(N0, SignBit))
1308 return DAG.getNode(ISD::UREM, VT, N0, N1);
1309
Dan Gohmanfdb31f12007-11-26 23:46:11 +00001310 // If X/C can be simplified by the division-by-constant logic, lower
1311 // X%C to the equivalent of X-X/C*C.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001312 if (N1C && !N1C->isNullValue()) {
1313 SDOperand Div = DAG.getNode(ISD::SDIV, VT, N0, N1);
Dan Gohmanfdb31f12007-11-26 23:46:11 +00001314 SDOperand OptimizedDiv = combine(Div.Val);
1315 if (OptimizedDiv.Val && OptimizedDiv.Val != Div.Val) {
1316 SDOperand Mul = DAG.getNode(ISD::MUL, VT, OptimizedDiv, N1);
1317 SDOperand Sub = DAG.getNode(ISD::SUB, VT, N0, Mul);
1318 AddToWorkList(Mul.Val);
1319 return Sub;
1320 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001321 }
1322
1323 // undef % X -> 0
1324 if (N0.getOpcode() == ISD::UNDEF)
1325 return DAG.getConstant(0, VT);
1326 // X % undef -> undef
1327 if (N1.getOpcode() == ISD::UNDEF)
1328 return N1;
1329
1330 return SDOperand();
1331}
1332
1333SDOperand DAGCombiner::visitUREM(SDNode *N) {
1334 SDOperand N0 = N->getOperand(0);
1335 SDOperand N1 = N->getOperand(1);
1336 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1337 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1338 MVT::ValueType VT = N->getValueType(0);
1339
1340 // fold (urem c1, c2) -> c1%c2
1341 if (N0C && N1C && !N1C->isNullValue())
1342 return DAG.getNode(ISD::UREM, VT, N0, N1);
1343 // fold (urem x, pow2) -> (and x, pow2-1)
1344 if (N1C && !N1C->isNullValue() && isPowerOf2_64(N1C->getValue()))
1345 return DAG.getNode(ISD::AND, VT, N0, DAG.getConstant(N1C->getValue()-1,VT));
1346 // fold (urem x, (shl pow2, y)) -> (and x, (add (shl pow2, y), -1))
1347 if (N1.getOpcode() == ISD::SHL) {
1348 if (ConstantSDNode *SHC = dyn_cast<ConstantSDNode>(N1.getOperand(0))) {
1349 if (isPowerOf2_64(SHC->getValue())) {
1350 SDOperand Add = DAG.getNode(ISD::ADD, VT, N1,DAG.getConstant(~0ULL,VT));
1351 AddToWorkList(Add.Val);
1352 return DAG.getNode(ISD::AND, VT, N0, Add);
1353 }
1354 }
1355 }
1356
Dan Gohmanfdb31f12007-11-26 23:46:11 +00001357 // If X/C can be simplified by the division-by-constant logic, lower
1358 // X%C to the equivalent of X-X/C*C.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001359 if (N1C && !N1C->isNullValue()) {
1360 SDOperand Div = DAG.getNode(ISD::UDIV, VT, N0, N1);
Dan Gohmanfdb31f12007-11-26 23:46:11 +00001361 SDOperand OptimizedDiv = combine(Div.Val);
1362 if (OptimizedDiv.Val && OptimizedDiv.Val != Div.Val) {
1363 SDOperand Mul = DAG.getNode(ISD::MUL, VT, OptimizedDiv, N1);
1364 SDOperand Sub = DAG.getNode(ISD::SUB, VT, N0, Mul);
1365 AddToWorkList(Mul.Val);
1366 return Sub;
1367 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001368 }
1369
1370 // undef % X -> 0
1371 if (N0.getOpcode() == ISD::UNDEF)
1372 return DAG.getConstant(0, VT);
1373 // X % undef -> undef
1374 if (N1.getOpcode() == ISD::UNDEF)
1375 return N1;
1376
1377 return SDOperand();
1378}
1379
1380SDOperand DAGCombiner::visitMULHS(SDNode *N) {
1381 SDOperand N0 = N->getOperand(0);
1382 SDOperand N1 = N->getOperand(1);
1383 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1384 MVT::ValueType VT = N->getValueType(0);
1385
1386 // fold (mulhs x, 0) -> 0
1387 if (N1C && N1C->isNullValue())
1388 return N1;
1389 // fold (mulhs x, 1) -> (sra x, size(x)-1)
1390 if (N1C && N1C->getValue() == 1)
1391 return DAG.getNode(ISD::SRA, N0.getValueType(), N0,
1392 DAG.getConstant(MVT::getSizeInBits(N0.getValueType())-1,
1393 TLI.getShiftAmountTy()));
1394 // fold (mulhs x, undef) -> 0
1395 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
1396 return DAG.getConstant(0, VT);
1397
1398 return SDOperand();
1399}
1400
1401SDOperand DAGCombiner::visitMULHU(SDNode *N) {
1402 SDOperand N0 = N->getOperand(0);
1403 SDOperand N1 = N->getOperand(1);
1404 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1405 MVT::ValueType VT = N->getValueType(0);
1406
1407 // fold (mulhu x, 0) -> 0
1408 if (N1C && N1C->isNullValue())
1409 return N1;
1410 // fold (mulhu x, 1) -> 0
1411 if (N1C && N1C->getValue() == 1)
1412 return DAG.getConstant(0, N0.getValueType());
1413 // fold (mulhu x, undef) -> 0
1414 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
1415 return DAG.getConstant(0, VT);
1416
1417 return SDOperand();
1418}
1419
Dan Gohman6c89ea72007-10-08 17:57:15 +00001420/// SimplifyNodeWithTwoResults - Perform optimizations common to nodes that
1421/// compute two values. LoOp and HiOp give the opcodes for the two computations
1422/// that are being performed. Return true if a simplification was made.
1423///
1424bool DAGCombiner::SimplifyNodeWithTwoResults(SDNode *N,
1425 unsigned LoOp, unsigned HiOp) {
Dan Gohman6c89ea72007-10-08 17:57:15 +00001426 // If the high half is not needed, just compute the low half.
Evan Chengddfa8c72007-11-08 09:25:29 +00001427 bool HiExists = N->hasAnyUseOfValue(1);
1428 if (!HiExists &&
Dan Gohman6c89ea72007-10-08 17:57:15 +00001429 (!AfterLegalize ||
1430 TLI.isOperationLegal(LoOp, N->getValueType(0)))) {
1431 DAG.ReplaceAllUsesOfValueWith(SDOperand(N, 0),
1432 DAG.getNode(LoOp, N->getValueType(0),
1433 N->op_begin(),
Chris Lattner8a258202007-10-15 06:10:22 +00001434 N->getNumOperands()));
Dan Gohman6c89ea72007-10-08 17:57:15 +00001435 return true;
1436 }
1437
1438 // If the low half is not needed, just compute the high half.
Evan Chengddfa8c72007-11-08 09:25:29 +00001439 bool LoExists = N->hasAnyUseOfValue(0);
1440 if (!LoExists &&
Dan Gohman6c89ea72007-10-08 17:57:15 +00001441 (!AfterLegalize ||
1442 TLI.isOperationLegal(HiOp, N->getValueType(1)))) {
1443 DAG.ReplaceAllUsesOfValueWith(SDOperand(N, 1),
1444 DAG.getNode(HiOp, N->getValueType(1),
1445 N->op_begin(),
Chris Lattner8a258202007-10-15 06:10:22 +00001446 N->getNumOperands()));
Dan Gohman6c89ea72007-10-08 17:57:15 +00001447 return true;
1448 }
1449
Evan Chengddfa8c72007-11-08 09:25:29 +00001450 // If both halves are used, return as it is.
1451 if (LoExists && HiExists)
1452 return false;
1453
1454 // If the two computed results can be simplified separately, separate them.
1455 bool RetVal = false;
1456 if (LoExists) {
1457 SDOperand Lo = DAG.getNode(LoOp, N->getValueType(0),
1458 N->op_begin(), N->getNumOperands());
1459 SDOperand LoOpt = combine(Lo.Val);
1460 if (LoOpt.Val && LoOpt != Lo &&
1461 TLI.isOperationLegal(LoOpt.getOpcode(), LoOpt.getValueType())) {
1462 RetVal = true;
1463 DAG.ReplaceAllUsesOfValueWith(SDOperand(N, 0), LoOpt);
Evan Cheng72b84d02007-12-19 01:34:38 +00001464 } else
1465 DAG.DeleteNode(Lo.Val);
Dan Gohman6c89ea72007-10-08 17:57:15 +00001466 }
1467
Evan Chengddfa8c72007-11-08 09:25:29 +00001468 if (HiExists) {
1469 SDOperand Hi = DAG.getNode(HiOp, N->getValueType(1),
1470 N->op_begin(), N->getNumOperands());
1471 SDOperand HiOpt = combine(Hi.Val);
1472 if (HiOpt.Val && HiOpt != Hi &&
1473 TLI.isOperationLegal(HiOpt.getOpcode(), HiOpt.getValueType())) {
1474 RetVal = true;
1475 DAG.ReplaceAllUsesOfValueWith(SDOperand(N, 1), HiOpt);
Evan Cheng72b84d02007-12-19 01:34:38 +00001476 } else
1477 DAG.DeleteNode(Hi.Val);
Evan Chengddfa8c72007-11-08 09:25:29 +00001478 }
1479
1480 return RetVal;
Dan Gohman6c89ea72007-10-08 17:57:15 +00001481}
1482
1483SDOperand DAGCombiner::visitSMUL_LOHI(SDNode *N) {
1484
1485 if (SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHS))
1486 return SDOperand();
1487
1488 return SDOperand();
1489}
1490
1491SDOperand DAGCombiner::visitUMUL_LOHI(SDNode *N) {
1492
1493 if (SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHU))
1494 return SDOperand();
1495
1496 return SDOperand();
1497}
1498
1499SDOperand DAGCombiner::visitSDIVREM(SDNode *N) {
1500
1501 if (SimplifyNodeWithTwoResults(N, ISD::SDIV, ISD::SREM))
1502 return SDOperand();
1503
1504 return SDOperand();
1505}
1506
1507SDOperand DAGCombiner::visitUDIVREM(SDNode *N) {
1508
1509 if (SimplifyNodeWithTwoResults(N, ISD::UDIV, ISD::UREM))
1510 return SDOperand();
1511
1512 return SDOperand();
1513}
1514
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001515/// SimplifyBinOpWithSameOpcodeHands - If this is a binary operator with
1516/// two operands of the same opcode, try to simplify it.
1517SDOperand DAGCombiner::SimplifyBinOpWithSameOpcodeHands(SDNode *N) {
1518 SDOperand N0 = N->getOperand(0), N1 = N->getOperand(1);
1519 MVT::ValueType VT = N0.getValueType();
1520 assert(N0.getOpcode() == N1.getOpcode() && "Bad input!");
1521
1522 // For each of OP in AND/OR/XOR:
1523 // fold (OP (zext x), (zext y)) -> (zext (OP x, y))
1524 // fold (OP (sext x), (sext y)) -> (sext (OP x, y))
1525 // fold (OP (aext x), (aext y)) -> (aext (OP x, y))
1526 // fold (OP (trunc x), (trunc y)) -> (trunc (OP x, y))
1527 if ((N0.getOpcode() == ISD::ZERO_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND||
1528 N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::TRUNCATE) &&
1529 N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType()) {
1530 SDOperand ORNode = DAG.getNode(N->getOpcode(),
1531 N0.getOperand(0).getValueType(),
1532 N0.getOperand(0), N1.getOperand(0));
1533 AddToWorkList(ORNode.Val);
1534 return DAG.getNode(N0.getOpcode(), VT, ORNode);
1535 }
1536
1537 // For each of OP in SHL/SRL/SRA/AND...
1538 // fold (and (OP x, z), (OP y, z)) -> (OP (and x, y), z)
1539 // fold (or (OP x, z), (OP y, z)) -> (OP (or x, y), z)
1540 // fold (xor (OP x, z), (OP y, z)) -> (OP (xor x, y), z)
1541 if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL ||
1542 N0.getOpcode() == ISD::SRA || N0.getOpcode() == ISD::AND) &&
1543 N0.getOperand(1) == N1.getOperand(1)) {
1544 SDOperand ORNode = DAG.getNode(N->getOpcode(),
1545 N0.getOperand(0).getValueType(),
1546 N0.getOperand(0), N1.getOperand(0));
1547 AddToWorkList(ORNode.Val);
1548 return DAG.getNode(N0.getOpcode(), VT, ORNode, N0.getOperand(1));
1549 }
1550
1551 return SDOperand();
1552}
1553
1554SDOperand DAGCombiner::visitAND(SDNode *N) {
1555 SDOperand N0 = N->getOperand(0);
1556 SDOperand N1 = N->getOperand(1);
1557 SDOperand LL, LR, RL, RR, CC0, CC1;
1558 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1559 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1560 MVT::ValueType VT = N1.getValueType();
1561
1562 // fold vector ops
1563 if (MVT::isVector(VT)) {
1564 SDOperand FoldedVOp = SimplifyVBinOp(N);
1565 if (FoldedVOp.Val) return FoldedVOp;
1566 }
1567
1568 // fold (and x, undef) -> 0
1569 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
1570 return DAG.getConstant(0, VT);
1571 // fold (and c1, c2) -> c1&c2
1572 if (N0C && N1C)
1573 return DAG.getNode(ISD::AND, VT, N0, N1);
1574 // canonicalize constant to RHS
1575 if (N0C && !N1C)
1576 return DAG.getNode(ISD::AND, VT, N1, N0);
1577 // fold (and x, -1) -> x
1578 if (N1C && N1C->isAllOnesValue())
1579 return N0;
1580 // if (and x, c) is known to be zero, return 0
1581 if (N1C && DAG.MaskedValueIsZero(SDOperand(N, 0), MVT::getIntVTBitMask(VT)))
1582 return DAG.getConstant(0, VT);
1583 // reassociate and
1584 SDOperand RAND = ReassociateOps(ISD::AND, N0, N1);
1585 if (RAND.Val != 0)
1586 return RAND;
1587 // fold (and (or x, 0xFFFF), 0xFF) -> 0xFF
1588 if (N1C && N0.getOpcode() == ISD::OR)
1589 if (ConstantSDNode *ORI = dyn_cast<ConstantSDNode>(N0.getOperand(1)))
1590 if ((ORI->getValue() & N1C->getValue()) == N1C->getValue())
1591 return N1;
1592 // fold (and (any_ext V), c) -> (zero_ext V) if 'and' only clears top bits.
1593 if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
1594 unsigned InMask = MVT::getIntVTBitMask(N0.getOperand(0).getValueType());
1595 if (DAG.MaskedValueIsZero(N0.getOperand(0),
1596 ~N1C->getValue() & InMask)) {
1597 SDOperand Zext = DAG.getNode(ISD::ZERO_EXTEND, N0.getValueType(),
1598 N0.getOperand(0));
1599
1600 // Replace uses of the AND with uses of the Zero extend node.
1601 CombineTo(N, Zext);
1602
1603 // We actually want to replace all uses of the any_extend with the
1604 // zero_extend, to avoid duplicating things. This will later cause this
1605 // AND to be folded.
1606 CombineTo(N0.Val, Zext);
1607 return SDOperand(N, 0); // Return N so it doesn't get rechecked!
1608 }
1609 }
1610 // fold (and (setcc x), (setcc y)) -> (setcc (and x, y))
1611 if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){
1612 ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get();
1613 ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get();
1614
1615 if (LR == RR && isa<ConstantSDNode>(LR) && Op0 == Op1 &&
1616 MVT::isInteger(LL.getValueType())) {
1617 // fold (X == 0) & (Y == 0) -> (X|Y == 0)
1618 if (cast<ConstantSDNode>(LR)->getValue() == 0 && Op1 == ISD::SETEQ) {
1619 SDOperand ORNode = DAG.getNode(ISD::OR, LR.getValueType(), LL, RL);
1620 AddToWorkList(ORNode.Val);
1621 return DAG.getSetCC(VT, ORNode, LR, Op1);
1622 }
1623 // fold (X == -1) & (Y == -1) -> (X&Y == -1)
1624 if (cast<ConstantSDNode>(LR)->isAllOnesValue() && Op1 == ISD::SETEQ) {
1625 SDOperand ANDNode = DAG.getNode(ISD::AND, LR.getValueType(), LL, RL);
1626 AddToWorkList(ANDNode.Val);
1627 return DAG.getSetCC(VT, ANDNode, LR, Op1);
1628 }
1629 // fold (X > -1) & (Y > -1) -> (X|Y > -1)
1630 if (cast<ConstantSDNode>(LR)->isAllOnesValue() && Op1 == ISD::SETGT) {
1631 SDOperand ORNode = DAG.getNode(ISD::OR, LR.getValueType(), LL, RL);
1632 AddToWorkList(ORNode.Val);
1633 return DAG.getSetCC(VT, ORNode, LR, Op1);
1634 }
1635 }
1636 // canonicalize equivalent to ll == rl
1637 if (LL == RR && LR == RL) {
1638 Op1 = ISD::getSetCCSwappedOperands(Op1);
1639 std::swap(RL, RR);
1640 }
1641 if (LL == RL && LR == RR) {
1642 bool isInteger = MVT::isInteger(LL.getValueType());
1643 ISD::CondCode Result = ISD::getSetCCAndOperation(Op0, Op1, isInteger);
1644 if (Result != ISD::SETCC_INVALID)
1645 return DAG.getSetCC(N0.getValueType(), LL, LR, Result);
1646 }
1647 }
1648
1649 // Simplify: and (op x...), (op y...) -> (op (and x, y))
1650 if (N0.getOpcode() == N1.getOpcode()) {
1651 SDOperand Tmp = SimplifyBinOpWithSameOpcodeHands(N);
1652 if (Tmp.Val) return Tmp;
1653 }
1654
1655 // fold (and (sign_extend_inreg x, i16 to i32), 1) -> (and x, 1)
1656 // fold (and (sra)) -> (and (srl)) when possible.
1657 if (!MVT::isVector(VT) &&
1658 SimplifyDemandedBits(SDOperand(N, 0)))
1659 return SDOperand(N, 0);
1660 // fold (zext_inreg (extload x)) -> (zextload x)
1661 if (ISD::isEXTLoad(N0.Val) && ISD::isUNINDEXEDLoad(N0.Val)) {
1662 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
1663 MVT::ValueType EVT = LN0->getLoadedVT();
1664 // If we zero all the possible extended bits, then we can turn this into
1665 // a zextload if we are running before legalize or the operation is legal.
1666 if (DAG.MaskedValueIsZero(N1, ~0ULL << MVT::getSizeInBits(EVT)) &&
1667 (!AfterLegalize || TLI.isLoadXLegal(ISD::ZEXTLOAD, EVT))) {
1668 SDOperand ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, VT, LN0->getChain(),
1669 LN0->getBasePtr(), LN0->getSrcValue(),
1670 LN0->getSrcValueOffset(), EVT,
1671 LN0->isVolatile(),
1672 LN0->getAlignment());
1673 AddToWorkList(N);
1674 CombineTo(N0.Val, ExtLoad, ExtLoad.getValue(1));
1675 return SDOperand(N, 0); // Return N so it doesn't get rechecked!
1676 }
1677 }
1678 // fold (zext_inreg (sextload x)) -> (zextload x) iff load has one use
1679 if (ISD::isSEXTLoad(N0.Val) && ISD::isUNINDEXEDLoad(N0.Val) &&
1680 N0.hasOneUse()) {
1681 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
1682 MVT::ValueType EVT = LN0->getLoadedVT();
1683 // If we zero all the possible extended bits, then we can turn this into
1684 // a zextload if we are running before legalize or the operation is legal.
1685 if (DAG.MaskedValueIsZero(N1, ~0ULL << MVT::getSizeInBits(EVT)) &&
1686 (!AfterLegalize || TLI.isLoadXLegal(ISD::ZEXTLOAD, EVT))) {
1687 SDOperand ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, VT, LN0->getChain(),
1688 LN0->getBasePtr(), LN0->getSrcValue(),
1689 LN0->getSrcValueOffset(), EVT,
1690 LN0->isVolatile(),
1691 LN0->getAlignment());
1692 AddToWorkList(N);
1693 CombineTo(N0.Val, ExtLoad, ExtLoad.getValue(1));
1694 return SDOperand(N, 0); // Return N so it doesn't get rechecked!
1695 }
1696 }
1697
1698 // fold (and (load x), 255) -> (zextload x, i8)
1699 // fold (and (extload x, i16), 255) -> (zextload x, i8)
1700 if (N1C && N0.getOpcode() == ISD::LOAD) {
1701 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
1702 if (LN0->getExtensionType() != ISD::SEXTLOAD &&
Chris Lattner3bc08502008-01-17 19:59:44 +00001703 LN0->isUnindexed() && N0.hasOneUse()) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001704 MVT::ValueType EVT, LoadedVT;
1705 if (N1C->getValue() == 255)
1706 EVT = MVT::i8;
1707 else if (N1C->getValue() == 65535)
1708 EVT = MVT::i16;
1709 else if (N1C->getValue() == ~0U)
1710 EVT = MVT::i32;
1711 else
1712 EVT = MVT::Other;
1713
1714 LoadedVT = LN0->getLoadedVT();
1715 if (EVT != MVT::Other && LoadedVT > EVT &&
1716 (!AfterLegalize || TLI.isLoadXLegal(ISD::ZEXTLOAD, EVT))) {
1717 MVT::ValueType PtrType = N0.getOperand(1).getValueType();
1718 // For big endian targets, we need to add an offset to the pointer to
1719 // load the correct bytes. For little endian systems, we merely need to
1720 // read fewer bytes from the same pointer.
Duncan Sands4f18d4f2007-11-09 08:57:19 +00001721 unsigned LVTStoreBytes = MVT::getStoreSizeInBits(LoadedVT)/8;
1722 unsigned EVTStoreBytes = MVT::getStoreSizeInBits(EVT)/8;
1723 unsigned PtrOff = LVTStoreBytes - EVTStoreBytes;
Duncan Sandsa3691432007-10-28 12:59:45 +00001724 unsigned Alignment = LN0->getAlignment();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001725 SDOperand NewPtr = LN0->getBasePtr();
Duncan Sandsa3691432007-10-28 12:59:45 +00001726 if (!TLI.isLittleEndian()) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001727 NewPtr = DAG.getNode(ISD::ADD, PtrType, NewPtr,
1728 DAG.getConstant(PtrOff, PtrType));
Duncan Sandsa3691432007-10-28 12:59:45 +00001729 Alignment = MinAlign(Alignment, PtrOff);
1730 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001731 AddToWorkList(NewPtr.Val);
1732 SDOperand Load =
1733 DAG.getExtLoad(ISD::ZEXTLOAD, VT, LN0->getChain(), NewPtr,
1734 LN0->getSrcValue(), LN0->getSrcValueOffset(), EVT,
Duncan Sandsa3691432007-10-28 12:59:45 +00001735 LN0->isVolatile(), Alignment);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001736 AddToWorkList(N);
1737 CombineTo(N0.Val, Load, Load.getValue(1));
1738 return SDOperand(N, 0); // Return N so it doesn't get rechecked!
1739 }
1740 }
1741 }
1742
1743 return SDOperand();
1744}
1745
1746SDOperand DAGCombiner::visitOR(SDNode *N) {
1747 SDOperand N0 = N->getOperand(0);
1748 SDOperand N1 = N->getOperand(1);
1749 SDOperand LL, LR, RL, RR, CC0, CC1;
1750 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1751 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1752 MVT::ValueType VT = N1.getValueType();
1753 unsigned OpSizeInBits = MVT::getSizeInBits(VT);
1754
1755 // fold vector ops
1756 if (MVT::isVector(VT)) {
1757 SDOperand FoldedVOp = SimplifyVBinOp(N);
1758 if (FoldedVOp.Val) return FoldedVOp;
1759 }
1760
1761 // fold (or x, undef) -> -1
1762 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
1763 return DAG.getConstant(~0ULL, VT);
1764 // fold (or c1, c2) -> c1|c2
1765 if (N0C && N1C)
1766 return DAG.getNode(ISD::OR, VT, N0, N1);
1767 // canonicalize constant to RHS
1768 if (N0C && !N1C)
1769 return DAG.getNode(ISD::OR, VT, N1, N0);
1770 // fold (or x, 0) -> x
1771 if (N1C && N1C->isNullValue())
1772 return N0;
1773 // fold (or x, -1) -> -1
1774 if (N1C && N1C->isAllOnesValue())
1775 return N1;
1776 // fold (or x, c) -> c iff (x & ~c) == 0
1777 if (N1C &&
1778 DAG.MaskedValueIsZero(N0,~N1C->getValue() & (~0ULL>>(64-OpSizeInBits))))
1779 return N1;
1780 // reassociate or
1781 SDOperand ROR = ReassociateOps(ISD::OR, N0, N1);
1782 if (ROR.Val != 0)
1783 return ROR;
1784 // Canonicalize (or (and X, c1), c2) -> (and (or X, c2), c1|c2)
1785 if (N1C && N0.getOpcode() == ISD::AND && N0.Val->hasOneUse() &&
1786 isa<ConstantSDNode>(N0.getOperand(1))) {
1787 ConstantSDNode *C1 = cast<ConstantSDNode>(N0.getOperand(1));
1788 return DAG.getNode(ISD::AND, VT, DAG.getNode(ISD::OR, VT, N0.getOperand(0),
1789 N1),
1790 DAG.getConstant(N1C->getValue() | C1->getValue(), VT));
1791 }
1792 // fold (or (setcc x), (setcc y)) -> (setcc (or x, y))
1793 if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){
1794 ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get();
1795 ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get();
1796
1797 if (LR == RR && isa<ConstantSDNode>(LR) && Op0 == Op1 &&
1798 MVT::isInteger(LL.getValueType())) {
1799 // fold (X != 0) | (Y != 0) -> (X|Y != 0)
1800 // fold (X < 0) | (Y < 0) -> (X|Y < 0)
1801 if (cast<ConstantSDNode>(LR)->getValue() == 0 &&
1802 (Op1 == ISD::SETNE || Op1 == ISD::SETLT)) {
1803 SDOperand ORNode = DAG.getNode(ISD::OR, LR.getValueType(), LL, RL);
1804 AddToWorkList(ORNode.Val);
1805 return DAG.getSetCC(VT, ORNode, LR, Op1);
1806 }
1807 // fold (X != -1) | (Y != -1) -> (X&Y != -1)
1808 // fold (X > -1) | (Y > -1) -> (X&Y > -1)
1809 if (cast<ConstantSDNode>(LR)->isAllOnesValue() &&
1810 (Op1 == ISD::SETNE || Op1 == ISD::SETGT)) {
1811 SDOperand ANDNode = DAG.getNode(ISD::AND, LR.getValueType(), LL, RL);
1812 AddToWorkList(ANDNode.Val);
1813 return DAG.getSetCC(VT, ANDNode, LR, Op1);
1814 }
1815 }
1816 // canonicalize equivalent to ll == rl
1817 if (LL == RR && LR == RL) {
1818 Op1 = ISD::getSetCCSwappedOperands(Op1);
1819 std::swap(RL, RR);
1820 }
1821 if (LL == RL && LR == RR) {
1822 bool isInteger = MVT::isInteger(LL.getValueType());
1823 ISD::CondCode Result = ISD::getSetCCOrOperation(Op0, Op1, isInteger);
1824 if (Result != ISD::SETCC_INVALID)
1825 return DAG.getSetCC(N0.getValueType(), LL, LR, Result);
1826 }
1827 }
1828
1829 // Simplify: or (op x...), (op y...) -> (op (or x, y))
1830 if (N0.getOpcode() == N1.getOpcode()) {
1831 SDOperand Tmp = SimplifyBinOpWithSameOpcodeHands(N);
1832 if (Tmp.Val) return Tmp;
1833 }
1834
1835 // (X & C1) | (Y & C2) -> (X|Y) & C3 if possible.
1836 if (N0.getOpcode() == ISD::AND &&
1837 N1.getOpcode() == ISD::AND &&
1838 N0.getOperand(1).getOpcode() == ISD::Constant &&
1839 N1.getOperand(1).getOpcode() == ISD::Constant &&
1840 // Don't increase # computations.
1841 (N0.Val->hasOneUse() || N1.Val->hasOneUse())) {
1842 // We can only do this xform if we know that bits from X that are set in C2
1843 // but not in C1 are already zero. Likewise for Y.
1844 uint64_t LHSMask = cast<ConstantSDNode>(N0.getOperand(1))->getValue();
1845 uint64_t RHSMask = cast<ConstantSDNode>(N1.getOperand(1))->getValue();
1846
1847 if (DAG.MaskedValueIsZero(N0.getOperand(0), RHSMask&~LHSMask) &&
1848 DAG.MaskedValueIsZero(N1.getOperand(0), LHSMask&~RHSMask)) {
1849 SDOperand X =DAG.getNode(ISD::OR, VT, N0.getOperand(0), N1.getOperand(0));
1850 return DAG.getNode(ISD::AND, VT, X, DAG.getConstant(LHSMask|RHSMask, VT));
1851 }
1852 }
1853
1854
1855 // See if this is some rotate idiom.
1856 if (SDNode *Rot = MatchRotate(N0, N1))
1857 return SDOperand(Rot, 0);
1858
1859 return SDOperand();
1860}
1861
1862
1863/// MatchRotateHalf - Match "(X shl/srl V1) & V2" where V2 may not be present.
1864static bool MatchRotateHalf(SDOperand Op, SDOperand &Shift, SDOperand &Mask) {
1865 if (Op.getOpcode() == ISD::AND) {
1866 if (isa<ConstantSDNode>(Op.getOperand(1))) {
1867 Mask = Op.getOperand(1);
1868 Op = Op.getOperand(0);
1869 } else {
1870 return false;
1871 }
1872 }
1873
1874 if (Op.getOpcode() == ISD::SRL || Op.getOpcode() == ISD::SHL) {
1875 Shift = Op;
1876 return true;
1877 }
1878 return false;
1879}
1880
1881
1882// MatchRotate - Handle an 'or' of two operands. If this is one of the many
1883// idioms for rotate, and if the target supports rotation instructions, generate
1884// a rot[lr].
1885SDNode *DAGCombiner::MatchRotate(SDOperand LHS, SDOperand RHS) {
1886 // Must be a legal type. Expanded an promoted things won't work with rotates.
1887 MVT::ValueType VT = LHS.getValueType();
1888 if (!TLI.isTypeLegal(VT)) return 0;
1889
1890 // The target must have at least one rotate flavor.
1891 bool HasROTL = TLI.isOperationLegal(ISD::ROTL, VT);
1892 bool HasROTR = TLI.isOperationLegal(ISD::ROTR, VT);
1893 if (!HasROTL && !HasROTR) return 0;
1894
1895 // Match "(X shl/srl V1) & V2" where V2 may not be present.
1896 SDOperand LHSShift; // The shift.
1897 SDOperand LHSMask; // AND value if any.
1898 if (!MatchRotateHalf(LHS, LHSShift, LHSMask))
1899 return 0; // Not part of a rotate.
1900
1901 SDOperand RHSShift; // The shift.
1902 SDOperand RHSMask; // AND value if any.
1903 if (!MatchRotateHalf(RHS, RHSShift, RHSMask))
1904 return 0; // Not part of a rotate.
1905
1906 if (LHSShift.getOperand(0) != RHSShift.getOperand(0))
1907 return 0; // Not shifting the same value.
1908
1909 if (LHSShift.getOpcode() == RHSShift.getOpcode())
1910 return 0; // Shifts must disagree.
1911
1912 // Canonicalize shl to left side in a shl/srl pair.
1913 if (RHSShift.getOpcode() == ISD::SHL) {
1914 std::swap(LHS, RHS);
1915 std::swap(LHSShift, RHSShift);
1916 std::swap(LHSMask , RHSMask );
1917 }
1918
1919 unsigned OpSizeInBits = MVT::getSizeInBits(VT);
1920 SDOperand LHSShiftArg = LHSShift.getOperand(0);
1921 SDOperand LHSShiftAmt = LHSShift.getOperand(1);
1922 SDOperand RHSShiftAmt = RHSShift.getOperand(1);
1923
1924 // fold (or (shl x, C1), (srl x, C2)) -> (rotl x, C1)
1925 // fold (or (shl x, C1), (srl x, C2)) -> (rotr x, C2)
1926 if (LHSShiftAmt.getOpcode() == ISD::Constant &&
1927 RHSShiftAmt.getOpcode() == ISD::Constant) {
1928 uint64_t LShVal = cast<ConstantSDNode>(LHSShiftAmt)->getValue();
1929 uint64_t RShVal = cast<ConstantSDNode>(RHSShiftAmt)->getValue();
1930 if ((LShVal + RShVal) != OpSizeInBits)
1931 return 0;
1932
1933 SDOperand Rot;
1934 if (HasROTL)
1935 Rot = DAG.getNode(ISD::ROTL, VT, LHSShiftArg, LHSShiftAmt);
1936 else
1937 Rot = DAG.getNode(ISD::ROTR, VT, LHSShiftArg, RHSShiftAmt);
1938
1939 // If there is an AND of either shifted operand, apply it to the result.
1940 if (LHSMask.Val || RHSMask.Val) {
1941 uint64_t Mask = MVT::getIntVTBitMask(VT);
1942
1943 if (LHSMask.Val) {
1944 uint64_t RHSBits = (1ULL << LShVal)-1;
1945 Mask &= cast<ConstantSDNode>(LHSMask)->getValue() | RHSBits;
1946 }
1947 if (RHSMask.Val) {
1948 uint64_t LHSBits = ~((1ULL << (OpSizeInBits-RShVal))-1);
1949 Mask &= cast<ConstantSDNode>(RHSMask)->getValue() | LHSBits;
1950 }
1951
1952 Rot = DAG.getNode(ISD::AND, VT, Rot, DAG.getConstant(Mask, VT));
1953 }
1954
1955 return Rot.Val;
1956 }
1957
1958 // If there is a mask here, and we have a variable shift, we can't be sure
1959 // that we're masking out the right stuff.
1960 if (LHSMask.Val || RHSMask.Val)
1961 return 0;
1962
1963 // fold (or (shl x, y), (srl x, (sub 32, y))) -> (rotl x, y)
1964 // fold (or (shl x, y), (srl x, (sub 32, y))) -> (rotr x, (sub 32, y))
1965 if (RHSShiftAmt.getOpcode() == ISD::SUB &&
1966 LHSShiftAmt == RHSShiftAmt.getOperand(1)) {
1967 if (ConstantSDNode *SUBC =
1968 dyn_cast<ConstantSDNode>(RHSShiftAmt.getOperand(0))) {
1969 if (SUBC->getValue() == OpSizeInBits)
1970 if (HasROTL)
1971 return DAG.getNode(ISD::ROTL, VT, LHSShiftArg, LHSShiftAmt).Val;
1972 else
1973 return DAG.getNode(ISD::ROTR, VT, LHSShiftArg, RHSShiftAmt).Val;
1974 }
1975 }
1976
1977 // fold (or (shl x, (sub 32, y)), (srl x, r)) -> (rotr x, y)
1978 // fold (or (shl x, (sub 32, y)), (srl x, r)) -> (rotl x, (sub 32, y))
1979 if (LHSShiftAmt.getOpcode() == ISD::SUB &&
1980 RHSShiftAmt == LHSShiftAmt.getOperand(1)) {
1981 if (ConstantSDNode *SUBC =
1982 dyn_cast<ConstantSDNode>(LHSShiftAmt.getOperand(0))) {
1983 if (SUBC->getValue() == OpSizeInBits)
1984 if (HasROTL)
1985 return DAG.getNode(ISD::ROTL, VT, LHSShiftArg, LHSShiftAmt).Val;
1986 else
1987 return DAG.getNode(ISD::ROTR, VT, LHSShiftArg, RHSShiftAmt).Val;
1988 }
1989 }
1990
1991 // Look for sign/zext/any-extended cases:
1992 if ((LHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND
1993 || LHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND
1994 || LHSShiftAmt.getOpcode() == ISD::ANY_EXTEND) &&
1995 (RHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND
1996 || RHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND
1997 || RHSShiftAmt.getOpcode() == ISD::ANY_EXTEND)) {
1998 SDOperand LExtOp0 = LHSShiftAmt.getOperand(0);
1999 SDOperand RExtOp0 = RHSShiftAmt.getOperand(0);
2000 if (RExtOp0.getOpcode() == ISD::SUB &&
2001 RExtOp0.getOperand(1) == LExtOp0) {
2002 // fold (or (shl x, (*ext y)), (srl x, (*ext (sub 32, y)))) ->
2003 // (rotr x, y)
2004 // fold (or (shl x, (*ext y)), (srl x, (*ext (sub 32, y)))) ->
2005 // (rotl x, (sub 32, y))
2006 if (ConstantSDNode *SUBC = cast<ConstantSDNode>(RExtOp0.getOperand(0))) {
2007 if (SUBC->getValue() == OpSizeInBits) {
2008 if (HasROTL)
2009 return DAG.getNode(ISD::ROTL, VT, LHSShiftArg, LHSShiftAmt).Val;
2010 else
2011 return DAG.getNode(ISD::ROTR, VT, LHSShiftArg, RHSShiftAmt).Val;
2012 }
2013 }
2014 } else if (LExtOp0.getOpcode() == ISD::SUB &&
2015 RExtOp0 == LExtOp0.getOperand(1)) {
2016 // fold (or (shl x, (*ext (sub 32, y))), (srl x, (*ext r))) ->
2017 // (rotl x, y)
2018 // fold (or (shl x, (*ext (sub 32, y))), (srl x, (*ext r))) ->
2019 // (rotr x, (sub 32, y))
2020 if (ConstantSDNode *SUBC = cast<ConstantSDNode>(LExtOp0.getOperand(0))) {
2021 if (SUBC->getValue() == OpSizeInBits) {
2022 if (HasROTL)
2023 return DAG.getNode(ISD::ROTL, VT, LHSShiftArg, RHSShiftAmt).Val;
2024 else
2025 return DAG.getNode(ISD::ROTL, VT, LHSShiftArg, LHSShiftAmt).Val;
2026 }
2027 }
2028 }
2029 }
2030
2031 return 0;
2032}
2033
2034
2035SDOperand DAGCombiner::visitXOR(SDNode *N) {
2036 SDOperand N0 = N->getOperand(0);
2037 SDOperand N1 = N->getOperand(1);
2038 SDOperand LHS, RHS, CC;
2039 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
2040 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2041 MVT::ValueType VT = N0.getValueType();
2042
2043 // fold vector ops
2044 if (MVT::isVector(VT)) {
2045 SDOperand FoldedVOp = SimplifyVBinOp(N);
2046 if (FoldedVOp.Val) return FoldedVOp;
2047 }
2048
2049 // fold (xor x, undef) -> undef
2050 if (N0.getOpcode() == ISD::UNDEF)
2051 return N0;
2052 if (N1.getOpcode() == ISD::UNDEF)
2053 return N1;
2054 // fold (xor c1, c2) -> c1^c2
2055 if (N0C && N1C)
2056 return DAG.getNode(ISD::XOR, VT, N0, N1);
2057 // canonicalize constant to RHS
2058 if (N0C && !N1C)
2059 return DAG.getNode(ISD::XOR, VT, N1, N0);
2060 // fold (xor x, 0) -> x
2061 if (N1C && N1C->isNullValue())
2062 return N0;
2063 // reassociate xor
2064 SDOperand RXOR = ReassociateOps(ISD::XOR, N0, N1);
2065 if (RXOR.Val != 0)
2066 return RXOR;
2067 // fold !(x cc y) -> (x !cc y)
2068 if (N1C && N1C->getValue() == 1 && isSetCCEquivalent(N0, LHS, RHS, CC)) {
2069 bool isInt = MVT::isInteger(LHS.getValueType());
2070 ISD::CondCode NotCC = ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(),
2071 isInt);
2072 if (N0.getOpcode() == ISD::SETCC)
2073 return DAG.getSetCC(VT, LHS, RHS, NotCC);
2074 if (N0.getOpcode() == ISD::SELECT_CC)
2075 return DAG.getSelectCC(LHS, RHS, N0.getOperand(2),N0.getOperand(3),NotCC);
2076 assert(0 && "Unhandled SetCC Equivalent!");
2077 abort();
2078 }
Chris Lattnere27cd502007-09-10 21:39:07 +00002079 // fold (not (zext (setcc x, y))) -> (zext (not (setcc x, y)))
2080 if (N1C && N1C->getValue() == 1 && N0.getOpcode() == ISD::ZERO_EXTEND &&
2081 N0.Val->hasOneUse() && isSetCCEquivalent(N0.getOperand(0), LHS, RHS, CC)){
2082 SDOperand V = N0.getOperand(0);
2083 V = DAG.getNode(ISD::XOR, V.getValueType(), V,
Duncan Sandsbed21472007-10-10 09:54:50 +00002084 DAG.getConstant(1, V.getValueType()));
Chris Lattnere27cd502007-09-10 21:39:07 +00002085 AddToWorkList(V.Val);
2086 return DAG.getNode(ISD::ZERO_EXTEND, VT, V);
2087 }
2088
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002089 // fold !(x or y) -> (!x and !y) iff x or y are setcc
2090 if (N1C && N1C->getValue() == 1 && VT == MVT::i1 &&
2091 (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
2092 SDOperand LHS = N0.getOperand(0), RHS = N0.getOperand(1);
2093 if (isOneUseSetCC(RHS) || isOneUseSetCC(LHS)) {
2094 unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
2095 LHS = DAG.getNode(ISD::XOR, VT, LHS, N1); // RHS = ~LHS
2096 RHS = DAG.getNode(ISD::XOR, VT, RHS, N1); // RHS = ~RHS
2097 AddToWorkList(LHS.Val); AddToWorkList(RHS.Val);
2098 return DAG.getNode(NewOpcode, VT, LHS, RHS);
2099 }
2100 }
2101 // fold !(x or y) -> (!x and !y) iff x or y are constants
2102 if (N1C && N1C->isAllOnesValue() &&
2103 (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
2104 SDOperand LHS = N0.getOperand(0), RHS = N0.getOperand(1);
2105 if (isa<ConstantSDNode>(RHS) || isa<ConstantSDNode>(LHS)) {
2106 unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
2107 LHS = DAG.getNode(ISD::XOR, VT, LHS, N1); // RHS = ~LHS
2108 RHS = DAG.getNode(ISD::XOR, VT, RHS, N1); // RHS = ~RHS
2109 AddToWorkList(LHS.Val); AddToWorkList(RHS.Val);
2110 return DAG.getNode(NewOpcode, VT, LHS, RHS);
2111 }
2112 }
2113 // fold (xor (xor x, c1), c2) -> (xor x, c1^c2)
2114 if (N1C && N0.getOpcode() == ISD::XOR) {
2115 ConstantSDNode *N00C = dyn_cast<ConstantSDNode>(N0.getOperand(0));
2116 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
2117 if (N00C)
2118 return DAG.getNode(ISD::XOR, VT, N0.getOperand(1),
2119 DAG.getConstant(N1C->getValue()^N00C->getValue(), VT));
2120 if (N01C)
2121 return DAG.getNode(ISD::XOR, VT, N0.getOperand(0),
2122 DAG.getConstant(N1C->getValue()^N01C->getValue(), VT));
2123 }
2124 // fold (xor x, x) -> 0
2125 if (N0 == N1) {
2126 if (!MVT::isVector(VT)) {
2127 return DAG.getConstant(0, VT);
2128 } else if (!AfterLegalize || TLI.isOperationLegal(ISD::BUILD_VECTOR, VT)) {
2129 // Produce a vector of zeros.
2130 SDOperand El = DAG.getConstant(0, MVT::getVectorElementType(VT));
2131 std::vector<SDOperand> Ops(MVT::getVectorNumElements(VT), El);
2132 return DAG.getNode(ISD::BUILD_VECTOR, VT, &Ops[0], Ops.size());
2133 }
2134 }
2135
2136 // Simplify: xor (op x...), (op y...) -> (op (xor x, y))
2137 if (N0.getOpcode() == N1.getOpcode()) {
2138 SDOperand Tmp = SimplifyBinOpWithSameOpcodeHands(N);
2139 if (Tmp.Val) return Tmp;
2140 }
2141
2142 // Simplify the expression using non-local knowledge.
2143 if (!MVT::isVector(VT) &&
2144 SimplifyDemandedBits(SDOperand(N, 0)))
2145 return SDOperand(N, 0);
2146
2147 return SDOperand();
2148}
2149
Chris Lattner91ed3c32007-12-06 07:33:36 +00002150/// visitShiftByConstant - Handle transforms common to the three shifts, when
2151/// the shift amount is a constant.
2152SDOperand DAGCombiner::visitShiftByConstant(SDNode *N, unsigned Amt) {
2153 SDNode *LHS = N->getOperand(0).Val;
2154 if (!LHS->hasOneUse()) return SDOperand();
2155
2156 // We want to pull some binops through shifts, so that we have (and (shift))
2157 // instead of (shift (and)), likewise for add, or, xor, etc. This sort of
2158 // thing happens with address calculations, so it's important to canonicalize
2159 // it.
2160 bool HighBitSet = false; // Can we transform this if the high bit is set?
2161
2162 switch (LHS->getOpcode()) {
2163 default: return SDOperand();
2164 case ISD::OR:
2165 case ISD::XOR:
2166 HighBitSet = false; // We can only transform sra if the high bit is clear.
2167 break;
2168 case ISD::AND:
2169 HighBitSet = true; // We can only transform sra if the high bit is set.
2170 break;
2171 case ISD::ADD:
2172 if (N->getOpcode() != ISD::SHL)
2173 return SDOperand(); // only shl(add) not sr[al](add).
2174 HighBitSet = false; // We can only transform sra if the high bit is clear.
2175 break;
2176 }
2177
2178 // We require the RHS of the binop to be a constant as well.
2179 ConstantSDNode *BinOpCst = dyn_cast<ConstantSDNode>(LHS->getOperand(1));
2180 if (!BinOpCst) return SDOperand();
2181
Chris Lattnerdcd19762007-12-06 07:47:55 +00002182
2183 // FIXME: disable this for unless the input to the binop is a shift by a
2184 // constant. If it is not a shift, it pessimizes some common cases like:
2185 //
2186 //void foo(int *X, int i) { X[i & 1235] = 1; }
2187 //int bar(int *X, int i) { return X[i & 255]; }
2188 SDNode *BinOpLHSVal = LHS->getOperand(0).Val;
2189 if ((BinOpLHSVal->getOpcode() != ISD::SHL &&
2190 BinOpLHSVal->getOpcode() != ISD::SRA &&
2191 BinOpLHSVal->getOpcode() != ISD::SRL) ||
2192 !isa<ConstantSDNode>(BinOpLHSVal->getOperand(1)))
2193 return SDOperand();
2194
Chris Lattner91ed3c32007-12-06 07:33:36 +00002195 MVT::ValueType VT = N->getValueType(0);
2196
2197 // If this is a signed shift right, and the high bit is modified
2198 // by the logical operation, do not perform the transformation.
2199 // The highBitSet boolean indicates the value of the high bit of
2200 // the constant which would cause it to be modified for this
2201 // operation.
2202 if (N->getOpcode() == ISD::SRA) {
2203 uint64_t BinOpRHSSign = BinOpCst->getValue() >> MVT::getSizeInBits(VT)-1;
2204 if ((bool)BinOpRHSSign != HighBitSet)
2205 return SDOperand();
2206 }
2207
2208 // Fold the constants, shifting the binop RHS by the shift amount.
2209 SDOperand NewRHS = DAG.getNode(N->getOpcode(), N->getValueType(0),
2210 LHS->getOperand(1), N->getOperand(1));
2211
2212 // Create the new shift.
2213 SDOperand NewShift = DAG.getNode(N->getOpcode(), VT, LHS->getOperand(0),
2214 N->getOperand(1));
2215
2216 // Create the new binop.
2217 return DAG.getNode(LHS->getOpcode(), VT, NewShift, NewRHS);
2218}
2219
2220
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002221SDOperand DAGCombiner::visitSHL(SDNode *N) {
2222 SDOperand N0 = N->getOperand(0);
2223 SDOperand N1 = N->getOperand(1);
2224 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
2225 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2226 MVT::ValueType VT = N0.getValueType();
2227 unsigned OpSizeInBits = MVT::getSizeInBits(VT);
2228
2229 // fold (shl c1, c2) -> c1<<c2
2230 if (N0C && N1C)
2231 return DAG.getNode(ISD::SHL, VT, N0, N1);
2232 // fold (shl 0, x) -> 0
2233 if (N0C && N0C->isNullValue())
2234 return N0;
2235 // fold (shl x, c >= size(x)) -> undef
2236 if (N1C && N1C->getValue() >= OpSizeInBits)
2237 return DAG.getNode(ISD::UNDEF, VT);
2238 // fold (shl x, 0) -> x
2239 if (N1C && N1C->isNullValue())
2240 return N0;
2241 // if (shl x, c) is known to be zero, return 0
2242 if (DAG.MaskedValueIsZero(SDOperand(N, 0), MVT::getIntVTBitMask(VT)))
2243 return DAG.getConstant(0, VT);
2244 if (N1C && SimplifyDemandedBits(SDOperand(N, 0)))
2245 return SDOperand(N, 0);
2246 // fold (shl (shl x, c1), c2) -> 0 or (shl x, c1+c2)
2247 if (N1C && N0.getOpcode() == ISD::SHL &&
2248 N0.getOperand(1).getOpcode() == ISD::Constant) {
2249 uint64_t c1 = cast<ConstantSDNode>(N0.getOperand(1))->getValue();
2250 uint64_t c2 = N1C->getValue();
2251 if (c1 + c2 > OpSizeInBits)
2252 return DAG.getConstant(0, VT);
2253 return DAG.getNode(ISD::SHL, VT, N0.getOperand(0),
2254 DAG.getConstant(c1 + c2, N1.getValueType()));
2255 }
2256 // fold (shl (srl x, c1), c2) -> (shl (and x, -1 << c1), c2-c1) or
2257 // (srl (and x, -1 << c1), c1-c2)
2258 if (N1C && N0.getOpcode() == ISD::SRL &&
2259 N0.getOperand(1).getOpcode() == ISD::Constant) {
2260 uint64_t c1 = cast<ConstantSDNode>(N0.getOperand(1))->getValue();
2261 uint64_t c2 = N1C->getValue();
2262 SDOperand Mask = DAG.getNode(ISD::AND, VT, N0.getOperand(0),
2263 DAG.getConstant(~0ULL << c1, VT));
2264 if (c2 > c1)
2265 return DAG.getNode(ISD::SHL, VT, Mask,
2266 DAG.getConstant(c2-c1, N1.getValueType()));
2267 else
2268 return DAG.getNode(ISD::SRL, VT, Mask,
2269 DAG.getConstant(c1-c2, N1.getValueType()));
2270 }
2271 // fold (shl (sra x, c1), c1) -> (and x, -1 << c1)
2272 if (N1C && N0.getOpcode() == ISD::SRA && N1 == N0.getOperand(1))
2273 return DAG.getNode(ISD::AND, VT, N0.getOperand(0),
2274 DAG.getConstant(~0ULL << N1C->getValue(), VT));
Chris Lattner91ed3c32007-12-06 07:33:36 +00002275
2276 return N1C ? visitShiftByConstant(N, N1C->getValue()) : SDOperand();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002277}
2278
2279SDOperand DAGCombiner::visitSRA(SDNode *N) {
2280 SDOperand N0 = N->getOperand(0);
2281 SDOperand N1 = N->getOperand(1);
2282 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
2283 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2284 MVT::ValueType VT = N0.getValueType();
2285
2286 // fold (sra c1, c2) -> c1>>c2
2287 if (N0C && N1C)
2288 return DAG.getNode(ISD::SRA, VT, N0, N1);
2289 // fold (sra 0, x) -> 0
2290 if (N0C && N0C->isNullValue())
2291 return N0;
2292 // fold (sra -1, x) -> -1
2293 if (N0C && N0C->isAllOnesValue())
2294 return N0;
2295 // fold (sra x, c >= size(x)) -> undef
2296 if (N1C && N1C->getValue() >= MVT::getSizeInBits(VT))
2297 return DAG.getNode(ISD::UNDEF, VT);
2298 // fold (sra x, 0) -> x
2299 if (N1C && N1C->isNullValue())
2300 return N0;
2301 // fold (sra (shl x, c1), c1) -> sext_inreg for some c1 and target supports
2302 // sext_inreg.
2303 if (N1C && N0.getOpcode() == ISD::SHL && N1 == N0.getOperand(1)) {
2304 unsigned LowBits = MVT::getSizeInBits(VT) - (unsigned)N1C->getValue();
2305 MVT::ValueType EVT;
2306 switch (LowBits) {
2307 default: EVT = MVT::Other; break;
2308 case 1: EVT = MVT::i1; break;
2309 case 8: EVT = MVT::i8; break;
2310 case 16: EVT = MVT::i16; break;
2311 case 32: EVT = MVT::i32; break;
2312 }
2313 if (EVT > MVT::Other && TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, EVT))
2314 return DAG.getNode(ISD::SIGN_EXTEND_INREG, VT, N0.getOperand(0),
2315 DAG.getValueType(EVT));
2316 }
2317
2318 // fold (sra (sra x, c1), c2) -> (sra x, c1+c2)
2319 if (N1C && N0.getOpcode() == ISD::SRA) {
2320 if (ConstantSDNode *C1 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
2321 unsigned Sum = N1C->getValue() + C1->getValue();
2322 if (Sum >= MVT::getSizeInBits(VT)) Sum = MVT::getSizeInBits(VT)-1;
2323 return DAG.getNode(ISD::SRA, VT, N0.getOperand(0),
2324 DAG.getConstant(Sum, N1C->getValueType(0)));
2325 }
2326 }
2327
2328 // Simplify, based on bits shifted out of the LHS.
2329 if (N1C && SimplifyDemandedBits(SDOperand(N, 0)))
2330 return SDOperand(N, 0);
2331
2332
2333 // If the sign bit is known to be zero, switch this to a SRL.
2334 if (DAG.MaskedValueIsZero(N0, MVT::getIntVTSignBit(VT)))
2335 return DAG.getNode(ISD::SRL, VT, N0, N1);
Chris Lattner91ed3c32007-12-06 07:33:36 +00002336
2337 return N1C ? visitShiftByConstant(N, N1C->getValue()) : SDOperand();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002338}
2339
2340SDOperand DAGCombiner::visitSRL(SDNode *N) {
2341 SDOperand N0 = N->getOperand(0);
2342 SDOperand N1 = N->getOperand(1);
2343 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
2344 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2345 MVT::ValueType VT = N0.getValueType();
2346 unsigned OpSizeInBits = MVT::getSizeInBits(VT);
2347
2348 // fold (srl c1, c2) -> c1 >>u c2
2349 if (N0C && N1C)
2350 return DAG.getNode(ISD::SRL, VT, N0, N1);
2351 // fold (srl 0, x) -> 0
2352 if (N0C && N0C->isNullValue())
2353 return N0;
2354 // fold (srl x, c >= size(x)) -> undef
2355 if (N1C && N1C->getValue() >= OpSizeInBits)
2356 return DAG.getNode(ISD::UNDEF, VT);
2357 // fold (srl x, 0) -> x
2358 if (N1C && N1C->isNullValue())
2359 return N0;
2360 // if (srl x, c) is known to be zero, return 0
2361 if (N1C && DAG.MaskedValueIsZero(SDOperand(N, 0), ~0ULL >> (64-OpSizeInBits)))
2362 return DAG.getConstant(0, VT);
2363
2364 // fold (srl (srl x, c1), c2) -> 0 or (srl x, c1+c2)
2365 if (N1C && N0.getOpcode() == ISD::SRL &&
2366 N0.getOperand(1).getOpcode() == ISD::Constant) {
2367 uint64_t c1 = cast<ConstantSDNode>(N0.getOperand(1))->getValue();
2368 uint64_t c2 = N1C->getValue();
2369 if (c1 + c2 > OpSizeInBits)
2370 return DAG.getConstant(0, VT);
2371 return DAG.getNode(ISD::SRL, VT, N0.getOperand(0),
2372 DAG.getConstant(c1 + c2, N1.getValueType()));
2373 }
2374
2375 // fold (srl (anyextend x), c) -> (anyextend (srl x, c))
2376 if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
2377 // Shifting in all undef bits?
2378 MVT::ValueType SmallVT = N0.getOperand(0).getValueType();
2379 if (N1C->getValue() >= MVT::getSizeInBits(SmallVT))
2380 return DAG.getNode(ISD::UNDEF, VT);
2381
2382 SDOperand SmallShift = DAG.getNode(ISD::SRL, SmallVT, N0.getOperand(0), N1);
2383 AddToWorkList(SmallShift.Val);
2384 return DAG.getNode(ISD::ANY_EXTEND, VT, SmallShift);
2385 }
2386
2387 // fold (srl (sra X, Y), 31) -> (srl X, 31). This srl only looks at the sign
2388 // bit, which is unmodified by sra.
2389 if (N1C && N1C->getValue()+1 == MVT::getSizeInBits(VT)) {
2390 if (N0.getOpcode() == ISD::SRA)
2391 return DAG.getNode(ISD::SRL, VT, N0.getOperand(0), N1);
2392 }
2393
2394 // fold (srl (ctlz x), "5") -> x iff x has one bit set (the low bit).
2395 if (N1C && N0.getOpcode() == ISD::CTLZ &&
2396 N1C->getValue() == Log2_32(MVT::getSizeInBits(VT))) {
2397 uint64_t KnownZero, KnownOne, Mask = MVT::getIntVTBitMask(VT);
2398 DAG.ComputeMaskedBits(N0.getOperand(0), Mask, KnownZero, KnownOne);
2399
2400 // If any of the input bits are KnownOne, then the input couldn't be all
2401 // zeros, thus the result of the srl will always be zero.
2402 if (KnownOne) return DAG.getConstant(0, VT);
2403
2404 // If all of the bits input the to ctlz node are known to be zero, then
2405 // the result of the ctlz is "32" and the result of the shift is one.
2406 uint64_t UnknownBits = ~KnownZero & Mask;
2407 if (UnknownBits == 0) return DAG.getConstant(1, VT);
2408
2409 // Otherwise, check to see if there is exactly one bit input to the ctlz.
2410 if ((UnknownBits & (UnknownBits-1)) == 0) {
2411 // Okay, we know that only that the single bit specified by UnknownBits
2412 // could be set on input to the CTLZ node. If this bit is set, the SRL
2413 // will return 0, if it is clear, it returns 1. Change the CTLZ/SRL pair
2414 // to an SRL,XOR pair, which is likely to simplify more.
2415 unsigned ShAmt = CountTrailingZeros_64(UnknownBits);
2416 SDOperand Op = N0.getOperand(0);
2417 if (ShAmt) {
2418 Op = DAG.getNode(ISD::SRL, VT, Op,
2419 DAG.getConstant(ShAmt, TLI.getShiftAmountTy()));
2420 AddToWorkList(Op.Val);
2421 }
2422 return DAG.getNode(ISD::XOR, VT, Op, DAG.getConstant(1, VT));
2423 }
2424 }
2425
2426 // fold operands of srl based on knowledge that the low bits are not
2427 // demanded.
2428 if (N1C && SimplifyDemandedBits(SDOperand(N, 0)))
2429 return SDOperand(N, 0);
2430
Chris Lattner91ed3c32007-12-06 07:33:36 +00002431 return N1C ? visitShiftByConstant(N, N1C->getValue()) : SDOperand();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002432}
2433
2434SDOperand DAGCombiner::visitCTLZ(SDNode *N) {
2435 SDOperand N0 = N->getOperand(0);
2436 MVT::ValueType VT = N->getValueType(0);
2437
2438 // fold (ctlz c1) -> c2
2439 if (isa<ConstantSDNode>(N0))
2440 return DAG.getNode(ISD::CTLZ, VT, N0);
2441 return SDOperand();
2442}
2443
2444SDOperand DAGCombiner::visitCTTZ(SDNode *N) {
2445 SDOperand N0 = N->getOperand(0);
2446 MVT::ValueType VT = N->getValueType(0);
2447
2448 // fold (cttz c1) -> c2
2449 if (isa<ConstantSDNode>(N0))
2450 return DAG.getNode(ISD::CTTZ, VT, N0);
2451 return SDOperand();
2452}
2453
2454SDOperand DAGCombiner::visitCTPOP(SDNode *N) {
2455 SDOperand N0 = N->getOperand(0);
2456 MVT::ValueType VT = N->getValueType(0);
2457
2458 // fold (ctpop c1) -> c2
2459 if (isa<ConstantSDNode>(N0))
2460 return DAG.getNode(ISD::CTPOP, VT, N0);
2461 return SDOperand();
2462}
2463
2464SDOperand DAGCombiner::visitSELECT(SDNode *N) {
2465 SDOperand N0 = N->getOperand(0);
2466 SDOperand N1 = N->getOperand(1);
2467 SDOperand N2 = N->getOperand(2);
2468 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
2469 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2470 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2);
2471 MVT::ValueType VT = N->getValueType(0);
Evan Chengff601dc2007-08-18 05:57:05 +00002472 MVT::ValueType VT0 = N0.getValueType();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002473
2474 // fold select C, X, X -> X
2475 if (N1 == N2)
2476 return N1;
2477 // fold select true, X, Y -> X
2478 if (N0C && !N0C->isNullValue())
2479 return N1;
2480 // fold select false, X, Y -> Y
2481 if (N0C && N0C->isNullValue())
2482 return N2;
2483 // fold select C, 1, X -> C | X
2484 if (MVT::i1 == VT && N1C && N1C->getValue() == 1)
2485 return DAG.getNode(ISD::OR, VT, N0, N2);
Evan Chengff601dc2007-08-18 05:57:05 +00002486 // fold select C, 0, 1 -> ~C
2487 if (MVT::isInteger(VT) && MVT::isInteger(VT0) &&
2488 N1C && N2C && N1C->isNullValue() && N2C->getValue() == 1) {
2489 SDOperand XORNode = DAG.getNode(ISD::XOR, VT0, N0, DAG.getConstant(1, VT0));
2490 if (VT == VT0)
2491 return XORNode;
2492 AddToWorkList(XORNode.Val);
2493 if (MVT::getSizeInBits(VT) > MVT::getSizeInBits(VT0))
2494 return DAG.getNode(ISD::ZERO_EXTEND, VT, XORNode);
2495 return DAG.getNode(ISD::TRUNCATE, VT, XORNode);
2496 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002497 // fold select C, 0, X -> ~C & X
Dale Johannesen53e0ad72007-12-06 17:53:31 +00002498 if (VT == VT0 && VT == MVT::i1 && N1C && N1C->isNullValue()) {
2499 SDOperand XORNode = DAG.getNode(ISD::XOR, VT, N0, DAG.getConstant(1, VT));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002500 AddToWorkList(XORNode.Val);
2501 return DAG.getNode(ISD::AND, VT, XORNode, N2);
2502 }
2503 // fold select C, X, 1 -> ~C | X
Dale Johannesen53e0ad72007-12-06 17:53:31 +00002504 if (VT == VT0 && VT == MVT::i1 && N2C && N2C->getValue() == 1) {
2505 SDOperand XORNode = DAG.getNode(ISD::XOR, VT, N0, DAG.getConstant(1, VT));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002506 AddToWorkList(XORNode.Val);
2507 return DAG.getNode(ISD::OR, VT, XORNode, N1);
2508 }
2509 // fold select C, X, 0 -> C & X
2510 // FIXME: this should check for C type == X type, not i1?
2511 if (MVT::i1 == VT && N2C && N2C->isNullValue())
2512 return DAG.getNode(ISD::AND, VT, N0, N1);
2513 // fold X ? X : Y --> X ? 1 : Y --> X | Y
2514 if (MVT::i1 == VT && N0 == N1)
2515 return DAG.getNode(ISD::OR, VT, N0, N2);
2516 // fold X ? Y : X --> X ? Y : 0 --> X & Y
2517 if (MVT::i1 == VT && N0 == N2)
2518 return DAG.getNode(ISD::AND, VT, N0, N1);
2519
2520 // If we can fold this based on the true/false value, do so.
2521 if (SimplifySelectOps(N, N1, N2))
2522 return SDOperand(N, 0); // Don't revisit N.
2523
2524 // fold selects based on a setcc into other things, such as min/max/abs
2525 if (N0.getOpcode() == ISD::SETCC)
2526 // FIXME:
2527 // Check against MVT::Other for SELECT_CC, which is a workaround for targets
2528 // having to say they don't support SELECT_CC on every type the DAG knows
2529 // about, since there is no way to mark an opcode illegal at all value types
2530 if (TLI.isOperationLegal(ISD::SELECT_CC, MVT::Other))
2531 return DAG.getNode(ISD::SELECT_CC, VT, N0.getOperand(0), N0.getOperand(1),
2532 N1, N2, N0.getOperand(2));
2533 else
2534 return SimplifySelect(N0, N1, N2);
2535 return SDOperand();
2536}
2537
2538SDOperand DAGCombiner::visitSELECT_CC(SDNode *N) {
2539 SDOperand N0 = N->getOperand(0);
2540 SDOperand N1 = N->getOperand(1);
2541 SDOperand N2 = N->getOperand(2);
2542 SDOperand N3 = N->getOperand(3);
2543 SDOperand N4 = N->getOperand(4);
2544 ISD::CondCode CC = cast<CondCodeSDNode>(N4)->get();
2545
2546 // fold select_cc lhs, rhs, x, x, cc -> x
2547 if (N2 == N3)
2548 return N2;
2549
2550 // Determine if the condition we're dealing with is constant
2551 SDOperand SCC = SimplifySetCC(TLI.getSetCCResultTy(), N0, N1, CC, false);
2552 if (SCC.Val) AddToWorkList(SCC.Val);
2553
2554 if (ConstantSDNode *SCCC = dyn_cast_or_null<ConstantSDNode>(SCC.Val)) {
2555 if (SCCC->getValue())
2556 return N2; // cond always true -> true val
2557 else
2558 return N3; // cond always false -> false val
2559 }
2560
2561 // Fold to a simpler select_cc
2562 if (SCC.Val && SCC.getOpcode() == ISD::SETCC)
2563 return DAG.getNode(ISD::SELECT_CC, N2.getValueType(),
2564 SCC.getOperand(0), SCC.getOperand(1), N2, N3,
2565 SCC.getOperand(2));
2566
2567 // If we can fold this based on the true/false value, do so.
2568 if (SimplifySelectOps(N, N2, N3))
2569 return SDOperand(N, 0); // Don't revisit N.
2570
2571 // fold select_cc into other things, such as min/max/abs
2572 return SimplifySelectCC(N0, N1, N2, N3, CC);
2573}
2574
2575SDOperand DAGCombiner::visitSETCC(SDNode *N) {
2576 return SimplifySetCC(N->getValueType(0), N->getOperand(0), N->getOperand(1),
2577 cast<CondCodeSDNode>(N->getOperand(2))->get());
2578}
2579
Evan Cheng9decb332007-10-29 19:58:20 +00002580// ExtendUsesToFormExtLoad - Trying to extend uses of a load to enable this:
2581// "fold ({s|z}ext (load x)) -> ({s|z}ext (truncate ({s|z}extload x)))"
2582// transformation. Returns true if extension are possible and the above
2583// mentioned transformation is profitable.
2584static bool ExtendUsesToFormExtLoad(SDNode *N, SDOperand N0,
2585 unsigned ExtOpc,
2586 SmallVector<SDNode*, 4> &ExtendNodes,
2587 TargetLowering &TLI) {
2588 bool HasCopyToRegUses = false;
2589 bool isTruncFree = TLI.isTruncateFree(N->getValueType(0), N0.getValueType());
2590 for (SDNode::use_iterator UI = N0.Val->use_begin(), UE = N0.Val->use_end();
2591 UI != UE; ++UI) {
2592 SDNode *User = *UI;
2593 if (User == N)
2594 continue;
2595 // FIXME: Only extend SETCC N, N and SETCC N, c for now.
2596 if (User->getOpcode() == ISD::SETCC) {
2597 ISD::CondCode CC = cast<CondCodeSDNode>(User->getOperand(2))->get();
2598 if (ExtOpc == ISD::ZERO_EXTEND && ISD::isSignedIntSetCC(CC))
2599 // Sign bits will be lost after a zext.
2600 return false;
2601 bool Add = false;
2602 for (unsigned i = 0; i != 2; ++i) {
2603 SDOperand UseOp = User->getOperand(i);
2604 if (UseOp == N0)
2605 continue;
2606 if (!isa<ConstantSDNode>(UseOp))
2607 return false;
2608 Add = true;
2609 }
2610 if (Add)
2611 ExtendNodes.push_back(User);
2612 } else {
2613 for (unsigned i = 0, e = User->getNumOperands(); i != e; ++i) {
2614 SDOperand UseOp = User->getOperand(i);
2615 if (UseOp == N0) {
2616 // If truncate from extended type to original load type is free
2617 // on this target, then it's ok to extend a CopyToReg.
2618 if (isTruncFree && User->getOpcode() == ISD::CopyToReg)
2619 HasCopyToRegUses = true;
2620 else
2621 return false;
2622 }
2623 }
2624 }
2625 }
2626
2627 if (HasCopyToRegUses) {
2628 bool BothLiveOut = false;
2629 for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
2630 UI != UE; ++UI) {
2631 SDNode *User = *UI;
2632 for (unsigned i = 0, e = User->getNumOperands(); i != e; ++i) {
2633 SDOperand UseOp = User->getOperand(i);
2634 if (UseOp.Val == N && UseOp.ResNo == 0) {
2635 BothLiveOut = true;
2636 break;
2637 }
2638 }
2639 }
2640 if (BothLiveOut)
2641 // Both unextended and extended values are live out. There had better be
2642 // good a reason for the transformation.
2643 return ExtendNodes.size();
2644 }
2645 return true;
2646}
2647
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002648SDOperand DAGCombiner::visitSIGN_EXTEND(SDNode *N) {
2649 SDOperand N0 = N->getOperand(0);
2650 MVT::ValueType VT = N->getValueType(0);
2651
2652 // fold (sext c1) -> c1
2653 if (isa<ConstantSDNode>(N0))
2654 return DAG.getNode(ISD::SIGN_EXTEND, VT, N0);
2655
2656 // fold (sext (sext x)) -> (sext x)
2657 // fold (sext (aext x)) -> (sext x)
2658 if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
2659 return DAG.getNode(ISD::SIGN_EXTEND, VT, N0.getOperand(0));
2660
2661 // fold (sext (truncate (load x))) -> (sext (smaller load x))
2662 // fold (sext (truncate (srl (load x), c))) -> (sext (smaller load (x+c/n)))
2663 if (N0.getOpcode() == ISD::TRUNCATE) {
2664 SDOperand NarrowLoad = ReduceLoadWidth(N0.Val);
2665 if (NarrowLoad.Val) {
2666 if (NarrowLoad.Val != N0.Val)
2667 CombineTo(N0.Val, NarrowLoad);
2668 return DAG.getNode(ISD::SIGN_EXTEND, VT, NarrowLoad);
2669 }
2670 }
2671
2672 // See if the value being truncated is already sign extended. If so, just
2673 // eliminate the trunc/sext pair.
2674 if (N0.getOpcode() == ISD::TRUNCATE) {
2675 SDOperand Op = N0.getOperand(0);
2676 unsigned OpBits = MVT::getSizeInBits(Op.getValueType());
2677 unsigned MidBits = MVT::getSizeInBits(N0.getValueType());
2678 unsigned DestBits = MVT::getSizeInBits(VT);
2679 unsigned NumSignBits = DAG.ComputeNumSignBits(Op);
2680
2681 if (OpBits == DestBits) {
2682 // Op is i32, Mid is i8, and Dest is i32. If Op has more than 24 sign
2683 // bits, it is already ready.
2684 if (NumSignBits > DestBits-MidBits)
2685 return Op;
2686 } else if (OpBits < DestBits) {
2687 // Op is i32, Mid is i8, and Dest is i64. If Op has more than 24 sign
2688 // bits, just sext from i32.
2689 if (NumSignBits > OpBits-MidBits)
2690 return DAG.getNode(ISD::SIGN_EXTEND, VT, Op);
2691 } else {
2692 // Op is i64, Mid is i8, and Dest is i32. If Op has more than 56 sign
2693 // bits, just truncate to i32.
2694 if (NumSignBits > OpBits-MidBits)
2695 return DAG.getNode(ISD::TRUNCATE, VT, Op);
2696 }
2697
2698 // fold (sext (truncate x)) -> (sextinreg x).
2699 if (!AfterLegalize || TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG,
2700 N0.getValueType())) {
2701 if (Op.getValueType() < VT)
2702 Op = DAG.getNode(ISD::ANY_EXTEND, VT, Op);
2703 else if (Op.getValueType() > VT)
2704 Op = DAG.getNode(ISD::TRUNCATE, VT, Op);
2705 return DAG.getNode(ISD::SIGN_EXTEND_INREG, VT, Op,
2706 DAG.getValueType(N0.getValueType()));
2707 }
2708 }
2709
2710 // fold (sext (load x)) -> (sext (truncate (sextload x)))
Evan Cheng9decb332007-10-29 19:58:20 +00002711 if (ISD::isNON_EXTLoad(N0.Val) &&
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002712 (!AfterLegalize||TLI.isLoadXLegal(ISD::SEXTLOAD, N0.getValueType()))){
Evan Cheng9decb332007-10-29 19:58:20 +00002713 bool DoXform = true;
2714 SmallVector<SDNode*, 4> SetCCs;
2715 if (!N0.hasOneUse())
2716 DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::SIGN_EXTEND, SetCCs, TLI);
2717 if (DoXform) {
2718 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
2719 SDOperand ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, VT, LN0->getChain(),
2720 LN0->getBasePtr(), LN0->getSrcValue(),
2721 LN0->getSrcValueOffset(),
2722 N0.getValueType(),
2723 LN0->isVolatile(),
2724 LN0->getAlignment());
2725 CombineTo(N, ExtLoad);
2726 SDOperand Trunc = DAG.getNode(ISD::TRUNCATE, N0.getValueType(), ExtLoad);
2727 CombineTo(N0.Val, Trunc, ExtLoad.getValue(1));
2728 // Extend SetCC uses if necessary.
2729 for (unsigned i = 0, e = SetCCs.size(); i != e; ++i) {
2730 SDNode *SetCC = SetCCs[i];
2731 SmallVector<SDOperand, 4> Ops;
2732 for (unsigned j = 0; j != 2; ++j) {
2733 SDOperand SOp = SetCC->getOperand(j);
2734 if (SOp == Trunc)
2735 Ops.push_back(ExtLoad);
2736 else
2737 Ops.push_back(DAG.getNode(ISD::SIGN_EXTEND, VT, SOp));
2738 }
2739 Ops.push_back(SetCC->getOperand(2));
2740 CombineTo(SetCC, DAG.getNode(ISD::SETCC, SetCC->getValueType(0),
2741 &Ops[0], Ops.size()));
2742 }
2743 return SDOperand(N, 0); // Return N so it doesn't get rechecked!
2744 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002745 }
2746
2747 // fold (sext (sextload x)) -> (sext (truncate (sextload x)))
2748 // fold (sext ( extload x)) -> (sext (truncate (sextload x)))
2749 if ((ISD::isSEXTLoad(N0.Val) || ISD::isEXTLoad(N0.Val)) &&
2750 ISD::isUNINDEXEDLoad(N0.Val) && N0.hasOneUse()) {
2751 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
2752 MVT::ValueType EVT = LN0->getLoadedVT();
2753 if (!AfterLegalize || TLI.isLoadXLegal(ISD::SEXTLOAD, EVT)) {
2754 SDOperand ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, VT, LN0->getChain(),
2755 LN0->getBasePtr(), LN0->getSrcValue(),
2756 LN0->getSrcValueOffset(), EVT,
2757 LN0->isVolatile(),
2758 LN0->getAlignment());
2759 CombineTo(N, ExtLoad);
2760 CombineTo(N0.Val, DAG.getNode(ISD::TRUNCATE, N0.getValueType(), ExtLoad),
2761 ExtLoad.getValue(1));
2762 return SDOperand(N, 0); // Return N so it doesn't get rechecked!
2763 }
2764 }
2765
2766 // sext(setcc x,y,cc) -> select_cc x, y, -1, 0, cc
2767 if (N0.getOpcode() == ISD::SETCC) {
2768 SDOperand SCC =
2769 SimplifySelectCC(N0.getOperand(0), N0.getOperand(1),
2770 DAG.getConstant(~0ULL, VT), DAG.getConstant(0, VT),
2771 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
2772 if (SCC.Val) return SCC;
2773 }
2774
2775 return SDOperand();
2776}
2777
2778SDOperand DAGCombiner::visitZERO_EXTEND(SDNode *N) {
2779 SDOperand N0 = N->getOperand(0);
2780 MVT::ValueType VT = N->getValueType(0);
2781
2782 // fold (zext c1) -> c1
2783 if (isa<ConstantSDNode>(N0))
2784 return DAG.getNode(ISD::ZERO_EXTEND, VT, N0);
2785 // fold (zext (zext x)) -> (zext x)
2786 // fold (zext (aext x)) -> (zext x)
2787 if (N0.getOpcode() == ISD::ZERO_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
2788 return DAG.getNode(ISD::ZERO_EXTEND, VT, N0.getOperand(0));
2789
2790 // fold (zext (truncate (load x))) -> (zext (smaller load x))
2791 // fold (zext (truncate (srl (load x), c))) -> (zext (small load (x+c/n)))
2792 if (N0.getOpcode() == ISD::TRUNCATE) {
2793 SDOperand NarrowLoad = ReduceLoadWidth(N0.Val);
2794 if (NarrowLoad.Val) {
2795 if (NarrowLoad.Val != N0.Val)
2796 CombineTo(N0.Val, NarrowLoad);
2797 return DAG.getNode(ISD::ZERO_EXTEND, VT, NarrowLoad);
2798 }
2799 }
2800
2801 // fold (zext (truncate x)) -> (and x, mask)
2802 if (N0.getOpcode() == ISD::TRUNCATE &&
2803 (!AfterLegalize || TLI.isOperationLegal(ISD::AND, VT))) {
2804 SDOperand Op = N0.getOperand(0);
2805 if (Op.getValueType() < VT) {
2806 Op = DAG.getNode(ISD::ANY_EXTEND, VT, Op);
2807 } else if (Op.getValueType() > VT) {
2808 Op = DAG.getNode(ISD::TRUNCATE, VT, Op);
2809 }
2810 return DAG.getZeroExtendInReg(Op, N0.getValueType());
2811 }
2812
2813 // fold (zext (and (trunc x), cst)) -> (and x, cst).
2814 if (N0.getOpcode() == ISD::AND &&
2815 N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
2816 N0.getOperand(1).getOpcode() == ISD::Constant) {
2817 SDOperand X = N0.getOperand(0).getOperand(0);
2818 if (X.getValueType() < VT) {
2819 X = DAG.getNode(ISD::ANY_EXTEND, VT, X);
2820 } else if (X.getValueType() > VT) {
2821 X = DAG.getNode(ISD::TRUNCATE, VT, X);
2822 }
2823 uint64_t Mask = cast<ConstantSDNode>(N0.getOperand(1))->getValue();
2824 return DAG.getNode(ISD::AND, VT, X, DAG.getConstant(Mask, VT));
2825 }
2826
2827 // fold (zext (load x)) -> (zext (truncate (zextload x)))
Evan Cheng9decb332007-10-29 19:58:20 +00002828 if (ISD::isNON_EXTLoad(N0.Val) &&
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002829 (!AfterLegalize||TLI.isLoadXLegal(ISD::ZEXTLOAD, N0.getValueType()))) {
Evan Cheng9decb332007-10-29 19:58:20 +00002830 bool DoXform = true;
2831 SmallVector<SDNode*, 4> SetCCs;
2832 if (!N0.hasOneUse())
2833 DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ZERO_EXTEND, SetCCs, TLI);
2834 if (DoXform) {
2835 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
2836 SDOperand ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, VT, LN0->getChain(),
2837 LN0->getBasePtr(), LN0->getSrcValue(),
2838 LN0->getSrcValueOffset(),
2839 N0.getValueType(),
2840 LN0->isVolatile(),
2841 LN0->getAlignment());
2842 CombineTo(N, ExtLoad);
2843 SDOperand Trunc = DAG.getNode(ISD::TRUNCATE, N0.getValueType(), ExtLoad);
2844 CombineTo(N0.Val, Trunc, ExtLoad.getValue(1));
2845 // Extend SetCC uses if necessary.
2846 for (unsigned i = 0, e = SetCCs.size(); i != e; ++i) {
2847 SDNode *SetCC = SetCCs[i];
2848 SmallVector<SDOperand, 4> Ops;
2849 for (unsigned j = 0; j != 2; ++j) {
2850 SDOperand SOp = SetCC->getOperand(j);
2851 if (SOp == Trunc)
2852 Ops.push_back(ExtLoad);
2853 else
Evan Cheng06aaf4c2007-10-30 20:11:21 +00002854 Ops.push_back(DAG.getNode(ISD::ZERO_EXTEND, VT, SOp));
Evan Cheng9decb332007-10-29 19:58:20 +00002855 }
2856 Ops.push_back(SetCC->getOperand(2));
2857 CombineTo(SetCC, DAG.getNode(ISD::SETCC, SetCC->getValueType(0),
2858 &Ops[0], Ops.size()));
2859 }
2860 return SDOperand(N, 0); // Return N so it doesn't get rechecked!
2861 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002862 }
2863
2864 // fold (zext (zextload x)) -> (zext (truncate (zextload x)))
2865 // fold (zext ( extload x)) -> (zext (truncate (zextload x)))
2866 if ((ISD::isZEXTLoad(N0.Val) || ISD::isEXTLoad(N0.Val)) &&
2867 ISD::isUNINDEXEDLoad(N0.Val) && N0.hasOneUse()) {
2868 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
2869 MVT::ValueType EVT = LN0->getLoadedVT();
2870 SDOperand ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, VT, LN0->getChain(),
2871 LN0->getBasePtr(), LN0->getSrcValue(),
2872 LN0->getSrcValueOffset(), EVT,
2873 LN0->isVolatile(),
2874 LN0->getAlignment());
2875 CombineTo(N, ExtLoad);
2876 CombineTo(N0.Val, DAG.getNode(ISD::TRUNCATE, N0.getValueType(), ExtLoad),
2877 ExtLoad.getValue(1));
2878 return SDOperand(N, 0); // Return N so it doesn't get rechecked!
2879 }
2880
2881 // zext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
2882 if (N0.getOpcode() == ISD::SETCC) {
2883 SDOperand SCC =
2884 SimplifySelectCC(N0.getOperand(0), N0.getOperand(1),
2885 DAG.getConstant(1, VT), DAG.getConstant(0, VT),
2886 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
2887 if (SCC.Val) return SCC;
2888 }
2889
2890 return SDOperand();
2891}
2892
2893SDOperand DAGCombiner::visitANY_EXTEND(SDNode *N) {
2894 SDOperand N0 = N->getOperand(0);
2895 MVT::ValueType VT = N->getValueType(0);
2896
2897 // fold (aext c1) -> c1
2898 if (isa<ConstantSDNode>(N0))
2899 return DAG.getNode(ISD::ANY_EXTEND, VT, N0);
2900 // fold (aext (aext x)) -> (aext x)
2901 // fold (aext (zext x)) -> (zext x)
2902 // fold (aext (sext x)) -> (sext x)
2903 if (N0.getOpcode() == ISD::ANY_EXTEND ||
2904 N0.getOpcode() == ISD::ZERO_EXTEND ||
2905 N0.getOpcode() == ISD::SIGN_EXTEND)
2906 return DAG.getNode(N0.getOpcode(), VT, N0.getOperand(0));
2907
2908 // fold (aext (truncate (load x))) -> (aext (smaller load x))
2909 // fold (aext (truncate (srl (load x), c))) -> (aext (small load (x+c/n)))
2910 if (N0.getOpcode() == ISD::TRUNCATE) {
2911 SDOperand NarrowLoad = ReduceLoadWidth(N0.Val);
2912 if (NarrowLoad.Val) {
2913 if (NarrowLoad.Val != N0.Val)
2914 CombineTo(N0.Val, NarrowLoad);
2915 return DAG.getNode(ISD::ANY_EXTEND, VT, NarrowLoad);
2916 }
2917 }
2918
2919 // fold (aext (truncate x))
2920 if (N0.getOpcode() == ISD::TRUNCATE) {
2921 SDOperand TruncOp = N0.getOperand(0);
2922 if (TruncOp.getValueType() == VT)
2923 return TruncOp; // x iff x size == zext size.
2924 if (TruncOp.getValueType() > VT)
2925 return DAG.getNode(ISD::TRUNCATE, VT, TruncOp);
2926 return DAG.getNode(ISD::ANY_EXTEND, VT, TruncOp);
2927 }
2928
2929 // fold (aext (and (trunc x), cst)) -> (and x, cst).
2930 if (N0.getOpcode() == ISD::AND &&
2931 N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
2932 N0.getOperand(1).getOpcode() == ISD::Constant) {
2933 SDOperand X = N0.getOperand(0).getOperand(0);
2934 if (X.getValueType() < VT) {
2935 X = DAG.getNode(ISD::ANY_EXTEND, VT, X);
2936 } else if (X.getValueType() > VT) {
2937 X = DAG.getNode(ISD::TRUNCATE, VT, X);
2938 }
2939 uint64_t Mask = cast<ConstantSDNode>(N0.getOperand(1))->getValue();
2940 return DAG.getNode(ISD::AND, VT, X, DAG.getConstant(Mask, VT));
2941 }
2942
2943 // fold (aext (load x)) -> (aext (truncate (extload x)))
2944 if (ISD::isNON_EXTLoad(N0.Val) && N0.hasOneUse() &&
2945 (!AfterLegalize||TLI.isLoadXLegal(ISD::EXTLOAD, N0.getValueType()))) {
2946 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
2947 SDOperand ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, VT, LN0->getChain(),
2948 LN0->getBasePtr(), LN0->getSrcValue(),
2949 LN0->getSrcValueOffset(),
2950 N0.getValueType(),
2951 LN0->isVolatile(),
2952 LN0->getAlignment());
2953 CombineTo(N, ExtLoad);
2954 CombineTo(N0.Val, DAG.getNode(ISD::TRUNCATE, N0.getValueType(), ExtLoad),
2955 ExtLoad.getValue(1));
2956 return SDOperand(N, 0); // Return N so it doesn't get rechecked!
2957 }
2958
2959 // fold (aext (zextload x)) -> (aext (truncate (zextload x)))
2960 // fold (aext (sextload x)) -> (aext (truncate (sextload x)))
2961 // fold (aext ( extload x)) -> (aext (truncate (extload x)))
2962 if (N0.getOpcode() == ISD::LOAD &&
2963 !ISD::isNON_EXTLoad(N0.Val) && ISD::isUNINDEXEDLoad(N0.Val) &&
2964 N0.hasOneUse()) {
2965 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
2966 MVT::ValueType EVT = LN0->getLoadedVT();
2967 SDOperand ExtLoad = DAG.getExtLoad(LN0->getExtensionType(), VT,
2968 LN0->getChain(), LN0->getBasePtr(),
2969 LN0->getSrcValue(),
2970 LN0->getSrcValueOffset(), EVT,
2971 LN0->isVolatile(),
2972 LN0->getAlignment());
2973 CombineTo(N, ExtLoad);
2974 CombineTo(N0.Val, DAG.getNode(ISD::TRUNCATE, N0.getValueType(), ExtLoad),
2975 ExtLoad.getValue(1));
2976 return SDOperand(N, 0); // Return N so it doesn't get rechecked!
2977 }
2978
2979 // aext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
2980 if (N0.getOpcode() == ISD::SETCC) {
2981 SDOperand SCC =
2982 SimplifySelectCC(N0.getOperand(0), N0.getOperand(1),
2983 DAG.getConstant(1, VT), DAG.getConstant(0, VT),
2984 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
2985 if (SCC.Val)
2986 return SCC;
2987 }
2988
2989 return SDOperand();
2990}
2991
Chris Lattnere8671c52007-10-13 06:35:54 +00002992/// GetDemandedBits - See if the specified operand can be simplified with the
2993/// knowledge that only the bits specified by Mask are used. If so, return the
2994/// simpler operand, otherwise return a null SDOperand.
2995SDOperand DAGCombiner::GetDemandedBits(SDOperand V, uint64_t Mask) {
2996 switch (V.getOpcode()) {
2997 default: break;
2998 case ISD::OR:
2999 case ISD::XOR:
3000 // If the LHS or RHS don't contribute bits to the or, drop them.
3001 if (DAG.MaskedValueIsZero(V.getOperand(0), Mask))
3002 return V.getOperand(1);
3003 if (DAG.MaskedValueIsZero(V.getOperand(1), Mask))
3004 return V.getOperand(0);
3005 break;
Chris Lattnerb77ea552007-10-13 06:58:48 +00003006 case ISD::SRL:
3007 // Only look at single-use SRLs.
3008 if (!V.Val->hasOneUse())
3009 break;
3010 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(V.getOperand(1))) {
3011 // See if we can recursively simplify the LHS.
3012 unsigned Amt = RHSC->getValue();
3013 Mask = (Mask << Amt) & MVT::getIntVTBitMask(V.getValueType());
3014 SDOperand SimplifyLHS = GetDemandedBits(V.getOperand(0), Mask);
3015 if (SimplifyLHS.Val) {
3016 return DAG.getNode(ISD::SRL, V.getValueType(),
3017 SimplifyLHS, V.getOperand(1));
3018 }
3019 }
Chris Lattnere8671c52007-10-13 06:35:54 +00003020 }
3021 return SDOperand();
3022}
3023
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003024/// ReduceLoadWidth - If the result of a wider load is shifted to right of N
3025/// bits and then truncated to a narrower type and where N is a multiple
3026/// of number of bits of the narrower type, transform it to a narrower load
3027/// from address + N / num of bits of new type. If the result is to be
3028/// extended, also fold the extension to form a extending load.
3029SDOperand DAGCombiner::ReduceLoadWidth(SDNode *N) {
3030 unsigned Opc = N->getOpcode();
3031 ISD::LoadExtType ExtType = ISD::NON_EXTLOAD;
3032 SDOperand N0 = N->getOperand(0);
3033 MVT::ValueType VT = N->getValueType(0);
3034 MVT::ValueType EVT = N->getValueType(0);
3035
3036 // Special case: SIGN_EXTEND_INREG is basically truncating to EVT then
3037 // extended to VT.
3038 if (Opc == ISD::SIGN_EXTEND_INREG) {
3039 ExtType = ISD::SEXTLOAD;
3040 EVT = cast<VTSDNode>(N->getOperand(1))->getVT();
3041 if (AfterLegalize && !TLI.isLoadXLegal(ISD::SEXTLOAD, EVT))
3042 return SDOperand();
3043 }
3044
3045 unsigned EVTBits = MVT::getSizeInBits(EVT);
3046 unsigned ShAmt = 0;
3047 bool CombineSRL = false;
3048 if (N0.getOpcode() == ISD::SRL && N0.hasOneUse()) {
3049 if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
3050 ShAmt = N01->getValue();
3051 // Is the shift amount a multiple of size of VT?
3052 if ((ShAmt & (EVTBits-1)) == 0) {
3053 N0 = N0.getOperand(0);
3054 if (MVT::getSizeInBits(N0.getValueType()) <= EVTBits)
3055 return SDOperand();
3056 CombineSRL = true;
3057 }
3058 }
3059 }
3060
3061 if (ISD::isNON_EXTLoad(N0.Val) && N0.hasOneUse() &&
3062 // Do not allow folding to i1 here. i1 is implicitly stored in memory in
3063 // zero extended form: by shrinking the load, we lose track of the fact
3064 // that it is already zero extended.
3065 // FIXME: This should be reevaluated.
3066 VT != MVT::i1) {
3067 assert(MVT::getSizeInBits(N0.getValueType()) > EVTBits &&
3068 "Cannot truncate to larger type!");
3069 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
3070 MVT::ValueType PtrType = N0.getOperand(1).getValueType();
3071 // For big endian targets, we need to adjust the offset to the pointer to
3072 // load the correct bytes.
Duncan Sands4f18d4f2007-11-09 08:57:19 +00003073 if (!TLI.isLittleEndian()) {
3074 unsigned LVTStoreBits = MVT::getStoreSizeInBits(N0.getValueType());
3075 unsigned EVTStoreBits = MVT::getStoreSizeInBits(EVT);
3076 ShAmt = LVTStoreBits - EVTStoreBits - ShAmt;
3077 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003078 uint64_t PtrOff = ShAmt / 8;
Duncan Sandsa3691432007-10-28 12:59:45 +00003079 unsigned NewAlign = MinAlign(LN0->getAlignment(), PtrOff);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003080 SDOperand NewPtr = DAG.getNode(ISD::ADD, PtrType, LN0->getBasePtr(),
3081 DAG.getConstant(PtrOff, PtrType));
3082 AddToWorkList(NewPtr.Val);
3083 SDOperand Load = (ExtType == ISD::NON_EXTLOAD)
3084 ? DAG.getLoad(VT, LN0->getChain(), NewPtr,
3085 LN0->getSrcValue(), LN0->getSrcValueOffset(),
Duncan Sandsa3691432007-10-28 12:59:45 +00003086 LN0->isVolatile(), NewAlign)
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003087 : DAG.getExtLoad(ExtType, VT, LN0->getChain(), NewPtr,
3088 LN0->getSrcValue(), LN0->getSrcValueOffset(), EVT,
Duncan Sandsa3691432007-10-28 12:59:45 +00003089 LN0->isVolatile(), NewAlign);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003090 AddToWorkList(N);
3091 if (CombineSRL) {
Chris Lattner8a258202007-10-15 06:10:22 +00003092 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003093 CombineTo(N->getOperand(0).Val, Load);
3094 } else
3095 CombineTo(N0.Val, Load, Load.getValue(1));
3096 if (ShAmt) {
3097 if (Opc == ISD::SIGN_EXTEND_INREG)
3098 return DAG.getNode(Opc, VT, Load, N->getOperand(1));
3099 else
3100 return DAG.getNode(Opc, VT, Load);
3101 }
3102 return SDOperand(N, 0); // Return N so it doesn't get rechecked!
3103 }
3104
3105 return SDOperand();
3106}
3107
3108
3109SDOperand DAGCombiner::visitSIGN_EXTEND_INREG(SDNode *N) {
3110 SDOperand N0 = N->getOperand(0);
3111 SDOperand N1 = N->getOperand(1);
3112 MVT::ValueType VT = N->getValueType(0);
3113 MVT::ValueType EVT = cast<VTSDNode>(N1)->getVT();
3114 unsigned EVTBits = MVT::getSizeInBits(EVT);
3115
3116 // fold (sext_in_reg c1) -> c1
3117 if (isa<ConstantSDNode>(N0) || N0.getOpcode() == ISD::UNDEF)
3118 return DAG.getNode(ISD::SIGN_EXTEND_INREG, VT, N0, N1);
3119
3120 // If the input is already sign extended, just drop the extension.
3121 if (DAG.ComputeNumSignBits(N0) >= MVT::getSizeInBits(VT)-EVTBits+1)
3122 return N0;
3123
3124 // fold (sext_in_reg (sext_in_reg x, VT2), VT1) -> (sext_in_reg x, minVT) pt2
3125 if (N0.getOpcode() == ISD::SIGN_EXTEND_INREG &&
3126 EVT < cast<VTSDNode>(N0.getOperand(1))->getVT()) {
3127 return DAG.getNode(ISD::SIGN_EXTEND_INREG, VT, N0.getOperand(0), N1);
3128 }
3129
3130 // fold (sext_in_reg x) -> (zext_in_reg x) if the sign bit is known zero.
3131 if (DAG.MaskedValueIsZero(N0, 1ULL << (EVTBits-1)))
3132 return DAG.getZeroExtendInReg(N0, EVT);
3133
3134 // fold operands of sext_in_reg based on knowledge that the top bits are not
3135 // demanded.
3136 if (SimplifyDemandedBits(SDOperand(N, 0)))
3137 return SDOperand(N, 0);
3138
3139 // fold (sext_in_reg (load x)) -> (smaller sextload x)
3140 // fold (sext_in_reg (srl (load x), c)) -> (smaller sextload (x+c/evtbits))
3141 SDOperand NarrowLoad = ReduceLoadWidth(N);
3142 if (NarrowLoad.Val)
3143 return NarrowLoad;
3144
3145 // fold (sext_in_reg (srl X, 24), i8) -> sra X, 24
3146 // fold (sext_in_reg (srl X, 23), i8) -> sra X, 23 iff possible.
3147 // We already fold "(sext_in_reg (srl X, 25), i8) -> srl X, 25" above.
3148 if (N0.getOpcode() == ISD::SRL) {
3149 if (ConstantSDNode *ShAmt = dyn_cast<ConstantSDNode>(N0.getOperand(1)))
3150 if (ShAmt->getValue()+EVTBits <= MVT::getSizeInBits(VT)) {
3151 // We can turn this into an SRA iff the input to the SRL is already sign
3152 // extended enough.
3153 unsigned InSignBits = DAG.ComputeNumSignBits(N0.getOperand(0));
3154 if (MVT::getSizeInBits(VT)-(ShAmt->getValue()+EVTBits) < InSignBits)
3155 return DAG.getNode(ISD::SRA, VT, N0.getOperand(0), N0.getOperand(1));
3156 }
3157 }
3158
3159 // fold (sext_inreg (extload x)) -> (sextload x)
3160 if (ISD::isEXTLoad(N0.Val) &&
3161 ISD::isUNINDEXEDLoad(N0.Val) &&
3162 EVT == cast<LoadSDNode>(N0)->getLoadedVT() &&
3163 (!AfterLegalize || TLI.isLoadXLegal(ISD::SEXTLOAD, EVT))) {
3164 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
3165 SDOperand ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, VT, LN0->getChain(),
3166 LN0->getBasePtr(), LN0->getSrcValue(),
3167 LN0->getSrcValueOffset(), EVT,
3168 LN0->isVolatile(),
3169 LN0->getAlignment());
3170 CombineTo(N, ExtLoad);
3171 CombineTo(N0.Val, ExtLoad, ExtLoad.getValue(1));
3172 return SDOperand(N, 0); // Return N so it doesn't get rechecked!
3173 }
3174 // fold (sext_inreg (zextload x)) -> (sextload x) iff load has one use
3175 if (ISD::isZEXTLoad(N0.Val) && ISD::isUNINDEXEDLoad(N0.Val) &&
3176 N0.hasOneUse() &&
3177 EVT == cast<LoadSDNode>(N0)->getLoadedVT() &&
3178 (!AfterLegalize || TLI.isLoadXLegal(ISD::SEXTLOAD, EVT))) {
3179 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
3180 SDOperand ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, VT, LN0->getChain(),
3181 LN0->getBasePtr(), LN0->getSrcValue(),
3182 LN0->getSrcValueOffset(), EVT,
3183 LN0->isVolatile(),
3184 LN0->getAlignment());
3185 CombineTo(N, ExtLoad);
3186 CombineTo(N0.Val, ExtLoad, ExtLoad.getValue(1));
3187 return SDOperand(N, 0); // Return N so it doesn't get rechecked!
3188 }
3189 return SDOperand();
3190}
3191
3192SDOperand DAGCombiner::visitTRUNCATE(SDNode *N) {
3193 SDOperand N0 = N->getOperand(0);
3194 MVT::ValueType VT = N->getValueType(0);
3195
3196 // noop truncate
3197 if (N0.getValueType() == N->getValueType(0))
3198 return N0;
3199 // fold (truncate c1) -> c1
3200 if (isa<ConstantSDNode>(N0))
3201 return DAG.getNode(ISD::TRUNCATE, VT, N0);
3202 // fold (truncate (truncate x)) -> (truncate x)
3203 if (N0.getOpcode() == ISD::TRUNCATE)
3204 return DAG.getNode(ISD::TRUNCATE, VT, N0.getOperand(0));
3205 // fold (truncate (ext x)) -> (ext x) or (truncate x) or x
3206 if (N0.getOpcode() == ISD::ZERO_EXTEND || N0.getOpcode() == ISD::SIGN_EXTEND||
3207 N0.getOpcode() == ISD::ANY_EXTEND) {
3208 if (N0.getOperand(0).getValueType() < VT)
3209 // if the source is smaller than the dest, we still need an extend
3210 return DAG.getNode(N0.getOpcode(), VT, N0.getOperand(0));
3211 else if (N0.getOperand(0).getValueType() > VT)
3212 // if the source is larger than the dest, than we just need the truncate
3213 return DAG.getNode(ISD::TRUNCATE, VT, N0.getOperand(0));
3214 else
3215 // if the source and dest are the same type, we can drop both the extend
3216 // and the truncate
3217 return N0.getOperand(0);
3218 }
3219
Chris Lattnere8671c52007-10-13 06:35:54 +00003220 // See if we can simplify the input to this truncate through knowledge that
3221 // only the low bits are being used. For example "trunc (or (shl x, 8), y)"
3222 // -> trunc y
3223 SDOperand Shorter = GetDemandedBits(N0, MVT::getIntVTBitMask(VT));
3224 if (Shorter.Val)
3225 return DAG.getNode(ISD::TRUNCATE, VT, Shorter);
3226
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003227 // fold (truncate (load x)) -> (smaller load x)
3228 // fold (truncate (srl (load x), c)) -> (smaller load (x+c/evtbits))
3229 return ReduceLoadWidth(N);
3230}
3231
3232SDOperand DAGCombiner::visitBIT_CONVERT(SDNode *N) {
3233 SDOperand N0 = N->getOperand(0);
3234 MVT::ValueType VT = N->getValueType(0);
3235
3236 // If the input is a BUILD_VECTOR with all constant elements, fold this now.
3237 // Only do this before legalize, since afterward the target may be depending
3238 // on the bitconvert.
3239 // First check to see if this is all constant.
3240 if (!AfterLegalize &&
3241 N0.getOpcode() == ISD::BUILD_VECTOR && N0.Val->hasOneUse() &&
3242 MVT::isVector(VT)) {
3243 bool isSimple = true;
3244 for (unsigned i = 0, e = N0.getNumOperands(); i != e; ++i)
3245 if (N0.getOperand(i).getOpcode() != ISD::UNDEF &&
3246 N0.getOperand(i).getOpcode() != ISD::Constant &&
3247 N0.getOperand(i).getOpcode() != ISD::ConstantFP) {
3248 isSimple = false;
3249 break;
3250 }
3251
3252 MVT::ValueType DestEltVT = MVT::getVectorElementType(N->getValueType(0));
3253 assert(!MVT::isVector(DestEltVT) &&
3254 "Element type of vector ValueType must not be vector!");
3255 if (isSimple) {
3256 return ConstantFoldBIT_CONVERTofBUILD_VECTOR(N0.Val, DestEltVT);
3257 }
3258 }
3259
3260 // If the input is a constant, let getNode() fold it.
3261 if (isa<ConstantSDNode>(N0) || isa<ConstantFPSDNode>(N0)) {
3262 SDOperand Res = DAG.getNode(ISD::BIT_CONVERT, VT, N0);
3263 if (Res.Val != N) return Res;
3264 }
3265
3266 if (N0.getOpcode() == ISD::BIT_CONVERT) // conv(conv(x,t1),t2) -> conv(x,t2)
3267 return DAG.getNode(ISD::BIT_CONVERT, VT, N0.getOperand(0));
3268
3269 // fold (conv (load x)) -> (load (conv*)x)
Evan Chengd7ba7ed2007-10-06 08:19:55 +00003270 // If the resultant load doesn't need a higher alignment than the original!
3271 if (ISD::isNormalLoad(N0.Val) && N0.hasOneUse() &&
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003272 TLI.isOperationLegal(ISD::LOAD, VT)) {
3273 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
3274 unsigned Align = TLI.getTargetMachine().getTargetData()->
3275 getABITypeAlignment(MVT::getTypeForValueType(VT));
3276 unsigned OrigAlign = LN0->getAlignment();
3277 if (Align <= OrigAlign) {
3278 SDOperand Load = DAG.getLoad(VT, LN0->getChain(), LN0->getBasePtr(),
3279 LN0->getSrcValue(), LN0->getSrcValueOffset(),
3280 LN0->isVolatile(), Align);
3281 AddToWorkList(N);
3282 CombineTo(N0.Val, DAG.getNode(ISD::BIT_CONVERT, N0.getValueType(), Load),
3283 Load.getValue(1));
3284 return Load;
3285 }
3286 }
3287
3288 return SDOperand();
3289}
3290
3291/// ConstantFoldBIT_CONVERTofBUILD_VECTOR - We know that BV is a build_vector
3292/// node with Constant, ConstantFP or Undef operands. DstEltVT indicates the
3293/// destination element value type.
3294SDOperand DAGCombiner::
3295ConstantFoldBIT_CONVERTofBUILD_VECTOR(SDNode *BV, MVT::ValueType DstEltVT) {
3296 MVT::ValueType SrcEltVT = BV->getOperand(0).getValueType();
3297
3298 // If this is already the right type, we're done.
3299 if (SrcEltVT == DstEltVT) return SDOperand(BV, 0);
3300
3301 unsigned SrcBitSize = MVT::getSizeInBits(SrcEltVT);
3302 unsigned DstBitSize = MVT::getSizeInBits(DstEltVT);
3303
3304 // If this is a conversion of N elements of one type to N elements of another
3305 // type, convert each element. This handles FP<->INT cases.
3306 if (SrcBitSize == DstBitSize) {
3307 SmallVector<SDOperand, 8> Ops;
3308 for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) {
3309 Ops.push_back(DAG.getNode(ISD::BIT_CONVERT, DstEltVT, BV->getOperand(i)));
3310 AddToWorkList(Ops.back().Val);
3311 }
3312 MVT::ValueType VT =
3313 MVT::getVectorType(DstEltVT,
3314 MVT::getVectorNumElements(BV->getValueType(0)));
3315 return DAG.getNode(ISD::BUILD_VECTOR, VT, &Ops[0], Ops.size());
3316 }
3317
3318 // Otherwise, we're growing or shrinking the elements. To avoid having to
3319 // handle annoying details of growing/shrinking FP values, we convert them to
3320 // int first.
3321 if (MVT::isFloatingPoint(SrcEltVT)) {
3322 // Convert the input float vector to a int vector where the elements are the
3323 // same sizes.
3324 assert((SrcEltVT == MVT::f32 || SrcEltVT == MVT::f64) && "Unknown FP VT!");
3325 MVT::ValueType IntVT = SrcEltVT == MVT::f32 ? MVT::i32 : MVT::i64;
3326 BV = ConstantFoldBIT_CONVERTofBUILD_VECTOR(BV, IntVT).Val;
3327 SrcEltVT = IntVT;
3328 }
3329
3330 // Now we know the input is an integer vector. If the output is a FP type,
3331 // convert to integer first, then to FP of the right size.
3332 if (MVT::isFloatingPoint(DstEltVT)) {
3333 assert((DstEltVT == MVT::f32 || DstEltVT == MVT::f64) && "Unknown FP VT!");
3334 MVT::ValueType TmpVT = DstEltVT == MVT::f32 ? MVT::i32 : MVT::i64;
3335 SDNode *Tmp = ConstantFoldBIT_CONVERTofBUILD_VECTOR(BV, TmpVT).Val;
3336
3337 // Next, convert to FP elements of the same size.
3338 return ConstantFoldBIT_CONVERTofBUILD_VECTOR(Tmp, DstEltVT);
3339 }
3340
3341 // Okay, we know the src/dst types are both integers of differing types.
3342 // Handling growing first.
3343 assert(MVT::isInteger(SrcEltVT) && MVT::isInteger(DstEltVT));
3344 if (SrcBitSize < DstBitSize) {
3345 unsigned NumInputsPerOutput = DstBitSize/SrcBitSize;
3346
3347 SmallVector<SDOperand, 8> Ops;
3348 for (unsigned i = 0, e = BV->getNumOperands(); i != e;
3349 i += NumInputsPerOutput) {
3350 bool isLE = TLI.isLittleEndian();
3351 uint64_t NewBits = 0;
3352 bool EltIsUndef = true;
3353 for (unsigned j = 0; j != NumInputsPerOutput; ++j) {
3354 // Shift the previously computed bits over.
3355 NewBits <<= SrcBitSize;
3356 SDOperand Op = BV->getOperand(i+ (isLE ? (NumInputsPerOutput-j-1) : j));
3357 if (Op.getOpcode() == ISD::UNDEF) continue;
3358 EltIsUndef = false;
3359
3360 NewBits |= cast<ConstantSDNode>(Op)->getValue();
3361 }
3362
3363 if (EltIsUndef)
3364 Ops.push_back(DAG.getNode(ISD::UNDEF, DstEltVT));
3365 else
3366 Ops.push_back(DAG.getConstant(NewBits, DstEltVT));
3367 }
3368
3369 MVT::ValueType VT = MVT::getVectorType(DstEltVT,
3370 Ops.size());
3371 return DAG.getNode(ISD::BUILD_VECTOR, VT, &Ops[0], Ops.size());
3372 }
3373
3374 // Finally, this must be the case where we are shrinking elements: each input
3375 // turns into multiple outputs.
3376 unsigned NumOutputsPerInput = SrcBitSize/DstBitSize;
3377 SmallVector<SDOperand, 8> Ops;
3378 for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) {
3379 if (BV->getOperand(i).getOpcode() == ISD::UNDEF) {
3380 for (unsigned j = 0; j != NumOutputsPerInput; ++j)
3381 Ops.push_back(DAG.getNode(ISD::UNDEF, DstEltVT));
3382 continue;
3383 }
3384 uint64_t OpVal = cast<ConstantSDNode>(BV->getOperand(i))->getValue();
3385
3386 for (unsigned j = 0; j != NumOutputsPerInput; ++j) {
3387 unsigned ThisVal = OpVal & ((1ULL << DstBitSize)-1);
3388 OpVal >>= DstBitSize;
3389 Ops.push_back(DAG.getConstant(ThisVal, DstEltVT));
3390 }
3391
3392 // For big endian targets, swap the order of the pieces of each element.
3393 if (!TLI.isLittleEndian())
3394 std::reverse(Ops.end()-NumOutputsPerInput, Ops.end());
3395 }
3396 MVT::ValueType VT = MVT::getVectorType(DstEltVT, Ops.size());
3397 return DAG.getNode(ISD::BUILD_VECTOR, VT, &Ops[0], Ops.size());
3398}
3399
3400
3401
3402SDOperand DAGCombiner::visitFADD(SDNode *N) {
3403 SDOperand N0 = N->getOperand(0);
3404 SDOperand N1 = N->getOperand(1);
3405 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
3406 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
3407 MVT::ValueType VT = N->getValueType(0);
3408
3409 // fold vector ops
3410 if (MVT::isVector(VT)) {
3411 SDOperand FoldedVOp = SimplifyVBinOp(N);
3412 if (FoldedVOp.Val) return FoldedVOp;
3413 }
3414
3415 // fold (fadd c1, c2) -> c1+c2
Dale Johannesenb89072e2007-10-16 23:38:29 +00003416 if (N0CFP && N1CFP && VT != MVT::ppcf128)
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003417 return DAG.getNode(ISD::FADD, VT, N0, N1);
3418 // canonicalize constant to RHS
3419 if (N0CFP && !N1CFP)
3420 return DAG.getNode(ISD::FADD, VT, N1, N0);
3421 // fold (A + (-B)) -> A-B
3422 if (isNegatibleForFree(N1) == 2)
3423 return DAG.getNode(ISD::FSUB, VT, N0, GetNegatedExpression(N1, DAG));
3424 // fold ((-A) + B) -> B-A
3425 if (isNegatibleForFree(N0) == 2)
3426 return DAG.getNode(ISD::FSUB, VT, N1, GetNegatedExpression(N0, DAG));
3427
3428 // If allowed, fold (fadd (fadd x, c1), c2) -> (fadd x, (fadd c1, c2))
3429 if (UnsafeFPMath && N1CFP && N0.getOpcode() == ISD::FADD &&
3430 N0.Val->hasOneUse() && isa<ConstantFPSDNode>(N0.getOperand(1)))
3431 return DAG.getNode(ISD::FADD, VT, N0.getOperand(0),
3432 DAG.getNode(ISD::FADD, VT, N0.getOperand(1), N1));
3433
3434 return SDOperand();
3435}
3436
3437SDOperand DAGCombiner::visitFSUB(SDNode *N) {
3438 SDOperand N0 = N->getOperand(0);
3439 SDOperand N1 = N->getOperand(1);
3440 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
3441 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
3442 MVT::ValueType VT = N->getValueType(0);
3443
3444 // fold vector ops
3445 if (MVT::isVector(VT)) {
3446 SDOperand FoldedVOp = SimplifyVBinOp(N);
3447 if (FoldedVOp.Val) return FoldedVOp;
3448 }
3449
3450 // fold (fsub c1, c2) -> c1-c2
Dale Johannesenb89072e2007-10-16 23:38:29 +00003451 if (N0CFP && N1CFP && VT != MVT::ppcf128)
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003452 return DAG.getNode(ISD::FSUB, VT, N0, N1);
3453 // fold (0-B) -> -B
Dale Johannesen7604c1b2007-08-31 23:34:27 +00003454 if (UnsafeFPMath && N0CFP && N0CFP->getValueAPF().isZero()) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003455 if (isNegatibleForFree(N1))
3456 return GetNegatedExpression(N1, DAG);
3457 return DAG.getNode(ISD::FNEG, VT, N1);
3458 }
3459 // fold (A-(-B)) -> A+B
3460 if (isNegatibleForFree(N1))
3461 return DAG.getNode(ISD::FADD, VT, N0, GetNegatedExpression(N1, DAG));
3462
3463 return SDOperand();
3464}
3465
3466SDOperand DAGCombiner::visitFMUL(SDNode *N) {
3467 SDOperand N0 = N->getOperand(0);
3468 SDOperand N1 = N->getOperand(1);
3469 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
3470 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
3471 MVT::ValueType VT = N->getValueType(0);
3472
3473 // fold vector ops
3474 if (MVT::isVector(VT)) {
3475 SDOperand FoldedVOp = SimplifyVBinOp(N);
3476 if (FoldedVOp.Val) return FoldedVOp;
3477 }
3478
3479 // fold (fmul c1, c2) -> c1*c2
Dale Johannesenb89072e2007-10-16 23:38:29 +00003480 if (N0CFP && N1CFP && VT != MVT::ppcf128)
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003481 return DAG.getNode(ISD::FMUL, VT, N0, N1);
3482 // canonicalize constant to RHS
3483 if (N0CFP && !N1CFP)
3484 return DAG.getNode(ISD::FMUL, VT, N1, N0);
3485 // fold (fmul X, 2.0) -> (fadd X, X)
3486 if (N1CFP && N1CFP->isExactlyValue(+2.0))
3487 return DAG.getNode(ISD::FADD, VT, N0, N0);
3488 // fold (fmul X, -1.0) -> (fneg X)
3489 if (N1CFP && N1CFP->isExactlyValue(-1.0))
3490 return DAG.getNode(ISD::FNEG, VT, N0);
3491
3492 // -X * -Y -> X*Y
3493 if (char LHSNeg = isNegatibleForFree(N0)) {
3494 if (char RHSNeg = isNegatibleForFree(N1)) {
3495 // Both can be negated for free, check to see if at least one is cheaper
3496 // negated.
3497 if (LHSNeg == 2 || RHSNeg == 2)
3498 return DAG.getNode(ISD::FMUL, VT, GetNegatedExpression(N0, DAG),
3499 GetNegatedExpression(N1, DAG));
3500 }
3501 }
3502
3503 // If allowed, fold (fmul (fmul x, c1), c2) -> (fmul x, (fmul c1, c2))
3504 if (UnsafeFPMath && N1CFP && N0.getOpcode() == ISD::FMUL &&
3505 N0.Val->hasOneUse() && isa<ConstantFPSDNode>(N0.getOperand(1)))
3506 return DAG.getNode(ISD::FMUL, VT, N0.getOperand(0),
3507 DAG.getNode(ISD::FMUL, VT, N0.getOperand(1), N1));
3508
3509 return SDOperand();
3510}
3511
3512SDOperand DAGCombiner::visitFDIV(SDNode *N) {
3513 SDOperand N0 = N->getOperand(0);
3514 SDOperand N1 = N->getOperand(1);
3515 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
3516 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
3517 MVT::ValueType VT = N->getValueType(0);
3518
3519 // fold vector ops
3520 if (MVT::isVector(VT)) {
3521 SDOperand FoldedVOp = SimplifyVBinOp(N);
3522 if (FoldedVOp.Val) return FoldedVOp;
3523 }
3524
3525 // fold (fdiv c1, c2) -> c1/c2
Dale Johannesenb89072e2007-10-16 23:38:29 +00003526 if (N0CFP && N1CFP && VT != MVT::ppcf128)
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003527 return DAG.getNode(ISD::FDIV, VT, N0, N1);
3528
3529
3530 // -X / -Y -> X*Y
3531 if (char LHSNeg = isNegatibleForFree(N0)) {
3532 if (char RHSNeg = isNegatibleForFree(N1)) {
3533 // Both can be negated for free, check to see if at least one is cheaper
3534 // negated.
3535 if (LHSNeg == 2 || RHSNeg == 2)
3536 return DAG.getNode(ISD::FDIV, VT, GetNegatedExpression(N0, DAG),
3537 GetNegatedExpression(N1, DAG));
3538 }
3539 }
3540
3541 return SDOperand();
3542}
3543
3544SDOperand DAGCombiner::visitFREM(SDNode *N) {
3545 SDOperand N0 = N->getOperand(0);
3546 SDOperand N1 = N->getOperand(1);
3547 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
3548 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
3549 MVT::ValueType VT = N->getValueType(0);
3550
3551 // fold (frem c1, c2) -> fmod(c1,c2)
Dale Johannesenb89072e2007-10-16 23:38:29 +00003552 if (N0CFP && N1CFP && VT != MVT::ppcf128)
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003553 return DAG.getNode(ISD::FREM, VT, N0, N1);
3554
3555 return SDOperand();
3556}
3557
3558SDOperand DAGCombiner::visitFCOPYSIGN(SDNode *N) {
3559 SDOperand N0 = N->getOperand(0);
3560 SDOperand N1 = N->getOperand(1);
3561 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
3562 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
3563 MVT::ValueType VT = N->getValueType(0);
3564
Dale Johannesenb89072e2007-10-16 23:38:29 +00003565 if (N0CFP && N1CFP && VT != MVT::ppcf128) // Constant fold
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003566 return DAG.getNode(ISD::FCOPYSIGN, VT, N0, N1);
3567
3568 if (N1CFP) {
Dale Johannesenc53301c2007-08-26 01:18:27 +00003569 const APFloat& V = N1CFP->getValueAPF();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003570 // copysign(x, c1) -> fabs(x) iff ispos(c1)
3571 // copysign(x, c1) -> fneg(fabs(x)) iff isneg(c1)
Dale Johannesen7f2c1d12007-08-25 22:10:57 +00003572 if (!V.isNegative())
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003573 return DAG.getNode(ISD::FABS, VT, N0);
3574 else
3575 return DAG.getNode(ISD::FNEG, VT, DAG.getNode(ISD::FABS, VT, N0));
3576 }
3577
3578 // copysign(fabs(x), y) -> copysign(x, y)
3579 // copysign(fneg(x), y) -> copysign(x, y)
3580 // copysign(copysign(x,z), y) -> copysign(x, y)
3581 if (N0.getOpcode() == ISD::FABS || N0.getOpcode() == ISD::FNEG ||
3582 N0.getOpcode() == ISD::FCOPYSIGN)
3583 return DAG.getNode(ISD::FCOPYSIGN, VT, N0.getOperand(0), N1);
3584
3585 // copysign(x, abs(y)) -> abs(x)
3586 if (N1.getOpcode() == ISD::FABS)
3587 return DAG.getNode(ISD::FABS, VT, N0);
3588
3589 // copysign(x, copysign(y,z)) -> copysign(x, z)
3590 if (N1.getOpcode() == ISD::FCOPYSIGN)
3591 return DAG.getNode(ISD::FCOPYSIGN, VT, N0, N1.getOperand(1));
3592
3593 // copysign(x, fp_extend(y)) -> copysign(x, y)
3594 // copysign(x, fp_round(y)) -> copysign(x, y)
3595 if (N1.getOpcode() == ISD::FP_EXTEND || N1.getOpcode() == ISD::FP_ROUND)
3596 return DAG.getNode(ISD::FCOPYSIGN, VT, N0, N1.getOperand(0));
3597
3598 return SDOperand();
3599}
3600
3601
3602
3603SDOperand DAGCombiner::visitSINT_TO_FP(SDNode *N) {
3604 SDOperand N0 = N->getOperand(0);
3605 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
3606 MVT::ValueType VT = N->getValueType(0);
3607
3608 // fold (sint_to_fp c1) -> c1fp
Dale Johannesenb89072e2007-10-16 23:38:29 +00003609 if (N0C && N0.getValueType() != MVT::ppcf128)
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003610 return DAG.getNode(ISD::SINT_TO_FP, VT, N0);
3611 return SDOperand();
3612}
3613
3614SDOperand DAGCombiner::visitUINT_TO_FP(SDNode *N) {
3615 SDOperand N0 = N->getOperand(0);
3616 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
3617 MVT::ValueType VT = N->getValueType(0);
3618
3619 // fold (uint_to_fp c1) -> c1fp
Dale Johannesenb89072e2007-10-16 23:38:29 +00003620 if (N0C && N0.getValueType() != MVT::ppcf128)
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003621 return DAG.getNode(ISD::UINT_TO_FP, VT, N0);
3622 return SDOperand();
3623}
3624
3625SDOperand DAGCombiner::visitFP_TO_SINT(SDNode *N) {
3626 SDOperand N0 = N->getOperand(0);
3627 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
3628 MVT::ValueType VT = N->getValueType(0);
3629
3630 // fold (fp_to_sint c1fp) -> c1
3631 if (N0CFP)
3632 return DAG.getNode(ISD::FP_TO_SINT, VT, N0);
3633 return SDOperand();
3634}
3635
3636SDOperand DAGCombiner::visitFP_TO_UINT(SDNode *N) {
3637 SDOperand N0 = N->getOperand(0);
3638 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
3639 MVT::ValueType VT = N->getValueType(0);
3640
3641 // fold (fp_to_uint c1fp) -> c1
Dale Johannesenb89072e2007-10-16 23:38:29 +00003642 if (N0CFP && VT != MVT::ppcf128)
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003643 return DAG.getNode(ISD::FP_TO_UINT, VT, N0);
3644 return SDOperand();
3645}
3646
3647SDOperand DAGCombiner::visitFP_ROUND(SDNode *N) {
3648 SDOperand N0 = N->getOperand(0);
Chris Lattner5872a362008-01-17 07:00:52 +00003649 SDOperand N1 = N->getOperand(1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003650 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
3651 MVT::ValueType VT = N->getValueType(0);
3652
3653 // fold (fp_round c1fp) -> c1fp
Dale Johannesenb89072e2007-10-16 23:38:29 +00003654 if (N0CFP && N0.getValueType() != MVT::ppcf128)
Chris Lattner5872a362008-01-17 07:00:52 +00003655 return DAG.getNode(ISD::FP_ROUND, VT, N0, N1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003656
3657 // fold (fp_round (fp_extend x)) -> x
3658 if (N0.getOpcode() == ISD::FP_EXTEND && VT == N0.getOperand(0).getValueType())
3659 return N0.getOperand(0);
3660
Chris Lattner7afb8552008-01-24 06:45:35 +00003661 // fold (fp_round (fp_round x)) -> (fp_round x)
3662 if (N0.getOpcode() == ISD::FP_ROUND) {
3663 // This is a value preserving truncation if both round's are.
3664 bool IsTrunc = N->getConstantOperandVal(1) == 1 &&
3665 N0.Val->getConstantOperandVal(1) == 1;
3666 return DAG.getNode(ISD::FP_ROUND, VT, N0.getOperand(0),
3667 DAG.getIntPtrConstant(IsTrunc));
3668 }
3669
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003670 // fold (fp_round (copysign X, Y)) -> (copysign (fp_round X), Y)
3671 if (N0.getOpcode() == ISD::FCOPYSIGN && N0.Val->hasOneUse()) {
Chris Lattner5872a362008-01-17 07:00:52 +00003672 SDOperand Tmp = DAG.getNode(ISD::FP_ROUND, VT, N0.getOperand(0), N1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003673 AddToWorkList(Tmp.Val);
3674 return DAG.getNode(ISD::FCOPYSIGN, VT, Tmp, N0.getOperand(1));
3675 }
3676
3677 return SDOperand();
3678}
3679
3680SDOperand DAGCombiner::visitFP_ROUND_INREG(SDNode *N) {
3681 SDOperand N0 = N->getOperand(0);
3682 MVT::ValueType VT = N->getValueType(0);
3683 MVT::ValueType EVT = cast<VTSDNode>(N->getOperand(1))->getVT();
3684 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
3685
3686 // fold (fp_round_inreg c1fp) -> c1fp
3687 if (N0CFP) {
Dale Johannesen7604c1b2007-08-31 23:34:27 +00003688 SDOperand Round = DAG.getConstantFP(N0CFP->getValueAPF(), EVT);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003689 return DAG.getNode(ISD::FP_EXTEND, VT, Round);
3690 }
3691 return SDOperand();
3692}
3693
3694SDOperand DAGCombiner::visitFP_EXTEND(SDNode *N) {
3695 SDOperand N0 = N->getOperand(0);
3696 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
3697 MVT::ValueType VT = N->getValueType(0);
3698
Chris Lattner6f981fc2007-12-29 06:55:23 +00003699 // If this is fp_round(fpextend), don't fold it, allow ourselves to be folded.
3700 if (N->hasOneUse() && (*N->use_begin())->getOpcode() == ISD::FP_ROUND)
3701 return SDOperand();
Chris Lattner5872a362008-01-17 07:00:52 +00003702
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003703 // fold (fp_extend c1fp) -> c1fp
Dale Johannesenb89072e2007-10-16 23:38:29 +00003704 if (N0CFP && VT != MVT::ppcf128)
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003705 return DAG.getNode(ISD::FP_EXTEND, VT, N0);
Chris Lattner5872a362008-01-17 07:00:52 +00003706
3707 // Turn fp_extend(fp_round(X, 1)) -> x since the fp_round doesn't affect the
3708 // value of X.
3709 if (N0.getOpcode() == ISD::FP_ROUND && N0.Val->getConstantOperandVal(1) == 1){
3710 SDOperand In = N0.getOperand(0);
3711 if (In.getValueType() == VT) return In;
3712 if (VT < In.getValueType())
3713 return DAG.getNode(ISD::FP_ROUND, VT, In, N0.getOperand(1));
3714 return DAG.getNode(ISD::FP_EXTEND, VT, In);
3715 }
3716
3717 // fold (fpext (load x)) -> (fpext (fptrunc (extload x)))
Dale Johannesen2550e3a2007-10-19 20:29:00 +00003718 if (ISD::isNON_EXTLoad(N0.Val) && N0.hasOneUse() &&
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003719 (!AfterLegalize||TLI.isLoadXLegal(ISD::EXTLOAD, N0.getValueType()))) {
3720 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
3721 SDOperand ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, VT, LN0->getChain(),
3722 LN0->getBasePtr(), LN0->getSrcValue(),
3723 LN0->getSrcValueOffset(),
3724 N0.getValueType(),
3725 LN0->isVolatile(),
3726 LN0->getAlignment());
3727 CombineTo(N, ExtLoad);
Chris Lattner5872a362008-01-17 07:00:52 +00003728 CombineTo(N0.Val, DAG.getNode(ISD::FP_ROUND, N0.getValueType(), ExtLoad,
3729 DAG.getIntPtrConstant(1)),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003730 ExtLoad.getValue(1));
3731 return SDOperand(N, 0); // Return N so it doesn't get rechecked!
3732 }
3733
3734
3735 return SDOperand();
3736}
3737
3738SDOperand DAGCombiner::visitFNEG(SDNode *N) {
3739 SDOperand N0 = N->getOperand(0);
3740
3741 if (isNegatibleForFree(N0))
3742 return GetNegatedExpression(N0, DAG);
3743
3744 return SDOperand();
3745}
3746
3747SDOperand DAGCombiner::visitFABS(SDNode *N) {
3748 SDOperand N0 = N->getOperand(0);
3749 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
3750 MVT::ValueType VT = N->getValueType(0);
3751
3752 // fold (fabs c1) -> fabs(c1)
Dale Johannesenb89072e2007-10-16 23:38:29 +00003753 if (N0CFP && VT != MVT::ppcf128)
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003754 return DAG.getNode(ISD::FABS, VT, N0);
3755 // fold (fabs (fabs x)) -> (fabs x)
3756 if (N0.getOpcode() == ISD::FABS)
3757 return N->getOperand(0);
3758 // fold (fabs (fneg x)) -> (fabs x)
3759 // fold (fabs (fcopysign x, y)) -> (fabs x)
3760 if (N0.getOpcode() == ISD::FNEG || N0.getOpcode() == ISD::FCOPYSIGN)
3761 return DAG.getNode(ISD::FABS, VT, N0.getOperand(0));
3762
3763 return SDOperand();
3764}
3765
3766SDOperand DAGCombiner::visitBRCOND(SDNode *N) {
3767 SDOperand Chain = N->getOperand(0);
3768 SDOperand N1 = N->getOperand(1);
3769 SDOperand N2 = N->getOperand(2);
3770 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
3771
3772 // never taken branch, fold to chain
3773 if (N1C && N1C->isNullValue())
3774 return Chain;
3775 // unconditional branch
3776 if (N1C && N1C->getValue() == 1)
3777 return DAG.getNode(ISD::BR, MVT::Other, Chain, N2);
3778 // fold a brcond with a setcc condition into a BR_CC node if BR_CC is legal
3779 // on the target.
3780 if (N1.getOpcode() == ISD::SETCC &&
3781 TLI.isOperationLegal(ISD::BR_CC, MVT::Other)) {
3782 return DAG.getNode(ISD::BR_CC, MVT::Other, Chain, N1.getOperand(2),
3783 N1.getOperand(0), N1.getOperand(1), N2);
3784 }
3785 return SDOperand();
3786}
3787
3788// Operand List for BR_CC: Chain, CondCC, CondLHS, CondRHS, DestBB.
3789//
3790SDOperand DAGCombiner::visitBR_CC(SDNode *N) {
3791 CondCodeSDNode *CC = cast<CondCodeSDNode>(N->getOperand(1));
3792 SDOperand CondLHS = N->getOperand(2), CondRHS = N->getOperand(3);
3793
3794 // Use SimplifySetCC to simplify SETCC's.
3795 SDOperand Simp = SimplifySetCC(MVT::i1, CondLHS, CondRHS, CC->get(), false);
3796 if (Simp.Val) AddToWorkList(Simp.Val);
3797
3798 ConstantSDNode *SCCC = dyn_cast_or_null<ConstantSDNode>(Simp.Val);
3799
3800 // fold br_cc true, dest -> br dest (unconditional branch)
3801 if (SCCC && SCCC->getValue())
3802 return DAG.getNode(ISD::BR, MVT::Other, N->getOperand(0),
3803 N->getOperand(4));
3804 // fold br_cc false, dest -> unconditional fall through
3805 if (SCCC && SCCC->isNullValue())
3806 return N->getOperand(0);
3807
3808 // fold to a simpler setcc
3809 if (Simp.Val && Simp.getOpcode() == ISD::SETCC)
3810 return DAG.getNode(ISD::BR_CC, MVT::Other, N->getOperand(0),
3811 Simp.getOperand(2), Simp.getOperand(0),
3812 Simp.getOperand(1), N->getOperand(4));
3813 return SDOperand();
3814}
3815
3816
3817/// CombineToPreIndexedLoadStore - Try turning a load / store and a
3818/// pre-indexed load / store when the base pointer is a add or subtract
3819/// and it has other uses besides the load / store. After the
3820/// transformation, the new indexed load / store has effectively folded
3821/// the add / subtract in and all of its other uses are redirected to the
3822/// new load / store.
3823bool DAGCombiner::CombineToPreIndexedLoadStore(SDNode *N) {
3824 if (!AfterLegalize)
3825 return false;
3826
3827 bool isLoad = true;
3828 SDOperand Ptr;
3829 MVT::ValueType VT;
3830 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
Chris Lattner3bc08502008-01-17 19:59:44 +00003831 if (LD->isIndexed())
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003832 return false;
3833 VT = LD->getLoadedVT();
3834 if (!TLI.isIndexedLoadLegal(ISD::PRE_INC, VT) &&
3835 !TLI.isIndexedLoadLegal(ISD::PRE_DEC, VT))
3836 return false;
3837 Ptr = LD->getBasePtr();
3838 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
Chris Lattner3bc08502008-01-17 19:59:44 +00003839 if (ST->isIndexed())
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003840 return false;
3841 VT = ST->getStoredVT();
3842 if (!TLI.isIndexedStoreLegal(ISD::PRE_INC, VT) &&
3843 !TLI.isIndexedStoreLegal(ISD::PRE_DEC, VT))
3844 return false;
3845 Ptr = ST->getBasePtr();
3846 isLoad = false;
3847 } else
3848 return false;
3849
3850 // If the pointer is not an add/sub, or if it doesn't have multiple uses, bail
3851 // out. There is no reason to make this a preinc/predec.
3852 if ((Ptr.getOpcode() != ISD::ADD && Ptr.getOpcode() != ISD::SUB) ||
3853 Ptr.Val->hasOneUse())
3854 return false;
3855
3856 // Ask the target to do addressing mode selection.
3857 SDOperand BasePtr;
3858 SDOperand Offset;
3859 ISD::MemIndexedMode AM = ISD::UNINDEXED;
3860 if (!TLI.getPreIndexedAddressParts(N, BasePtr, Offset, AM, DAG))
3861 return false;
3862 // Don't create a indexed load / store with zero offset.
3863 if (isa<ConstantSDNode>(Offset) &&
3864 cast<ConstantSDNode>(Offset)->getValue() == 0)
3865 return false;
3866
3867 // Try turning it into a pre-indexed load / store except when:
3868 // 1) The new base ptr is a frame index.
3869 // 2) If N is a store and the new base ptr is either the same as or is a
3870 // predecessor of the value being stored.
3871 // 3) Another use of old base ptr is a predecessor of N. If ptr is folded
3872 // that would create a cycle.
3873 // 4) All uses are load / store ops that use it as old base ptr.
3874
3875 // Check #1. Preinc'ing a frame index would require copying the stack pointer
3876 // (plus the implicit offset) to a register to preinc anyway.
3877 if (isa<FrameIndexSDNode>(BasePtr))
3878 return false;
3879
3880 // Check #2.
3881 if (!isLoad) {
3882 SDOperand Val = cast<StoreSDNode>(N)->getValue();
3883 if (Val == BasePtr || BasePtr.Val->isPredecessor(Val.Val))
3884 return false;
3885 }
3886
3887 // Now check for #3 and #4.
3888 bool RealUse = false;
3889 for (SDNode::use_iterator I = Ptr.Val->use_begin(),
3890 E = Ptr.Val->use_end(); I != E; ++I) {
3891 SDNode *Use = *I;
3892 if (Use == N)
3893 continue;
3894 if (Use->isPredecessor(N))
3895 return false;
3896
3897 if (!((Use->getOpcode() == ISD::LOAD &&
3898 cast<LoadSDNode>(Use)->getBasePtr() == Ptr) ||
3899 (Use->getOpcode() == ISD::STORE) &&
3900 cast<StoreSDNode>(Use)->getBasePtr() == Ptr))
3901 RealUse = true;
3902 }
3903 if (!RealUse)
3904 return false;
3905
3906 SDOperand Result;
3907 if (isLoad)
3908 Result = DAG.getIndexedLoad(SDOperand(N,0), BasePtr, Offset, AM);
3909 else
3910 Result = DAG.getIndexedStore(SDOperand(N,0), BasePtr, Offset, AM);
3911 ++PreIndexedNodes;
3912 ++NodesCombined;
3913 DOUT << "\nReplacing.4 "; DEBUG(N->dump(&DAG));
3914 DOUT << "\nWith: "; DEBUG(Result.Val->dump(&DAG));
3915 DOUT << '\n';
3916 std::vector<SDNode*> NowDead;
3917 if (isLoad) {
3918 DAG.ReplaceAllUsesOfValueWith(SDOperand(N, 0), Result.getValue(0),
Chris Lattner8a258202007-10-15 06:10:22 +00003919 &NowDead);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003920 DAG.ReplaceAllUsesOfValueWith(SDOperand(N, 1), Result.getValue(2),
Chris Lattner8a258202007-10-15 06:10:22 +00003921 &NowDead);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003922 } else {
3923 DAG.ReplaceAllUsesOfValueWith(SDOperand(N, 0), Result.getValue(1),
Chris Lattner8a258202007-10-15 06:10:22 +00003924 &NowDead);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003925 }
3926
3927 // Nodes can end up on the worklist more than once. Make sure we do
3928 // not process a node that has been replaced.
3929 for (unsigned i = 0, e = NowDead.size(); i != e; ++i)
3930 removeFromWorkList(NowDead[i]);
3931 // Finally, since the node is now dead, remove it from the graph.
3932 DAG.DeleteNode(N);
3933
3934 // Replace the uses of Ptr with uses of the updated base value.
3935 DAG.ReplaceAllUsesOfValueWith(Ptr, Result.getValue(isLoad ? 1 : 0),
Chris Lattner8a258202007-10-15 06:10:22 +00003936 &NowDead);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003937 removeFromWorkList(Ptr.Val);
3938 for (unsigned i = 0, e = NowDead.size(); i != e; ++i)
3939 removeFromWorkList(NowDead[i]);
3940 DAG.DeleteNode(Ptr.Val);
3941
3942 return true;
3943}
3944
3945/// CombineToPostIndexedLoadStore - Try combine a load / store with a
3946/// add / sub of the base pointer node into a post-indexed load / store.
3947/// The transformation folded the add / subtract into the new indexed
3948/// load / store effectively and all of its uses are redirected to the
3949/// new load / store.
3950bool DAGCombiner::CombineToPostIndexedLoadStore(SDNode *N) {
3951 if (!AfterLegalize)
3952 return false;
3953
3954 bool isLoad = true;
3955 SDOperand Ptr;
3956 MVT::ValueType VT;
3957 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
Chris Lattner3bc08502008-01-17 19:59:44 +00003958 if (LD->isIndexed())
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003959 return false;
3960 VT = LD->getLoadedVT();
3961 if (!TLI.isIndexedLoadLegal(ISD::POST_INC, VT) &&
3962 !TLI.isIndexedLoadLegal(ISD::POST_DEC, VT))
3963 return false;
3964 Ptr = LD->getBasePtr();
3965 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
Chris Lattner3bc08502008-01-17 19:59:44 +00003966 if (ST->isIndexed())
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003967 return false;
3968 VT = ST->getStoredVT();
3969 if (!TLI.isIndexedStoreLegal(ISD::POST_INC, VT) &&
3970 !TLI.isIndexedStoreLegal(ISD::POST_DEC, VT))
3971 return false;
3972 Ptr = ST->getBasePtr();
3973 isLoad = false;
3974 } else
3975 return false;
3976
3977 if (Ptr.Val->hasOneUse())
3978 return false;
3979
3980 for (SDNode::use_iterator I = Ptr.Val->use_begin(),
3981 E = Ptr.Val->use_end(); I != E; ++I) {
3982 SDNode *Op = *I;
3983 if (Op == N ||
3984 (Op->getOpcode() != ISD::ADD && Op->getOpcode() != ISD::SUB))
3985 continue;
3986
3987 SDOperand BasePtr;
3988 SDOperand Offset;
3989 ISD::MemIndexedMode AM = ISD::UNINDEXED;
3990 if (TLI.getPostIndexedAddressParts(N, Op, BasePtr, Offset, AM, DAG)) {
3991 if (Ptr == Offset)
3992 std::swap(BasePtr, Offset);
3993 if (Ptr != BasePtr)
3994 continue;
3995 // Don't create a indexed load / store with zero offset.
3996 if (isa<ConstantSDNode>(Offset) &&
3997 cast<ConstantSDNode>(Offset)->getValue() == 0)
3998 continue;
3999
4000 // Try turning it into a post-indexed load / store except when
4001 // 1) All uses are load / store ops that use it as base ptr.
4002 // 2) Op must be independent of N, i.e. Op is neither a predecessor
4003 // nor a successor of N. Otherwise, if Op is folded that would
4004 // create a cycle.
4005
4006 // Check for #1.
4007 bool TryNext = false;
4008 for (SDNode::use_iterator II = BasePtr.Val->use_begin(),
4009 EE = BasePtr.Val->use_end(); II != EE; ++II) {
4010 SDNode *Use = *II;
4011 if (Use == Ptr.Val)
4012 continue;
4013
4014 // If all the uses are load / store addresses, then don't do the
4015 // transformation.
4016 if (Use->getOpcode() == ISD::ADD || Use->getOpcode() == ISD::SUB){
4017 bool RealUse = false;
4018 for (SDNode::use_iterator III = Use->use_begin(),
4019 EEE = Use->use_end(); III != EEE; ++III) {
4020 SDNode *UseUse = *III;
4021 if (!((UseUse->getOpcode() == ISD::LOAD &&
4022 cast<LoadSDNode>(UseUse)->getBasePtr().Val == Use) ||
4023 (UseUse->getOpcode() == ISD::STORE) &&
4024 cast<StoreSDNode>(UseUse)->getBasePtr().Val == Use))
4025 RealUse = true;
4026 }
4027
4028 if (!RealUse) {
4029 TryNext = true;
4030 break;
4031 }
4032 }
4033 }
4034 if (TryNext)
4035 continue;
4036
4037 // Check for #2
4038 if (!Op->isPredecessor(N) && !N->isPredecessor(Op)) {
4039 SDOperand Result = isLoad
4040 ? DAG.getIndexedLoad(SDOperand(N,0), BasePtr, Offset, AM)
4041 : DAG.getIndexedStore(SDOperand(N,0), BasePtr, Offset, AM);
4042 ++PostIndexedNodes;
4043 ++NodesCombined;
4044 DOUT << "\nReplacing.5 "; DEBUG(N->dump(&DAG));
4045 DOUT << "\nWith: "; DEBUG(Result.Val->dump(&DAG));
4046 DOUT << '\n';
4047 std::vector<SDNode*> NowDead;
4048 if (isLoad) {
4049 DAG.ReplaceAllUsesOfValueWith(SDOperand(N, 0), Result.getValue(0),
Chris Lattner8a258202007-10-15 06:10:22 +00004050 &NowDead);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004051 DAG.ReplaceAllUsesOfValueWith(SDOperand(N, 1), Result.getValue(2),
Chris Lattner8a258202007-10-15 06:10:22 +00004052 &NowDead);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004053 } else {
4054 DAG.ReplaceAllUsesOfValueWith(SDOperand(N, 0), Result.getValue(1),
Chris Lattner8a258202007-10-15 06:10:22 +00004055 &NowDead);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004056 }
4057
4058 // Nodes can end up on the worklist more than once. Make sure we do
4059 // not process a node that has been replaced.
4060 for (unsigned i = 0, e = NowDead.size(); i != e; ++i)
4061 removeFromWorkList(NowDead[i]);
4062 // Finally, since the node is now dead, remove it from the graph.
4063 DAG.DeleteNode(N);
4064
4065 // Replace the uses of Use with uses of the updated base value.
4066 DAG.ReplaceAllUsesOfValueWith(SDOperand(Op, 0),
4067 Result.getValue(isLoad ? 1 : 0),
Chris Lattner8a258202007-10-15 06:10:22 +00004068 &NowDead);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004069 removeFromWorkList(Op);
4070 for (unsigned i = 0, e = NowDead.size(); i != e; ++i)
4071 removeFromWorkList(NowDead[i]);
4072 DAG.DeleteNode(Op);
4073
4074 return true;
4075 }
4076 }
4077 }
4078 return false;
4079}
4080
Chris Lattner4e137af2008-01-25 07:20:16 +00004081/// InferAlignment - If we can infer some alignment information from this
4082/// pointer, return it.
4083static unsigned InferAlignment(SDOperand Ptr, SelectionDAG &DAG) {
4084 // If this is a direct reference to a stack slot, use information about the
4085 // stack slot's alignment.
4086 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Ptr)) {
4087 return DAG.getMachineFunction().getFrameInfo()->
4088 getObjectAlignment(FI->getIndex());
4089 }
4090
4091 // FIXME: Handle FI+CST.
4092
4093 return 0;
4094}
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004095
4096SDOperand DAGCombiner::visitLOAD(SDNode *N) {
4097 LoadSDNode *LD = cast<LoadSDNode>(N);
4098 SDOperand Chain = LD->getChain();
4099 SDOperand Ptr = LD->getBasePtr();
Chris Lattner4e137af2008-01-25 07:20:16 +00004100
4101 // Try to infer better alignment information than the load already has.
4102 if (LD->isUnindexed()) {
4103 if (unsigned Align = InferAlignment(Ptr, DAG)) {
4104 if (Align > LD->getAlignment())
4105 return DAG.getExtLoad(LD->getExtensionType(), LD->getValueType(0),
4106 Chain, Ptr, LD->getSrcValue(),
4107 LD->getSrcValueOffset(), LD->getLoadedVT(),
4108 LD->isVolatile(), Align);
4109 }
4110 }
4111
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004112
4113 // If load is not volatile and there are no uses of the loaded value (and
4114 // the updated indexed value in case of indexed loads), change uses of the
4115 // chain value into uses of the chain input (i.e. delete the dead load).
4116 if (!LD->isVolatile()) {
4117 if (N->getValueType(1) == MVT::Other) {
4118 // Unindexed loads.
Evan Chenge8b886a2008-01-16 23:11:54 +00004119 if (N->hasNUsesOfValue(0, 0)) {
4120 // It's not safe to use the two value CombineTo variant here. e.g.
4121 // v1, chain2 = load chain1, loc
4122 // v2, chain3 = load chain2, loc
4123 // v3 = add v2, c
Chris Lattnerbb67c192008-01-24 07:57:06 +00004124 // Now we replace use of chain2 with chain1. This makes the second load
4125 // isomorphic to the one we are deleting, and thus makes this load live.
Evan Chenge8b886a2008-01-16 23:11:54 +00004126 std::vector<SDNode*> NowDead;
Evan Chenge8b886a2008-01-16 23:11:54 +00004127 DOUT << "\nReplacing.6 "; DEBUG(N->dump(&DAG));
Chris Lattnerbb67c192008-01-24 07:57:06 +00004128 DOUT << "\nWith chain: "; DEBUG(Chain.Val->dump(&DAG));
4129 DOUT << "\n";
Evan Chenge8b886a2008-01-16 23:11:54 +00004130 DAG.ReplaceAllUsesOfValueWith(SDOperand(N, 1), Chain, &NowDead);
Evan Chenge8b886a2008-01-16 23:11:54 +00004131 for (unsigned i = 0, e = NowDead.size(); i != e; ++i)
4132 removeFromWorkList(NowDead[i]);
Chris Lattnerbb67c192008-01-24 07:57:06 +00004133 if (N->use_empty()) {
4134 removeFromWorkList(N);
4135 DAG.DeleteNode(N);
4136 }
Evan Chenge8b886a2008-01-16 23:11:54 +00004137 return SDOperand(N, 0); // Return N so it doesn't get rechecked!
4138 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004139 } else {
4140 // Indexed loads.
4141 assert(N->getValueType(2) == MVT::Other && "Malformed indexed loads?");
4142 if (N->hasNUsesOfValue(0, 0) && N->hasNUsesOfValue(0, 1)) {
Evan Chenge8b886a2008-01-16 23:11:54 +00004143 std::vector<SDNode*> NowDead;
4144 SDOperand Undef = DAG.getNode(ISD::UNDEF, N->getValueType(0));
4145 DOUT << "\nReplacing.6 "; DEBUG(N->dump(&DAG));
4146 DOUT << "\nWith: "; DEBUG(Undef.Val->dump(&DAG));
4147 DOUT << " and 2 other values\n";
4148 DAG.ReplaceAllUsesOfValueWith(SDOperand(N, 0), Undef, &NowDead);
4149 DAG.ReplaceAllUsesOfValueWith(SDOperand(N, 1),
Chris Lattner667f9c12008-01-17 07:20:38 +00004150 DAG.getNode(ISD::UNDEF, N->getValueType(1)),
Evan Chenge8b886a2008-01-16 23:11:54 +00004151 &NowDead);
4152 DAG.ReplaceAllUsesOfValueWith(SDOperand(N, 2), Chain, &NowDead);
4153 removeFromWorkList(N);
4154 for (unsigned i = 0, e = NowDead.size(); i != e; ++i)
4155 removeFromWorkList(NowDead[i]);
4156 DAG.DeleteNode(N);
4157 return SDOperand(N, 0); // Return N so it doesn't get rechecked!
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004158 }
4159 }
4160 }
4161
4162 // If this load is directly stored, replace the load value with the stored
4163 // value.
4164 // TODO: Handle store large -> read small portion.
4165 // TODO: Handle TRUNCSTORE/LOADEXT
4166 if (LD->getExtensionType() == ISD::NON_EXTLOAD) {
4167 if (ISD::isNON_TRUNCStore(Chain.Val)) {
4168 StoreSDNode *PrevST = cast<StoreSDNode>(Chain);
4169 if (PrevST->getBasePtr() == Ptr &&
4170 PrevST->getValue().getValueType() == N->getValueType(0))
4171 return CombineTo(N, Chain.getOperand(1), Chain);
4172 }
4173 }
4174
4175 if (CombinerAA) {
4176 // Walk up chain skipping non-aliasing memory nodes.
4177 SDOperand BetterChain = FindBetterChain(N, Chain);
4178
4179 // If there is a better chain.
4180 if (Chain != BetterChain) {
4181 SDOperand ReplLoad;
4182
4183 // Replace the chain to void dependency.
4184 if (LD->getExtensionType() == ISD::NON_EXTLOAD) {
4185 ReplLoad = DAG.getLoad(N->getValueType(0), BetterChain, Ptr,
Duncan Sandsa3691432007-10-28 12:59:45 +00004186 LD->getSrcValue(), LD->getSrcValueOffset(),
4187 LD->isVolatile(), LD->getAlignment());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004188 } else {
4189 ReplLoad = DAG.getExtLoad(LD->getExtensionType(),
4190 LD->getValueType(0),
4191 BetterChain, Ptr, LD->getSrcValue(),
4192 LD->getSrcValueOffset(),
4193 LD->getLoadedVT(),
4194 LD->isVolatile(),
4195 LD->getAlignment());
4196 }
4197
4198 // Create token factor to keep old chain connected.
4199 SDOperand Token = DAG.getNode(ISD::TokenFactor, MVT::Other,
4200 Chain, ReplLoad.getValue(1));
4201
4202 // Replace uses with load result and token factor. Don't add users
4203 // to work list.
4204 return CombineTo(N, ReplLoad.getValue(0), Token, false);
4205 }
4206 }
4207
4208 // Try transforming N to an indexed load.
4209 if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
4210 return SDOperand(N, 0);
4211
4212 return SDOperand();
4213}
4214
Chris Lattner2e023772008-01-08 23:08:06 +00004215
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004216SDOperand DAGCombiner::visitSTORE(SDNode *N) {
4217 StoreSDNode *ST = cast<StoreSDNode>(N);
4218 SDOperand Chain = ST->getChain();
4219 SDOperand Value = ST->getValue();
4220 SDOperand Ptr = ST->getBasePtr();
4221
Chris Lattner4e137af2008-01-25 07:20:16 +00004222 // Try to infer better alignment information than the store already has.
4223 if (ST->isUnindexed()) {
4224 if (unsigned Align = InferAlignment(Ptr, DAG)) {
4225 if (Align > ST->getAlignment())
4226 return DAG.getTruncStore(Chain, Value, Ptr, ST->getSrcValue(),
4227 ST->getSrcValueOffset(), ST->getStoredVT(),
4228 ST->isVolatile(), Align);
4229 }
4230 }
4231
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004232 // If this is a store of a bit convert, store the input value if the
4233 // resultant store does not need a higher alignment than the original.
4234 if (Value.getOpcode() == ISD::BIT_CONVERT && !ST->isTruncatingStore() &&
Chris Lattner3bc08502008-01-17 19:59:44 +00004235 ST->isUnindexed()) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004236 unsigned Align = ST->getAlignment();
4237 MVT::ValueType SVT = Value.getOperand(0).getValueType();
4238 unsigned OrigAlign = TLI.getTargetMachine().getTargetData()->
4239 getABITypeAlignment(MVT::getTypeForValueType(SVT));
4240 if (Align <= OrigAlign && TLI.isOperationLegal(ISD::STORE, SVT))
4241 return DAG.getStore(Chain, Value.getOperand(0), Ptr, ST->getSrcValue(),
4242 ST->getSrcValueOffset(), ST->isVolatile(), Align);
4243 }
4244
4245 // Turn 'store float 1.0, Ptr' -> 'store int 0x12345678, Ptr'
4246 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Value)) {
4247 if (Value.getOpcode() != ISD::TargetConstantFP) {
4248 SDOperand Tmp;
4249 switch (CFP->getValueType(0)) {
4250 default: assert(0 && "Unknown FP type");
Dale Johannesen1b4181d2007-09-18 18:36:59 +00004251 case MVT::f80: // We don't do this for these yet.
4252 case MVT::f128:
4253 case MVT::ppcf128:
4254 break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004255 case MVT::f32:
4256 if (!AfterLegalize || TLI.isTypeLegal(MVT::i32)) {
Dale Johannesenfbd9cda2007-09-12 03:30:33 +00004257 Tmp = DAG.getConstant((uint32_t)CFP->getValueAPF().
4258 convertToAPInt().getZExtValue(), MVT::i32);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004259 return DAG.getStore(Chain, Tmp, Ptr, ST->getSrcValue(),
4260 ST->getSrcValueOffset(), ST->isVolatile(),
4261 ST->getAlignment());
4262 }
4263 break;
4264 case MVT::f64:
4265 if (!AfterLegalize || TLI.isTypeLegal(MVT::i64)) {
Dale Johannesenfbd9cda2007-09-12 03:30:33 +00004266 Tmp = DAG.getConstant(CFP->getValueAPF().convertToAPInt().
4267 getZExtValue(), MVT::i64);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004268 return DAG.getStore(Chain, Tmp, Ptr, ST->getSrcValue(),
4269 ST->getSrcValueOffset(), ST->isVolatile(),
4270 ST->getAlignment());
4271 } else if (TLI.isTypeLegal(MVT::i32)) {
Duncan Sandsa3691432007-10-28 12:59:45 +00004272 // Many FP stores are not made apparent until after legalize, e.g. for
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004273 // argument passing. Since this is so common, custom legalize the
4274 // 64-bit integer store into two 32-bit stores.
Dale Johannesenfbd9cda2007-09-12 03:30:33 +00004275 uint64_t Val = CFP->getValueAPF().convertToAPInt().getZExtValue();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004276 SDOperand Lo = DAG.getConstant(Val & 0xFFFFFFFF, MVT::i32);
4277 SDOperand Hi = DAG.getConstant(Val >> 32, MVT::i32);
4278 if (!TLI.isLittleEndian()) std::swap(Lo, Hi);
4279
4280 int SVOffset = ST->getSrcValueOffset();
4281 unsigned Alignment = ST->getAlignment();
4282 bool isVolatile = ST->isVolatile();
4283
4284 SDOperand St0 = DAG.getStore(Chain, Lo, Ptr, ST->getSrcValue(),
4285 ST->getSrcValueOffset(),
4286 isVolatile, ST->getAlignment());
4287 Ptr = DAG.getNode(ISD::ADD, Ptr.getValueType(), Ptr,
4288 DAG.getConstant(4, Ptr.getValueType()));
4289 SVOffset += 4;
Duncan Sandsa3691432007-10-28 12:59:45 +00004290 Alignment = MinAlign(Alignment, 4U);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004291 SDOperand St1 = DAG.getStore(Chain, Hi, Ptr, ST->getSrcValue(),
4292 SVOffset, isVolatile, Alignment);
4293 return DAG.getNode(ISD::TokenFactor, MVT::Other, St0, St1);
4294 }
4295 break;
4296 }
4297 }
4298 }
4299
4300 if (CombinerAA) {
4301 // Walk up chain skipping non-aliasing memory nodes.
4302 SDOperand BetterChain = FindBetterChain(N, Chain);
4303
4304 // If there is a better chain.
4305 if (Chain != BetterChain) {
4306 // Replace the chain to avoid dependency.
4307 SDOperand ReplStore;
4308 if (ST->isTruncatingStore()) {
4309 ReplStore = DAG.getTruncStore(BetterChain, Value, Ptr,
Chris Lattner667f9c12008-01-17 07:20:38 +00004310 ST->getSrcValue(),ST->getSrcValueOffset(),
4311 ST->getStoredVT(),
4312 ST->isVolatile(), ST->getAlignment());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004313 } else {
4314 ReplStore = DAG.getStore(BetterChain, Value, Ptr,
Chris Lattner667f9c12008-01-17 07:20:38 +00004315 ST->getSrcValue(), ST->getSrcValueOffset(),
4316 ST->isVolatile(), ST->getAlignment());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004317 }
4318
4319 // Create token to keep both nodes around.
4320 SDOperand Token =
4321 DAG.getNode(ISD::TokenFactor, MVT::Other, Chain, ReplStore);
4322
4323 // Don't add users to work list.
4324 return CombineTo(N, Token, false);
4325 }
4326 }
4327
4328 // Try transforming N to an indexed store.
4329 if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
4330 return SDOperand(N, 0);
4331
Chris Lattner447d8e82007-12-29 06:26:16 +00004332 // FIXME: is there such a thing as a truncating indexed store?
Chris Lattner3bc08502008-01-17 19:59:44 +00004333 if (ST->isTruncatingStore() && ST->isUnindexed() &&
Chris Lattnere8671c52007-10-13 06:35:54 +00004334 MVT::isInteger(Value.getValueType())) {
4335 // See if we can simplify the input to this truncstore with knowledge that
4336 // only the low bits are being used. For example:
4337 // "truncstore (or (shl x, 8), y), i8" -> "truncstore y, i8"
4338 SDOperand Shorter =
4339 GetDemandedBits(Value, MVT::getIntVTBitMask(ST->getStoredVT()));
4340 AddToWorkList(Value.Val);
4341 if (Shorter.Val)
4342 return DAG.getTruncStore(Chain, Shorter, Ptr, ST->getSrcValue(),
4343 ST->getSrcValueOffset(), ST->getStoredVT(),
4344 ST->isVolatile(), ST->getAlignment());
Chris Lattnerb77ea552007-10-13 06:58:48 +00004345
4346 // Otherwise, see if we can simplify the operation with
4347 // SimplifyDemandedBits, which only works if the value has a single use.
4348 if (SimplifyDemandedBits(Value, MVT::getIntVTBitMask(ST->getStoredVT())))
4349 return SDOperand(N, 0);
Chris Lattnere8671c52007-10-13 06:35:54 +00004350 }
4351
Chris Lattner447d8e82007-12-29 06:26:16 +00004352 // If this is a load followed by a store to the same location, then the store
4353 // is dead/noop.
4354 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Value)) {
Chris Lattner2e023772008-01-08 23:08:06 +00004355 if (Ld->getBasePtr() == Ptr && ST->getStoredVT() == Ld->getLoadedVT() &&
Chris Lattner3bc08502008-01-17 19:59:44 +00004356 ST->isUnindexed() && !ST->isVolatile() &&
Chris Lattner2e023772008-01-08 23:08:06 +00004357 // There can't be any side effects between the load and store, such as
4358 // a call or store.
Chris Lattner10d94f92008-01-16 05:49:24 +00004359 Chain.reachesChainWithoutSideEffects(SDOperand(Ld, 1))) {
Chris Lattner447d8e82007-12-29 06:26:16 +00004360 // The store is dead, remove it.
4361 return Chain;
4362 }
4363 }
4364
Chris Lattner3bc08502008-01-17 19:59:44 +00004365 // If this is an FP_ROUND or TRUNC followed by a store, fold this into a
4366 // truncating store. We can do this even if this is already a truncstore.
4367 if ((Value.getOpcode() == ISD::FP_ROUND || Value.getOpcode() == ISD::TRUNCATE)
4368 && TLI.isTypeLegal(Value.getOperand(0).getValueType()) &&
4369 Value.Val->hasOneUse() && ST->isUnindexed() &&
4370 TLI.isTruncStoreLegal(Value.getOperand(0).getValueType(),
4371 ST->getStoredVT())) {
4372 return DAG.getTruncStore(Chain, Value.getOperand(0), Ptr, ST->getSrcValue(),
4373 ST->getSrcValueOffset(), ST->getStoredVT(),
4374 ST->isVolatile(), ST->getAlignment());
4375 }
4376
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004377 return SDOperand();
4378}
4379
4380SDOperand DAGCombiner::visitINSERT_VECTOR_ELT(SDNode *N) {
4381 SDOperand InVec = N->getOperand(0);
4382 SDOperand InVal = N->getOperand(1);
4383 SDOperand EltNo = N->getOperand(2);
4384
4385 // If the invec is a BUILD_VECTOR and if EltNo is a constant, build a new
4386 // vector with the inserted element.
4387 if (InVec.getOpcode() == ISD::BUILD_VECTOR && isa<ConstantSDNode>(EltNo)) {
4388 unsigned Elt = cast<ConstantSDNode>(EltNo)->getValue();
4389 SmallVector<SDOperand, 8> Ops(InVec.Val->op_begin(), InVec.Val->op_end());
4390 if (Elt < Ops.size())
4391 Ops[Elt] = InVal;
4392 return DAG.getNode(ISD::BUILD_VECTOR, InVec.getValueType(),
4393 &Ops[0], Ops.size());
4394 }
4395
4396 return SDOperand();
4397}
4398
Evan Chengd7ba7ed2007-10-06 08:19:55 +00004399SDOperand DAGCombiner::visitEXTRACT_VECTOR_ELT(SDNode *N) {
4400 SDOperand InVec = N->getOperand(0);
4401 SDOperand EltNo = N->getOperand(1);
4402
4403 // (vextract (v4f32 s2v (f32 load $addr)), 0) -> (f32 load $addr)
4404 // (vextract (v4i32 bc (v4f32 s2v (f32 load $addr))), 0) -> (i32 load $addr)
4405 if (isa<ConstantSDNode>(EltNo)) {
4406 unsigned Elt = cast<ConstantSDNode>(EltNo)->getValue();
4407 bool NewLoad = false;
4408 if (Elt == 0) {
4409 MVT::ValueType VT = InVec.getValueType();
4410 MVT::ValueType EVT = MVT::getVectorElementType(VT);
4411 MVT::ValueType LVT = EVT;
4412 unsigned NumElts = MVT::getVectorNumElements(VT);
4413 if (InVec.getOpcode() == ISD::BIT_CONVERT) {
4414 MVT::ValueType BCVT = InVec.getOperand(0).getValueType();
Dan Gohmana3591d92007-10-29 20:44:42 +00004415 if (!MVT::isVector(BCVT) ||
4416 NumElts != MVT::getVectorNumElements(BCVT))
Evan Chengd7ba7ed2007-10-06 08:19:55 +00004417 return SDOperand();
4418 InVec = InVec.getOperand(0);
4419 EVT = MVT::getVectorElementType(BCVT);
4420 NewLoad = true;
4421 }
4422 if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR &&
4423 InVec.getOperand(0).getValueType() == EVT &&
4424 ISD::isNormalLoad(InVec.getOperand(0).Val) &&
4425 InVec.getOperand(0).hasOneUse()) {
4426 LoadSDNode *LN0 = cast<LoadSDNode>(InVec.getOperand(0));
4427 unsigned Align = LN0->getAlignment();
4428 if (NewLoad) {
4429 // Check the resultant load doesn't need a higher alignment than the
4430 // original load.
4431 unsigned NewAlign = TLI.getTargetMachine().getTargetData()->
4432 getABITypeAlignment(MVT::getTypeForValueType(LVT));
4433 if (!TLI.isOperationLegal(ISD::LOAD, LVT) || NewAlign > Align)
4434 return SDOperand();
4435 Align = NewAlign;
4436 }
4437
4438 return DAG.getLoad(LVT, LN0->getChain(), LN0->getBasePtr(),
4439 LN0->getSrcValue(), LN0->getSrcValueOffset(),
4440 LN0->isVolatile(), Align);
4441 }
4442 }
4443 }
4444 return SDOperand();
4445}
4446
4447
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004448SDOperand DAGCombiner::visitBUILD_VECTOR(SDNode *N) {
4449 unsigned NumInScalars = N->getNumOperands();
4450 MVT::ValueType VT = N->getValueType(0);
4451 unsigned NumElts = MVT::getVectorNumElements(VT);
4452 MVT::ValueType EltType = MVT::getVectorElementType(VT);
4453
4454 // Check to see if this is a BUILD_VECTOR of a bunch of EXTRACT_VECTOR_ELT
4455 // operations. If so, and if the EXTRACT_VECTOR_ELT vector inputs come from
4456 // at most two distinct vectors, turn this into a shuffle node.
4457 SDOperand VecIn1, VecIn2;
4458 for (unsigned i = 0; i != NumInScalars; ++i) {
4459 // Ignore undef inputs.
4460 if (N->getOperand(i).getOpcode() == ISD::UNDEF) continue;
4461
4462 // If this input is something other than a EXTRACT_VECTOR_ELT with a
4463 // constant index, bail out.
4464 if (N->getOperand(i).getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
4465 !isa<ConstantSDNode>(N->getOperand(i).getOperand(1))) {
4466 VecIn1 = VecIn2 = SDOperand(0, 0);
4467 break;
4468 }
4469
4470 // If the input vector type disagrees with the result of the build_vector,
4471 // we can't make a shuffle.
4472 SDOperand ExtractedFromVec = N->getOperand(i).getOperand(0);
4473 if (ExtractedFromVec.getValueType() != VT) {
4474 VecIn1 = VecIn2 = SDOperand(0, 0);
4475 break;
4476 }
4477
4478 // Otherwise, remember this. We allow up to two distinct input vectors.
4479 if (ExtractedFromVec == VecIn1 || ExtractedFromVec == VecIn2)
4480 continue;
4481
4482 if (VecIn1.Val == 0) {
4483 VecIn1 = ExtractedFromVec;
4484 } else if (VecIn2.Val == 0) {
4485 VecIn2 = ExtractedFromVec;
4486 } else {
4487 // Too many inputs.
4488 VecIn1 = VecIn2 = SDOperand(0, 0);
4489 break;
4490 }
4491 }
4492
4493 // If everything is good, we can make a shuffle operation.
4494 if (VecIn1.Val) {
4495 SmallVector<SDOperand, 8> BuildVecIndices;
4496 for (unsigned i = 0; i != NumInScalars; ++i) {
4497 if (N->getOperand(i).getOpcode() == ISD::UNDEF) {
4498 BuildVecIndices.push_back(DAG.getNode(ISD::UNDEF, TLI.getPointerTy()));
4499 continue;
4500 }
4501
4502 SDOperand Extract = N->getOperand(i);
4503
4504 // If extracting from the first vector, just use the index directly.
4505 if (Extract.getOperand(0) == VecIn1) {
4506 BuildVecIndices.push_back(Extract.getOperand(1));
4507 continue;
4508 }
4509
4510 // Otherwise, use InIdx + VecSize
4511 unsigned Idx = cast<ConstantSDNode>(Extract.getOperand(1))->getValue();
Chris Lattner5872a362008-01-17 07:00:52 +00004512 BuildVecIndices.push_back(DAG.getIntPtrConstant(Idx+NumInScalars));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004513 }
4514
4515 // Add count and size info.
Chris Lattner5872a362008-01-17 07:00:52 +00004516 MVT::ValueType BuildVecVT = MVT::getVectorType(TLI.getPointerTy(), NumElts);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004517
4518 // Return the new VECTOR_SHUFFLE node.
4519 SDOperand Ops[5];
4520 Ops[0] = VecIn1;
4521 if (VecIn2.Val) {
4522 Ops[1] = VecIn2;
4523 } else {
4524 // Use an undef build_vector as input for the second operand.
4525 std::vector<SDOperand> UnOps(NumInScalars,
4526 DAG.getNode(ISD::UNDEF,
4527 EltType));
4528 Ops[1] = DAG.getNode(ISD::BUILD_VECTOR, VT,
4529 &UnOps[0], UnOps.size());
4530 AddToWorkList(Ops[1].Val);
4531 }
4532 Ops[2] = DAG.getNode(ISD::BUILD_VECTOR, BuildVecVT,
4533 &BuildVecIndices[0], BuildVecIndices.size());
4534 return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, Ops, 3);
4535 }
4536
4537 return SDOperand();
4538}
4539
4540SDOperand DAGCombiner::visitCONCAT_VECTORS(SDNode *N) {
4541 // TODO: Check to see if this is a CONCAT_VECTORS of a bunch of
4542 // EXTRACT_SUBVECTOR operations. If so, and if the EXTRACT_SUBVECTOR vector
4543 // inputs come from at most two distinct vectors, turn this into a shuffle
4544 // node.
4545
4546 // If we only have one input vector, we don't need to do any concatenation.
4547 if (N->getNumOperands() == 1) {
4548 return N->getOperand(0);
4549 }
4550
4551 return SDOperand();
4552}
4553
4554SDOperand DAGCombiner::visitVECTOR_SHUFFLE(SDNode *N) {
4555 SDOperand ShufMask = N->getOperand(2);
4556 unsigned NumElts = ShufMask.getNumOperands();
4557
4558 // If the shuffle mask is an identity operation on the LHS, return the LHS.
4559 bool isIdentity = true;
4560 for (unsigned i = 0; i != NumElts; ++i) {
4561 if (ShufMask.getOperand(i).getOpcode() != ISD::UNDEF &&
4562 cast<ConstantSDNode>(ShufMask.getOperand(i))->getValue() != i) {
4563 isIdentity = false;
4564 break;
4565 }
4566 }
4567 if (isIdentity) return N->getOperand(0);
4568
4569 // If the shuffle mask is an identity operation on the RHS, return the RHS.
4570 isIdentity = true;
4571 for (unsigned i = 0; i != NumElts; ++i) {
4572 if (ShufMask.getOperand(i).getOpcode() != ISD::UNDEF &&
4573 cast<ConstantSDNode>(ShufMask.getOperand(i))->getValue() != i+NumElts) {
4574 isIdentity = false;
4575 break;
4576 }
4577 }
4578 if (isIdentity) return N->getOperand(1);
4579
4580 // Check if the shuffle is a unary shuffle, i.e. one of the vectors is not
4581 // needed at all.
4582 bool isUnary = true;
4583 bool isSplat = true;
4584 int VecNum = -1;
4585 unsigned BaseIdx = 0;
4586 for (unsigned i = 0; i != NumElts; ++i)
4587 if (ShufMask.getOperand(i).getOpcode() != ISD::UNDEF) {
4588 unsigned Idx = cast<ConstantSDNode>(ShufMask.getOperand(i))->getValue();
4589 int V = (Idx < NumElts) ? 0 : 1;
4590 if (VecNum == -1) {
4591 VecNum = V;
4592 BaseIdx = Idx;
4593 } else {
4594 if (BaseIdx != Idx)
4595 isSplat = false;
4596 if (VecNum != V) {
4597 isUnary = false;
4598 break;
4599 }
4600 }
4601 }
4602
4603 SDOperand N0 = N->getOperand(0);
4604 SDOperand N1 = N->getOperand(1);
4605 // Normalize unary shuffle so the RHS is undef.
4606 if (isUnary && VecNum == 1)
4607 std::swap(N0, N1);
4608
4609 // If it is a splat, check if the argument vector is a build_vector with
4610 // all scalar elements the same.
4611 if (isSplat) {
4612 SDNode *V = N0.Val;
4613
4614 // If this is a bit convert that changes the element type of the vector but
4615 // not the number of vector elements, look through it. Be careful not to
4616 // look though conversions that change things like v4f32 to v2f64.
4617 if (V->getOpcode() == ISD::BIT_CONVERT) {
4618 SDOperand ConvInput = V->getOperand(0);
4619 if (MVT::getVectorNumElements(ConvInput.getValueType()) == NumElts)
4620 V = ConvInput.Val;
4621 }
4622
4623 if (V->getOpcode() == ISD::BUILD_VECTOR) {
4624 unsigned NumElems = V->getNumOperands();
4625 if (NumElems > BaseIdx) {
4626 SDOperand Base;
4627 bool AllSame = true;
4628 for (unsigned i = 0; i != NumElems; ++i) {
4629 if (V->getOperand(i).getOpcode() != ISD::UNDEF) {
4630 Base = V->getOperand(i);
4631 break;
4632 }
4633 }
4634 // Splat of <u, u, u, u>, return <u, u, u, u>
4635 if (!Base.Val)
4636 return N0;
4637 for (unsigned i = 0; i != NumElems; ++i) {
Evan Cheng8d68c2b2007-09-18 21:54:37 +00004638 if (V->getOperand(i) != Base) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004639 AllSame = false;
4640 break;
4641 }
4642 }
4643 // Splat of <x, x, x, x>, return <x, x, x, x>
4644 if (AllSame)
4645 return N0;
4646 }
4647 }
4648 }
4649
4650 // If it is a unary or the LHS and the RHS are the same node, turn the RHS
4651 // into an undef.
4652 if (isUnary || N0 == N1) {
4653 // Check the SHUFFLE mask, mapping any inputs from the 2nd operand into the
4654 // first operand.
4655 SmallVector<SDOperand, 8> MappedOps;
4656 for (unsigned i = 0; i != NumElts; ++i) {
4657 if (ShufMask.getOperand(i).getOpcode() == ISD::UNDEF ||
4658 cast<ConstantSDNode>(ShufMask.getOperand(i))->getValue() < NumElts) {
4659 MappedOps.push_back(ShufMask.getOperand(i));
4660 } else {
4661 unsigned NewIdx =
4662 cast<ConstantSDNode>(ShufMask.getOperand(i))->getValue() - NumElts;
4663 MappedOps.push_back(DAG.getConstant(NewIdx, MVT::i32));
4664 }
4665 }
4666 ShufMask = DAG.getNode(ISD::BUILD_VECTOR, ShufMask.getValueType(),
4667 &MappedOps[0], MappedOps.size());
4668 AddToWorkList(ShufMask.Val);
4669 return DAG.getNode(ISD::VECTOR_SHUFFLE, N->getValueType(0),
4670 N0,
4671 DAG.getNode(ISD::UNDEF, N->getValueType(0)),
4672 ShufMask);
4673 }
4674
4675 return SDOperand();
4676}
4677
4678/// XformToShuffleWithZero - Returns a vector_shuffle if it able to transform
4679/// an AND to a vector_shuffle with the destination vector and a zero vector.
4680/// e.g. AND V, <0xffffffff, 0, 0xffffffff, 0>. ==>
4681/// vector_shuffle V, Zero, <0, 4, 2, 4>
4682SDOperand DAGCombiner::XformToShuffleWithZero(SDNode *N) {
4683 SDOperand LHS = N->getOperand(0);
4684 SDOperand RHS = N->getOperand(1);
4685 if (N->getOpcode() == ISD::AND) {
4686 if (RHS.getOpcode() == ISD::BIT_CONVERT)
4687 RHS = RHS.getOperand(0);
4688 if (RHS.getOpcode() == ISD::BUILD_VECTOR) {
4689 std::vector<SDOperand> IdxOps;
4690 unsigned NumOps = RHS.getNumOperands();
4691 unsigned NumElts = NumOps;
4692 MVT::ValueType EVT = MVT::getVectorElementType(RHS.getValueType());
4693 for (unsigned i = 0; i != NumElts; ++i) {
4694 SDOperand Elt = RHS.getOperand(i);
4695 if (!isa<ConstantSDNode>(Elt))
4696 return SDOperand();
4697 else if (cast<ConstantSDNode>(Elt)->isAllOnesValue())
4698 IdxOps.push_back(DAG.getConstant(i, EVT));
4699 else if (cast<ConstantSDNode>(Elt)->isNullValue())
4700 IdxOps.push_back(DAG.getConstant(NumElts, EVT));
4701 else
4702 return SDOperand();
4703 }
4704
4705 // Let's see if the target supports this vector_shuffle.
4706 if (!TLI.isVectorClearMaskLegal(IdxOps, EVT, DAG))
4707 return SDOperand();
4708
4709 // Return the new VECTOR_SHUFFLE node.
4710 MVT::ValueType VT = MVT::getVectorType(EVT, NumElts);
4711 std::vector<SDOperand> Ops;
4712 LHS = DAG.getNode(ISD::BIT_CONVERT, VT, LHS);
4713 Ops.push_back(LHS);
4714 AddToWorkList(LHS.Val);
4715 std::vector<SDOperand> ZeroOps(NumElts, DAG.getConstant(0, EVT));
4716 Ops.push_back(DAG.getNode(ISD::BUILD_VECTOR, VT,
4717 &ZeroOps[0], ZeroOps.size()));
4718 Ops.push_back(DAG.getNode(ISD::BUILD_VECTOR, VT,
4719 &IdxOps[0], IdxOps.size()));
4720 SDOperand Result = DAG.getNode(ISD::VECTOR_SHUFFLE, VT,
4721 &Ops[0], Ops.size());
4722 if (VT != LHS.getValueType()) {
4723 Result = DAG.getNode(ISD::BIT_CONVERT, LHS.getValueType(), Result);
4724 }
4725 return Result;
4726 }
4727 }
4728 return SDOperand();
4729}
4730
4731/// SimplifyVBinOp - Visit a binary vector operation, like ADD.
4732SDOperand DAGCombiner::SimplifyVBinOp(SDNode *N) {
4733 // After legalize, the target may be depending on adds and other
4734 // binary ops to provide legal ways to construct constants or other
4735 // things. Simplifying them may result in a loss of legality.
4736 if (AfterLegalize) return SDOperand();
4737
4738 MVT::ValueType VT = N->getValueType(0);
4739 assert(MVT::isVector(VT) && "SimplifyVBinOp only works on vectors!");
4740
4741 MVT::ValueType EltType = MVT::getVectorElementType(VT);
4742 SDOperand LHS = N->getOperand(0);
4743 SDOperand RHS = N->getOperand(1);
4744 SDOperand Shuffle = XformToShuffleWithZero(N);
4745 if (Shuffle.Val) return Shuffle;
4746
4747 // If the LHS and RHS are BUILD_VECTOR nodes, see if we can constant fold
4748 // this operation.
4749 if (LHS.getOpcode() == ISD::BUILD_VECTOR &&
4750 RHS.getOpcode() == ISD::BUILD_VECTOR) {
4751 SmallVector<SDOperand, 8> Ops;
4752 for (unsigned i = 0, e = LHS.getNumOperands(); i != e; ++i) {
4753 SDOperand LHSOp = LHS.getOperand(i);
4754 SDOperand RHSOp = RHS.getOperand(i);
4755 // If these two elements can't be folded, bail out.
4756 if ((LHSOp.getOpcode() != ISD::UNDEF &&
4757 LHSOp.getOpcode() != ISD::Constant &&
4758 LHSOp.getOpcode() != ISD::ConstantFP) ||
4759 (RHSOp.getOpcode() != ISD::UNDEF &&
4760 RHSOp.getOpcode() != ISD::Constant &&
4761 RHSOp.getOpcode() != ISD::ConstantFP))
4762 break;
4763 // Can't fold divide by zero.
4764 if (N->getOpcode() == ISD::SDIV || N->getOpcode() == ISD::UDIV ||
4765 N->getOpcode() == ISD::FDIV) {
4766 if ((RHSOp.getOpcode() == ISD::Constant &&
4767 cast<ConstantSDNode>(RHSOp.Val)->isNullValue()) ||
4768 (RHSOp.getOpcode() == ISD::ConstantFP &&
Dale Johannesen7604c1b2007-08-31 23:34:27 +00004769 cast<ConstantFPSDNode>(RHSOp.Val)->getValueAPF().isZero()))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004770 break;
4771 }
4772 Ops.push_back(DAG.getNode(N->getOpcode(), EltType, LHSOp, RHSOp));
4773 AddToWorkList(Ops.back().Val);
4774 assert((Ops.back().getOpcode() == ISD::UNDEF ||
4775 Ops.back().getOpcode() == ISD::Constant ||
4776 Ops.back().getOpcode() == ISD::ConstantFP) &&
4777 "Scalar binop didn't fold!");
4778 }
4779
4780 if (Ops.size() == LHS.getNumOperands()) {
4781 MVT::ValueType VT = LHS.getValueType();
4782 return DAG.getNode(ISD::BUILD_VECTOR, VT, &Ops[0], Ops.size());
4783 }
4784 }
4785
4786 return SDOperand();
4787}
4788
4789SDOperand DAGCombiner::SimplifySelect(SDOperand N0, SDOperand N1, SDOperand N2){
4790 assert(N0.getOpcode() ==ISD::SETCC && "First argument must be a SetCC node!");
4791
4792 SDOperand SCC = SimplifySelectCC(N0.getOperand(0), N0.getOperand(1), N1, N2,
4793 cast<CondCodeSDNode>(N0.getOperand(2))->get());
4794 // If we got a simplified select_cc node back from SimplifySelectCC, then
4795 // break it down into a new SETCC node, and a new SELECT node, and then return
4796 // the SELECT node, since we were called with a SELECT node.
4797 if (SCC.Val) {
4798 // Check to see if we got a select_cc back (to turn into setcc/select).
4799 // Otherwise, just return whatever node we got back, like fabs.
4800 if (SCC.getOpcode() == ISD::SELECT_CC) {
4801 SDOperand SETCC = DAG.getNode(ISD::SETCC, N0.getValueType(),
4802 SCC.getOperand(0), SCC.getOperand(1),
4803 SCC.getOperand(4));
4804 AddToWorkList(SETCC.Val);
4805 return DAG.getNode(ISD::SELECT, SCC.getValueType(), SCC.getOperand(2),
4806 SCC.getOperand(3), SETCC);
4807 }
4808 return SCC;
4809 }
4810 return SDOperand();
4811}
4812
4813/// SimplifySelectOps - Given a SELECT or a SELECT_CC node, where LHS and RHS
4814/// are the two values being selected between, see if we can simplify the
4815/// select. Callers of this should assume that TheSelect is deleted if this
4816/// returns true. As such, they should return the appropriate thing (e.g. the
4817/// node) back to the top-level of the DAG combiner loop to avoid it being
4818/// looked at.
4819///
4820bool DAGCombiner::SimplifySelectOps(SDNode *TheSelect, SDOperand LHS,
4821 SDOperand RHS) {
4822
4823 // If this is a select from two identical things, try to pull the operation
4824 // through the select.
4825 if (LHS.getOpcode() == RHS.getOpcode() && LHS.hasOneUse() && RHS.hasOneUse()){
4826 // If this is a load and the token chain is identical, replace the select
4827 // of two loads with a load through a select of the address to load from.
4828 // This triggers in things like "select bool X, 10.0, 123.0" after the FP
4829 // constants have been dropped into the constant pool.
4830 if (LHS.getOpcode() == ISD::LOAD &&
4831 // Token chains must be identical.
4832 LHS.getOperand(0) == RHS.getOperand(0)) {
4833 LoadSDNode *LLD = cast<LoadSDNode>(LHS);
4834 LoadSDNode *RLD = cast<LoadSDNode>(RHS);
4835
4836 // If this is an EXTLOAD, the VT's must match.
4837 if (LLD->getLoadedVT() == RLD->getLoadedVT()) {
4838 // FIXME: this conflates two src values, discarding one. This is not
4839 // the right thing to do, but nothing uses srcvalues now. When they do,
4840 // turn SrcValue into a list of locations.
4841 SDOperand Addr;
4842 if (TheSelect->getOpcode() == ISD::SELECT) {
4843 // Check that the condition doesn't reach either load. If so, folding
4844 // this will induce a cycle into the DAG.
4845 if (!LLD->isPredecessor(TheSelect->getOperand(0).Val) &&
4846 !RLD->isPredecessor(TheSelect->getOperand(0).Val)) {
4847 Addr = DAG.getNode(ISD::SELECT, LLD->getBasePtr().getValueType(),
4848 TheSelect->getOperand(0), LLD->getBasePtr(),
4849 RLD->getBasePtr());
4850 }
4851 } else {
4852 // Check that the condition doesn't reach either load. If so, folding
4853 // this will induce a cycle into the DAG.
4854 if (!LLD->isPredecessor(TheSelect->getOperand(0).Val) &&
4855 !RLD->isPredecessor(TheSelect->getOperand(0).Val) &&
4856 !LLD->isPredecessor(TheSelect->getOperand(1).Val) &&
4857 !RLD->isPredecessor(TheSelect->getOperand(1).Val)) {
4858 Addr = DAG.getNode(ISD::SELECT_CC, LLD->getBasePtr().getValueType(),
4859 TheSelect->getOperand(0),
4860 TheSelect->getOperand(1),
4861 LLD->getBasePtr(), RLD->getBasePtr(),
4862 TheSelect->getOperand(4));
4863 }
4864 }
4865
4866 if (Addr.Val) {
4867 SDOperand Load;
4868 if (LLD->getExtensionType() == ISD::NON_EXTLOAD)
4869 Load = DAG.getLoad(TheSelect->getValueType(0), LLD->getChain(),
4870 Addr,LLD->getSrcValue(),
4871 LLD->getSrcValueOffset(),
4872 LLD->isVolatile(),
4873 LLD->getAlignment());
4874 else {
4875 Load = DAG.getExtLoad(LLD->getExtensionType(),
4876 TheSelect->getValueType(0),
4877 LLD->getChain(), Addr, LLD->getSrcValue(),
4878 LLD->getSrcValueOffset(),
4879 LLD->getLoadedVT(),
4880 LLD->isVolatile(),
4881 LLD->getAlignment());
4882 }
4883 // Users of the select now use the result of the load.
4884 CombineTo(TheSelect, Load);
4885
4886 // Users of the old loads now use the new load's chain. We know the
4887 // old-load value is dead now.
4888 CombineTo(LHS.Val, Load.getValue(0), Load.getValue(1));
4889 CombineTo(RHS.Val, Load.getValue(0), Load.getValue(1));
4890 return true;
4891 }
4892 }
4893 }
4894 }
4895
4896 return false;
4897}
4898
4899SDOperand DAGCombiner::SimplifySelectCC(SDOperand N0, SDOperand N1,
4900 SDOperand N2, SDOperand N3,
4901 ISD::CondCode CC, bool NotExtCompare) {
4902
4903 MVT::ValueType VT = N2.getValueType();
4904 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.Val);
4905 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2.Val);
4906 ConstantSDNode *N3C = dyn_cast<ConstantSDNode>(N3.Val);
4907
4908 // Determine if the condition we're dealing with is constant
4909 SDOperand SCC = SimplifySetCC(TLI.getSetCCResultTy(), N0, N1, CC, false);
4910 if (SCC.Val) AddToWorkList(SCC.Val);
4911 ConstantSDNode *SCCC = dyn_cast_or_null<ConstantSDNode>(SCC.Val);
4912
4913 // fold select_cc true, x, y -> x
4914 if (SCCC && SCCC->getValue())
4915 return N2;
4916 // fold select_cc false, x, y -> y
4917 if (SCCC && SCCC->getValue() == 0)
4918 return N3;
4919
4920 // Check to see if we can simplify the select into an fabs node
4921 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N1)) {
4922 // Allow either -0.0 or 0.0
Dale Johannesen7f2c1d12007-08-25 22:10:57 +00004923 if (CFP->getValueAPF().isZero()) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004924 // select (setg[te] X, +/-0.0), X, fneg(X) -> fabs
4925 if ((CC == ISD::SETGE || CC == ISD::SETGT) &&
4926 N0 == N2 && N3.getOpcode() == ISD::FNEG &&
4927 N2 == N3.getOperand(0))
4928 return DAG.getNode(ISD::FABS, VT, N0);
4929
4930 // select (setl[te] X, +/-0.0), fneg(X), X -> fabs
4931 if ((CC == ISD::SETLT || CC == ISD::SETLE) &&
4932 N0 == N3 && N2.getOpcode() == ISD::FNEG &&
4933 N2.getOperand(0) == N3)
4934 return DAG.getNode(ISD::FABS, VT, N3);
4935 }
4936 }
4937
4938 // Check to see if we can perform the "gzip trick", transforming
4939 // select_cc setlt X, 0, A, 0 -> and (sra X, size(X)-1), A
4940 if (N1C && N3C && N3C->isNullValue() && CC == ISD::SETLT &&
4941 MVT::isInteger(N0.getValueType()) &&
4942 MVT::isInteger(N2.getValueType()) &&
4943 (N1C->isNullValue() || // (a < 0) ? b : 0
4944 (N1C->getValue() == 1 && N0 == N2))) { // (a < 1) ? a : 0
4945 MVT::ValueType XType = N0.getValueType();
4946 MVT::ValueType AType = N2.getValueType();
4947 if (XType >= AType) {
4948 // and (sra X, size(X)-1, A) -> "and (srl X, C2), A" iff A is a
4949 // single-bit constant.
4950 if (N2C && ((N2C->getValue() & (N2C->getValue()-1)) == 0)) {
4951 unsigned ShCtV = Log2_64(N2C->getValue());
4952 ShCtV = MVT::getSizeInBits(XType)-ShCtV-1;
4953 SDOperand ShCt = DAG.getConstant(ShCtV, TLI.getShiftAmountTy());
4954 SDOperand Shift = DAG.getNode(ISD::SRL, XType, N0, ShCt);
4955 AddToWorkList(Shift.Val);
4956 if (XType > AType) {
4957 Shift = DAG.getNode(ISD::TRUNCATE, AType, Shift);
4958 AddToWorkList(Shift.Val);
4959 }
4960 return DAG.getNode(ISD::AND, AType, Shift, N2);
4961 }
4962 SDOperand Shift = DAG.getNode(ISD::SRA, XType, N0,
4963 DAG.getConstant(MVT::getSizeInBits(XType)-1,
4964 TLI.getShiftAmountTy()));
4965 AddToWorkList(Shift.Val);
4966 if (XType > AType) {
4967 Shift = DAG.getNode(ISD::TRUNCATE, AType, Shift);
4968 AddToWorkList(Shift.Val);
4969 }
4970 return DAG.getNode(ISD::AND, AType, Shift, N2);
4971 }
4972 }
4973
4974 // fold select C, 16, 0 -> shl C, 4
4975 if (N2C && N3C && N3C->isNullValue() && isPowerOf2_64(N2C->getValue()) &&
4976 TLI.getSetCCResultContents() == TargetLowering::ZeroOrOneSetCCResult) {
4977
4978 // If the caller doesn't want us to simplify this into a zext of a compare,
4979 // don't do it.
4980 if (NotExtCompare && N2C->getValue() == 1)
4981 return SDOperand();
4982
4983 // Get a SetCC of the condition
4984 // FIXME: Should probably make sure that setcc is legal if we ever have a
4985 // target where it isn't.
4986 SDOperand Temp, SCC;
4987 // cast from setcc result type to select result type
4988 if (AfterLegalize) {
4989 SCC = DAG.getSetCC(TLI.getSetCCResultTy(), N0, N1, CC);
4990 if (N2.getValueType() < SCC.getValueType())
4991 Temp = DAG.getZeroExtendInReg(SCC, N2.getValueType());
4992 else
4993 Temp = DAG.getNode(ISD::ZERO_EXTEND, N2.getValueType(), SCC);
4994 } else {
4995 SCC = DAG.getSetCC(MVT::i1, N0, N1, CC);
4996 Temp = DAG.getNode(ISD::ZERO_EXTEND, N2.getValueType(), SCC);
4997 }
4998 AddToWorkList(SCC.Val);
4999 AddToWorkList(Temp.Val);
5000
5001 if (N2C->getValue() == 1)
5002 return Temp;
5003 // shl setcc result by log2 n2c
5004 return DAG.getNode(ISD::SHL, N2.getValueType(), Temp,
5005 DAG.getConstant(Log2_64(N2C->getValue()),
5006 TLI.getShiftAmountTy()));
5007 }
5008
5009 // Check to see if this is the equivalent of setcc
5010 // FIXME: Turn all of these into setcc if setcc if setcc is legal
5011 // otherwise, go ahead with the folds.
5012 if (0 && N3C && N3C->isNullValue() && N2C && (N2C->getValue() == 1ULL)) {
5013 MVT::ValueType XType = N0.getValueType();
5014 if (TLI.isOperationLegal(ISD::SETCC, TLI.getSetCCResultTy())) {
5015 SDOperand Res = DAG.getSetCC(TLI.getSetCCResultTy(), N0, N1, CC);
5016 if (Res.getValueType() != VT)
5017 Res = DAG.getNode(ISD::ZERO_EXTEND, VT, Res);
5018 return Res;
5019 }
5020
5021 // seteq X, 0 -> srl (ctlz X, log2(size(X)))
5022 if (N1C && N1C->isNullValue() && CC == ISD::SETEQ &&
5023 TLI.isOperationLegal(ISD::CTLZ, XType)) {
5024 SDOperand Ctlz = DAG.getNode(ISD::CTLZ, XType, N0);
5025 return DAG.getNode(ISD::SRL, XType, Ctlz,
5026 DAG.getConstant(Log2_32(MVT::getSizeInBits(XType)),
5027 TLI.getShiftAmountTy()));
5028 }
5029 // setgt X, 0 -> srl (and (-X, ~X), size(X)-1)
5030 if (N1C && N1C->isNullValue() && CC == ISD::SETGT) {
5031 SDOperand NegN0 = DAG.getNode(ISD::SUB, XType, DAG.getConstant(0, XType),
5032 N0);
5033 SDOperand NotN0 = DAG.getNode(ISD::XOR, XType, N0,
5034 DAG.getConstant(~0ULL, XType));
5035 return DAG.getNode(ISD::SRL, XType,
5036 DAG.getNode(ISD::AND, XType, NegN0, NotN0),
5037 DAG.getConstant(MVT::getSizeInBits(XType)-1,
5038 TLI.getShiftAmountTy()));
5039 }
5040 // setgt X, -1 -> xor (srl (X, size(X)-1), 1)
5041 if (N1C && N1C->isAllOnesValue() && CC == ISD::SETGT) {
5042 SDOperand Sign = DAG.getNode(ISD::SRL, XType, N0,
5043 DAG.getConstant(MVT::getSizeInBits(XType)-1,
5044 TLI.getShiftAmountTy()));
5045 return DAG.getNode(ISD::XOR, XType, Sign, DAG.getConstant(1, XType));
5046 }
5047 }
5048
5049 // Check to see if this is an integer abs. select_cc setl[te] X, 0, -X, X ->
5050 // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
5051 if (N1C && N1C->isNullValue() && (CC == ISD::SETLT || CC == ISD::SETLE) &&
5052 N0 == N3 && N2.getOpcode() == ISD::SUB && N0 == N2.getOperand(1) &&
5053 N2.getOperand(0) == N1 && MVT::isInteger(N0.getValueType())) {
5054 MVT::ValueType XType = N0.getValueType();
5055 SDOperand Shift = DAG.getNode(ISD::SRA, XType, N0,
5056 DAG.getConstant(MVT::getSizeInBits(XType)-1,
5057 TLI.getShiftAmountTy()));
5058 SDOperand Add = DAG.getNode(ISD::ADD, XType, N0, Shift);
5059 AddToWorkList(Shift.Val);
5060 AddToWorkList(Add.Val);
5061 return DAG.getNode(ISD::XOR, XType, Add, Shift);
5062 }
5063 // Check to see if this is an integer abs. select_cc setgt X, -1, X, -X ->
5064 // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
5065 if (N1C && N1C->isAllOnesValue() && CC == ISD::SETGT &&
5066 N0 == N2 && N3.getOpcode() == ISD::SUB && N0 == N3.getOperand(1)) {
5067 if (ConstantSDNode *SubC = dyn_cast<ConstantSDNode>(N3.getOperand(0))) {
5068 MVT::ValueType XType = N0.getValueType();
5069 if (SubC->isNullValue() && MVT::isInteger(XType)) {
5070 SDOperand Shift = DAG.getNode(ISD::SRA, XType, N0,
5071 DAG.getConstant(MVT::getSizeInBits(XType)-1,
5072 TLI.getShiftAmountTy()));
5073 SDOperand Add = DAG.getNode(ISD::ADD, XType, N0, Shift);
5074 AddToWorkList(Shift.Val);
5075 AddToWorkList(Add.Val);
5076 return DAG.getNode(ISD::XOR, XType, Add, Shift);
5077 }
5078 }
5079 }
5080
5081 return SDOperand();
5082}
5083
5084/// SimplifySetCC - This is a stub for TargetLowering::SimplifySetCC.
5085SDOperand DAGCombiner::SimplifySetCC(MVT::ValueType VT, SDOperand N0,
5086 SDOperand N1, ISD::CondCode Cond,
5087 bool foldBooleans) {
5088 TargetLowering::DAGCombinerInfo
5089 DagCombineInfo(DAG, !AfterLegalize, false, this);
5090 return TLI.SimplifySetCC(VT, N0, N1, Cond, foldBooleans, DagCombineInfo);
5091}
5092
5093/// BuildSDIVSequence - Given an ISD::SDIV node expressing a divide by constant,
5094/// return a DAG expression to select that will generate the same value by
5095/// multiplying by a magic number. See:
5096/// <http://the.wall.riscom.net/books/proc/ppc/cwg/code2.html>
5097SDOperand DAGCombiner::BuildSDIV(SDNode *N) {
5098 std::vector<SDNode*> Built;
5099 SDOperand S = TLI.BuildSDIV(N, DAG, &Built);
5100
5101 for (std::vector<SDNode*>::iterator ii = Built.begin(), ee = Built.end();
5102 ii != ee; ++ii)
5103 AddToWorkList(*ii);
5104 return S;
5105}
5106
5107/// BuildUDIVSequence - Given an ISD::UDIV node expressing a divide by constant,
5108/// return a DAG expression to select that will generate the same value by
5109/// multiplying by a magic number. See:
5110/// <http://the.wall.riscom.net/books/proc/ppc/cwg/code2.html>
5111SDOperand DAGCombiner::BuildUDIV(SDNode *N) {
5112 std::vector<SDNode*> Built;
5113 SDOperand S = TLI.BuildUDIV(N, DAG, &Built);
5114
5115 for (std::vector<SDNode*>::iterator ii = Built.begin(), ee = Built.end();
5116 ii != ee; ++ii)
5117 AddToWorkList(*ii);
5118 return S;
5119}
5120
5121/// FindBaseOffset - Return true if base is known not to alias with anything
5122/// but itself. Provides base object and offset as results.
5123static bool FindBaseOffset(SDOperand Ptr, SDOperand &Base, int64_t &Offset) {
5124 // Assume it is a primitive operation.
5125 Base = Ptr; Offset = 0;
5126
5127 // If it's an adding a simple constant then integrate the offset.
5128 if (Base.getOpcode() == ISD::ADD) {
5129 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Base.getOperand(1))) {
5130 Base = Base.getOperand(0);
5131 Offset += C->getValue();
5132 }
5133 }
5134
5135 // If it's any of the following then it can't alias with anything but itself.
5136 return isa<FrameIndexSDNode>(Base) ||
5137 isa<ConstantPoolSDNode>(Base) ||
5138 isa<GlobalAddressSDNode>(Base);
5139}
5140
5141/// isAlias - Return true if there is any possibility that the two addresses
5142/// overlap.
5143bool DAGCombiner::isAlias(SDOperand Ptr1, int64_t Size1,
5144 const Value *SrcValue1, int SrcValueOffset1,
5145 SDOperand Ptr2, int64_t Size2,
5146 const Value *SrcValue2, int SrcValueOffset2)
5147{
5148 // If they are the same then they must be aliases.
5149 if (Ptr1 == Ptr2) return true;
5150
5151 // Gather base node and offset information.
5152 SDOperand Base1, Base2;
5153 int64_t Offset1, Offset2;
5154 bool KnownBase1 = FindBaseOffset(Ptr1, Base1, Offset1);
5155 bool KnownBase2 = FindBaseOffset(Ptr2, Base2, Offset2);
5156
5157 // If they have a same base address then...
5158 if (Base1 == Base2) {
5159 // Check to see if the addresses overlap.
5160 return!((Offset1 + Size1) <= Offset2 || (Offset2 + Size2) <= Offset1);
5161 }
5162
5163 // If we know both bases then they can't alias.
5164 if (KnownBase1 && KnownBase2) return false;
5165
5166 if (CombinerGlobalAA) {
5167 // Use alias analysis information.
Dan Gohmane142c2e2007-08-27 16:32:11 +00005168 int64_t MinOffset = std::min(SrcValueOffset1, SrcValueOffset2);
5169 int64_t Overlap1 = Size1 + SrcValueOffset1 - MinOffset;
5170 int64_t Overlap2 = Size2 + SrcValueOffset2 - MinOffset;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005171 AliasAnalysis::AliasResult AAResult =
5172 AA.alias(SrcValue1, Overlap1, SrcValue2, Overlap2);
5173 if (AAResult == AliasAnalysis::NoAlias)
5174 return false;
5175 }
5176
5177 // Otherwise we have to assume they alias.
5178 return true;
5179}
5180
5181/// FindAliasInfo - Extracts the relevant alias information from the memory
5182/// node. Returns true if the operand was a load.
5183bool DAGCombiner::FindAliasInfo(SDNode *N,
5184 SDOperand &Ptr, int64_t &Size,
5185 const Value *&SrcValue, int &SrcValueOffset) {
5186 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
5187 Ptr = LD->getBasePtr();
5188 Size = MVT::getSizeInBits(LD->getLoadedVT()) >> 3;
5189 SrcValue = LD->getSrcValue();
5190 SrcValueOffset = LD->getSrcValueOffset();
5191 return true;
5192 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
5193 Ptr = ST->getBasePtr();
5194 Size = MVT::getSizeInBits(ST->getStoredVT()) >> 3;
5195 SrcValue = ST->getSrcValue();
5196 SrcValueOffset = ST->getSrcValueOffset();
5197 } else {
5198 assert(0 && "FindAliasInfo expected a memory operand");
5199 }
5200
5201 return false;
5202}
5203
5204/// GatherAllAliases - Walk up chain skipping non-aliasing memory nodes,
5205/// looking for aliasing nodes and adding them to the Aliases vector.
5206void DAGCombiner::GatherAllAliases(SDNode *N, SDOperand OriginalChain,
5207 SmallVector<SDOperand, 8> &Aliases) {
5208 SmallVector<SDOperand, 8> Chains; // List of chains to visit.
5209 std::set<SDNode *> Visited; // Visited node set.
5210
5211 // Get alias information for node.
5212 SDOperand Ptr;
5213 int64_t Size;
5214 const Value *SrcValue;
5215 int SrcValueOffset;
5216 bool IsLoad = FindAliasInfo(N, Ptr, Size, SrcValue, SrcValueOffset);
5217
5218 // Starting off.
5219 Chains.push_back(OriginalChain);
5220
5221 // Look at each chain and determine if it is an alias. If so, add it to the
5222 // aliases list. If not, then continue up the chain looking for the next
5223 // candidate.
5224 while (!Chains.empty()) {
5225 SDOperand Chain = Chains.back();
5226 Chains.pop_back();
5227
5228 // Don't bother if we've been before.
5229 if (Visited.find(Chain.Val) != Visited.end()) continue;
5230 Visited.insert(Chain.Val);
5231
5232 switch (Chain.getOpcode()) {
5233 case ISD::EntryToken:
5234 // Entry token is ideal chain operand, but handled in FindBetterChain.
5235 break;
5236
5237 case ISD::LOAD:
5238 case ISD::STORE: {
5239 // Get alias information for Chain.
5240 SDOperand OpPtr;
5241 int64_t OpSize;
5242 const Value *OpSrcValue;
5243 int OpSrcValueOffset;
5244 bool IsOpLoad = FindAliasInfo(Chain.Val, OpPtr, OpSize,
5245 OpSrcValue, OpSrcValueOffset);
5246
5247 // If chain is alias then stop here.
5248 if (!(IsLoad && IsOpLoad) &&
5249 isAlias(Ptr, Size, SrcValue, SrcValueOffset,
5250 OpPtr, OpSize, OpSrcValue, OpSrcValueOffset)) {
5251 Aliases.push_back(Chain);
5252 } else {
5253 // Look further up the chain.
5254 Chains.push_back(Chain.getOperand(0));
5255 // Clean up old chain.
5256 AddToWorkList(Chain.Val);
5257 }
5258 break;
5259 }
5260
5261 case ISD::TokenFactor:
5262 // We have to check each of the operands of the token factor, so we queue
5263 // then up. Adding the operands to the queue (stack) in reverse order
5264 // maintains the original order and increases the likelihood that getNode
5265 // will find a matching token factor (CSE.)
5266 for (unsigned n = Chain.getNumOperands(); n;)
5267 Chains.push_back(Chain.getOperand(--n));
5268 // Eliminate the token factor if we can.
5269 AddToWorkList(Chain.Val);
5270 break;
5271
5272 default:
5273 // For all other instructions we will just have to take what we can get.
5274 Aliases.push_back(Chain);
5275 break;
5276 }
5277 }
5278}
5279
5280/// FindBetterChain - Walk up chain skipping non-aliasing memory nodes, looking
5281/// for a better chain (aliasing node.)
5282SDOperand DAGCombiner::FindBetterChain(SDNode *N, SDOperand OldChain) {
5283 SmallVector<SDOperand, 8> Aliases; // Ops for replacing token factor.
5284
5285 // Accumulate all the aliases to this node.
5286 GatherAllAliases(N, OldChain, Aliases);
5287
5288 if (Aliases.size() == 0) {
5289 // If no operands then chain to entry token.
5290 return DAG.getEntryNode();
5291 } else if (Aliases.size() == 1) {
5292 // If a single operand then chain to it. We don't need to revisit it.
5293 return Aliases[0];
5294 }
5295
5296 // Construct a custom tailored token factor.
5297 SDOperand NewChain = DAG.getNode(ISD::TokenFactor, MVT::Other,
5298 &Aliases[0], Aliases.size());
5299
5300 // Make sure the old chain gets cleaned up.
5301 if (NewChain != OldChain) AddToWorkList(OldChain.Val);
5302
5303 return NewChain;
5304}
5305
5306// SelectionDAG::Combine - This is the entry point for the file.
5307//
5308void SelectionDAG::Combine(bool RunningAfterLegalize, AliasAnalysis &AA) {
5309 if (!RunningAfterLegalize && ViewDAGCombine1)
5310 viewGraph();
5311 if (RunningAfterLegalize && ViewDAGCombine2)
5312 viewGraph();
5313 /// run - This is the main entry point to this class.
5314 ///
5315 DAGCombiner(*this, AA).Run(RunningAfterLegalize);
5316}