1 //===-- DAGCombiner.cpp - Implement a DAG node combiner -------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
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.
13 //===----------------------------------------------------------------------===//
15 #define DEBUG_TYPE "dagcombine"
16 #include "llvm/CodeGen/SelectionDAG.h"
17 #include "llvm/CodeGen/MachineFunction.h"
18 #include "llvm/CodeGen/MachineFrameInfo.h"
19 #include "llvm/Analysis/AliasAnalysis.h"
20 #include "llvm/Target/TargetData.h"
21 #include "llvm/Target/TargetFrameInfo.h"
22 #include "llvm/Target/TargetLowering.h"
23 #include "llvm/Target/TargetMachine.h"
24 #include "llvm/Target/TargetOptions.h"
25 #include "llvm/ADT/SmallPtrSet.h"
26 #include "llvm/ADT/Statistic.h"
27 #include "llvm/Support/Compiler.h"
28 #include "llvm/Support/CommandLine.h"
29 #include "llvm/Support/Debug.h"
30 #include "llvm/Support/MathExtras.h"
35 STATISTIC(NodesCombined , "Number of dag nodes combined");
36 STATISTIC(PreIndexedNodes , "Number of pre-indexed nodes created");
37 STATISTIC(PostIndexedNodes, "Number of post-indexed nodes created");
42 ViewDAGCombine1("view-dag-combine1-dags", cl::Hidden,
43 cl::desc("Pop up a window to show dags before the first "
46 ViewDAGCombine2("view-dag-combine2-dags", cl::Hidden,
47 cl::desc("Pop up a window to show dags before the second "
50 static const bool ViewDAGCombine1 = false;
51 static const bool ViewDAGCombine2 = false;
55 CombinerAA("combiner-alias-analysis", cl::Hidden,
56 cl::desc("Turn on alias analysis during testing"));
59 CombinerGlobalAA("combiner-global-alias-analysis", cl::Hidden,
60 cl::desc("Include global information in alias analysis"));
62 //------------------------------ DAGCombiner ---------------------------------//
64 class VISIBILITY_HIDDEN DAGCombiner {
69 // Worklist of all of the nodes that need to be simplified.
70 std::vector<SDNode*> WorkList;
72 // AA - Used for DAG load/store alias analysis.
75 /// AddUsersToWorkList - When an instruction is simplified, add all users of
76 /// the instruction to the work lists because they might get more simplified
79 void AddUsersToWorkList(SDNode *N) {
80 for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
82 AddToWorkList(UI->getUser());
85 /// visit - call the node-specific routine that knows how to fold each
86 /// particular type of node.
87 SDOperand visit(SDNode *N);
90 /// AddToWorkList - Add to the work list making sure it's instance is at the
91 /// the back (next to be processed.)
92 void AddToWorkList(SDNode *N) {
93 removeFromWorkList(N);
94 WorkList.push_back(N);
97 /// removeFromWorkList - remove all instances of N from the worklist.
99 void removeFromWorkList(SDNode *N) {
100 WorkList.erase(std::remove(WorkList.begin(), WorkList.end(), N),
104 SDOperand CombineTo(SDNode *N, const SDOperand *To, unsigned NumTo,
107 SDOperand CombineTo(SDNode *N, SDOperand Res, bool AddTo = true) {
108 return CombineTo(N, &Res, 1, AddTo);
111 SDOperand CombineTo(SDNode *N, SDOperand Res0, SDOperand Res1,
113 SDOperand To[] = { Res0, Res1 };
114 return CombineTo(N, To, 2, AddTo);
119 /// SimplifyDemandedBits - Check the specified integer node value to see if
120 /// it can be simplified or if things it uses can be simplified by bit
121 /// propagation. If so, return true.
122 bool SimplifyDemandedBits(SDOperand Op) {
123 APInt Demanded = APInt::getAllOnesValue(Op.getValueSizeInBits());
124 return SimplifyDemandedBits(Op, Demanded);
127 bool SimplifyDemandedBits(SDOperand Op, const APInt &Demanded);
129 bool CombineToPreIndexedLoadStore(SDNode *N);
130 bool CombineToPostIndexedLoadStore(SDNode *N);
133 /// combine - call the node-specific routine that knows how to fold each
134 /// particular type of node. If that doesn't do anything, try the
135 /// target-specific DAG combines.
136 SDOperand combine(SDNode *N);
138 // Visitation implementation - Implement dag node combining for different
139 // node types. The semantics are as follows:
141 // SDOperand.Val == 0 - No change was made
142 // SDOperand.Val == N - N was replaced, is dead, and is already handled.
143 // otherwise - N should be replaced by the returned Operand.
145 SDOperand visitTokenFactor(SDNode *N);
146 SDOperand visitMERGE_VALUES(SDNode *N);
147 SDOperand visitADD(SDNode *N);
148 SDOperand visitSUB(SDNode *N);
149 SDOperand visitADDC(SDNode *N);
150 SDOperand visitADDE(SDNode *N);
151 SDOperand visitMUL(SDNode *N);
152 SDOperand visitSDIV(SDNode *N);
153 SDOperand visitUDIV(SDNode *N);
154 SDOperand visitSREM(SDNode *N);
155 SDOperand visitUREM(SDNode *N);
156 SDOperand visitMULHU(SDNode *N);
157 SDOperand visitMULHS(SDNode *N);
158 SDOperand visitSMUL_LOHI(SDNode *N);
159 SDOperand visitUMUL_LOHI(SDNode *N);
160 SDOperand visitSDIVREM(SDNode *N);
161 SDOperand visitUDIVREM(SDNode *N);
162 SDOperand visitAND(SDNode *N);
163 SDOperand visitOR(SDNode *N);
164 SDOperand visitXOR(SDNode *N);
165 SDOperand SimplifyVBinOp(SDNode *N);
166 SDOperand visitSHL(SDNode *N);
167 SDOperand visitSRA(SDNode *N);
168 SDOperand visitSRL(SDNode *N);
169 SDOperand visitCTLZ(SDNode *N);
170 SDOperand visitCTTZ(SDNode *N);
171 SDOperand visitCTPOP(SDNode *N);
172 SDOperand visitSELECT(SDNode *N);
173 SDOperand visitSELECT_CC(SDNode *N);
174 SDOperand visitSETCC(SDNode *N);
175 SDOperand visitSIGN_EXTEND(SDNode *N);
176 SDOperand visitZERO_EXTEND(SDNode *N);
177 SDOperand visitANY_EXTEND(SDNode *N);
178 SDOperand visitSIGN_EXTEND_INREG(SDNode *N);
179 SDOperand visitTRUNCATE(SDNode *N);
180 SDOperand visitBIT_CONVERT(SDNode *N);
181 SDOperand visitBUILD_PAIR(SDNode *N);
182 SDOperand visitFADD(SDNode *N);
183 SDOperand visitFSUB(SDNode *N);
184 SDOperand visitFMUL(SDNode *N);
185 SDOperand visitFDIV(SDNode *N);
186 SDOperand visitFREM(SDNode *N);
187 SDOperand visitFCOPYSIGN(SDNode *N);
188 SDOperand visitSINT_TO_FP(SDNode *N);
189 SDOperand visitUINT_TO_FP(SDNode *N);
190 SDOperand visitFP_TO_SINT(SDNode *N);
191 SDOperand visitFP_TO_UINT(SDNode *N);
192 SDOperand visitFP_ROUND(SDNode *N);
193 SDOperand visitFP_ROUND_INREG(SDNode *N);
194 SDOperand visitFP_EXTEND(SDNode *N);
195 SDOperand visitFNEG(SDNode *N);
196 SDOperand visitFABS(SDNode *N);
197 SDOperand visitBRCOND(SDNode *N);
198 SDOperand visitBR_CC(SDNode *N);
199 SDOperand visitLOAD(SDNode *N);
200 SDOperand visitSTORE(SDNode *N);
201 SDOperand visitINSERT_VECTOR_ELT(SDNode *N);
202 SDOperand visitEXTRACT_VECTOR_ELT(SDNode *N);
203 SDOperand visitBUILD_VECTOR(SDNode *N);
204 SDOperand visitCONCAT_VECTORS(SDNode *N);
205 SDOperand visitVECTOR_SHUFFLE(SDNode *N);
207 SDOperand XformToShuffleWithZero(SDNode *N);
208 SDOperand ReassociateOps(unsigned Opc, SDOperand LHS, SDOperand RHS);
210 SDOperand visitShiftByConstant(SDNode *N, unsigned Amt);
212 bool SimplifySelectOps(SDNode *SELECT, SDOperand LHS, SDOperand RHS);
213 SDOperand SimplifyBinOpWithSameOpcodeHands(SDNode *N);
214 SDOperand SimplifySelect(SDOperand N0, SDOperand N1, SDOperand N2);
215 SDOperand SimplifySelectCC(SDOperand N0, SDOperand N1, SDOperand N2,
216 SDOperand N3, ISD::CondCode CC,
217 bool NotExtCompare = false);
218 SDOperand SimplifySetCC(MVT VT, SDOperand N0, SDOperand N1,
219 ISD::CondCode Cond, bool foldBooleans = true);
220 SDOperand SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp,
222 SDOperand CombineConsecutiveLoads(SDNode *N, MVT VT);
223 SDOperand ConstantFoldBIT_CONVERTofBUILD_VECTOR(SDNode *, MVT);
224 SDOperand BuildSDIV(SDNode *N);
225 SDOperand BuildUDIV(SDNode *N);
226 SDNode *MatchRotate(SDOperand LHS, SDOperand RHS);
227 SDOperand ReduceLoadWidth(SDNode *N);
229 SDOperand GetDemandedBits(SDOperand V, const APInt &Mask);
231 /// GatherAllAliases - Walk up chain skipping non-aliasing memory nodes,
232 /// looking for aliasing nodes and adding them to the Aliases vector.
233 void GatherAllAliases(SDNode *N, SDOperand OriginalChain,
234 SmallVector<SDOperand, 8> &Aliases);
236 /// isAlias - Return true if there is any possibility that the two addresses
238 bool isAlias(SDOperand Ptr1, int64_t Size1,
239 const Value *SrcValue1, int SrcValueOffset1,
240 SDOperand Ptr2, int64_t Size2,
241 const Value *SrcValue2, int SrcValueOffset2);
243 /// FindAliasInfo - Extracts the relevant alias information from the memory
244 /// node. Returns true if the operand was a load.
245 bool FindAliasInfo(SDNode *N,
246 SDOperand &Ptr, int64_t &Size,
247 const Value *&SrcValue, int &SrcValueOffset);
249 /// FindBetterChain - Walk up chain skipping non-aliasing memory nodes,
250 /// looking for a better chain (aliasing node.)
251 SDOperand FindBetterChain(SDNode *N, SDOperand Chain);
254 DAGCombiner(SelectionDAG &D, AliasAnalysis &A)
256 TLI(D.getTargetLoweringInfo()),
257 AfterLegalize(false),
260 /// Run - runs the dag combiner on all nodes in the work list
261 void Run(bool RunningAfterLegalize);
267 /// WorkListRemover - This class is a DAGUpdateListener that removes any deleted
268 /// nodes from the worklist.
269 class VISIBILITY_HIDDEN WorkListRemover :
270 public SelectionDAG::DAGUpdateListener {
273 explicit WorkListRemover(DAGCombiner &dc) : DC(dc) {}
275 virtual void NodeDeleted(SDNode *N, SDNode *E) {
276 DC.removeFromWorkList(N);
279 virtual void NodeUpdated(SDNode *N) {
285 //===----------------------------------------------------------------------===//
286 // TargetLowering::DAGCombinerInfo implementation
287 //===----------------------------------------------------------------------===//
289 void TargetLowering::DAGCombinerInfo::AddToWorklist(SDNode *N) {
290 ((DAGCombiner*)DC)->AddToWorkList(N);
293 SDOperand TargetLowering::DAGCombinerInfo::
294 CombineTo(SDNode *N, const std::vector<SDOperand> &To) {
295 return ((DAGCombiner*)DC)->CombineTo(N, &To[0], To.size());
298 SDOperand TargetLowering::DAGCombinerInfo::
299 CombineTo(SDNode *N, SDOperand Res) {
300 return ((DAGCombiner*)DC)->CombineTo(N, Res);
304 SDOperand TargetLowering::DAGCombinerInfo::
305 CombineTo(SDNode *N, SDOperand Res0, SDOperand Res1) {
306 return ((DAGCombiner*)DC)->CombineTo(N, Res0, Res1);
310 //===----------------------------------------------------------------------===//
312 //===----------------------------------------------------------------------===//
314 /// isNegatibleForFree - Return 1 if we can compute the negated form of the
315 /// specified expression for the same cost as the expression itself, or 2 if we
316 /// can compute the negated form more cheaply than the expression itself.
317 static char isNegatibleForFree(SDOperand Op, bool AfterLegalize,
318 unsigned Depth = 0) {
319 // No compile time optimizations on this type.
320 if (Op.getValueType() == MVT::ppcf128)
323 // fneg is removable even if it has multiple uses.
324 if (Op.getOpcode() == ISD::FNEG) return 2;
326 // Don't allow anything with multiple uses.
327 if (!Op.hasOneUse()) return 0;
329 // Don't recurse exponentially.
330 if (Depth > 6) return 0;
332 switch (Op.getOpcode()) {
333 default: return false;
334 case ISD::ConstantFP:
335 // Don't invert constant FP values after legalize. The negated constant
336 // isn't necessarily legal.
337 return AfterLegalize ? 0 : 1;
339 // FIXME: determine better conditions for this xform.
340 if (!UnsafeFPMath) return 0;
343 if (char V = isNegatibleForFree(Op.getOperand(0), AfterLegalize, Depth+1))
346 return isNegatibleForFree(Op.getOperand(1), AfterLegalize, Depth+1);
348 // We can't turn -(A-B) into B-A when we honor signed zeros.
349 if (!UnsafeFPMath) return 0;
356 if (HonorSignDependentRoundingFPMath()) return 0;
358 // -(X*Y) -> (-X * Y) or (X*-Y)
359 if (char V = isNegatibleForFree(Op.getOperand(0), AfterLegalize, Depth+1))
362 return isNegatibleForFree(Op.getOperand(1), AfterLegalize, Depth+1);
367 return isNegatibleForFree(Op.getOperand(0), AfterLegalize, Depth+1);
371 /// GetNegatedExpression - If isNegatibleForFree returns true, this function
372 /// returns the newly negated expression.
373 static SDOperand GetNegatedExpression(SDOperand Op, SelectionDAG &DAG,
374 bool AfterLegalize, unsigned Depth = 0) {
375 // fneg is removable even if it has multiple uses.
376 if (Op.getOpcode() == ISD::FNEG) return Op.getOperand(0);
378 // Don't allow anything with multiple uses.
379 assert(Op.hasOneUse() && "Unknown reuse!");
381 assert(Depth <= 6 && "GetNegatedExpression doesn't match isNegatibleForFree");
382 switch (Op.getOpcode()) {
383 default: assert(0 && "Unknown code");
384 case ISD::ConstantFP: {
385 APFloat V = cast<ConstantFPSDNode>(Op)->getValueAPF();
387 return DAG.getConstantFP(V, Op.getValueType());
390 // FIXME: determine better conditions for this xform.
391 assert(UnsafeFPMath);
394 if (isNegatibleForFree(Op.getOperand(0), AfterLegalize, Depth+1))
395 return DAG.getNode(ISD::FSUB, Op.getValueType(),
396 GetNegatedExpression(Op.getOperand(0), DAG,
397 AfterLegalize, Depth+1),
400 return DAG.getNode(ISD::FSUB, Op.getValueType(),
401 GetNegatedExpression(Op.getOperand(1), DAG,
402 AfterLegalize, Depth+1),
405 // We can't turn -(A-B) into B-A when we honor signed zeros.
406 assert(UnsafeFPMath);
409 if (ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(Op.getOperand(0)))
410 if (N0CFP->getValueAPF().isZero())
411 return Op.getOperand(1);
414 return DAG.getNode(ISD::FSUB, Op.getValueType(), Op.getOperand(1),
419 assert(!HonorSignDependentRoundingFPMath());
422 if (isNegatibleForFree(Op.getOperand(0), AfterLegalize, Depth+1))
423 return DAG.getNode(Op.getOpcode(), Op.getValueType(),
424 GetNegatedExpression(Op.getOperand(0), DAG,
425 AfterLegalize, Depth+1),
429 return DAG.getNode(Op.getOpcode(), Op.getValueType(),
431 GetNegatedExpression(Op.getOperand(1), DAG,
432 AfterLegalize, Depth+1));
436 return DAG.getNode(Op.getOpcode(), Op.getValueType(),
437 GetNegatedExpression(Op.getOperand(0), DAG,
438 AfterLegalize, Depth+1));
440 return DAG.getNode(ISD::FP_ROUND, Op.getValueType(),
441 GetNegatedExpression(Op.getOperand(0), DAG,
442 AfterLegalize, Depth+1),
448 // isSetCCEquivalent - Return true if this node is a setcc, or is a select_cc
449 // that selects between the values 1 and 0, making it equivalent to a setcc.
450 // Also, set the incoming LHS, RHS, and CC references to the appropriate
451 // nodes based on the type of node we are checking. This simplifies life a
452 // bit for the callers.
453 static bool isSetCCEquivalent(SDOperand N, SDOperand &LHS, SDOperand &RHS,
455 if (N.getOpcode() == ISD::SETCC) {
456 LHS = N.getOperand(0);
457 RHS = N.getOperand(1);
458 CC = N.getOperand(2);
461 if (N.getOpcode() == ISD::SELECT_CC &&
462 N.getOperand(2).getOpcode() == ISD::Constant &&
463 N.getOperand(3).getOpcode() == ISD::Constant &&
464 cast<ConstantSDNode>(N.getOperand(2))->getAPIntValue() == 1 &&
465 cast<ConstantSDNode>(N.getOperand(3))->isNullValue()) {
466 LHS = N.getOperand(0);
467 RHS = N.getOperand(1);
468 CC = N.getOperand(4);
474 // isOneUseSetCC - Return true if this is a SetCC-equivalent operation with only
475 // one use. If this is true, it allows the users to invert the operation for
476 // free when it is profitable to do so.
477 static bool isOneUseSetCC(SDOperand N) {
478 SDOperand N0, N1, N2;
479 if (isSetCCEquivalent(N, N0, N1, N2) && N.Val->hasOneUse())
484 SDOperand DAGCombiner::ReassociateOps(unsigned Opc, SDOperand N0, SDOperand N1){
485 MVT VT = N0.getValueType();
486 // reassoc. (op (op x, c1), y) -> (op (op x, y), c1) iff x+c1 has one use
487 // reassoc. (op (op x, c1), c2) -> (op x, (op c1, c2))
488 if (N0.getOpcode() == Opc && isa<ConstantSDNode>(N0.getOperand(1))) {
489 if (isa<ConstantSDNode>(N1)) {
490 SDOperand OpNode = DAG.getNode(Opc, VT, N0.getOperand(1), N1);
491 AddToWorkList(OpNode.Val);
492 return DAG.getNode(Opc, VT, OpNode, N0.getOperand(0));
493 } else if (N0.hasOneUse()) {
494 SDOperand OpNode = DAG.getNode(Opc, VT, N0.getOperand(0), N1);
495 AddToWorkList(OpNode.Val);
496 return DAG.getNode(Opc, VT, OpNode, N0.getOperand(1));
499 // reassoc. (op y, (op x, c1)) -> (op (op x, y), c1) iff x+c1 has one use
500 // reassoc. (op c2, (op x, c1)) -> (op x, (op c1, c2))
501 if (N1.getOpcode() == Opc && isa<ConstantSDNode>(N1.getOperand(1))) {
502 if (isa<ConstantSDNode>(N0)) {
503 SDOperand OpNode = DAG.getNode(Opc, VT, N1.getOperand(1), N0);
504 AddToWorkList(OpNode.Val);
505 return DAG.getNode(Opc, VT, OpNode, N1.getOperand(0));
506 } else if (N1.hasOneUse()) {
507 SDOperand OpNode = DAG.getNode(Opc, VT, N1.getOperand(0), N0);
508 AddToWorkList(OpNode.Val);
509 return DAG.getNode(Opc, VT, OpNode, N1.getOperand(1));
515 SDOperand DAGCombiner::CombineTo(SDNode *N, const SDOperand *To, unsigned NumTo,
517 assert(N->getNumValues() == NumTo && "Broken CombineTo call!");
519 DOUT << "\nReplacing.1 "; DEBUG(N->dump(&DAG));
520 DOUT << "\nWith: "; DEBUG(To[0].Val->dump(&DAG));
521 DOUT << " and " << NumTo-1 << " other values\n";
522 WorkListRemover DeadNodes(*this);
523 DAG.ReplaceAllUsesWith(N, To, &DeadNodes);
526 // Push the new nodes and any users onto the worklist
527 for (unsigned i = 0, e = NumTo; i != e; ++i) {
528 AddToWorkList(To[i].Val);
529 AddUsersToWorkList(To[i].Val);
533 // Nodes can be reintroduced into the worklist. Make sure we do not
534 // process a node that has been replaced.
535 removeFromWorkList(N);
537 // Finally, since the node is now dead, remove it from the graph.
539 return SDOperand(N, 0);
542 /// SimplifyDemandedBits - Check the specified integer node value to see if
543 /// it can be simplified or if things it uses can be simplified by bit
544 /// propagation. If so, return true.
545 bool DAGCombiner::SimplifyDemandedBits(SDOperand Op, const APInt &Demanded) {
546 TargetLowering::TargetLoweringOpt TLO(DAG, AfterLegalize);
547 APInt KnownZero, KnownOne;
548 if (!TLI.SimplifyDemandedBits(Op, Demanded, KnownZero, KnownOne, TLO))
552 AddToWorkList(Op.Val);
554 // Replace the old value with the new one.
556 DOUT << "\nReplacing.2 "; DEBUG(TLO.Old.Val->dump(&DAG));
557 DOUT << "\nWith: "; DEBUG(TLO.New.Val->dump(&DAG));
560 // Replace all uses. If any nodes become isomorphic to other nodes and
561 // are deleted, make sure to remove them from our worklist.
562 WorkListRemover DeadNodes(*this);
563 DAG.ReplaceAllUsesOfValueWith(TLO.Old, TLO.New, &DeadNodes);
565 // Push the new node and any (possibly new) users onto the worklist.
566 AddToWorkList(TLO.New.Val);
567 AddUsersToWorkList(TLO.New.Val);
569 // Finally, if the node is now dead, remove it from the graph. The node
570 // may not be dead if the replacement process recursively simplified to
571 // something else needing this node.
572 if (TLO.Old.Val->use_empty()) {
573 removeFromWorkList(TLO.Old.Val);
575 // If the operands of this node are only used by the node, they will now
576 // be dead. Make sure to visit them first to delete dead nodes early.
577 for (unsigned i = 0, e = TLO.Old.Val->getNumOperands(); i != e; ++i)
578 if (TLO.Old.Val->getOperand(i).Val->hasOneUse())
579 AddToWorkList(TLO.Old.Val->getOperand(i).Val);
581 DAG.DeleteNode(TLO.Old.Val);
586 //===----------------------------------------------------------------------===//
587 // Main DAG Combiner implementation
588 //===----------------------------------------------------------------------===//
590 void DAGCombiner::Run(bool RunningAfterLegalize) {
591 // set the instance variable, so that the various visit routines may use it.
592 AfterLegalize = RunningAfterLegalize;
594 // Add all the dag nodes to the worklist.
595 for (SelectionDAG::allnodes_iterator I = DAG.allnodes_begin(),
596 E = DAG.allnodes_end(); I != E; ++I)
597 WorkList.push_back(I);
599 // Create a dummy node (which is not added to allnodes), that adds a reference
600 // to the root node, preventing it from being deleted, and tracking any
601 // changes of the root.
602 HandleSDNode Dummy(DAG.getRoot());
604 // The root of the dag may dangle to deleted nodes until the dag combiner is
605 // done. Set it to null to avoid confusion.
606 DAG.setRoot(SDOperand());
608 // while the worklist isn't empty, inspect the node on the end of it and
609 // try and combine it.
610 while (!WorkList.empty()) {
611 SDNode *N = WorkList.back();
614 // If N has no uses, it is dead. Make sure to revisit all N's operands once
615 // N is deleted from the DAG, since they too may now be dead or may have a
616 // reduced number of uses, allowing other xforms.
617 if (N->use_empty() && N != &Dummy) {
618 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
619 AddToWorkList(N->getOperand(i).Val);
625 SDOperand RV = combine(N);
632 // If we get back the same node we passed in, rather than a new node or
633 // zero, we know that the node must have defined multiple values and
634 // CombineTo was used. Since CombineTo takes care of the worklist
635 // mechanics for us, we have no work to do in this case.
639 assert(N->getOpcode() != ISD::DELETED_NODE &&
640 RV.Val->getOpcode() != ISD::DELETED_NODE &&
641 "Node was deleted but visit returned new node!");
643 DOUT << "\nReplacing.3 "; DEBUG(N->dump(&DAG));
644 DOUT << "\nWith: "; DEBUG(RV.Val->dump(&DAG));
646 WorkListRemover DeadNodes(*this);
647 if (N->getNumValues() == RV.Val->getNumValues())
648 DAG.ReplaceAllUsesWith(N, RV.Val, &DeadNodes);
650 assert(N->getValueType(0) == RV.getValueType() &&
651 N->getNumValues() == 1 && "Type mismatch");
653 DAG.ReplaceAllUsesWith(N, &OpV, &DeadNodes);
656 // Push the new node and any users onto the worklist
657 AddToWorkList(RV.Val);
658 AddUsersToWorkList(RV.Val);
660 // Add any uses of the old node to the worklist in case this node is the
661 // last one that uses them. They may become dead after this node is
663 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
664 AddToWorkList(N->getOperand(i).Val);
666 // Nodes can be reintroduced into the worklist. Make sure we do not
667 // process a node that has been replaced.
668 removeFromWorkList(N);
670 // Finally, since the node is now dead, remove it from the graph.
674 // If the root changed (e.g. it was a dead load, update the root).
675 DAG.setRoot(Dummy.getValue());
678 SDOperand DAGCombiner::visit(SDNode *N) {
679 switch(N->getOpcode()) {
681 case ISD::TokenFactor: return visitTokenFactor(N);
682 case ISD::MERGE_VALUES: return visitMERGE_VALUES(N);
683 case ISD::ADD: return visitADD(N);
684 case ISD::SUB: return visitSUB(N);
685 case ISD::ADDC: return visitADDC(N);
686 case ISD::ADDE: return visitADDE(N);
687 case ISD::MUL: return visitMUL(N);
688 case ISD::SDIV: return visitSDIV(N);
689 case ISD::UDIV: return visitUDIV(N);
690 case ISD::SREM: return visitSREM(N);
691 case ISD::UREM: return visitUREM(N);
692 case ISD::MULHU: return visitMULHU(N);
693 case ISD::MULHS: return visitMULHS(N);
694 case ISD::SMUL_LOHI: return visitSMUL_LOHI(N);
695 case ISD::UMUL_LOHI: return visitUMUL_LOHI(N);
696 case ISD::SDIVREM: return visitSDIVREM(N);
697 case ISD::UDIVREM: return visitUDIVREM(N);
698 case ISD::AND: return visitAND(N);
699 case ISD::OR: return visitOR(N);
700 case ISD::XOR: return visitXOR(N);
701 case ISD::SHL: return visitSHL(N);
702 case ISD::SRA: return visitSRA(N);
703 case ISD::SRL: return visitSRL(N);
704 case ISD::CTLZ: return visitCTLZ(N);
705 case ISD::CTTZ: return visitCTTZ(N);
706 case ISD::CTPOP: return visitCTPOP(N);
707 case ISD::SELECT: return visitSELECT(N);
708 case ISD::SELECT_CC: return visitSELECT_CC(N);
709 case ISD::SETCC: return visitSETCC(N);
710 case ISD::SIGN_EXTEND: return visitSIGN_EXTEND(N);
711 case ISD::ZERO_EXTEND: return visitZERO_EXTEND(N);
712 case ISD::ANY_EXTEND: return visitANY_EXTEND(N);
713 case ISD::SIGN_EXTEND_INREG: return visitSIGN_EXTEND_INREG(N);
714 case ISD::TRUNCATE: return visitTRUNCATE(N);
715 case ISD::BIT_CONVERT: return visitBIT_CONVERT(N);
716 case ISD::BUILD_PAIR: return visitBUILD_PAIR(N);
717 case ISD::FADD: return visitFADD(N);
718 case ISD::FSUB: return visitFSUB(N);
719 case ISD::FMUL: return visitFMUL(N);
720 case ISD::FDIV: return visitFDIV(N);
721 case ISD::FREM: return visitFREM(N);
722 case ISD::FCOPYSIGN: return visitFCOPYSIGN(N);
723 case ISD::SINT_TO_FP: return visitSINT_TO_FP(N);
724 case ISD::UINT_TO_FP: return visitUINT_TO_FP(N);
725 case ISD::FP_TO_SINT: return visitFP_TO_SINT(N);
726 case ISD::FP_TO_UINT: return visitFP_TO_UINT(N);
727 case ISD::FP_ROUND: return visitFP_ROUND(N);
728 case ISD::FP_ROUND_INREG: return visitFP_ROUND_INREG(N);
729 case ISD::FP_EXTEND: return visitFP_EXTEND(N);
730 case ISD::FNEG: return visitFNEG(N);
731 case ISD::FABS: return visitFABS(N);
732 case ISD::BRCOND: return visitBRCOND(N);
733 case ISD::BR_CC: return visitBR_CC(N);
734 case ISD::LOAD: return visitLOAD(N);
735 case ISD::STORE: return visitSTORE(N);
736 case ISD::INSERT_VECTOR_ELT: return visitINSERT_VECTOR_ELT(N);
737 case ISD::EXTRACT_VECTOR_ELT: return visitEXTRACT_VECTOR_ELT(N);
738 case ISD::BUILD_VECTOR: return visitBUILD_VECTOR(N);
739 case ISD::CONCAT_VECTORS: return visitCONCAT_VECTORS(N);
740 case ISD::VECTOR_SHUFFLE: return visitVECTOR_SHUFFLE(N);
745 SDOperand DAGCombiner::combine(SDNode *N) {
747 SDOperand RV = visit(N);
749 // If nothing happened, try a target-specific DAG combine.
751 assert(N->getOpcode() != ISD::DELETED_NODE &&
752 "Node was deleted but visit returned NULL!");
754 if (N->getOpcode() >= ISD::BUILTIN_OP_END ||
755 TLI.hasTargetDAGCombine((ISD::NodeType)N->getOpcode())) {
757 // Expose the DAG combiner to the target combiner impls.
758 TargetLowering::DAGCombinerInfo
759 DagCombineInfo(DAG, !AfterLegalize, false, this);
761 RV = TLI.PerformDAGCombine(N, DagCombineInfo);
765 // If N is a commutative binary node, try commuting it to enable more
768 SelectionDAG::isCommutativeBinOp(N->getOpcode()) &&
769 N->getNumValues() == 1) {
770 SDOperand N0 = N->getOperand(0);
771 SDOperand N1 = N->getOperand(1);
772 // Constant operands are canonicalized to RHS.
773 if (isa<ConstantSDNode>(N0) || !isa<ConstantSDNode>(N1)) {
774 SDOperand Ops[] = { N1, N0 };
775 SDNode *CSENode = DAG.getNodeIfExists(N->getOpcode(), N->getVTList(),
778 return SDOperand(CSENode, 0);
785 /// getInputChainForNode - Given a node, return its input chain if it has one,
786 /// otherwise return a null sd operand.
787 static SDOperand getInputChainForNode(SDNode *N) {
788 if (unsigned NumOps = N->getNumOperands()) {
789 if (N->getOperand(0).getValueType() == MVT::Other)
790 return N->getOperand(0);
791 else if (N->getOperand(NumOps-1).getValueType() == MVT::Other)
792 return N->getOperand(NumOps-1);
793 for (unsigned i = 1; i < NumOps-1; ++i)
794 if (N->getOperand(i).getValueType() == MVT::Other)
795 return N->getOperand(i);
797 return SDOperand(0, 0);
800 SDOperand DAGCombiner::visitTokenFactor(SDNode *N) {
801 // If N has two operands, where one has an input chain equal to the other,
802 // the 'other' chain is redundant.
803 if (N->getNumOperands() == 2) {
804 if (getInputChainForNode(N->getOperand(0).Val) == N->getOperand(1))
805 return N->getOperand(0);
806 if (getInputChainForNode(N->getOperand(1).Val) == N->getOperand(0))
807 return N->getOperand(1);
810 SmallVector<SDNode *, 8> TFs; // List of token factors to visit.
811 SmallVector<SDOperand, 8> Ops; // Ops for replacing token factor.
812 SmallPtrSet<SDNode*, 16> SeenOps;
813 bool Changed = false; // If we should replace this token factor.
815 // Start out with this token factor.
818 // Iterate through token factors. The TFs grows when new token factors are
820 for (unsigned i = 0; i < TFs.size(); ++i) {
823 // Check each of the operands.
824 for (unsigned i = 0, ie = TF->getNumOperands(); i != ie; ++i) {
825 SDOperand Op = TF->getOperand(i);
827 switch (Op.getOpcode()) {
828 case ISD::EntryToken:
829 // Entry tokens don't need to be added to the list. They are
834 case ISD::TokenFactor:
835 if ((CombinerAA || Op.hasOneUse()) &&
836 std::find(TFs.begin(), TFs.end(), Op.Val) == TFs.end()) {
837 // Queue up for processing.
838 TFs.push_back(Op.Val);
839 // Clean up in case the token factor is removed.
840 AddToWorkList(Op.Val);
847 // Only add if it isn't already in the list.
848 if (SeenOps.insert(Op.Val))
859 // If we've change things around then replace token factor.
862 // The entry token is the only possible outcome.
863 Result = DAG.getEntryNode();
865 // New and improved token factor.
866 Result = DAG.getNode(ISD::TokenFactor, MVT::Other, &Ops[0], Ops.size());
869 // Don't add users to work list.
870 return CombineTo(N, Result, false);
876 /// MERGE_VALUES can always be eliminated.
877 SDOperand DAGCombiner::visitMERGE_VALUES(SDNode *N) {
878 WorkListRemover DeadNodes(*this);
879 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
880 DAG.ReplaceAllUsesOfValueWith(SDOperand(N, i), N->getOperand(i),
882 removeFromWorkList(N);
884 return SDOperand(N, 0); // Return N so it doesn't get rechecked!
889 SDOperand combineShlAddConstant(SDOperand N0, SDOperand N1, SelectionDAG &DAG) {
890 MVT VT = N0.getValueType();
891 SDOperand N00 = N0.getOperand(0);
892 SDOperand N01 = N0.getOperand(1);
893 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N01);
894 if (N01C && N00.getOpcode() == ISD::ADD && N00.Val->hasOneUse() &&
895 isa<ConstantSDNode>(N00.getOperand(1))) {
896 N0 = DAG.getNode(ISD::ADD, VT,
897 DAG.getNode(ISD::SHL, VT, N00.getOperand(0), N01),
898 DAG.getNode(ISD::SHL, VT, N00.getOperand(1), N01));
899 return DAG.getNode(ISD::ADD, VT, N0, N1);
905 SDOperand combineSelectAndUse(SDNode *N, SDOperand Slct, SDOperand OtherOp,
907 MVT VT = N->getValueType(0);
908 unsigned Opc = N->getOpcode();
909 bool isSlctCC = Slct.getOpcode() == ISD::SELECT_CC;
910 SDOperand LHS = isSlctCC ? Slct.getOperand(2) : Slct.getOperand(1);
911 SDOperand RHS = isSlctCC ? Slct.getOperand(3) : Slct.getOperand(2);
912 ISD::CondCode CC = ISD::SETCC_INVALID;
914 CC = cast<CondCodeSDNode>(Slct.getOperand(4))->get();
916 SDOperand CCOp = Slct.getOperand(0);
917 if (CCOp.getOpcode() == ISD::SETCC)
918 CC = cast<CondCodeSDNode>(CCOp.getOperand(2))->get();
921 bool DoXform = false;
923 assert ((Opc == ISD::ADD || (Opc == ISD::SUB && Slct == N->getOperand(1))) &&
925 if (LHS.getOpcode() == ISD::Constant &&
926 cast<ConstantSDNode>(LHS)->isNullValue())
928 else if (CC != ISD::SETCC_INVALID &&
929 RHS.getOpcode() == ISD::Constant &&
930 cast<ConstantSDNode>(RHS)->isNullValue()) {
932 SDOperand Op0 = Slct.getOperand(0);
933 bool isInt = (isSlctCC ? Op0.getValueType() :
934 Op0.getOperand(0).getValueType()).isInteger();
935 CC = ISD::getSetCCInverse(CC, isInt);
941 SDOperand Result = DAG.getNode(Opc, VT, OtherOp, RHS);
943 return DAG.getSelectCC(OtherOp, Result,
944 Slct.getOperand(0), Slct.getOperand(1), CC);
945 SDOperand CCOp = Slct.getOperand(0);
947 CCOp = DAG.getSetCC(CCOp.getValueType(), CCOp.getOperand(0),
948 CCOp.getOperand(1), CC);
949 return DAG.getNode(ISD::SELECT, VT, CCOp, OtherOp, Result);
954 SDOperand DAGCombiner::visitADD(SDNode *N) {
955 SDOperand N0 = N->getOperand(0);
956 SDOperand N1 = N->getOperand(1);
957 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
958 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
959 MVT VT = N0.getValueType();
963 SDOperand FoldedVOp = SimplifyVBinOp(N);
964 if (FoldedVOp.Val) return FoldedVOp;
967 // fold (add x, undef) -> undef
968 if (N0.getOpcode() == ISD::UNDEF)
970 if (N1.getOpcode() == ISD::UNDEF)
972 // fold (add c1, c2) -> c1+c2
974 return DAG.getConstant(N0C->getAPIntValue() + N1C->getAPIntValue(), VT);
975 // canonicalize constant to RHS
977 return DAG.getNode(ISD::ADD, VT, N1, N0);
978 // fold (add x, 0) -> x
979 if (N1C && N1C->isNullValue())
981 // fold ((c1-A)+c2) -> (c1+c2)-A
982 if (N1C && N0.getOpcode() == ISD::SUB)
983 if (ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getOperand(0)))
984 return DAG.getNode(ISD::SUB, VT,
985 DAG.getConstant(N1C->getAPIntValue()+
986 N0C->getAPIntValue(), VT),
989 SDOperand RADD = ReassociateOps(ISD::ADD, N0, N1);
992 // fold ((0-A) + B) -> B-A
993 if (N0.getOpcode() == ISD::SUB && isa<ConstantSDNode>(N0.getOperand(0)) &&
994 cast<ConstantSDNode>(N0.getOperand(0))->isNullValue())
995 return DAG.getNode(ISD::SUB, VT, N1, N0.getOperand(1));
996 // fold (A + (0-B)) -> A-B
997 if (N1.getOpcode() == ISD::SUB && isa<ConstantSDNode>(N1.getOperand(0)) &&
998 cast<ConstantSDNode>(N1.getOperand(0))->isNullValue())
999 return DAG.getNode(ISD::SUB, VT, N0, N1.getOperand(1));
1000 // fold (A+(B-A)) -> B
1001 if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(1))
1002 return N1.getOperand(0);
1004 if (!VT.isVector() && SimplifyDemandedBits(SDOperand(N, 0)))
1005 return SDOperand(N, 0);
1007 // fold (a+b) -> (a|b) iff a and b share no bits.
1008 if (VT.isInteger() && !VT.isVector()) {
1009 APInt LHSZero, LHSOne;
1010 APInt RHSZero, RHSOne;
1011 APInt Mask = APInt::getAllOnesValue(VT.getSizeInBits());
1012 DAG.ComputeMaskedBits(N0, Mask, LHSZero, LHSOne);
1013 if (LHSZero.getBoolValue()) {
1014 DAG.ComputeMaskedBits(N1, Mask, RHSZero, RHSOne);
1016 // If all possibly-set bits on the LHS are clear on the RHS, return an OR.
1017 // If all possibly-set bits on the RHS are clear on the LHS, return an OR.
1018 if ((RHSZero & (~LHSZero & Mask)) == (~LHSZero & Mask) ||
1019 (LHSZero & (~RHSZero & Mask)) == (~RHSZero & Mask))
1020 return DAG.getNode(ISD::OR, VT, N0, N1);
1024 // fold (add (shl (add x, c1), c2), ) -> (add (add (shl x, c2), c1<<c2), )
1025 if (N0.getOpcode() == ISD::SHL && N0.Val->hasOneUse()) {
1026 SDOperand Result = combineShlAddConstant(N0, N1, DAG);
1027 if (Result.Val) return Result;
1029 if (N1.getOpcode() == ISD::SHL && N1.Val->hasOneUse()) {
1030 SDOperand Result = combineShlAddConstant(N1, N0, DAG);
1031 if (Result.Val) return Result;
1034 // fold (add (select cc, 0, c), x) -> (select cc, x, (add, x, c))
1035 if (N0.getOpcode() == ISD::SELECT && N0.Val->hasOneUse()) {
1036 SDOperand Result = combineSelectAndUse(N, N0, N1, DAG);
1037 if (Result.Val) return Result;
1039 if (N1.getOpcode() == ISD::SELECT && N1.Val->hasOneUse()) {
1040 SDOperand Result = combineSelectAndUse(N, N1, N0, DAG);
1041 if (Result.Val) return Result;
1047 SDOperand DAGCombiner::visitADDC(SDNode *N) {
1048 SDOperand N0 = N->getOperand(0);
1049 SDOperand N1 = N->getOperand(1);
1050 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1051 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1052 MVT VT = N0.getValueType();
1054 // If the flag result is dead, turn this into an ADD.
1055 if (N->hasNUsesOfValue(0, 1))
1056 return CombineTo(N, DAG.getNode(ISD::ADD, VT, N1, N0),
1057 DAG.getNode(ISD::CARRY_FALSE, MVT::Flag));
1059 // canonicalize constant to RHS.
1061 SDOperand Ops[] = { N1, N0 };
1062 return DAG.getNode(ISD::ADDC, N->getVTList(), Ops, 2);
1065 // fold (addc x, 0) -> x + no carry out
1066 if (N1C && N1C->isNullValue())
1067 return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE, MVT::Flag));
1069 // fold (addc a, b) -> (or a, b), CARRY_FALSE iff a and b share no bits.
1070 APInt LHSZero, LHSOne;
1071 APInt RHSZero, RHSOne;
1072 APInt Mask = APInt::getAllOnesValue(VT.getSizeInBits());
1073 DAG.ComputeMaskedBits(N0, Mask, LHSZero, LHSOne);
1074 if (LHSZero.getBoolValue()) {
1075 DAG.ComputeMaskedBits(N1, Mask, RHSZero, RHSOne);
1077 // If all possibly-set bits on the LHS are clear on the RHS, return an OR.
1078 // If all possibly-set bits on the RHS are clear on the LHS, return an OR.
1079 if ((RHSZero & (~LHSZero & Mask)) == (~LHSZero & Mask) ||
1080 (LHSZero & (~RHSZero & Mask)) == (~RHSZero & Mask))
1081 return CombineTo(N, DAG.getNode(ISD::OR, VT, N0, N1),
1082 DAG.getNode(ISD::CARRY_FALSE, MVT::Flag));
1088 SDOperand DAGCombiner::visitADDE(SDNode *N) {
1089 SDOperand N0 = N->getOperand(0);
1090 SDOperand N1 = N->getOperand(1);
1091 SDOperand CarryIn = N->getOperand(2);
1092 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1093 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1094 //MVT VT = N0.getValueType();
1096 // canonicalize constant to RHS
1098 SDOperand Ops[] = { N1, N0, CarryIn };
1099 return DAG.getNode(ISD::ADDE, N->getVTList(), Ops, 3);
1102 // fold (adde x, y, false) -> (addc x, y)
1103 if (CarryIn.getOpcode() == ISD::CARRY_FALSE) {
1104 SDOperand Ops[] = { N1, N0 };
1105 return DAG.getNode(ISD::ADDC, N->getVTList(), Ops, 2);
1113 SDOperand DAGCombiner::visitSUB(SDNode *N) {
1114 SDOperand N0 = N->getOperand(0);
1115 SDOperand N1 = N->getOperand(1);
1116 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.Val);
1117 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.Val);
1118 MVT VT = N0.getValueType();
1121 if (VT.isVector()) {
1122 SDOperand FoldedVOp = SimplifyVBinOp(N);
1123 if (FoldedVOp.Val) return FoldedVOp;
1126 // fold (sub x, x) -> 0
1128 return DAG.getConstant(0, N->getValueType(0));
1129 // fold (sub c1, c2) -> c1-c2
1131 return DAG.getNode(ISD::SUB, VT, N0, N1);
1132 // fold (sub x, c) -> (add x, -c)
1134 return DAG.getNode(ISD::ADD, VT, N0,
1135 DAG.getConstant(-N1C->getAPIntValue(), VT));
1136 // fold (A+B)-A -> B
1137 if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1)
1138 return N0.getOperand(1);
1139 // fold (A+B)-B -> A
1140 if (N0.getOpcode() == ISD::ADD && N0.getOperand(1) == N1)
1141 return N0.getOperand(0);
1142 // fold (sub x, (select cc, 0, c)) -> (select cc, x, (sub, x, c))
1143 if (N1.getOpcode() == ISD::SELECT && N1.Val->hasOneUse()) {
1144 SDOperand Result = combineSelectAndUse(N, N1, N0, DAG);
1145 if (Result.Val) return Result;
1147 // If either operand of a sub is undef, the result is undef
1148 if (N0.getOpcode() == ISD::UNDEF)
1150 if (N1.getOpcode() == ISD::UNDEF)
1156 SDOperand DAGCombiner::visitMUL(SDNode *N) {
1157 SDOperand N0 = N->getOperand(0);
1158 SDOperand N1 = N->getOperand(1);
1159 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1160 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1161 MVT VT = N0.getValueType();
1164 if (VT.isVector()) {
1165 SDOperand FoldedVOp = SimplifyVBinOp(N);
1166 if (FoldedVOp.Val) return FoldedVOp;
1169 // fold (mul x, undef) -> 0
1170 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
1171 return DAG.getConstant(0, VT);
1172 // fold (mul c1, c2) -> c1*c2
1174 return DAG.getNode(ISD::MUL, VT, N0, N1);
1175 // canonicalize constant to RHS
1177 return DAG.getNode(ISD::MUL, VT, N1, N0);
1178 // fold (mul x, 0) -> 0
1179 if (N1C && N1C->isNullValue())
1181 // fold (mul x, -1) -> 0-x
1182 if (N1C && N1C->isAllOnesValue())
1183 return DAG.getNode(ISD::SUB, VT, DAG.getConstant(0, VT), N0);
1184 // fold (mul x, (1 << c)) -> x << c
1185 if (N1C && N1C->getAPIntValue().isPowerOf2())
1186 return DAG.getNode(ISD::SHL, VT, N0,
1187 DAG.getConstant(N1C->getAPIntValue().logBase2(),
1188 TLI.getShiftAmountTy()));
1189 // fold (mul x, -(1 << c)) -> -(x << c) or (-x) << c
1190 if (N1C && isPowerOf2_64(-N1C->getSignExtended())) {
1191 // FIXME: If the input is something that is easily negated (e.g. a
1192 // single-use add), we should put the negate there.
1193 return DAG.getNode(ISD::SUB, VT, DAG.getConstant(0, VT),
1194 DAG.getNode(ISD::SHL, VT, N0,
1195 DAG.getConstant(Log2_64(-N1C->getSignExtended()),
1196 TLI.getShiftAmountTy())));
1199 // (mul (shl X, c1), c2) -> (mul X, c2 << c1)
1200 if (N1C && N0.getOpcode() == ISD::SHL &&
1201 isa<ConstantSDNode>(N0.getOperand(1))) {
1202 SDOperand C3 = DAG.getNode(ISD::SHL, VT, N1, N0.getOperand(1));
1203 AddToWorkList(C3.Val);
1204 return DAG.getNode(ISD::MUL, VT, N0.getOperand(0), C3);
1207 // Change (mul (shl X, C), Y) -> (shl (mul X, Y), C) when the shift has one
1210 SDOperand Sh(0,0), Y(0,0);
1211 // Check for both (mul (shl X, C), Y) and (mul Y, (shl X, C)).
1212 if (N0.getOpcode() == ISD::SHL && isa<ConstantSDNode>(N0.getOperand(1)) &&
1213 N0.Val->hasOneUse()) {
1215 } else if (N1.getOpcode() == ISD::SHL &&
1216 isa<ConstantSDNode>(N1.getOperand(1)) && N1.Val->hasOneUse()) {
1220 SDOperand Mul = DAG.getNode(ISD::MUL, VT, Sh.getOperand(0), Y);
1221 return DAG.getNode(ISD::SHL, VT, Mul, Sh.getOperand(1));
1224 // fold (mul (add x, c1), c2) -> (add (mul x, c2), c1*c2)
1225 if (N1C && N0.getOpcode() == ISD::ADD && N0.Val->hasOneUse() &&
1226 isa<ConstantSDNode>(N0.getOperand(1))) {
1227 return DAG.getNode(ISD::ADD, VT,
1228 DAG.getNode(ISD::MUL, VT, N0.getOperand(0), N1),
1229 DAG.getNode(ISD::MUL, VT, N0.getOperand(1), N1));
1233 SDOperand RMUL = ReassociateOps(ISD::MUL, N0, N1);
1240 SDOperand DAGCombiner::visitSDIV(SDNode *N) {
1241 SDOperand N0 = N->getOperand(0);
1242 SDOperand N1 = N->getOperand(1);
1243 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.Val);
1244 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.Val);
1245 MVT VT = N->getValueType(0);
1248 if (VT.isVector()) {
1249 SDOperand FoldedVOp = SimplifyVBinOp(N);
1250 if (FoldedVOp.Val) return FoldedVOp;
1253 // fold (sdiv c1, c2) -> c1/c2
1254 if (N0C && N1C && !N1C->isNullValue())
1255 return DAG.getNode(ISD::SDIV, VT, N0, N1);
1256 // fold (sdiv X, 1) -> X
1257 if (N1C && N1C->getSignExtended() == 1LL)
1259 // fold (sdiv X, -1) -> 0-X
1260 if (N1C && N1C->isAllOnesValue())
1261 return DAG.getNode(ISD::SUB, VT, DAG.getConstant(0, VT), N0);
1262 // If we know the sign bits of both operands are zero, strength reduce to a
1263 // udiv instead. Handles (X&15) /s 4 -> X&15 >> 2
1264 if (!VT.isVector()) {
1265 if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
1266 return DAG.getNode(ISD::UDIV, N1.getValueType(), N0, N1);
1268 // fold (sdiv X, pow2) -> simple ops after legalize
1269 if (N1C && !N1C->isNullValue() && !TLI.isIntDivCheap() &&
1270 (isPowerOf2_64(N1C->getSignExtended()) ||
1271 isPowerOf2_64(-N1C->getSignExtended()))) {
1272 // If dividing by powers of two is cheap, then don't perform the following
1274 if (TLI.isPow2DivCheap())
1276 int64_t pow2 = N1C->getSignExtended();
1277 int64_t abs2 = pow2 > 0 ? pow2 : -pow2;
1278 unsigned lg2 = Log2_64(abs2);
1279 // Splat the sign bit into the register
1280 SDOperand SGN = DAG.getNode(ISD::SRA, VT, N0,
1281 DAG.getConstant(VT.getSizeInBits()-1,
1282 TLI.getShiftAmountTy()));
1283 AddToWorkList(SGN.Val);
1284 // Add (N0 < 0) ? abs2 - 1 : 0;
1285 SDOperand SRL = DAG.getNode(ISD::SRL, VT, SGN,
1286 DAG.getConstant(VT.getSizeInBits()-lg2,
1287 TLI.getShiftAmountTy()));
1288 SDOperand ADD = DAG.getNode(ISD::ADD, VT, N0, SRL);
1289 AddToWorkList(SRL.Val);
1290 AddToWorkList(ADD.Val); // Divide by pow2
1291 SDOperand SRA = DAG.getNode(ISD::SRA, VT, ADD,
1292 DAG.getConstant(lg2, TLI.getShiftAmountTy()));
1293 // If we're dividing by a positive value, we're done. Otherwise, we must
1294 // negate the result.
1297 AddToWorkList(SRA.Val);
1298 return DAG.getNode(ISD::SUB, VT, DAG.getConstant(0, VT), SRA);
1300 // if integer divide is expensive and we satisfy the requirements, emit an
1301 // alternate sequence.
1302 if (N1C && (N1C->getSignExtended() < -1 || N1C->getSignExtended() > 1) &&
1303 !TLI.isIntDivCheap()) {
1304 SDOperand Op = BuildSDIV(N);
1305 if (Op.Val) return Op;
1309 if (N0.getOpcode() == ISD::UNDEF)
1310 return DAG.getConstant(0, VT);
1311 // X / undef -> undef
1312 if (N1.getOpcode() == ISD::UNDEF)
1318 SDOperand DAGCombiner::visitUDIV(SDNode *N) {
1319 SDOperand N0 = N->getOperand(0);
1320 SDOperand N1 = N->getOperand(1);
1321 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.Val);
1322 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.Val);
1323 MVT VT = N->getValueType(0);
1326 if (VT.isVector()) {
1327 SDOperand FoldedVOp = SimplifyVBinOp(N);
1328 if (FoldedVOp.Val) return FoldedVOp;
1331 // fold (udiv c1, c2) -> c1/c2
1332 if (N0C && N1C && !N1C->isNullValue())
1333 return DAG.getNode(ISD::UDIV, VT, N0, N1);
1334 // fold (udiv x, (1 << c)) -> x >>u c
1335 if (N1C && N1C->getAPIntValue().isPowerOf2())
1336 return DAG.getNode(ISD::SRL, VT, N0,
1337 DAG.getConstant(N1C->getAPIntValue().logBase2(),
1338 TLI.getShiftAmountTy()));
1339 // fold (udiv x, (shl c, y)) -> x >>u (log2(c)+y) iff c is power of 2
1340 if (N1.getOpcode() == ISD::SHL) {
1341 if (ConstantSDNode *SHC = dyn_cast<ConstantSDNode>(N1.getOperand(0))) {
1342 if (SHC->getAPIntValue().isPowerOf2()) {
1343 MVT ADDVT = N1.getOperand(1).getValueType();
1344 SDOperand Add = DAG.getNode(ISD::ADD, ADDVT, N1.getOperand(1),
1345 DAG.getConstant(SHC->getAPIntValue()
1348 AddToWorkList(Add.Val);
1349 return DAG.getNode(ISD::SRL, VT, N0, Add);
1353 // fold (udiv x, c) -> alternate
1354 if (N1C && !N1C->isNullValue() && !TLI.isIntDivCheap()) {
1355 SDOperand Op = BuildUDIV(N);
1356 if (Op.Val) return Op;
1360 if (N0.getOpcode() == ISD::UNDEF)
1361 return DAG.getConstant(0, VT);
1362 // X / undef -> undef
1363 if (N1.getOpcode() == ISD::UNDEF)
1369 SDOperand DAGCombiner::visitSREM(SDNode *N) {
1370 SDOperand N0 = N->getOperand(0);
1371 SDOperand N1 = N->getOperand(1);
1372 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1373 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1374 MVT VT = N->getValueType(0);
1376 // fold (srem c1, c2) -> c1%c2
1377 if (N0C && N1C && !N1C->isNullValue())
1378 return DAG.getNode(ISD::SREM, VT, N0, N1);
1379 // If we know the sign bits of both operands are zero, strength reduce to a
1380 // urem instead. Handles (X & 0x0FFFFFFF) %s 16 -> X&15
1381 if (!VT.isVector()) {
1382 if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
1383 return DAG.getNode(ISD::UREM, VT, N0, N1);
1386 // If X/C can be simplified by the division-by-constant logic, lower
1387 // X%C to the equivalent of X-X/C*C.
1388 if (N1C && !N1C->isNullValue()) {
1389 SDOperand Div = DAG.getNode(ISD::SDIV, VT, N0, N1);
1390 AddToWorkList(Div.Val);
1391 SDOperand OptimizedDiv = combine(Div.Val);
1392 if (OptimizedDiv.Val && OptimizedDiv.Val != Div.Val) {
1393 SDOperand Mul = DAG.getNode(ISD::MUL, VT, OptimizedDiv, N1);
1394 SDOperand Sub = DAG.getNode(ISD::SUB, VT, N0, Mul);
1395 AddToWorkList(Mul.Val);
1401 if (N0.getOpcode() == ISD::UNDEF)
1402 return DAG.getConstant(0, VT);
1403 // X % undef -> undef
1404 if (N1.getOpcode() == ISD::UNDEF)
1410 SDOperand DAGCombiner::visitUREM(SDNode *N) {
1411 SDOperand N0 = N->getOperand(0);
1412 SDOperand N1 = N->getOperand(1);
1413 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1414 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1415 MVT VT = N->getValueType(0);
1417 // fold (urem c1, c2) -> c1%c2
1418 if (N0C && N1C && !N1C->isNullValue())
1419 return DAG.getNode(ISD::UREM, VT, N0, N1);
1420 // fold (urem x, pow2) -> (and x, pow2-1)
1421 if (N1C && !N1C->isNullValue() && N1C->getAPIntValue().isPowerOf2())
1422 return DAG.getNode(ISD::AND, VT, N0,
1423 DAG.getConstant(N1C->getAPIntValue()-1,VT));
1424 // fold (urem x, (shl pow2, y)) -> (and x, (add (shl pow2, y), -1))
1425 if (N1.getOpcode() == ISD::SHL) {
1426 if (ConstantSDNode *SHC = dyn_cast<ConstantSDNode>(N1.getOperand(0))) {
1427 if (SHC->getAPIntValue().isPowerOf2()) {
1429 DAG.getNode(ISD::ADD, VT, N1,
1430 DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()),
1432 AddToWorkList(Add.Val);
1433 return DAG.getNode(ISD::AND, VT, N0, Add);
1438 // If X/C can be simplified by the division-by-constant logic, lower
1439 // X%C to the equivalent of X-X/C*C.
1440 if (N1C && !N1C->isNullValue()) {
1441 SDOperand Div = DAG.getNode(ISD::UDIV, VT, N0, N1);
1442 SDOperand OptimizedDiv = combine(Div.Val);
1443 if (OptimizedDiv.Val && OptimizedDiv.Val != Div.Val) {
1444 SDOperand Mul = DAG.getNode(ISD::MUL, VT, OptimizedDiv, N1);
1445 SDOperand Sub = DAG.getNode(ISD::SUB, VT, N0, Mul);
1446 AddToWorkList(Mul.Val);
1452 if (N0.getOpcode() == ISD::UNDEF)
1453 return DAG.getConstant(0, VT);
1454 // X % undef -> undef
1455 if (N1.getOpcode() == ISD::UNDEF)
1461 SDOperand DAGCombiner::visitMULHS(SDNode *N) {
1462 SDOperand N0 = N->getOperand(0);
1463 SDOperand N1 = N->getOperand(1);
1464 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1465 MVT VT = N->getValueType(0);
1467 // fold (mulhs x, 0) -> 0
1468 if (N1C && N1C->isNullValue())
1470 // fold (mulhs x, 1) -> (sra x, size(x)-1)
1471 if (N1C && N1C->getAPIntValue() == 1)
1472 return DAG.getNode(ISD::SRA, N0.getValueType(), N0,
1473 DAG.getConstant(N0.getValueType().getSizeInBits()-1,
1474 TLI.getShiftAmountTy()));
1475 // fold (mulhs x, undef) -> 0
1476 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
1477 return DAG.getConstant(0, VT);
1482 SDOperand DAGCombiner::visitMULHU(SDNode *N) {
1483 SDOperand N0 = N->getOperand(0);
1484 SDOperand N1 = N->getOperand(1);
1485 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1486 MVT VT = N->getValueType(0);
1488 // fold (mulhu x, 0) -> 0
1489 if (N1C && N1C->isNullValue())
1491 // fold (mulhu x, 1) -> 0
1492 if (N1C && N1C->getAPIntValue() == 1)
1493 return DAG.getConstant(0, N0.getValueType());
1494 // fold (mulhu x, undef) -> 0
1495 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
1496 return DAG.getConstant(0, VT);
1501 /// SimplifyNodeWithTwoResults - Perform optimizations common to nodes that
1502 /// compute two values. LoOp and HiOp give the opcodes for the two computations
1503 /// that are being performed. Return true if a simplification was made.
1505 SDOperand DAGCombiner::SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp,
1507 // If the high half is not needed, just compute the low half.
1508 bool HiExists = N->hasAnyUseOfValue(1);
1511 TLI.isOperationLegal(LoOp, N->getValueType(0)))) {
1512 SDOperand Res = DAG.getNode(LoOp, N->getValueType(0), N->op_begin(),
1513 N->getNumOperands());
1514 return CombineTo(N, Res, Res);
1517 // If the low half is not needed, just compute the high half.
1518 bool LoExists = N->hasAnyUseOfValue(0);
1521 TLI.isOperationLegal(HiOp, N->getValueType(1)))) {
1522 SDOperand Res = DAG.getNode(HiOp, N->getValueType(1), N->op_begin(),
1523 N->getNumOperands());
1524 return CombineTo(N, Res, Res);
1527 // If both halves are used, return as it is.
1528 if (LoExists && HiExists)
1531 // If the two computed results can be simplified separately, separate them.
1533 SDOperand Lo = DAG.getNode(LoOp, N->getValueType(0),
1534 N->op_begin(), N->getNumOperands());
1535 AddToWorkList(Lo.Val);
1536 SDOperand LoOpt = combine(Lo.Val);
1537 if (LoOpt.Val && LoOpt.Val != Lo.Val &&
1539 TLI.isOperationLegal(LoOpt.getOpcode(), LoOpt.getValueType())))
1540 return CombineTo(N, LoOpt, LoOpt);
1544 SDOperand Hi = DAG.getNode(HiOp, N->getValueType(1),
1545 N->op_begin(), N->getNumOperands());
1546 AddToWorkList(Hi.Val);
1547 SDOperand HiOpt = combine(Hi.Val);
1548 if (HiOpt.Val && HiOpt != Hi &&
1550 TLI.isOperationLegal(HiOpt.getOpcode(), HiOpt.getValueType())))
1551 return CombineTo(N, HiOpt, HiOpt);
1556 SDOperand DAGCombiner::visitSMUL_LOHI(SDNode *N) {
1557 SDOperand Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHS);
1558 if (Res.Val) return Res;
1563 SDOperand DAGCombiner::visitUMUL_LOHI(SDNode *N) {
1564 SDOperand Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHU);
1565 if (Res.Val) return Res;
1570 SDOperand DAGCombiner::visitSDIVREM(SDNode *N) {
1571 SDOperand Res = SimplifyNodeWithTwoResults(N, ISD::SDIV, ISD::SREM);
1572 if (Res.Val) return Res;
1577 SDOperand DAGCombiner::visitUDIVREM(SDNode *N) {
1578 SDOperand Res = SimplifyNodeWithTwoResults(N, ISD::UDIV, ISD::UREM);
1579 if (Res.Val) return Res;
1584 /// SimplifyBinOpWithSameOpcodeHands - If this is a binary operator with
1585 /// two operands of the same opcode, try to simplify it.
1586 SDOperand DAGCombiner::SimplifyBinOpWithSameOpcodeHands(SDNode *N) {
1587 SDOperand N0 = N->getOperand(0), N1 = N->getOperand(1);
1588 MVT VT = N0.getValueType();
1589 assert(N0.getOpcode() == N1.getOpcode() && "Bad input!");
1591 // For each of OP in AND/OR/XOR:
1592 // fold (OP (zext x), (zext y)) -> (zext (OP x, y))
1593 // fold (OP (sext x), (sext y)) -> (sext (OP x, y))
1594 // fold (OP (aext x), (aext y)) -> (aext (OP x, y))
1595 // fold (OP (trunc x), (trunc y)) -> (trunc (OP x, y))
1596 if ((N0.getOpcode() == ISD::ZERO_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND||
1597 N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::TRUNCATE) &&
1598 N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType()) {
1599 SDOperand ORNode = DAG.getNode(N->getOpcode(),
1600 N0.getOperand(0).getValueType(),
1601 N0.getOperand(0), N1.getOperand(0));
1602 AddToWorkList(ORNode.Val);
1603 return DAG.getNode(N0.getOpcode(), VT, ORNode);
1606 // For each of OP in SHL/SRL/SRA/AND...
1607 // fold (and (OP x, z), (OP y, z)) -> (OP (and x, y), z)
1608 // fold (or (OP x, z), (OP y, z)) -> (OP (or x, y), z)
1609 // fold (xor (OP x, z), (OP y, z)) -> (OP (xor x, y), z)
1610 if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL ||
1611 N0.getOpcode() == ISD::SRA || N0.getOpcode() == ISD::AND) &&
1612 N0.getOperand(1) == N1.getOperand(1)) {
1613 SDOperand ORNode = DAG.getNode(N->getOpcode(),
1614 N0.getOperand(0).getValueType(),
1615 N0.getOperand(0), N1.getOperand(0));
1616 AddToWorkList(ORNode.Val);
1617 return DAG.getNode(N0.getOpcode(), VT, ORNode, N0.getOperand(1));
1623 SDOperand DAGCombiner::visitAND(SDNode *N) {
1624 SDOperand N0 = N->getOperand(0);
1625 SDOperand N1 = N->getOperand(1);
1626 SDOperand LL, LR, RL, RR, CC0, CC1;
1627 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1628 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1629 MVT VT = N1.getValueType();
1630 unsigned BitWidth = VT.getSizeInBits();
1633 if (VT.isVector()) {
1634 SDOperand FoldedVOp = SimplifyVBinOp(N);
1635 if (FoldedVOp.Val) return FoldedVOp;
1638 // fold (and x, undef) -> 0
1639 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
1640 return DAG.getConstant(0, VT);
1641 // fold (and c1, c2) -> c1&c2
1643 return DAG.getNode(ISD::AND, VT, N0, N1);
1644 // canonicalize constant to RHS
1646 return DAG.getNode(ISD::AND, VT, N1, N0);
1647 // fold (and x, -1) -> x
1648 if (N1C && N1C->isAllOnesValue())
1650 // if (and x, c) is known to be zero, return 0
1651 if (N1C && DAG.MaskedValueIsZero(SDOperand(N, 0),
1652 APInt::getAllOnesValue(BitWidth)))
1653 return DAG.getConstant(0, VT);
1655 SDOperand RAND = ReassociateOps(ISD::AND, N0, N1);
1658 // fold (and (or x, 0xFFFF), 0xFF) -> 0xFF
1659 if (N1C && N0.getOpcode() == ISD::OR)
1660 if (ConstantSDNode *ORI = dyn_cast<ConstantSDNode>(N0.getOperand(1)))
1661 if ((ORI->getAPIntValue() & N1C->getAPIntValue()) == N1C->getAPIntValue())
1663 // fold (and (any_ext V), c) -> (zero_ext V) if 'and' only clears top bits.
1664 if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
1665 SDOperand N0Op0 = N0.getOperand(0);
1666 APInt Mask = ~N1C->getAPIntValue();
1667 Mask.trunc(N0Op0.getValueSizeInBits());
1668 if (DAG.MaskedValueIsZero(N0Op0, Mask)) {
1669 SDOperand Zext = DAG.getNode(ISD::ZERO_EXTEND, N0.getValueType(),
1672 // Replace uses of the AND with uses of the Zero extend node.
1675 // We actually want to replace all uses of the any_extend with the
1676 // zero_extend, to avoid duplicating things. This will later cause this
1677 // AND to be folded.
1678 CombineTo(N0.Val, Zext);
1679 return SDOperand(N, 0); // Return N so it doesn't get rechecked!
1682 // fold (and (setcc x), (setcc y)) -> (setcc (and x, y))
1683 if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){
1684 ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get();
1685 ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get();
1687 if (LR == RR && isa<ConstantSDNode>(LR) && Op0 == Op1 &&
1688 LL.getValueType().isInteger()) {
1689 // fold (X == 0) & (Y == 0) -> (X|Y == 0)
1690 if (cast<ConstantSDNode>(LR)->isNullValue() && Op1 == ISD::SETEQ) {
1691 SDOperand ORNode = DAG.getNode(ISD::OR, LR.getValueType(), LL, RL);
1692 AddToWorkList(ORNode.Val);
1693 return DAG.getSetCC(VT, ORNode, LR, Op1);
1695 // fold (X == -1) & (Y == -1) -> (X&Y == -1)
1696 if (cast<ConstantSDNode>(LR)->isAllOnesValue() && Op1 == ISD::SETEQ) {
1697 SDOperand ANDNode = DAG.getNode(ISD::AND, LR.getValueType(), LL, RL);
1698 AddToWorkList(ANDNode.Val);
1699 return DAG.getSetCC(VT, ANDNode, LR, Op1);
1701 // fold (X > -1) & (Y > -1) -> (X|Y > -1)
1702 if (cast<ConstantSDNode>(LR)->isAllOnesValue() && Op1 == ISD::SETGT) {
1703 SDOperand ORNode = DAG.getNode(ISD::OR, LR.getValueType(), LL, RL);
1704 AddToWorkList(ORNode.Val);
1705 return DAG.getSetCC(VT, ORNode, LR, Op1);
1708 // canonicalize equivalent to ll == rl
1709 if (LL == RR && LR == RL) {
1710 Op1 = ISD::getSetCCSwappedOperands(Op1);
1713 if (LL == RL && LR == RR) {
1714 bool isInteger = LL.getValueType().isInteger();
1715 ISD::CondCode Result = ISD::getSetCCAndOperation(Op0, Op1, isInteger);
1716 if (Result != ISD::SETCC_INVALID)
1717 return DAG.getSetCC(N0.getValueType(), LL, LR, Result);
1721 // Simplify: and (op x...), (op y...) -> (op (and x, y))
1722 if (N0.getOpcode() == N1.getOpcode()) {
1723 SDOperand Tmp = SimplifyBinOpWithSameOpcodeHands(N);
1724 if (Tmp.Val) return Tmp;
1727 // fold (and (sign_extend_inreg x, i16 to i32), 1) -> (and x, 1)
1728 // fold (and (sra)) -> (and (srl)) when possible.
1729 if (!VT.isVector() &&
1730 SimplifyDemandedBits(SDOperand(N, 0)))
1731 return SDOperand(N, 0);
1732 // fold (zext_inreg (extload x)) -> (zextload x)
1733 if (ISD::isEXTLoad(N0.Val) && ISD::isUNINDEXEDLoad(N0.Val)) {
1734 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
1735 MVT EVT = LN0->getMemoryVT();
1736 // If we zero all the possible extended bits, then we can turn this into
1737 // a zextload if we are running before legalize or the operation is legal.
1738 unsigned BitWidth = N1.getValueSizeInBits();
1739 if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth,
1740 BitWidth - EVT.getSizeInBits())) &&
1741 ((!AfterLegalize && !LN0->isVolatile()) ||
1742 TLI.isLoadXLegal(ISD::ZEXTLOAD, EVT))) {
1743 SDOperand ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, VT, LN0->getChain(),
1744 LN0->getBasePtr(), LN0->getSrcValue(),
1745 LN0->getSrcValueOffset(), EVT,
1747 LN0->getAlignment());
1749 CombineTo(N0.Val, ExtLoad, ExtLoad.getValue(1));
1750 return SDOperand(N, 0); // Return N so it doesn't get rechecked!
1753 // fold (zext_inreg (sextload x)) -> (zextload x) iff load has one use
1754 if (ISD::isSEXTLoad(N0.Val) && ISD::isUNINDEXEDLoad(N0.Val) &&
1756 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
1757 MVT EVT = LN0->getMemoryVT();
1758 // If we zero all the possible extended bits, then we can turn this into
1759 // a zextload if we are running before legalize or the operation is legal.
1760 unsigned BitWidth = N1.getValueSizeInBits();
1761 if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth,
1762 BitWidth - EVT.getSizeInBits())) &&
1763 ((!AfterLegalize && !LN0->isVolatile()) ||
1764 TLI.isLoadXLegal(ISD::ZEXTLOAD, EVT))) {
1765 SDOperand ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, VT, LN0->getChain(),
1766 LN0->getBasePtr(), LN0->getSrcValue(),
1767 LN0->getSrcValueOffset(), EVT,
1769 LN0->getAlignment());
1771 CombineTo(N0.Val, ExtLoad, ExtLoad.getValue(1));
1772 return SDOperand(N, 0); // Return N so it doesn't get rechecked!
1776 // fold (and (load x), 255) -> (zextload x, i8)
1777 // fold (and (extload x, i16), 255) -> (zextload x, i8)
1778 if (N1C && N0.getOpcode() == ISD::LOAD) {
1779 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
1780 if (LN0->getExtensionType() != ISD::SEXTLOAD &&
1781 LN0->isUnindexed() && N0.hasOneUse() &&
1782 // Do not change the width of a volatile load.
1783 !LN0->isVolatile()) {
1784 MVT EVT = MVT::Other;
1785 uint32_t ActiveBits = N1C->getAPIntValue().getActiveBits();
1786 if (ActiveBits > 0 && APIntOps::isMask(ActiveBits, N1C->getAPIntValue()))
1787 EVT = MVT::getIntegerVT(ActiveBits);
1789 MVT LoadedVT = LN0->getMemoryVT();
1790 // Do not generate loads of non-round integer types since these can
1791 // be expensive (and would be wrong if the type is not byte sized).
1792 if (EVT != MVT::Other && LoadedVT.bitsGT(EVT) && EVT.isRound() &&
1793 (!AfterLegalize || TLI.isLoadXLegal(ISD::ZEXTLOAD, EVT))) {
1794 MVT PtrType = N0.getOperand(1).getValueType();
1795 // For big endian targets, we need to add an offset to the pointer to
1796 // load the correct bytes. For little endian systems, we merely need to
1797 // read fewer bytes from the same pointer.
1798 unsigned LVTStoreBytes = LoadedVT.getStoreSizeInBits()/8;
1799 unsigned EVTStoreBytes = EVT.getStoreSizeInBits()/8;
1800 unsigned PtrOff = LVTStoreBytes - EVTStoreBytes;
1801 unsigned Alignment = LN0->getAlignment();
1802 SDOperand NewPtr = LN0->getBasePtr();
1803 if (TLI.isBigEndian()) {
1804 NewPtr = DAG.getNode(ISD::ADD, PtrType, NewPtr,
1805 DAG.getConstant(PtrOff, PtrType));
1806 Alignment = MinAlign(Alignment, PtrOff);
1808 AddToWorkList(NewPtr.Val);
1810 DAG.getExtLoad(ISD::ZEXTLOAD, VT, LN0->getChain(), NewPtr,
1811 LN0->getSrcValue(), LN0->getSrcValueOffset(), EVT,
1812 LN0->isVolatile(), Alignment);
1814 CombineTo(N0.Val, Load, Load.getValue(1));
1815 return SDOperand(N, 0); // Return N so it doesn't get rechecked!
1823 SDOperand DAGCombiner::visitOR(SDNode *N) {
1824 SDOperand N0 = N->getOperand(0);
1825 SDOperand N1 = N->getOperand(1);
1826 SDOperand LL, LR, RL, RR, CC0, CC1;
1827 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1828 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1829 MVT VT = N1.getValueType();
1832 if (VT.isVector()) {
1833 SDOperand FoldedVOp = SimplifyVBinOp(N);
1834 if (FoldedVOp.Val) return FoldedVOp;
1837 // fold (or x, undef) -> -1
1838 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
1839 return DAG.getConstant(~0ULL, VT);
1840 // fold (or c1, c2) -> c1|c2
1842 return DAG.getNode(ISD::OR, VT, N0, N1);
1843 // canonicalize constant to RHS
1845 return DAG.getNode(ISD::OR, VT, N1, N0);
1846 // fold (or x, 0) -> x
1847 if (N1C && N1C->isNullValue())
1849 // fold (or x, -1) -> -1
1850 if (N1C && N1C->isAllOnesValue())
1852 // fold (or x, c) -> c iff (x & ~c) == 0
1853 if (N1C && DAG.MaskedValueIsZero(N0, ~N1C->getAPIntValue()))
1856 SDOperand ROR = ReassociateOps(ISD::OR, N0, N1);
1859 // Canonicalize (or (and X, c1), c2) -> (and (or X, c2), c1|c2)
1860 if (N1C && N0.getOpcode() == ISD::AND && N0.Val->hasOneUse() &&
1861 isa<ConstantSDNode>(N0.getOperand(1))) {
1862 ConstantSDNode *C1 = cast<ConstantSDNode>(N0.getOperand(1));
1863 return DAG.getNode(ISD::AND, VT, DAG.getNode(ISD::OR, VT, N0.getOperand(0),
1865 DAG.getConstant(N1C->getAPIntValue() |
1866 C1->getAPIntValue(), VT));
1868 // fold (or (setcc x), (setcc y)) -> (setcc (or x, y))
1869 if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){
1870 ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get();
1871 ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get();
1873 if (LR == RR && isa<ConstantSDNode>(LR) && Op0 == Op1 &&
1874 LL.getValueType().isInteger()) {
1875 // fold (X != 0) | (Y != 0) -> (X|Y != 0)
1876 // fold (X < 0) | (Y < 0) -> (X|Y < 0)
1877 if (cast<ConstantSDNode>(LR)->isNullValue() &&
1878 (Op1 == ISD::SETNE || Op1 == ISD::SETLT)) {
1879 SDOperand ORNode = DAG.getNode(ISD::OR, LR.getValueType(), LL, RL);
1880 AddToWorkList(ORNode.Val);
1881 return DAG.getSetCC(VT, ORNode, LR, Op1);
1883 // fold (X != -1) | (Y != -1) -> (X&Y != -1)
1884 // fold (X > -1) | (Y > -1) -> (X&Y > -1)
1885 if (cast<ConstantSDNode>(LR)->isAllOnesValue() &&
1886 (Op1 == ISD::SETNE || Op1 == ISD::SETGT)) {
1887 SDOperand ANDNode = DAG.getNode(ISD::AND, LR.getValueType(), LL, RL);
1888 AddToWorkList(ANDNode.Val);
1889 return DAG.getSetCC(VT, ANDNode, LR, Op1);
1892 // canonicalize equivalent to ll == rl
1893 if (LL == RR && LR == RL) {
1894 Op1 = ISD::getSetCCSwappedOperands(Op1);
1897 if (LL == RL && LR == RR) {
1898 bool isInteger = LL.getValueType().isInteger();
1899 ISD::CondCode Result = ISD::getSetCCOrOperation(Op0, Op1, isInteger);
1900 if (Result != ISD::SETCC_INVALID)
1901 return DAG.getSetCC(N0.getValueType(), LL, LR, Result);
1905 // Simplify: or (op x...), (op y...) -> (op (or x, y))
1906 if (N0.getOpcode() == N1.getOpcode()) {
1907 SDOperand Tmp = SimplifyBinOpWithSameOpcodeHands(N);
1908 if (Tmp.Val) return Tmp;
1911 // (X & C1) | (Y & C2) -> (X|Y) & C3 if possible.
1912 if (N0.getOpcode() == ISD::AND &&
1913 N1.getOpcode() == ISD::AND &&
1914 N0.getOperand(1).getOpcode() == ISD::Constant &&
1915 N1.getOperand(1).getOpcode() == ISD::Constant &&
1916 // Don't increase # computations.
1917 (N0.Val->hasOneUse() || N1.Val->hasOneUse())) {
1918 // We can only do this xform if we know that bits from X that are set in C2
1919 // but not in C1 are already zero. Likewise for Y.
1920 const APInt &LHSMask =
1921 cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
1922 const APInt &RHSMask =
1923 cast<ConstantSDNode>(N1.getOperand(1))->getAPIntValue();
1925 if (DAG.MaskedValueIsZero(N0.getOperand(0), RHSMask&~LHSMask) &&
1926 DAG.MaskedValueIsZero(N1.getOperand(0), LHSMask&~RHSMask)) {
1927 SDOperand X =DAG.getNode(ISD::OR, VT, N0.getOperand(0), N1.getOperand(0));
1928 return DAG.getNode(ISD::AND, VT, X, DAG.getConstant(LHSMask|RHSMask, VT));
1933 // See if this is some rotate idiom.
1934 if (SDNode *Rot = MatchRotate(N0, N1))
1935 return SDOperand(Rot, 0);
1941 /// MatchRotateHalf - Match "(X shl/srl V1) & V2" where V2 may not be present.
1942 static bool MatchRotateHalf(SDOperand Op, SDOperand &Shift, SDOperand &Mask) {
1943 if (Op.getOpcode() == ISD::AND) {
1944 if (isa<ConstantSDNode>(Op.getOperand(1))) {
1945 Mask = Op.getOperand(1);
1946 Op = Op.getOperand(0);
1952 if (Op.getOpcode() == ISD::SRL || Op.getOpcode() == ISD::SHL) {
1960 // MatchRotate - Handle an 'or' of two operands. If this is one of the many
1961 // idioms for rotate, and if the target supports rotation instructions, generate
1963 SDNode *DAGCombiner::MatchRotate(SDOperand LHS, SDOperand RHS) {
1964 // Must be a legal type. Expanded 'n promoted things won't work with rotates.
1965 MVT VT = LHS.getValueType();
1966 if (!TLI.isTypeLegal(VT)) return 0;
1968 // The target must have at least one rotate flavor.
1969 bool HasROTL = TLI.isOperationLegal(ISD::ROTL, VT);
1970 bool HasROTR = TLI.isOperationLegal(ISD::ROTR, VT);
1971 if (!HasROTL && !HasROTR) return 0;
1973 // Match "(X shl/srl V1) & V2" where V2 may not be present.
1974 SDOperand LHSShift; // The shift.
1975 SDOperand LHSMask; // AND value if any.
1976 if (!MatchRotateHalf(LHS, LHSShift, LHSMask))
1977 return 0; // Not part of a rotate.
1979 SDOperand RHSShift; // The shift.
1980 SDOperand RHSMask; // AND value if any.
1981 if (!MatchRotateHalf(RHS, RHSShift, RHSMask))
1982 return 0; // Not part of a rotate.
1984 if (LHSShift.getOperand(0) != RHSShift.getOperand(0))
1985 return 0; // Not shifting the same value.
1987 if (LHSShift.getOpcode() == RHSShift.getOpcode())
1988 return 0; // Shifts must disagree.
1990 // Canonicalize shl to left side in a shl/srl pair.
1991 if (RHSShift.getOpcode() == ISD::SHL) {
1992 std::swap(LHS, RHS);
1993 std::swap(LHSShift, RHSShift);
1994 std::swap(LHSMask , RHSMask );
1997 unsigned OpSizeInBits = VT.getSizeInBits();
1998 SDOperand LHSShiftArg = LHSShift.getOperand(0);
1999 SDOperand LHSShiftAmt = LHSShift.getOperand(1);
2000 SDOperand RHSShiftAmt = RHSShift.getOperand(1);
2002 // fold (or (shl x, C1), (srl x, C2)) -> (rotl x, C1)
2003 // fold (or (shl x, C1), (srl x, C2)) -> (rotr x, C2)
2004 if (LHSShiftAmt.getOpcode() == ISD::Constant &&
2005 RHSShiftAmt.getOpcode() == ISD::Constant) {
2006 uint64_t LShVal = cast<ConstantSDNode>(LHSShiftAmt)->getValue();
2007 uint64_t RShVal = cast<ConstantSDNode>(RHSShiftAmt)->getValue();
2008 if ((LShVal + RShVal) != OpSizeInBits)
2013 Rot = DAG.getNode(ISD::ROTL, VT, LHSShiftArg, LHSShiftAmt);
2015 Rot = DAG.getNode(ISD::ROTR, VT, LHSShiftArg, RHSShiftAmt);
2017 // If there is an AND of either shifted operand, apply it to the result.
2018 if (LHSMask.Val || RHSMask.Val) {
2019 APInt Mask = APInt::getAllOnesValue(OpSizeInBits);
2022 APInt RHSBits = APInt::getLowBitsSet(OpSizeInBits, LShVal);
2023 Mask &= cast<ConstantSDNode>(LHSMask)->getAPIntValue() | RHSBits;
2026 APInt LHSBits = APInt::getHighBitsSet(OpSizeInBits, RShVal);
2027 Mask &= cast<ConstantSDNode>(RHSMask)->getAPIntValue() | LHSBits;
2030 Rot = DAG.getNode(ISD::AND, VT, Rot, DAG.getConstant(Mask, VT));
2036 // If there is a mask here, and we have a variable shift, we can't be sure
2037 // that we're masking out the right stuff.
2038 if (LHSMask.Val || RHSMask.Val)
2041 // fold (or (shl x, y), (srl x, (sub 32, y))) -> (rotl x, y)
2042 // fold (or (shl x, y), (srl x, (sub 32, y))) -> (rotr x, (sub 32, y))
2043 if (RHSShiftAmt.getOpcode() == ISD::SUB &&
2044 LHSShiftAmt == RHSShiftAmt.getOperand(1)) {
2045 if (ConstantSDNode *SUBC =
2046 dyn_cast<ConstantSDNode>(RHSShiftAmt.getOperand(0))) {
2047 if (SUBC->getAPIntValue() == OpSizeInBits) {
2049 return DAG.getNode(ISD::ROTL, VT, LHSShiftArg, LHSShiftAmt).Val;
2051 return DAG.getNode(ISD::ROTR, VT, LHSShiftArg, RHSShiftAmt).Val;
2056 // fold (or (shl x, (sub 32, y)), (srl x, r)) -> (rotr x, y)
2057 // fold (or (shl x, (sub 32, y)), (srl x, r)) -> (rotl x, (sub 32, y))
2058 if (LHSShiftAmt.getOpcode() == ISD::SUB &&
2059 RHSShiftAmt == LHSShiftAmt.getOperand(1)) {
2060 if (ConstantSDNode *SUBC =
2061 dyn_cast<ConstantSDNode>(LHSShiftAmt.getOperand(0))) {
2062 if (SUBC->getAPIntValue() == OpSizeInBits) {
2064 return DAG.getNode(ISD::ROTL, VT, LHSShiftArg, LHSShiftAmt).Val;
2066 return DAG.getNode(ISD::ROTR, VT, LHSShiftArg, RHSShiftAmt).Val;
2071 // Look for sign/zext/any-extended cases:
2072 if ((LHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND
2073 || LHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND
2074 || LHSShiftAmt.getOpcode() == ISD::ANY_EXTEND) &&
2075 (RHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND
2076 || RHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND
2077 || RHSShiftAmt.getOpcode() == ISD::ANY_EXTEND)) {
2078 SDOperand LExtOp0 = LHSShiftAmt.getOperand(0);
2079 SDOperand RExtOp0 = RHSShiftAmt.getOperand(0);
2080 if (RExtOp0.getOpcode() == ISD::SUB &&
2081 RExtOp0.getOperand(1) == LExtOp0) {
2082 // fold (or (shl x, (*ext y)), (srl x, (*ext (sub 32, y)))) ->
2084 // fold (or (shl x, (*ext y)), (srl x, (*ext (sub 32, y)))) ->
2085 // (rotl x, (sub 32, y))
2086 if (ConstantSDNode *SUBC = cast<ConstantSDNode>(RExtOp0.getOperand(0))) {
2087 if (SUBC->getAPIntValue() == OpSizeInBits) {
2089 return DAG.getNode(ISD::ROTL, VT, LHSShiftArg, LHSShiftAmt).Val;
2091 return DAG.getNode(ISD::ROTR, VT, LHSShiftArg, RHSShiftAmt).Val;
2094 } else if (LExtOp0.getOpcode() == ISD::SUB &&
2095 RExtOp0 == LExtOp0.getOperand(1)) {
2096 // fold (or (shl x, (*ext (sub 32, y))), (srl x, (*ext r))) ->
2098 // fold (or (shl x, (*ext (sub 32, y))), (srl x, (*ext r))) ->
2099 // (rotr x, (sub 32, y))
2100 if (ConstantSDNode *SUBC = cast<ConstantSDNode>(LExtOp0.getOperand(0))) {
2101 if (SUBC->getAPIntValue() == OpSizeInBits) {
2103 return DAG.getNode(ISD::ROTL, VT, LHSShiftArg, RHSShiftAmt).Val;
2105 return DAG.getNode(ISD::ROTL, VT, LHSShiftArg, LHSShiftAmt).Val;
2115 SDOperand DAGCombiner::visitXOR(SDNode *N) {
2116 SDOperand N0 = N->getOperand(0);
2117 SDOperand N1 = N->getOperand(1);
2118 SDOperand LHS, RHS, CC;
2119 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
2120 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2121 MVT VT = N0.getValueType();
2124 if (VT.isVector()) {
2125 SDOperand FoldedVOp = SimplifyVBinOp(N);
2126 if (FoldedVOp.Val) return FoldedVOp;
2129 // fold (xor undef, undef) -> 0. This is a common idiom (misuse).
2130 if (N0.getOpcode() == ISD::UNDEF && N1.getOpcode() == ISD::UNDEF)
2131 return DAG.getConstant(0, VT);
2132 // fold (xor x, undef) -> undef
2133 if (N0.getOpcode() == ISD::UNDEF)
2135 if (N1.getOpcode() == ISD::UNDEF)
2137 // fold (xor c1, c2) -> c1^c2
2139 return DAG.getNode(ISD::XOR, VT, N0, N1);
2140 // canonicalize constant to RHS
2142 return DAG.getNode(ISD::XOR, VT, N1, N0);
2143 // fold (xor x, 0) -> x
2144 if (N1C && N1C->isNullValue())
2147 SDOperand RXOR = ReassociateOps(ISD::XOR, N0, N1);
2150 // fold !(x cc y) -> (x !cc y)
2151 if (N1C && N1C->getAPIntValue() == 1 && isSetCCEquivalent(N0, LHS, RHS, CC)) {
2152 bool isInt = LHS.getValueType().isInteger();
2153 ISD::CondCode NotCC = ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(),
2155 if (N0.getOpcode() == ISD::SETCC)
2156 return DAG.getSetCC(VT, LHS, RHS, NotCC);
2157 if (N0.getOpcode() == ISD::SELECT_CC)
2158 return DAG.getSelectCC(LHS, RHS, N0.getOperand(2),N0.getOperand(3),NotCC);
2159 assert(0 && "Unhandled SetCC Equivalent!");
2162 // fold (not (zext (setcc x, y))) -> (zext (not (setcc x, y)))
2163 if (N1C && N1C->getAPIntValue() == 1 && N0.getOpcode() == ISD::ZERO_EXTEND &&
2164 N0.Val->hasOneUse() && isSetCCEquivalent(N0.getOperand(0), LHS, RHS, CC)){
2165 SDOperand V = N0.getOperand(0);
2166 V = DAG.getNode(ISD::XOR, V.getValueType(), V,
2167 DAG.getConstant(1, V.getValueType()));
2168 AddToWorkList(V.Val);
2169 return DAG.getNode(ISD::ZERO_EXTEND, VT, V);
2172 // fold !(x or y) -> (!x and !y) iff x or y are setcc
2173 if (N1C && N1C->getAPIntValue() == 1 && VT == MVT::i1 &&
2174 (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
2175 SDOperand LHS = N0.getOperand(0), RHS = N0.getOperand(1);
2176 if (isOneUseSetCC(RHS) || isOneUseSetCC(LHS)) {
2177 unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
2178 LHS = DAG.getNode(ISD::XOR, VT, LHS, N1); // RHS = ~LHS
2179 RHS = DAG.getNode(ISD::XOR, VT, RHS, N1); // RHS = ~RHS
2180 AddToWorkList(LHS.Val); AddToWorkList(RHS.Val);
2181 return DAG.getNode(NewOpcode, VT, LHS, RHS);
2184 // fold !(x or y) -> (!x and !y) iff x or y are constants
2185 if (N1C && N1C->isAllOnesValue() &&
2186 (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
2187 SDOperand LHS = N0.getOperand(0), RHS = N0.getOperand(1);
2188 if (isa<ConstantSDNode>(RHS) || isa<ConstantSDNode>(LHS)) {
2189 unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
2190 LHS = DAG.getNode(ISD::XOR, VT, LHS, N1); // RHS = ~LHS
2191 RHS = DAG.getNode(ISD::XOR, VT, RHS, N1); // RHS = ~RHS
2192 AddToWorkList(LHS.Val); AddToWorkList(RHS.Val);
2193 return DAG.getNode(NewOpcode, VT, LHS, RHS);
2196 // fold (xor (xor x, c1), c2) -> (xor x, c1^c2)
2197 if (N1C && N0.getOpcode() == ISD::XOR) {
2198 ConstantSDNode *N00C = dyn_cast<ConstantSDNode>(N0.getOperand(0));
2199 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
2201 return DAG.getNode(ISD::XOR, VT, N0.getOperand(1),
2202 DAG.getConstant(N1C->getAPIntValue()^
2203 N00C->getAPIntValue(), VT));
2205 return DAG.getNode(ISD::XOR, VT, N0.getOperand(0),
2206 DAG.getConstant(N1C->getAPIntValue()^
2207 N01C->getAPIntValue(), VT));
2209 // fold (xor x, x) -> 0
2211 if (!VT.isVector()) {
2212 return DAG.getConstant(0, VT);
2213 } else if (!AfterLegalize || TLI.isOperationLegal(ISD::BUILD_VECTOR, VT)) {
2214 // Produce a vector of zeros.
2215 SDOperand El = DAG.getConstant(0, VT.getVectorElementType());
2216 std::vector<SDOperand> Ops(VT.getVectorNumElements(), El);
2217 return DAG.getNode(ISD::BUILD_VECTOR, VT, &Ops[0], Ops.size());
2221 // Simplify: xor (op x...), (op y...) -> (op (xor x, y))
2222 if (N0.getOpcode() == N1.getOpcode()) {
2223 SDOperand Tmp = SimplifyBinOpWithSameOpcodeHands(N);
2224 if (Tmp.Val) return Tmp;
2227 // Simplify the expression using non-local knowledge.
2228 if (!VT.isVector() &&
2229 SimplifyDemandedBits(SDOperand(N, 0)))
2230 return SDOperand(N, 0);
2235 /// visitShiftByConstant - Handle transforms common to the three shifts, when
2236 /// the shift amount is a constant.
2237 SDOperand DAGCombiner::visitShiftByConstant(SDNode *N, unsigned Amt) {
2238 SDNode *LHS = N->getOperand(0).Val;
2239 if (!LHS->hasOneUse()) return SDOperand();
2241 // We want to pull some binops through shifts, so that we have (and (shift))
2242 // instead of (shift (and)), likewise for add, or, xor, etc. This sort of
2243 // thing happens with address calculations, so it's important to canonicalize
2245 bool HighBitSet = false; // Can we transform this if the high bit is set?
2247 switch (LHS->getOpcode()) {
2248 default: return SDOperand();
2251 HighBitSet = false; // We can only transform sra if the high bit is clear.
2254 HighBitSet = true; // We can only transform sra if the high bit is set.
2257 if (N->getOpcode() != ISD::SHL)
2258 return SDOperand(); // only shl(add) not sr[al](add).
2259 HighBitSet = false; // We can only transform sra if the high bit is clear.
2263 // We require the RHS of the binop to be a constant as well.
2264 ConstantSDNode *BinOpCst = dyn_cast<ConstantSDNode>(LHS->getOperand(1));
2265 if (!BinOpCst) return SDOperand();
2268 // FIXME: disable this for unless the input to the binop is a shift by a
2269 // constant. If it is not a shift, it pessimizes some common cases like:
2271 //void foo(int *X, int i) { X[i & 1235] = 1; }
2272 //int bar(int *X, int i) { return X[i & 255]; }
2273 SDNode *BinOpLHSVal = LHS->getOperand(0).Val;
2274 if ((BinOpLHSVal->getOpcode() != ISD::SHL &&
2275 BinOpLHSVal->getOpcode() != ISD::SRA &&
2276 BinOpLHSVal->getOpcode() != ISD::SRL) ||
2277 !isa<ConstantSDNode>(BinOpLHSVal->getOperand(1)))
2280 MVT VT = N->getValueType(0);
2282 // If this is a signed shift right, and the high bit is modified
2283 // by the logical operation, do not perform the transformation.
2284 // The highBitSet boolean indicates the value of the high bit of
2285 // the constant which would cause it to be modified for this
2287 if (N->getOpcode() == ISD::SRA) {
2288 bool BinOpRHSSignSet = BinOpCst->getAPIntValue().isNegative();
2289 if (BinOpRHSSignSet != HighBitSet)
2293 // Fold the constants, shifting the binop RHS by the shift amount.
2294 SDOperand NewRHS = DAG.getNode(N->getOpcode(), N->getValueType(0),
2295 LHS->getOperand(1), N->getOperand(1));
2297 // Create the new shift.
2298 SDOperand NewShift = DAG.getNode(N->getOpcode(), VT, LHS->getOperand(0),
2301 // Create the new binop.
2302 return DAG.getNode(LHS->getOpcode(), VT, NewShift, NewRHS);
2306 SDOperand DAGCombiner::visitSHL(SDNode *N) {
2307 SDOperand N0 = N->getOperand(0);
2308 SDOperand N1 = N->getOperand(1);
2309 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
2310 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2311 MVT VT = N0.getValueType();
2312 unsigned OpSizeInBits = VT.getSizeInBits();
2314 // fold (shl c1, c2) -> c1<<c2
2316 return DAG.getNode(ISD::SHL, VT, N0, N1);
2317 // fold (shl 0, x) -> 0
2318 if (N0C && N0C->isNullValue())
2320 // fold (shl x, c >= size(x)) -> undef
2321 if (N1C && N1C->getValue() >= OpSizeInBits)
2322 return DAG.getNode(ISD::UNDEF, VT);
2323 // fold (shl x, 0) -> x
2324 if (N1C && N1C->isNullValue())
2326 // if (shl x, c) is known to be zero, return 0
2327 if (DAG.MaskedValueIsZero(SDOperand(N, 0),
2328 APInt::getAllOnesValue(VT.getSizeInBits())))
2329 return DAG.getConstant(0, VT);
2330 if (N1C && SimplifyDemandedBits(SDOperand(N, 0)))
2331 return SDOperand(N, 0);
2332 // fold (shl (shl x, c1), c2) -> 0 or (shl x, c1+c2)
2333 if (N1C && N0.getOpcode() == ISD::SHL &&
2334 N0.getOperand(1).getOpcode() == ISD::Constant) {
2335 uint64_t c1 = cast<ConstantSDNode>(N0.getOperand(1))->getValue();
2336 uint64_t c2 = N1C->getValue();
2337 if (c1 + c2 > OpSizeInBits)
2338 return DAG.getConstant(0, VT);
2339 return DAG.getNode(ISD::SHL, VT, N0.getOperand(0),
2340 DAG.getConstant(c1 + c2, N1.getValueType()));
2342 // fold (shl (srl x, c1), c2) -> (shl (and x, -1 << c1), c2-c1) or
2343 // (srl (and x, -1 << c1), c1-c2)
2344 if (N1C && N0.getOpcode() == ISD::SRL &&
2345 N0.getOperand(1).getOpcode() == ISD::Constant) {
2346 uint64_t c1 = cast<ConstantSDNode>(N0.getOperand(1))->getValue();
2347 uint64_t c2 = N1C->getValue();
2348 SDOperand Mask = DAG.getNode(ISD::AND, VT, N0.getOperand(0),
2349 DAG.getConstant(~0ULL << c1, VT));
2351 return DAG.getNode(ISD::SHL, VT, Mask,
2352 DAG.getConstant(c2-c1, N1.getValueType()));
2354 return DAG.getNode(ISD::SRL, VT, Mask,
2355 DAG.getConstant(c1-c2, N1.getValueType()));
2357 // fold (shl (sra x, c1), c1) -> (and x, -1 << c1)
2358 if (N1C && N0.getOpcode() == ISD::SRA && N1 == N0.getOperand(1))
2359 return DAG.getNode(ISD::AND, VT, N0.getOperand(0),
2360 DAG.getConstant(~0ULL << N1C->getValue(), VT));
2362 return N1C ? visitShiftByConstant(N, N1C->getValue()) : SDOperand();
2365 SDOperand DAGCombiner::visitSRA(SDNode *N) {
2366 SDOperand N0 = N->getOperand(0);
2367 SDOperand N1 = N->getOperand(1);
2368 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
2369 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2370 MVT VT = N0.getValueType();
2372 // fold (sra c1, c2) -> c1>>c2
2374 return DAG.getNode(ISD::SRA, VT, N0, N1);
2375 // fold (sra 0, x) -> 0
2376 if (N0C && N0C->isNullValue())
2378 // fold (sra -1, x) -> -1
2379 if (N0C && N0C->isAllOnesValue())
2381 // fold (sra x, c >= size(x)) -> undef
2382 if (N1C && N1C->getValue() >= VT.getSizeInBits())
2383 return DAG.getNode(ISD::UNDEF, VT);
2384 // fold (sra x, 0) -> x
2385 if (N1C && N1C->isNullValue())
2387 // fold (sra (shl x, c1), c1) -> sext_inreg for some c1 and target supports
2389 if (N1C && N0.getOpcode() == ISD::SHL && N1 == N0.getOperand(1)) {
2390 unsigned LowBits = VT.getSizeInBits() - (unsigned)N1C->getValue();
2391 MVT EVT = MVT::getIntegerVT(LowBits);
2392 if (EVT.isSimple() && // TODO: remove when apint codegen support lands.
2393 (!AfterLegalize || TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, EVT)))
2394 return DAG.getNode(ISD::SIGN_EXTEND_INREG, VT, N0.getOperand(0),
2395 DAG.getValueType(EVT));
2398 // fold (sra (sra x, c1), c2) -> (sra x, c1+c2)
2399 if (N1C && N0.getOpcode() == ISD::SRA) {
2400 if (ConstantSDNode *C1 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
2401 unsigned Sum = N1C->getValue() + C1->getValue();
2402 if (Sum >= VT.getSizeInBits()) Sum = VT.getSizeInBits()-1;
2403 return DAG.getNode(ISD::SRA, VT, N0.getOperand(0),
2404 DAG.getConstant(Sum, N1C->getValueType(0)));
2408 // fold sra (shl X, m), result_size - n
2409 // -> (sign_extend (trunc (shl X, result_size - n - m))) for
2410 // result_size - n != m.
2411 // If truncate is free for the target sext(shl) is likely to result in better
2413 if (N0.getOpcode() == ISD::SHL) {
2414 // Get the two constanst of the shifts, CN0 = m, CN = n.
2415 const ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
2417 // Determine what the truncate's result bitsize and type would be.
2418 unsigned VTValSize = VT.getSizeInBits();
2420 MVT::getIntegerVT(VTValSize - N1C->getValue());
2421 // Determine the residual right-shift amount.
2422 unsigned ShiftAmt = N1C->getValue() - N01C->getValue();
2424 // If the shift is not a no-op (in which case this should be just a sign
2425 // extend already), the truncated to type is legal, sign_extend is legal
2426 // on that type, and the the truncate to that type is both legal and free,
2427 // perform the transform.
2429 TLI.isOperationLegal(ISD::SIGN_EXTEND, TruncVT) &&
2430 TLI.isOperationLegal(ISD::TRUNCATE, VT) &&
2431 TLI.isTruncateFree(VT, TruncVT)) {
2433 SDOperand Amt = DAG.getConstant(ShiftAmt, TLI.getShiftAmountTy());
2434 SDOperand Shift = DAG.getNode(ISD::SRL, VT, N0.getOperand(0), Amt);
2435 SDOperand Trunc = DAG.getNode(ISD::TRUNCATE, TruncVT, Shift);
2436 return DAG.getNode(ISD::SIGN_EXTEND, N->getValueType(0), Trunc);
2441 // Simplify, based on bits shifted out of the LHS.
2442 if (N1C && SimplifyDemandedBits(SDOperand(N, 0)))
2443 return SDOperand(N, 0);
2446 // If the sign bit is known to be zero, switch this to a SRL.
2447 if (DAG.SignBitIsZero(N0))
2448 return DAG.getNode(ISD::SRL, VT, N0, N1);
2450 return N1C ? visitShiftByConstant(N, N1C->getValue()) : SDOperand();
2453 SDOperand DAGCombiner::visitSRL(SDNode *N) {
2454 SDOperand N0 = N->getOperand(0);
2455 SDOperand N1 = N->getOperand(1);
2456 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
2457 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2458 MVT VT = N0.getValueType();
2459 unsigned OpSizeInBits = VT.getSizeInBits();
2461 // fold (srl c1, c2) -> c1 >>u c2
2463 return DAG.getNode(ISD::SRL, VT, N0, N1);
2464 // fold (srl 0, x) -> 0
2465 if (N0C && N0C->isNullValue())
2467 // fold (srl x, c >= size(x)) -> undef
2468 if (N1C && N1C->getValue() >= OpSizeInBits)
2469 return DAG.getNode(ISD::UNDEF, VT);
2470 // fold (srl x, 0) -> x
2471 if (N1C && N1C->isNullValue())
2473 // if (srl x, c) is known to be zero, return 0
2474 if (N1C && DAG.MaskedValueIsZero(SDOperand(N, 0),
2475 APInt::getAllOnesValue(OpSizeInBits)))
2476 return DAG.getConstant(0, VT);
2478 // fold (srl (srl x, c1), c2) -> 0 or (srl x, c1+c2)
2479 if (N1C && N0.getOpcode() == ISD::SRL &&
2480 N0.getOperand(1).getOpcode() == ISD::Constant) {
2481 uint64_t c1 = cast<ConstantSDNode>(N0.getOperand(1))->getValue();
2482 uint64_t c2 = N1C->getValue();
2483 if (c1 + c2 > OpSizeInBits)
2484 return DAG.getConstant(0, VT);
2485 return DAG.getNode(ISD::SRL, VT, N0.getOperand(0),
2486 DAG.getConstant(c1 + c2, N1.getValueType()));
2489 // fold (srl (anyextend x), c) -> (anyextend (srl x, c))
2490 if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
2491 // Shifting in all undef bits?
2492 MVT SmallVT = N0.getOperand(0).getValueType();
2493 if (N1C->getValue() >= SmallVT.getSizeInBits())
2494 return DAG.getNode(ISD::UNDEF, VT);
2496 SDOperand SmallShift = DAG.getNode(ISD::SRL, SmallVT, N0.getOperand(0), N1);
2497 AddToWorkList(SmallShift.Val);
2498 return DAG.getNode(ISD::ANY_EXTEND, VT, SmallShift);
2501 // fold (srl (sra X, Y), 31) -> (srl X, 31). This srl only looks at the sign
2502 // bit, which is unmodified by sra.
2503 if (N1C && N1C->getValue()+1 == VT.getSizeInBits()) {
2504 if (N0.getOpcode() == ISD::SRA)
2505 return DAG.getNode(ISD::SRL, VT, N0.getOperand(0), N1);
2508 // fold (srl (ctlz x), "5") -> x iff x has one bit set (the low bit).
2509 if (N1C && N0.getOpcode() == ISD::CTLZ &&
2510 N1C->getAPIntValue() == Log2_32(VT.getSizeInBits())) {
2511 APInt KnownZero, KnownOne;
2512 APInt Mask = APInt::getAllOnesValue(VT.getSizeInBits());
2513 DAG.ComputeMaskedBits(N0.getOperand(0), Mask, KnownZero, KnownOne);
2515 // If any of the input bits are KnownOne, then the input couldn't be all
2516 // zeros, thus the result of the srl will always be zero.
2517 if (KnownOne.getBoolValue()) return DAG.getConstant(0, VT);
2519 // If all of the bits input the to ctlz node are known to be zero, then
2520 // the result of the ctlz is "32" and the result of the shift is one.
2521 APInt UnknownBits = ~KnownZero & Mask;
2522 if (UnknownBits == 0) return DAG.getConstant(1, VT);
2524 // Otherwise, check to see if there is exactly one bit input to the ctlz.
2525 if ((UnknownBits & (UnknownBits-1)) == 0) {
2526 // Okay, we know that only that the single bit specified by UnknownBits
2527 // could be set on input to the CTLZ node. If this bit is set, the SRL
2528 // will return 0, if it is clear, it returns 1. Change the CTLZ/SRL pair
2529 // to an SRL,XOR pair, which is likely to simplify more.
2530 unsigned ShAmt = UnknownBits.countTrailingZeros();
2531 SDOperand Op = N0.getOperand(0);
2533 Op = DAG.getNode(ISD::SRL, VT, Op,
2534 DAG.getConstant(ShAmt, TLI.getShiftAmountTy()));
2535 AddToWorkList(Op.Val);
2537 return DAG.getNode(ISD::XOR, VT, Op, DAG.getConstant(1, VT));
2541 // fold operands of srl based on knowledge that the low bits are not
2543 if (N1C && SimplifyDemandedBits(SDOperand(N, 0)))
2544 return SDOperand(N, 0);
2546 return N1C ? visitShiftByConstant(N, N1C->getValue()) : SDOperand();
2549 SDOperand DAGCombiner::visitCTLZ(SDNode *N) {
2550 SDOperand N0 = N->getOperand(0);
2551 MVT VT = N->getValueType(0);
2553 // fold (ctlz c1) -> c2
2554 if (isa<ConstantSDNode>(N0))
2555 return DAG.getNode(ISD::CTLZ, VT, N0);
2559 SDOperand DAGCombiner::visitCTTZ(SDNode *N) {
2560 SDOperand N0 = N->getOperand(0);
2561 MVT VT = N->getValueType(0);
2563 // fold (cttz c1) -> c2
2564 if (isa<ConstantSDNode>(N0))
2565 return DAG.getNode(ISD::CTTZ, VT, N0);
2569 SDOperand DAGCombiner::visitCTPOP(SDNode *N) {
2570 SDOperand N0 = N->getOperand(0);
2571 MVT VT = N->getValueType(0);
2573 // fold (ctpop c1) -> c2
2574 if (isa<ConstantSDNode>(N0))
2575 return DAG.getNode(ISD::CTPOP, VT, N0);
2579 SDOperand DAGCombiner::visitSELECT(SDNode *N) {
2580 SDOperand N0 = N->getOperand(0);
2581 SDOperand N1 = N->getOperand(1);
2582 SDOperand N2 = N->getOperand(2);
2583 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
2584 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2585 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2);
2586 MVT VT = N->getValueType(0);
2587 MVT VT0 = N0.getValueType();
2589 // fold select C, X, X -> X
2592 // fold select true, X, Y -> X
2593 if (N0C && !N0C->isNullValue())
2595 // fold select false, X, Y -> Y
2596 if (N0C && N0C->isNullValue())
2598 // fold select C, 1, X -> C | X
2599 if (VT == MVT::i1 && N1C && N1C->getAPIntValue() == 1)
2600 return DAG.getNode(ISD::OR, VT, N0, N2);
2601 // fold select C, 0, 1 -> ~C
2602 if (VT.isInteger() && VT0.isInteger() &&
2603 N1C && N2C && N1C->isNullValue() && N2C->getAPIntValue() == 1) {
2604 SDOperand XORNode = DAG.getNode(ISD::XOR, VT0, N0, DAG.getConstant(1, VT0));
2607 AddToWorkList(XORNode.Val);
2609 return DAG.getNode(ISD::ZERO_EXTEND, VT, XORNode);
2610 return DAG.getNode(ISD::TRUNCATE, VT, XORNode);
2612 // fold select C, 0, X -> ~C & X
2613 if (VT == VT0 && VT == MVT::i1 && N1C && N1C->isNullValue()) {
2614 SDOperand XORNode = DAG.getNode(ISD::XOR, VT, N0, DAG.getConstant(1, VT));
2615 AddToWorkList(XORNode.Val);
2616 return DAG.getNode(ISD::AND, VT, XORNode, N2);
2618 // fold select C, X, 1 -> ~C | X
2619 if (VT == VT0 && VT == MVT::i1 && N2C && N2C->getAPIntValue() == 1) {
2620 SDOperand XORNode = DAG.getNode(ISD::XOR, VT, N0, DAG.getConstant(1, VT));
2621 AddToWorkList(XORNode.Val);
2622 return DAG.getNode(ISD::OR, VT, XORNode, N1);
2624 // fold select C, X, 0 -> C & X
2625 // FIXME: this should check for C type == X type, not i1?
2626 if (VT == MVT::i1 && N2C && N2C->isNullValue())
2627 return DAG.getNode(ISD::AND, VT, N0, N1);
2628 // fold X ? X : Y --> X ? 1 : Y --> X | Y
2629 if (VT == MVT::i1 && N0 == N1)
2630 return DAG.getNode(ISD::OR, VT, N0, N2);
2631 // fold X ? Y : X --> X ? Y : 0 --> X & Y
2632 if (VT == MVT::i1 && N0 == N2)
2633 return DAG.getNode(ISD::AND, VT, N0, N1);
2635 // If we can fold this based on the true/false value, do so.
2636 if (SimplifySelectOps(N, N1, N2))
2637 return SDOperand(N, 0); // Don't revisit N.
2639 // fold selects based on a setcc into other things, such as min/max/abs
2640 if (N0.getOpcode() == ISD::SETCC) {
2642 // Check against MVT::Other for SELECT_CC, which is a workaround for targets
2643 // having to say they don't support SELECT_CC on every type the DAG knows
2644 // about, since there is no way to mark an opcode illegal at all value types
2645 if (TLI.isOperationLegal(ISD::SELECT_CC, MVT::Other))
2646 return DAG.getNode(ISD::SELECT_CC, VT, N0.getOperand(0), N0.getOperand(1),
2647 N1, N2, N0.getOperand(2));
2649 return SimplifySelect(N0, N1, N2);
2654 SDOperand DAGCombiner::visitSELECT_CC(SDNode *N) {
2655 SDOperand N0 = N->getOperand(0);
2656 SDOperand N1 = N->getOperand(1);
2657 SDOperand N2 = N->getOperand(2);
2658 SDOperand N3 = N->getOperand(3);
2659 SDOperand N4 = N->getOperand(4);
2660 ISD::CondCode CC = cast<CondCodeSDNode>(N4)->get();
2662 // fold select_cc lhs, rhs, x, x, cc -> x
2666 // Determine if the condition we're dealing with is constant
2667 SDOperand SCC = SimplifySetCC(TLI.getSetCCResultType(N0), N0, N1, CC, false);
2668 if (SCC.Val) AddToWorkList(SCC.Val);
2670 if (ConstantSDNode *SCCC = dyn_cast_or_null<ConstantSDNode>(SCC.Val)) {
2671 if (!SCCC->isNullValue())
2672 return N2; // cond always true -> true val
2674 return N3; // cond always false -> false val
2677 // Fold to a simpler select_cc
2678 if (SCC.Val && SCC.getOpcode() == ISD::SETCC)
2679 return DAG.getNode(ISD::SELECT_CC, N2.getValueType(),
2680 SCC.getOperand(0), SCC.getOperand(1), N2, N3,
2683 // If we can fold this based on the true/false value, do so.
2684 if (SimplifySelectOps(N, N2, N3))
2685 return SDOperand(N, 0); // Don't revisit N.
2687 // fold select_cc into other things, such as min/max/abs
2688 return SimplifySelectCC(N0, N1, N2, N3, CC);
2691 SDOperand DAGCombiner::visitSETCC(SDNode *N) {
2692 return SimplifySetCC(N->getValueType(0), N->getOperand(0), N->getOperand(1),
2693 cast<CondCodeSDNode>(N->getOperand(2))->get());
2696 // ExtendUsesToFormExtLoad - Trying to extend uses of a load to enable this:
2697 // "fold ({s|z}ext (load x)) -> ({s|z}ext (truncate ({s|z}extload x)))"
2698 // transformation. Returns true if extension are possible and the above
2699 // mentioned transformation is profitable.
2700 static bool ExtendUsesToFormExtLoad(SDNode *N, SDOperand N0,
2702 SmallVector<SDNode*, 4> &ExtendNodes,
2703 TargetLowering &TLI) {
2704 bool HasCopyToRegUses = false;
2705 bool isTruncFree = TLI.isTruncateFree(N->getValueType(0), N0.getValueType());
2706 for (SDNode::use_iterator UI = N0.Val->use_begin(), UE = N0.Val->use_end();
2708 SDNode *User = UI->getUser();
2711 // FIXME: Only extend SETCC N, N and SETCC N, c for now.
2712 if (User->getOpcode() == ISD::SETCC) {
2713 ISD::CondCode CC = cast<CondCodeSDNode>(User->getOperand(2))->get();
2714 if (ExtOpc == ISD::ZERO_EXTEND && ISD::isSignedIntSetCC(CC))
2715 // Sign bits will be lost after a zext.
2718 for (unsigned i = 0; i != 2; ++i) {
2719 SDOperand UseOp = User->getOperand(i);
2722 if (!isa<ConstantSDNode>(UseOp))
2727 ExtendNodes.push_back(User);
2729 for (unsigned i = 0, e = User->getNumOperands(); i != e; ++i) {
2730 SDOperand UseOp = User->getOperand(i);
2732 // If truncate from extended type to original load type is free
2733 // on this target, then it's ok to extend a CopyToReg.
2734 if (isTruncFree && User->getOpcode() == ISD::CopyToReg)
2735 HasCopyToRegUses = true;
2743 if (HasCopyToRegUses) {
2744 bool BothLiveOut = false;
2745 for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
2747 SDNode *User = UI->getUser();
2748 for (unsigned i = 0, e = User->getNumOperands(); i != e; ++i) {
2749 SDOperand UseOp = User->getOperand(i);
2750 if (UseOp.Val == N && UseOp.ResNo == 0) {
2757 // Both unextended and extended values are live out. There had better be
2758 // good a reason for the transformation.
2759 return ExtendNodes.size();
2764 SDOperand DAGCombiner::visitSIGN_EXTEND(SDNode *N) {
2765 SDOperand N0 = N->getOperand(0);
2766 MVT VT = N->getValueType(0);
2768 // fold (sext c1) -> c1
2769 if (isa<ConstantSDNode>(N0))
2770 return DAG.getNode(ISD::SIGN_EXTEND, VT, N0);
2772 // fold (sext (sext x)) -> (sext x)
2773 // fold (sext (aext x)) -> (sext x)
2774 if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
2775 return DAG.getNode(ISD::SIGN_EXTEND, VT, N0.getOperand(0));
2777 if (N0.getOpcode() == ISD::TRUNCATE) {
2778 // fold (sext (truncate (load x))) -> (sext (smaller load x))
2779 // fold (sext (truncate (srl (load x), c))) -> (sext (smaller load (x+c/n)))
2780 SDOperand NarrowLoad = ReduceLoadWidth(N0.Val);
2781 if (NarrowLoad.Val) {
2782 if (NarrowLoad.Val != N0.Val)
2783 CombineTo(N0.Val, NarrowLoad);
2784 return DAG.getNode(ISD::SIGN_EXTEND, VT, NarrowLoad);
2787 // See if the value being truncated is already sign extended. If so, just
2788 // eliminate the trunc/sext pair.
2789 SDOperand Op = N0.getOperand(0);
2790 unsigned OpBits = Op.getValueType().getSizeInBits();
2791 unsigned MidBits = N0.getValueType().getSizeInBits();
2792 unsigned DestBits = VT.getSizeInBits();
2793 unsigned NumSignBits = DAG.ComputeNumSignBits(Op);
2795 if (OpBits == DestBits) {
2796 // Op is i32, Mid is i8, and Dest is i32. If Op has more than 24 sign
2797 // bits, it is already ready.
2798 if (NumSignBits > DestBits-MidBits)
2800 } else if (OpBits < DestBits) {
2801 // Op is i32, Mid is i8, and Dest is i64. If Op has more than 24 sign
2802 // bits, just sext from i32.
2803 if (NumSignBits > OpBits-MidBits)
2804 return DAG.getNode(ISD::SIGN_EXTEND, VT, Op);
2806 // Op is i64, Mid is i8, and Dest is i32. If Op has more than 56 sign
2807 // bits, just truncate to i32.
2808 if (NumSignBits > OpBits-MidBits)
2809 return DAG.getNode(ISD::TRUNCATE, VT, Op);
2812 // fold (sext (truncate x)) -> (sextinreg x).
2813 if (!AfterLegalize || TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG,
2814 N0.getValueType())) {
2815 if (Op.getValueType().bitsLT(VT))
2816 Op = DAG.getNode(ISD::ANY_EXTEND, VT, Op);
2817 else if (Op.getValueType().bitsGT(VT))
2818 Op = DAG.getNode(ISD::TRUNCATE, VT, Op);
2819 return DAG.getNode(ISD::SIGN_EXTEND_INREG, VT, Op,
2820 DAG.getValueType(N0.getValueType()));
2824 // fold (sext (load x)) -> (sext (truncate (sextload x)))
2825 if (ISD::isNON_EXTLoad(N0.Val) &&
2826 ((!AfterLegalize && !cast<LoadSDNode>(N0)->isVolatile()) ||
2827 TLI.isLoadXLegal(ISD::SEXTLOAD, N0.getValueType()))) {
2828 bool DoXform = true;
2829 SmallVector<SDNode*, 4> SetCCs;
2830 if (!N0.hasOneUse())
2831 DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::SIGN_EXTEND, SetCCs, TLI);
2833 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
2834 SDOperand ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, VT, LN0->getChain(),
2835 LN0->getBasePtr(), LN0->getSrcValue(),
2836 LN0->getSrcValueOffset(),
2839 LN0->getAlignment());
2840 CombineTo(N, ExtLoad);
2841 SDOperand Trunc = DAG.getNode(ISD::TRUNCATE, N0.getValueType(), ExtLoad);
2842 CombineTo(N0.Val, Trunc, ExtLoad.getValue(1));
2843 // Extend SetCC uses if necessary.
2844 for (unsigned i = 0, e = SetCCs.size(); i != e; ++i) {
2845 SDNode *SetCC = SetCCs[i];
2846 SmallVector<SDOperand, 4> Ops;
2847 for (unsigned j = 0; j != 2; ++j) {
2848 SDOperand SOp = SetCC->getOperand(j);
2850 Ops.push_back(ExtLoad);
2852 Ops.push_back(DAG.getNode(ISD::SIGN_EXTEND, VT, SOp));
2854 Ops.push_back(SetCC->getOperand(2));
2855 CombineTo(SetCC, DAG.getNode(ISD::SETCC, SetCC->getValueType(0),
2856 &Ops[0], Ops.size()));
2858 return SDOperand(N, 0); // Return N so it doesn't get rechecked!
2862 // fold (sext (sextload x)) -> (sext (truncate (sextload x)))
2863 // fold (sext ( extload x)) -> (sext (truncate (sextload x)))
2864 if ((ISD::isSEXTLoad(N0.Val) || ISD::isEXTLoad(N0.Val)) &&
2865 ISD::isUNINDEXEDLoad(N0.Val) && N0.hasOneUse()) {
2866 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
2867 MVT EVT = LN0->getMemoryVT();
2868 if ((!AfterLegalize && !LN0->isVolatile()) ||
2869 TLI.isLoadXLegal(ISD::SEXTLOAD, EVT)) {
2870 SDOperand ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, VT, LN0->getChain(),
2871 LN0->getBasePtr(), LN0->getSrcValue(),
2872 LN0->getSrcValueOffset(), EVT,
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!
2882 // sext(setcc x,y,cc) -> select_cc x, y, -1, 0, cc
2883 if (N0.getOpcode() == ISD::SETCC) {
2885 SimplifySelectCC(N0.getOperand(0), N0.getOperand(1),
2886 DAG.getConstant(~0ULL, VT), DAG.getConstant(0, VT),
2887 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
2888 if (SCC.Val) return SCC;
2891 // fold (sext x) -> (zext x) if the sign bit is known zero.
2892 if ((!AfterLegalize || TLI.isOperationLegal(ISD::ZERO_EXTEND, VT)) &&
2893 DAG.SignBitIsZero(N0))
2894 return DAG.getNode(ISD::ZERO_EXTEND, VT, N0);
2899 SDOperand DAGCombiner::visitZERO_EXTEND(SDNode *N) {
2900 SDOperand N0 = N->getOperand(0);
2901 MVT VT = N->getValueType(0);
2903 // fold (zext c1) -> c1
2904 if (isa<ConstantSDNode>(N0))
2905 return DAG.getNode(ISD::ZERO_EXTEND, VT, N0);
2906 // fold (zext (zext x)) -> (zext x)
2907 // fold (zext (aext x)) -> (zext x)
2908 if (N0.getOpcode() == ISD::ZERO_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
2909 return DAG.getNode(ISD::ZERO_EXTEND, VT, N0.getOperand(0));
2911 // fold (zext (truncate (load x))) -> (zext (smaller load x))
2912 // fold (zext (truncate (srl (load x), c))) -> (zext (small load (x+c/n)))
2913 if (N0.getOpcode() == ISD::TRUNCATE) {
2914 SDOperand NarrowLoad = ReduceLoadWidth(N0.Val);
2915 if (NarrowLoad.Val) {
2916 if (NarrowLoad.Val != N0.Val)
2917 CombineTo(N0.Val, NarrowLoad);
2918 return DAG.getNode(ISD::ZERO_EXTEND, VT, NarrowLoad);
2922 // fold (zext (truncate x)) -> (and x, mask)
2923 if (N0.getOpcode() == ISD::TRUNCATE &&
2924 (!AfterLegalize || TLI.isOperationLegal(ISD::AND, VT))) {
2925 SDOperand Op = N0.getOperand(0);
2926 if (Op.getValueType().bitsLT(VT)) {
2927 Op = DAG.getNode(ISD::ANY_EXTEND, VT, Op);
2928 } else if (Op.getValueType().bitsGT(VT)) {
2929 Op = DAG.getNode(ISD::TRUNCATE, VT, Op);
2931 return DAG.getZeroExtendInReg(Op, N0.getValueType());
2934 // fold (zext (and (trunc x), cst)) -> (and x, cst).
2935 if (N0.getOpcode() == ISD::AND &&
2936 N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
2937 N0.getOperand(1).getOpcode() == ISD::Constant) {
2938 SDOperand X = N0.getOperand(0).getOperand(0);
2939 if (X.getValueType().bitsLT(VT)) {
2940 X = DAG.getNode(ISD::ANY_EXTEND, VT, X);
2941 } else if (X.getValueType().bitsGT(VT)) {
2942 X = DAG.getNode(ISD::TRUNCATE, VT, X);
2944 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
2945 Mask.zext(VT.getSizeInBits());
2946 return DAG.getNode(ISD::AND, VT, X, DAG.getConstant(Mask, VT));
2949 // fold (zext (load x)) -> (zext (truncate (zextload x)))
2950 if (ISD::isNON_EXTLoad(N0.Val) &&
2951 ((!AfterLegalize && !cast<LoadSDNode>(N0)->isVolatile()) ||
2952 TLI.isLoadXLegal(ISD::ZEXTLOAD, N0.getValueType()))) {
2953 bool DoXform = true;
2954 SmallVector<SDNode*, 4> SetCCs;
2955 if (!N0.hasOneUse())
2956 DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ZERO_EXTEND, SetCCs, TLI);
2958 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
2959 SDOperand ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, VT, LN0->getChain(),
2960 LN0->getBasePtr(), LN0->getSrcValue(),
2961 LN0->getSrcValueOffset(),
2964 LN0->getAlignment());
2965 CombineTo(N, ExtLoad);
2966 SDOperand Trunc = DAG.getNode(ISD::TRUNCATE, N0.getValueType(), ExtLoad);
2967 CombineTo(N0.Val, Trunc, ExtLoad.getValue(1));
2968 // Extend SetCC uses if necessary.
2969 for (unsigned i = 0, e = SetCCs.size(); i != e; ++i) {
2970 SDNode *SetCC = SetCCs[i];
2971 SmallVector<SDOperand, 4> Ops;
2972 for (unsigned j = 0; j != 2; ++j) {
2973 SDOperand SOp = SetCC->getOperand(j);
2975 Ops.push_back(ExtLoad);
2977 Ops.push_back(DAG.getNode(ISD::ZERO_EXTEND, VT, SOp));
2979 Ops.push_back(SetCC->getOperand(2));
2980 CombineTo(SetCC, DAG.getNode(ISD::SETCC, SetCC->getValueType(0),
2981 &Ops[0], Ops.size()));
2983 return SDOperand(N, 0); // Return N so it doesn't get rechecked!
2987 // fold (zext (zextload x)) -> (zext (truncate (zextload x)))
2988 // fold (zext ( extload x)) -> (zext (truncate (zextload x)))
2989 if ((ISD::isZEXTLoad(N0.Val) || ISD::isEXTLoad(N0.Val)) &&
2990 ISD::isUNINDEXEDLoad(N0.Val) && N0.hasOneUse()) {
2991 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
2992 MVT EVT = LN0->getMemoryVT();
2993 if ((!AfterLegalize && !LN0->isVolatile()) ||
2994 TLI.isLoadXLegal(ISD::ZEXTLOAD, EVT)) {
2995 SDOperand ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, VT, LN0->getChain(),
2996 LN0->getBasePtr(), LN0->getSrcValue(),
2997 LN0->getSrcValueOffset(), EVT,
2999 LN0->getAlignment());
3000 CombineTo(N, ExtLoad);
3001 CombineTo(N0.Val, DAG.getNode(ISD::TRUNCATE, N0.getValueType(), ExtLoad),
3002 ExtLoad.getValue(1));
3003 return SDOperand(N, 0); // Return N so it doesn't get rechecked!
3007 // zext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
3008 if (N0.getOpcode() == ISD::SETCC) {
3010 SimplifySelectCC(N0.getOperand(0), N0.getOperand(1),
3011 DAG.getConstant(1, VT), DAG.getConstant(0, VT),
3012 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
3013 if (SCC.Val) return SCC;
3019 SDOperand DAGCombiner::visitANY_EXTEND(SDNode *N) {
3020 SDOperand N0 = N->getOperand(0);
3021 MVT VT = N->getValueType(0);
3023 // fold (aext c1) -> c1
3024 if (isa<ConstantSDNode>(N0))
3025 return DAG.getNode(ISD::ANY_EXTEND, VT, N0);
3026 // fold (aext (aext x)) -> (aext x)
3027 // fold (aext (zext x)) -> (zext x)
3028 // fold (aext (sext x)) -> (sext x)
3029 if (N0.getOpcode() == ISD::ANY_EXTEND ||
3030 N0.getOpcode() == ISD::ZERO_EXTEND ||
3031 N0.getOpcode() == ISD::SIGN_EXTEND)
3032 return DAG.getNode(N0.getOpcode(), VT, N0.getOperand(0));
3034 // fold (aext (truncate (load x))) -> (aext (smaller load x))
3035 // fold (aext (truncate (srl (load x), c))) -> (aext (small load (x+c/n)))
3036 if (N0.getOpcode() == ISD::TRUNCATE) {
3037 SDOperand NarrowLoad = ReduceLoadWidth(N0.Val);
3038 if (NarrowLoad.Val) {
3039 if (NarrowLoad.Val != N0.Val)
3040 CombineTo(N0.Val, NarrowLoad);
3041 return DAG.getNode(ISD::ANY_EXTEND, VT, NarrowLoad);
3045 // fold (aext (truncate x))
3046 if (N0.getOpcode() == ISD::TRUNCATE) {
3047 SDOperand TruncOp = N0.getOperand(0);
3048 if (TruncOp.getValueType() == VT)
3049 return TruncOp; // x iff x size == zext size.
3050 if (TruncOp.getValueType().bitsGT(VT))
3051 return DAG.getNode(ISD::TRUNCATE, VT, TruncOp);
3052 return DAG.getNode(ISD::ANY_EXTEND, VT, TruncOp);
3055 // fold (aext (and (trunc x), cst)) -> (and x, cst).
3056 if (N0.getOpcode() == ISD::AND &&
3057 N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
3058 N0.getOperand(1).getOpcode() == ISD::Constant) {
3059 SDOperand X = N0.getOperand(0).getOperand(0);
3060 if (X.getValueType().bitsLT(VT)) {
3061 X = DAG.getNode(ISD::ANY_EXTEND, VT, X);
3062 } else if (X.getValueType().bitsGT(VT)) {
3063 X = DAG.getNode(ISD::TRUNCATE, VT, X);
3065 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
3066 Mask.zext(VT.getSizeInBits());
3067 return DAG.getNode(ISD::AND, VT, X, DAG.getConstant(Mask, VT));
3070 // fold (aext (load x)) -> (aext (truncate (extload x)))
3071 if (ISD::isNON_EXTLoad(N0.Val) && N0.hasOneUse() &&
3072 ((!AfterLegalize && !cast<LoadSDNode>(N0)->isVolatile()) ||
3073 TLI.isLoadXLegal(ISD::EXTLOAD, N0.getValueType()))) {
3074 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
3075 SDOperand ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, VT, LN0->getChain(),
3076 LN0->getBasePtr(), LN0->getSrcValue(),
3077 LN0->getSrcValueOffset(),
3080 LN0->getAlignment());
3081 CombineTo(N, ExtLoad);
3082 CombineTo(N0.Val, DAG.getNode(ISD::TRUNCATE, N0.getValueType(), ExtLoad),
3083 ExtLoad.getValue(1));
3084 return SDOperand(N, 0); // Return N so it doesn't get rechecked!
3087 // fold (aext (zextload x)) -> (aext (truncate (zextload x)))
3088 // fold (aext (sextload x)) -> (aext (truncate (sextload x)))
3089 // fold (aext ( extload x)) -> (aext (truncate (extload x)))
3090 if (N0.getOpcode() == ISD::LOAD &&
3091 !ISD::isNON_EXTLoad(N0.Val) && ISD::isUNINDEXEDLoad(N0.Val) &&
3093 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
3094 MVT EVT = LN0->getMemoryVT();
3095 SDOperand ExtLoad = DAG.getExtLoad(LN0->getExtensionType(), VT,
3096 LN0->getChain(), LN0->getBasePtr(),
3098 LN0->getSrcValueOffset(), EVT,
3100 LN0->getAlignment());
3101 CombineTo(N, ExtLoad);
3102 CombineTo(N0.Val, DAG.getNode(ISD::TRUNCATE, N0.getValueType(), ExtLoad),
3103 ExtLoad.getValue(1));
3104 return SDOperand(N, 0); // Return N so it doesn't get rechecked!
3107 // aext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
3108 if (N0.getOpcode() == ISD::SETCC) {
3110 SimplifySelectCC(N0.getOperand(0), N0.getOperand(1),
3111 DAG.getConstant(1, VT), DAG.getConstant(0, VT),
3112 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
3120 /// GetDemandedBits - See if the specified operand can be simplified with the
3121 /// knowledge that only the bits specified by Mask are used. If so, return the
3122 /// simpler operand, otherwise return a null SDOperand.
3123 SDOperand DAGCombiner::GetDemandedBits(SDOperand V, const APInt &Mask) {
3124 switch (V.getOpcode()) {
3128 // If the LHS or RHS don't contribute bits to the or, drop them.
3129 if (DAG.MaskedValueIsZero(V.getOperand(0), Mask))
3130 return V.getOperand(1);
3131 if (DAG.MaskedValueIsZero(V.getOperand(1), Mask))
3132 return V.getOperand(0);
3135 // Only look at single-use SRLs.
3136 if (!V.Val->hasOneUse())
3138 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(V.getOperand(1))) {
3139 // See if we can recursively simplify the LHS.
3140 unsigned Amt = RHSC->getValue();
3141 APInt NewMask = Mask << Amt;
3142 SDOperand SimplifyLHS = GetDemandedBits(V.getOperand(0), NewMask);
3143 if (SimplifyLHS.Val) {
3144 return DAG.getNode(ISD::SRL, V.getValueType(),
3145 SimplifyLHS, V.getOperand(1));
3152 /// ReduceLoadWidth - If the result of a wider load is shifted to right of N
3153 /// bits and then truncated to a narrower type and where N is a multiple
3154 /// of number of bits of the narrower type, transform it to a narrower load
3155 /// from address + N / num of bits of new type. If the result is to be
3156 /// extended, also fold the extension to form a extending load.
3157 SDOperand DAGCombiner::ReduceLoadWidth(SDNode *N) {
3158 unsigned Opc = N->getOpcode();
3159 ISD::LoadExtType ExtType = ISD::NON_EXTLOAD;
3160 SDOperand N0 = N->getOperand(0);
3161 MVT VT = N->getValueType(0);
3162 MVT EVT = N->getValueType(0);
3164 // Special case: SIGN_EXTEND_INREG is basically truncating to EVT then
3166 if (Opc == ISD::SIGN_EXTEND_INREG) {
3167 ExtType = ISD::SEXTLOAD;
3168 EVT = cast<VTSDNode>(N->getOperand(1))->getVT();
3169 if (AfterLegalize && !TLI.isLoadXLegal(ISD::SEXTLOAD, EVT))
3173 unsigned EVTBits = EVT.getSizeInBits();
3175 bool CombineSRL = false;
3176 if (N0.getOpcode() == ISD::SRL && N0.hasOneUse()) {
3177 if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
3178 ShAmt = N01->getValue();
3179 // Is the shift amount a multiple of size of VT?
3180 if ((ShAmt & (EVTBits-1)) == 0) {
3181 N0 = N0.getOperand(0);
3182 if (N0.getValueType().getSizeInBits() <= EVTBits)
3189 // Do not generate loads of non-round integer types since these can
3190 // be expensive (and would be wrong if the type is not byte sized).
3191 if (ISD::isNON_EXTLoad(N0.Val) && N0.hasOneUse() && VT.isRound() &&
3192 // Do not change the width of a volatile load.
3193 !cast<LoadSDNode>(N0)->isVolatile()) {
3194 assert(N0.getValueType().getSizeInBits() > EVTBits &&
3195 "Cannot truncate to larger type!");
3196 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
3197 MVT PtrType = N0.getOperand(1).getValueType();
3198 // For big endian targets, we need to adjust the offset to the pointer to
3199 // load the correct bytes.
3200 if (TLI.isBigEndian()) {
3201 unsigned LVTStoreBits = N0.getValueType().getStoreSizeInBits();
3202 unsigned EVTStoreBits = EVT.getStoreSizeInBits();
3203 ShAmt = LVTStoreBits - EVTStoreBits - ShAmt;
3205 uint64_t PtrOff = ShAmt / 8;
3206 unsigned NewAlign = MinAlign(LN0->getAlignment(), PtrOff);
3207 SDOperand NewPtr = DAG.getNode(ISD::ADD, PtrType, LN0->getBasePtr(),
3208 DAG.getConstant(PtrOff, PtrType));
3209 AddToWorkList(NewPtr.Val);
3210 SDOperand Load = (ExtType == ISD::NON_EXTLOAD)
3211 ? DAG.getLoad(VT, LN0->getChain(), NewPtr,
3212 LN0->getSrcValue(), LN0->getSrcValueOffset(),
3213 LN0->isVolatile(), NewAlign)
3214 : DAG.getExtLoad(ExtType, VT, LN0->getChain(), NewPtr,
3215 LN0->getSrcValue(), LN0->getSrcValueOffset(), EVT,
3216 LN0->isVolatile(), NewAlign);
3219 WorkListRemover DeadNodes(*this);
3220 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1),
3222 CombineTo(N->getOperand(0).Val, Load);
3224 CombineTo(N0.Val, Load, Load.getValue(1));
3226 if (Opc == ISD::SIGN_EXTEND_INREG)
3227 return DAG.getNode(Opc, VT, Load, N->getOperand(1));
3229 return DAG.getNode(Opc, VT, Load);
3231 return SDOperand(N, 0); // Return N so it doesn't get rechecked!
3238 SDOperand DAGCombiner::visitSIGN_EXTEND_INREG(SDNode *N) {
3239 SDOperand N0 = N->getOperand(0);
3240 SDOperand N1 = N->getOperand(1);
3241 MVT VT = N->getValueType(0);
3242 MVT EVT = cast<VTSDNode>(N1)->getVT();
3243 unsigned VTBits = VT.getSizeInBits();
3244 unsigned EVTBits = EVT.getSizeInBits();
3246 // fold (sext_in_reg c1) -> c1
3247 if (isa<ConstantSDNode>(N0) || N0.getOpcode() == ISD::UNDEF)
3248 return DAG.getNode(ISD::SIGN_EXTEND_INREG, VT, N0, N1);
3250 // If the input is already sign extended, just drop the extension.
3251 if (DAG.ComputeNumSignBits(N0) >= VT.getSizeInBits()-EVTBits+1)
3254 // fold (sext_in_reg (sext_in_reg x, VT2), VT1) -> (sext_in_reg x, minVT) pt2
3255 if (N0.getOpcode() == ISD::SIGN_EXTEND_INREG &&
3256 EVT.bitsLT(cast<VTSDNode>(N0.getOperand(1))->getVT())) {
3257 return DAG.getNode(ISD::SIGN_EXTEND_INREG, VT, N0.getOperand(0), N1);
3260 // fold (sext_in_reg x) -> (zext_in_reg x) if the sign bit is known zero.
3261 if (DAG.MaskedValueIsZero(N0, APInt::getBitsSet(VTBits, EVTBits-1, EVTBits)))
3262 return DAG.getZeroExtendInReg(N0, EVT);
3264 // fold operands of sext_in_reg based on knowledge that the top bits are not
3266 if (SimplifyDemandedBits(SDOperand(N, 0)))
3267 return SDOperand(N, 0);
3269 // fold (sext_in_reg (load x)) -> (smaller sextload x)
3270 // fold (sext_in_reg (srl (load x), c)) -> (smaller sextload (x+c/evtbits))
3271 SDOperand NarrowLoad = ReduceLoadWidth(N);
3275 // fold (sext_in_reg (srl X, 24), i8) -> sra X, 24
3276 // fold (sext_in_reg (srl X, 23), i8) -> sra X, 23 iff possible.
3277 // We already fold "(sext_in_reg (srl X, 25), i8) -> srl X, 25" above.
3278 if (N0.getOpcode() == ISD::SRL) {
3279 if (ConstantSDNode *ShAmt = dyn_cast<ConstantSDNode>(N0.getOperand(1)))
3280 if (ShAmt->getValue()+EVTBits <= VT.getSizeInBits()) {
3281 // We can turn this into an SRA iff the input to the SRL is already sign
3283 unsigned InSignBits = DAG.ComputeNumSignBits(N0.getOperand(0));
3284 if (VT.getSizeInBits()-(ShAmt->getValue()+EVTBits) < InSignBits)
3285 return DAG.getNode(ISD::SRA, VT, N0.getOperand(0), N0.getOperand(1));
3289 // fold (sext_inreg (extload x)) -> (sextload x)
3290 if (ISD::isEXTLoad(N0.Val) &&
3291 ISD::isUNINDEXEDLoad(N0.Val) &&
3292 EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
3293 ((!AfterLegalize && !cast<LoadSDNode>(N0)->isVolatile()) ||
3294 TLI.isLoadXLegal(ISD::SEXTLOAD, EVT))) {
3295 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
3296 SDOperand ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, VT, LN0->getChain(),
3297 LN0->getBasePtr(), LN0->getSrcValue(),
3298 LN0->getSrcValueOffset(), EVT,
3300 LN0->getAlignment());
3301 CombineTo(N, ExtLoad);
3302 CombineTo(N0.Val, ExtLoad, ExtLoad.getValue(1));
3303 return SDOperand(N, 0); // Return N so it doesn't get rechecked!
3305 // fold (sext_inreg (zextload x)) -> (sextload x) iff load has one use
3306 if (ISD::isZEXTLoad(N0.Val) && ISD::isUNINDEXEDLoad(N0.Val) &&
3308 EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
3309 ((!AfterLegalize && !cast<LoadSDNode>(N0)->isVolatile()) ||
3310 TLI.isLoadXLegal(ISD::SEXTLOAD, EVT))) {
3311 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
3312 SDOperand ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, VT, LN0->getChain(),
3313 LN0->getBasePtr(), LN0->getSrcValue(),
3314 LN0->getSrcValueOffset(), EVT,
3316 LN0->getAlignment());
3317 CombineTo(N, ExtLoad);
3318 CombineTo(N0.Val, ExtLoad, ExtLoad.getValue(1));
3319 return SDOperand(N, 0); // Return N so it doesn't get rechecked!
3324 SDOperand DAGCombiner::visitTRUNCATE(SDNode *N) {
3325 SDOperand N0 = N->getOperand(0);
3326 MVT VT = N->getValueType(0);
3329 if (N0.getValueType() == N->getValueType(0))
3331 // fold (truncate c1) -> c1
3332 if (isa<ConstantSDNode>(N0))
3333 return DAG.getNode(ISD::TRUNCATE, VT, N0);
3334 // fold (truncate (truncate x)) -> (truncate x)
3335 if (N0.getOpcode() == ISD::TRUNCATE)
3336 return DAG.getNode(ISD::TRUNCATE, VT, N0.getOperand(0));
3337 // fold (truncate (ext x)) -> (ext x) or (truncate x) or x
3338 if (N0.getOpcode() == ISD::ZERO_EXTEND || N0.getOpcode() == ISD::SIGN_EXTEND||
3339 N0.getOpcode() == ISD::ANY_EXTEND) {
3340 if (N0.getOperand(0).getValueType().bitsLT(VT))
3341 // if the source is smaller than the dest, we still need an extend
3342 return DAG.getNode(N0.getOpcode(), VT, N0.getOperand(0));
3343 else if (N0.getOperand(0).getValueType().bitsGT(VT))
3344 // if the source is larger than the dest, than we just need the truncate
3345 return DAG.getNode(ISD::TRUNCATE, VT, N0.getOperand(0));
3347 // if the source and dest are the same type, we can drop both the extend
3349 return N0.getOperand(0);
3352 // See if we can simplify the input to this truncate through knowledge that
3353 // only the low bits are being used. For example "trunc (or (shl x, 8), y)"
3356 GetDemandedBits(N0, APInt::getLowBitsSet(N0.getValueSizeInBits(),
3357 VT.getSizeInBits()));
3359 return DAG.getNode(ISD::TRUNCATE, VT, Shorter);
3361 // fold (truncate (load x)) -> (smaller load x)
3362 // fold (truncate (srl (load x), c)) -> (smaller load (x+c/evtbits))
3363 return ReduceLoadWidth(N);
3366 static SDNode *getBuildPairElt(SDNode *N, unsigned i) {
3367 SDOperand Elt = N->getOperand(i);
3368 if (Elt.getOpcode() != ISD::MERGE_VALUES)
3370 return Elt.getOperand(Elt.ResNo).Val;
3373 /// CombineConsecutiveLoads - build_pair (load, load) -> load
3374 /// if load locations are consecutive.
3375 SDOperand DAGCombiner::CombineConsecutiveLoads(SDNode *N, MVT VT) {
3376 assert(N->getOpcode() == ISD::BUILD_PAIR);
3378 SDNode *LD1 = getBuildPairElt(N, 0);
3379 if (!ISD::isNON_EXTLoad(LD1) || !LD1->hasOneUse())
3381 MVT LD1VT = LD1->getValueType(0);
3382 SDNode *LD2 = getBuildPairElt(N, 1);
3383 const MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
3384 if (ISD::isNON_EXTLoad(LD2) &&
3386 // If both are volatile this would reduce the number of volatile loads.
3387 // If one is volatile it might be ok, but play conservative and bail out.
3388 !cast<LoadSDNode>(LD1)->isVolatile() &&
3389 !cast<LoadSDNode>(LD2)->isVolatile() &&
3390 TLI.isConsecutiveLoad(LD2, LD1, LD1VT.getSizeInBits()/8, 1, MFI)) {
3391 LoadSDNode *LD = cast<LoadSDNode>(LD1);
3392 unsigned Align = LD->getAlignment();
3393 unsigned NewAlign = TLI.getTargetMachine().getTargetData()->
3394 getABITypeAlignment(VT.getTypeForMVT());
3395 if (NewAlign <= Align &&
3396 (!AfterLegalize || TLI.isOperationLegal(ISD::LOAD, VT)))
3397 return DAG.getLoad(VT, LD->getChain(), LD->getBasePtr(),
3398 LD->getSrcValue(), LD->getSrcValueOffset(),
3404 SDOperand DAGCombiner::visitBIT_CONVERT(SDNode *N) {
3405 SDOperand N0 = N->getOperand(0);
3406 MVT VT = N->getValueType(0);
3408 // If the input is a BUILD_VECTOR with all constant elements, fold this now.
3409 // Only do this before legalize, since afterward the target may be depending
3410 // on the bitconvert.
3411 // First check to see if this is all constant.
3412 if (!AfterLegalize &&
3413 N0.getOpcode() == ISD::BUILD_VECTOR && N0.Val->hasOneUse() &&
3415 bool isSimple = true;
3416 for (unsigned i = 0, e = N0.getNumOperands(); i != e; ++i)
3417 if (N0.getOperand(i).getOpcode() != ISD::UNDEF &&
3418 N0.getOperand(i).getOpcode() != ISD::Constant &&
3419 N0.getOperand(i).getOpcode() != ISD::ConstantFP) {
3424 MVT DestEltVT = N->getValueType(0).getVectorElementType();
3425 assert(!DestEltVT.isVector() &&
3426 "Element type of vector ValueType must not be vector!");
3428 return ConstantFoldBIT_CONVERTofBUILD_VECTOR(N0.Val, DestEltVT);
3432 // If the input is a constant, let getNode() fold it.
3433 if (isa<ConstantSDNode>(N0) || isa<ConstantFPSDNode>(N0)) {
3434 SDOperand Res = DAG.getNode(ISD::BIT_CONVERT, VT, N0);
3435 if (Res.Val != N) return Res;
3438 if (N0.getOpcode() == ISD::BIT_CONVERT) // conv(conv(x,t1),t2) -> conv(x,t2)
3439 return DAG.getNode(ISD::BIT_CONVERT, VT, N0.getOperand(0));
3441 // fold (conv (load x)) -> (load (conv*)x)
3442 // If the resultant load doesn't need a higher alignment than the original!
3443 if (ISD::isNormalLoad(N0.Val) && N0.hasOneUse() &&
3444 // Do not change the width of a volatile load.
3445 !cast<LoadSDNode>(N0)->isVolatile() &&
3446 (!AfterLegalize || TLI.isOperationLegal(ISD::LOAD, VT))) {
3447 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
3448 unsigned Align = TLI.getTargetMachine().getTargetData()->
3449 getABITypeAlignment(VT.getTypeForMVT());
3450 unsigned OrigAlign = LN0->getAlignment();
3451 if (Align <= OrigAlign) {
3452 SDOperand Load = DAG.getLoad(VT, LN0->getChain(), LN0->getBasePtr(),
3453 LN0->getSrcValue(), LN0->getSrcValueOffset(),
3454 LN0->isVolatile(), Align);
3456 CombineTo(N0.Val, DAG.getNode(ISD::BIT_CONVERT, N0.getValueType(), Load),
3462 // Fold bitconvert(fneg(x)) -> xor(bitconvert(x), signbit)
3463 // Fold bitconvert(fabs(x)) -> and(bitconvert(x), ~signbit)
3464 // This often reduces constant pool loads.
3465 if ((N0.getOpcode() == ISD::FNEG || N0.getOpcode() == ISD::FABS) &&
3466 N0.Val->hasOneUse() && VT.isInteger() && !VT.isVector()) {
3467 SDOperand NewConv = DAG.getNode(ISD::BIT_CONVERT, VT, N0.getOperand(0));
3468 AddToWorkList(NewConv.Val);
3470 APInt SignBit = APInt::getSignBit(VT.getSizeInBits());
3471 if (N0.getOpcode() == ISD::FNEG)
3472 return DAG.getNode(ISD::XOR, VT, NewConv, DAG.getConstant(SignBit, VT));
3473 assert(N0.getOpcode() == ISD::FABS);
3474 return DAG.getNode(ISD::AND, VT, NewConv, DAG.getConstant(~SignBit, VT));
3477 // Fold bitconvert(fcopysign(cst, x)) -> bitconvert(x)&sign | cst&~sign'
3478 // Note that we don't handle copysign(x,cst) because this can always be folded
3479 // to an fneg or fabs.
3480 if (N0.getOpcode() == ISD::FCOPYSIGN && N0.Val->hasOneUse() &&
3481 isa<ConstantFPSDNode>(N0.getOperand(0)) &&
3482 VT.isInteger() && !VT.isVector()) {
3483 unsigned OrigXWidth = N0.getOperand(1).getValueType().getSizeInBits();
3484 SDOperand X = DAG.getNode(ISD::BIT_CONVERT,
3485 MVT::getIntegerVT(OrigXWidth),
3487 AddToWorkList(X.Val);
3489 // If X has a different width than the result/lhs, sext it or truncate it.
3490 unsigned VTWidth = VT.getSizeInBits();
3491 if (OrigXWidth < VTWidth) {
3492 X = DAG.getNode(ISD::SIGN_EXTEND, VT, X);
3493 AddToWorkList(X.Val);
3494 } else if (OrigXWidth > VTWidth) {
3495 // To get the sign bit in the right place, we have to shift it right
3496 // before truncating.
3497 X = DAG.getNode(ISD::SRL, X.getValueType(), X,
3498 DAG.getConstant(OrigXWidth-VTWidth, X.getValueType()));
3499 AddToWorkList(X.Val);
3500 X = DAG.getNode(ISD::TRUNCATE, VT, X);
3501 AddToWorkList(X.Val);
3504 APInt SignBit = APInt::getSignBit(VT.getSizeInBits());
3505 X = DAG.getNode(ISD::AND, VT, X, DAG.getConstant(SignBit, VT));
3506 AddToWorkList(X.Val);
3508 SDOperand Cst = DAG.getNode(ISD::BIT_CONVERT, VT, N0.getOperand(0));
3509 Cst = DAG.getNode(ISD::AND, VT, Cst, DAG.getConstant(~SignBit, VT));
3510 AddToWorkList(Cst.Val);
3512 return DAG.getNode(ISD::OR, VT, X, Cst);
3515 // bitconvert(build_pair(ld, ld)) -> ld iff load locations are consecutive.
3516 if (N0.getOpcode() == ISD::BUILD_PAIR) {
3517 SDOperand CombineLD = CombineConsecutiveLoads(N0.Val, VT);
3525 SDOperand DAGCombiner::visitBUILD_PAIR(SDNode *N) {
3526 MVT VT = N->getValueType(0);
3527 return CombineConsecutiveLoads(N, VT);
3530 /// ConstantFoldBIT_CONVERTofBUILD_VECTOR - We know that BV is a build_vector
3531 /// node with Constant, ConstantFP or Undef operands. DstEltVT indicates the
3532 /// destination element value type.
3533 SDOperand DAGCombiner::
3534 ConstantFoldBIT_CONVERTofBUILD_VECTOR(SDNode *BV, MVT DstEltVT) {
3535 MVT SrcEltVT = BV->getOperand(0).getValueType();
3537 // If this is already the right type, we're done.
3538 if (SrcEltVT == DstEltVT) return SDOperand(BV, 0);
3540 unsigned SrcBitSize = SrcEltVT.getSizeInBits();
3541 unsigned DstBitSize = DstEltVT.getSizeInBits();
3543 // If this is a conversion of N elements of one type to N elements of another
3544 // type, convert each element. This handles FP<->INT cases.
3545 if (SrcBitSize == DstBitSize) {
3546 SmallVector<SDOperand, 8> Ops;
3547 for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) {
3548 Ops.push_back(DAG.getNode(ISD::BIT_CONVERT, DstEltVT, BV->getOperand(i)));
3549 AddToWorkList(Ops.back().Val);
3551 MVT VT = MVT::getVectorVT(DstEltVT,
3552 BV->getValueType(0).getVectorNumElements());
3553 return DAG.getNode(ISD::BUILD_VECTOR, VT, &Ops[0], Ops.size());
3556 // Otherwise, we're growing or shrinking the elements. To avoid having to
3557 // handle annoying details of growing/shrinking FP values, we convert them to
3559 if (SrcEltVT.isFloatingPoint()) {
3560 // Convert the input float vector to a int vector where the elements are the
3562 assert((SrcEltVT == MVT::f32 || SrcEltVT == MVT::f64) && "Unknown FP VT!");
3563 MVT IntVT = MVT::getIntegerVT(SrcEltVT.getSizeInBits());
3564 BV = ConstantFoldBIT_CONVERTofBUILD_VECTOR(BV, IntVT).Val;
3568 // Now we know the input is an integer vector. If the output is a FP type,
3569 // convert to integer first, then to FP of the right size.
3570 if (DstEltVT.isFloatingPoint()) {
3571 assert((DstEltVT == MVT::f32 || DstEltVT == MVT::f64) && "Unknown FP VT!");
3572 MVT TmpVT = MVT::getIntegerVT(DstEltVT.getSizeInBits());
3573 SDNode *Tmp = ConstantFoldBIT_CONVERTofBUILD_VECTOR(BV, TmpVT).Val;
3575 // Next, convert to FP elements of the same size.
3576 return ConstantFoldBIT_CONVERTofBUILD_VECTOR(Tmp, DstEltVT);
3579 // Okay, we know the src/dst types are both integers of differing types.
3580 // Handling growing first.
3581 assert(SrcEltVT.isInteger() && DstEltVT.isInteger());
3582 if (SrcBitSize < DstBitSize) {
3583 unsigned NumInputsPerOutput = DstBitSize/SrcBitSize;
3585 SmallVector<SDOperand, 8> Ops;
3586 for (unsigned i = 0, e = BV->getNumOperands(); i != e;
3587 i += NumInputsPerOutput) {
3588 bool isLE = TLI.isLittleEndian();
3589 APInt NewBits = APInt(DstBitSize, 0);
3590 bool EltIsUndef = true;
3591 for (unsigned j = 0; j != NumInputsPerOutput; ++j) {
3592 // Shift the previously computed bits over.
3593 NewBits <<= SrcBitSize;
3594 SDOperand Op = BV->getOperand(i+ (isLE ? (NumInputsPerOutput-j-1) : j));
3595 if (Op.getOpcode() == ISD::UNDEF) continue;
3599 APInt(cast<ConstantSDNode>(Op)->getAPIntValue()).zext(DstBitSize);
3603 Ops.push_back(DAG.getNode(ISD::UNDEF, DstEltVT));
3605 Ops.push_back(DAG.getConstant(NewBits, DstEltVT));
3608 MVT VT = MVT::getVectorVT(DstEltVT, Ops.size());
3609 return DAG.getNode(ISD::BUILD_VECTOR, VT, &Ops[0], Ops.size());
3612 // Finally, this must be the case where we are shrinking elements: each input
3613 // turns into multiple outputs.
3614 bool isS2V = ISD::isScalarToVector(BV);
3615 unsigned NumOutputsPerInput = SrcBitSize/DstBitSize;
3616 MVT VT = MVT::getVectorVT(DstEltVT, NumOutputsPerInput*BV->getNumOperands());
3617 SmallVector<SDOperand, 8> Ops;
3618 for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) {
3619 if (BV->getOperand(i).getOpcode() == ISD::UNDEF) {
3620 for (unsigned j = 0; j != NumOutputsPerInput; ++j)
3621 Ops.push_back(DAG.getNode(ISD::UNDEF, DstEltVT));
3624 APInt OpVal = cast<ConstantSDNode>(BV->getOperand(i))->getAPIntValue();
3625 for (unsigned j = 0; j != NumOutputsPerInput; ++j) {
3626 APInt ThisVal = APInt(OpVal).trunc(DstBitSize);
3627 Ops.push_back(DAG.getConstant(ThisVal, DstEltVT));
3628 if (isS2V && i == 0 && j == 0 && APInt(ThisVal).zext(SrcBitSize) == OpVal)
3629 // Simply turn this into a SCALAR_TO_VECTOR of the new type.
3630 return DAG.getNode(ISD::SCALAR_TO_VECTOR, VT, Ops[0]);
3631 OpVal = OpVal.lshr(DstBitSize);
3634 // For big endian targets, swap the order of the pieces of each element.
3635 if (TLI.isBigEndian())
3636 std::reverse(Ops.end()-NumOutputsPerInput, Ops.end());
3638 return DAG.getNode(ISD::BUILD_VECTOR, VT, &Ops[0], Ops.size());
3643 SDOperand DAGCombiner::visitFADD(SDNode *N) {
3644 SDOperand N0 = N->getOperand(0);
3645 SDOperand N1 = N->getOperand(1);
3646 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
3647 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
3648 MVT VT = N->getValueType(0);
3651 if (VT.isVector()) {
3652 SDOperand FoldedVOp = SimplifyVBinOp(N);
3653 if (FoldedVOp.Val) return FoldedVOp;
3656 // fold (fadd c1, c2) -> c1+c2
3657 if (N0CFP && N1CFP && VT != MVT::ppcf128)
3658 return DAG.getNode(ISD::FADD, VT, N0, N1);
3659 // canonicalize constant to RHS
3660 if (N0CFP && !N1CFP)
3661 return DAG.getNode(ISD::FADD, VT, N1, N0);
3662 // fold (A + (-B)) -> A-B
3663 if (isNegatibleForFree(N1, AfterLegalize) == 2)
3664 return DAG.getNode(ISD::FSUB, VT, N0,
3665 GetNegatedExpression(N1, DAG, AfterLegalize));
3666 // fold ((-A) + B) -> B-A
3667 if (isNegatibleForFree(N0, AfterLegalize) == 2)
3668 return DAG.getNode(ISD::FSUB, VT, N1,
3669 GetNegatedExpression(N0, DAG, AfterLegalize));
3671 // If allowed, fold (fadd (fadd x, c1), c2) -> (fadd x, (fadd c1, c2))
3672 if (UnsafeFPMath && N1CFP && N0.getOpcode() == ISD::FADD &&
3673 N0.Val->hasOneUse() && isa<ConstantFPSDNode>(N0.getOperand(1)))
3674 return DAG.getNode(ISD::FADD, VT, N0.getOperand(0),
3675 DAG.getNode(ISD::FADD, VT, N0.getOperand(1), N1));
3680 SDOperand DAGCombiner::visitFSUB(SDNode *N) {
3681 SDOperand N0 = N->getOperand(0);
3682 SDOperand N1 = N->getOperand(1);
3683 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
3684 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
3685 MVT VT = N->getValueType(0);
3688 if (VT.isVector()) {
3689 SDOperand FoldedVOp = SimplifyVBinOp(N);
3690 if (FoldedVOp.Val) return FoldedVOp;
3693 // fold (fsub c1, c2) -> c1-c2
3694 if (N0CFP && N1CFP && VT != MVT::ppcf128)
3695 return DAG.getNode(ISD::FSUB, VT, N0, N1);
3697 if (UnsafeFPMath && N0CFP && N0CFP->getValueAPF().isZero()) {
3698 if (isNegatibleForFree(N1, AfterLegalize))
3699 return GetNegatedExpression(N1, DAG, AfterLegalize);
3700 return DAG.getNode(ISD::FNEG, VT, N1);
3702 // fold (A-(-B)) -> A+B
3703 if (isNegatibleForFree(N1, AfterLegalize))
3704 return DAG.getNode(ISD::FADD, VT, N0,
3705 GetNegatedExpression(N1, DAG, AfterLegalize));
3710 SDOperand DAGCombiner::visitFMUL(SDNode *N) {
3711 SDOperand N0 = N->getOperand(0);
3712 SDOperand N1 = N->getOperand(1);
3713 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
3714 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
3715 MVT VT = N->getValueType(0);
3718 if (VT.isVector()) {
3719 SDOperand FoldedVOp = SimplifyVBinOp(N);
3720 if (FoldedVOp.Val) return FoldedVOp;
3723 // fold (fmul c1, c2) -> c1*c2
3724 if (N0CFP && N1CFP && VT != MVT::ppcf128)
3725 return DAG.getNode(ISD::FMUL, VT, N0, N1);
3726 // canonicalize constant to RHS
3727 if (N0CFP && !N1CFP)
3728 return DAG.getNode(ISD::FMUL, VT, N1, N0);
3729 // fold (fmul X, 2.0) -> (fadd X, X)
3730 if (N1CFP && N1CFP->isExactlyValue(+2.0))
3731 return DAG.getNode(ISD::FADD, VT, N0, N0);
3732 // fold (fmul X, -1.0) -> (fneg X)
3733 if (N1CFP && N1CFP->isExactlyValue(-1.0))
3734 return DAG.getNode(ISD::FNEG, VT, N0);
3737 if (char LHSNeg = isNegatibleForFree(N0, AfterLegalize)) {
3738 if (char RHSNeg = isNegatibleForFree(N1, AfterLegalize)) {
3739 // Both can be negated for free, check to see if at least one is cheaper
3741 if (LHSNeg == 2 || RHSNeg == 2)
3742 return DAG.getNode(ISD::FMUL, VT,
3743 GetNegatedExpression(N0, DAG, AfterLegalize),
3744 GetNegatedExpression(N1, DAG, AfterLegalize));
3748 // If allowed, fold (fmul (fmul x, c1), c2) -> (fmul x, (fmul c1, c2))
3749 if (UnsafeFPMath && N1CFP && N0.getOpcode() == ISD::FMUL &&
3750 N0.Val->hasOneUse() && isa<ConstantFPSDNode>(N0.getOperand(1)))
3751 return DAG.getNode(ISD::FMUL, VT, N0.getOperand(0),
3752 DAG.getNode(ISD::FMUL, VT, N0.getOperand(1), N1));
3757 SDOperand DAGCombiner::visitFDIV(SDNode *N) {
3758 SDOperand N0 = N->getOperand(0);
3759 SDOperand N1 = N->getOperand(1);
3760 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
3761 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
3762 MVT VT = N->getValueType(0);
3765 if (VT.isVector()) {
3766 SDOperand FoldedVOp = SimplifyVBinOp(N);
3767 if (FoldedVOp.Val) return FoldedVOp;
3770 // fold (fdiv c1, c2) -> c1/c2
3771 if (N0CFP && N1CFP && VT != MVT::ppcf128)
3772 return DAG.getNode(ISD::FDIV, VT, N0, N1);
3776 if (char LHSNeg = isNegatibleForFree(N0, AfterLegalize)) {
3777 if (char RHSNeg = isNegatibleForFree(N1, AfterLegalize)) {
3778 // Both can be negated for free, check to see if at least one is cheaper
3780 if (LHSNeg == 2 || RHSNeg == 2)
3781 return DAG.getNode(ISD::FDIV, VT,
3782 GetNegatedExpression(N0, DAG, AfterLegalize),
3783 GetNegatedExpression(N1, DAG, AfterLegalize));
3790 SDOperand DAGCombiner::visitFREM(SDNode *N) {
3791 SDOperand N0 = N->getOperand(0);
3792 SDOperand N1 = N->getOperand(1);
3793 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
3794 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
3795 MVT VT = N->getValueType(0);
3797 // fold (frem c1, c2) -> fmod(c1,c2)
3798 if (N0CFP && N1CFP && VT != MVT::ppcf128)
3799 return DAG.getNode(ISD::FREM, VT, N0, N1);
3804 SDOperand DAGCombiner::visitFCOPYSIGN(SDNode *N) {
3805 SDOperand N0 = N->getOperand(0);
3806 SDOperand N1 = N->getOperand(1);
3807 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
3808 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
3809 MVT VT = N->getValueType(0);
3811 if (N0CFP && N1CFP && VT != MVT::ppcf128) // Constant fold
3812 return DAG.getNode(ISD::FCOPYSIGN, VT, N0, N1);
3815 const APFloat& V = N1CFP->getValueAPF();
3816 // copysign(x, c1) -> fabs(x) iff ispos(c1)
3817 // copysign(x, c1) -> fneg(fabs(x)) iff isneg(c1)
3818 if (!V.isNegative())
3819 return DAG.getNode(ISD::FABS, VT, N0);
3821 return DAG.getNode(ISD::FNEG, VT, DAG.getNode(ISD::FABS, VT, N0));
3824 // copysign(fabs(x), y) -> copysign(x, y)
3825 // copysign(fneg(x), y) -> copysign(x, y)
3826 // copysign(copysign(x,z), y) -> copysign(x, y)
3827 if (N0.getOpcode() == ISD::FABS || N0.getOpcode() == ISD::FNEG ||
3828 N0.getOpcode() == ISD::FCOPYSIGN)
3829 return DAG.getNode(ISD::FCOPYSIGN, VT, N0.getOperand(0), N1);
3831 // copysign(x, abs(y)) -> abs(x)
3832 if (N1.getOpcode() == ISD::FABS)
3833 return DAG.getNode(ISD::FABS, VT, N0);
3835 // copysign(x, copysign(y,z)) -> copysign(x, z)
3836 if (N1.getOpcode() == ISD::FCOPYSIGN)
3837 return DAG.getNode(ISD::FCOPYSIGN, VT, N0, N1.getOperand(1));
3839 // copysign(x, fp_extend(y)) -> copysign(x, y)
3840 // copysign(x, fp_round(y)) -> copysign(x, y)
3841 if (N1.getOpcode() == ISD::FP_EXTEND || N1.getOpcode() == ISD::FP_ROUND)
3842 return DAG.getNode(ISD::FCOPYSIGN, VT, N0, N1.getOperand(0));
3849 SDOperand DAGCombiner::visitSINT_TO_FP(SDNode *N) {
3850 SDOperand N0 = N->getOperand(0);
3851 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
3852 MVT VT = N->getValueType(0);
3854 // fold (sint_to_fp c1) -> c1fp
3855 if (N0C && N0.getValueType() != MVT::ppcf128)
3856 return DAG.getNode(ISD::SINT_TO_FP, VT, N0);
3860 SDOperand DAGCombiner::visitUINT_TO_FP(SDNode *N) {
3861 SDOperand N0 = N->getOperand(0);
3862 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
3863 MVT VT = N->getValueType(0);
3865 // fold (uint_to_fp c1) -> c1fp
3866 if (N0C && N0.getValueType() != MVT::ppcf128)
3867 return DAG.getNode(ISD::UINT_TO_FP, VT, N0);
3871 SDOperand DAGCombiner::visitFP_TO_SINT(SDNode *N) {
3872 SDOperand N0 = N->getOperand(0);
3873 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
3874 MVT VT = N->getValueType(0);
3876 // fold (fp_to_sint c1fp) -> c1
3878 return DAG.getNode(ISD::FP_TO_SINT, VT, N0);
3882 SDOperand DAGCombiner::visitFP_TO_UINT(SDNode *N) {
3883 SDOperand N0 = N->getOperand(0);
3884 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
3885 MVT VT = N->getValueType(0);
3887 // fold (fp_to_uint c1fp) -> c1
3888 if (N0CFP && VT != MVT::ppcf128)
3889 return DAG.getNode(ISD::FP_TO_UINT, VT, N0);
3893 SDOperand DAGCombiner::visitFP_ROUND(SDNode *N) {
3894 SDOperand N0 = N->getOperand(0);
3895 SDOperand N1 = N->getOperand(1);
3896 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
3897 MVT VT = N->getValueType(0);
3899 // fold (fp_round c1fp) -> c1fp
3900 if (N0CFP && N0.getValueType() != MVT::ppcf128)
3901 return DAG.getNode(ISD::FP_ROUND, VT, N0, N1);
3903 // fold (fp_round (fp_extend x)) -> x
3904 if (N0.getOpcode() == ISD::FP_EXTEND && VT == N0.getOperand(0).getValueType())
3905 return N0.getOperand(0);
3907 // fold (fp_round (fp_round x)) -> (fp_round x)
3908 if (N0.getOpcode() == ISD::FP_ROUND) {
3909 // This is a value preserving truncation if both round's are.
3910 bool IsTrunc = N->getConstantOperandVal(1) == 1 &&
3911 N0.Val->getConstantOperandVal(1) == 1;
3912 return DAG.getNode(ISD::FP_ROUND, VT, N0.getOperand(0),
3913 DAG.getIntPtrConstant(IsTrunc));
3916 // fold (fp_round (copysign X, Y)) -> (copysign (fp_round X), Y)
3917 if (N0.getOpcode() == ISD::FCOPYSIGN && N0.Val->hasOneUse()) {
3918 SDOperand Tmp = DAG.getNode(ISD::FP_ROUND, VT, N0.getOperand(0), N1);
3919 AddToWorkList(Tmp.Val);
3920 return DAG.getNode(ISD::FCOPYSIGN, VT, Tmp, N0.getOperand(1));
3926 SDOperand DAGCombiner::visitFP_ROUND_INREG(SDNode *N) {
3927 SDOperand N0 = N->getOperand(0);
3928 MVT VT = N->getValueType(0);
3929 MVT EVT = cast<VTSDNode>(N->getOperand(1))->getVT();
3930 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
3932 // fold (fp_round_inreg c1fp) -> c1fp
3934 SDOperand Round = DAG.getConstantFP(N0CFP->getValueAPF(), EVT);
3935 return DAG.getNode(ISD::FP_EXTEND, VT, Round);
3940 SDOperand DAGCombiner::visitFP_EXTEND(SDNode *N) {
3941 SDOperand N0 = N->getOperand(0);
3942 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
3943 MVT VT = N->getValueType(0);
3945 // If this is fp_round(fpextend), don't fold it, allow ourselves to be folded.
3946 if (N->hasOneUse() &&
3947 N->use_begin()->getSDOperand().getOpcode() == ISD::FP_ROUND)
3950 // fold (fp_extend c1fp) -> c1fp
3951 if (N0CFP && VT != MVT::ppcf128)
3952 return DAG.getNode(ISD::FP_EXTEND, VT, N0);
3954 // Turn fp_extend(fp_round(X, 1)) -> x since the fp_round doesn't affect the
3956 if (N0.getOpcode() == ISD::FP_ROUND && N0.Val->getConstantOperandVal(1) == 1){
3957 SDOperand In = N0.getOperand(0);
3958 if (In.getValueType() == VT) return In;
3959 if (VT.bitsLT(In.getValueType()))
3960 return DAG.getNode(ISD::FP_ROUND, VT, In, N0.getOperand(1));
3961 return DAG.getNode(ISD::FP_EXTEND, VT, In);
3964 // fold (fpext (load x)) -> (fpext (fptrunc (extload x)))
3965 if (ISD::isNON_EXTLoad(N0.Val) && N0.hasOneUse() &&
3966 ((!AfterLegalize && !cast<LoadSDNode>(N0)->isVolatile()) ||
3967 TLI.isLoadXLegal(ISD::EXTLOAD, N0.getValueType()))) {
3968 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
3969 SDOperand ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, VT, LN0->getChain(),
3970 LN0->getBasePtr(), LN0->getSrcValue(),
3971 LN0->getSrcValueOffset(),
3974 LN0->getAlignment());
3975 CombineTo(N, ExtLoad);
3976 CombineTo(N0.Val, DAG.getNode(ISD::FP_ROUND, N0.getValueType(), ExtLoad,
3977 DAG.getIntPtrConstant(1)),
3978 ExtLoad.getValue(1));
3979 return SDOperand(N, 0); // Return N so it doesn't get rechecked!
3985 SDOperand DAGCombiner::visitFNEG(SDNode *N) {
3986 SDOperand N0 = N->getOperand(0);
3988 if (isNegatibleForFree(N0, AfterLegalize))
3989 return GetNegatedExpression(N0, DAG, AfterLegalize);
3991 // Transform fneg(bitconvert(x)) -> bitconvert(x^sign) to avoid loading
3992 // constant pool values.
3993 if (N0.getOpcode() == ISD::BIT_CONVERT && N0.Val->hasOneUse() &&
3994 N0.getOperand(0).getValueType().isInteger() &&
3995 !N0.getOperand(0).getValueType().isVector()) {
3996 SDOperand Int = N0.getOperand(0);
3997 MVT IntVT = Int.getValueType();
3998 if (IntVT.isInteger() && !IntVT.isVector()) {
3999 Int = DAG.getNode(ISD::XOR, IntVT, Int,
4000 DAG.getConstant(IntVT.getIntegerVTSignBit(), IntVT));
4001 AddToWorkList(Int.Val);
4002 return DAG.getNode(ISD::BIT_CONVERT, N->getValueType(0), Int);
4009 SDOperand DAGCombiner::visitFABS(SDNode *N) {
4010 SDOperand N0 = N->getOperand(0);
4011 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
4012 MVT VT = N->getValueType(0);
4014 // fold (fabs c1) -> fabs(c1)
4015 if (N0CFP && VT != MVT::ppcf128)
4016 return DAG.getNode(ISD::FABS, VT, N0);
4017 // fold (fabs (fabs x)) -> (fabs x)
4018 if (N0.getOpcode() == ISD::FABS)
4019 return N->getOperand(0);
4020 // fold (fabs (fneg x)) -> (fabs x)
4021 // fold (fabs (fcopysign x, y)) -> (fabs x)
4022 if (N0.getOpcode() == ISD::FNEG || N0.getOpcode() == ISD::FCOPYSIGN)
4023 return DAG.getNode(ISD::FABS, VT, N0.getOperand(0));
4025 // Transform fabs(bitconvert(x)) -> bitconvert(x&~sign) to avoid loading
4026 // constant pool values.
4027 if (N0.getOpcode() == ISD::BIT_CONVERT && N0.Val->hasOneUse() &&
4028 N0.getOperand(0).getValueType().isInteger() &&
4029 !N0.getOperand(0).getValueType().isVector()) {
4030 SDOperand Int = N0.getOperand(0);
4031 MVT IntVT = Int.getValueType();
4032 if (IntVT.isInteger() && !IntVT.isVector()) {
4033 Int = DAG.getNode(ISD::AND, IntVT, Int,
4034 DAG.getConstant(~IntVT.getIntegerVTSignBit(), IntVT));
4035 AddToWorkList(Int.Val);
4036 return DAG.getNode(ISD::BIT_CONVERT, N->getValueType(0), Int);
4043 SDOperand DAGCombiner::visitBRCOND(SDNode *N) {
4044 SDOperand Chain = N->getOperand(0);
4045 SDOperand N1 = N->getOperand(1);
4046 SDOperand N2 = N->getOperand(2);
4047 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4049 // never taken branch, fold to chain
4050 if (N1C && N1C->isNullValue())
4052 // unconditional branch
4053 if (N1C && N1C->getAPIntValue() == 1)
4054 return DAG.getNode(ISD::BR, MVT::Other, Chain, N2);
4055 // fold a brcond with a setcc condition into a BR_CC node if BR_CC is legal
4057 if (N1.getOpcode() == ISD::SETCC &&
4058 TLI.isOperationLegal(ISD::BR_CC, MVT::Other)) {
4059 return DAG.getNode(ISD::BR_CC, MVT::Other, Chain, N1.getOperand(2),
4060 N1.getOperand(0), N1.getOperand(1), N2);
4065 // Operand List for BR_CC: Chain, CondCC, CondLHS, CondRHS, DestBB.
4067 SDOperand DAGCombiner::visitBR_CC(SDNode *N) {
4068 CondCodeSDNode *CC = cast<CondCodeSDNode>(N->getOperand(1));
4069 SDOperand CondLHS = N->getOperand(2), CondRHS = N->getOperand(3);
4071 // Use SimplifySetCC to simplify SETCC's.
4072 SDOperand Simp = SimplifySetCC(MVT::i1, CondLHS, CondRHS, CC->get(), false);
4073 if (Simp.Val) AddToWorkList(Simp.Val);
4075 ConstantSDNode *SCCC = dyn_cast_or_null<ConstantSDNode>(Simp.Val);
4077 // fold br_cc true, dest -> br dest (unconditional branch)
4078 if (SCCC && !SCCC->isNullValue())
4079 return DAG.getNode(ISD::BR, MVT::Other, N->getOperand(0),
4081 // fold br_cc false, dest -> unconditional fall through
4082 if (SCCC && SCCC->isNullValue())
4083 return N->getOperand(0);
4085 // fold to a simpler setcc
4086 if (Simp.Val && Simp.getOpcode() == ISD::SETCC)
4087 return DAG.getNode(ISD::BR_CC, MVT::Other, N->getOperand(0),
4088 Simp.getOperand(2), Simp.getOperand(0),
4089 Simp.getOperand(1), N->getOperand(4));
4094 /// CombineToPreIndexedLoadStore - Try turning a load / store into a
4095 /// pre-indexed load / store when the base pointer is an add or subtract
4096 /// and it has other uses besides the load / store. After the
4097 /// transformation, the new indexed load / store has effectively folded
4098 /// the add / subtract in and all of its other uses are redirected to the
4099 /// new load / store.
4100 bool DAGCombiner::CombineToPreIndexedLoadStore(SDNode *N) {
4107 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
4108 if (LD->isIndexed())
4110 VT = LD->getMemoryVT();
4111 if (!TLI.isIndexedLoadLegal(ISD::PRE_INC, VT) &&
4112 !TLI.isIndexedLoadLegal(ISD::PRE_DEC, VT))
4114 Ptr = LD->getBasePtr();
4115 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
4116 if (ST->isIndexed())
4118 VT = ST->getMemoryVT();
4119 if (!TLI.isIndexedStoreLegal(ISD::PRE_INC, VT) &&
4120 !TLI.isIndexedStoreLegal(ISD::PRE_DEC, VT))
4122 Ptr = ST->getBasePtr();
4127 // If the pointer is not an add/sub, or if it doesn't have multiple uses, bail
4128 // out. There is no reason to make this a preinc/predec.
4129 if ((Ptr.getOpcode() != ISD::ADD && Ptr.getOpcode() != ISD::SUB) ||
4130 Ptr.Val->hasOneUse())
4133 // Ask the target to do addressing mode selection.
4136 ISD::MemIndexedMode AM = ISD::UNINDEXED;
4137 if (!TLI.getPreIndexedAddressParts(N, BasePtr, Offset, AM, DAG))
4139 // Don't create a indexed load / store with zero offset.
4140 if (isa<ConstantSDNode>(Offset) &&
4141 cast<ConstantSDNode>(Offset)->isNullValue())
4144 // Try turning it into a pre-indexed load / store except when:
4145 // 1) The new base ptr is a frame index.
4146 // 2) If N is a store and the new base ptr is either the same as or is a
4147 // predecessor of the value being stored.
4148 // 3) Another use of old base ptr is a predecessor of N. If ptr is folded
4149 // that would create a cycle.
4150 // 4) All uses are load / store ops that use it as old base ptr.
4152 // Check #1. Preinc'ing a frame index would require copying the stack pointer
4153 // (plus the implicit offset) to a register to preinc anyway.
4154 if (isa<FrameIndexSDNode>(BasePtr))
4159 SDOperand Val = cast<StoreSDNode>(N)->getValue();
4160 if (Val == BasePtr || BasePtr.Val->isPredecessorOf(Val.Val))
4164 // Now check for #3 and #4.
4165 bool RealUse = false;
4166 for (SDNode::use_iterator I = Ptr.Val->use_begin(),
4167 E = Ptr.Val->use_end(); I != E; ++I) {
4168 SDNode *Use = I->getUser();
4171 if (Use->isPredecessorOf(N))
4174 if (!((Use->getOpcode() == ISD::LOAD &&
4175 cast<LoadSDNode>(Use)->getBasePtr() == Ptr) ||
4176 (Use->getOpcode() == ISD::STORE &&
4177 cast<StoreSDNode>(Use)->getBasePtr() == Ptr)))
4185 Result = DAG.getIndexedLoad(SDOperand(N,0), BasePtr, Offset, AM);
4187 Result = DAG.getIndexedStore(SDOperand(N,0), BasePtr, Offset, AM);
4190 DOUT << "\nReplacing.4 "; DEBUG(N->dump(&DAG));
4191 DOUT << "\nWith: "; DEBUG(Result.Val->dump(&DAG));
4193 WorkListRemover DeadNodes(*this);
4195 DAG.ReplaceAllUsesOfValueWith(SDOperand(N, 0), Result.getValue(0),
4197 DAG.ReplaceAllUsesOfValueWith(SDOperand(N, 1), Result.getValue(2),
4200 DAG.ReplaceAllUsesOfValueWith(SDOperand(N, 0), Result.getValue(1),
4204 // Finally, since the node is now dead, remove it from the graph.
4207 // Replace the uses of Ptr with uses of the updated base value.
4208 DAG.ReplaceAllUsesOfValueWith(Ptr, Result.getValue(isLoad ? 1 : 0),
4210 removeFromWorkList(Ptr.Val);
4211 DAG.DeleteNode(Ptr.Val);
4216 /// CombineToPostIndexedLoadStore - Try to combine a load / store with a
4217 /// add / sub of the base pointer node into a post-indexed load / store.
4218 /// The transformation folded the add / subtract into the new indexed
4219 /// load / store effectively and all of its uses are redirected to the
4220 /// new load / store.
4221 bool DAGCombiner::CombineToPostIndexedLoadStore(SDNode *N) {
4228 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
4229 if (LD->isIndexed())
4231 VT = LD->getMemoryVT();
4232 if (!TLI.isIndexedLoadLegal(ISD::POST_INC, VT) &&
4233 !TLI.isIndexedLoadLegal(ISD::POST_DEC, VT))
4235 Ptr = LD->getBasePtr();
4236 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
4237 if (ST->isIndexed())
4239 VT = ST->getMemoryVT();
4240 if (!TLI.isIndexedStoreLegal(ISD::POST_INC, VT) &&
4241 !TLI.isIndexedStoreLegal(ISD::POST_DEC, VT))
4243 Ptr = ST->getBasePtr();
4248 if (Ptr.Val->hasOneUse())
4251 for (SDNode::use_iterator I = Ptr.Val->use_begin(),
4252 E = Ptr.Val->use_end(); I != E; ++I) {
4253 SDNode *Op = I->getUser();
4255 (Op->getOpcode() != ISD::ADD && Op->getOpcode() != ISD::SUB))
4260 ISD::MemIndexedMode AM = ISD::UNINDEXED;
4261 if (TLI.getPostIndexedAddressParts(N, Op, BasePtr, Offset, AM, DAG)) {
4263 std::swap(BasePtr, Offset);
4266 // Don't create a indexed load / store with zero offset.
4267 if (isa<ConstantSDNode>(Offset) &&
4268 cast<ConstantSDNode>(Offset)->isNullValue())
4271 // Try turning it into a post-indexed load / store except when
4272 // 1) All uses are load / store ops that use it as base ptr.
4273 // 2) Op must be independent of N, i.e. Op is neither a predecessor
4274 // nor a successor of N. Otherwise, if Op is folded that would
4278 bool TryNext = false;
4279 for (SDNode::use_iterator II = BasePtr.Val->use_begin(),
4280 EE = BasePtr.Val->use_end(); II != EE; ++II) {
4281 SDNode *Use = II->getUser();
4285 // If all the uses are load / store addresses, then don't do the
4287 if (Use->getOpcode() == ISD::ADD || Use->getOpcode() == ISD::SUB){
4288 bool RealUse = false;
4289 for (SDNode::use_iterator III = Use->use_begin(),
4290 EEE = Use->use_end(); III != EEE; ++III) {
4291 SDNode *UseUse = III->getUser();
4292 if (!((UseUse->getOpcode() == ISD::LOAD &&
4293 cast<LoadSDNode>(UseUse)->getBasePtr().Val == Use) ||
4294 (UseUse->getOpcode() == ISD::STORE &&
4295 cast<StoreSDNode>(UseUse)->getBasePtr().Val == Use)))
4309 if (!Op->isPredecessorOf(N) && !N->isPredecessorOf(Op)) {
4310 SDOperand Result = isLoad
4311 ? DAG.getIndexedLoad(SDOperand(N,0), BasePtr, Offset, AM)
4312 : DAG.getIndexedStore(SDOperand(N,0), BasePtr, Offset, AM);
4315 DOUT << "\nReplacing.5 "; DEBUG(N->dump(&DAG));
4316 DOUT << "\nWith: "; DEBUG(Result.Val->dump(&DAG));
4318 WorkListRemover DeadNodes(*this);
4320 DAG.ReplaceAllUsesOfValueWith(SDOperand(N, 0), Result.getValue(0),
4322 DAG.ReplaceAllUsesOfValueWith(SDOperand(N, 1), Result.getValue(2),
4325 DAG.ReplaceAllUsesOfValueWith(SDOperand(N, 0), Result.getValue(1),
4329 // Finally, since the node is now dead, remove it from the graph.
4332 // Replace the uses of Use with uses of the updated base value.
4333 DAG.ReplaceAllUsesOfValueWith(SDOperand(Op, 0),
4334 Result.getValue(isLoad ? 1 : 0),
4336 removeFromWorkList(Op);
4345 /// InferAlignment - If we can infer some alignment information from this
4346 /// pointer, return it.
4347 static unsigned InferAlignment(SDOperand Ptr, SelectionDAG &DAG) {
4348 // If this is a direct reference to a stack slot, use information about the
4349 // stack slot's alignment.
4350 int FrameIdx = 1 << 31;
4351 int64_t FrameOffset = 0;
4352 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Ptr)) {
4353 FrameIdx = FI->getIndex();
4354 } else if (Ptr.getOpcode() == ISD::ADD &&
4355 isa<ConstantSDNode>(Ptr.getOperand(1)) &&
4356 isa<FrameIndexSDNode>(Ptr.getOperand(0))) {
4357 FrameIdx = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
4358 FrameOffset = Ptr.getConstantOperandVal(1);
4361 if (FrameIdx != (1 << 31)) {
4362 // FIXME: Handle FI+CST.
4363 const MachineFrameInfo &MFI = *DAG.getMachineFunction().getFrameInfo();
4364 if (MFI.isFixedObjectIndex(FrameIdx)) {
4365 int64_t ObjectOffset = MFI.getObjectOffset(FrameIdx);
4367 // The alignment of the frame index can be determined from its offset from
4368 // the incoming frame position. If the frame object is at offset 32 and
4369 // the stack is guaranteed to be 16-byte aligned, then we know that the
4370 // object is 16-byte aligned.
4371 unsigned StackAlign = DAG.getTarget().getFrameInfo()->getStackAlignment();
4372 unsigned Align = MinAlign(ObjectOffset, StackAlign);
4374 // Finally, the frame object itself may have a known alignment. Factor
4375 // the alignment + offset into a new alignment. For example, if we know
4376 // the FI is 8 byte aligned, but the pointer is 4 off, we really have a
4377 // 4-byte alignment of the resultant pointer. Likewise align 4 + 4-byte
4378 // offset = 4-byte alignment, align 4 + 1-byte offset = align 1, etc.
4379 unsigned FIInfoAlign = MinAlign(MFI.getObjectAlignment(FrameIdx),
4381 return std::max(Align, FIInfoAlign);
4388 SDOperand DAGCombiner::visitLOAD(SDNode *N) {
4389 LoadSDNode *LD = cast<LoadSDNode>(N);
4390 SDOperand Chain = LD->getChain();
4391 SDOperand Ptr = LD->getBasePtr();
4393 // Try to infer better alignment information than the load already has.
4394 if (LD->isUnindexed()) {
4395 if (unsigned Align = InferAlignment(Ptr, DAG)) {
4396 if (Align > LD->getAlignment())
4397 return DAG.getExtLoad(LD->getExtensionType(), LD->getValueType(0),
4398 Chain, Ptr, LD->getSrcValue(),
4399 LD->getSrcValueOffset(), LD->getMemoryVT(),
4400 LD->isVolatile(), Align);
4405 // If load is not volatile and there are no uses of the loaded value (and
4406 // the updated indexed value in case of indexed loads), change uses of the
4407 // chain value into uses of the chain input (i.e. delete the dead load).
4408 if (!LD->isVolatile()) {
4409 if (N->getValueType(1) == MVT::Other) {
4411 if (N->hasNUsesOfValue(0, 0)) {
4412 // It's not safe to use the two value CombineTo variant here. e.g.
4413 // v1, chain2 = load chain1, loc
4414 // v2, chain3 = load chain2, loc
4416 // Now we replace use of chain2 with chain1. This makes the second load
4417 // isomorphic to the one we are deleting, and thus makes this load live.
4418 DOUT << "\nReplacing.6 "; DEBUG(N->dump(&DAG));
4419 DOUT << "\nWith chain: "; DEBUG(Chain.Val->dump(&DAG));
4421 WorkListRemover DeadNodes(*this);
4422 DAG.ReplaceAllUsesOfValueWith(SDOperand(N, 1), Chain, &DeadNodes);
4423 if (N->use_empty()) {
4424 removeFromWorkList(N);
4427 return SDOperand(N, 0); // Return N so it doesn't get rechecked!
4431 assert(N->getValueType(2) == MVT::Other && "Malformed indexed loads?");
4432 if (N->hasNUsesOfValue(0, 0) && N->hasNUsesOfValue(0, 1)) {
4433 SDOperand Undef = DAG.getNode(ISD::UNDEF, N->getValueType(0));
4434 DOUT << "\nReplacing.6 "; DEBUG(N->dump(&DAG));
4435 DOUT << "\nWith: "; DEBUG(Undef.Val->dump(&DAG));
4436 DOUT << " and 2 other values\n";
4437 WorkListRemover DeadNodes(*this);
4438 DAG.ReplaceAllUsesOfValueWith(SDOperand(N, 0), Undef, &DeadNodes);
4439 DAG.ReplaceAllUsesOfValueWith(SDOperand(N, 1),
4440 DAG.getNode(ISD::UNDEF, N->getValueType(1)),
4442 DAG.ReplaceAllUsesOfValueWith(SDOperand(N, 2), Chain, &DeadNodes);
4443 removeFromWorkList(N);
4445 return SDOperand(N, 0); // Return N so it doesn't get rechecked!
4450 // If this load is directly stored, replace the load value with the stored
4452 // TODO: Handle store large -> read small portion.
4453 // TODO: Handle TRUNCSTORE/LOADEXT
4454 if (LD->getExtensionType() == ISD::NON_EXTLOAD &&
4455 !LD->isVolatile()) {
4456 if (ISD::isNON_TRUNCStore(Chain.Val)) {
4457 StoreSDNode *PrevST = cast<StoreSDNode>(Chain);
4458 if (PrevST->getBasePtr() == Ptr &&
4459 PrevST->getValue().getValueType() == N->getValueType(0))
4460 return CombineTo(N, Chain.getOperand(1), Chain);
4465 // Walk up chain skipping non-aliasing memory nodes.
4466 SDOperand BetterChain = FindBetterChain(N, Chain);
4468 // If there is a better chain.
4469 if (Chain != BetterChain) {
4472 // Replace the chain to void dependency.
4473 if (LD->getExtensionType() == ISD::NON_EXTLOAD) {
4474 ReplLoad = DAG.getLoad(N->getValueType(0), BetterChain, Ptr,
4475 LD->getSrcValue(), LD->getSrcValueOffset(),
4476 LD->isVolatile(), LD->getAlignment());
4478 ReplLoad = DAG.getExtLoad(LD->getExtensionType(),
4479 LD->getValueType(0),
4480 BetterChain, Ptr, LD->getSrcValue(),
4481 LD->getSrcValueOffset(),
4484 LD->getAlignment());
4487 // Create token factor to keep old chain connected.
4488 SDOperand Token = DAG.getNode(ISD::TokenFactor, MVT::Other,
4489 Chain, ReplLoad.getValue(1));
4491 // Replace uses with load result and token factor. Don't add users
4493 return CombineTo(N, ReplLoad.getValue(0), Token, false);
4497 // Try transforming N to an indexed load.
4498 if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
4499 return SDOperand(N, 0);
4505 SDOperand DAGCombiner::visitSTORE(SDNode *N) {
4506 StoreSDNode *ST = cast<StoreSDNode>(N);
4507 SDOperand Chain = ST->getChain();
4508 SDOperand Value = ST->getValue();
4509 SDOperand Ptr = ST->getBasePtr();
4511 // Try to infer better alignment information than the store already has.
4512 if (ST->isUnindexed()) {
4513 if (unsigned Align = InferAlignment(Ptr, DAG)) {
4514 if (Align > ST->getAlignment())
4515 return DAG.getTruncStore(Chain, Value, Ptr, ST->getSrcValue(),
4516 ST->getSrcValueOffset(), ST->getMemoryVT(),
4517 ST->isVolatile(), Align);
4521 // If this is a store of a bit convert, store the input value if the
4522 // resultant store does not need a higher alignment than the original.
4523 if (Value.getOpcode() == ISD::BIT_CONVERT && !ST->isTruncatingStore() &&
4524 ST->isUnindexed()) {
4525 unsigned Align = ST->getAlignment();
4526 MVT SVT = Value.getOperand(0).getValueType();
4527 unsigned OrigAlign = TLI.getTargetMachine().getTargetData()->
4528 getABITypeAlignment(SVT.getTypeForMVT());
4529 if (Align <= OrigAlign &&
4530 ((!AfterLegalize && !ST->isVolatile()) ||
4531 TLI.isOperationLegal(ISD::STORE, SVT)))
4532 return DAG.getStore(Chain, Value.getOperand(0), Ptr, ST->getSrcValue(),
4533 ST->getSrcValueOffset(), ST->isVolatile(), Align);
4536 // Turn 'store float 1.0, Ptr' -> 'store int 0x12345678, Ptr'
4537 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Value)) {
4538 // NOTE: If the original store is volatile, this transform must not increase
4539 // the number of stores. For example, on x86-32 an f64 can be stored in one
4540 // processor operation but an i64 (which is not legal) requires two. So the
4541 // transform should not be done in this case.
4542 if (Value.getOpcode() != ISD::TargetConstantFP) {
4544 switch (CFP->getValueType(0).getSimpleVT()) {
4545 default: assert(0 && "Unknown FP type");
4546 case MVT::f80: // We don't do this for these yet.
4551 if ((!AfterLegalize && !ST->isVolatile()) ||
4552 TLI.isOperationLegal(ISD::STORE, MVT::i32)) {
4553 Tmp = DAG.getConstant((uint32_t)CFP->getValueAPF().
4554 convertToAPInt().getZExtValue(), MVT::i32);
4555 return DAG.getStore(Chain, Tmp, Ptr, ST->getSrcValue(),
4556 ST->getSrcValueOffset(), ST->isVolatile(),
4557 ST->getAlignment());
4561 if ((!AfterLegalize && !ST->isVolatile()) ||
4562 TLI.isOperationLegal(ISD::STORE, MVT::i64)) {
4563 Tmp = DAG.getConstant(CFP->getValueAPF().convertToAPInt().
4564 getZExtValue(), MVT::i64);
4565 return DAG.getStore(Chain, Tmp, Ptr, ST->getSrcValue(),
4566 ST->getSrcValueOffset(), ST->isVolatile(),
4567 ST->getAlignment());
4568 } else if (!ST->isVolatile() &&
4569 TLI.isOperationLegal(ISD::STORE, MVT::i32)) {
4570 // Many FP stores are not made apparent until after legalize, e.g. for
4571 // argument passing. Since this is so common, custom legalize the
4572 // 64-bit integer store into two 32-bit stores.
4573 uint64_t Val = CFP->getValueAPF().convertToAPInt().getZExtValue();
4574 SDOperand Lo = DAG.getConstant(Val & 0xFFFFFFFF, MVT::i32);
4575 SDOperand Hi = DAG.getConstant(Val >> 32, MVT::i32);
4576 if (TLI.isBigEndian()) std::swap(Lo, Hi);
4578 int SVOffset = ST->getSrcValueOffset();
4579 unsigned Alignment = ST->getAlignment();
4580 bool isVolatile = ST->isVolatile();
4582 SDOperand St0 = DAG.getStore(Chain, Lo, Ptr, ST->getSrcValue(),
4583 ST->getSrcValueOffset(),
4584 isVolatile, ST->getAlignment());
4585 Ptr = DAG.getNode(ISD::ADD, Ptr.getValueType(), Ptr,
4586 DAG.getConstant(4, Ptr.getValueType()));
4588 Alignment = MinAlign(Alignment, 4U);
4589 SDOperand St1 = DAG.getStore(Chain, Hi, Ptr, ST->getSrcValue(),
4590 SVOffset, isVolatile, Alignment);
4591 return DAG.getNode(ISD::TokenFactor, MVT::Other, St0, St1);
4599 // Walk up chain skipping non-aliasing memory nodes.
4600 SDOperand BetterChain = FindBetterChain(N, Chain);
4602 // If there is a better chain.
4603 if (Chain != BetterChain) {
4604 // Replace the chain to avoid dependency.
4605 SDOperand ReplStore;
4606 if (ST->isTruncatingStore()) {
4607 ReplStore = DAG.getTruncStore(BetterChain, Value, Ptr,
4608 ST->getSrcValue(),ST->getSrcValueOffset(),
4610 ST->isVolatile(), ST->getAlignment());
4612 ReplStore = DAG.getStore(BetterChain, Value, Ptr,
4613 ST->getSrcValue(), ST->getSrcValueOffset(),
4614 ST->isVolatile(), ST->getAlignment());
4617 // Create token to keep both nodes around.
4619 DAG.getNode(ISD::TokenFactor, MVT::Other, Chain, ReplStore);
4621 // Don't add users to work list.
4622 return CombineTo(N, Token, false);
4626 // Try transforming N to an indexed store.
4627 if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
4628 return SDOperand(N, 0);
4630 // FIXME: is there such a thing as a truncating indexed store?
4631 if (ST->isTruncatingStore() && ST->isUnindexed() &&
4632 Value.getValueType().isInteger()) {
4633 // See if we can simplify the input to this truncstore with knowledge that
4634 // only the low bits are being used. For example:
4635 // "truncstore (or (shl x, 8), y), i8" -> "truncstore y, i8"
4637 GetDemandedBits(Value,
4638 APInt::getLowBitsSet(Value.getValueSizeInBits(),
4639 ST->getMemoryVT().getSizeInBits()));
4640 AddToWorkList(Value.Val);
4642 return DAG.getTruncStore(Chain, Shorter, Ptr, ST->getSrcValue(),
4643 ST->getSrcValueOffset(), ST->getMemoryVT(),
4644 ST->isVolatile(), ST->getAlignment());
4646 // Otherwise, see if we can simplify the operation with
4647 // SimplifyDemandedBits, which only works if the value has a single use.
4648 if (SimplifyDemandedBits(Value,
4649 APInt::getLowBitsSet(
4650 Value.getValueSizeInBits(),
4651 ST->getMemoryVT().getSizeInBits())))
4652 return SDOperand(N, 0);
4655 // If this is a load followed by a store to the same location, then the store
4657 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Value)) {
4658 if (Ld->getBasePtr() == Ptr && ST->getMemoryVT() == Ld->getMemoryVT() &&
4659 ST->isUnindexed() && !ST->isVolatile() &&
4660 // There can't be any side effects between the load and store, such as
4662 Chain.reachesChainWithoutSideEffects(SDOperand(Ld, 1))) {
4663 // The store is dead, remove it.
4668 // If this is an FP_ROUND or TRUNC followed by a store, fold this into a
4669 // truncating store. We can do this even if this is already a truncstore.
4670 if ((Value.getOpcode() == ISD::FP_ROUND || Value.getOpcode() == ISD::TRUNCATE)
4671 && Value.Val->hasOneUse() && ST->isUnindexed() &&
4672 TLI.isTruncStoreLegal(Value.getOperand(0).getValueType(),
4673 ST->getMemoryVT())) {
4674 return DAG.getTruncStore(Chain, Value.getOperand(0), Ptr, ST->getSrcValue(),
4675 ST->getSrcValueOffset(), ST->getMemoryVT(),
4676 ST->isVolatile(), ST->getAlignment());
4682 SDOperand DAGCombiner::visitINSERT_VECTOR_ELT(SDNode *N) {
4683 SDOperand InVec = N->getOperand(0);
4684 SDOperand InVal = N->getOperand(1);
4685 SDOperand EltNo = N->getOperand(2);
4687 // If the invec is a BUILD_VECTOR and if EltNo is a constant, build a new
4688 // vector with the inserted element.
4689 if (InVec.getOpcode() == ISD::BUILD_VECTOR && isa<ConstantSDNode>(EltNo)) {
4690 unsigned Elt = cast<ConstantSDNode>(EltNo)->getValue();
4691 SmallVector<SDOperand, 8> Ops(InVec.Val->op_begin(), InVec.Val->op_end());
4692 if (Elt < Ops.size())
4694 return DAG.getNode(ISD::BUILD_VECTOR, InVec.getValueType(),
4695 &Ops[0], Ops.size());
4701 SDOperand DAGCombiner::visitEXTRACT_VECTOR_ELT(SDNode *N) {
4702 // (vextract (v4f32 load $addr), c) -> (f32 load $addr+c*size)
4703 // (vextract (v4f32 s2v (f32 load $addr)), c) -> (f32 load $addr+c*size)
4704 // (vextract (v4f32 shuffle (load $addr), <1,u,u,u>), 0) -> (f32 load $addr)
4706 // Perform only after legalization to ensure build_vector / vector_shuffle
4707 // optimizations have already been done.
4708 if (!AfterLegalize) return SDOperand();
4710 SDOperand InVec = N->getOperand(0);
4711 SDOperand EltNo = N->getOperand(1);
4713 if (isa<ConstantSDNode>(EltNo)) {
4714 unsigned Elt = cast<ConstantSDNode>(EltNo)->getValue();
4715 bool NewLoad = false;
4716 MVT VT = InVec.getValueType();
4717 MVT EVT = VT.getVectorElementType();
4719 if (InVec.getOpcode() == ISD::BIT_CONVERT) {
4720 MVT BCVT = InVec.getOperand(0).getValueType();
4721 if (!BCVT.isVector() || EVT.bitsGT(BCVT.getVectorElementType()))
4723 InVec = InVec.getOperand(0);
4724 EVT = BCVT.getVectorElementType();
4728 LoadSDNode *LN0 = NULL;
4729 if (ISD::isNormalLoad(InVec.Val))
4730 LN0 = cast<LoadSDNode>(InVec);
4731 else if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR &&
4732 InVec.getOperand(0).getValueType() == EVT &&
4733 ISD::isNormalLoad(InVec.getOperand(0).Val)) {
4734 LN0 = cast<LoadSDNode>(InVec.getOperand(0));
4735 } else if (InVec.getOpcode() == ISD::VECTOR_SHUFFLE) {
4736 // (vextract (vector_shuffle (load $addr), v2, <1, u, u, u>), 1)
4738 // (load $addr+1*size)
4739 unsigned Idx = cast<ConstantSDNode>(InVec.getOperand(2).
4740 getOperand(Elt))->getValue();
4741 unsigned NumElems = InVec.getOperand(2).getNumOperands();
4742 InVec = (Idx < NumElems) ? InVec.getOperand(0) : InVec.getOperand(1);
4743 if (InVec.getOpcode() == ISD::BIT_CONVERT)
4744 InVec = InVec.getOperand(0);
4745 if (ISD::isNormalLoad(InVec.Val)) {
4746 LN0 = cast<LoadSDNode>(InVec);
4747 Elt = (Idx < NumElems) ? Idx : Idx - NumElems;
4750 if (!LN0 || !LN0->hasOneUse() || LN0->isVolatile())
4753 unsigned Align = LN0->getAlignment();
4755 // Check the resultant load doesn't need a higher alignment than the
4757 unsigned NewAlign = TLI.getTargetMachine().getTargetData()->
4758 getABITypeAlignment(LVT.getTypeForMVT());
4759 if (NewAlign > Align || !TLI.isOperationLegal(ISD::LOAD, LVT))
4764 SDOperand NewPtr = LN0->getBasePtr();
4766 unsigned PtrOff = LVT.getSizeInBits() * Elt / 8;
4767 MVT PtrType = NewPtr.getValueType();
4768 if (TLI.isBigEndian())
4769 PtrOff = VT.getSizeInBits() / 8 - PtrOff;
4770 NewPtr = DAG.getNode(ISD::ADD, PtrType, NewPtr,
4771 DAG.getConstant(PtrOff, PtrType));
4773 return DAG.getLoad(LVT, LN0->getChain(), NewPtr,
4774 LN0->getSrcValue(), LN0->getSrcValueOffset(),
4775 LN0->isVolatile(), Align);
4781 SDOperand DAGCombiner::visitBUILD_VECTOR(SDNode *N) {
4782 unsigned NumInScalars = N->getNumOperands();
4783 MVT VT = N->getValueType(0);
4784 unsigned NumElts = VT.getVectorNumElements();
4785 MVT EltType = VT.getVectorElementType();
4787 // Check to see if this is a BUILD_VECTOR of a bunch of EXTRACT_VECTOR_ELT
4788 // operations. If so, and if the EXTRACT_VECTOR_ELT vector inputs come from
4789 // at most two distinct vectors, turn this into a shuffle node.
4790 SDOperand VecIn1, VecIn2;
4791 for (unsigned i = 0; i != NumInScalars; ++i) {
4792 // Ignore undef inputs.
4793 if (N->getOperand(i).getOpcode() == ISD::UNDEF) continue;
4795 // If this input is something other than a EXTRACT_VECTOR_ELT with a
4796 // constant index, bail out.
4797 if (N->getOperand(i).getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
4798 !isa<ConstantSDNode>(N->getOperand(i).getOperand(1))) {
4799 VecIn1 = VecIn2 = SDOperand(0, 0);
4803 // If the input vector type disagrees with the result of the build_vector,
4804 // we can't make a shuffle.
4805 SDOperand ExtractedFromVec = N->getOperand(i).getOperand(0);
4806 if (ExtractedFromVec.getValueType() != VT) {
4807 VecIn1 = VecIn2 = SDOperand(0, 0);
4811 // Otherwise, remember this. We allow up to two distinct input vectors.
4812 if (ExtractedFromVec == VecIn1 || ExtractedFromVec == VecIn2)
4815 if (VecIn1.Val == 0) {
4816 VecIn1 = ExtractedFromVec;
4817 } else if (VecIn2.Val == 0) {
4818 VecIn2 = ExtractedFromVec;
4821 VecIn1 = VecIn2 = SDOperand(0, 0);
4826 // If everything is good, we can make a shuffle operation.
4828 SmallVector<SDOperand, 8> BuildVecIndices;
4829 for (unsigned i = 0; i != NumInScalars; ++i) {
4830 if (N->getOperand(i).getOpcode() == ISD::UNDEF) {
4831 BuildVecIndices.push_back(DAG.getNode(ISD::UNDEF, TLI.getPointerTy()));
4835 SDOperand Extract = N->getOperand(i);
4837 // If extracting from the first vector, just use the index directly.
4838 if (Extract.getOperand(0) == VecIn1) {
4839 BuildVecIndices.push_back(Extract.getOperand(1));
4843 // Otherwise, use InIdx + VecSize
4844 unsigned Idx = cast<ConstantSDNode>(Extract.getOperand(1))->getValue();
4845 BuildVecIndices.push_back(DAG.getIntPtrConstant(Idx+NumInScalars));
4848 // Add count and size info.
4849 MVT BuildVecVT = MVT::getVectorVT(TLI.getPointerTy(), NumElts);
4851 // Return the new VECTOR_SHUFFLE node.
4857 // Use an undef build_vector as input for the second operand.
4858 std::vector<SDOperand> UnOps(NumInScalars,
4859 DAG.getNode(ISD::UNDEF,
4861 Ops[1] = DAG.getNode(ISD::BUILD_VECTOR, VT,
4862 &UnOps[0], UnOps.size());
4863 AddToWorkList(Ops[1].Val);
4865 Ops[2] = DAG.getNode(ISD::BUILD_VECTOR, BuildVecVT,
4866 &BuildVecIndices[0], BuildVecIndices.size());
4867 return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, Ops, 3);
4873 SDOperand DAGCombiner::visitCONCAT_VECTORS(SDNode *N) {
4874 // TODO: Check to see if this is a CONCAT_VECTORS of a bunch of
4875 // EXTRACT_SUBVECTOR operations. If so, and if the EXTRACT_SUBVECTOR vector
4876 // inputs come from at most two distinct vectors, turn this into a shuffle
4879 // If we only have one input vector, we don't need to do any concatenation.
4880 if (N->getNumOperands() == 1) {
4881 return N->getOperand(0);
4887 SDOperand DAGCombiner::visitVECTOR_SHUFFLE(SDNode *N) {
4888 SDOperand ShufMask = N->getOperand(2);
4889 unsigned NumElts = ShufMask.getNumOperands();
4891 // If the shuffle mask is an identity operation on the LHS, return the LHS.
4892 bool isIdentity = true;
4893 for (unsigned i = 0; i != NumElts; ++i) {
4894 if (ShufMask.getOperand(i).getOpcode() != ISD::UNDEF &&
4895 cast<ConstantSDNode>(ShufMask.getOperand(i))->getValue() != i) {
4900 if (isIdentity) return N->getOperand(0);
4902 // If the shuffle mask is an identity operation on the RHS, return the RHS.
4904 for (unsigned i = 0; i != NumElts; ++i) {
4905 if (ShufMask.getOperand(i).getOpcode() != ISD::UNDEF &&
4906 cast<ConstantSDNode>(ShufMask.getOperand(i))->getValue() != i+NumElts) {
4911 if (isIdentity) return N->getOperand(1);
4913 // Check if the shuffle is a unary shuffle, i.e. one of the vectors is not
4915 bool isUnary = true;
4916 bool isSplat = true;
4918 unsigned BaseIdx = 0;
4919 for (unsigned i = 0; i != NumElts; ++i)
4920 if (ShufMask.getOperand(i).getOpcode() != ISD::UNDEF) {
4921 unsigned Idx = cast<ConstantSDNode>(ShufMask.getOperand(i))->getValue();
4922 int V = (Idx < NumElts) ? 0 : 1;
4936 SDOperand N0 = N->getOperand(0);
4937 SDOperand N1 = N->getOperand(1);
4938 // Normalize unary shuffle so the RHS is undef.
4939 if (isUnary && VecNum == 1)
4942 // If it is a splat, check if the argument vector is a build_vector with
4943 // all scalar elements the same.
4947 // If this is a bit convert that changes the element type of the vector but
4948 // not the number of vector elements, look through it. Be careful not to
4949 // look though conversions that change things like v4f32 to v2f64.
4950 if (V->getOpcode() == ISD::BIT_CONVERT) {
4951 SDOperand ConvInput = V->getOperand(0);
4952 if (ConvInput.getValueType().getVectorNumElements() == NumElts)
4956 if (V->getOpcode() == ISD::BUILD_VECTOR) {
4957 unsigned NumElems = V->getNumOperands();
4958 if (NumElems > BaseIdx) {
4960 bool AllSame = true;
4961 for (unsigned i = 0; i != NumElems; ++i) {
4962 if (V->getOperand(i).getOpcode() != ISD::UNDEF) {
4963 Base = V->getOperand(i);
4967 // Splat of <u, u, u, u>, return <u, u, u, u>
4970 for (unsigned i = 0; i != NumElems; ++i) {
4971 if (V->getOperand(i) != Base) {
4976 // Splat of <x, x, x, x>, return <x, x, x, x>
4983 // If it is a unary or the LHS and the RHS are the same node, turn the RHS
4985 if (isUnary || N0 == N1) {
4986 // Check the SHUFFLE mask, mapping any inputs from the 2nd operand into the
4988 SmallVector<SDOperand, 8> MappedOps;
4989 for (unsigned i = 0; i != NumElts; ++i) {
4990 if (ShufMask.getOperand(i).getOpcode() == ISD::UNDEF ||
4991 cast<ConstantSDNode>(ShufMask.getOperand(i))->getValue() < NumElts) {
4992 MappedOps.push_back(ShufMask.getOperand(i));
4995 cast<ConstantSDNode>(ShufMask.getOperand(i))->getValue() - NumElts;
4996 MappedOps.push_back(DAG.getConstant(NewIdx, MVT::i32));
4999 ShufMask = DAG.getNode(ISD::BUILD_VECTOR, ShufMask.getValueType(),
5000 &MappedOps[0], MappedOps.size());
5001 AddToWorkList(ShufMask.Val);
5002 return DAG.getNode(ISD::VECTOR_SHUFFLE, N->getValueType(0),
5004 DAG.getNode(ISD::UNDEF, N->getValueType(0)),
5011 /// XformToShuffleWithZero - Returns a vector_shuffle if it able to transform
5012 /// an AND to a vector_shuffle with the destination vector and a zero vector.
5013 /// e.g. AND V, <0xffffffff, 0, 0xffffffff, 0>. ==>
5014 /// vector_shuffle V, Zero, <0, 4, 2, 4>
5015 SDOperand DAGCombiner::XformToShuffleWithZero(SDNode *N) {
5016 SDOperand LHS = N->getOperand(0);
5017 SDOperand RHS = N->getOperand(1);
5018 if (N->getOpcode() == ISD::AND) {
5019 if (RHS.getOpcode() == ISD::BIT_CONVERT)
5020 RHS = RHS.getOperand(0);
5021 if (RHS.getOpcode() == ISD::BUILD_VECTOR) {
5022 std::vector<SDOperand> IdxOps;
5023 unsigned NumOps = RHS.getNumOperands();
5024 unsigned NumElts = NumOps;
5025 MVT EVT = RHS.getValueType().getVectorElementType();
5026 for (unsigned i = 0; i != NumElts; ++i) {
5027 SDOperand Elt = RHS.getOperand(i);
5028 if (!isa<ConstantSDNode>(Elt))
5030 else if (cast<ConstantSDNode>(Elt)->isAllOnesValue())
5031 IdxOps.push_back(DAG.getConstant(i, EVT));
5032 else if (cast<ConstantSDNode>(Elt)->isNullValue())
5033 IdxOps.push_back(DAG.getConstant(NumElts, EVT));
5038 // Let's see if the target supports this vector_shuffle.
5039 if (!TLI.isVectorClearMaskLegal(IdxOps, EVT, DAG))
5042 // Return the new VECTOR_SHUFFLE node.
5043 MVT VT = MVT::getVectorVT(EVT, NumElts);
5044 std::vector<SDOperand> Ops;
5045 LHS = DAG.getNode(ISD::BIT_CONVERT, VT, LHS);
5047 AddToWorkList(LHS.Val);
5048 std::vector<SDOperand> ZeroOps(NumElts, DAG.getConstant(0, EVT));
5049 Ops.push_back(DAG.getNode(ISD::BUILD_VECTOR, VT,
5050 &ZeroOps[0], ZeroOps.size()));
5051 Ops.push_back(DAG.getNode(ISD::BUILD_VECTOR, VT,
5052 &IdxOps[0], IdxOps.size()));
5053 SDOperand Result = DAG.getNode(ISD::VECTOR_SHUFFLE, VT,
5054 &Ops[0], Ops.size());
5055 if (VT != LHS.getValueType()) {
5056 Result = DAG.getNode(ISD::BIT_CONVERT, LHS.getValueType(), Result);
5064 /// SimplifyVBinOp - Visit a binary vector operation, like ADD.
5065 SDOperand DAGCombiner::SimplifyVBinOp(SDNode *N) {
5066 // After legalize, the target may be depending on adds and other
5067 // binary ops to provide legal ways to construct constants or other
5068 // things. Simplifying them may result in a loss of legality.
5069 if (AfterLegalize) return SDOperand();
5071 MVT VT = N->getValueType(0);
5072 assert(VT.isVector() && "SimplifyVBinOp only works on vectors!");
5074 MVT EltType = VT.getVectorElementType();
5075 SDOperand LHS = N->getOperand(0);
5076 SDOperand RHS = N->getOperand(1);
5077 SDOperand Shuffle = XformToShuffleWithZero(N);
5078 if (Shuffle.Val) return Shuffle;
5080 // If the LHS and RHS are BUILD_VECTOR nodes, see if we can constant fold
5082 if (LHS.getOpcode() == ISD::BUILD_VECTOR &&
5083 RHS.getOpcode() == ISD::BUILD_VECTOR) {
5084 SmallVector<SDOperand, 8> Ops;
5085 for (unsigned i = 0, e = LHS.getNumOperands(); i != e; ++i) {
5086 SDOperand LHSOp = LHS.getOperand(i);
5087 SDOperand RHSOp = RHS.getOperand(i);
5088 // If these two elements can't be folded, bail out.
5089 if ((LHSOp.getOpcode() != ISD::UNDEF &&
5090 LHSOp.getOpcode() != ISD::Constant &&
5091 LHSOp.getOpcode() != ISD::ConstantFP) ||
5092 (RHSOp.getOpcode() != ISD::UNDEF &&
5093 RHSOp.getOpcode() != ISD::Constant &&
5094 RHSOp.getOpcode() != ISD::ConstantFP))
5096 // Can't fold divide by zero.
5097 if (N->getOpcode() == ISD::SDIV || N->getOpcode() == ISD::UDIV ||
5098 N->getOpcode() == ISD::FDIV) {
5099 if ((RHSOp.getOpcode() == ISD::Constant &&
5100 cast<ConstantSDNode>(RHSOp.Val)->isNullValue()) ||
5101 (RHSOp.getOpcode() == ISD::ConstantFP &&
5102 cast<ConstantFPSDNode>(RHSOp.Val)->getValueAPF().isZero()))
5105 Ops.push_back(DAG.getNode(N->getOpcode(), EltType, LHSOp, RHSOp));
5106 AddToWorkList(Ops.back().Val);
5107 assert((Ops.back().getOpcode() == ISD::UNDEF ||
5108 Ops.back().getOpcode() == ISD::Constant ||
5109 Ops.back().getOpcode() == ISD::ConstantFP) &&
5110 "Scalar binop didn't fold!");
5113 if (Ops.size() == LHS.getNumOperands()) {
5114 MVT VT = LHS.getValueType();
5115 return DAG.getNode(ISD::BUILD_VECTOR, VT, &Ops[0], Ops.size());
5122 SDOperand DAGCombiner::SimplifySelect(SDOperand N0, SDOperand N1, SDOperand N2){
5123 assert(N0.getOpcode() ==ISD::SETCC && "First argument must be a SetCC node!");
5125 SDOperand SCC = SimplifySelectCC(N0.getOperand(0), N0.getOperand(1), N1, N2,
5126 cast<CondCodeSDNode>(N0.getOperand(2))->get());
5127 // If we got a simplified select_cc node back from SimplifySelectCC, then
5128 // break it down into a new SETCC node, and a new SELECT node, and then return
5129 // the SELECT node, since we were called with a SELECT node.
5131 // Check to see if we got a select_cc back (to turn into setcc/select).
5132 // Otherwise, just return whatever node we got back, like fabs.
5133 if (SCC.getOpcode() == ISD::SELECT_CC) {
5134 SDOperand SETCC = DAG.getNode(ISD::SETCC, N0.getValueType(),
5135 SCC.getOperand(0), SCC.getOperand(1),
5137 AddToWorkList(SETCC.Val);
5138 return DAG.getNode(ISD::SELECT, SCC.getValueType(), SCC.getOperand(2),
5139 SCC.getOperand(3), SETCC);
5146 /// SimplifySelectOps - Given a SELECT or a SELECT_CC node, where LHS and RHS
5147 /// are the two values being selected between, see if we can simplify the
5148 /// select. Callers of this should assume that TheSelect is deleted if this
5149 /// returns true. As such, they should return the appropriate thing (e.g. the
5150 /// node) back to the top-level of the DAG combiner loop to avoid it being
5153 bool DAGCombiner::SimplifySelectOps(SDNode *TheSelect, SDOperand LHS,
5156 // If this is a select from two identical things, try to pull the operation
5157 // through the select.
5158 if (LHS.getOpcode() == RHS.getOpcode() && LHS.hasOneUse() && RHS.hasOneUse()){
5159 // If this is a load and the token chain is identical, replace the select
5160 // of two loads with a load through a select of the address to load from.
5161 // This triggers in things like "select bool X, 10.0, 123.0" after the FP
5162 // constants have been dropped into the constant pool.
5163 if (LHS.getOpcode() == ISD::LOAD &&
5164 // Do not let this transformation reduce the number of volatile loads.
5165 !cast<LoadSDNode>(LHS)->isVolatile() &&
5166 !cast<LoadSDNode>(RHS)->isVolatile() &&
5167 // Token chains must be identical.
5168 LHS.getOperand(0) == RHS.getOperand(0)) {
5169 LoadSDNode *LLD = cast<LoadSDNode>(LHS);
5170 LoadSDNode *RLD = cast<LoadSDNode>(RHS);
5172 // If this is an EXTLOAD, the VT's must match.
5173 if (LLD->getMemoryVT() == RLD->getMemoryVT()) {
5174 // FIXME: this conflates two src values, discarding one. This is not
5175 // the right thing to do, but nothing uses srcvalues now. When they do,
5176 // turn SrcValue into a list of locations.
5178 if (TheSelect->getOpcode() == ISD::SELECT) {
5179 // Check that the condition doesn't reach either load. If so, folding
5180 // this will induce a cycle into the DAG.
5181 if (!LLD->isPredecessorOf(TheSelect->getOperand(0).Val) &&
5182 !RLD->isPredecessorOf(TheSelect->getOperand(0).Val)) {
5183 Addr = DAG.getNode(ISD::SELECT, LLD->getBasePtr().getValueType(),
5184 TheSelect->getOperand(0), LLD->getBasePtr(),
5188 // Check that the condition doesn't reach either load. If so, folding
5189 // this will induce a cycle into the DAG.
5190 if (!LLD->isPredecessorOf(TheSelect->getOperand(0).Val) &&
5191 !RLD->isPredecessorOf(TheSelect->getOperand(0).Val) &&
5192 !LLD->isPredecessorOf(TheSelect->getOperand(1).Val) &&
5193 !RLD->isPredecessorOf(TheSelect->getOperand(1).Val)) {
5194 Addr = DAG.getNode(ISD::SELECT_CC, LLD->getBasePtr().getValueType(),
5195 TheSelect->getOperand(0),
5196 TheSelect->getOperand(1),
5197 LLD->getBasePtr(), RLD->getBasePtr(),
5198 TheSelect->getOperand(4));
5204 if (LLD->getExtensionType() == ISD::NON_EXTLOAD)
5205 Load = DAG.getLoad(TheSelect->getValueType(0), LLD->getChain(),
5206 Addr,LLD->getSrcValue(),
5207 LLD->getSrcValueOffset(),
5209 LLD->getAlignment());
5211 Load = DAG.getExtLoad(LLD->getExtensionType(),
5212 TheSelect->getValueType(0),
5213 LLD->getChain(), Addr, LLD->getSrcValue(),
5214 LLD->getSrcValueOffset(),
5217 LLD->getAlignment());
5219 // Users of the select now use the result of the load.
5220 CombineTo(TheSelect, Load);
5222 // Users of the old loads now use the new load's chain. We know the
5223 // old-load value is dead now.
5224 CombineTo(LHS.Val, Load.getValue(0), Load.getValue(1));
5225 CombineTo(RHS.Val, Load.getValue(0), Load.getValue(1));
5235 SDOperand DAGCombiner::SimplifySelectCC(SDOperand N0, SDOperand N1,
5236 SDOperand N2, SDOperand N3,
5237 ISD::CondCode CC, bool NotExtCompare) {
5239 MVT VT = N2.getValueType();
5240 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.Val);
5241 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2.Val);
5242 ConstantSDNode *N3C = dyn_cast<ConstantSDNode>(N3.Val);
5244 // Determine if the condition we're dealing with is constant
5245 SDOperand SCC = SimplifySetCC(TLI.getSetCCResultType(N0), N0, N1, CC, false);
5246 if (SCC.Val) AddToWorkList(SCC.Val);
5247 ConstantSDNode *SCCC = dyn_cast_or_null<ConstantSDNode>(SCC.Val);
5249 // fold select_cc true, x, y -> x
5250 if (SCCC && !SCCC->isNullValue())
5252 // fold select_cc false, x, y -> y
5253 if (SCCC && SCCC->isNullValue())
5256 // Check to see if we can simplify the select into an fabs node
5257 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N1)) {
5258 // Allow either -0.0 or 0.0
5259 if (CFP->getValueAPF().isZero()) {
5260 // select (setg[te] X, +/-0.0), X, fneg(X) -> fabs
5261 if ((CC == ISD::SETGE || CC == ISD::SETGT) &&
5262 N0 == N2 && N3.getOpcode() == ISD::FNEG &&
5263 N2 == N3.getOperand(0))
5264 return DAG.getNode(ISD::FABS, VT, N0);
5266 // select (setl[te] X, +/-0.0), fneg(X), X -> fabs
5267 if ((CC == ISD::SETLT || CC == ISD::SETLE) &&
5268 N0 == N3 && N2.getOpcode() == ISD::FNEG &&
5269 N2.getOperand(0) == N3)
5270 return DAG.getNode(ISD::FABS, VT, N3);
5274 // Check to see if we can perform the "gzip trick", transforming
5275 // select_cc setlt X, 0, A, 0 -> and (sra X, size(X)-1), A
5276 if (N1C && N3C && N3C->isNullValue() && CC == ISD::SETLT &&
5277 N0.getValueType().isInteger() &&
5278 N2.getValueType().isInteger() &&
5279 (N1C->isNullValue() || // (a < 0) ? b : 0
5280 (N1C->getAPIntValue() == 1 && N0 == N2))) { // (a < 1) ? a : 0
5281 MVT XType = N0.getValueType();
5282 MVT AType = N2.getValueType();
5283 if (XType.bitsGE(AType)) {
5284 // and (sra X, size(X)-1, A) -> "and (srl X, C2), A" iff A is a
5285 // single-bit constant.
5286 if (N2C && ((N2C->getAPIntValue() & (N2C->getAPIntValue()-1)) == 0)) {
5287 unsigned ShCtV = N2C->getAPIntValue().logBase2();
5288 ShCtV = XType.getSizeInBits()-ShCtV-1;
5289 SDOperand ShCt = DAG.getConstant(ShCtV, TLI.getShiftAmountTy());
5290 SDOperand Shift = DAG.getNode(ISD::SRL, XType, N0, ShCt);
5291 AddToWorkList(Shift.Val);
5292 if (XType.bitsGT(AType)) {
5293 Shift = DAG.getNode(ISD::TRUNCATE, AType, Shift);
5294 AddToWorkList(Shift.Val);
5296 return DAG.getNode(ISD::AND, AType, Shift, N2);
5298 SDOperand Shift = DAG.getNode(ISD::SRA, XType, N0,
5299 DAG.getConstant(XType.getSizeInBits()-1,
5300 TLI.getShiftAmountTy()));
5301 AddToWorkList(Shift.Val);
5302 if (XType.bitsGT(AType)) {
5303 Shift = DAG.getNode(ISD::TRUNCATE, AType, Shift);
5304 AddToWorkList(Shift.Val);
5306 return DAG.getNode(ISD::AND, AType, Shift, N2);
5310 // fold select C, 16, 0 -> shl C, 4
5311 if (N2C && N3C && N3C->isNullValue() && N2C->getAPIntValue().isPowerOf2() &&
5312 TLI.getSetCCResultContents() == TargetLowering::ZeroOrOneSetCCResult) {
5314 // If the caller doesn't want us to simplify this into a zext of a compare,
5316 if (NotExtCompare && N2C->getAPIntValue() == 1)
5319 // Get a SetCC of the condition
5320 // FIXME: Should probably make sure that setcc is legal if we ever have a
5321 // target where it isn't.
5322 SDOperand Temp, SCC;
5323 // cast from setcc result type to select result type
5324 if (AfterLegalize) {
5325 SCC = DAG.getSetCC(TLI.getSetCCResultType(N0), N0, N1, CC);
5326 if (N2.getValueType().bitsLT(SCC.getValueType()))
5327 Temp = DAG.getZeroExtendInReg(SCC, N2.getValueType());
5329 Temp = DAG.getNode(ISD::ZERO_EXTEND, N2.getValueType(), SCC);
5331 SCC = DAG.getSetCC(MVT::i1, N0, N1, CC);
5332 Temp = DAG.getNode(ISD::ZERO_EXTEND, N2.getValueType(), SCC);
5334 AddToWorkList(SCC.Val);
5335 AddToWorkList(Temp.Val);
5337 if (N2C->getAPIntValue() == 1)
5339 // shl setcc result by log2 n2c
5340 return DAG.getNode(ISD::SHL, N2.getValueType(), Temp,
5341 DAG.getConstant(N2C->getAPIntValue().logBase2(),
5342 TLI.getShiftAmountTy()));
5345 // Check to see if this is the equivalent of setcc
5346 // FIXME: Turn all of these into setcc if setcc if setcc is legal
5347 // otherwise, go ahead with the folds.
5348 if (0 && N3C && N3C->isNullValue() && N2C && (N2C->getAPIntValue() == 1ULL)) {
5349 MVT XType = N0.getValueType();
5350 if (!AfterLegalize ||
5351 TLI.isOperationLegal(ISD::SETCC, TLI.getSetCCResultType(N0))) {
5352 SDOperand Res = DAG.getSetCC(TLI.getSetCCResultType(N0), N0, N1, CC);
5353 if (Res.getValueType() != VT)
5354 Res = DAG.getNode(ISD::ZERO_EXTEND, VT, Res);
5358 // seteq X, 0 -> srl (ctlz X, log2(size(X)))
5359 if (N1C && N1C->isNullValue() && CC == ISD::SETEQ &&
5361 TLI.isOperationLegal(ISD::CTLZ, XType))) {
5362 SDOperand Ctlz = DAG.getNode(ISD::CTLZ, XType, N0);
5363 return DAG.getNode(ISD::SRL, XType, Ctlz,
5364 DAG.getConstant(Log2_32(XType.getSizeInBits()),
5365 TLI.getShiftAmountTy()));
5367 // setgt X, 0 -> srl (and (-X, ~X), size(X)-1)
5368 if (N1C && N1C->isNullValue() && CC == ISD::SETGT) {
5369 SDOperand NegN0 = DAG.getNode(ISD::SUB, XType, DAG.getConstant(0, XType),
5371 SDOperand NotN0 = DAG.getNode(ISD::XOR, XType, N0,
5372 DAG.getConstant(~0ULL, XType));
5373 return DAG.getNode(ISD::SRL, XType,
5374 DAG.getNode(ISD::AND, XType, NegN0, NotN0),
5375 DAG.getConstant(XType.getSizeInBits()-1,
5376 TLI.getShiftAmountTy()));
5378 // setgt X, -1 -> xor (srl (X, size(X)-1), 1)
5379 if (N1C && N1C->isAllOnesValue() && CC == ISD::SETGT) {
5380 SDOperand Sign = DAG.getNode(ISD::SRL, XType, N0,
5381 DAG.getConstant(XType.getSizeInBits()-1,
5382 TLI.getShiftAmountTy()));
5383 return DAG.getNode(ISD::XOR, XType, Sign, DAG.getConstant(1, XType));
5387 // Check to see if this is an integer abs. select_cc setl[te] X, 0, -X, X ->
5388 // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
5389 if (N1C && N1C->isNullValue() && (CC == ISD::SETLT || CC == ISD::SETLE) &&
5390 N0 == N3 && N2.getOpcode() == ISD::SUB && N0 == N2.getOperand(1) &&
5391 N2.getOperand(0) == N1 && N0.getValueType().isInteger()) {
5392 MVT XType = N0.getValueType();
5393 SDOperand Shift = DAG.getNode(ISD::SRA, XType, N0,
5394 DAG.getConstant(XType.getSizeInBits()-1,
5395 TLI.getShiftAmountTy()));
5396 SDOperand Add = DAG.getNode(ISD::ADD, XType, N0, Shift);
5397 AddToWorkList(Shift.Val);
5398 AddToWorkList(Add.Val);
5399 return DAG.getNode(ISD::XOR, XType, Add, Shift);
5401 // Check to see if this is an integer abs. select_cc setgt X, -1, X, -X ->
5402 // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
5403 if (N1C && N1C->isAllOnesValue() && CC == ISD::SETGT &&
5404 N0 == N2 && N3.getOpcode() == ISD::SUB && N0 == N3.getOperand(1)) {
5405 if (ConstantSDNode *SubC = dyn_cast<ConstantSDNode>(N3.getOperand(0))) {
5406 MVT XType = N0.getValueType();
5407 if (SubC->isNullValue() && XType.isInteger()) {
5408 SDOperand Shift = DAG.getNode(ISD::SRA, XType, N0,
5409 DAG.getConstant(XType.getSizeInBits()-1,
5410 TLI.getShiftAmountTy()));
5411 SDOperand Add = DAG.getNode(ISD::ADD, XType, N0, Shift);
5412 AddToWorkList(Shift.Val);
5413 AddToWorkList(Add.Val);
5414 return DAG.getNode(ISD::XOR, XType, Add, Shift);
5422 /// SimplifySetCC - This is a stub for TargetLowering::SimplifySetCC.
5423 SDOperand DAGCombiner::SimplifySetCC(MVT VT, SDOperand N0,
5424 SDOperand N1, ISD::CondCode Cond,
5425 bool foldBooleans) {
5426 TargetLowering::DAGCombinerInfo
5427 DagCombineInfo(DAG, !AfterLegalize, false, this);
5428 return TLI.SimplifySetCC(VT, N0, N1, Cond, foldBooleans, DagCombineInfo);
5431 /// BuildSDIVSequence - Given an ISD::SDIV node expressing a divide by constant,
5432 /// return a DAG expression to select that will generate the same value by
5433 /// multiplying by a magic number. See:
5434 /// <http://the.wall.riscom.net/books/proc/ppc/cwg/code2.html>
5435 SDOperand DAGCombiner::BuildSDIV(SDNode *N) {
5436 std::vector<SDNode*> Built;
5437 SDOperand S = TLI.BuildSDIV(N, DAG, &Built);
5439 for (std::vector<SDNode*>::iterator ii = Built.begin(), ee = Built.end();
5445 /// BuildUDIVSequence - Given an ISD::UDIV node expressing a divide by constant,
5446 /// return a DAG expression to select that will generate the same value by
5447 /// multiplying by a magic number. See:
5448 /// <http://the.wall.riscom.net/books/proc/ppc/cwg/code2.html>
5449 SDOperand DAGCombiner::BuildUDIV(SDNode *N) {
5450 std::vector<SDNode*> Built;
5451 SDOperand S = TLI.BuildUDIV(N, DAG, &Built);
5453 for (std::vector<SDNode*>::iterator ii = Built.begin(), ee = Built.end();
5459 /// FindBaseOffset - Return true if base is known not to alias with anything
5460 /// but itself. Provides base object and offset as results.
5461 static bool FindBaseOffset(SDOperand Ptr, SDOperand &Base, int64_t &Offset) {
5462 // Assume it is a primitive operation.
5463 Base = Ptr; Offset = 0;
5465 // If it's an adding a simple constant then integrate the offset.
5466 if (Base.getOpcode() == ISD::ADD) {
5467 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Base.getOperand(1))) {
5468 Base = Base.getOperand(0);
5469 Offset += C->getValue();
5473 // If it's any of the following then it can't alias with anything but itself.
5474 return isa<FrameIndexSDNode>(Base) ||
5475 isa<ConstantPoolSDNode>(Base) ||
5476 isa<GlobalAddressSDNode>(Base);
5479 /// isAlias - Return true if there is any possibility that the two addresses
5481 bool DAGCombiner::isAlias(SDOperand Ptr1, int64_t Size1,
5482 const Value *SrcValue1, int SrcValueOffset1,
5483 SDOperand Ptr2, int64_t Size2,
5484 const Value *SrcValue2, int SrcValueOffset2)
5486 // If they are the same then they must be aliases.
5487 if (Ptr1 == Ptr2) return true;
5489 // Gather base node and offset information.
5490 SDOperand Base1, Base2;
5491 int64_t Offset1, Offset2;
5492 bool KnownBase1 = FindBaseOffset(Ptr1, Base1, Offset1);
5493 bool KnownBase2 = FindBaseOffset(Ptr2, Base2, Offset2);
5495 // If they have a same base address then...
5496 if (Base1 == Base2) {
5497 // Check to see if the addresses overlap.
5498 return!((Offset1 + Size1) <= Offset2 || (Offset2 + Size2) <= Offset1);
5501 // If we know both bases then they can't alias.
5502 if (KnownBase1 && KnownBase2) return false;
5504 if (CombinerGlobalAA) {
5505 // Use alias analysis information.
5506 int64_t MinOffset = std::min(SrcValueOffset1, SrcValueOffset2);
5507 int64_t Overlap1 = Size1 + SrcValueOffset1 - MinOffset;
5508 int64_t Overlap2 = Size2 + SrcValueOffset2 - MinOffset;
5509 AliasAnalysis::AliasResult AAResult =
5510 AA.alias(SrcValue1, Overlap1, SrcValue2, Overlap2);
5511 if (AAResult == AliasAnalysis::NoAlias)
5515 // Otherwise we have to assume they alias.
5519 /// FindAliasInfo - Extracts the relevant alias information from the memory
5520 /// node. Returns true if the operand was a load.
5521 bool DAGCombiner::FindAliasInfo(SDNode *N,
5522 SDOperand &Ptr, int64_t &Size,
5523 const Value *&SrcValue, int &SrcValueOffset) {
5524 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
5525 Ptr = LD->getBasePtr();
5526 Size = LD->getMemoryVT().getSizeInBits() >> 3;
5527 SrcValue = LD->getSrcValue();
5528 SrcValueOffset = LD->getSrcValueOffset();
5530 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
5531 Ptr = ST->getBasePtr();
5532 Size = ST->getMemoryVT().getSizeInBits() >> 3;
5533 SrcValue = ST->getSrcValue();
5534 SrcValueOffset = ST->getSrcValueOffset();
5536 assert(0 && "FindAliasInfo expected a memory operand");
5542 /// GatherAllAliases - Walk up chain skipping non-aliasing memory nodes,
5543 /// looking for aliasing nodes and adding them to the Aliases vector.
5544 void DAGCombiner::GatherAllAliases(SDNode *N, SDOperand OriginalChain,
5545 SmallVector<SDOperand, 8> &Aliases) {
5546 SmallVector<SDOperand, 8> Chains; // List of chains to visit.
5547 std::set<SDNode *> Visited; // Visited node set.
5549 // Get alias information for node.
5552 const Value *SrcValue;
5554 bool IsLoad = FindAliasInfo(N, Ptr, Size, SrcValue, SrcValueOffset);
5557 Chains.push_back(OriginalChain);
5559 // Look at each chain and determine if it is an alias. If so, add it to the
5560 // aliases list. If not, then continue up the chain looking for the next
5562 while (!Chains.empty()) {
5563 SDOperand Chain = Chains.back();
5566 // Don't bother if we've been before.
5567 if (Visited.find(Chain.Val) != Visited.end()) continue;
5568 Visited.insert(Chain.Val);
5570 switch (Chain.getOpcode()) {
5571 case ISD::EntryToken:
5572 // Entry token is ideal chain operand, but handled in FindBetterChain.
5577 // Get alias information for Chain.
5580 const Value *OpSrcValue;
5581 int OpSrcValueOffset;
5582 bool IsOpLoad = FindAliasInfo(Chain.Val, OpPtr, OpSize,
5583 OpSrcValue, OpSrcValueOffset);
5585 // If chain is alias then stop here.
5586 if (!(IsLoad && IsOpLoad) &&
5587 isAlias(Ptr, Size, SrcValue, SrcValueOffset,
5588 OpPtr, OpSize, OpSrcValue, OpSrcValueOffset)) {
5589 Aliases.push_back(Chain);
5591 // Look further up the chain.
5592 Chains.push_back(Chain.getOperand(0));
5593 // Clean up old chain.
5594 AddToWorkList(Chain.Val);
5599 case ISD::TokenFactor:
5600 // We have to check each of the operands of the token factor, so we queue
5601 // then up. Adding the operands to the queue (stack) in reverse order
5602 // maintains the original order and increases the likelihood that getNode
5603 // will find a matching token factor (CSE.)
5604 for (unsigned n = Chain.getNumOperands(); n;)
5605 Chains.push_back(Chain.getOperand(--n));
5606 // Eliminate the token factor if we can.
5607 AddToWorkList(Chain.Val);
5611 // For all other instructions we will just have to take what we can get.
5612 Aliases.push_back(Chain);
5618 /// FindBetterChain - Walk up chain skipping non-aliasing memory nodes, looking
5619 /// for a better chain (aliasing node.)
5620 SDOperand DAGCombiner::FindBetterChain(SDNode *N, SDOperand OldChain) {
5621 SmallVector<SDOperand, 8> Aliases; // Ops for replacing token factor.
5623 // Accumulate all the aliases to this node.
5624 GatherAllAliases(N, OldChain, Aliases);
5626 if (Aliases.size() == 0) {
5627 // If no operands then chain to entry token.
5628 return DAG.getEntryNode();
5629 } else if (Aliases.size() == 1) {
5630 // If a single operand then chain to it. We don't need to revisit it.
5634 // Construct a custom tailored token factor.
5635 SDOperand NewChain = DAG.getNode(ISD::TokenFactor, MVT::Other,
5636 &Aliases[0], Aliases.size());
5638 // Make sure the old chain gets cleaned up.
5639 if (NewChain != OldChain) AddToWorkList(OldChain.Val);
5644 // SelectionDAG::Combine - This is the entry point for the file.
5646 void SelectionDAG::Combine(bool RunningAfterLegalize, AliasAnalysis &AA) {
5647 if (!RunningAfterLegalize && ViewDAGCombine1)
5649 if (RunningAfterLegalize && ViewDAGCombine2)
5651 /// run - This is the main entry point to this class.
5653 DAGCombiner(*this, AA).Run(RunningAfterLegalize);