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");
41 CombinerAA("combiner-alias-analysis", cl::Hidden,
42 cl::desc("Turn on alias analysis during testing"));
45 CombinerGlobalAA("combiner-global-alias-analysis", cl::Hidden,
46 cl::desc("Include global information in alias analysis"));
48 //------------------------------ DAGCombiner ---------------------------------//
50 class VISIBILITY_HIDDEN DAGCombiner {
52 const TargetLowering &TLI;
58 // Worklist of all of the nodes that need to be simplified.
59 std::vector<SDNode*> WorkList;
61 // AA - Used for DAG load/store alias analysis.
64 /// AddUsersToWorkList - When an instruction is simplified, add all users of
65 /// the instruction to the work lists because they might get more simplified
68 void AddUsersToWorkList(SDNode *N) {
69 for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
74 /// visit - call the node-specific routine that knows how to fold each
75 /// particular type of node.
76 SDValue visit(SDNode *N);
79 /// AddToWorkList - Add to the work list making sure it's instance is at the
80 /// the back (next to be processed.)
81 void AddToWorkList(SDNode *N) {
82 removeFromWorkList(N);
83 WorkList.push_back(N);
86 /// removeFromWorkList - remove all instances of N from the worklist.
88 void removeFromWorkList(SDNode *N) {
89 WorkList.erase(std::remove(WorkList.begin(), WorkList.end(), N),
93 SDValue CombineTo(SDNode *N, const SDValue *To, unsigned NumTo,
96 SDValue CombineTo(SDNode *N, SDValue Res, bool AddTo = true) {
97 return CombineTo(N, &Res, 1, AddTo);
100 SDValue CombineTo(SDNode *N, SDValue Res0, SDValue Res1,
102 SDValue To[] = { Res0, Res1 };
103 return CombineTo(N, To, 2, AddTo);
108 /// SimplifyDemandedBits - Check the specified integer node value to see if
109 /// it can be simplified or if things it uses can be simplified by bit
110 /// propagation. If so, return true.
111 bool SimplifyDemandedBits(SDValue Op) {
112 APInt Demanded = APInt::getAllOnesValue(Op.getValueSizeInBits());
113 return SimplifyDemandedBits(Op, Demanded);
116 bool SimplifyDemandedBits(SDValue Op, const APInt &Demanded);
118 bool CombineToPreIndexedLoadStore(SDNode *N);
119 bool CombineToPostIndexedLoadStore(SDNode *N);
122 /// combine - call the node-specific routine that knows how to fold each
123 /// particular type of node. If that doesn't do anything, try the
124 /// target-specific DAG combines.
125 SDValue combine(SDNode *N);
127 // Visitation implementation - Implement dag node combining for different
128 // node types. The semantics are as follows:
130 // SDValue.getNode() == 0 - No change was made
131 // SDValue.getNode() == N - N was replaced, is dead and has been handled.
132 // otherwise - N should be replaced by the returned Operand.
134 SDValue visitTokenFactor(SDNode *N);
135 SDValue visitMERGE_VALUES(SDNode *N);
136 SDValue visitADD(SDNode *N);
137 SDValue visitSUB(SDNode *N);
138 SDValue visitADDC(SDNode *N);
139 SDValue visitADDE(SDNode *N);
140 SDValue visitMUL(SDNode *N);
141 SDValue visitSDIV(SDNode *N);
142 SDValue visitUDIV(SDNode *N);
143 SDValue visitSREM(SDNode *N);
144 SDValue visitUREM(SDNode *N);
145 SDValue visitMULHU(SDNode *N);
146 SDValue visitMULHS(SDNode *N);
147 SDValue visitSMUL_LOHI(SDNode *N);
148 SDValue visitUMUL_LOHI(SDNode *N);
149 SDValue visitSDIVREM(SDNode *N);
150 SDValue visitUDIVREM(SDNode *N);
151 SDValue visitAND(SDNode *N);
152 SDValue visitOR(SDNode *N);
153 SDValue visitXOR(SDNode *N);
154 SDValue SimplifyVBinOp(SDNode *N);
155 SDValue visitSHL(SDNode *N);
156 SDValue visitSRA(SDNode *N);
157 SDValue visitSRL(SDNode *N);
158 SDValue visitCTLZ(SDNode *N);
159 SDValue visitCTTZ(SDNode *N);
160 SDValue visitCTPOP(SDNode *N);
161 SDValue visitSELECT(SDNode *N);
162 SDValue visitSELECT_CC(SDNode *N);
163 SDValue visitSETCC(SDNode *N);
164 SDValue visitSIGN_EXTEND(SDNode *N);
165 SDValue visitZERO_EXTEND(SDNode *N);
166 SDValue visitANY_EXTEND(SDNode *N);
167 SDValue visitSIGN_EXTEND_INREG(SDNode *N);
168 SDValue visitTRUNCATE(SDNode *N);
169 SDValue visitBIT_CONVERT(SDNode *N);
170 SDValue visitBUILD_PAIR(SDNode *N);
171 SDValue visitFADD(SDNode *N);
172 SDValue visitFSUB(SDNode *N);
173 SDValue visitFMUL(SDNode *N);
174 SDValue visitFDIV(SDNode *N);
175 SDValue visitFREM(SDNode *N);
176 SDValue visitFCOPYSIGN(SDNode *N);
177 SDValue visitSINT_TO_FP(SDNode *N);
178 SDValue visitUINT_TO_FP(SDNode *N);
179 SDValue visitFP_TO_SINT(SDNode *N);
180 SDValue visitFP_TO_UINT(SDNode *N);
181 SDValue visitFP_ROUND(SDNode *N);
182 SDValue visitFP_ROUND_INREG(SDNode *N);
183 SDValue visitFP_EXTEND(SDNode *N);
184 SDValue visitFNEG(SDNode *N);
185 SDValue visitFABS(SDNode *N);
186 SDValue visitBRCOND(SDNode *N);
187 SDValue visitBR_CC(SDNode *N);
188 SDValue visitLOAD(SDNode *N);
189 SDValue visitSTORE(SDNode *N);
190 SDValue visitINSERT_VECTOR_ELT(SDNode *N);
191 SDValue visitEXTRACT_VECTOR_ELT(SDNode *N);
192 SDValue visitBUILD_VECTOR(SDNode *N);
193 SDValue visitCONCAT_VECTORS(SDNode *N);
194 SDValue visitVECTOR_SHUFFLE(SDNode *N);
196 SDValue XformToShuffleWithZero(SDNode *N);
197 SDValue ReassociateOps(unsigned Opc, SDValue LHS, SDValue RHS);
199 SDValue visitShiftByConstant(SDNode *N, unsigned Amt);
201 bool SimplifySelectOps(SDNode *SELECT, SDValue LHS, SDValue RHS);
202 SDValue SimplifyBinOpWithSameOpcodeHands(SDNode *N);
203 SDValue SimplifySelect(SDValue N0, SDValue N1, SDValue N2);
204 SDValue SimplifySelectCC(SDValue N0, SDValue N1, SDValue N2,
205 SDValue N3, ISD::CondCode CC,
206 bool NotExtCompare = false);
207 SDValue SimplifySetCC(MVT VT, SDValue N0, SDValue N1, ISD::CondCode Cond,
208 bool foldBooleans = true);
209 SDValue SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp,
211 SDValue CombineConsecutiveLoads(SDNode *N, MVT VT);
212 SDValue ConstantFoldBIT_CONVERTofBUILD_VECTOR(SDNode *, MVT);
213 SDValue BuildSDIV(SDNode *N);
214 SDValue BuildUDIV(SDNode *N);
215 SDNode *MatchRotate(SDValue LHS, SDValue RHS);
216 SDValue ReduceLoadWidth(SDNode *N);
218 SDValue GetDemandedBits(SDValue V, const APInt &Mask);
220 /// GatherAllAliases - Walk up chain skipping non-aliasing memory nodes,
221 /// looking for aliasing nodes and adding them to the Aliases vector.
222 void GatherAllAliases(SDNode *N, SDValue OriginalChain,
223 SmallVector<SDValue, 8> &Aliases);
225 /// isAlias - Return true if there is any possibility that the two addresses
227 bool isAlias(SDValue Ptr1, int64_t Size1,
228 const Value *SrcValue1, int SrcValueOffset1,
229 SDValue Ptr2, int64_t Size2,
230 const Value *SrcValue2, int SrcValueOffset2);
232 /// FindAliasInfo - Extracts the relevant alias information from the memory
233 /// node. Returns true if the operand was a load.
234 bool FindAliasInfo(SDNode *N,
235 SDValue &Ptr, int64_t &Size,
236 const Value *&SrcValue, int &SrcValueOffset);
238 /// FindBetterChain - Walk up chain skipping non-aliasing memory nodes,
239 /// looking for a better chain (aliasing node.)
240 SDValue FindBetterChain(SDNode *N, SDValue Chain);
243 DAGCombiner(SelectionDAG &D, AliasAnalysis &A, bool fast)
245 TLI(D.getTargetLoweringInfo()),
247 LegalOperations(false),
252 /// Run - runs the dag combiner on all nodes in the work list
253 void Run(CombineLevel AtLevel);
259 /// WorkListRemover - This class is a DAGUpdateListener that removes any deleted
260 /// nodes from the worklist.
261 class VISIBILITY_HIDDEN WorkListRemover :
262 public SelectionDAG::DAGUpdateListener {
265 explicit WorkListRemover(DAGCombiner &dc) : DC(dc) {}
267 virtual void NodeDeleted(SDNode *N, SDNode *E) {
268 DC.removeFromWorkList(N);
271 virtual void NodeUpdated(SDNode *N) {
277 //===----------------------------------------------------------------------===//
278 // TargetLowering::DAGCombinerInfo implementation
279 //===----------------------------------------------------------------------===//
281 void TargetLowering::DAGCombinerInfo::AddToWorklist(SDNode *N) {
282 ((DAGCombiner*)DC)->AddToWorkList(N);
285 SDValue TargetLowering::DAGCombinerInfo::
286 CombineTo(SDNode *N, const std::vector<SDValue> &To) {
287 return ((DAGCombiner*)DC)->CombineTo(N, &To[0], To.size());
290 SDValue TargetLowering::DAGCombinerInfo::
291 CombineTo(SDNode *N, SDValue Res) {
292 return ((DAGCombiner*)DC)->CombineTo(N, Res);
296 SDValue TargetLowering::DAGCombinerInfo::
297 CombineTo(SDNode *N, SDValue Res0, SDValue Res1) {
298 return ((DAGCombiner*)DC)->CombineTo(N, Res0, Res1);
302 //===----------------------------------------------------------------------===//
304 //===----------------------------------------------------------------------===//
306 /// isNegatibleForFree - Return 1 if we can compute the negated form of the
307 /// specified expression for the same cost as the expression itself, or 2 if we
308 /// can compute the negated form more cheaply than the expression itself.
309 static char isNegatibleForFree(SDValue Op, bool LegalOperations,
310 unsigned Depth = 0) {
311 // No compile time optimizations on this type.
312 if (Op.getValueType() == MVT::ppcf128)
315 // fneg is removable even if it has multiple uses.
316 if (Op.getOpcode() == ISD::FNEG) return 2;
318 // Don't allow anything with multiple uses.
319 if (!Op.hasOneUse()) return 0;
321 // Don't recurse exponentially.
322 if (Depth > 6) return 0;
324 switch (Op.getOpcode()) {
325 default: return false;
326 case ISD::ConstantFP:
327 // Don't invert constant FP values after legalize. The negated constant
328 // isn't necessarily legal.
329 return LegalOperations ? 0 : 1;
331 // FIXME: determine better conditions for this xform.
332 if (!UnsafeFPMath) return 0;
335 if (char V = isNegatibleForFree(Op.getOperand(0), LegalOperations, Depth+1))
338 return isNegatibleForFree(Op.getOperand(1), LegalOperations, Depth+1);
340 // We can't turn -(A-B) into B-A when we honor signed zeros.
341 if (!UnsafeFPMath) return 0;
348 if (HonorSignDependentRoundingFPMath()) return 0;
350 // -(X*Y) -> (-X * Y) or (X*-Y)
351 if (char V = isNegatibleForFree(Op.getOperand(0), LegalOperations, Depth+1))
354 return isNegatibleForFree(Op.getOperand(1), LegalOperations, Depth+1);
359 return isNegatibleForFree(Op.getOperand(0), LegalOperations, Depth+1);
363 /// GetNegatedExpression - If isNegatibleForFree returns true, this function
364 /// returns the newly negated expression.
365 static SDValue GetNegatedExpression(SDValue Op, SelectionDAG &DAG,
366 bool LegalOperations, unsigned Depth = 0) {
367 // fneg is removable even if it has multiple uses.
368 if (Op.getOpcode() == ISD::FNEG) return Op.getOperand(0);
370 // Don't allow anything with multiple uses.
371 assert(Op.hasOneUse() && "Unknown reuse!");
373 assert(Depth <= 6 && "GetNegatedExpression doesn't match isNegatibleForFree");
374 switch (Op.getOpcode()) {
375 default: assert(0 && "Unknown code");
376 case ISD::ConstantFP: {
377 APFloat V = cast<ConstantFPSDNode>(Op)->getValueAPF();
379 return DAG.getConstantFP(V, Op.getValueType());
382 // FIXME: determine better conditions for this xform.
383 assert(UnsafeFPMath);
386 if (isNegatibleForFree(Op.getOperand(0), LegalOperations, Depth+1))
387 return DAG.getNode(ISD::FSUB, Op.getValueType(),
388 GetNegatedExpression(Op.getOperand(0), DAG,
389 LegalOperations, Depth+1),
392 return DAG.getNode(ISD::FSUB, Op.getValueType(),
393 GetNegatedExpression(Op.getOperand(1), DAG,
394 LegalOperations, Depth+1),
397 // We can't turn -(A-B) into B-A when we honor signed zeros.
398 assert(UnsafeFPMath);
401 if (ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(Op.getOperand(0)))
402 if (N0CFP->getValueAPF().isZero())
403 return Op.getOperand(1);
406 return DAG.getNode(ISD::FSUB, Op.getValueType(), Op.getOperand(1),
411 assert(!HonorSignDependentRoundingFPMath());
414 if (isNegatibleForFree(Op.getOperand(0), LegalOperations, Depth+1))
415 return DAG.getNode(Op.getOpcode(), Op.getValueType(),
416 GetNegatedExpression(Op.getOperand(0), DAG,
417 LegalOperations, Depth+1),
421 return DAG.getNode(Op.getOpcode(), Op.getValueType(),
423 GetNegatedExpression(Op.getOperand(1), DAG,
424 LegalOperations, Depth+1));
428 return DAG.getNode(Op.getOpcode(), Op.getValueType(),
429 GetNegatedExpression(Op.getOperand(0), DAG,
430 LegalOperations, Depth+1));
432 return DAG.getNode(ISD::FP_ROUND, Op.getValueType(),
433 GetNegatedExpression(Op.getOperand(0), DAG,
434 LegalOperations, Depth+1),
440 // isSetCCEquivalent - Return true if this node is a setcc, or is a select_cc
441 // that selects between the values 1 and 0, making it equivalent to a setcc.
442 // Also, set the incoming LHS, RHS, and CC references to the appropriate
443 // nodes based on the type of node we are checking. This simplifies life a
444 // bit for the callers.
445 static bool isSetCCEquivalent(SDValue N, SDValue &LHS, SDValue &RHS,
447 if (N.getOpcode() == ISD::SETCC) {
448 LHS = N.getOperand(0);
449 RHS = N.getOperand(1);
450 CC = N.getOperand(2);
453 if (N.getOpcode() == ISD::SELECT_CC &&
454 N.getOperand(2).getOpcode() == ISD::Constant &&
455 N.getOperand(3).getOpcode() == ISD::Constant &&
456 cast<ConstantSDNode>(N.getOperand(2))->getAPIntValue() == 1 &&
457 cast<ConstantSDNode>(N.getOperand(3))->isNullValue()) {
458 LHS = N.getOperand(0);
459 RHS = N.getOperand(1);
460 CC = N.getOperand(4);
466 // isOneUseSetCC - Return true if this is a SetCC-equivalent operation with only
467 // one use. If this is true, it allows the users to invert the operation for
468 // free when it is profitable to do so.
469 static bool isOneUseSetCC(SDValue N) {
471 if (isSetCCEquivalent(N, N0, N1, N2) && N.getNode()->hasOneUse())
476 SDValue DAGCombiner::ReassociateOps(unsigned Opc, SDValue N0, SDValue N1){
477 MVT VT = N0.getValueType();
478 // reassoc. (op (op x, c1), y) -> (op (op x, y), c1) iff x+c1 has one use
479 // reassoc. (op (op x, c1), c2) -> (op x, (op c1, c2))
480 if (N0.getOpcode() == Opc && isa<ConstantSDNode>(N0.getOperand(1))) {
481 if (isa<ConstantSDNode>(N1)) {
482 SDValue OpNode = DAG.getNode(Opc, VT, N0.getOperand(1), N1);
483 AddToWorkList(OpNode.getNode());
484 return DAG.getNode(Opc, VT, OpNode, N0.getOperand(0));
485 } else if (N0.hasOneUse()) {
486 SDValue OpNode = DAG.getNode(Opc, VT, N0.getOperand(0), N1);
487 AddToWorkList(OpNode.getNode());
488 return DAG.getNode(Opc, VT, OpNode, N0.getOperand(1));
491 // reassoc. (op y, (op x, c1)) -> (op (op x, y), c1) iff x+c1 has one use
492 // reassoc. (op c2, (op x, c1)) -> (op x, (op c1, c2))
493 if (N1.getOpcode() == Opc && isa<ConstantSDNode>(N1.getOperand(1))) {
494 if (isa<ConstantSDNode>(N0)) {
495 SDValue OpNode = DAG.getNode(Opc, VT, N1.getOperand(1), N0);
496 AddToWorkList(OpNode.getNode());
497 return DAG.getNode(Opc, VT, OpNode, N1.getOperand(0));
498 } else if (N1.hasOneUse()) {
499 SDValue OpNode = DAG.getNode(Opc, VT, N1.getOperand(0), N0);
500 AddToWorkList(OpNode.getNode());
501 return DAG.getNode(Opc, VT, OpNode, N1.getOperand(1));
507 SDValue DAGCombiner::CombineTo(SDNode *N, const SDValue *To, unsigned NumTo,
509 assert(N->getNumValues() == NumTo && "Broken CombineTo call!");
511 DOUT << "\nReplacing.1 "; DEBUG(N->dump(&DAG));
512 DOUT << "\nWith: "; DEBUG(To[0].getNode()->dump(&DAG));
513 DOUT << " and " << NumTo-1 << " other values\n";
514 DEBUG(for (unsigned i = 0, e = NumTo; i != e; ++i)
515 assert(N->getValueType(i) == To[i].getValueType() &&
516 "Cannot combine value to value of different type!"));
517 WorkListRemover DeadNodes(*this);
518 DAG.ReplaceAllUsesWith(N, To, &DeadNodes);
521 // Push the new nodes and any users onto the worklist
522 for (unsigned i = 0, e = NumTo; i != e; ++i) {
523 AddToWorkList(To[i].getNode());
524 AddUsersToWorkList(To[i].getNode());
528 // Finally, if the node is now dead, remove it from the graph. The node
529 // may not be dead if the replacement process recursively simplified to
530 // something else needing this node.
531 if (N->use_empty()) {
532 // Nodes can be reintroduced into the worklist. Make sure we do not
533 // process a node that has been replaced.
534 removeFromWorkList(N);
536 // Finally, since the node is now dead, remove it from the graph.
539 return SDValue(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(SDValue Op, const APInt &Demanded) {
546 TargetLowering::TargetLoweringOpt TLO(DAG);
547 APInt KnownZero, KnownOne;
548 if (!TLI.SimplifyDemandedBits(Op, Demanded, KnownZero, KnownOne, TLO))
552 AddToWorkList(Op.getNode());
554 // Replace the old value with the new one.
556 DOUT << "\nReplacing.2 "; DEBUG(TLO.Old.getNode()->dump(&DAG));
557 DOUT << "\nWith: "; DEBUG(TLO.New.getNode()->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.getNode());
567 AddUsersToWorkList(TLO.New.getNode());
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.getNode()->use_empty()) {
573 removeFromWorkList(TLO.Old.getNode());
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.getNode()->getNumOperands(); i != e; ++i)
578 if (TLO.Old.getNode()->getOperand(i).getNode()->hasOneUse())
579 AddToWorkList(TLO.Old.getNode()->getOperand(i).getNode());
581 DAG.DeleteNode(TLO.Old.getNode());
586 //===----------------------------------------------------------------------===//
587 // Main DAG Combiner implementation
588 //===----------------------------------------------------------------------===//
590 void DAGCombiner::Run(CombineLevel AtLevel) {
591 // set the instance variables, so that the various visit routines may use it.
593 LegalOperations = Level >= NoIllegalOperations;
594 LegalTypes = Level >= NoIllegalTypes;
596 // Add all the dag nodes to the worklist.
597 WorkList.reserve(DAG.allnodes_size());
598 for (SelectionDAG::allnodes_iterator I = DAG.allnodes_begin(),
599 E = DAG.allnodes_end(); I != E; ++I)
600 WorkList.push_back(I);
602 // Create a dummy node (which is not added to allnodes), that adds a reference
603 // to the root node, preventing it from being deleted, and tracking any
604 // changes of the root.
605 HandleSDNode Dummy(DAG.getRoot());
607 // The root of the dag may dangle to deleted nodes until the dag combiner is
608 // done. Set it to null to avoid confusion.
609 DAG.setRoot(SDValue());
611 // while the worklist isn't empty, inspect the node on the end of it and
612 // try and combine it.
613 while (!WorkList.empty()) {
614 SDNode *N = WorkList.back();
617 // If N has no uses, it is dead. Make sure to revisit all N's operands once
618 // N is deleted from the DAG, since they too may now be dead or may have a
619 // reduced number of uses, allowing other xforms.
620 if (N->use_empty() && N != &Dummy) {
621 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
622 AddToWorkList(N->getOperand(i).getNode());
628 SDValue RV = combine(N);
630 if (RV.getNode() == 0)
635 // If we get back the same node we passed in, rather than a new node or
636 // zero, we know that the node must have defined multiple values and
637 // CombineTo was used. Since CombineTo takes care of the worklist
638 // mechanics for us, we have no work to do in this case.
639 if (RV.getNode() == N)
642 assert(N->getOpcode() != ISD::DELETED_NODE &&
643 RV.getNode()->getOpcode() != ISD::DELETED_NODE &&
644 "Node was deleted but visit returned new node!");
646 DOUT << "\nReplacing.3 "; DEBUG(N->dump(&DAG));
647 DOUT << "\nWith: "; DEBUG(RV.getNode()->dump(&DAG));
649 WorkListRemover DeadNodes(*this);
650 if (N->getNumValues() == RV.getNode()->getNumValues())
651 DAG.ReplaceAllUsesWith(N, RV.getNode(), &DeadNodes);
653 assert(N->getValueType(0) == RV.getValueType() &&
654 N->getNumValues() == 1 && "Type mismatch");
656 DAG.ReplaceAllUsesWith(N, &OpV, &DeadNodes);
659 // Push the new node and any users onto the worklist
660 AddToWorkList(RV.getNode());
661 AddUsersToWorkList(RV.getNode());
663 // Add any uses of the old node to the worklist in case this node is the
664 // last one that uses them. They may become dead after this node is
666 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
667 AddToWorkList(N->getOperand(i).getNode());
669 // Finally, if the node is now dead, remove it from the graph. The node
670 // may not be dead if the replacement process recursively simplified to
671 // something else needing this node.
672 if (N->use_empty()) {
673 // Nodes can be reintroduced into the worklist. Make sure we do not
674 // process a node that has been replaced.
675 removeFromWorkList(N);
677 // Finally, since the node is now dead, remove it from the graph.
682 // If the root changed (e.g. it was a dead load, update the root).
683 DAG.setRoot(Dummy.getValue());
686 SDValue DAGCombiner::visit(SDNode *N) {
687 switch(N->getOpcode()) {
689 case ISD::TokenFactor: return visitTokenFactor(N);
690 case ISD::MERGE_VALUES: return visitMERGE_VALUES(N);
691 case ISD::ADD: return visitADD(N);
692 case ISD::SUB: return visitSUB(N);
693 case ISD::ADDC: return visitADDC(N);
694 case ISD::ADDE: return visitADDE(N);
695 case ISD::MUL: return visitMUL(N);
696 case ISD::SDIV: return visitSDIV(N);
697 case ISD::UDIV: return visitUDIV(N);
698 case ISD::SREM: return visitSREM(N);
699 case ISD::UREM: return visitUREM(N);
700 case ISD::MULHU: return visitMULHU(N);
701 case ISD::MULHS: return visitMULHS(N);
702 case ISD::SMUL_LOHI: return visitSMUL_LOHI(N);
703 case ISD::UMUL_LOHI: return visitUMUL_LOHI(N);
704 case ISD::SDIVREM: return visitSDIVREM(N);
705 case ISD::UDIVREM: return visitUDIVREM(N);
706 case ISD::AND: return visitAND(N);
707 case ISD::OR: return visitOR(N);
708 case ISD::XOR: return visitXOR(N);
709 case ISD::SHL: return visitSHL(N);
710 case ISD::SRA: return visitSRA(N);
711 case ISD::SRL: return visitSRL(N);
712 case ISD::CTLZ: return visitCTLZ(N);
713 case ISD::CTTZ: return visitCTTZ(N);
714 case ISD::CTPOP: return visitCTPOP(N);
715 case ISD::SELECT: return visitSELECT(N);
716 case ISD::SELECT_CC: return visitSELECT_CC(N);
717 case ISD::SETCC: return visitSETCC(N);
718 case ISD::SIGN_EXTEND: return visitSIGN_EXTEND(N);
719 case ISD::ZERO_EXTEND: return visitZERO_EXTEND(N);
720 case ISD::ANY_EXTEND: return visitANY_EXTEND(N);
721 case ISD::SIGN_EXTEND_INREG: return visitSIGN_EXTEND_INREG(N);
722 case ISD::TRUNCATE: return visitTRUNCATE(N);
723 case ISD::BIT_CONVERT: return visitBIT_CONVERT(N);
724 case ISD::BUILD_PAIR: return visitBUILD_PAIR(N);
725 case ISD::FADD: return visitFADD(N);
726 case ISD::FSUB: return visitFSUB(N);
727 case ISD::FMUL: return visitFMUL(N);
728 case ISD::FDIV: return visitFDIV(N);
729 case ISD::FREM: return visitFREM(N);
730 case ISD::FCOPYSIGN: return visitFCOPYSIGN(N);
731 case ISD::SINT_TO_FP: return visitSINT_TO_FP(N);
732 case ISD::UINT_TO_FP: return visitUINT_TO_FP(N);
733 case ISD::FP_TO_SINT: return visitFP_TO_SINT(N);
734 case ISD::FP_TO_UINT: return visitFP_TO_UINT(N);
735 case ISD::FP_ROUND: return visitFP_ROUND(N);
736 case ISD::FP_ROUND_INREG: return visitFP_ROUND_INREG(N);
737 case ISD::FP_EXTEND: return visitFP_EXTEND(N);
738 case ISD::FNEG: return visitFNEG(N);
739 case ISD::FABS: return visitFABS(N);
740 case ISD::BRCOND: return visitBRCOND(N);
741 case ISD::BR_CC: return visitBR_CC(N);
742 case ISD::LOAD: return visitLOAD(N);
743 case ISD::STORE: return visitSTORE(N);
744 case ISD::INSERT_VECTOR_ELT: return visitINSERT_VECTOR_ELT(N);
745 case ISD::EXTRACT_VECTOR_ELT: return visitEXTRACT_VECTOR_ELT(N);
746 case ISD::BUILD_VECTOR: return visitBUILD_VECTOR(N);
747 case ISD::CONCAT_VECTORS: return visitCONCAT_VECTORS(N);
748 case ISD::VECTOR_SHUFFLE: return visitVECTOR_SHUFFLE(N);
753 SDValue DAGCombiner::combine(SDNode *N) {
755 SDValue RV = visit(N);
757 // If nothing happened, try a target-specific DAG combine.
758 if (RV.getNode() == 0) {
759 assert(N->getOpcode() != ISD::DELETED_NODE &&
760 "Node was deleted but visit returned NULL!");
762 if (N->getOpcode() >= ISD::BUILTIN_OP_END ||
763 TLI.hasTargetDAGCombine((ISD::NodeType)N->getOpcode())) {
765 // Expose the DAG combiner to the target combiner impls.
766 TargetLowering::DAGCombinerInfo
767 DagCombineInfo(DAG, Level == Unrestricted, false, this);
769 RV = TLI.PerformDAGCombine(N, DagCombineInfo);
773 // If N is a commutative binary node, try commuting it to enable more
775 if (RV.getNode() == 0 &&
776 SelectionDAG::isCommutativeBinOp(N->getOpcode()) &&
777 N->getNumValues() == 1) {
778 SDValue N0 = N->getOperand(0);
779 SDValue N1 = N->getOperand(1);
780 // Constant operands are canonicalized to RHS.
781 if (isa<ConstantSDNode>(N0) || !isa<ConstantSDNode>(N1)) {
782 SDValue Ops[] = { N1, N0 };
783 SDNode *CSENode = DAG.getNodeIfExists(N->getOpcode(), N->getVTList(),
786 return SDValue(CSENode, 0);
793 /// getInputChainForNode - Given a node, return its input chain if it has one,
794 /// otherwise return a null sd operand.
795 static SDValue getInputChainForNode(SDNode *N) {
796 if (unsigned NumOps = N->getNumOperands()) {
797 if (N->getOperand(0).getValueType() == MVT::Other)
798 return N->getOperand(0);
799 else if (N->getOperand(NumOps-1).getValueType() == MVT::Other)
800 return N->getOperand(NumOps-1);
801 for (unsigned i = 1; i < NumOps-1; ++i)
802 if (N->getOperand(i).getValueType() == MVT::Other)
803 return N->getOperand(i);
805 return SDValue(0, 0);
808 SDValue DAGCombiner::visitTokenFactor(SDNode *N) {
809 // If N has two operands, where one has an input chain equal to the other,
810 // the 'other' chain is redundant.
811 if (N->getNumOperands() == 2) {
812 if (getInputChainForNode(N->getOperand(0).getNode()) == N->getOperand(1))
813 return N->getOperand(0);
814 if (getInputChainForNode(N->getOperand(1).getNode()) == N->getOperand(0))
815 return N->getOperand(1);
818 SmallVector<SDNode *, 8> TFs; // List of token factors to visit.
819 SmallVector<SDValue, 8> Ops; // Ops for replacing token factor.
820 SmallPtrSet<SDNode*, 16> SeenOps;
821 bool Changed = false; // If we should replace this token factor.
823 // Start out with this token factor.
826 // Iterate through token factors. The TFs grows when new token factors are
828 for (unsigned i = 0; i < TFs.size(); ++i) {
831 // Check each of the operands.
832 for (unsigned i = 0, ie = TF->getNumOperands(); i != ie; ++i) {
833 SDValue Op = TF->getOperand(i);
835 switch (Op.getOpcode()) {
836 case ISD::EntryToken:
837 // Entry tokens don't need to be added to the list. They are
842 case ISD::TokenFactor:
843 if ((CombinerAA || Op.hasOneUse()) &&
844 std::find(TFs.begin(), TFs.end(), Op.getNode()) == TFs.end()) {
845 // Queue up for processing.
846 TFs.push_back(Op.getNode());
847 // Clean up in case the token factor is removed.
848 AddToWorkList(Op.getNode());
855 // Only add if it isn't already in the list.
856 if (SeenOps.insert(Op.getNode()))
867 // If we've change things around then replace token factor.
870 // The entry token is the only possible outcome.
871 Result = DAG.getEntryNode();
873 // New and improved token factor.
874 Result = DAG.getNode(ISD::TokenFactor, MVT::Other, &Ops[0], Ops.size());
877 // Don't add users to work list.
878 return CombineTo(N, Result, false);
884 /// MERGE_VALUES can always be eliminated.
885 SDValue DAGCombiner::visitMERGE_VALUES(SDNode *N) {
886 WorkListRemover DeadNodes(*this);
887 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
888 DAG.ReplaceAllUsesOfValueWith(SDValue(N, i), N->getOperand(i),
890 removeFromWorkList(N);
892 return SDValue(N, 0); // Return N so it doesn't get rechecked!
897 SDValue combineShlAddConstant(SDValue N0, SDValue N1, SelectionDAG &DAG) {
898 MVT VT = N0.getValueType();
899 SDValue N00 = N0.getOperand(0);
900 SDValue N01 = N0.getOperand(1);
901 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N01);
902 if (N01C && N00.getOpcode() == ISD::ADD && N00.getNode()->hasOneUse() &&
903 isa<ConstantSDNode>(N00.getOperand(1))) {
904 N0 = DAG.getNode(ISD::ADD, VT,
905 DAG.getNode(ISD::SHL, VT, N00.getOperand(0), N01),
906 DAG.getNode(ISD::SHL, VT, N00.getOperand(1), N01));
907 return DAG.getNode(ISD::ADD, VT, N0, N1);
913 SDValue combineSelectAndUse(SDNode *N, SDValue Slct, SDValue OtherOp,
914 SelectionDAG &DAG, const TargetLowering &TLI,
915 bool LegalOperations) {
916 MVT VT = N->getValueType(0);
917 unsigned Opc = N->getOpcode();
918 bool isSlctCC = Slct.getOpcode() == ISD::SELECT_CC;
919 SDValue LHS = isSlctCC ? Slct.getOperand(2) : Slct.getOperand(1);
920 SDValue RHS = isSlctCC ? Slct.getOperand(3) : Slct.getOperand(2);
921 ISD::CondCode CC = ISD::SETCC_INVALID;
924 CC = cast<CondCodeSDNode>(Slct.getOperand(4))->get();
926 SDValue CCOp = Slct.getOperand(0);
927 if (CCOp.getOpcode() == ISD::SETCC)
928 CC = cast<CondCodeSDNode>(CCOp.getOperand(2))->get();
931 bool DoXform = false;
933 assert ((Opc == ISD::ADD || (Opc == ISD::SUB && Slct == N->getOperand(1))) &&
936 if (LHS.getOpcode() == ISD::Constant &&
937 cast<ConstantSDNode>(LHS)->isNullValue()) {
939 } else if (CC != ISD::SETCC_INVALID &&
940 RHS.getOpcode() == ISD::Constant &&
941 cast<ConstantSDNode>(RHS)->isNullValue()) {
943 SDValue Op0 = Slct.getOperand(0);
944 MVT OpVT = isSlctCC ? Op0.getValueType() :
945 Op0.getOperand(0).getValueType();
946 bool isInt = OpVT.isInteger();
947 CC = ISD::getSetCCInverse(CC, isInt);
949 if (LegalOperations && !TLI.isCondCodeLegal(CC, OpVT))
950 return SDValue(); // Inverse operator isn't legal.
957 SDValue Result = DAG.getNode(Opc, VT, OtherOp, RHS);
959 return DAG.getSelectCC(OtherOp, Result,
960 Slct.getOperand(0), Slct.getOperand(1), CC);
961 SDValue CCOp = Slct.getOperand(0);
963 CCOp = DAG.getSetCC(CCOp.getValueType(), CCOp.getOperand(0),
964 CCOp.getOperand(1), CC);
965 return DAG.getNode(ISD::SELECT, VT, CCOp, OtherOp, Result);
970 SDValue DAGCombiner::visitADD(SDNode *N) {
971 SDValue N0 = N->getOperand(0);
972 SDValue N1 = N->getOperand(1);
973 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
974 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
975 MVT VT = N0.getValueType();
979 SDValue FoldedVOp = SimplifyVBinOp(N);
980 if (FoldedVOp.getNode()) return FoldedVOp;
983 // fold (add x, undef) -> undef
984 if (N0.getOpcode() == ISD::UNDEF)
986 if (N1.getOpcode() == ISD::UNDEF)
988 // fold (add c1, c2) -> c1+c2
990 return DAG.FoldConstantArithmetic(ISD::ADD, VT, N0C, N1C);
991 // canonicalize constant to RHS
993 return DAG.getNode(ISD::ADD, VT, N1, N0);
994 // fold (add x, 0) -> x
995 if (N1C && N1C->isNullValue())
997 // fold (add Sym, c) -> Sym+c
998 if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N0))
999 if (!LegalOperations && TLI.isOffsetFoldingLegal(GA) && N1C &&
1000 GA->getOpcode() == ISD::GlobalAddress)
1001 return DAG.getGlobalAddress(GA->getGlobal(), VT,
1003 (uint64_t)N1C->getSExtValue());
1004 // fold ((c1-A)+c2) -> (c1+c2)-A
1005 if (N1C && N0.getOpcode() == ISD::SUB)
1006 if (ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getOperand(0)))
1007 return DAG.getNode(ISD::SUB, VT,
1008 DAG.getConstant(N1C->getAPIntValue()+
1009 N0C->getAPIntValue(), VT),
1012 SDValue RADD = ReassociateOps(ISD::ADD, N0, N1);
1013 if (RADD.getNode() != 0)
1015 // fold ((0-A) + B) -> B-A
1016 if (N0.getOpcode() == ISD::SUB && isa<ConstantSDNode>(N0.getOperand(0)) &&
1017 cast<ConstantSDNode>(N0.getOperand(0))->isNullValue())
1018 return DAG.getNode(ISD::SUB, VT, N1, N0.getOperand(1));
1019 // fold (A + (0-B)) -> A-B
1020 if (N1.getOpcode() == ISD::SUB && isa<ConstantSDNode>(N1.getOperand(0)) &&
1021 cast<ConstantSDNode>(N1.getOperand(0))->isNullValue())
1022 return DAG.getNode(ISD::SUB, VT, N0, N1.getOperand(1));
1023 // fold (A+(B-A)) -> B
1024 if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(1))
1025 return N1.getOperand(0);
1026 // fold ((B-A)+A) -> B
1027 if (N0.getOpcode() == ISD::SUB && N1 == N0.getOperand(1))
1028 return N0.getOperand(0);
1029 // fold (A+(B-(A+C))) to (B-C)
1030 if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD &&
1031 N0 == N1.getOperand(1).getOperand(0)) {
1032 return DAG.getNode(ISD::SUB, VT, N1.getOperand(0),
1033 N1.getOperand(1).getOperand(1));
1035 // fold (A+(B-(C+A))) to (B-C)
1036 if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD &&
1037 N0 == N1.getOperand(1).getOperand(1)) {
1038 return DAG.getNode(ISD::SUB, VT, N1.getOperand(0),
1039 N1.getOperand(1).getOperand(0));
1041 // fold (A+((B-A)+or-C)) to (B+or-C)
1042 if ((N1.getOpcode() == ISD::SUB || N1.getOpcode() == ISD::ADD) &&
1043 N1.getOperand(0).getOpcode() == ISD::SUB &&
1044 N0 == N1.getOperand(0).getOperand(1)) {
1045 return DAG.getNode(N1.getOpcode(), VT, N1.getOperand(0).getOperand(0),
1049 // fold (A-B)+(C-D) to (A+C)-(B+D) when A or C is constant
1050 if (N0.getOpcode() == ISD::SUB && N1.getOpcode() == ISD::SUB) {
1051 SDValue N00 = N0.getOperand(0);
1052 SDValue N01 = N0.getOperand(1);
1053 SDValue N10 = N1.getOperand(0);
1054 SDValue N11 = N1.getOperand(1);
1055 if (isa<ConstantSDNode>(N00) || isa<ConstantSDNode>(N10)) {
1056 return DAG.getNode(ISD::SUB, VT,
1057 DAG.getNode(ISD::ADD, VT, N00, N10),
1058 DAG.getNode(ISD::ADD, VT, N01, N11));
1062 if (!VT.isVector() && SimplifyDemandedBits(SDValue(N, 0)))
1063 return SDValue(N, 0);
1065 // fold (a+b) -> (a|b) iff a and b share no bits.
1066 if (VT.isInteger() && !VT.isVector()) {
1067 APInt LHSZero, LHSOne;
1068 APInt RHSZero, RHSOne;
1069 APInt Mask = APInt::getAllOnesValue(VT.getSizeInBits());
1070 DAG.ComputeMaskedBits(N0, Mask, LHSZero, LHSOne);
1071 if (LHSZero.getBoolValue()) {
1072 DAG.ComputeMaskedBits(N1, Mask, RHSZero, RHSOne);
1074 // If all possibly-set bits on the LHS are clear on the RHS, return an OR.
1075 // If all possibly-set bits on the RHS are clear on the LHS, return an OR.
1076 if ((RHSZero & (~LHSZero & Mask)) == (~LHSZero & Mask) ||
1077 (LHSZero & (~RHSZero & Mask)) == (~RHSZero & Mask))
1078 return DAG.getNode(ISD::OR, VT, N0, N1);
1082 // fold (add (shl (add x, c1), c2), ) -> (add (add (shl x, c2), c1<<c2), )
1083 if (N0.getOpcode() == ISD::SHL && N0.getNode()->hasOneUse()) {
1084 SDValue Result = combineShlAddConstant(N0, N1, DAG);
1085 if (Result.getNode()) return Result;
1087 if (N1.getOpcode() == ISD::SHL && N1.getNode()->hasOneUse()) {
1088 SDValue Result = combineShlAddConstant(N1, N0, DAG);
1089 if (Result.getNode()) return Result;
1092 // fold (add (select cc, 0, c), x) -> (select cc, x, (add, x, c))
1093 if (N0.getOpcode() == ISD::SELECT && N0.getNode()->hasOneUse()) {
1094 SDValue Result = combineSelectAndUse(N, N0, N1, DAG, TLI, LegalOperations);
1095 if (Result.getNode()) return Result;
1097 if (N1.getOpcode() == ISD::SELECT && N1.getNode()->hasOneUse()) {
1098 SDValue Result = combineSelectAndUse(N, N1, N0, DAG, TLI, LegalOperations);
1099 if (Result.getNode()) return Result;
1105 SDValue DAGCombiner::visitADDC(SDNode *N) {
1106 SDValue N0 = N->getOperand(0);
1107 SDValue N1 = N->getOperand(1);
1108 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1109 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1110 MVT VT = N0.getValueType();
1112 // If the flag result is dead, turn this into an ADD.
1113 if (N->hasNUsesOfValue(0, 1))
1114 return CombineTo(N, DAG.getNode(ISD::ADD, VT, N1, N0),
1115 DAG.getNode(ISD::CARRY_FALSE, MVT::Flag));
1117 // canonicalize constant to RHS.
1119 return DAG.getNode(ISD::ADDC, N->getVTList(), N1, N0);
1121 // fold (addc x, 0) -> x + no carry out
1122 if (N1C && N1C->isNullValue())
1123 return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE, MVT::Flag));
1125 // fold (addc a, b) -> (or a, b), CARRY_FALSE iff a and b share no bits.
1126 APInt LHSZero, LHSOne;
1127 APInt RHSZero, RHSOne;
1128 APInt Mask = APInt::getAllOnesValue(VT.getSizeInBits());
1129 DAG.ComputeMaskedBits(N0, Mask, LHSZero, LHSOne);
1130 if (LHSZero.getBoolValue()) {
1131 DAG.ComputeMaskedBits(N1, Mask, RHSZero, RHSOne);
1133 // If all possibly-set bits on the LHS are clear on the RHS, return an OR.
1134 // If all possibly-set bits on the RHS are clear on the LHS, return an OR.
1135 if ((RHSZero & (~LHSZero & Mask)) == (~LHSZero & Mask) ||
1136 (LHSZero & (~RHSZero & Mask)) == (~RHSZero & Mask))
1137 return CombineTo(N, DAG.getNode(ISD::OR, VT, N0, N1),
1138 DAG.getNode(ISD::CARRY_FALSE, MVT::Flag));
1144 SDValue DAGCombiner::visitADDE(SDNode *N) {
1145 SDValue N0 = N->getOperand(0);
1146 SDValue N1 = N->getOperand(1);
1147 SDValue CarryIn = N->getOperand(2);
1148 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1149 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1150 //MVT VT = N0.getValueType();
1152 // canonicalize constant to RHS
1154 return DAG.getNode(ISD::ADDE, N->getVTList(), N1, N0, CarryIn);
1156 // fold (adde x, y, false) -> (addc x, y)
1157 if (CarryIn.getOpcode() == ISD::CARRY_FALSE)
1158 return DAG.getNode(ISD::ADDC, N->getVTList(), N1, N0);
1165 SDValue DAGCombiner::visitSUB(SDNode *N) {
1166 SDValue N0 = N->getOperand(0);
1167 SDValue N1 = N->getOperand(1);
1168 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getNode());
1169 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
1170 MVT VT = N0.getValueType();
1173 if (VT.isVector()) {
1174 SDValue FoldedVOp = SimplifyVBinOp(N);
1175 if (FoldedVOp.getNode()) return FoldedVOp;
1178 // fold (sub x, x) -> 0
1180 return DAG.getConstant(0, N->getValueType(0));
1181 // fold (sub c1, c2) -> c1-c2
1183 return DAG.FoldConstantArithmetic(ISD::SUB, VT, N0C, N1C);
1184 // fold (sub x, c) -> (add x, -c)
1186 return DAG.getNode(ISD::ADD, VT, N0,
1187 DAG.getConstant(-N1C->getAPIntValue(), VT));
1188 // fold (A+B)-A -> B
1189 if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1)
1190 return N0.getOperand(1);
1191 // fold (A+B)-B -> A
1192 if (N0.getOpcode() == ISD::ADD && N0.getOperand(1) == N1)
1193 return N0.getOperand(0);
1194 // fold ((A+(B+or-C))-B) -> A+or-C
1195 if (N0.getOpcode() == ISD::ADD &&
1196 (N0.getOperand(1).getOpcode() == ISD::SUB ||
1197 N0.getOperand(1).getOpcode() == ISD::ADD) &&
1198 N0.getOperand(1).getOperand(0) == N1)
1199 return DAG.getNode(N0.getOperand(1).getOpcode(), VT, N0.getOperand(0),
1200 N0.getOperand(1).getOperand(1));
1201 // fold ((A+(C+B))-B) -> A+C
1202 if (N0.getOpcode() == ISD::ADD &&
1203 N0.getOperand(1).getOpcode() == ISD::ADD &&
1204 N0.getOperand(1).getOperand(1) == N1)
1205 return DAG.getNode(ISD::ADD, VT, N0.getOperand(0),
1206 N0.getOperand(1).getOperand(0));
1207 // fold ((A-(B-C))-C) -> A-B
1208 if (N0.getOpcode() == ISD::SUB &&
1209 N0.getOperand(1).getOpcode() == ISD::SUB &&
1210 N0.getOperand(1).getOperand(1) == N1)
1211 return DAG.getNode(ISD::SUB, VT, N0.getOperand(0),
1212 N0.getOperand(1).getOperand(0));
1213 // fold (sub x, (select cc, 0, c)) -> (select cc, x, (sub, x, c))
1214 if (N1.getOpcode() == ISD::SELECT && N1.getNode()->hasOneUse()) {
1215 SDValue Result = combineSelectAndUse(N, N1, N0, DAG, TLI, LegalOperations);
1216 if (Result.getNode()) return Result;
1218 // If either operand of a sub is undef, the result is undef
1219 if (N0.getOpcode() == ISD::UNDEF)
1221 if (N1.getOpcode() == ISD::UNDEF)
1224 // If the relocation model supports it, consider symbol offsets.
1225 if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N0))
1226 if (!LegalOperations && TLI.isOffsetFoldingLegal(GA)) {
1227 // fold (sub Sym, c) -> Sym-c
1228 if (N1C && GA->getOpcode() == ISD::GlobalAddress)
1229 return DAG.getGlobalAddress(GA->getGlobal(), VT,
1231 (uint64_t)N1C->getSExtValue());
1232 // fold (sub Sym+c1, Sym+c2) -> c1-c2
1233 if (GlobalAddressSDNode *GB = dyn_cast<GlobalAddressSDNode>(N1))
1234 if (GA->getGlobal() == GB->getGlobal())
1235 return DAG.getConstant((uint64_t)GA->getOffset() - GB->getOffset(),
1242 SDValue DAGCombiner::visitMUL(SDNode *N) {
1243 SDValue N0 = N->getOperand(0);
1244 SDValue N1 = N->getOperand(1);
1245 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1246 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1247 MVT VT = N0.getValueType();
1250 if (VT.isVector()) {
1251 SDValue FoldedVOp = SimplifyVBinOp(N);
1252 if (FoldedVOp.getNode()) return FoldedVOp;
1255 // fold (mul x, undef) -> 0
1256 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
1257 return DAG.getConstant(0, VT);
1258 // fold (mul c1, c2) -> c1*c2
1260 return DAG.FoldConstantArithmetic(ISD::MUL, VT, N0C, N1C);
1261 // canonicalize constant to RHS
1263 return DAG.getNode(ISD::MUL, VT, N1, N0);
1264 // fold (mul x, 0) -> 0
1265 if (N1C && N1C->isNullValue())
1267 // fold (mul x, -1) -> 0-x
1268 if (N1C && N1C->isAllOnesValue())
1269 return DAG.getNode(ISD::SUB, VT, DAG.getConstant(0, VT), N0);
1270 // fold (mul x, (1 << c)) -> x << c
1271 if (N1C && N1C->getAPIntValue().isPowerOf2())
1272 return DAG.getNode(ISD::SHL, VT, N0,
1273 DAG.getConstant(N1C->getAPIntValue().logBase2(),
1274 TLI.getShiftAmountTy()));
1275 // fold (mul x, -(1 << c)) -> -(x << c) or (-x) << c
1276 if (N1C && isPowerOf2_64(-N1C->getSExtValue())) {
1277 // FIXME: If the input is something that is easily negated (e.g. a
1278 // single-use add), we should put the negate there.
1279 return DAG.getNode(ISD::SUB, VT, DAG.getConstant(0, VT),
1280 DAG.getNode(ISD::SHL, VT, N0,
1281 DAG.getConstant(Log2_64(-N1C->getSExtValue()),
1282 TLI.getShiftAmountTy())));
1285 // (mul (shl X, c1), c2) -> (mul X, c2 << c1)
1286 if (N1C && N0.getOpcode() == ISD::SHL &&
1287 isa<ConstantSDNode>(N0.getOperand(1))) {
1288 SDValue C3 = DAG.getNode(ISD::SHL, VT, N1, N0.getOperand(1));
1289 AddToWorkList(C3.getNode());
1290 return DAG.getNode(ISD::MUL, VT, N0.getOperand(0), C3);
1293 // Change (mul (shl X, C), Y) -> (shl (mul X, Y), C) when the shift has one
1296 SDValue Sh(0,0), Y(0,0);
1297 // Check for both (mul (shl X, C), Y) and (mul Y, (shl X, C)).
1298 if (N0.getOpcode() == ISD::SHL && isa<ConstantSDNode>(N0.getOperand(1)) &&
1299 N0.getNode()->hasOneUse()) {
1301 } else if (N1.getOpcode() == ISD::SHL &&
1302 isa<ConstantSDNode>(N1.getOperand(1)) &&
1303 N1.getNode()->hasOneUse()) {
1307 SDValue Mul = DAG.getNode(ISD::MUL, VT, Sh.getOperand(0), Y);
1308 return DAG.getNode(ISD::SHL, VT, Mul, Sh.getOperand(1));
1311 // fold (mul (add x, c1), c2) -> (add (mul x, c2), c1*c2)
1312 if (N1C && N0.getOpcode() == ISD::ADD && N0.getNode()->hasOneUse() &&
1313 isa<ConstantSDNode>(N0.getOperand(1))) {
1314 return DAG.getNode(ISD::ADD, VT,
1315 DAG.getNode(ISD::MUL, VT, N0.getOperand(0), N1),
1316 DAG.getNode(ISD::MUL, VT, N0.getOperand(1), N1));
1320 SDValue RMUL = ReassociateOps(ISD::MUL, N0, N1);
1321 if (RMUL.getNode() != 0)
1327 SDValue DAGCombiner::visitSDIV(SDNode *N) {
1328 SDValue N0 = N->getOperand(0);
1329 SDValue N1 = N->getOperand(1);
1330 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getNode());
1331 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
1332 MVT VT = N->getValueType(0);
1335 if (VT.isVector()) {
1336 SDValue FoldedVOp = SimplifyVBinOp(N);
1337 if (FoldedVOp.getNode()) return FoldedVOp;
1340 // fold (sdiv c1, c2) -> c1/c2
1341 if (N0C && N1C && !N1C->isNullValue())
1342 return DAG.FoldConstantArithmetic(ISD::SDIV, VT, N0C, N1C);
1343 // fold (sdiv X, 1) -> X
1344 if (N1C && N1C->getSExtValue() == 1LL)
1346 // fold (sdiv X, -1) -> 0-X
1347 if (N1C && N1C->isAllOnesValue())
1348 return DAG.getNode(ISD::SUB, VT, DAG.getConstant(0, VT), N0);
1349 // If we know the sign bits of both operands are zero, strength reduce to a
1350 // udiv instead. Handles (X&15) /s 4 -> X&15 >> 2
1351 if (!VT.isVector()) {
1352 if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
1353 return DAG.getNode(ISD::UDIV, N1.getValueType(), N0, N1);
1355 // fold (sdiv X, pow2) -> simple ops after legalize
1356 if (N1C && !N1C->isNullValue() && !TLI.isIntDivCheap() &&
1357 (isPowerOf2_64(N1C->getSExtValue()) ||
1358 isPowerOf2_64(-N1C->getSExtValue()))) {
1359 // If dividing by powers of two is cheap, then don't perform the following
1361 if (TLI.isPow2DivCheap())
1363 int64_t pow2 = N1C->getSExtValue();
1364 int64_t abs2 = pow2 > 0 ? pow2 : -pow2;
1365 unsigned lg2 = Log2_64(abs2);
1366 // Splat the sign bit into the register
1367 SDValue SGN = DAG.getNode(ISD::SRA, VT, N0,
1368 DAG.getConstant(VT.getSizeInBits()-1,
1369 TLI.getShiftAmountTy()));
1370 AddToWorkList(SGN.getNode());
1371 // Add (N0 < 0) ? abs2 - 1 : 0;
1372 SDValue SRL = DAG.getNode(ISD::SRL, VT, SGN,
1373 DAG.getConstant(VT.getSizeInBits()-lg2,
1374 TLI.getShiftAmountTy()));
1375 SDValue ADD = DAG.getNode(ISD::ADD, VT, N0, SRL);
1376 AddToWorkList(SRL.getNode());
1377 AddToWorkList(ADD.getNode()); // Divide by pow2
1378 SDValue SRA = DAG.getNode(ISD::SRA, VT, ADD,
1379 DAG.getConstant(lg2, TLI.getShiftAmountTy()));
1380 // If we're dividing by a positive value, we're done. Otherwise, we must
1381 // negate the result.
1384 AddToWorkList(SRA.getNode());
1385 return DAG.getNode(ISD::SUB, VT, DAG.getConstant(0, VT), SRA);
1387 // if integer divide is expensive and we satisfy the requirements, emit an
1388 // alternate sequence.
1389 if (N1C && (N1C->getSExtValue() < -1 || N1C->getSExtValue() > 1) &&
1390 !TLI.isIntDivCheap()) {
1391 SDValue Op = BuildSDIV(N);
1392 if (Op.getNode()) return Op;
1396 if (N0.getOpcode() == ISD::UNDEF)
1397 return DAG.getConstant(0, VT);
1398 // X / undef -> undef
1399 if (N1.getOpcode() == ISD::UNDEF)
1405 SDValue DAGCombiner::visitUDIV(SDNode *N) {
1406 SDValue N0 = N->getOperand(0);
1407 SDValue N1 = N->getOperand(1);
1408 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getNode());
1409 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
1410 MVT VT = N->getValueType(0);
1413 if (VT.isVector()) {
1414 SDValue FoldedVOp = SimplifyVBinOp(N);
1415 if (FoldedVOp.getNode()) return FoldedVOp;
1418 // fold (udiv c1, c2) -> c1/c2
1419 if (N0C && N1C && !N1C->isNullValue())
1420 return DAG.FoldConstantArithmetic(ISD::UDIV, VT, N0C, N1C);
1421 // fold (udiv x, (1 << c)) -> x >>u c
1422 if (N1C && N1C->getAPIntValue().isPowerOf2())
1423 return DAG.getNode(ISD::SRL, VT, N0,
1424 DAG.getConstant(N1C->getAPIntValue().logBase2(),
1425 TLI.getShiftAmountTy()));
1426 // fold (udiv x, (shl c, y)) -> x >>u (log2(c)+y) iff c is power of 2
1427 if (N1.getOpcode() == ISD::SHL) {
1428 if (ConstantSDNode *SHC = dyn_cast<ConstantSDNode>(N1.getOperand(0))) {
1429 if (SHC->getAPIntValue().isPowerOf2()) {
1430 MVT ADDVT = N1.getOperand(1).getValueType();
1431 SDValue Add = DAG.getNode(ISD::ADD, ADDVT, N1.getOperand(1),
1432 DAG.getConstant(SHC->getAPIntValue()
1435 AddToWorkList(Add.getNode());
1436 return DAG.getNode(ISD::SRL, VT, N0, Add);
1440 // fold (udiv x, c) -> alternate
1441 if (N1C && !N1C->isNullValue() && !TLI.isIntDivCheap()) {
1442 SDValue Op = BuildUDIV(N);
1443 if (Op.getNode()) return Op;
1447 if (N0.getOpcode() == ISD::UNDEF)
1448 return DAG.getConstant(0, VT);
1449 // X / undef -> undef
1450 if (N1.getOpcode() == ISD::UNDEF)
1456 SDValue DAGCombiner::visitSREM(SDNode *N) {
1457 SDValue N0 = N->getOperand(0);
1458 SDValue N1 = N->getOperand(1);
1459 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1460 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1461 MVT VT = N->getValueType(0);
1463 // fold (srem c1, c2) -> c1%c2
1464 if (N0C && N1C && !N1C->isNullValue())
1465 return DAG.FoldConstantArithmetic(ISD::SREM, VT, N0C, N1C);
1466 // If we know the sign bits of both operands are zero, strength reduce to a
1467 // urem instead. Handles (X & 0x0FFFFFFF) %s 16 -> X&15
1468 if (!VT.isVector()) {
1469 if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
1470 return DAG.getNode(ISD::UREM, VT, N0, N1);
1473 // If X/C can be simplified by the division-by-constant logic, lower
1474 // X%C to the equivalent of X-X/C*C.
1475 if (N1C && !N1C->isNullValue()) {
1476 SDValue Div = DAG.getNode(ISD::SDIV, VT, N0, N1);
1477 AddToWorkList(Div.getNode());
1478 SDValue OptimizedDiv = combine(Div.getNode());
1479 if (OptimizedDiv.getNode() && OptimizedDiv.getNode() != Div.getNode()) {
1480 SDValue Mul = DAG.getNode(ISD::MUL, VT, OptimizedDiv, N1);
1481 SDValue Sub = DAG.getNode(ISD::SUB, VT, N0, Mul);
1482 AddToWorkList(Mul.getNode());
1488 if (N0.getOpcode() == ISD::UNDEF)
1489 return DAG.getConstant(0, VT);
1490 // X % undef -> undef
1491 if (N1.getOpcode() == ISD::UNDEF)
1497 SDValue DAGCombiner::visitUREM(SDNode *N) {
1498 SDValue N0 = N->getOperand(0);
1499 SDValue N1 = N->getOperand(1);
1500 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1501 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1502 MVT VT = N->getValueType(0);
1504 // fold (urem c1, c2) -> c1%c2
1505 if (N0C && N1C && !N1C->isNullValue())
1506 return DAG.FoldConstantArithmetic(ISD::UREM, VT, N0C, N1C);
1507 // fold (urem x, pow2) -> (and x, pow2-1)
1508 if (N1C && !N1C->isNullValue() && N1C->getAPIntValue().isPowerOf2())
1509 return DAG.getNode(ISD::AND, VT, N0,
1510 DAG.getConstant(N1C->getAPIntValue()-1,VT));
1511 // fold (urem x, (shl pow2, y)) -> (and x, (add (shl pow2, y), -1))
1512 if (N1.getOpcode() == ISD::SHL) {
1513 if (ConstantSDNode *SHC = dyn_cast<ConstantSDNode>(N1.getOperand(0))) {
1514 if (SHC->getAPIntValue().isPowerOf2()) {
1516 DAG.getNode(ISD::ADD, VT, N1,
1517 DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()),
1519 AddToWorkList(Add.getNode());
1520 return DAG.getNode(ISD::AND, VT, N0, Add);
1525 // If X/C can be simplified by the division-by-constant logic, lower
1526 // X%C to the equivalent of X-X/C*C.
1527 if (N1C && !N1C->isNullValue()) {
1528 SDValue Div = DAG.getNode(ISD::UDIV, VT, N0, N1);
1529 AddToWorkList(Div.getNode());
1530 SDValue OptimizedDiv = combine(Div.getNode());
1531 if (OptimizedDiv.getNode() && OptimizedDiv.getNode() != Div.getNode()) {
1532 SDValue Mul = DAG.getNode(ISD::MUL, VT, OptimizedDiv, N1);
1533 SDValue Sub = DAG.getNode(ISD::SUB, VT, N0, Mul);
1534 AddToWorkList(Mul.getNode());
1540 if (N0.getOpcode() == ISD::UNDEF)
1541 return DAG.getConstant(0, VT);
1542 // X % undef -> undef
1543 if (N1.getOpcode() == ISD::UNDEF)
1549 SDValue DAGCombiner::visitMULHS(SDNode *N) {
1550 SDValue N0 = N->getOperand(0);
1551 SDValue N1 = N->getOperand(1);
1552 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1553 MVT VT = N->getValueType(0);
1555 // fold (mulhs x, 0) -> 0
1556 if (N1C && N1C->isNullValue())
1558 // fold (mulhs x, 1) -> (sra x, size(x)-1)
1559 if (N1C && N1C->getAPIntValue() == 1)
1560 return DAG.getNode(ISD::SRA, N0.getValueType(), N0,
1561 DAG.getConstant(N0.getValueType().getSizeInBits()-1,
1562 TLI.getShiftAmountTy()));
1563 // fold (mulhs x, undef) -> 0
1564 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
1565 return DAG.getConstant(0, VT);
1570 SDValue DAGCombiner::visitMULHU(SDNode *N) {
1571 SDValue N0 = N->getOperand(0);
1572 SDValue N1 = N->getOperand(1);
1573 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1574 MVT VT = N->getValueType(0);
1576 // fold (mulhu x, 0) -> 0
1577 if (N1C && N1C->isNullValue())
1579 // fold (mulhu x, 1) -> 0
1580 if (N1C && N1C->getAPIntValue() == 1)
1581 return DAG.getConstant(0, N0.getValueType());
1582 // fold (mulhu x, undef) -> 0
1583 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
1584 return DAG.getConstant(0, VT);
1589 /// SimplifyNodeWithTwoResults - Perform optimizations common to nodes that
1590 /// compute two values. LoOp and HiOp give the opcodes for the two computations
1591 /// that are being performed. Return true if a simplification was made.
1593 SDValue DAGCombiner::SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp,
1595 // If the high half is not needed, just compute the low half.
1596 bool HiExists = N->hasAnyUseOfValue(1);
1598 (!LegalOperations ||
1599 TLI.isOperationLegal(LoOp, N->getValueType(0)))) {
1600 SDValue Res = DAG.getNode(LoOp, N->getValueType(0), N->op_begin(),
1601 N->getNumOperands());
1602 return CombineTo(N, Res, Res);
1605 // If the low half is not needed, just compute the high half.
1606 bool LoExists = N->hasAnyUseOfValue(0);
1608 (!LegalOperations ||
1609 TLI.isOperationLegal(HiOp, N->getValueType(1)))) {
1610 SDValue Res = DAG.getNode(HiOp, N->getValueType(1), N->op_begin(),
1611 N->getNumOperands());
1612 return CombineTo(N, Res, Res);
1615 // If both halves are used, return as it is.
1616 if (LoExists && HiExists)
1619 // If the two computed results can be simplified separately, separate them.
1621 SDValue Lo = DAG.getNode(LoOp, N->getValueType(0),
1622 N->op_begin(), N->getNumOperands());
1623 AddToWorkList(Lo.getNode());
1624 SDValue LoOpt = combine(Lo.getNode());
1625 if (LoOpt.getNode() && LoOpt.getNode() != Lo.getNode() &&
1626 (!LegalOperations ||
1627 TLI.isOperationLegal(LoOpt.getOpcode(), LoOpt.getValueType())))
1628 return CombineTo(N, LoOpt, LoOpt);
1632 SDValue Hi = DAG.getNode(HiOp, N->getValueType(1),
1633 N->op_begin(), N->getNumOperands());
1634 AddToWorkList(Hi.getNode());
1635 SDValue HiOpt = combine(Hi.getNode());
1636 if (HiOpt.getNode() && HiOpt != Hi &&
1637 (!LegalOperations ||
1638 TLI.isOperationLegal(HiOpt.getOpcode(), HiOpt.getValueType())))
1639 return CombineTo(N, HiOpt, HiOpt);
1644 SDValue DAGCombiner::visitSMUL_LOHI(SDNode *N) {
1645 SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHS);
1646 if (Res.getNode()) return Res;
1651 SDValue DAGCombiner::visitUMUL_LOHI(SDNode *N) {
1652 SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHU);
1653 if (Res.getNode()) return Res;
1658 SDValue DAGCombiner::visitSDIVREM(SDNode *N) {
1659 SDValue Res = SimplifyNodeWithTwoResults(N, ISD::SDIV, ISD::SREM);
1660 if (Res.getNode()) return Res;
1665 SDValue DAGCombiner::visitUDIVREM(SDNode *N) {
1666 SDValue Res = SimplifyNodeWithTwoResults(N, ISD::UDIV, ISD::UREM);
1667 if (Res.getNode()) return Res;
1672 /// SimplifyBinOpWithSameOpcodeHands - If this is a binary operator with
1673 /// two operands of the same opcode, try to simplify it.
1674 SDValue DAGCombiner::SimplifyBinOpWithSameOpcodeHands(SDNode *N) {
1675 SDValue N0 = N->getOperand(0), N1 = N->getOperand(1);
1676 MVT VT = N0.getValueType();
1677 assert(N0.getOpcode() == N1.getOpcode() && "Bad input!");
1679 // For each of OP in AND/OR/XOR:
1680 // fold (OP (zext x), (zext y)) -> (zext (OP x, y))
1681 // fold (OP (sext x), (sext y)) -> (sext (OP x, y))
1682 // fold (OP (aext x), (aext y)) -> (aext (OP x, y))
1683 // fold (OP (trunc x), (trunc y)) -> (trunc (OP x, y))
1684 if ((N0.getOpcode() == ISD::ZERO_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND||
1685 N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::TRUNCATE) &&
1686 N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType()) {
1687 SDValue ORNode = DAG.getNode(N->getOpcode(),
1688 N0.getOperand(0).getValueType(),
1689 N0.getOperand(0), N1.getOperand(0));
1690 AddToWorkList(ORNode.getNode());
1691 return DAG.getNode(N0.getOpcode(), VT, ORNode);
1694 // For each of OP in SHL/SRL/SRA/AND...
1695 // fold (and (OP x, z), (OP y, z)) -> (OP (and x, y), z)
1696 // fold (or (OP x, z), (OP y, z)) -> (OP (or x, y), z)
1697 // fold (xor (OP x, z), (OP y, z)) -> (OP (xor x, y), z)
1698 if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL ||
1699 N0.getOpcode() == ISD::SRA || N0.getOpcode() == ISD::AND) &&
1700 N0.getOperand(1) == N1.getOperand(1)) {
1701 SDValue ORNode = DAG.getNode(N->getOpcode(),
1702 N0.getOperand(0).getValueType(),
1703 N0.getOperand(0), N1.getOperand(0));
1704 AddToWorkList(ORNode.getNode());
1705 return DAG.getNode(N0.getOpcode(), VT, ORNode, N0.getOperand(1));
1711 SDValue DAGCombiner::visitAND(SDNode *N) {
1712 SDValue N0 = N->getOperand(0);
1713 SDValue N1 = N->getOperand(1);
1714 SDValue LL, LR, RL, RR, CC0, CC1;
1715 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1716 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1717 MVT VT = N1.getValueType();
1718 unsigned BitWidth = VT.getSizeInBits();
1721 if (VT.isVector()) {
1722 SDValue FoldedVOp = SimplifyVBinOp(N);
1723 if (FoldedVOp.getNode()) return FoldedVOp;
1726 // fold (and x, undef) -> 0
1727 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
1728 return DAG.getConstant(0, VT);
1729 // fold (and c1, c2) -> c1&c2
1731 return DAG.FoldConstantArithmetic(ISD::AND, VT, N0C, N1C);
1732 // canonicalize constant to RHS
1734 return DAG.getNode(ISD::AND, VT, N1, N0);
1735 // fold (and x, -1) -> x
1736 if (N1C && N1C->isAllOnesValue())
1738 // if (and x, c) is known to be zero, return 0
1739 if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0),
1740 APInt::getAllOnesValue(BitWidth)))
1741 return DAG.getConstant(0, VT);
1743 SDValue RAND = ReassociateOps(ISD::AND, N0, N1);
1744 if (RAND.getNode() != 0)
1746 // fold (and (or x, 0xFFFF), 0xFF) -> 0xFF
1747 if (N1C && N0.getOpcode() == ISD::OR)
1748 if (ConstantSDNode *ORI = dyn_cast<ConstantSDNode>(N0.getOperand(1)))
1749 if ((ORI->getAPIntValue() & N1C->getAPIntValue()) == N1C->getAPIntValue())
1751 // fold (and (any_ext V), c) -> (zero_ext V) if 'and' only clears top bits.
1752 if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
1753 SDValue N0Op0 = N0.getOperand(0);
1754 APInt Mask = ~N1C->getAPIntValue();
1755 Mask.trunc(N0Op0.getValueSizeInBits());
1756 if (DAG.MaskedValueIsZero(N0Op0, Mask)) {
1757 SDValue Zext = DAG.getNode(ISD::ZERO_EXTEND, N0.getValueType(),
1760 // Replace uses of the AND with uses of the Zero extend node.
1763 // We actually want to replace all uses of the any_extend with the
1764 // zero_extend, to avoid duplicating things. This will later cause this
1765 // AND to be folded.
1766 CombineTo(N0.getNode(), Zext);
1767 return SDValue(N, 0); // Return N so it doesn't get rechecked!
1770 // fold (and (setcc x), (setcc y)) -> (setcc (and x, y))
1771 if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){
1772 ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get();
1773 ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get();
1775 if (LR == RR && isa<ConstantSDNode>(LR) && Op0 == Op1 &&
1776 LL.getValueType().isInteger()) {
1777 // fold (X == 0) & (Y == 0) -> (X|Y == 0)
1778 if (cast<ConstantSDNode>(LR)->isNullValue() && Op1 == ISD::SETEQ) {
1779 SDValue ORNode = DAG.getNode(ISD::OR, LR.getValueType(), LL, RL);
1780 AddToWorkList(ORNode.getNode());
1781 return DAG.getSetCC(VT, ORNode, LR, Op1);
1783 // fold (X == -1) & (Y == -1) -> (X&Y == -1)
1784 if (cast<ConstantSDNode>(LR)->isAllOnesValue() && Op1 == ISD::SETEQ) {
1785 SDValue ANDNode = DAG.getNode(ISD::AND, LR.getValueType(), LL, RL);
1786 AddToWorkList(ANDNode.getNode());
1787 return DAG.getSetCC(VT, ANDNode, LR, Op1);
1789 // fold (X > -1) & (Y > -1) -> (X|Y > -1)
1790 if (cast<ConstantSDNode>(LR)->isAllOnesValue() && Op1 == ISD::SETGT) {
1791 SDValue ORNode = DAG.getNode(ISD::OR, LR.getValueType(), LL, RL);
1792 AddToWorkList(ORNode.getNode());
1793 return DAG.getSetCC(VT, ORNode, LR, Op1);
1796 // canonicalize equivalent to ll == rl
1797 if (LL == RR && LR == RL) {
1798 Op1 = ISD::getSetCCSwappedOperands(Op1);
1801 if (LL == RL && LR == RR) {
1802 bool isInteger = LL.getValueType().isInteger();
1803 ISD::CondCode Result = ISD::getSetCCAndOperation(Op0, Op1, isInteger);
1804 if (Result != ISD::SETCC_INVALID &&
1805 (!LegalOperations || TLI.isCondCodeLegal(Result, LL.getValueType())))
1806 return DAG.getSetCC(N0.getValueType(), LL, LR, Result);
1810 // Simplify: and (op x...), (op y...) -> (op (and x, y))
1811 if (N0.getOpcode() == N1.getOpcode()) {
1812 SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
1813 if (Tmp.getNode()) return Tmp;
1816 // fold (and (sign_extend_inreg x, i16 to i32), 1) -> (and x, 1)
1817 // fold (and (sra)) -> (and (srl)) when possible.
1818 if (!VT.isVector() &&
1819 SimplifyDemandedBits(SDValue(N, 0)))
1820 return SDValue(N, 0);
1821 // fold (zext_inreg (extload x)) -> (zextload x)
1822 if (ISD::isEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode())) {
1823 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
1824 MVT EVT = LN0->getMemoryVT();
1825 // If we zero all the possible extended bits, then we can turn this into
1826 // a zextload if we are running before legalize or the operation is legal.
1827 unsigned BitWidth = N1.getValueSizeInBits();
1828 if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth,
1829 BitWidth - EVT.getSizeInBits())) &&
1830 ((!LegalOperations && !LN0->isVolatile()) ||
1831 TLI.isLoadExtLegal(ISD::ZEXTLOAD, EVT))) {
1832 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, VT, LN0->getChain(),
1833 LN0->getBasePtr(), LN0->getSrcValue(),
1834 LN0->getSrcValueOffset(), EVT,
1835 LN0->isVolatile(), LN0->getAlignment());
1837 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
1838 return SDValue(N, 0); // Return N so it doesn't get rechecked!
1841 // fold (zext_inreg (sextload x)) -> (zextload x) iff load has one use
1842 if (ISD::isSEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
1844 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
1845 MVT EVT = LN0->getMemoryVT();
1846 // If we zero all the possible extended bits, then we can turn this into
1847 // a zextload if we are running before legalize or the operation is legal.
1848 unsigned BitWidth = N1.getValueSizeInBits();
1849 if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth,
1850 BitWidth - EVT.getSizeInBits())) &&
1851 ((!LegalOperations && !LN0->isVolatile()) ||
1852 TLI.isLoadExtLegal(ISD::ZEXTLOAD, EVT))) {
1853 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, VT, LN0->getChain(),
1854 LN0->getBasePtr(), LN0->getSrcValue(),
1855 LN0->getSrcValueOffset(), EVT,
1856 LN0->isVolatile(), LN0->getAlignment());
1858 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
1859 return SDValue(N, 0); // Return N so it doesn't get rechecked!
1863 // fold (and (load x), 255) -> (zextload x, i8)
1864 // fold (and (extload x, i16), 255) -> (zextload x, i8)
1865 if (N1C && N0.getOpcode() == ISD::LOAD) {
1866 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
1867 if (LN0->getExtensionType() != ISD::SEXTLOAD &&
1868 LN0->isUnindexed() && N0.hasOneUse() &&
1869 // Do not change the width of a volatile load.
1870 !LN0->isVolatile()) {
1871 MVT EVT = MVT::Other;
1872 uint32_t ActiveBits = N1C->getAPIntValue().getActiveBits();
1873 if (ActiveBits > 0 && APIntOps::isMask(ActiveBits, N1C->getAPIntValue()))
1874 EVT = MVT::getIntegerVT(ActiveBits);
1876 MVT LoadedVT = LN0->getMemoryVT();
1877 // Do not generate loads of non-round integer types since these can
1878 // be expensive (and would be wrong if the type is not byte sized).
1879 if (EVT != MVT::Other && LoadedVT.bitsGT(EVT) && EVT.isRound() &&
1880 (!LegalOperations || TLI.isLoadExtLegal(ISD::ZEXTLOAD, EVT))) {
1881 MVT PtrType = N0.getOperand(1).getValueType();
1882 // For big endian targets, we need to add an offset to the pointer to
1883 // load the correct bytes. For little endian systems, we merely need to
1884 // read fewer bytes from the same pointer.
1885 unsigned LVTStoreBytes = LoadedVT.getStoreSizeInBits()/8;
1886 unsigned EVTStoreBytes = EVT.getStoreSizeInBits()/8;
1887 unsigned PtrOff = LVTStoreBytes - EVTStoreBytes;
1888 unsigned Alignment = LN0->getAlignment();
1889 SDValue NewPtr = LN0->getBasePtr();
1890 if (TLI.isBigEndian()) {
1891 NewPtr = DAG.getNode(ISD::ADD, PtrType, NewPtr,
1892 DAG.getConstant(PtrOff, PtrType));
1893 Alignment = MinAlign(Alignment, PtrOff);
1895 AddToWorkList(NewPtr.getNode());
1897 DAG.getExtLoad(ISD::ZEXTLOAD, VT, LN0->getChain(), NewPtr,
1898 LN0->getSrcValue(), LN0->getSrcValueOffset(), EVT,
1899 LN0->isVolatile(), Alignment);
1901 CombineTo(N0.getNode(), Load, Load.getValue(1));
1902 return SDValue(N, 0); // Return N so it doesn't get rechecked!
1910 SDValue DAGCombiner::visitOR(SDNode *N) {
1911 SDValue N0 = N->getOperand(0);
1912 SDValue N1 = N->getOperand(1);
1913 SDValue LL, LR, RL, RR, CC0, CC1;
1914 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1915 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1916 MVT VT = N1.getValueType();
1919 if (VT.isVector()) {
1920 SDValue FoldedVOp = SimplifyVBinOp(N);
1921 if (FoldedVOp.getNode()) return FoldedVOp;
1924 // fold (or x, undef) -> -1
1925 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
1926 return DAG.getConstant(~0ULL, VT);
1927 // fold (or c1, c2) -> c1|c2
1929 return DAG.FoldConstantArithmetic(ISD::OR, VT, N0C, N1C);
1930 // canonicalize constant to RHS
1932 return DAG.getNode(ISD::OR, VT, N1, N0);
1933 // fold (or x, 0) -> x
1934 if (N1C && N1C->isNullValue())
1936 // fold (or x, -1) -> -1
1937 if (N1C && N1C->isAllOnesValue())
1939 // fold (or x, c) -> c iff (x & ~c) == 0
1940 if (N1C && DAG.MaskedValueIsZero(N0, ~N1C->getAPIntValue()))
1943 SDValue ROR = ReassociateOps(ISD::OR, N0, N1);
1944 if (ROR.getNode() != 0)
1946 // Canonicalize (or (and X, c1), c2) -> (and (or X, c2), c1|c2)
1947 if (N1C && N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() &&
1948 isa<ConstantSDNode>(N0.getOperand(1))) {
1949 ConstantSDNode *C1 = cast<ConstantSDNode>(N0.getOperand(1));
1950 return DAG.getNode(ISD::AND, VT, DAG.getNode(ISD::OR, VT, N0.getOperand(0),
1952 DAG.getConstant(N1C->getAPIntValue() |
1953 C1->getAPIntValue(), VT));
1955 // fold (or (setcc x), (setcc y)) -> (setcc (or x, y))
1956 if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){
1957 ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get();
1958 ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get();
1960 if (LR == RR && isa<ConstantSDNode>(LR) && Op0 == Op1 &&
1961 LL.getValueType().isInteger()) {
1962 // fold (X != 0) | (Y != 0) -> (X|Y != 0)
1963 // fold (X < 0) | (Y < 0) -> (X|Y < 0)
1964 if (cast<ConstantSDNode>(LR)->isNullValue() &&
1965 (Op1 == ISD::SETNE || Op1 == ISD::SETLT)) {
1966 SDValue ORNode = DAG.getNode(ISD::OR, LR.getValueType(), LL, RL);
1967 AddToWorkList(ORNode.getNode());
1968 return DAG.getSetCC(VT, ORNode, LR, Op1);
1970 // fold (X != -1) | (Y != -1) -> (X&Y != -1)
1971 // fold (X > -1) | (Y > -1) -> (X&Y > -1)
1972 if (cast<ConstantSDNode>(LR)->isAllOnesValue() &&
1973 (Op1 == ISD::SETNE || Op1 == ISD::SETGT)) {
1974 SDValue ANDNode = DAG.getNode(ISD::AND, LR.getValueType(), LL, RL);
1975 AddToWorkList(ANDNode.getNode());
1976 return DAG.getSetCC(VT, ANDNode, LR, Op1);
1979 // canonicalize equivalent to ll == rl
1980 if (LL == RR && LR == RL) {
1981 Op1 = ISD::getSetCCSwappedOperands(Op1);
1984 if (LL == RL && LR == RR) {
1985 bool isInteger = LL.getValueType().isInteger();
1986 ISD::CondCode Result = ISD::getSetCCOrOperation(Op0, Op1, isInteger);
1987 if (Result != ISD::SETCC_INVALID &&
1988 (!LegalOperations || TLI.isCondCodeLegal(Result, LL.getValueType())))
1989 return DAG.getSetCC(N0.getValueType(), LL, LR, Result);
1993 // Simplify: or (op x...), (op y...) -> (op (or x, y))
1994 if (N0.getOpcode() == N1.getOpcode()) {
1995 SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
1996 if (Tmp.getNode()) return Tmp;
1999 // (X & C1) | (Y & C2) -> (X|Y) & C3 if possible.
2000 if (N0.getOpcode() == ISD::AND &&
2001 N1.getOpcode() == ISD::AND &&
2002 N0.getOperand(1).getOpcode() == ISD::Constant &&
2003 N1.getOperand(1).getOpcode() == ISD::Constant &&
2004 // Don't increase # computations.
2005 (N0.getNode()->hasOneUse() || N1.getNode()->hasOneUse())) {
2006 // We can only do this xform if we know that bits from X that are set in C2
2007 // but not in C1 are already zero. Likewise for Y.
2008 const APInt &LHSMask =
2009 cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
2010 const APInt &RHSMask =
2011 cast<ConstantSDNode>(N1.getOperand(1))->getAPIntValue();
2013 if (DAG.MaskedValueIsZero(N0.getOperand(0), RHSMask&~LHSMask) &&
2014 DAG.MaskedValueIsZero(N1.getOperand(0), LHSMask&~RHSMask)) {
2015 SDValue X =DAG.getNode(ISD::OR, VT, N0.getOperand(0), N1.getOperand(0));
2016 return DAG.getNode(ISD::AND, VT, X, DAG.getConstant(LHSMask|RHSMask, VT));
2021 // See if this is some rotate idiom.
2022 if (SDNode *Rot = MatchRotate(N0, N1))
2023 return SDValue(Rot, 0);
2029 /// MatchRotateHalf - Match "(X shl/srl V1) & V2" where V2 may not be present.
2030 static bool MatchRotateHalf(SDValue Op, SDValue &Shift, SDValue &Mask) {
2031 if (Op.getOpcode() == ISD::AND) {
2032 if (isa<ConstantSDNode>(Op.getOperand(1))) {
2033 Mask = Op.getOperand(1);
2034 Op = Op.getOperand(0);
2040 if (Op.getOpcode() == ISD::SRL || Op.getOpcode() == ISD::SHL) {
2048 // MatchRotate - Handle an 'or' of two operands. If this is one of the many
2049 // idioms for rotate, and if the target supports rotation instructions, generate
2051 SDNode *DAGCombiner::MatchRotate(SDValue LHS, SDValue RHS) {
2052 // Must be a legal type. Expanded 'n promoted things won't work with rotates.
2053 MVT VT = LHS.getValueType();
2054 if (!TLI.isTypeLegal(VT)) return 0;
2056 // The target must have at least one rotate flavor.
2057 bool HasROTL = TLI.isOperationLegal(ISD::ROTL, VT);
2058 bool HasROTR = TLI.isOperationLegal(ISD::ROTR, VT);
2059 if (!HasROTL && !HasROTR) return 0;
2061 // Match "(X shl/srl V1) & V2" where V2 may not be present.
2062 SDValue LHSShift; // The shift.
2063 SDValue LHSMask; // AND value if any.
2064 if (!MatchRotateHalf(LHS, LHSShift, LHSMask))
2065 return 0; // Not part of a rotate.
2067 SDValue RHSShift; // The shift.
2068 SDValue RHSMask; // AND value if any.
2069 if (!MatchRotateHalf(RHS, RHSShift, RHSMask))
2070 return 0; // Not part of a rotate.
2072 if (LHSShift.getOperand(0) != RHSShift.getOperand(0))
2073 return 0; // Not shifting the same value.
2075 if (LHSShift.getOpcode() == RHSShift.getOpcode())
2076 return 0; // Shifts must disagree.
2078 // Canonicalize shl to left side in a shl/srl pair.
2079 if (RHSShift.getOpcode() == ISD::SHL) {
2080 std::swap(LHS, RHS);
2081 std::swap(LHSShift, RHSShift);
2082 std::swap(LHSMask , RHSMask );
2085 unsigned OpSizeInBits = VT.getSizeInBits();
2086 SDValue LHSShiftArg = LHSShift.getOperand(0);
2087 SDValue LHSShiftAmt = LHSShift.getOperand(1);
2088 SDValue RHSShiftAmt = RHSShift.getOperand(1);
2090 // fold (or (shl x, C1), (srl x, C2)) -> (rotl x, C1)
2091 // fold (or (shl x, C1), (srl x, C2)) -> (rotr x, C2)
2092 if (LHSShiftAmt.getOpcode() == ISD::Constant &&
2093 RHSShiftAmt.getOpcode() == ISD::Constant) {
2094 uint64_t LShVal = cast<ConstantSDNode>(LHSShiftAmt)->getZExtValue();
2095 uint64_t RShVal = cast<ConstantSDNode>(RHSShiftAmt)->getZExtValue();
2096 if ((LShVal + RShVal) != OpSizeInBits)
2101 Rot = DAG.getNode(ISD::ROTL, VT, LHSShiftArg, LHSShiftAmt);
2103 Rot = DAG.getNode(ISD::ROTR, VT, LHSShiftArg, RHSShiftAmt);
2105 // If there is an AND of either shifted operand, apply it to the result.
2106 if (LHSMask.getNode() || RHSMask.getNode()) {
2107 APInt Mask = APInt::getAllOnesValue(OpSizeInBits);
2109 if (LHSMask.getNode()) {
2110 APInt RHSBits = APInt::getLowBitsSet(OpSizeInBits, LShVal);
2111 Mask &= cast<ConstantSDNode>(LHSMask)->getAPIntValue() | RHSBits;
2113 if (RHSMask.getNode()) {
2114 APInt LHSBits = APInt::getHighBitsSet(OpSizeInBits, RShVal);
2115 Mask &= cast<ConstantSDNode>(RHSMask)->getAPIntValue() | LHSBits;
2118 Rot = DAG.getNode(ISD::AND, VT, Rot, DAG.getConstant(Mask, VT));
2121 return Rot.getNode();
2124 // If there is a mask here, and we have a variable shift, we can't be sure
2125 // that we're masking out the right stuff.
2126 if (LHSMask.getNode() || RHSMask.getNode())
2129 // fold (or (shl x, y), (srl x, (sub 32, y))) -> (rotl x, y)
2130 // fold (or (shl x, y), (srl x, (sub 32, y))) -> (rotr x, (sub 32, y))
2131 if (RHSShiftAmt.getOpcode() == ISD::SUB &&
2132 LHSShiftAmt == RHSShiftAmt.getOperand(1)) {
2133 if (ConstantSDNode *SUBC =
2134 dyn_cast<ConstantSDNode>(RHSShiftAmt.getOperand(0))) {
2135 if (SUBC->getAPIntValue() == OpSizeInBits) {
2137 return DAG.getNode(ISD::ROTL, VT, LHSShiftArg, LHSShiftAmt).getNode();
2139 return DAG.getNode(ISD::ROTR, VT, LHSShiftArg, RHSShiftAmt).getNode();
2144 // fold (or (shl x, (sub 32, y)), (srl x, r)) -> (rotr x, y)
2145 // fold (or (shl x, (sub 32, y)), (srl x, r)) -> (rotl x, (sub 32, y))
2146 if (LHSShiftAmt.getOpcode() == ISD::SUB &&
2147 RHSShiftAmt == LHSShiftAmt.getOperand(1)) {
2148 if (ConstantSDNode *SUBC =
2149 dyn_cast<ConstantSDNode>(LHSShiftAmt.getOperand(0))) {
2150 if (SUBC->getAPIntValue() == OpSizeInBits) {
2152 return DAG.getNode(ISD::ROTR, VT, LHSShiftArg, RHSShiftAmt).getNode();
2154 return DAG.getNode(ISD::ROTL, VT, LHSShiftArg, LHSShiftAmt).getNode();
2159 // Look for sign/zext/any-extended or truncate cases:
2160 if ((LHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND
2161 || LHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND
2162 || LHSShiftAmt.getOpcode() == ISD::ANY_EXTEND
2163 || LHSShiftAmt.getOpcode() == ISD::TRUNCATE) &&
2164 (RHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND
2165 || RHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND
2166 || RHSShiftAmt.getOpcode() == ISD::ANY_EXTEND
2167 || RHSShiftAmt.getOpcode() == ISD::TRUNCATE)) {
2168 SDValue LExtOp0 = LHSShiftAmt.getOperand(0);
2169 SDValue RExtOp0 = RHSShiftAmt.getOperand(0);
2170 if (RExtOp0.getOpcode() == ISD::SUB &&
2171 RExtOp0.getOperand(1) == LExtOp0) {
2172 // fold (or (shl x, (*ext y)), (srl x, (*ext (sub 32, y)))) ->
2174 // fold (or (shl x, (*ext y)), (srl x, (*ext (sub 32, y)))) ->
2175 // (rotr x, (sub 32, y))
2176 if (ConstantSDNode *SUBC =
2177 dyn_cast<ConstantSDNode>(RExtOp0.getOperand(0))) {
2178 if (SUBC->getAPIntValue() == OpSizeInBits) {
2179 return DAG.getNode(HasROTL ? ISD::ROTL : ISD::ROTR, VT, LHSShiftArg,
2180 HasROTL ? LHSShiftAmt : RHSShiftAmt).getNode();
2183 } else if (LExtOp0.getOpcode() == ISD::SUB &&
2184 RExtOp0 == LExtOp0.getOperand(1)) {
2185 // fold (or (shl x, (*ext (sub 32, y))), (srl x, (*ext y))) ->
2187 // fold (or (shl x, (*ext (sub 32, y))), (srl x, (*ext y))) ->
2188 // (rotl x, (sub 32, y))
2189 if (ConstantSDNode *SUBC =
2190 dyn_cast<ConstantSDNode>(LExtOp0.getOperand(0))) {
2191 if (SUBC->getAPIntValue() == OpSizeInBits) {
2192 return DAG.getNode(HasROTR ? ISD::ROTR : ISD::ROTL, VT, LHSShiftArg,
2193 HasROTR ? RHSShiftAmt : LHSShiftAmt).getNode();
2203 SDValue DAGCombiner::visitXOR(SDNode *N) {
2204 SDValue N0 = N->getOperand(0);
2205 SDValue N1 = N->getOperand(1);
2206 SDValue LHS, RHS, CC;
2207 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
2208 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2209 MVT VT = N0.getValueType();
2212 if (VT.isVector()) {
2213 SDValue FoldedVOp = SimplifyVBinOp(N);
2214 if (FoldedVOp.getNode()) return FoldedVOp;
2217 // fold (xor undef, undef) -> 0. This is a common idiom (misuse).
2218 if (N0.getOpcode() == ISD::UNDEF && N1.getOpcode() == ISD::UNDEF)
2219 return DAG.getConstant(0, VT);
2220 // fold (xor x, undef) -> undef
2221 if (N0.getOpcode() == ISD::UNDEF)
2223 if (N1.getOpcode() == ISD::UNDEF)
2225 // fold (xor c1, c2) -> c1^c2
2227 return DAG.FoldConstantArithmetic(ISD::XOR, VT, N0C, N1C);
2228 // canonicalize constant to RHS
2230 return DAG.getNode(ISD::XOR, VT, N1, N0);
2231 // fold (xor x, 0) -> x
2232 if (N1C && N1C->isNullValue())
2235 SDValue RXOR = ReassociateOps(ISD::XOR, N0, N1);
2236 if (RXOR.getNode() != 0)
2239 // fold !(x cc y) -> (x !cc y)
2240 if (N1C && N1C->getAPIntValue() == 1 && isSetCCEquivalent(N0, LHS, RHS, CC)) {
2241 bool isInt = LHS.getValueType().isInteger();
2242 ISD::CondCode NotCC = ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(),
2245 if (!LegalOperations || TLI.isCondCodeLegal(NotCC, LHS.getValueType())) {
2246 switch (N0.getOpcode()) {
2248 assert(0 && "Unhandled SetCC Equivalent!");
2251 return DAG.getSetCC(VT, LHS, RHS, NotCC);
2252 case ISD::SELECT_CC:
2253 return DAG.getSelectCC(LHS, RHS, N0.getOperand(2),
2254 N0.getOperand(3), NotCC);
2259 // fold (not (zext (setcc x, y))) -> (zext (not (setcc x, y)))
2260 if (N1C && N1C->getAPIntValue() == 1 && N0.getOpcode() == ISD::ZERO_EXTEND &&
2261 N0.getNode()->hasOneUse() &&
2262 isSetCCEquivalent(N0.getOperand(0), LHS, RHS, CC)){
2263 SDValue V = N0.getOperand(0);
2264 V = DAG.getNode(ISD::XOR, V.getValueType(), V,
2265 DAG.getConstant(1, V.getValueType()));
2266 AddToWorkList(V.getNode());
2267 return DAG.getNode(ISD::ZERO_EXTEND, VT, V);
2270 // fold !(x or y) -> (!x and !y) iff x or y are setcc
2271 if (N1C && N1C->getAPIntValue() == 1 && VT == MVT::i1 &&
2272 (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
2273 SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
2274 if (isOneUseSetCC(RHS) || isOneUseSetCC(LHS)) {
2275 unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
2276 LHS = DAG.getNode(ISD::XOR, VT, LHS, N1); // RHS = ~LHS
2277 RHS = DAG.getNode(ISD::XOR, VT, RHS, N1); // RHS = ~RHS
2278 AddToWorkList(LHS.getNode()); AddToWorkList(RHS.getNode());
2279 return DAG.getNode(NewOpcode, VT, LHS, RHS);
2282 // fold !(x or y) -> (!x and !y) iff x or y are constants
2283 if (N1C && N1C->isAllOnesValue() &&
2284 (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
2285 SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
2286 if (isa<ConstantSDNode>(RHS) || isa<ConstantSDNode>(LHS)) {
2287 unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
2288 LHS = DAG.getNode(ISD::XOR, VT, LHS, N1); // RHS = ~LHS
2289 RHS = DAG.getNode(ISD::XOR, VT, RHS, N1); // RHS = ~RHS
2290 AddToWorkList(LHS.getNode()); AddToWorkList(RHS.getNode());
2291 return DAG.getNode(NewOpcode, VT, LHS, RHS);
2294 // fold (xor (xor x, c1), c2) -> (xor x, c1^c2)
2295 if (N1C && N0.getOpcode() == ISD::XOR) {
2296 ConstantSDNode *N00C = dyn_cast<ConstantSDNode>(N0.getOperand(0));
2297 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
2299 return DAG.getNode(ISD::XOR, VT, N0.getOperand(1),
2300 DAG.getConstant(N1C->getAPIntValue()^
2301 N00C->getAPIntValue(), VT));
2303 return DAG.getNode(ISD::XOR, VT, N0.getOperand(0),
2304 DAG.getConstant(N1C->getAPIntValue()^
2305 N01C->getAPIntValue(), VT));
2307 // fold (xor x, x) -> 0
2309 if (!VT.isVector()) {
2310 return DAG.getConstant(0, VT);
2311 } else if (!LegalOperations || TLI.isOperationLegal(ISD::BUILD_VECTOR, VT)){
2312 // Produce a vector of zeros.
2313 SDValue El = DAG.getConstant(0, VT.getVectorElementType());
2314 std::vector<SDValue> Ops(VT.getVectorNumElements(), El);
2315 return DAG.getNode(ISD::BUILD_VECTOR, VT, &Ops[0], Ops.size());
2319 // Simplify: xor (op x...), (op y...) -> (op (xor x, y))
2320 if (N0.getOpcode() == N1.getOpcode()) {
2321 SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
2322 if (Tmp.getNode()) return Tmp;
2325 // Simplify the expression using non-local knowledge.
2326 if (!VT.isVector() &&
2327 SimplifyDemandedBits(SDValue(N, 0)))
2328 return SDValue(N, 0);
2333 /// visitShiftByConstant - Handle transforms common to the three shifts, when
2334 /// the shift amount is a constant.
2335 SDValue DAGCombiner::visitShiftByConstant(SDNode *N, unsigned Amt) {
2336 SDNode *LHS = N->getOperand(0).getNode();
2337 if (!LHS->hasOneUse()) return SDValue();
2339 // We want to pull some binops through shifts, so that we have (and (shift))
2340 // instead of (shift (and)), likewise for add, or, xor, etc. This sort of
2341 // thing happens with address calculations, so it's important to canonicalize
2343 bool HighBitSet = false; // Can we transform this if the high bit is set?
2345 switch (LHS->getOpcode()) {
2346 default: return SDValue();
2349 HighBitSet = false; // We can only transform sra if the high bit is clear.
2352 HighBitSet = true; // We can only transform sra if the high bit is set.
2355 if (N->getOpcode() != ISD::SHL)
2356 return SDValue(); // only shl(add) not sr[al](add).
2357 HighBitSet = false; // We can only transform sra if the high bit is clear.
2361 // We require the RHS of the binop to be a constant as well.
2362 ConstantSDNode *BinOpCst = dyn_cast<ConstantSDNode>(LHS->getOperand(1));
2363 if (!BinOpCst) return SDValue();
2366 // FIXME: disable this for unless the input to the binop is a shift by a
2367 // constant. If it is not a shift, it pessimizes some common cases like:
2369 //void foo(int *X, int i) { X[i & 1235] = 1; }
2370 //int bar(int *X, int i) { return X[i & 255]; }
2371 SDNode *BinOpLHSVal = LHS->getOperand(0).getNode();
2372 if ((BinOpLHSVal->getOpcode() != ISD::SHL &&
2373 BinOpLHSVal->getOpcode() != ISD::SRA &&
2374 BinOpLHSVal->getOpcode() != ISD::SRL) ||
2375 !isa<ConstantSDNode>(BinOpLHSVal->getOperand(1)))
2378 MVT VT = N->getValueType(0);
2380 // If this is a signed shift right, and the high bit is modified
2381 // by the logical operation, do not perform the transformation.
2382 // The highBitSet boolean indicates the value of the high bit of
2383 // the constant which would cause it to be modified for this
2385 if (N->getOpcode() == ISD::SRA) {
2386 bool BinOpRHSSignSet = BinOpCst->getAPIntValue().isNegative();
2387 if (BinOpRHSSignSet != HighBitSet)
2391 // Fold the constants, shifting the binop RHS by the shift amount.
2392 SDValue NewRHS = DAG.getNode(N->getOpcode(), N->getValueType(0),
2393 LHS->getOperand(1), N->getOperand(1));
2395 // Create the new shift.
2396 SDValue NewShift = DAG.getNode(N->getOpcode(), VT, LHS->getOperand(0),
2399 // Create the new binop.
2400 return DAG.getNode(LHS->getOpcode(), VT, NewShift, NewRHS);
2404 SDValue DAGCombiner::visitSHL(SDNode *N) {
2405 SDValue N0 = N->getOperand(0);
2406 SDValue N1 = N->getOperand(1);
2407 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
2408 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2409 MVT VT = N0.getValueType();
2410 unsigned OpSizeInBits = VT.getSizeInBits();
2412 // fold (shl c1, c2) -> c1<<c2
2414 return DAG.FoldConstantArithmetic(ISD::SHL, VT, N0C, N1C);
2415 // fold (shl 0, x) -> 0
2416 if (N0C && N0C->isNullValue())
2418 // fold (shl x, c >= size(x)) -> undef
2419 if (N1C && N1C->getZExtValue() >= OpSizeInBits)
2420 return DAG.getNode(ISD::UNDEF, VT);
2421 // fold (shl x, 0) -> x
2422 if (N1C && N1C->isNullValue())
2424 // if (shl x, c) is known to be zero, return 0
2425 if (DAG.MaskedValueIsZero(SDValue(N, 0),
2426 APInt::getAllOnesValue(VT.getSizeInBits())))
2427 return DAG.getConstant(0, VT);
2428 // fold (shl x, (trunc (and y, c))) -> (shl x, (and (trunc y), c))
2429 // iff (trunc c) == c
2430 if (N1.getOpcode() == ISD::TRUNCATE &&
2431 N1.getOperand(0).getOpcode() == ISD::AND &&
2432 N1.hasOneUse() && N1.getOperand(0).hasOneUse()) {
2433 SDValue N101 = N1.getOperand(0).getOperand(1);
2434 if (ConstantSDNode *N101C = dyn_cast<ConstantSDNode>(N101)) {
2435 MVT TruncVT = N1.getValueType();
2436 SDValue N100 = N1.getOperand(0).getOperand(0);
2437 return DAG.getNode(ISD::SHL, VT, N0,
2438 DAG.getNode(ISD::AND, TruncVT,
2439 DAG.getNode(ISD::TRUNCATE, TruncVT, N100),
2440 DAG.getConstant(N101C->getZExtValue(),
2445 if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
2446 return SDValue(N, 0);
2447 // fold (shl (shl x, c1), c2) -> 0 or (shl x, c1+c2)
2448 if (N1C && N0.getOpcode() == ISD::SHL &&
2449 N0.getOperand(1).getOpcode() == ISD::Constant) {
2450 uint64_t c1 = cast<ConstantSDNode>(N0.getOperand(1))->getZExtValue();
2451 uint64_t c2 = N1C->getZExtValue();
2452 if (c1 + c2 > OpSizeInBits)
2453 return DAG.getConstant(0, VT);
2454 return DAG.getNode(ISD::SHL, VT, N0.getOperand(0),
2455 DAG.getConstant(c1 + c2, N1.getValueType()));
2457 // fold (shl (srl x, c1), c2) -> (shl (and x, -1 << c1), c2-c1) or
2458 // (srl (and x, -1 << c1), c1-c2)
2459 if (N1C && N0.getOpcode() == ISD::SRL &&
2460 N0.getOperand(1).getOpcode() == ISD::Constant) {
2461 uint64_t c1 = cast<ConstantSDNode>(N0.getOperand(1))->getZExtValue();
2462 uint64_t c2 = N1C->getZExtValue();
2463 SDValue Mask = DAG.getNode(ISD::AND, VT, N0.getOperand(0),
2464 DAG.getConstant(~0ULL << c1, VT));
2466 return DAG.getNode(ISD::SHL, VT, Mask,
2467 DAG.getConstant(c2-c1, N1.getValueType()));
2469 return DAG.getNode(ISD::SRL, VT, Mask,
2470 DAG.getConstant(c1-c2, N1.getValueType()));
2472 // fold (shl (sra x, c1), c1) -> (and x, -1 << c1)
2473 if (N1C && N0.getOpcode() == ISD::SRA && N1 == N0.getOperand(1))
2474 return DAG.getNode(ISD::AND, VT, N0.getOperand(0),
2475 DAG.getConstant(~0ULL << N1C->getZExtValue(), VT));
2477 return N1C ? visitShiftByConstant(N, N1C->getZExtValue()) : SDValue();
2480 SDValue DAGCombiner::visitSRA(SDNode *N) {
2481 SDValue N0 = N->getOperand(0);
2482 SDValue N1 = N->getOperand(1);
2483 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
2484 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2485 MVT VT = N0.getValueType();
2487 // fold (sra c1, c2) -> c1>>c2
2489 return DAG.FoldConstantArithmetic(ISD::SRA, VT, N0C, N1C);
2490 // fold (sra 0, x) -> 0
2491 if (N0C && N0C->isNullValue())
2493 // fold (sra -1, x) -> -1
2494 if (N0C && N0C->isAllOnesValue())
2496 // fold (sra x, c >= size(x)) -> undef
2497 if (N1C && N1C->getZExtValue() >= VT.getSizeInBits())
2498 return DAG.getNode(ISD::UNDEF, VT);
2499 // fold (sra x, 0) -> x
2500 if (N1C && N1C->isNullValue())
2502 // fold (sra (shl x, c1), c1) -> sext_inreg for some c1 and target supports
2504 if (N1C && N0.getOpcode() == ISD::SHL && N1 == N0.getOperand(1)) {
2505 unsigned LowBits = VT.getSizeInBits() - (unsigned)N1C->getZExtValue();
2506 MVT EVT = MVT::getIntegerVT(LowBits);
2507 if ((!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, EVT)))
2508 return DAG.getNode(ISD::SIGN_EXTEND_INREG, VT, N0.getOperand(0),
2509 DAG.getValueType(EVT));
2512 // fold (sra (sra x, c1), c2) -> (sra x, c1+c2)
2513 if (N1C && N0.getOpcode() == ISD::SRA) {
2514 if (ConstantSDNode *C1 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
2515 unsigned Sum = N1C->getZExtValue() + C1->getZExtValue();
2516 if (Sum >= VT.getSizeInBits()) Sum = VT.getSizeInBits()-1;
2517 return DAG.getNode(ISD::SRA, VT, N0.getOperand(0),
2518 DAG.getConstant(Sum, N1C->getValueType(0)));
2522 // fold sra (shl X, m), result_size - n
2523 // -> (sign_extend (trunc (shl X, result_size - n - m))) for
2524 // result_size - n != m.
2525 // If truncate is free for the target sext(shl) is likely to result in better
2527 if (N0.getOpcode() == ISD::SHL) {
2528 // Get the two constanst of the shifts, CN0 = m, CN = n.
2529 const ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
2531 // Determine what the truncate's result bitsize and type would be.
2532 unsigned VTValSize = VT.getSizeInBits();
2534 MVT::getIntegerVT(VTValSize - N1C->getZExtValue());
2535 // Determine the residual right-shift amount.
2536 unsigned ShiftAmt = N1C->getZExtValue() - N01C->getZExtValue();
2538 // If the shift is not a no-op (in which case this should be just a sign
2539 // extend already), the truncated to type is legal, sign_extend is legal
2540 // on that type, and the the truncate to that type is both legal and free,
2541 // perform the transform.
2543 TLI.isOperationLegal(ISD::SIGN_EXTEND, TruncVT) &&
2544 TLI.isOperationLegal(ISD::TRUNCATE, VT) &&
2545 TLI.isTruncateFree(VT, TruncVT)) {
2547 SDValue Amt = DAG.getConstant(ShiftAmt, TLI.getShiftAmountTy());
2548 SDValue Shift = DAG.getNode(ISD::SRL, VT, N0.getOperand(0), Amt);
2549 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, TruncVT, Shift);
2550 return DAG.getNode(ISD::SIGN_EXTEND, N->getValueType(0), Trunc);
2555 // fold (sra x, (trunc (and y, c))) -> (sra x, (and (trunc y), c))
2556 // iff (trunc c) == c
2557 if (N1.getOpcode() == ISD::TRUNCATE &&
2558 N1.getOperand(0).getOpcode() == ISD::AND &&
2559 N1.hasOneUse() && N1.getOperand(0).hasOneUse()) {
2560 SDValue N101 = N1.getOperand(0).getOperand(1);
2561 if (ConstantSDNode *N101C = dyn_cast<ConstantSDNode>(N101)) {
2562 MVT TruncVT = N1.getValueType();
2563 SDValue N100 = N1.getOperand(0).getOperand(0);
2564 return DAG.getNode(ISD::SRA, VT, N0,
2565 DAG.getNode(ISD::AND, TruncVT,
2566 DAG.getNode(ISD::TRUNCATE, TruncVT, N100),
2567 DAG.getConstant(N101C->getZExtValue(),
2572 // Simplify, based on bits shifted out of the LHS.
2573 if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
2574 return SDValue(N, 0);
2577 // If the sign bit is known to be zero, switch this to a SRL.
2578 if (DAG.SignBitIsZero(N0))
2579 return DAG.getNode(ISD::SRL, VT, N0, N1);
2581 return N1C ? visitShiftByConstant(N, N1C->getZExtValue()) : SDValue();
2584 SDValue DAGCombiner::visitSRL(SDNode *N) {
2585 SDValue N0 = N->getOperand(0);
2586 SDValue N1 = N->getOperand(1);
2587 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
2588 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2589 MVT VT = N0.getValueType();
2590 unsigned OpSizeInBits = VT.getSizeInBits();
2592 // fold (srl c1, c2) -> c1 >>u c2
2594 return DAG.FoldConstantArithmetic(ISD::SRL, VT, N0C, N1C);
2595 // fold (srl 0, x) -> 0
2596 if (N0C && N0C->isNullValue())
2598 // fold (srl x, c >= size(x)) -> undef
2599 if (N1C && N1C->getZExtValue() >= OpSizeInBits)
2600 return DAG.getNode(ISD::UNDEF, VT);
2601 // fold (srl x, 0) -> x
2602 if (N1C && N1C->isNullValue())
2604 // if (srl x, c) is known to be zero, return 0
2605 if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0),
2606 APInt::getAllOnesValue(OpSizeInBits)))
2607 return DAG.getConstant(0, VT);
2609 // fold (srl (srl x, c1), c2) -> 0 or (srl x, c1+c2)
2610 if (N1C && N0.getOpcode() == ISD::SRL &&
2611 N0.getOperand(1).getOpcode() == ISD::Constant) {
2612 uint64_t c1 = cast<ConstantSDNode>(N0.getOperand(1))->getZExtValue();
2613 uint64_t c2 = N1C->getZExtValue();
2614 if (c1 + c2 > OpSizeInBits)
2615 return DAG.getConstant(0, VT);
2616 return DAG.getNode(ISD::SRL, VT, N0.getOperand(0),
2617 DAG.getConstant(c1 + c2, N1.getValueType()));
2620 // fold (srl (anyextend x), c) -> (anyextend (srl x, c))
2621 if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
2622 // Shifting in all undef bits?
2623 MVT SmallVT = N0.getOperand(0).getValueType();
2624 if (N1C->getZExtValue() >= SmallVT.getSizeInBits())
2625 return DAG.getNode(ISD::UNDEF, VT);
2627 SDValue SmallShift = DAG.getNode(ISD::SRL, SmallVT, N0.getOperand(0), N1);
2628 AddToWorkList(SmallShift.getNode());
2629 return DAG.getNode(ISD::ANY_EXTEND, VT, SmallShift);
2632 // fold (srl (sra X, Y), 31) -> (srl X, 31). This srl only looks at the sign
2633 // bit, which is unmodified by sra.
2634 if (N1C && N1C->getZExtValue()+1 == VT.getSizeInBits()) {
2635 if (N0.getOpcode() == ISD::SRA)
2636 return DAG.getNode(ISD::SRL, VT, N0.getOperand(0), N1);
2639 // fold (srl (ctlz x), "5") -> x iff x has one bit set (the low bit).
2640 if (N1C && N0.getOpcode() == ISD::CTLZ &&
2641 N1C->getAPIntValue() == Log2_32(VT.getSizeInBits())) {
2642 APInt KnownZero, KnownOne;
2643 APInt Mask = APInt::getAllOnesValue(VT.getSizeInBits());
2644 DAG.ComputeMaskedBits(N0.getOperand(0), Mask, KnownZero, KnownOne);
2646 // If any of the input bits are KnownOne, then the input couldn't be all
2647 // zeros, thus the result of the srl will always be zero.
2648 if (KnownOne.getBoolValue()) return DAG.getConstant(0, VT);
2650 // If all of the bits input the to ctlz node are known to be zero, then
2651 // the result of the ctlz is "32" and the result of the shift is one.
2652 APInt UnknownBits = ~KnownZero & Mask;
2653 if (UnknownBits == 0) return DAG.getConstant(1, VT);
2655 // Otherwise, check to see if there is exactly one bit input to the ctlz.
2656 if ((UnknownBits & (UnknownBits-1)) == 0) {
2657 // Okay, we know that only that the single bit specified by UnknownBits
2658 // could be set on input to the CTLZ node. If this bit is set, the SRL
2659 // will return 0, if it is clear, it returns 1. Change the CTLZ/SRL pair
2660 // to an SRL,XOR pair, which is likely to simplify more.
2661 unsigned ShAmt = UnknownBits.countTrailingZeros();
2662 SDValue Op = N0.getOperand(0);
2664 Op = DAG.getNode(ISD::SRL, VT, Op,
2665 DAG.getConstant(ShAmt, TLI.getShiftAmountTy()));
2666 AddToWorkList(Op.getNode());
2668 return DAG.getNode(ISD::XOR, VT, Op, DAG.getConstant(1, VT));
2672 // fold (srl x, (trunc (and y, c))) -> (srl x, (and (trunc y), c))
2673 // iff (trunc c) == c
2674 if (N1.getOpcode() == ISD::TRUNCATE &&
2675 N1.getOperand(0).getOpcode() == ISD::AND &&
2676 N1.hasOneUse() && N1.getOperand(0).hasOneUse()) {
2677 SDValue N101 = N1.getOperand(0).getOperand(1);
2678 if (ConstantSDNode *N101C = dyn_cast<ConstantSDNode>(N101)) {
2679 MVT TruncVT = N1.getValueType();
2680 SDValue N100 = N1.getOperand(0).getOperand(0);
2681 return DAG.getNode(ISD::SRL, VT, N0,
2682 DAG.getNode(ISD::AND, TruncVT,
2683 DAG.getNode(ISD::TRUNCATE, TruncVT, N100),
2684 DAG.getConstant(N101C->getZExtValue(),
2689 // fold operands of srl based on knowledge that the low bits are not
2691 if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
2692 return SDValue(N, 0);
2694 return N1C ? visitShiftByConstant(N, N1C->getZExtValue()) : SDValue();
2697 SDValue DAGCombiner::visitCTLZ(SDNode *N) {
2698 SDValue N0 = N->getOperand(0);
2699 MVT VT = N->getValueType(0);
2701 // fold (ctlz c1) -> c2
2702 if (isa<ConstantSDNode>(N0))
2703 return DAG.getNode(ISD::CTLZ, VT, N0);
2707 SDValue DAGCombiner::visitCTTZ(SDNode *N) {
2708 SDValue N0 = N->getOperand(0);
2709 MVT VT = N->getValueType(0);
2711 // fold (cttz c1) -> c2
2712 if (isa<ConstantSDNode>(N0))
2713 return DAG.getNode(ISD::CTTZ, VT, N0);
2717 SDValue DAGCombiner::visitCTPOP(SDNode *N) {
2718 SDValue N0 = N->getOperand(0);
2719 MVT VT = N->getValueType(0);
2721 // fold (ctpop c1) -> c2
2722 if (isa<ConstantSDNode>(N0))
2723 return DAG.getNode(ISD::CTPOP, VT, N0);
2727 SDValue DAGCombiner::visitSELECT(SDNode *N) {
2728 SDValue N0 = N->getOperand(0);
2729 SDValue N1 = N->getOperand(1);
2730 SDValue N2 = N->getOperand(2);
2731 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
2732 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2733 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2);
2734 MVT VT = N->getValueType(0);
2735 MVT VT0 = N0.getValueType();
2737 // fold select C, X, X -> X
2740 // fold select true, X, Y -> X
2741 if (N0C && !N0C->isNullValue())
2743 // fold select false, X, Y -> Y
2744 if (N0C && N0C->isNullValue())
2746 // fold select C, 1, X -> C | X
2747 if (VT == MVT::i1 && N1C && N1C->getAPIntValue() == 1)
2748 return DAG.getNode(ISD::OR, VT, N0, N2);
2749 // fold select C, 0, 1 -> ~C
2750 if (VT.isInteger() && VT0.isInteger() &&
2751 N1C && N2C && N1C->isNullValue() && N2C->getAPIntValue() == 1) {
2752 SDValue XORNode = DAG.getNode(ISD::XOR, VT0, N0, DAG.getConstant(1, VT0));
2755 AddToWorkList(XORNode.getNode());
2757 return DAG.getNode(ISD::ZERO_EXTEND, VT, XORNode);
2758 return DAG.getNode(ISD::TRUNCATE, VT, XORNode);
2760 // fold select C, 0, X -> ~C & X
2761 if (VT == VT0 && VT == MVT::i1 && N1C && N1C->isNullValue()) {
2762 SDValue XORNode = DAG.getNode(ISD::XOR, VT, N0, DAG.getConstant(1, VT));
2763 AddToWorkList(XORNode.getNode());
2764 return DAG.getNode(ISD::AND, VT, XORNode, N2);
2766 // fold select C, X, 1 -> ~C | X
2767 if (VT == VT0 && VT == MVT::i1 && N2C && N2C->getAPIntValue() == 1) {
2768 SDValue XORNode = DAG.getNode(ISD::XOR, VT, N0, DAG.getConstant(1, VT));
2769 AddToWorkList(XORNode.getNode());
2770 return DAG.getNode(ISD::OR, VT, XORNode, N1);
2772 // fold select C, X, 0 -> C & X
2773 // FIXME: this should check for C type == X type, not i1?
2774 if (VT == MVT::i1 && N2C && N2C->isNullValue())
2775 return DAG.getNode(ISD::AND, VT, N0, N1);
2776 // fold X ? X : Y --> X ? 1 : Y --> X | Y
2777 if (VT == MVT::i1 && N0 == N1)
2778 return DAG.getNode(ISD::OR, VT, N0, N2);
2779 // fold X ? Y : X --> X ? Y : 0 --> X & Y
2780 if (VT == MVT::i1 && N0 == N2)
2781 return DAG.getNode(ISD::AND, VT, N0, N1);
2783 // If we can fold this based on the true/false value, do so.
2784 if (SimplifySelectOps(N, N1, N2))
2785 return SDValue(N, 0); // Don't revisit N.
2787 // fold selects based on a setcc into other things, such as min/max/abs
2788 if (N0.getOpcode() == ISD::SETCC) {
2790 // Check against MVT::Other for SELECT_CC, which is a workaround for targets
2791 // having to say they don't support SELECT_CC on every type the DAG knows
2792 // about, since there is no way to mark an opcode illegal at all value types
2793 if (TLI.isOperationLegal(ISD::SELECT_CC, MVT::Other))
2794 return DAG.getNode(ISD::SELECT_CC, VT, N0.getOperand(0), N0.getOperand(1),
2795 N1, N2, N0.getOperand(2));
2797 return SimplifySelect(N0, N1, N2);
2802 SDValue DAGCombiner::visitSELECT_CC(SDNode *N) {
2803 SDValue N0 = N->getOperand(0);
2804 SDValue N1 = N->getOperand(1);
2805 SDValue N2 = N->getOperand(2);
2806 SDValue N3 = N->getOperand(3);
2807 SDValue N4 = N->getOperand(4);
2808 ISD::CondCode CC = cast<CondCodeSDNode>(N4)->get();
2810 // fold select_cc lhs, rhs, x, x, cc -> x
2814 // Determine if the condition we're dealing with is constant
2815 SDValue SCC = SimplifySetCC(TLI.getSetCCResultType(N0.getValueType()),
2817 if (SCC.getNode()) AddToWorkList(SCC.getNode());
2819 if (ConstantSDNode *SCCC = dyn_cast_or_null<ConstantSDNode>(SCC.getNode())) {
2820 if (!SCCC->isNullValue())
2821 return N2; // cond always true -> true val
2823 return N3; // cond always false -> false val
2826 // Fold to a simpler select_cc
2827 if (SCC.getNode() && SCC.getOpcode() == ISD::SETCC)
2828 return DAG.getNode(ISD::SELECT_CC, N2.getValueType(),
2829 SCC.getOperand(0), SCC.getOperand(1), N2, N3,
2832 // If we can fold this based on the true/false value, do so.
2833 if (SimplifySelectOps(N, N2, N3))
2834 return SDValue(N, 0); // Don't revisit N.
2836 // fold select_cc into other things, such as min/max/abs
2837 return SimplifySelectCC(N0, N1, N2, N3, CC);
2840 SDValue DAGCombiner::visitSETCC(SDNode *N) {
2841 return SimplifySetCC(N->getValueType(0), N->getOperand(0), N->getOperand(1),
2842 cast<CondCodeSDNode>(N->getOperand(2))->get());
2845 // ExtendUsesToFormExtLoad - Trying to extend uses of a load to enable this:
2846 // "fold ({s|z}ext (load x)) -> ({s|z}ext (truncate ({s|z}extload x)))"
2847 // transformation. Returns true if extension are possible and the above
2848 // mentioned transformation is profitable.
2849 static bool ExtendUsesToFormExtLoad(SDNode *N, SDValue N0,
2851 SmallVector<SDNode*, 4> &ExtendNodes,
2852 const TargetLowering &TLI) {
2853 bool HasCopyToRegUses = false;
2854 bool isTruncFree = TLI.isTruncateFree(N->getValueType(0), N0.getValueType());
2855 for (SDNode::use_iterator UI = N0.getNode()->use_begin(),
2856 UE = N0.getNode()->use_end();
2861 // FIXME: Only extend SETCC N, N and SETCC N, c for now.
2862 if (User->getOpcode() == ISD::SETCC) {
2863 ISD::CondCode CC = cast<CondCodeSDNode>(User->getOperand(2))->get();
2864 if (ExtOpc == ISD::ZERO_EXTEND && ISD::isSignedIntSetCC(CC))
2865 // Sign bits will be lost after a zext.
2868 for (unsigned i = 0; i != 2; ++i) {
2869 SDValue UseOp = User->getOperand(i);
2872 if (!isa<ConstantSDNode>(UseOp))
2877 ExtendNodes.push_back(User);
2879 for (unsigned i = 0, e = User->getNumOperands(); i != e; ++i) {
2880 SDValue UseOp = User->getOperand(i);
2882 // If truncate from extended type to original load type is free
2883 // on this target, then it's ok to extend a CopyToReg.
2884 if (isTruncFree && User->getOpcode() == ISD::CopyToReg)
2885 HasCopyToRegUses = true;
2893 if (HasCopyToRegUses) {
2894 bool BothLiveOut = false;
2895 for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
2898 for (unsigned i = 0, e = User->getNumOperands(); i != e; ++i) {
2899 SDValue UseOp = User->getOperand(i);
2900 if (UseOp.getNode() == N && UseOp.getResNo() == 0) {
2907 // Both unextended and extended values are live out. There had better be
2908 // good a reason for the transformation.
2909 return ExtendNodes.size();
2914 SDValue DAGCombiner::visitSIGN_EXTEND(SDNode *N) {
2915 SDValue N0 = N->getOperand(0);
2916 MVT VT = N->getValueType(0);
2918 // fold (sext c1) -> c1
2919 if (isa<ConstantSDNode>(N0))
2920 return DAG.getNode(ISD::SIGN_EXTEND, VT, N0);
2922 // fold (sext (sext x)) -> (sext x)
2923 // fold (sext (aext x)) -> (sext x)
2924 if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
2925 return DAG.getNode(ISD::SIGN_EXTEND, VT, N0.getOperand(0));
2927 if (N0.getOpcode() == ISD::TRUNCATE) {
2928 // fold (sext (truncate (load x))) -> (sext (smaller load x))
2929 // fold (sext (truncate (srl (load x), c))) -> (sext (smaller load (x+c/n)))
2930 SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
2931 if (NarrowLoad.getNode()) {
2932 if (NarrowLoad.getNode() != N0.getNode())
2933 CombineTo(N0.getNode(), NarrowLoad);
2934 return DAG.getNode(ISD::SIGN_EXTEND, VT, NarrowLoad);
2937 // See if the value being truncated is already sign extended. If so, just
2938 // eliminate the trunc/sext pair.
2939 SDValue Op = N0.getOperand(0);
2940 unsigned OpBits = Op.getValueType().getSizeInBits();
2941 unsigned MidBits = N0.getValueType().getSizeInBits();
2942 unsigned DestBits = VT.getSizeInBits();
2943 unsigned NumSignBits = DAG.ComputeNumSignBits(Op);
2945 if (OpBits == DestBits) {
2946 // Op is i32, Mid is i8, and Dest is i32. If Op has more than 24 sign
2947 // bits, it is already ready.
2948 if (NumSignBits > DestBits-MidBits)
2950 } else if (OpBits < DestBits) {
2951 // Op is i32, Mid is i8, and Dest is i64. If Op has more than 24 sign
2952 // bits, just sext from i32.
2953 if (NumSignBits > OpBits-MidBits)
2954 return DAG.getNode(ISD::SIGN_EXTEND, VT, Op);
2956 // Op is i64, Mid is i8, and Dest is i32. If Op has more than 56 sign
2957 // bits, just truncate to i32.
2958 if (NumSignBits > OpBits-MidBits)
2959 return DAG.getNode(ISD::TRUNCATE, VT, Op);
2962 // fold (sext (truncate x)) -> (sextinreg x).
2963 if (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG,
2964 N0.getValueType())) {
2965 if (Op.getValueType().bitsLT(VT))
2966 Op = DAG.getNode(ISD::ANY_EXTEND, VT, Op);
2967 else if (Op.getValueType().bitsGT(VT))
2968 Op = DAG.getNode(ISD::TRUNCATE, VT, Op);
2969 return DAG.getNode(ISD::SIGN_EXTEND_INREG, VT, Op,
2970 DAG.getValueType(N0.getValueType()));
2974 // fold (sext (load x)) -> (sext (truncate (sextload x)))
2975 if (ISD::isNON_EXTLoad(N0.getNode()) &&
2976 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
2977 TLI.isLoadExtLegal(ISD::SEXTLOAD, N0.getValueType()))) {
2978 bool DoXform = true;
2979 SmallVector<SDNode*, 4> SetCCs;
2980 if (!N0.hasOneUse())
2981 DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::SIGN_EXTEND, SetCCs, TLI);
2983 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
2984 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, VT, LN0->getChain(),
2985 LN0->getBasePtr(), LN0->getSrcValue(),
2986 LN0->getSrcValueOffset(),
2988 LN0->isVolatile(), LN0->getAlignment());
2989 CombineTo(N, ExtLoad);
2990 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, N0.getValueType(), ExtLoad);
2991 CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
2992 // Extend SetCC uses if necessary.
2993 for (unsigned i = 0, e = SetCCs.size(); i != e; ++i) {
2994 SDNode *SetCC = SetCCs[i];
2995 SmallVector<SDValue, 4> Ops;
2996 for (unsigned j = 0; j != 2; ++j) {
2997 SDValue SOp = SetCC->getOperand(j);
2999 Ops.push_back(ExtLoad);
3001 Ops.push_back(DAG.getNode(ISD::SIGN_EXTEND, VT, SOp));
3003 Ops.push_back(SetCC->getOperand(2));
3004 CombineTo(SetCC, DAG.getNode(ISD::SETCC, SetCC->getValueType(0),
3005 &Ops[0], Ops.size()));
3007 return SDValue(N, 0); // Return N so it doesn't get rechecked!
3011 // fold (sext (sextload x)) -> (sext (truncate (sextload x)))
3012 // fold (sext ( extload x)) -> (sext (truncate (sextload x)))
3013 if ((ISD::isSEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) &&
3014 ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) {
3015 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
3016 MVT EVT = LN0->getMemoryVT();
3017 if ((!LegalOperations && !LN0->isVolatile()) ||
3018 TLI.isLoadExtLegal(ISD::SEXTLOAD, EVT)) {
3019 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, VT, LN0->getChain(),
3020 LN0->getBasePtr(), LN0->getSrcValue(),
3021 LN0->getSrcValueOffset(), EVT,
3022 LN0->isVolatile(), LN0->getAlignment());
3023 CombineTo(N, ExtLoad);
3024 CombineTo(N0.getNode(),
3025 DAG.getNode(ISD::TRUNCATE, N0.getValueType(), ExtLoad),
3026 ExtLoad.getValue(1));
3027 return SDValue(N, 0); // Return N so it doesn't get rechecked!
3031 // sext(setcc x,y,cc) -> select_cc x, y, -1, 0, cc
3032 if (N0.getOpcode() == ISD::SETCC) {
3034 SimplifySelectCC(N0.getOperand(0), N0.getOperand(1),
3035 DAG.getConstant(~0ULL, VT), DAG.getConstant(0, VT),
3036 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
3037 if (SCC.getNode()) return SCC;
3040 // fold (sext x) -> (zext x) if the sign bit is known zero.
3041 if ((!LegalOperations || TLI.isOperationLegal(ISD::ZERO_EXTEND, VT)) &&
3042 DAG.SignBitIsZero(N0))
3043 return DAG.getNode(ISD::ZERO_EXTEND, VT, N0);
3048 SDValue DAGCombiner::visitZERO_EXTEND(SDNode *N) {
3049 SDValue N0 = N->getOperand(0);
3050 MVT VT = N->getValueType(0);
3052 // fold (zext c1) -> c1
3053 if (isa<ConstantSDNode>(N0))
3054 return DAG.getNode(ISD::ZERO_EXTEND, VT, N0);
3055 // fold (zext (zext x)) -> (zext x)
3056 // fold (zext (aext x)) -> (zext x)
3057 if (N0.getOpcode() == ISD::ZERO_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
3058 return DAG.getNode(ISD::ZERO_EXTEND, VT, N0.getOperand(0));
3060 // fold (zext (truncate (load x))) -> (zext (smaller load x))
3061 // fold (zext (truncate (srl (load x), c))) -> (zext (small load (x+c/n)))
3062 if (N0.getOpcode() == ISD::TRUNCATE) {
3063 SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
3064 if (NarrowLoad.getNode()) {
3065 if (NarrowLoad.getNode() != N0.getNode())
3066 CombineTo(N0.getNode(), NarrowLoad);
3067 return DAG.getNode(ISD::ZERO_EXTEND, VT, NarrowLoad);
3071 // fold (zext (truncate x)) -> (and x, mask)
3072 if (N0.getOpcode() == ISD::TRUNCATE &&
3073 (!LegalOperations || TLI.isOperationLegal(ISD::AND, VT))) {
3074 SDValue Op = N0.getOperand(0);
3075 if (Op.getValueType().bitsLT(VT)) {
3076 Op = DAG.getNode(ISD::ANY_EXTEND, VT, Op);
3077 } else if (Op.getValueType().bitsGT(VT)) {
3078 Op = DAG.getNode(ISD::TRUNCATE, VT, Op);
3080 return DAG.getZeroExtendInReg(Op, N0.getValueType());
3083 // fold (zext (and (trunc x), cst)) -> (and x, cst).
3084 if (N0.getOpcode() == ISD::AND &&
3085 N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
3086 N0.getOperand(1).getOpcode() == ISD::Constant) {
3087 SDValue X = N0.getOperand(0).getOperand(0);
3088 if (X.getValueType().bitsLT(VT)) {
3089 X = DAG.getNode(ISD::ANY_EXTEND, VT, X);
3090 } else if (X.getValueType().bitsGT(VT)) {
3091 X = DAG.getNode(ISD::TRUNCATE, VT, X);
3093 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
3094 Mask.zext(VT.getSizeInBits());
3095 return DAG.getNode(ISD::AND, VT, X, DAG.getConstant(Mask, VT));
3098 // fold (zext (load x)) -> (zext (truncate (zextload x)))
3099 if (ISD::isNON_EXTLoad(N0.getNode()) &&
3100 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
3101 TLI.isLoadExtLegal(ISD::ZEXTLOAD, N0.getValueType()))) {
3102 bool DoXform = true;
3103 SmallVector<SDNode*, 4> SetCCs;
3104 if (!N0.hasOneUse())
3105 DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ZERO_EXTEND, SetCCs, TLI);
3107 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
3108 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, VT, LN0->getChain(),
3109 LN0->getBasePtr(), LN0->getSrcValue(),
3110 LN0->getSrcValueOffset(),
3112 LN0->isVolatile(), LN0->getAlignment());
3113 CombineTo(N, ExtLoad);
3114 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, N0.getValueType(), ExtLoad);
3115 CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
3116 // Extend SetCC uses if necessary.
3117 for (unsigned i = 0, e = SetCCs.size(); i != e; ++i) {
3118 SDNode *SetCC = SetCCs[i];
3119 SmallVector<SDValue, 4> Ops;
3120 for (unsigned j = 0; j != 2; ++j) {
3121 SDValue SOp = SetCC->getOperand(j);
3123 Ops.push_back(ExtLoad);
3125 Ops.push_back(DAG.getNode(ISD::ZERO_EXTEND, VT, SOp));
3127 Ops.push_back(SetCC->getOperand(2));
3128 CombineTo(SetCC, DAG.getNode(ISD::SETCC, SetCC->getValueType(0),
3129 &Ops[0], Ops.size()));
3131 return SDValue(N, 0); // Return N so it doesn't get rechecked!
3135 // fold (zext (zextload x)) -> (zext (truncate (zextload x)))
3136 // fold (zext ( extload x)) -> (zext (truncate (zextload x)))
3137 if ((ISD::isZEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) &&
3138 ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) {
3139 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
3140 MVT EVT = LN0->getMemoryVT();
3141 if ((!LegalOperations && !LN0->isVolatile()) ||
3142 TLI.isLoadExtLegal(ISD::ZEXTLOAD, EVT)) {
3143 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, VT, LN0->getChain(),
3144 LN0->getBasePtr(), LN0->getSrcValue(),
3145 LN0->getSrcValueOffset(), EVT,
3146 LN0->isVolatile(), LN0->getAlignment());
3147 CombineTo(N, ExtLoad);
3148 CombineTo(N0.getNode(),
3149 DAG.getNode(ISD::TRUNCATE, N0.getValueType(), ExtLoad),
3150 ExtLoad.getValue(1));
3151 return SDValue(N, 0); // Return N so it doesn't get rechecked!
3155 // zext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
3156 if (N0.getOpcode() == ISD::SETCC) {
3158 SimplifySelectCC(N0.getOperand(0), N0.getOperand(1),
3159 DAG.getConstant(1, VT), DAG.getConstant(0, VT),
3160 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
3161 if (SCC.getNode()) return SCC;
3167 SDValue DAGCombiner::visitANY_EXTEND(SDNode *N) {
3168 SDValue N0 = N->getOperand(0);
3169 MVT VT = N->getValueType(0);
3171 // fold (aext c1) -> c1
3172 if (isa<ConstantSDNode>(N0))
3173 return DAG.getNode(ISD::ANY_EXTEND, VT, N0);
3174 // fold (aext (aext x)) -> (aext x)
3175 // fold (aext (zext x)) -> (zext x)
3176 // fold (aext (sext x)) -> (sext x)
3177 if (N0.getOpcode() == ISD::ANY_EXTEND ||
3178 N0.getOpcode() == ISD::ZERO_EXTEND ||
3179 N0.getOpcode() == ISD::SIGN_EXTEND)
3180 return DAG.getNode(N0.getOpcode(), VT, N0.getOperand(0));
3182 // fold (aext (truncate (load x))) -> (aext (smaller load x))
3183 // fold (aext (truncate (srl (load x), c))) -> (aext (small load (x+c/n)))
3184 if (N0.getOpcode() == ISD::TRUNCATE) {
3185 SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
3186 if (NarrowLoad.getNode()) {
3187 if (NarrowLoad.getNode() != N0.getNode())
3188 CombineTo(N0.getNode(), NarrowLoad);
3189 return DAG.getNode(ISD::ANY_EXTEND, VT, NarrowLoad);
3193 // fold (aext (truncate x))
3194 if (N0.getOpcode() == ISD::TRUNCATE) {
3195 SDValue TruncOp = N0.getOperand(0);
3196 if (TruncOp.getValueType() == VT)
3197 return TruncOp; // x iff x size == zext size.
3198 if (TruncOp.getValueType().bitsGT(VT))
3199 return DAG.getNode(ISD::TRUNCATE, VT, TruncOp);
3200 return DAG.getNode(ISD::ANY_EXTEND, VT, TruncOp);
3203 // fold (aext (and (trunc x), cst)) -> (and x, cst).
3204 if (N0.getOpcode() == ISD::AND &&
3205 N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
3206 N0.getOperand(1).getOpcode() == ISD::Constant) {
3207 SDValue X = N0.getOperand(0).getOperand(0);
3208 if (X.getValueType().bitsLT(VT)) {
3209 X = DAG.getNode(ISD::ANY_EXTEND, VT, X);
3210 } else if (X.getValueType().bitsGT(VT)) {
3211 X = DAG.getNode(ISD::TRUNCATE, VT, X);
3213 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
3214 Mask.zext(VT.getSizeInBits());
3215 return DAG.getNode(ISD::AND, VT, X, DAG.getConstant(Mask, VT));
3218 // fold (aext (load x)) -> (aext (truncate (extload x)))
3219 if (ISD::isNON_EXTLoad(N0.getNode()) && N0.hasOneUse() &&
3220 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
3221 TLI.isLoadExtLegal(ISD::EXTLOAD, N0.getValueType()))) {
3222 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
3223 SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, VT, LN0->getChain(),
3224 LN0->getBasePtr(), LN0->getSrcValue(),
3225 LN0->getSrcValueOffset(),
3227 LN0->isVolatile(), LN0->getAlignment());
3228 CombineTo(N, ExtLoad);
3229 // Redirect any chain users to the new load.
3230 DAG.ReplaceAllUsesOfValueWith(SDValue(LN0, 1),
3231 SDValue(ExtLoad.getNode(), 1));
3232 // If any node needs the original loaded value, recompute it.
3233 if (!LN0->use_empty())
3234 CombineTo(LN0, DAG.getNode(ISD::TRUNCATE, N0.getValueType(), ExtLoad),
3235 ExtLoad.getValue(1));
3236 return SDValue(N, 0); // Return N so it doesn't get rechecked!
3239 // fold (aext (zextload x)) -> (aext (truncate (zextload x)))
3240 // fold (aext (sextload x)) -> (aext (truncate (sextload x)))
3241 // fold (aext ( extload x)) -> (aext (truncate (extload x)))
3242 if (N0.getOpcode() == ISD::LOAD &&
3243 !ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
3245 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
3246 MVT EVT = LN0->getMemoryVT();
3247 SDValue ExtLoad = DAG.getExtLoad(LN0->getExtensionType(), VT,
3248 LN0->getChain(), LN0->getBasePtr(),
3250 LN0->getSrcValueOffset(), EVT,
3251 LN0->isVolatile(), LN0->getAlignment());
3252 CombineTo(N, ExtLoad);
3253 CombineTo(N0.getNode(),
3254 DAG.getNode(ISD::TRUNCATE, N0.getValueType(), ExtLoad),
3255 ExtLoad.getValue(1));
3256 return SDValue(N, 0); // Return N so it doesn't get rechecked!
3259 // aext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
3260 if (N0.getOpcode() == ISD::SETCC) {
3262 SimplifySelectCC(N0.getOperand(0), N0.getOperand(1),
3263 DAG.getConstant(1, VT), DAG.getConstant(0, VT),
3264 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
3272 /// GetDemandedBits - See if the specified operand can be simplified with the
3273 /// knowledge that only the bits specified by Mask are used. If so, return the
3274 /// simpler operand, otherwise return a null SDValue.
3275 SDValue DAGCombiner::GetDemandedBits(SDValue V, const APInt &Mask) {
3276 switch (V.getOpcode()) {
3280 // If the LHS or RHS don't contribute bits to the or, drop them.
3281 if (DAG.MaskedValueIsZero(V.getOperand(0), Mask))
3282 return V.getOperand(1);
3283 if (DAG.MaskedValueIsZero(V.getOperand(1), Mask))
3284 return V.getOperand(0);
3287 // Only look at single-use SRLs.
3288 if (!V.getNode()->hasOneUse())
3290 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(V.getOperand(1))) {
3291 // See if we can recursively simplify the LHS.
3292 unsigned Amt = RHSC->getZExtValue();
3293 // Watch out for shift count overflow though.
3294 if (Amt >= Mask.getBitWidth()) break;
3295 APInt NewMask = Mask << Amt;
3296 SDValue SimplifyLHS = GetDemandedBits(V.getOperand(0), NewMask);
3297 if (SimplifyLHS.getNode()) {
3298 return DAG.getNode(ISD::SRL, V.getValueType(),
3299 SimplifyLHS, V.getOperand(1));
3306 /// ReduceLoadWidth - If the result of a wider load is shifted to right of N
3307 /// bits and then truncated to a narrower type and where N is a multiple
3308 /// of number of bits of the narrower type, transform it to a narrower load
3309 /// from address + N / num of bits of new type. If the result is to be
3310 /// extended, also fold the extension to form a extending load.
3311 SDValue DAGCombiner::ReduceLoadWidth(SDNode *N) {
3312 unsigned Opc = N->getOpcode();
3313 ISD::LoadExtType ExtType = ISD::NON_EXTLOAD;
3314 SDValue N0 = N->getOperand(0);
3315 MVT VT = N->getValueType(0);
3318 // This transformation isn't valid for vector loads.
3322 // Special case: SIGN_EXTEND_INREG is basically truncating to EVT then
3324 if (Opc == ISD::SIGN_EXTEND_INREG) {
3325 ExtType = ISD::SEXTLOAD;
3326 EVT = cast<VTSDNode>(N->getOperand(1))->getVT();
3327 if (LegalOperations && !TLI.isLoadExtLegal(ISD::SEXTLOAD, EVT))
3331 unsigned EVTBits = EVT.getSizeInBits();
3333 if (N0.getOpcode() == ISD::SRL && N0.hasOneUse()) {
3334 if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
3335 ShAmt = N01->getZExtValue();
3336 // Is the shift amount a multiple of size of VT?
3337 if ((ShAmt & (EVTBits-1)) == 0) {
3338 N0 = N0.getOperand(0);
3339 if (N0.getValueType().getSizeInBits() <= EVTBits)
3345 // Do not generate loads of non-round integer types since these can
3346 // be expensive (and would be wrong if the type is not byte sized).
3347 if (isa<LoadSDNode>(N0) && N0.hasOneUse() && EVT.isRound() &&
3348 cast<LoadSDNode>(N0)->getMemoryVT().getSizeInBits() > EVTBits &&
3349 // Do not change the width of a volatile load.
3350 !cast<LoadSDNode>(N0)->isVolatile()) {
3351 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
3352 MVT PtrType = N0.getOperand(1).getValueType();
3353 // For big endian targets, we need to adjust the offset to the pointer to
3354 // load the correct bytes.
3355 if (TLI.isBigEndian()) {
3356 unsigned LVTStoreBits = LN0->getMemoryVT().getStoreSizeInBits();
3357 unsigned EVTStoreBits = EVT.getStoreSizeInBits();
3358 ShAmt = LVTStoreBits - EVTStoreBits - ShAmt;
3360 uint64_t PtrOff = ShAmt / 8;
3361 unsigned NewAlign = MinAlign(LN0->getAlignment(), PtrOff);
3362 SDValue NewPtr = DAG.getNode(ISD::ADD, PtrType, LN0->getBasePtr(),
3363 DAG.getConstant(PtrOff, PtrType));
3364 AddToWorkList(NewPtr.getNode());
3365 SDValue Load = (ExtType == ISD::NON_EXTLOAD)
3366 ? DAG.getLoad(VT, LN0->getChain(), NewPtr,
3367 LN0->getSrcValue(), LN0->getSrcValueOffset() + PtrOff,
3368 LN0->isVolatile(), NewAlign)
3369 : DAG.getExtLoad(ExtType, VT, LN0->getChain(), NewPtr,
3370 LN0->getSrcValue(), LN0->getSrcValueOffset() + PtrOff,
3371 EVT, LN0->isVolatile(), NewAlign);
3372 // Replace the old load's chain with the new load's chain.
3373 WorkListRemover DeadNodes(*this);
3374 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1),
3376 // Return the new loaded value.
3384 SDValue DAGCombiner::visitSIGN_EXTEND_INREG(SDNode *N) {
3385 SDValue N0 = N->getOperand(0);
3386 SDValue N1 = N->getOperand(1);
3387 MVT VT = N->getValueType(0);
3388 MVT EVT = cast<VTSDNode>(N1)->getVT();
3389 unsigned VTBits = VT.getSizeInBits();
3390 unsigned EVTBits = EVT.getSizeInBits();
3392 // fold (sext_in_reg c1) -> c1
3393 if (isa<ConstantSDNode>(N0) || N0.getOpcode() == ISD::UNDEF)
3394 return DAG.getNode(ISD::SIGN_EXTEND_INREG, VT, N0, N1);
3396 // If the input is already sign extended, just drop the extension.
3397 if (DAG.ComputeNumSignBits(N0) >= VT.getSizeInBits()-EVTBits+1)
3400 // fold (sext_in_reg (sext_in_reg x, VT2), VT1) -> (sext_in_reg x, minVT) pt2
3401 if (N0.getOpcode() == ISD::SIGN_EXTEND_INREG &&
3402 EVT.bitsLT(cast<VTSDNode>(N0.getOperand(1))->getVT())) {
3403 return DAG.getNode(ISD::SIGN_EXTEND_INREG, VT, N0.getOperand(0), N1);
3406 // fold (sext_in_reg (sext x)) -> (sext x)
3407 // fold (sext_in_reg (aext x)) -> (sext x)
3408 // if x is small enough.
3409 if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND) {
3410 SDValue N00 = N0.getOperand(0);
3411 if (N00.getValueType().getSizeInBits() < EVTBits)
3412 return DAG.getNode(ISD::SIGN_EXTEND, VT, N00, N1);
3415 // fold (sext_in_reg x) -> (zext_in_reg x) if the sign bit is known zero.
3416 if (DAG.MaskedValueIsZero(N0, APInt::getBitsSet(VTBits, EVTBits-1, EVTBits)))
3417 return DAG.getZeroExtendInReg(N0, EVT);
3419 // fold operands of sext_in_reg based on knowledge that the top bits are not
3421 if (SimplifyDemandedBits(SDValue(N, 0)))
3422 return SDValue(N, 0);
3424 // fold (sext_in_reg (load x)) -> (smaller sextload x)
3425 // fold (sext_in_reg (srl (load x), c)) -> (smaller sextload (x+c/evtbits))
3426 SDValue NarrowLoad = ReduceLoadWidth(N);
3427 if (NarrowLoad.getNode())
3430 // fold (sext_in_reg (srl X, 24), i8) -> sra X, 24
3431 // fold (sext_in_reg (srl X, 23), i8) -> sra X, 23 iff possible.
3432 // We already fold "(sext_in_reg (srl X, 25), i8) -> srl X, 25" above.
3433 if (N0.getOpcode() == ISD::SRL) {
3434 if (ConstantSDNode *ShAmt = dyn_cast<ConstantSDNode>(N0.getOperand(1)))
3435 if (ShAmt->getZExtValue()+EVTBits <= VT.getSizeInBits()) {
3436 // We can turn this into an SRA iff the input to the SRL is already sign
3438 unsigned InSignBits = DAG.ComputeNumSignBits(N0.getOperand(0));
3439 if (VT.getSizeInBits()-(ShAmt->getZExtValue()+EVTBits) < InSignBits)
3440 return DAG.getNode(ISD::SRA, VT, N0.getOperand(0), N0.getOperand(1));
3444 // fold (sext_inreg (extload x)) -> (sextload x)
3445 if (ISD::isEXTLoad(N0.getNode()) &&
3446 ISD::isUNINDEXEDLoad(N0.getNode()) &&
3447 EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
3448 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
3449 TLI.isLoadExtLegal(ISD::SEXTLOAD, EVT))) {
3450 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
3451 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, VT, LN0->getChain(),
3452 LN0->getBasePtr(), LN0->getSrcValue(),
3453 LN0->getSrcValueOffset(), EVT,
3454 LN0->isVolatile(), LN0->getAlignment());
3455 CombineTo(N, ExtLoad);
3456 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
3457 return SDValue(N, 0); // Return N so it doesn't get rechecked!
3459 // fold (sext_inreg (zextload x)) -> (sextload x) iff load has one use
3460 if (ISD::isZEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
3462 EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
3463 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
3464 TLI.isLoadExtLegal(ISD::SEXTLOAD, EVT))) {
3465 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
3466 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, VT, LN0->getChain(),
3467 LN0->getBasePtr(), LN0->getSrcValue(),
3468 LN0->getSrcValueOffset(), EVT,
3469 LN0->isVolatile(), LN0->getAlignment());
3470 CombineTo(N, ExtLoad);
3471 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
3472 return SDValue(N, 0); // Return N so it doesn't get rechecked!
3477 SDValue DAGCombiner::visitTRUNCATE(SDNode *N) {
3478 SDValue N0 = N->getOperand(0);
3479 MVT VT = N->getValueType(0);
3482 if (N0.getValueType() == N->getValueType(0))
3484 // fold (truncate c1) -> c1
3485 if (isa<ConstantSDNode>(N0))
3486 return DAG.getNode(ISD::TRUNCATE, VT, N0);
3487 // fold (truncate (truncate x)) -> (truncate x)
3488 if (N0.getOpcode() == ISD::TRUNCATE)
3489 return DAG.getNode(ISD::TRUNCATE, VT, N0.getOperand(0));
3490 // fold (truncate (ext x)) -> (ext x) or (truncate x) or x
3491 if (N0.getOpcode() == ISD::ZERO_EXTEND || N0.getOpcode() == ISD::SIGN_EXTEND||
3492 N0.getOpcode() == ISD::ANY_EXTEND) {
3493 if (N0.getOperand(0).getValueType().bitsLT(VT))
3494 // if the source is smaller than the dest, we still need an extend
3495 return DAG.getNode(N0.getOpcode(), VT, N0.getOperand(0));
3496 else if (N0.getOperand(0).getValueType().bitsGT(VT))
3497 // if the source is larger than the dest, than we just need the truncate
3498 return DAG.getNode(ISD::TRUNCATE, VT, N0.getOperand(0));
3500 // if the source and dest are the same type, we can drop both the extend
3502 return N0.getOperand(0);
3505 // See if we can simplify the input to this truncate through knowledge that
3506 // only the low bits are being used. For example "trunc (or (shl x, 8), y)"
3509 GetDemandedBits(N0, APInt::getLowBitsSet(N0.getValueSizeInBits(),
3510 VT.getSizeInBits()));
3511 if (Shorter.getNode())
3512 return DAG.getNode(ISD::TRUNCATE, VT, Shorter);
3514 // fold (truncate (load x)) -> (smaller load x)
3515 // fold (truncate (srl (load x), c)) -> (smaller load (x+c/evtbits))
3516 return ReduceLoadWidth(N);
3519 static SDNode *getBuildPairElt(SDNode *N, unsigned i) {
3520 SDValue Elt = N->getOperand(i);
3521 if (Elt.getOpcode() != ISD::MERGE_VALUES)
3522 return Elt.getNode();
3523 return Elt.getOperand(Elt.getResNo()).getNode();
3526 /// CombineConsecutiveLoads - build_pair (load, load) -> load
3527 /// if load locations are consecutive.
3528 SDValue DAGCombiner::CombineConsecutiveLoads(SDNode *N, MVT VT) {
3529 assert(N->getOpcode() == ISD::BUILD_PAIR);
3531 SDNode *LD1 = getBuildPairElt(N, 0);
3532 if (!ISD::isNON_EXTLoad(LD1) || !LD1->hasOneUse())
3534 MVT LD1VT = LD1->getValueType(0);
3535 SDNode *LD2 = getBuildPairElt(N, 1);
3536 const MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
3537 if (ISD::isNON_EXTLoad(LD2) &&
3539 // If both are volatile this would reduce the number of volatile loads.
3540 // If one is volatile it might be ok, but play conservative and bail out.
3541 !cast<LoadSDNode>(LD1)->isVolatile() &&
3542 !cast<LoadSDNode>(LD2)->isVolatile() &&
3543 TLI.isConsecutiveLoad(LD2, LD1, LD1VT.getSizeInBits()/8, 1, MFI)) {
3544 LoadSDNode *LD = cast<LoadSDNode>(LD1);
3545 unsigned Align = LD->getAlignment();
3546 unsigned NewAlign = TLI.getTargetData()->
3547 getABITypeAlignment(VT.getTypeForMVT());
3548 if (NewAlign <= Align &&
3549 (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT)))
3550 return DAG.getLoad(VT, LD->getChain(), LD->getBasePtr(),
3551 LD->getSrcValue(), LD->getSrcValueOffset(),
3557 SDValue DAGCombiner::visitBIT_CONVERT(SDNode *N) {
3558 SDValue N0 = N->getOperand(0);
3559 MVT VT = N->getValueType(0);
3561 // If the input is a BUILD_VECTOR with all constant elements, fold this now.
3562 // Only do this before legalize, since afterward the target may be depending
3563 // on the bitconvert.
3564 // First check to see if this is all constant.
3566 N0.getOpcode() == ISD::BUILD_VECTOR && N0.getNode()->hasOneUse() &&
3568 bool isSimple = true;
3569 for (unsigned i = 0, e = N0.getNumOperands(); i != e; ++i)
3570 if (N0.getOperand(i).getOpcode() != ISD::UNDEF &&
3571 N0.getOperand(i).getOpcode() != ISD::Constant &&
3572 N0.getOperand(i).getOpcode() != ISD::ConstantFP) {
3577 MVT DestEltVT = N->getValueType(0).getVectorElementType();
3578 assert(!DestEltVT.isVector() &&
3579 "Element type of vector ValueType must not be vector!");
3581 return ConstantFoldBIT_CONVERTofBUILD_VECTOR(N0.getNode(), DestEltVT);
3585 // If the input is a constant, let getNode fold it.
3586 if (isa<ConstantSDNode>(N0) || isa<ConstantFPSDNode>(N0)) {
3587 SDValue Res = DAG.getNode(ISD::BIT_CONVERT, VT, N0);
3588 if (Res.getNode() != N) return Res;
3591 if (N0.getOpcode() == ISD::BIT_CONVERT) // conv(conv(x,t1),t2) -> conv(x,t2)
3592 return DAG.getNode(ISD::BIT_CONVERT, VT, N0.getOperand(0));
3594 // fold (conv (load x)) -> (load (conv*)x)
3595 // If the resultant load doesn't need a higher alignment than the original!
3596 if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
3597 // Do not change the width of a volatile load.
3598 !cast<LoadSDNode>(N0)->isVolatile() &&
3599 (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT))) {
3600 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
3601 unsigned Align = TLI.getTargetData()->
3602 getABITypeAlignment(VT.getTypeForMVT());
3603 unsigned OrigAlign = LN0->getAlignment();
3604 if (Align <= OrigAlign) {
3605 SDValue Load = DAG.getLoad(VT, LN0->getChain(), LN0->getBasePtr(),
3606 LN0->getSrcValue(), LN0->getSrcValueOffset(),
3607 LN0->isVolatile(), OrigAlign);
3609 CombineTo(N0.getNode(),
3610 DAG.getNode(ISD::BIT_CONVERT, N0.getValueType(), Load),
3616 // Fold bitconvert(fneg(x)) -> xor(bitconvert(x), signbit)
3617 // Fold bitconvert(fabs(x)) -> and(bitconvert(x), ~signbit)
3618 // This often reduces constant pool loads.
3619 if ((N0.getOpcode() == ISD::FNEG || N0.getOpcode() == ISD::FABS) &&
3620 N0.getNode()->hasOneUse() && VT.isInteger() && !VT.isVector()) {
3621 SDValue NewConv = DAG.getNode(ISD::BIT_CONVERT, VT, N0.getOperand(0));
3622 AddToWorkList(NewConv.getNode());
3624 APInt SignBit = APInt::getSignBit(VT.getSizeInBits());
3625 if (N0.getOpcode() == ISD::FNEG)
3626 return DAG.getNode(ISD::XOR, VT, NewConv, DAG.getConstant(SignBit, VT));
3627 assert(N0.getOpcode() == ISD::FABS);
3628 return DAG.getNode(ISD::AND, VT, NewConv, DAG.getConstant(~SignBit, VT));
3631 // Fold bitconvert(fcopysign(cst, x)) -> bitconvert(x)&sign | cst&~sign'
3632 // Note that we don't handle copysign(x,cst) because this can always be folded
3633 // to an fneg or fabs.
3634 if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse() &&
3635 isa<ConstantFPSDNode>(N0.getOperand(0)) &&
3636 VT.isInteger() && !VT.isVector()) {
3637 unsigned OrigXWidth = N0.getOperand(1).getValueType().getSizeInBits();
3638 MVT IntXVT = MVT::getIntegerVT(OrigXWidth);
3639 if (TLI.isTypeLegal(IntXVT) || !LegalTypes) {
3640 SDValue X = DAG.getNode(ISD::BIT_CONVERT, IntXVT, N0.getOperand(1));
3641 AddToWorkList(X.getNode());
3643 // If X has a different width than the result/lhs, sext it or truncate it.
3644 unsigned VTWidth = VT.getSizeInBits();
3645 if (OrigXWidth < VTWidth) {
3646 X = DAG.getNode(ISD::SIGN_EXTEND, VT, X);
3647 AddToWorkList(X.getNode());
3648 } else if (OrigXWidth > VTWidth) {
3649 // To get the sign bit in the right place, we have to shift it right
3650 // before truncating.
3651 X = DAG.getNode(ISD::SRL, X.getValueType(), X,
3652 DAG.getConstant(OrigXWidth-VTWidth, X.getValueType()));
3653 AddToWorkList(X.getNode());
3654 X = DAG.getNode(ISD::TRUNCATE, VT, X);
3655 AddToWorkList(X.getNode());
3658 APInt SignBit = APInt::getSignBit(VT.getSizeInBits());
3659 X = DAG.getNode(ISD::AND, VT, X, DAG.getConstant(SignBit, VT));
3660 AddToWorkList(X.getNode());
3662 SDValue Cst = DAG.getNode(ISD::BIT_CONVERT, VT, N0.getOperand(0));
3663 Cst = DAG.getNode(ISD::AND, VT, Cst, DAG.getConstant(~SignBit, VT));
3664 AddToWorkList(Cst.getNode());
3666 return DAG.getNode(ISD::OR, VT, X, Cst);
3670 // bitconvert(build_pair(ld, ld)) -> ld iff load locations are consecutive.
3671 if (N0.getOpcode() == ISD::BUILD_PAIR) {
3672 SDValue CombineLD = CombineConsecutiveLoads(N0.getNode(), VT);
3673 if (CombineLD.getNode())
3680 SDValue DAGCombiner::visitBUILD_PAIR(SDNode *N) {
3681 MVT VT = N->getValueType(0);
3682 return CombineConsecutiveLoads(N, VT);
3685 /// ConstantFoldBIT_CONVERTofBUILD_VECTOR - We know that BV is a build_vector
3686 /// node with Constant, ConstantFP or Undef operands. DstEltVT indicates the
3687 /// destination element value type.
3688 SDValue DAGCombiner::
3689 ConstantFoldBIT_CONVERTofBUILD_VECTOR(SDNode *BV, MVT DstEltVT) {
3690 MVT SrcEltVT = BV->getOperand(0).getValueType();
3692 // If this is already the right type, we're done.
3693 if (SrcEltVT == DstEltVT) return SDValue(BV, 0);
3695 unsigned SrcBitSize = SrcEltVT.getSizeInBits();
3696 unsigned DstBitSize = DstEltVT.getSizeInBits();
3698 // If this is a conversion of N elements of one type to N elements of another
3699 // type, convert each element. This handles FP<->INT cases.
3700 if (SrcBitSize == DstBitSize) {
3701 SmallVector<SDValue, 8> Ops;
3702 for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) {
3703 Ops.push_back(DAG.getNode(ISD::BIT_CONVERT, DstEltVT, BV->getOperand(i)));
3704 AddToWorkList(Ops.back().getNode());
3706 MVT VT = MVT::getVectorVT(DstEltVT,
3707 BV->getValueType(0).getVectorNumElements());
3708 return DAG.getNode(ISD::BUILD_VECTOR, VT, &Ops[0], Ops.size());
3711 // Otherwise, we're growing or shrinking the elements. To avoid having to
3712 // handle annoying details of growing/shrinking FP values, we convert them to
3714 if (SrcEltVT.isFloatingPoint()) {
3715 // Convert the input float vector to a int vector where the elements are the
3717 assert((SrcEltVT == MVT::f32 || SrcEltVT == MVT::f64) && "Unknown FP VT!");
3718 MVT IntVT = MVT::getIntegerVT(SrcEltVT.getSizeInBits());
3719 BV = ConstantFoldBIT_CONVERTofBUILD_VECTOR(BV, IntVT).getNode();
3723 // Now we know the input is an integer vector. If the output is a FP type,
3724 // convert to integer first, then to FP of the right size.
3725 if (DstEltVT.isFloatingPoint()) {
3726 assert((DstEltVT == MVT::f32 || DstEltVT == MVT::f64) && "Unknown FP VT!");
3727 MVT TmpVT = MVT::getIntegerVT(DstEltVT.getSizeInBits());
3728 SDNode *Tmp = ConstantFoldBIT_CONVERTofBUILD_VECTOR(BV, TmpVT).getNode();
3730 // Next, convert to FP elements of the same size.
3731 return ConstantFoldBIT_CONVERTofBUILD_VECTOR(Tmp, DstEltVT);
3734 // Okay, we know the src/dst types are both integers of differing types.
3735 // Handling growing first.
3736 assert(SrcEltVT.isInteger() && DstEltVT.isInteger());
3737 if (SrcBitSize < DstBitSize) {
3738 unsigned NumInputsPerOutput = DstBitSize/SrcBitSize;
3740 SmallVector<SDValue, 8> Ops;
3741 for (unsigned i = 0, e = BV->getNumOperands(); i != e;
3742 i += NumInputsPerOutput) {
3743 bool isLE = TLI.isLittleEndian();
3744 APInt NewBits = APInt(DstBitSize, 0);
3745 bool EltIsUndef = true;
3746 for (unsigned j = 0; j != NumInputsPerOutput; ++j) {
3747 // Shift the previously computed bits over.
3748 NewBits <<= SrcBitSize;
3749 SDValue Op = BV->getOperand(i+ (isLE ? (NumInputsPerOutput-j-1) : j));
3750 if (Op.getOpcode() == ISD::UNDEF) continue;
3754 APInt(cast<ConstantSDNode>(Op)->getAPIntValue()).zext(DstBitSize);
3758 Ops.push_back(DAG.getNode(ISD::UNDEF, DstEltVT));
3760 Ops.push_back(DAG.getConstant(NewBits, DstEltVT));
3763 MVT VT = MVT::getVectorVT(DstEltVT, Ops.size());
3764 return DAG.getNode(ISD::BUILD_VECTOR, VT, &Ops[0], Ops.size());
3767 // Finally, this must be the case where we are shrinking elements: each input
3768 // turns into multiple outputs.
3769 bool isS2V = ISD::isScalarToVector(BV);
3770 unsigned NumOutputsPerInput = SrcBitSize/DstBitSize;
3771 MVT VT = MVT::getVectorVT(DstEltVT, NumOutputsPerInput*BV->getNumOperands());
3772 SmallVector<SDValue, 8> Ops;
3773 for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) {
3774 if (BV->getOperand(i).getOpcode() == ISD::UNDEF) {
3775 for (unsigned j = 0; j != NumOutputsPerInput; ++j)
3776 Ops.push_back(DAG.getNode(ISD::UNDEF, DstEltVT));
3779 APInt OpVal = cast<ConstantSDNode>(BV->getOperand(i))->getAPIntValue();
3780 for (unsigned j = 0; j != NumOutputsPerInput; ++j) {
3781 APInt ThisVal = APInt(OpVal).trunc(DstBitSize);
3782 Ops.push_back(DAG.getConstant(ThisVal, DstEltVT));
3783 if (isS2V && i == 0 && j == 0 && APInt(ThisVal).zext(SrcBitSize) == OpVal)
3784 // Simply turn this into a SCALAR_TO_VECTOR of the new type.
3785 return DAG.getNode(ISD::SCALAR_TO_VECTOR, VT, Ops[0]);
3786 OpVal = OpVal.lshr(DstBitSize);
3789 // For big endian targets, swap the order of the pieces of each element.
3790 if (TLI.isBigEndian())
3791 std::reverse(Ops.end()-NumOutputsPerInput, Ops.end());
3793 return DAG.getNode(ISD::BUILD_VECTOR, VT, &Ops[0], Ops.size());
3798 SDValue DAGCombiner::visitFADD(SDNode *N) {
3799 SDValue N0 = N->getOperand(0);
3800 SDValue N1 = N->getOperand(1);
3801 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
3802 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
3803 MVT VT = N->getValueType(0);
3806 if (VT.isVector()) {
3807 SDValue FoldedVOp = SimplifyVBinOp(N);
3808 if (FoldedVOp.getNode()) return FoldedVOp;
3811 // fold (fadd c1, c2) -> c1+c2
3812 if (N0CFP && N1CFP && VT != MVT::ppcf128)
3813 return DAG.getNode(ISD::FADD, VT, N0, N1);
3814 // canonicalize constant to RHS
3815 if (N0CFP && !N1CFP)
3816 return DAG.getNode(ISD::FADD, VT, N1, N0);
3817 // fold (A + (-B)) -> A-B
3818 if (isNegatibleForFree(N1, LegalOperations) == 2)
3819 return DAG.getNode(ISD::FSUB, VT, N0,
3820 GetNegatedExpression(N1, DAG, LegalOperations));
3821 // fold ((-A) + B) -> B-A
3822 if (isNegatibleForFree(N0, LegalOperations) == 2)
3823 return DAG.getNode(ISD::FSUB, VT, N1,
3824 GetNegatedExpression(N0, DAG, LegalOperations));
3826 // If allowed, fold (fadd (fadd x, c1), c2) -> (fadd x, (fadd c1, c2))
3827 if (UnsafeFPMath && N1CFP && N0.getOpcode() == ISD::FADD &&
3828 N0.getNode()->hasOneUse() && isa<ConstantFPSDNode>(N0.getOperand(1)))
3829 return DAG.getNode(ISD::FADD, VT, N0.getOperand(0),
3830 DAG.getNode(ISD::FADD, VT, N0.getOperand(1), N1));
3835 SDValue DAGCombiner::visitFSUB(SDNode *N) {
3836 SDValue N0 = N->getOperand(0);
3837 SDValue N1 = N->getOperand(1);
3838 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
3839 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
3840 MVT VT = N->getValueType(0);
3843 if (VT.isVector()) {
3844 SDValue FoldedVOp = SimplifyVBinOp(N);
3845 if (FoldedVOp.getNode()) return FoldedVOp;
3848 // fold (fsub c1, c2) -> c1-c2
3849 if (N0CFP && N1CFP && VT != MVT::ppcf128)
3850 return DAG.getNode(ISD::FSUB, VT, N0, N1);
3852 if (UnsafeFPMath && N0CFP && N0CFP->getValueAPF().isZero()) {
3853 if (isNegatibleForFree(N1, LegalOperations))
3854 return GetNegatedExpression(N1, DAG, LegalOperations);
3855 return DAG.getNode(ISD::FNEG, VT, N1);
3857 // fold (A-(-B)) -> A+B
3858 if (isNegatibleForFree(N1, LegalOperations))
3859 return DAG.getNode(ISD::FADD, VT, N0,
3860 GetNegatedExpression(N1, DAG, LegalOperations));
3865 SDValue DAGCombiner::visitFMUL(SDNode *N) {
3866 SDValue N0 = N->getOperand(0);
3867 SDValue N1 = N->getOperand(1);
3868 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
3869 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
3870 MVT VT = N->getValueType(0);
3873 if (VT.isVector()) {
3874 SDValue FoldedVOp = SimplifyVBinOp(N);
3875 if (FoldedVOp.getNode()) return FoldedVOp;
3878 // fold (fmul c1, c2) -> c1*c2
3879 if (N0CFP && N1CFP && VT != MVT::ppcf128)
3880 return DAG.getNode(ISD::FMUL, VT, N0, N1);
3881 // canonicalize constant to RHS
3882 if (N0CFP && !N1CFP)
3883 return DAG.getNode(ISD::FMUL, VT, N1, N0);
3884 // fold (fmul X, 2.0) -> (fadd X, X)
3885 if (N1CFP && N1CFP->isExactlyValue(+2.0))
3886 return DAG.getNode(ISD::FADD, VT, N0, N0);
3887 // fold (fmul X, -1.0) -> (fneg X)
3888 if (N1CFP && N1CFP->isExactlyValue(-1.0))
3889 return DAG.getNode(ISD::FNEG, VT, N0);
3892 if (char LHSNeg = isNegatibleForFree(N0, LegalOperations)) {
3893 if (char RHSNeg = isNegatibleForFree(N1, LegalOperations)) {
3894 // Both can be negated for free, check to see if at least one is cheaper
3896 if (LHSNeg == 2 || RHSNeg == 2)
3897 return DAG.getNode(ISD::FMUL, VT,
3898 GetNegatedExpression(N0, DAG, LegalOperations),
3899 GetNegatedExpression(N1, DAG, LegalOperations));
3903 // If allowed, fold (fmul (fmul x, c1), c2) -> (fmul x, (fmul c1, c2))
3904 if (UnsafeFPMath && N1CFP && N0.getOpcode() == ISD::FMUL &&
3905 N0.getNode()->hasOneUse() && isa<ConstantFPSDNode>(N0.getOperand(1)))
3906 return DAG.getNode(ISD::FMUL, VT, N0.getOperand(0),
3907 DAG.getNode(ISD::FMUL, VT, N0.getOperand(1), N1));
3912 SDValue DAGCombiner::visitFDIV(SDNode *N) {
3913 SDValue N0 = N->getOperand(0);
3914 SDValue N1 = N->getOperand(1);
3915 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
3916 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
3917 MVT VT = N->getValueType(0);
3920 if (VT.isVector()) {
3921 SDValue FoldedVOp = SimplifyVBinOp(N);
3922 if (FoldedVOp.getNode()) return FoldedVOp;
3925 // fold (fdiv c1, c2) -> c1/c2
3926 if (N0CFP && N1CFP && VT != MVT::ppcf128)
3927 return DAG.getNode(ISD::FDIV, VT, N0, N1);
3931 if (char LHSNeg = isNegatibleForFree(N0, LegalOperations)) {
3932 if (char RHSNeg = isNegatibleForFree(N1, LegalOperations)) {
3933 // Both can be negated for free, check to see if at least one is cheaper
3935 if (LHSNeg == 2 || RHSNeg == 2)
3936 return DAG.getNode(ISD::FDIV, VT,
3937 GetNegatedExpression(N0, DAG, LegalOperations),
3938 GetNegatedExpression(N1, DAG, LegalOperations));
3945 SDValue DAGCombiner::visitFREM(SDNode *N) {
3946 SDValue N0 = N->getOperand(0);
3947 SDValue N1 = N->getOperand(1);
3948 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
3949 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
3950 MVT VT = N->getValueType(0);
3952 // fold (frem c1, c2) -> fmod(c1,c2)
3953 if (N0CFP && N1CFP && VT != MVT::ppcf128)
3954 return DAG.getNode(ISD::FREM, VT, N0, N1);
3959 SDValue DAGCombiner::visitFCOPYSIGN(SDNode *N) {
3960 SDValue N0 = N->getOperand(0);
3961 SDValue N1 = N->getOperand(1);
3962 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
3963 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
3964 MVT VT = N->getValueType(0);
3966 if (N0CFP && N1CFP && VT != MVT::ppcf128) // Constant fold
3967 return DAG.getNode(ISD::FCOPYSIGN, VT, N0, N1);
3970 const APFloat& V = N1CFP->getValueAPF();
3971 // copysign(x, c1) -> fabs(x) iff ispos(c1)
3972 // copysign(x, c1) -> fneg(fabs(x)) iff isneg(c1)
3973 if (!V.isNegative())
3974 return DAG.getNode(ISD::FABS, VT, N0);
3976 return DAG.getNode(ISD::FNEG, VT, DAG.getNode(ISD::FABS, VT, N0));
3979 // copysign(fabs(x), y) -> copysign(x, y)
3980 // copysign(fneg(x), y) -> copysign(x, y)
3981 // copysign(copysign(x,z), y) -> copysign(x, y)
3982 if (N0.getOpcode() == ISD::FABS || N0.getOpcode() == ISD::FNEG ||
3983 N0.getOpcode() == ISD::FCOPYSIGN)
3984 return DAG.getNode(ISD::FCOPYSIGN, VT, N0.getOperand(0), N1);
3986 // copysign(x, abs(y)) -> abs(x)
3987 if (N1.getOpcode() == ISD::FABS)
3988 return DAG.getNode(ISD::FABS, VT, N0);
3990 // copysign(x, copysign(y,z)) -> copysign(x, z)
3991 if (N1.getOpcode() == ISD::FCOPYSIGN)
3992 return DAG.getNode(ISD::FCOPYSIGN, VT, N0, N1.getOperand(1));
3994 // copysign(x, fp_extend(y)) -> copysign(x, y)
3995 // copysign(x, fp_round(y)) -> copysign(x, y)
3996 if (N1.getOpcode() == ISD::FP_EXTEND || N1.getOpcode() == ISD::FP_ROUND)
3997 return DAG.getNode(ISD::FCOPYSIGN, VT, N0, N1.getOperand(0));
4004 SDValue DAGCombiner::visitSINT_TO_FP(SDNode *N) {
4005 SDValue N0 = N->getOperand(0);
4006 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
4007 MVT VT = N->getValueType(0);
4008 MVT OpVT = N0.getValueType();
4010 // fold (sint_to_fp c1) -> c1fp
4011 if (N0C && OpVT != MVT::ppcf128)
4012 return DAG.getNode(ISD::SINT_TO_FP, VT, N0);
4014 // If the input is a legal type, and SINT_TO_FP is not legal on this target,
4015 // but UINT_TO_FP is legal on this target, try to convert.
4016 if (!TLI.isOperationLegal(ISD::SINT_TO_FP, OpVT) &&
4017 TLI.isOperationLegal(ISD::UINT_TO_FP, OpVT)) {
4018 // If the sign bit is known to be zero, we can change this to UINT_TO_FP.
4019 if (DAG.SignBitIsZero(N0))
4020 return DAG.getNode(ISD::UINT_TO_FP, VT, N0);
4027 SDValue DAGCombiner::visitUINT_TO_FP(SDNode *N) {
4028 SDValue N0 = N->getOperand(0);
4029 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
4030 MVT VT = N->getValueType(0);
4031 MVT OpVT = N0.getValueType();
4033 // fold (uint_to_fp c1) -> c1fp
4034 if (N0C && OpVT != MVT::ppcf128)
4035 return DAG.getNode(ISD::UINT_TO_FP, VT, N0);
4037 // If the input is a legal type, and UINT_TO_FP is not legal on this target,
4038 // but SINT_TO_FP is legal on this target, try to convert.
4039 if (!TLI.isOperationLegal(ISD::UINT_TO_FP, OpVT) &&
4040 TLI.isOperationLegal(ISD::SINT_TO_FP, OpVT)) {
4041 // If the sign bit is known to be zero, we can change this to SINT_TO_FP.
4042 if (DAG.SignBitIsZero(N0))
4043 return DAG.getNode(ISD::SINT_TO_FP, VT, N0);
4049 SDValue DAGCombiner::visitFP_TO_SINT(SDNode *N) {
4050 SDValue N0 = N->getOperand(0);
4051 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
4052 MVT VT = N->getValueType(0);
4054 // fold (fp_to_sint c1fp) -> c1
4056 return DAG.getNode(ISD::FP_TO_SINT, VT, N0);
4060 SDValue DAGCombiner::visitFP_TO_UINT(SDNode *N) {
4061 SDValue N0 = N->getOperand(0);
4062 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
4063 MVT VT = N->getValueType(0);
4065 // fold (fp_to_uint c1fp) -> c1
4066 if (N0CFP && VT != MVT::ppcf128)
4067 return DAG.getNode(ISD::FP_TO_UINT, VT, N0);
4071 SDValue DAGCombiner::visitFP_ROUND(SDNode *N) {
4072 SDValue N0 = N->getOperand(0);
4073 SDValue N1 = N->getOperand(1);
4074 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
4075 MVT VT = N->getValueType(0);
4077 // fold (fp_round c1fp) -> c1fp
4078 if (N0CFP && N0.getValueType() != MVT::ppcf128)
4079 return DAG.getNode(ISD::FP_ROUND, VT, N0, N1);
4081 // fold (fp_round (fp_extend x)) -> x
4082 if (N0.getOpcode() == ISD::FP_EXTEND && VT == N0.getOperand(0).getValueType())
4083 return N0.getOperand(0);
4085 // fold (fp_round (fp_round x)) -> (fp_round x)
4086 if (N0.getOpcode() == ISD::FP_ROUND) {
4087 // This is a value preserving truncation if both round's are.
4088 bool IsTrunc = N->getConstantOperandVal(1) == 1 &&
4089 N0.getNode()->getConstantOperandVal(1) == 1;
4090 return DAG.getNode(ISD::FP_ROUND, VT, N0.getOperand(0),
4091 DAG.getIntPtrConstant(IsTrunc));
4094 // fold (fp_round (copysign X, Y)) -> (copysign (fp_round X), Y)
4095 if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse()) {
4096 SDValue Tmp = DAG.getNode(ISD::FP_ROUND, VT, N0.getOperand(0), N1);
4097 AddToWorkList(Tmp.getNode());
4098 return DAG.getNode(ISD::FCOPYSIGN, VT, Tmp, N0.getOperand(1));
4104 SDValue DAGCombiner::visitFP_ROUND_INREG(SDNode *N) {
4105 SDValue N0 = N->getOperand(0);
4106 MVT VT = N->getValueType(0);
4107 MVT EVT = cast<VTSDNode>(N->getOperand(1))->getVT();
4108 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
4110 // fold (fp_round_inreg c1fp) -> c1fp
4111 if (N0CFP && (TLI.isTypeLegal(EVT) || !LegalTypes)) {
4112 SDValue Round = DAG.getConstantFP(*N0CFP->getConstantFPValue(), EVT);
4113 return DAG.getNode(ISD::FP_EXTEND, VT, Round);
4118 SDValue DAGCombiner::visitFP_EXTEND(SDNode *N) {
4119 SDValue N0 = N->getOperand(0);
4120 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
4121 MVT VT = N->getValueType(0);
4123 // If this is fp_round(fpextend), don't fold it, allow ourselves to be folded.
4124 if (N->hasOneUse() &&
4125 N->use_begin().getUse().getSDValue().getOpcode() == ISD::FP_ROUND)
4128 // fold (fp_extend c1fp) -> c1fp
4129 if (N0CFP && VT != MVT::ppcf128)
4130 return DAG.getNode(ISD::FP_EXTEND, VT, N0);
4132 // Turn fp_extend(fp_round(X, 1)) -> x since the fp_round doesn't affect the
4134 if (N0.getOpcode() == ISD::FP_ROUND
4135 && N0.getNode()->getConstantOperandVal(1) == 1) {
4136 SDValue In = N0.getOperand(0);
4137 if (In.getValueType() == VT) return In;
4138 if (VT.bitsLT(In.getValueType()))
4139 return DAG.getNode(ISD::FP_ROUND, VT, In, N0.getOperand(1));
4140 return DAG.getNode(ISD::FP_EXTEND, VT, In);
4143 // fold (fpext (load x)) -> (fpext (fptrunc (extload x)))
4144 if (ISD::isNON_EXTLoad(N0.getNode()) && N0.hasOneUse() &&
4145 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
4146 TLI.isLoadExtLegal(ISD::EXTLOAD, N0.getValueType()))) {
4147 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
4148 SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, VT, LN0->getChain(),
4149 LN0->getBasePtr(), LN0->getSrcValue(),
4150 LN0->getSrcValueOffset(),
4152 LN0->isVolatile(), LN0->getAlignment());
4153 CombineTo(N, ExtLoad);
4154 CombineTo(N0.getNode(), DAG.getNode(ISD::FP_ROUND, N0.getValueType(),
4155 ExtLoad, DAG.getIntPtrConstant(1)),
4156 ExtLoad.getValue(1));
4157 return SDValue(N, 0); // Return N so it doesn't get rechecked!
4163 SDValue DAGCombiner::visitFNEG(SDNode *N) {
4164 SDValue N0 = N->getOperand(0);
4166 if (isNegatibleForFree(N0, LegalOperations))
4167 return GetNegatedExpression(N0, DAG, LegalOperations);
4169 // Transform fneg(bitconvert(x)) -> bitconvert(x^sign) to avoid loading
4170 // constant pool values.
4171 if (N0.getOpcode() == ISD::BIT_CONVERT && N0.getNode()->hasOneUse() &&
4172 N0.getOperand(0).getValueType().isInteger() &&
4173 !N0.getOperand(0).getValueType().isVector()) {
4174 SDValue Int = N0.getOperand(0);
4175 MVT IntVT = Int.getValueType();
4176 if (IntVT.isInteger() && !IntVT.isVector()) {
4177 Int = DAG.getNode(ISD::XOR, IntVT, Int,
4178 DAG.getConstant(IntVT.getIntegerVTSignBit(), IntVT));
4179 AddToWorkList(Int.getNode());
4180 return DAG.getNode(ISD::BIT_CONVERT, N->getValueType(0), Int);
4187 SDValue DAGCombiner::visitFABS(SDNode *N) {
4188 SDValue N0 = N->getOperand(0);
4189 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
4190 MVT VT = N->getValueType(0);
4192 // fold (fabs c1) -> fabs(c1)
4193 if (N0CFP && VT != MVT::ppcf128)
4194 return DAG.getNode(ISD::FABS, VT, N0);
4195 // fold (fabs (fabs x)) -> (fabs x)
4196 if (N0.getOpcode() == ISD::FABS)
4197 return N->getOperand(0);
4198 // fold (fabs (fneg x)) -> (fabs x)
4199 // fold (fabs (fcopysign x, y)) -> (fabs x)
4200 if (N0.getOpcode() == ISD::FNEG || N0.getOpcode() == ISD::FCOPYSIGN)
4201 return DAG.getNode(ISD::FABS, VT, N0.getOperand(0));
4203 // Transform fabs(bitconvert(x)) -> bitconvert(x&~sign) to avoid loading
4204 // constant pool values.
4205 if (N0.getOpcode() == ISD::BIT_CONVERT && N0.getNode()->hasOneUse() &&
4206 N0.getOperand(0).getValueType().isInteger() &&
4207 !N0.getOperand(0).getValueType().isVector()) {
4208 SDValue Int = N0.getOperand(0);
4209 MVT IntVT = Int.getValueType();
4210 if (IntVT.isInteger() && !IntVT.isVector()) {
4211 Int = DAG.getNode(ISD::AND, IntVT, Int,
4212 DAG.getConstant(~IntVT.getIntegerVTSignBit(), IntVT));
4213 AddToWorkList(Int.getNode());
4214 return DAG.getNode(ISD::BIT_CONVERT, N->getValueType(0), Int);
4221 SDValue DAGCombiner::visitBRCOND(SDNode *N) {
4222 SDValue Chain = N->getOperand(0);
4223 SDValue N1 = N->getOperand(1);
4224 SDValue N2 = N->getOperand(2);
4225 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4227 // never taken branch, fold to chain
4228 if (N1C && N1C->isNullValue())
4230 // unconditional branch
4231 if (N1C && N1C->getAPIntValue() == 1)
4232 return DAG.getNode(ISD::BR, MVT::Other, Chain, N2);
4233 // fold a brcond with a setcc condition into a BR_CC node if BR_CC is legal
4235 if (N1.getOpcode() == ISD::SETCC &&
4236 TLI.isOperationLegal(ISD::BR_CC, MVT::Other)) {
4237 return DAG.getNode(ISD::BR_CC, MVT::Other, Chain, N1.getOperand(2),
4238 N1.getOperand(0), N1.getOperand(1), N2);
4243 // Operand List for BR_CC: Chain, CondCC, CondLHS, CondRHS, DestBB.
4245 SDValue DAGCombiner::visitBR_CC(SDNode *N) {
4246 CondCodeSDNode *CC = cast<CondCodeSDNode>(N->getOperand(1));
4247 SDValue CondLHS = N->getOperand(2), CondRHS = N->getOperand(3);
4249 // Use SimplifySetCC to simplify SETCC's.
4250 SDValue Simp = SimplifySetCC(TLI.getSetCCResultType(CondLHS.getValueType()),
4251 CondLHS, CondRHS, CC->get(), false);
4252 if (Simp.getNode()) AddToWorkList(Simp.getNode());
4254 ConstantSDNode *SCCC = dyn_cast_or_null<ConstantSDNode>(Simp.getNode());
4256 // fold br_cc true, dest -> br dest (unconditional branch)
4257 if (SCCC && !SCCC->isNullValue())
4258 return DAG.getNode(ISD::BR, MVT::Other, N->getOperand(0),
4260 // fold br_cc false, dest -> unconditional fall through
4261 if (SCCC && SCCC->isNullValue())
4262 return N->getOperand(0);
4264 // fold to a simpler setcc
4265 if (Simp.getNode() && Simp.getOpcode() == ISD::SETCC)
4266 return DAG.getNode(ISD::BR_CC, MVT::Other, N->getOperand(0),
4267 Simp.getOperand(2), Simp.getOperand(0),
4268 Simp.getOperand(1), N->getOperand(4));
4273 /// CombineToPreIndexedLoadStore - Try turning a load / store into a
4274 /// pre-indexed load / store when the base pointer is an add or subtract
4275 /// and it has other uses besides the load / store. After the
4276 /// transformation, the new indexed load / store has effectively folded
4277 /// the add / subtract in and all of its other uses are redirected to the
4278 /// new load / store.
4279 bool DAGCombiner::CombineToPreIndexedLoadStore(SDNode *N) {
4280 if (!LegalOperations)
4286 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
4287 if (LD->isIndexed())
4289 VT = LD->getMemoryVT();
4290 if (!TLI.isIndexedLoadLegal(ISD::PRE_INC, VT) &&
4291 !TLI.isIndexedLoadLegal(ISD::PRE_DEC, VT))
4293 Ptr = LD->getBasePtr();
4294 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
4295 if (ST->isIndexed())
4297 VT = ST->getMemoryVT();
4298 if (!TLI.isIndexedStoreLegal(ISD::PRE_INC, VT) &&
4299 !TLI.isIndexedStoreLegal(ISD::PRE_DEC, VT))
4301 Ptr = ST->getBasePtr();
4306 // If the pointer is not an add/sub, or if it doesn't have multiple uses, bail
4307 // out. There is no reason to make this a preinc/predec.
4308 if ((Ptr.getOpcode() != ISD::ADD && Ptr.getOpcode() != ISD::SUB) ||
4309 Ptr.getNode()->hasOneUse())
4312 // Ask the target to do addressing mode selection.
4315 ISD::MemIndexedMode AM = ISD::UNINDEXED;
4316 if (!TLI.getPreIndexedAddressParts(N, BasePtr, Offset, AM, DAG))
4318 // Don't create a indexed load / store with zero offset.
4319 if (isa<ConstantSDNode>(Offset) &&
4320 cast<ConstantSDNode>(Offset)->isNullValue())
4323 // Try turning it into a pre-indexed load / store except when:
4324 // 1) The new base ptr is a frame index.
4325 // 2) If N is a store and the new base ptr is either the same as or is a
4326 // predecessor of the value being stored.
4327 // 3) Another use of old base ptr is a predecessor of N. If ptr is folded
4328 // that would create a cycle.
4329 // 4) All uses are load / store ops that use it as old base ptr.
4331 // Check #1. Preinc'ing a frame index would require copying the stack pointer
4332 // (plus the implicit offset) to a register to preinc anyway.
4333 if (isa<FrameIndexSDNode>(BasePtr))
4338 SDValue Val = cast<StoreSDNode>(N)->getValue();
4339 if (Val == BasePtr || BasePtr.getNode()->isPredecessorOf(Val.getNode()))
4343 // Now check for #3 and #4.
4344 bool RealUse = false;
4345 for (SDNode::use_iterator I = Ptr.getNode()->use_begin(),
4346 E = Ptr.getNode()->use_end(); I != E; ++I) {
4350 if (Use->isPredecessorOf(N))
4353 if (!((Use->getOpcode() == ISD::LOAD &&
4354 cast<LoadSDNode>(Use)->getBasePtr() == Ptr) ||
4355 (Use->getOpcode() == ISD::STORE &&
4356 cast<StoreSDNode>(Use)->getBasePtr() == Ptr)))
4364 Result = DAG.getIndexedLoad(SDValue(N,0), BasePtr, Offset, AM);
4366 Result = DAG.getIndexedStore(SDValue(N,0), BasePtr, Offset, AM);
4369 DOUT << "\nReplacing.4 "; DEBUG(N->dump(&DAG));
4370 DOUT << "\nWith: "; DEBUG(Result.getNode()->dump(&DAG));
4372 WorkListRemover DeadNodes(*this);
4374 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0),
4376 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2),
4379 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1),
4383 // Finally, since the node is now dead, remove it from the graph.
4386 // Replace the uses of Ptr with uses of the updated base value.
4387 DAG.ReplaceAllUsesOfValueWith(Ptr, Result.getValue(isLoad ? 1 : 0),
4389 removeFromWorkList(Ptr.getNode());
4390 DAG.DeleteNode(Ptr.getNode());
4395 /// CombineToPostIndexedLoadStore - Try to combine a load / store with a
4396 /// add / sub of the base pointer node into a post-indexed load / store.
4397 /// The transformation folded the add / subtract into the new indexed
4398 /// load / store effectively and all of its uses are redirected to the
4399 /// new load / store.
4400 bool DAGCombiner::CombineToPostIndexedLoadStore(SDNode *N) {
4401 if (!LegalOperations)
4407 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
4408 if (LD->isIndexed())
4410 VT = LD->getMemoryVT();
4411 if (!TLI.isIndexedLoadLegal(ISD::POST_INC, VT) &&
4412 !TLI.isIndexedLoadLegal(ISD::POST_DEC, VT))
4414 Ptr = LD->getBasePtr();
4415 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
4416 if (ST->isIndexed())
4418 VT = ST->getMemoryVT();
4419 if (!TLI.isIndexedStoreLegal(ISD::POST_INC, VT) &&
4420 !TLI.isIndexedStoreLegal(ISD::POST_DEC, VT))
4422 Ptr = ST->getBasePtr();
4427 if (Ptr.getNode()->hasOneUse())
4430 for (SDNode::use_iterator I = Ptr.getNode()->use_begin(),
4431 E = Ptr.getNode()->use_end(); I != E; ++I) {
4434 (Op->getOpcode() != ISD::ADD && Op->getOpcode() != ISD::SUB))
4439 ISD::MemIndexedMode AM = ISD::UNINDEXED;
4440 if (TLI.getPostIndexedAddressParts(N, Op, BasePtr, Offset, AM, DAG)) {
4442 std::swap(BasePtr, Offset);
4445 // Don't create a indexed load / store with zero offset.
4446 if (isa<ConstantSDNode>(Offset) &&
4447 cast<ConstantSDNode>(Offset)->isNullValue())
4450 // Try turning it into a post-indexed load / store except when
4451 // 1) All uses are load / store ops that use it as base ptr.
4452 // 2) Op must be independent of N, i.e. Op is neither a predecessor
4453 // nor a successor of N. Otherwise, if Op is folded that would
4457 bool TryNext = false;
4458 for (SDNode::use_iterator II = BasePtr.getNode()->use_begin(),
4459 EE = BasePtr.getNode()->use_end(); II != EE; ++II) {
4461 if (Use == Ptr.getNode())
4464 // If all the uses are load / store addresses, then don't do the
4466 if (Use->getOpcode() == ISD::ADD || Use->getOpcode() == ISD::SUB){
4467 bool RealUse = false;
4468 for (SDNode::use_iterator III = Use->use_begin(),
4469 EEE = Use->use_end(); III != EEE; ++III) {
4470 SDNode *UseUse = *III;
4471 if (!((UseUse->getOpcode() == ISD::LOAD &&
4472 cast<LoadSDNode>(UseUse)->getBasePtr().getNode() == Use) ||
4473 (UseUse->getOpcode() == ISD::STORE &&
4474 cast<StoreSDNode>(UseUse)->getBasePtr().getNode() == Use)))
4488 if (!Op->isPredecessorOf(N) && !N->isPredecessorOf(Op)) {
4489 SDValue Result = isLoad
4490 ? DAG.getIndexedLoad(SDValue(N,0), BasePtr, Offset, AM)
4491 : DAG.getIndexedStore(SDValue(N,0), BasePtr, Offset, AM);
4494 DOUT << "\nReplacing.5 "; DEBUG(N->dump(&DAG));
4495 DOUT << "\nWith: "; DEBUG(Result.getNode()->dump(&DAG));
4497 WorkListRemover DeadNodes(*this);
4499 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0),
4501 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2),
4504 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1),
4508 // Finally, since the node is now dead, remove it from the graph.
4511 // Replace the uses of Use with uses of the updated base value.
4512 DAG.ReplaceAllUsesOfValueWith(SDValue(Op, 0),
4513 Result.getValue(isLoad ? 1 : 0),
4515 removeFromWorkList(Op);
4524 /// InferAlignment - If we can infer some alignment information from this
4525 /// pointer, return it.
4526 static unsigned InferAlignment(SDValue Ptr, SelectionDAG &DAG) {
4527 // If this is a direct reference to a stack slot, use information about the
4528 // stack slot's alignment.
4529 int FrameIdx = 1 << 31;
4530 int64_t FrameOffset = 0;
4531 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Ptr)) {
4532 FrameIdx = FI->getIndex();
4533 } else if (Ptr.getOpcode() == ISD::ADD &&
4534 isa<ConstantSDNode>(Ptr.getOperand(1)) &&
4535 isa<FrameIndexSDNode>(Ptr.getOperand(0))) {
4536 FrameIdx = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
4537 FrameOffset = Ptr.getConstantOperandVal(1);
4540 if (FrameIdx != (1 << 31)) {
4541 // FIXME: Handle FI+CST.
4542 const MachineFrameInfo &MFI = *DAG.getMachineFunction().getFrameInfo();
4543 if (MFI.isFixedObjectIndex(FrameIdx)) {
4544 int64_t ObjectOffset = MFI.getObjectOffset(FrameIdx) + FrameOffset;
4546 // The alignment of the frame index can be determined from its offset from
4547 // the incoming frame position. If the frame object is at offset 32 and
4548 // the stack is guaranteed to be 16-byte aligned, then we know that the
4549 // object is 16-byte aligned.
4550 unsigned StackAlign = DAG.getTarget().getFrameInfo()->getStackAlignment();
4551 unsigned Align = MinAlign(ObjectOffset, StackAlign);
4553 // Finally, the frame object itself may have a known alignment. Factor
4554 // the alignment + offset into a new alignment. For example, if we know
4555 // the FI is 8 byte aligned, but the pointer is 4 off, we really have a
4556 // 4-byte alignment of the resultant pointer. Likewise align 4 + 4-byte
4557 // offset = 4-byte alignment, align 4 + 1-byte offset = align 1, etc.
4558 unsigned FIInfoAlign = MinAlign(MFI.getObjectAlignment(FrameIdx),
4560 return std::max(Align, FIInfoAlign);
4567 SDValue DAGCombiner::visitLOAD(SDNode *N) {
4568 LoadSDNode *LD = cast<LoadSDNode>(N);
4569 SDValue Chain = LD->getChain();
4570 SDValue Ptr = LD->getBasePtr();
4572 // Try to infer better alignment information than the load already has.
4573 if (!Fast && LD->isUnindexed()) {
4574 if (unsigned Align = InferAlignment(Ptr, DAG)) {
4575 if (Align > LD->getAlignment())
4576 return DAG.getExtLoad(LD->getExtensionType(), LD->getValueType(0),
4577 Chain, Ptr, LD->getSrcValue(),
4578 LD->getSrcValueOffset(), LD->getMemoryVT(),
4579 LD->isVolatile(), Align);
4584 // If load is not volatile and there are no uses of the loaded value (and
4585 // the updated indexed value in case of indexed loads), change uses of the
4586 // chain value into uses of the chain input (i.e. delete the dead load).
4587 if (!LD->isVolatile()) {
4588 if (N->getValueType(1) == MVT::Other) {
4590 if (N->hasNUsesOfValue(0, 0)) {
4591 // It's not safe to use the two value CombineTo variant here. e.g.
4592 // v1, chain2 = load chain1, loc
4593 // v2, chain3 = load chain2, loc
4595 // Now we replace use of chain2 with chain1. This makes the second load
4596 // isomorphic to the one we are deleting, and thus makes this load live.
4597 DOUT << "\nReplacing.6 "; DEBUG(N->dump(&DAG));
4598 DOUT << "\nWith chain: "; DEBUG(Chain.getNode()->dump(&DAG));
4600 WorkListRemover DeadNodes(*this);
4601 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain, &DeadNodes);
4602 if (N->use_empty()) {
4603 removeFromWorkList(N);
4606 return SDValue(N, 0); // Return N so it doesn't get rechecked!
4610 assert(N->getValueType(2) == MVT::Other && "Malformed indexed loads?");
4611 if (N->hasNUsesOfValue(0, 0) && N->hasNUsesOfValue(0, 1)) {
4612 SDValue Undef = DAG.getNode(ISD::UNDEF, N->getValueType(0));
4613 DOUT << "\nReplacing.6 "; DEBUG(N->dump(&DAG));
4614 DOUT << "\nWith: "; DEBUG(Undef.getNode()->dump(&DAG));
4615 DOUT << " and 2 other values\n";
4616 WorkListRemover DeadNodes(*this);
4617 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Undef, &DeadNodes);
4618 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1),
4619 DAG.getNode(ISD::UNDEF, N->getValueType(1)),
4621 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 2), Chain, &DeadNodes);
4622 removeFromWorkList(N);
4624 return SDValue(N, 0); // Return N so it doesn't get rechecked!
4629 // If this load is directly stored, replace the load value with the stored
4631 // TODO: Handle store large -> read small portion.
4632 // TODO: Handle TRUNCSTORE/LOADEXT
4633 if (LD->getExtensionType() == ISD::NON_EXTLOAD &&
4634 !LD->isVolatile()) {
4635 if (ISD::isNON_TRUNCStore(Chain.getNode())) {
4636 StoreSDNode *PrevST = cast<StoreSDNode>(Chain);
4637 if (PrevST->getBasePtr() == Ptr &&
4638 PrevST->getValue().getValueType() == N->getValueType(0))
4639 return CombineTo(N, Chain.getOperand(1), Chain);
4644 // Walk up chain skipping non-aliasing memory nodes.
4645 SDValue BetterChain = FindBetterChain(N, Chain);
4647 // If there is a better chain.
4648 if (Chain != BetterChain) {
4651 // Replace the chain to void dependency.
4652 if (LD->getExtensionType() == ISD::NON_EXTLOAD) {
4653 ReplLoad = DAG.getLoad(N->getValueType(0), BetterChain, Ptr,
4654 LD->getSrcValue(), LD->getSrcValueOffset(),
4655 LD->isVolatile(), LD->getAlignment());
4657 ReplLoad = DAG.getExtLoad(LD->getExtensionType(),
4658 LD->getValueType(0),
4659 BetterChain, Ptr, LD->getSrcValue(),
4660 LD->getSrcValueOffset(),
4663 LD->getAlignment());
4666 // Create token factor to keep old chain connected.
4667 SDValue Token = DAG.getNode(ISD::TokenFactor, MVT::Other,
4668 Chain, ReplLoad.getValue(1));
4670 // Replace uses with load result and token factor. Don't add users
4672 return CombineTo(N, ReplLoad.getValue(0), Token, false);
4676 // Try transforming N to an indexed load.
4677 if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
4678 return SDValue(N, 0);
4684 SDValue DAGCombiner::visitSTORE(SDNode *N) {
4685 StoreSDNode *ST = cast<StoreSDNode>(N);
4686 SDValue Chain = ST->getChain();
4687 SDValue Value = ST->getValue();
4688 SDValue Ptr = ST->getBasePtr();
4690 // Try to infer better alignment information than the store already has.
4691 if (!Fast && ST->isUnindexed()) {
4692 if (unsigned Align = InferAlignment(Ptr, DAG)) {
4693 if (Align > ST->getAlignment())
4694 return DAG.getTruncStore(Chain, Value, Ptr, ST->getSrcValue(),
4695 ST->getSrcValueOffset(), ST->getMemoryVT(),
4696 ST->isVolatile(), Align);
4700 // If this is a store of a bit convert, store the input value if the
4701 // resultant store does not need a higher alignment than the original.
4702 if (Value.getOpcode() == ISD::BIT_CONVERT && !ST->isTruncatingStore() &&
4703 ST->isUnindexed()) {
4704 unsigned Align = ST->getAlignment();
4705 MVT SVT = Value.getOperand(0).getValueType();
4706 unsigned OrigAlign = TLI.getTargetData()->
4707 getABITypeAlignment(SVT.getTypeForMVT());
4708 if (Align <= OrigAlign &&
4709 ((!LegalOperations && !ST->isVolatile()) ||
4710 TLI.isOperationLegal(ISD::STORE, SVT)))
4711 return DAG.getStore(Chain, Value.getOperand(0), Ptr, ST->getSrcValue(),
4712 ST->getSrcValueOffset(), ST->isVolatile(), OrigAlign);
4715 // Turn 'store float 1.0, Ptr' -> 'store int 0x12345678, Ptr'
4716 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Value)) {
4717 // NOTE: If the original store is volatile, this transform must not increase
4718 // the number of stores. For example, on x86-32 an f64 can be stored in one
4719 // processor operation but an i64 (which is not legal) requires two. So the
4720 // transform should not be done in this case.
4721 if (Value.getOpcode() != ISD::TargetConstantFP) {
4723 switch (CFP->getValueType(0).getSimpleVT()) {
4724 default: assert(0 && "Unknown FP type");
4725 case MVT::f80: // We don't do this for these yet.
4730 if (((TLI.isTypeLegal(MVT::i32) || !LegalTypes) && !LegalOperations &&
4731 !ST->isVolatile()) || TLI.isOperationLegal(ISD::STORE, MVT::i32)) {
4732 Tmp = DAG.getConstant((uint32_t)CFP->getValueAPF().
4733 bitcastToAPInt().getZExtValue(), MVT::i32);
4734 return DAG.getStore(Chain, Tmp, Ptr, ST->getSrcValue(),
4735 ST->getSrcValueOffset(), ST->isVolatile(),
4736 ST->getAlignment());
4740 if (((TLI.isTypeLegal(MVT::i64) || !LegalTypes) && !LegalOperations &&
4741 !ST->isVolatile()) || TLI.isOperationLegal(ISD::STORE, MVT::i64)) {
4742 Tmp = DAG.getConstant(CFP->getValueAPF().bitcastToAPInt().
4743 getZExtValue(), MVT::i64);
4744 return DAG.getStore(Chain, Tmp, Ptr, ST->getSrcValue(),
4745 ST->getSrcValueOffset(), ST->isVolatile(),
4746 ST->getAlignment());
4747 } else if (!ST->isVolatile() &&
4748 TLI.isOperationLegal(ISD::STORE, MVT::i32)) {
4749 // Many FP stores are not made apparent until after legalize, e.g. for
4750 // argument passing. Since this is so common, custom legalize the
4751 // 64-bit integer store into two 32-bit stores.
4752 uint64_t Val = CFP->getValueAPF().bitcastToAPInt().getZExtValue();
4753 SDValue Lo = DAG.getConstant(Val & 0xFFFFFFFF, MVT::i32);
4754 SDValue Hi = DAG.getConstant(Val >> 32, MVT::i32);
4755 if (TLI.isBigEndian()) std::swap(Lo, Hi);
4757 int SVOffset = ST->getSrcValueOffset();
4758 unsigned Alignment = ST->getAlignment();
4759 bool isVolatile = ST->isVolatile();
4761 SDValue St0 = DAG.getStore(Chain, Lo, Ptr, ST->getSrcValue(),
4762 ST->getSrcValueOffset(),
4763 isVolatile, ST->getAlignment());
4764 Ptr = DAG.getNode(ISD::ADD, Ptr.getValueType(), Ptr,
4765 DAG.getConstant(4, Ptr.getValueType()));
4767 Alignment = MinAlign(Alignment, 4U);
4768 SDValue St1 = DAG.getStore(Chain, Hi, Ptr, ST->getSrcValue(),
4769 SVOffset, isVolatile, Alignment);
4770 return DAG.getNode(ISD::TokenFactor, MVT::Other, St0, St1);
4778 // Walk up chain skipping non-aliasing memory nodes.
4779 SDValue BetterChain = FindBetterChain(N, Chain);
4781 // If there is a better chain.
4782 if (Chain != BetterChain) {
4783 // Replace the chain to avoid dependency.
4785 if (ST->isTruncatingStore()) {
4786 ReplStore = DAG.getTruncStore(BetterChain, Value, Ptr,
4787 ST->getSrcValue(),ST->getSrcValueOffset(),
4789 ST->isVolatile(), ST->getAlignment());
4791 ReplStore = DAG.getStore(BetterChain, Value, Ptr,
4792 ST->getSrcValue(), ST->getSrcValueOffset(),
4793 ST->isVolatile(), ST->getAlignment());
4796 // Create token to keep both nodes around.
4798 DAG.getNode(ISD::TokenFactor, MVT::Other, Chain, ReplStore);
4800 // Don't add users to work list.
4801 return CombineTo(N, Token, false);
4805 // Try transforming N to an indexed store.
4806 if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
4807 return SDValue(N, 0);
4809 // FIXME: is there such a thing as a truncating indexed store?
4810 if (ST->isTruncatingStore() && ST->isUnindexed() &&
4811 Value.getValueType().isInteger()) {
4812 // See if we can simplify the input to this truncstore with knowledge that
4813 // only the low bits are being used. For example:
4814 // "truncstore (or (shl x, 8), y), i8" -> "truncstore y, i8"
4816 GetDemandedBits(Value,
4817 APInt::getLowBitsSet(Value.getValueSizeInBits(),
4818 ST->getMemoryVT().getSizeInBits()));
4819 AddToWorkList(Value.getNode());
4820 if (Shorter.getNode())
4821 return DAG.getTruncStore(Chain, Shorter, Ptr, ST->getSrcValue(),
4822 ST->getSrcValueOffset(), ST->getMemoryVT(),
4823 ST->isVolatile(), ST->getAlignment());
4825 // Otherwise, see if we can simplify the operation with
4826 // SimplifyDemandedBits, which only works if the value has a single use.
4827 if (SimplifyDemandedBits(Value,
4828 APInt::getLowBitsSet(
4829 Value.getValueSizeInBits(),
4830 ST->getMemoryVT().getSizeInBits())))
4831 return SDValue(N, 0);
4834 // If this is a load followed by a store to the same location, then the store
4836 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Value)) {
4837 if (Ld->getBasePtr() == Ptr && ST->getMemoryVT() == Ld->getMemoryVT() &&
4838 ST->isUnindexed() && !ST->isVolatile() &&
4839 // There can't be any side effects between the load and store, such as
4841 Chain.reachesChainWithoutSideEffects(SDValue(Ld, 1))) {
4842 // The store is dead, remove it.
4847 // If this is an FP_ROUND or TRUNC followed by a store, fold this into a
4848 // truncating store. We can do this even if this is already a truncstore.
4849 if ((Value.getOpcode() == ISD::FP_ROUND || Value.getOpcode() == ISD::TRUNCATE)
4850 && Value.getNode()->hasOneUse() && ST->isUnindexed() &&
4851 TLI.isTruncStoreLegal(Value.getOperand(0).getValueType(),
4852 ST->getMemoryVT())) {
4853 return DAG.getTruncStore(Chain, Value.getOperand(0), Ptr, ST->getSrcValue(),
4854 ST->getSrcValueOffset(), ST->getMemoryVT(),
4855 ST->isVolatile(), ST->getAlignment());
4861 SDValue DAGCombiner::visitINSERT_VECTOR_ELT(SDNode *N) {
4862 SDValue InVec = N->getOperand(0);
4863 SDValue InVal = N->getOperand(1);
4864 SDValue EltNo = N->getOperand(2);
4866 // If the invec is a BUILD_VECTOR and if EltNo is a constant, build a new
4867 // vector with the inserted element.
4868 if (InVec.getOpcode() == ISD::BUILD_VECTOR && isa<ConstantSDNode>(EltNo)) {
4869 unsigned Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
4870 SmallVector<SDValue, 8> Ops(InVec.getNode()->op_begin(),
4871 InVec.getNode()->op_end());
4872 if (Elt < Ops.size())
4874 return DAG.getNode(ISD::BUILD_VECTOR, InVec.getValueType(),
4875 &Ops[0], Ops.size());
4881 SDValue DAGCombiner::visitEXTRACT_VECTOR_ELT(SDNode *N) {
4882 // (vextract (scalar_to_vector val, 0) -> val
4883 SDValue InVec = N->getOperand(0);
4885 if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR)
4886 return InVec.getOperand(0);
4888 // Perform only after legalization to ensure build_vector / vector_shuffle
4889 // optimizations have already been done.
4890 if (!LegalOperations) return SDValue();
4892 // (vextract (v4f32 load $addr), c) -> (f32 load $addr+c*size)
4893 // (vextract (v4f32 s2v (f32 load $addr)), c) -> (f32 load $addr+c*size)
4894 // (vextract (v4f32 shuffle (load $addr), <1,u,u,u>), 0) -> (f32 load $addr)
4895 SDValue EltNo = N->getOperand(1);
4897 if (isa<ConstantSDNode>(EltNo)) {
4898 unsigned Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
4899 bool NewLoad = false;
4900 bool BCNumEltsChanged = false;
4901 MVT VT = InVec.getValueType();
4902 MVT EVT = VT.getVectorElementType();
4904 if (InVec.getOpcode() == ISD::BIT_CONVERT) {
4905 MVT BCVT = InVec.getOperand(0).getValueType();
4906 if (!BCVT.isVector() || EVT.bitsGT(BCVT.getVectorElementType()))
4908 if (VT.getVectorNumElements() != BCVT.getVectorNumElements())
4909 BCNumEltsChanged = true;
4910 InVec = InVec.getOperand(0);
4911 EVT = BCVT.getVectorElementType();
4915 LoadSDNode *LN0 = NULL;
4916 if (ISD::isNormalLoad(InVec.getNode()))
4917 LN0 = cast<LoadSDNode>(InVec);
4918 else if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR &&
4919 InVec.getOperand(0).getValueType() == EVT &&
4920 ISD::isNormalLoad(InVec.getOperand(0).getNode())) {
4921 LN0 = cast<LoadSDNode>(InVec.getOperand(0));
4922 } else if (InVec.getOpcode() == ISD::VECTOR_SHUFFLE) {
4923 // (vextract (vector_shuffle (load $addr), v2, <1, u, u, u>), 1)
4925 // (load $addr+1*size)
4927 // If the bit convert changed the number of elements, it is unsafe
4928 // to examine the mask.
4929 if (BCNumEltsChanged)
4931 unsigned Idx = cast<ConstantSDNode>(InVec.getOperand(2).
4932 getOperand(Elt))->getZExtValue();
4933 unsigned NumElems = InVec.getOperand(2).getNumOperands();
4934 InVec = (Idx < NumElems) ? InVec.getOperand(0) : InVec.getOperand(1);
4935 if (InVec.getOpcode() == ISD::BIT_CONVERT)
4936 InVec = InVec.getOperand(0);
4937 if (ISD::isNormalLoad(InVec.getNode())) {
4938 LN0 = cast<LoadSDNode>(InVec);
4939 Elt = (Idx < NumElems) ? Idx : Idx - NumElems;
4942 if (!LN0 || !LN0->hasOneUse() || LN0->isVolatile())
4945 unsigned Align = LN0->getAlignment();
4947 // Check the resultant load doesn't need a higher alignment than the
4949 unsigned NewAlign = TLI.getTargetData()->
4950 getABITypeAlignment(LVT.getTypeForMVT());
4951 if (NewAlign > Align || !TLI.isOperationLegal(ISD::LOAD, LVT))
4956 SDValue NewPtr = LN0->getBasePtr();
4958 unsigned PtrOff = LVT.getSizeInBits() * Elt / 8;
4959 MVT PtrType = NewPtr.getValueType();
4960 if (TLI.isBigEndian())
4961 PtrOff = VT.getSizeInBits() / 8 - PtrOff;
4962 NewPtr = DAG.getNode(ISD::ADD, PtrType, NewPtr,
4963 DAG.getConstant(PtrOff, PtrType));
4965 return DAG.getLoad(LVT, LN0->getChain(), NewPtr,
4966 LN0->getSrcValue(), LN0->getSrcValueOffset(),
4967 LN0->isVolatile(), Align);
4973 SDValue DAGCombiner::visitBUILD_VECTOR(SDNode *N) {
4974 unsigned NumInScalars = N->getNumOperands();
4975 MVT VT = N->getValueType(0);
4976 unsigned NumElts = VT.getVectorNumElements();
4977 MVT EltType = VT.getVectorElementType();
4979 // Check to see if this is a BUILD_VECTOR of a bunch of EXTRACT_VECTOR_ELT
4980 // operations. If so, and if the EXTRACT_VECTOR_ELT vector inputs come from
4981 // at most two distinct vectors, turn this into a shuffle node.
4982 SDValue VecIn1, VecIn2;
4983 for (unsigned i = 0; i != NumInScalars; ++i) {
4984 // Ignore undef inputs.
4985 if (N->getOperand(i).getOpcode() == ISD::UNDEF) continue;
4987 // If this input is something other than a EXTRACT_VECTOR_ELT with a
4988 // constant index, bail out.
4989 if (N->getOperand(i).getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
4990 !isa<ConstantSDNode>(N->getOperand(i).getOperand(1))) {
4991 VecIn1 = VecIn2 = SDValue(0, 0);
4995 // If the input vector type disagrees with the result of the build_vector,
4996 // we can't make a shuffle.
4997 SDValue ExtractedFromVec = N->getOperand(i).getOperand(0);
4998 if (ExtractedFromVec.getValueType() != VT) {
4999 VecIn1 = VecIn2 = SDValue(0, 0);
5003 // Otherwise, remember this. We allow up to two distinct input vectors.
5004 if (ExtractedFromVec == VecIn1 || ExtractedFromVec == VecIn2)
5007 if (VecIn1.getNode() == 0) {
5008 VecIn1 = ExtractedFromVec;
5009 } else if (VecIn2.getNode() == 0) {
5010 VecIn2 = ExtractedFromVec;
5013 VecIn1 = VecIn2 = SDValue(0, 0);
5018 // If everything is good, we can make a shuffle operation.
5019 if (VecIn1.getNode()) {
5020 SmallVector<SDValue, 8> BuildVecIndices;
5021 for (unsigned i = 0; i != NumInScalars; ++i) {
5022 if (N->getOperand(i).getOpcode() == ISD::UNDEF) {
5023 BuildVecIndices.push_back(DAG.getNode(ISD::UNDEF, TLI.getPointerTy()));
5027 SDValue Extract = N->getOperand(i);
5029 // If extracting from the first vector, just use the index directly.
5030 if (Extract.getOperand(0) == VecIn1) {
5031 BuildVecIndices.push_back(Extract.getOperand(1));
5035 // Otherwise, use InIdx + VecSize
5037 cast<ConstantSDNode>(Extract.getOperand(1))->getZExtValue();
5038 BuildVecIndices.push_back(DAG.getIntPtrConstant(Idx+NumInScalars));
5041 // Add count and size info.
5042 MVT BuildVecVT = MVT::getVectorVT(TLI.getPointerTy(), NumElts);
5043 if (!TLI.isTypeLegal(BuildVecVT) && LegalTypes)
5046 // Return the new VECTOR_SHUFFLE node.
5049 if (VecIn2.getNode()) {
5052 // Use an undef build_vector as input for the second operand.
5053 std::vector<SDValue> UnOps(NumInScalars,
5054 DAG.getNode(ISD::UNDEF,
5056 Ops[1] = DAG.getNode(ISD::BUILD_VECTOR, VT,
5057 &UnOps[0], UnOps.size());
5058 AddToWorkList(Ops[1].getNode());
5060 Ops[2] = DAG.getNode(ISD::BUILD_VECTOR, BuildVecVT,
5061 &BuildVecIndices[0], BuildVecIndices.size());
5062 return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, Ops, 3);
5068 SDValue DAGCombiner::visitCONCAT_VECTORS(SDNode *N) {
5069 // TODO: Check to see if this is a CONCAT_VECTORS of a bunch of
5070 // EXTRACT_SUBVECTOR operations. If so, and if the EXTRACT_SUBVECTOR vector
5071 // inputs come from at most two distinct vectors, turn this into a shuffle
5074 // If we only have one input vector, we don't need to do any concatenation.
5075 if (N->getNumOperands() == 1) {
5076 return N->getOperand(0);
5082 SDValue DAGCombiner::visitVECTOR_SHUFFLE(SDNode *N) {
5083 SDValue ShufMask = N->getOperand(2);
5084 unsigned NumElts = ShufMask.getNumOperands();
5086 SDValue N0 = N->getOperand(0);
5087 SDValue N1 = N->getOperand(1);
5089 assert(N0.getValueType().getVectorNumElements() == NumElts &&
5090 "Vector shuffle must be normalized in DAG");
5092 // If the shuffle mask is an identity operation on the LHS, return the LHS.
5093 bool isIdentity = true;
5094 for (unsigned i = 0; i != NumElts; ++i) {
5095 if (ShufMask.getOperand(i).getOpcode() != ISD::UNDEF &&
5096 cast<ConstantSDNode>(ShufMask.getOperand(i))->getZExtValue() != i) {
5101 if (isIdentity) return N->getOperand(0);
5103 // If the shuffle mask is an identity operation on the RHS, return the RHS.
5105 for (unsigned i = 0; i != NumElts; ++i) {
5106 if (ShufMask.getOperand(i).getOpcode() != ISD::UNDEF &&
5107 cast<ConstantSDNode>(ShufMask.getOperand(i))->getZExtValue() !=
5113 if (isIdentity) return N->getOperand(1);
5115 // Check if the shuffle is a unary shuffle, i.e. one of the vectors is not
5117 bool isUnary = true;
5118 bool isSplat = true;
5120 unsigned BaseIdx = 0;
5121 for (unsigned i = 0; i != NumElts; ++i)
5122 if (ShufMask.getOperand(i).getOpcode() != ISD::UNDEF) {
5123 unsigned Idx=cast<ConstantSDNode>(ShufMask.getOperand(i))->getZExtValue();
5124 int V = (Idx < NumElts) ? 0 : 1;
5138 // Normalize unary shuffle so the RHS is undef.
5139 if (isUnary && VecNum == 1)
5142 // If it is a splat, check if the argument vector is a build_vector with
5143 // all scalar elements the same.
5145 SDNode *V = N0.getNode();
5147 // If this is a bit convert that changes the element type of the vector but
5148 // not the number of vector elements, look through it. Be careful not to
5149 // look though conversions that change things like v4f32 to v2f64.
5150 if (V->getOpcode() == ISD::BIT_CONVERT) {
5151 SDValue ConvInput = V->getOperand(0);
5152 if (ConvInput.getValueType().isVector() &&
5153 ConvInput.getValueType().getVectorNumElements() == NumElts)
5154 V = ConvInput.getNode();
5157 if (V->getOpcode() == ISD::BUILD_VECTOR) {
5158 unsigned NumElems = V->getNumOperands();
5159 if (NumElems > BaseIdx) {
5161 bool AllSame = true;
5162 for (unsigned i = 0; i != NumElems; ++i) {
5163 if (V->getOperand(i).getOpcode() != ISD::UNDEF) {
5164 Base = V->getOperand(i);
5168 // Splat of <u, u, u, u>, return <u, u, u, u>
5169 if (!Base.getNode())
5171 for (unsigned i = 0; i != NumElems; ++i) {
5172 if (V->getOperand(i) != Base) {
5177 // Splat of <x, x, x, x>, return <x, x, x, x>
5184 // If it is a unary or the LHS and the RHS are the same node, turn the RHS
5186 if (isUnary || N0 == N1) {
5187 // Check the SHUFFLE mask, mapping any inputs from the 2nd operand into the
5189 SmallVector<SDValue, 8> MappedOps;
5190 for (unsigned i = 0; i != NumElts; ++i) {
5191 if (ShufMask.getOperand(i).getOpcode() == ISD::UNDEF ||
5192 cast<ConstantSDNode>(ShufMask.getOperand(i))->getZExtValue() <
5194 MappedOps.push_back(ShufMask.getOperand(i));
5197 cast<ConstantSDNode>(ShufMask.getOperand(i))->getZExtValue() -
5199 MappedOps.push_back(DAG.getConstant(NewIdx,
5200 ShufMask.getOperand(i).getValueType()));
5203 ShufMask = DAG.getNode(ISD::BUILD_VECTOR, ShufMask.getValueType(),
5204 &MappedOps[0], MappedOps.size());
5205 AddToWorkList(ShufMask.getNode());
5206 return DAG.getNode(ISD::VECTOR_SHUFFLE, N->getValueType(0),
5208 DAG.getNode(ISD::UNDEF, N->getValueType(0)),
5215 /// XformToShuffleWithZero - Returns a vector_shuffle if it able to transform
5216 /// an AND to a vector_shuffle with the destination vector and a zero vector.
5217 /// e.g. AND V, <0xffffffff, 0, 0xffffffff, 0>. ==>
5218 /// vector_shuffle V, Zero, <0, 4, 2, 4>
5219 SDValue DAGCombiner::XformToShuffleWithZero(SDNode *N) {
5220 SDValue LHS = N->getOperand(0);
5221 SDValue RHS = N->getOperand(1);
5222 if (N->getOpcode() == ISD::AND) {
5223 if (RHS.getOpcode() == ISD::BIT_CONVERT)
5224 RHS = RHS.getOperand(0);
5225 if (RHS.getOpcode() == ISD::BUILD_VECTOR) {
5226 std::vector<SDValue> IdxOps;
5227 unsigned NumOps = RHS.getNumOperands();
5228 unsigned NumElts = NumOps;
5229 for (unsigned i = 0; i != NumElts; ++i) {
5230 SDValue Elt = RHS.getOperand(i);
5231 if (!isa<ConstantSDNode>(Elt))
5233 else if (cast<ConstantSDNode>(Elt)->isAllOnesValue())
5234 IdxOps.push_back(DAG.getIntPtrConstant(i));
5235 else if (cast<ConstantSDNode>(Elt)->isNullValue())
5236 IdxOps.push_back(DAG.getIntPtrConstant(NumElts));
5241 // Let's see if the target supports this vector_shuffle.
5242 if (!TLI.isVectorClearMaskLegal(IdxOps, TLI.getPointerTy(), DAG))
5245 // Return the new VECTOR_SHUFFLE node.
5246 MVT EVT = RHS.getValueType().getVectorElementType();
5247 MVT VT = MVT::getVectorVT(EVT, NumElts);
5248 MVT MaskVT = MVT::getVectorVT(TLI.getPointerTy(), NumElts);
5249 std::vector<SDValue> Ops;
5250 LHS = DAG.getNode(ISD::BIT_CONVERT, VT, LHS);
5252 AddToWorkList(LHS.getNode());
5253 std::vector<SDValue> ZeroOps(NumElts, DAG.getConstant(0, EVT));
5254 Ops.push_back(DAG.getNode(ISD::BUILD_VECTOR, VT,
5255 &ZeroOps[0], ZeroOps.size()));
5256 Ops.push_back(DAG.getNode(ISD::BUILD_VECTOR, MaskVT,
5257 &IdxOps[0], IdxOps.size()));
5258 SDValue Result = DAG.getNode(ISD::VECTOR_SHUFFLE, VT,
5259 &Ops[0], Ops.size());
5260 if (VT != N->getValueType(0))
5261 Result = DAG.getNode(ISD::BIT_CONVERT, N->getValueType(0), Result);
5268 /// SimplifyVBinOp - Visit a binary vector operation, like ADD.
5269 SDValue DAGCombiner::SimplifyVBinOp(SDNode *N) {
5270 // After legalize, the target may be depending on adds and other
5271 // binary ops to provide legal ways to construct constants or other
5272 // things. Simplifying them may result in a loss of legality.
5273 if (LegalOperations) return SDValue();
5275 MVT VT = N->getValueType(0);
5276 assert(VT.isVector() && "SimplifyVBinOp only works on vectors!");
5278 MVT EltType = VT.getVectorElementType();
5279 SDValue LHS = N->getOperand(0);
5280 SDValue RHS = N->getOperand(1);
5281 SDValue Shuffle = XformToShuffleWithZero(N);
5282 if (Shuffle.getNode()) return Shuffle;
5284 // If the LHS and RHS are BUILD_VECTOR nodes, see if we can constant fold
5286 if (LHS.getOpcode() == ISD::BUILD_VECTOR &&
5287 RHS.getOpcode() == ISD::BUILD_VECTOR) {
5288 SmallVector<SDValue, 8> Ops;
5289 for (unsigned i = 0, e = LHS.getNumOperands(); i != e; ++i) {
5290 SDValue LHSOp = LHS.getOperand(i);
5291 SDValue RHSOp = RHS.getOperand(i);
5292 // If these two elements can't be folded, bail out.
5293 if ((LHSOp.getOpcode() != ISD::UNDEF &&
5294 LHSOp.getOpcode() != ISD::Constant &&
5295 LHSOp.getOpcode() != ISD::ConstantFP) ||
5296 (RHSOp.getOpcode() != ISD::UNDEF &&
5297 RHSOp.getOpcode() != ISD::Constant &&
5298 RHSOp.getOpcode() != ISD::ConstantFP))
5300 // Can't fold divide by zero.
5301 if (N->getOpcode() == ISD::SDIV || N->getOpcode() == ISD::UDIV ||
5302 N->getOpcode() == ISD::FDIV) {
5303 if ((RHSOp.getOpcode() == ISD::Constant &&
5304 cast<ConstantSDNode>(RHSOp.getNode())->isNullValue()) ||
5305 (RHSOp.getOpcode() == ISD::ConstantFP &&
5306 cast<ConstantFPSDNode>(RHSOp.getNode())->getValueAPF().isZero()))
5309 Ops.push_back(DAG.getNode(N->getOpcode(), EltType, LHSOp, RHSOp));
5310 AddToWorkList(Ops.back().getNode());
5311 assert((Ops.back().getOpcode() == ISD::UNDEF ||
5312 Ops.back().getOpcode() == ISD::Constant ||
5313 Ops.back().getOpcode() == ISD::ConstantFP) &&
5314 "Scalar binop didn't fold!");
5317 if (Ops.size() == LHS.getNumOperands()) {
5318 MVT VT = LHS.getValueType();
5319 return DAG.getNode(ISD::BUILD_VECTOR, VT, &Ops[0], Ops.size());
5326 SDValue DAGCombiner::SimplifySelect(SDValue N0, SDValue N1, SDValue N2){
5327 assert(N0.getOpcode() ==ISD::SETCC && "First argument must be a SetCC node!");
5329 SDValue SCC = SimplifySelectCC(N0.getOperand(0), N0.getOperand(1), N1, N2,
5330 cast<CondCodeSDNode>(N0.getOperand(2))->get());
5331 // If we got a simplified select_cc node back from SimplifySelectCC, then
5332 // break it down into a new SETCC node, and a new SELECT node, and then return
5333 // the SELECT node, since we were called with a SELECT node.
5334 if (SCC.getNode()) {
5335 // Check to see if we got a select_cc back (to turn into setcc/select).
5336 // Otherwise, just return whatever node we got back, like fabs.
5337 if (SCC.getOpcode() == ISD::SELECT_CC) {
5338 SDValue SETCC = DAG.getNode(ISD::SETCC, N0.getValueType(),
5339 SCC.getOperand(0), SCC.getOperand(1),
5341 AddToWorkList(SETCC.getNode());
5342 return DAG.getNode(ISD::SELECT, SCC.getValueType(), SCC.getOperand(2),
5343 SCC.getOperand(3), SETCC);
5350 /// SimplifySelectOps - Given a SELECT or a SELECT_CC node, where LHS and RHS
5351 /// are the two values being selected between, see if we can simplify the
5352 /// select. Callers of this should assume that TheSelect is deleted if this
5353 /// returns true. As such, they should return the appropriate thing (e.g. the
5354 /// node) back to the top-level of the DAG combiner loop to avoid it being
5357 bool DAGCombiner::SimplifySelectOps(SDNode *TheSelect, SDValue LHS,
5360 // If this is a select from two identical things, try to pull the operation
5361 // through the select.
5362 if (LHS.getOpcode() == RHS.getOpcode() && LHS.hasOneUse() && RHS.hasOneUse()){
5363 // If this is a load and the token chain is identical, replace the select
5364 // of two loads with a load through a select of the address to load from.
5365 // This triggers in things like "select bool X, 10.0, 123.0" after the FP
5366 // constants have been dropped into the constant pool.
5367 if (LHS.getOpcode() == ISD::LOAD &&
5368 // Do not let this transformation reduce the number of volatile loads.
5369 !cast<LoadSDNode>(LHS)->isVolatile() &&
5370 !cast<LoadSDNode>(RHS)->isVolatile() &&
5371 // Token chains must be identical.
5372 LHS.getOperand(0) == RHS.getOperand(0)) {
5373 LoadSDNode *LLD = cast<LoadSDNode>(LHS);
5374 LoadSDNode *RLD = cast<LoadSDNode>(RHS);
5376 // If this is an EXTLOAD, the VT's must match.
5377 if (LLD->getMemoryVT() == RLD->getMemoryVT()) {
5378 // FIXME: this conflates two src values, discarding one. This is not
5379 // the right thing to do, but nothing uses srcvalues now. When they do,
5380 // turn SrcValue into a list of locations.
5382 if (TheSelect->getOpcode() == ISD::SELECT) {
5383 // Check that the condition doesn't reach either load. If so, folding
5384 // this will induce a cycle into the DAG.
5385 if (!LLD->isPredecessorOf(TheSelect->getOperand(0).getNode()) &&
5386 !RLD->isPredecessorOf(TheSelect->getOperand(0).getNode())) {
5387 Addr = DAG.getNode(ISD::SELECT, LLD->getBasePtr().getValueType(),
5388 TheSelect->getOperand(0), LLD->getBasePtr(),
5392 // Check that the condition doesn't reach either load. If so, folding
5393 // this will induce a cycle into the DAG.
5394 if (!LLD->isPredecessorOf(TheSelect->getOperand(0).getNode()) &&
5395 !RLD->isPredecessorOf(TheSelect->getOperand(0).getNode()) &&
5396 !LLD->isPredecessorOf(TheSelect->getOperand(1).getNode()) &&
5397 !RLD->isPredecessorOf(TheSelect->getOperand(1).getNode())) {
5398 Addr = DAG.getNode(ISD::SELECT_CC, LLD->getBasePtr().getValueType(),
5399 TheSelect->getOperand(0),
5400 TheSelect->getOperand(1),
5401 LLD->getBasePtr(), RLD->getBasePtr(),
5402 TheSelect->getOperand(4));
5406 if (Addr.getNode()) {
5408 if (LLD->getExtensionType() == ISD::NON_EXTLOAD)
5409 Load = DAG.getLoad(TheSelect->getValueType(0), LLD->getChain(),
5410 Addr,LLD->getSrcValue(),
5411 LLD->getSrcValueOffset(),
5413 LLD->getAlignment());
5415 Load = DAG.getExtLoad(LLD->getExtensionType(),
5416 TheSelect->getValueType(0),
5417 LLD->getChain(), Addr, LLD->getSrcValue(),
5418 LLD->getSrcValueOffset(),
5421 LLD->getAlignment());
5423 // Users of the select now use the result of the load.
5424 CombineTo(TheSelect, Load);
5426 // Users of the old loads now use the new load's chain. We know the
5427 // old-load value is dead now.
5428 CombineTo(LHS.getNode(), Load.getValue(0), Load.getValue(1));
5429 CombineTo(RHS.getNode(), Load.getValue(0), Load.getValue(1));
5439 SDValue DAGCombiner::SimplifySelectCC(SDValue N0, SDValue N1,
5440 SDValue N2, SDValue N3,
5441 ISD::CondCode CC, bool NotExtCompare) {
5443 MVT VT = N2.getValueType();
5444 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
5445 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2.getNode());
5446 ConstantSDNode *N3C = dyn_cast<ConstantSDNode>(N3.getNode());
5448 // Determine if the condition we're dealing with is constant
5449 SDValue SCC = SimplifySetCC(TLI.getSetCCResultType(N0.getValueType()),
5451 if (SCC.getNode()) AddToWorkList(SCC.getNode());
5452 ConstantSDNode *SCCC = dyn_cast_or_null<ConstantSDNode>(SCC.getNode());
5454 // fold select_cc true, x, y -> x
5455 if (SCCC && !SCCC->isNullValue())
5457 // fold select_cc false, x, y -> y
5458 if (SCCC && SCCC->isNullValue())
5461 // Check to see if we can simplify the select into an fabs node
5462 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N1)) {
5463 // Allow either -0.0 or 0.0
5464 if (CFP->getValueAPF().isZero()) {
5465 // select (setg[te] X, +/-0.0), X, fneg(X) -> fabs
5466 if ((CC == ISD::SETGE || CC == ISD::SETGT) &&
5467 N0 == N2 && N3.getOpcode() == ISD::FNEG &&
5468 N2 == N3.getOperand(0))
5469 return DAG.getNode(ISD::FABS, VT, N0);
5471 // select (setl[te] X, +/-0.0), fneg(X), X -> fabs
5472 if ((CC == ISD::SETLT || CC == ISD::SETLE) &&
5473 N0 == N3 && N2.getOpcode() == ISD::FNEG &&
5474 N2.getOperand(0) == N3)
5475 return DAG.getNode(ISD::FABS, VT, N3);
5479 // Check to see if we can perform the "gzip trick", transforming
5480 // select_cc setlt X, 0, A, 0 -> and (sra X, size(X)-1), A
5481 if (N1C && N3C && N3C->isNullValue() && CC == ISD::SETLT &&
5482 N0.getValueType().isInteger() &&
5483 N2.getValueType().isInteger() &&
5484 (N1C->isNullValue() || // (a < 0) ? b : 0
5485 (N1C->getAPIntValue() == 1 && N0 == N2))) { // (a < 1) ? a : 0
5486 MVT XType = N0.getValueType();
5487 MVT AType = N2.getValueType();
5488 if (XType.bitsGE(AType)) {
5489 // and (sra X, size(X)-1, A) -> "and (srl X, C2), A" iff A is a
5490 // single-bit constant.
5491 if (N2C && ((N2C->getAPIntValue() & (N2C->getAPIntValue()-1)) == 0)) {
5492 unsigned ShCtV = N2C->getAPIntValue().logBase2();
5493 ShCtV = XType.getSizeInBits()-ShCtV-1;
5494 SDValue ShCt = DAG.getConstant(ShCtV, TLI.getShiftAmountTy());
5495 SDValue Shift = DAG.getNode(ISD::SRL, XType, N0, ShCt);
5496 AddToWorkList(Shift.getNode());
5497 if (XType.bitsGT(AType)) {
5498 Shift = DAG.getNode(ISD::TRUNCATE, AType, Shift);
5499 AddToWorkList(Shift.getNode());
5501 return DAG.getNode(ISD::AND, AType, Shift, N2);
5503 SDValue Shift = DAG.getNode(ISD::SRA, XType, N0,
5504 DAG.getConstant(XType.getSizeInBits()-1,
5505 TLI.getShiftAmountTy()));
5506 AddToWorkList(Shift.getNode());
5507 if (XType.bitsGT(AType)) {
5508 Shift = DAG.getNode(ISD::TRUNCATE, AType, Shift);
5509 AddToWorkList(Shift.getNode());
5511 return DAG.getNode(ISD::AND, AType, Shift, N2);
5515 // fold select C, 16, 0 -> shl C, 4
5516 if (N2C && N3C && N3C->isNullValue() && N2C->getAPIntValue().isPowerOf2() &&
5517 TLI.getBooleanContents() == TargetLowering::ZeroOrOneBooleanContent) {
5519 // If the caller doesn't want us to simplify this into a zext of a compare,
5521 if (NotExtCompare && N2C->getAPIntValue() == 1)
5524 // Get a SetCC of the condition
5525 // FIXME: Should probably make sure that setcc is legal if we ever have a
5526 // target where it isn't.
5528 // cast from setcc result type to select result type
5530 SCC = DAG.getSetCC(TLI.getSetCCResultType(N0.getValueType()),
5532 if (N2.getValueType().bitsLT(SCC.getValueType()))
5533 Temp = DAG.getZeroExtendInReg(SCC, N2.getValueType());
5535 Temp = DAG.getNode(ISD::ZERO_EXTEND, N2.getValueType(), SCC);
5537 SCC = DAG.getSetCC(MVT::i1, N0, N1, CC);
5538 Temp = DAG.getNode(ISD::ZERO_EXTEND, N2.getValueType(), SCC);
5540 AddToWorkList(SCC.getNode());
5541 AddToWorkList(Temp.getNode());
5543 if (N2C->getAPIntValue() == 1)
5545 // shl setcc result by log2 n2c
5546 return DAG.getNode(ISD::SHL, N2.getValueType(), Temp,
5547 DAG.getConstant(N2C->getAPIntValue().logBase2(),
5548 TLI.getShiftAmountTy()));
5551 // Check to see if this is the equivalent of setcc
5552 // FIXME: Turn all of these into setcc if setcc if setcc is legal
5553 // otherwise, go ahead with the folds.
5554 if (0 && N3C && N3C->isNullValue() && N2C && (N2C->getAPIntValue() == 1ULL)) {
5555 MVT XType = N0.getValueType();
5556 if (!LegalOperations ||
5557 TLI.isOperationLegal(ISD::SETCC, TLI.getSetCCResultType(XType))) {
5558 SDValue Res = DAG.getSetCC(TLI.getSetCCResultType(XType), N0, N1, CC);
5559 if (Res.getValueType() != VT)
5560 Res = DAG.getNode(ISD::ZERO_EXTEND, VT, Res);
5564 // seteq X, 0 -> srl (ctlz X, log2(size(X)))
5565 if (N1C && N1C->isNullValue() && CC == ISD::SETEQ &&
5566 (!LegalOperations ||
5567 TLI.isOperationLegal(ISD::CTLZ, XType))) {
5568 SDValue Ctlz = DAG.getNode(ISD::CTLZ, XType, N0);
5569 return DAG.getNode(ISD::SRL, XType, Ctlz,
5570 DAG.getConstant(Log2_32(XType.getSizeInBits()),
5571 TLI.getShiftAmountTy()));
5573 // setgt X, 0 -> srl (and (-X, ~X), size(X)-1)
5574 if (N1C && N1C->isNullValue() && CC == ISD::SETGT) {
5575 SDValue NegN0 = DAG.getNode(ISD::SUB, XType, DAG.getConstant(0, XType),
5577 SDValue NotN0 = DAG.getNode(ISD::XOR, XType, N0,
5578 DAG.getConstant(~0ULL, XType));
5579 return DAG.getNode(ISD::SRL, XType,
5580 DAG.getNode(ISD::AND, XType, NegN0, NotN0),
5581 DAG.getConstant(XType.getSizeInBits()-1,
5582 TLI.getShiftAmountTy()));
5584 // setgt X, -1 -> xor (srl (X, size(X)-1), 1)
5585 if (N1C && N1C->isAllOnesValue() && CC == ISD::SETGT) {
5586 SDValue Sign = DAG.getNode(ISD::SRL, XType, N0,
5587 DAG.getConstant(XType.getSizeInBits()-1,
5588 TLI.getShiftAmountTy()));
5589 return DAG.getNode(ISD::XOR, XType, Sign, DAG.getConstant(1, XType));
5593 // Check to see if this is an integer abs. select_cc setl[te] X, 0, -X, X ->
5594 // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
5595 if (N1C && N1C->isNullValue() && (CC == ISD::SETLT || CC == ISD::SETLE) &&
5596 N0 == N3 && N2.getOpcode() == ISD::SUB && N0 == N2.getOperand(1) &&
5597 N2.getOperand(0) == N1 && N0.getValueType().isInteger()) {
5598 MVT XType = N0.getValueType();
5599 SDValue Shift = DAG.getNode(ISD::SRA, XType, N0,
5600 DAG.getConstant(XType.getSizeInBits()-1,
5601 TLI.getShiftAmountTy()));
5602 SDValue Add = DAG.getNode(ISD::ADD, XType, N0, Shift);
5603 AddToWorkList(Shift.getNode());
5604 AddToWorkList(Add.getNode());
5605 return DAG.getNode(ISD::XOR, XType, Add, Shift);
5607 // Check to see if this is an integer abs. select_cc setgt X, -1, X, -X ->
5608 // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
5609 if (N1C && N1C->isAllOnesValue() && CC == ISD::SETGT &&
5610 N0 == N2 && N3.getOpcode() == ISD::SUB && N0 == N3.getOperand(1)) {
5611 if (ConstantSDNode *SubC = dyn_cast<ConstantSDNode>(N3.getOperand(0))) {
5612 MVT XType = N0.getValueType();
5613 if (SubC->isNullValue() && XType.isInteger()) {
5614 SDValue Shift = DAG.getNode(ISD::SRA, XType, N0,
5615 DAG.getConstant(XType.getSizeInBits()-1,
5616 TLI.getShiftAmountTy()));
5617 SDValue Add = DAG.getNode(ISD::ADD, XType, N0, Shift);
5618 AddToWorkList(Shift.getNode());
5619 AddToWorkList(Add.getNode());
5620 return DAG.getNode(ISD::XOR, XType, Add, Shift);
5628 /// SimplifySetCC - This is a stub for TargetLowering::SimplifySetCC.
5629 SDValue DAGCombiner::SimplifySetCC(MVT VT, SDValue N0,
5630 SDValue N1, ISD::CondCode Cond,
5631 bool foldBooleans) {
5632 TargetLowering::DAGCombinerInfo
5633 DagCombineInfo(DAG, Level == Unrestricted, false, this);
5634 return TLI.SimplifySetCC(VT, N0, N1, Cond, foldBooleans, DagCombineInfo);
5637 /// BuildSDIVSequence - Given an ISD::SDIV node expressing a divide by constant,
5638 /// return a DAG expression to select that will generate the same value by
5639 /// multiplying by a magic number. See:
5640 /// <http://the.wall.riscom.net/books/proc/ppc/cwg/code2.html>
5641 SDValue DAGCombiner::BuildSDIV(SDNode *N) {
5642 std::vector<SDNode*> Built;
5643 SDValue S = TLI.BuildSDIV(N, DAG, &Built);
5645 for (std::vector<SDNode*>::iterator ii = Built.begin(), ee = Built.end();
5651 /// BuildUDIVSequence - Given an ISD::UDIV node expressing a divide by constant,
5652 /// return a DAG expression to select that will generate the same value by
5653 /// multiplying by a magic number. See:
5654 /// <http://the.wall.riscom.net/books/proc/ppc/cwg/code2.html>
5655 SDValue DAGCombiner::BuildUDIV(SDNode *N) {
5656 std::vector<SDNode*> Built;
5657 SDValue S = TLI.BuildUDIV(N, DAG, &Built);
5659 for (std::vector<SDNode*>::iterator ii = Built.begin(), ee = Built.end();
5665 /// FindBaseOffset - Return true if base is known not to alias with anything
5666 /// but itself. Provides base object and offset as results.
5667 static bool FindBaseOffset(SDValue Ptr, SDValue &Base, int64_t &Offset) {
5668 // Assume it is a primitive operation.
5669 Base = Ptr; Offset = 0;
5671 // If it's an adding a simple constant then integrate the offset.
5672 if (Base.getOpcode() == ISD::ADD) {
5673 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Base.getOperand(1))) {
5674 Base = Base.getOperand(0);
5675 Offset += C->getZExtValue();
5679 // If it's any of the following then it can't alias with anything but itself.
5680 return isa<FrameIndexSDNode>(Base) ||
5681 isa<ConstantPoolSDNode>(Base) ||
5682 isa<GlobalAddressSDNode>(Base);
5685 /// isAlias - Return true if there is any possibility that the two addresses
5687 bool DAGCombiner::isAlias(SDValue Ptr1, int64_t Size1,
5688 const Value *SrcValue1, int SrcValueOffset1,
5689 SDValue Ptr2, int64_t Size2,
5690 const Value *SrcValue2, int SrcValueOffset2)
5692 // If they are the same then they must be aliases.
5693 if (Ptr1 == Ptr2) return true;
5695 // Gather base node and offset information.
5696 SDValue Base1, Base2;
5697 int64_t Offset1, Offset2;
5698 bool KnownBase1 = FindBaseOffset(Ptr1, Base1, Offset1);
5699 bool KnownBase2 = FindBaseOffset(Ptr2, Base2, Offset2);
5701 // If they have a same base address then...
5702 if (Base1 == Base2) {
5703 // Check to see if the addresses overlap.
5704 return!((Offset1 + Size1) <= Offset2 || (Offset2 + Size2) <= Offset1);
5707 // If we know both bases then they can't alias.
5708 if (KnownBase1 && KnownBase2) return false;
5710 if (CombinerGlobalAA) {
5711 // Use alias analysis information.
5712 int64_t MinOffset = std::min(SrcValueOffset1, SrcValueOffset2);
5713 int64_t Overlap1 = Size1 + SrcValueOffset1 - MinOffset;
5714 int64_t Overlap2 = Size2 + SrcValueOffset2 - MinOffset;
5715 AliasAnalysis::AliasResult AAResult =
5716 AA.alias(SrcValue1, Overlap1, SrcValue2, Overlap2);
5717 if (AAResult == AliasAnalysis::NoAlias)
5721 // Otherwise we have to assume they alias.
5725 /// FindAliasInfo - Extracts the relevant alias information from the memory
5726 /// node. Returns true if the operand was a load.
5727 bool DAGCombiner::FindAliasInfo(SDNode *N,
5728 SDValue &Ptr, int64_t &Size,
5729 const Value *&SrcValue, int &SrcValueOffset) {
5730 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
5731 Ptr = LD->getBasePtr();
5732 Size = LD->getMemoryVT().getSizeInBits() >> 3;
5733 SrcValue = LD->getSrcValue();
5734 SrcValueOffset = LD->getSrcValueOffset();
5736 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
5737 Ptr = ST->getBasePtr();
5738 Size = ST->getMemoryVT().getSizeInBits() >> 3;
5739 SrcValue = ST->getSrcValue();
5740 SrcValueOffset = ST->getSrcValueOffset();
5742 assert(0 && "FindAliasInfo expected a memory operand");
5748 /// GatherAllAliases - Walk up chain skipping non-aliasing memory nodes,
5749 /// looking for aliasing nodes and adding them to the Aliases vector.
5750 void DAGCombiner::GatherAllAliases(SDNode *N, SDValue OriginalChain,
5751 SmallVector<SDValue, 8> &Aliases) {
5752 SmallVector<SDValue, 8> Chains; // List of chains to visit.
5753 std::set<SDNode *> Visited; // Visited node set.
5755 // Get alias information for node.
5758 const Value *SrcValue;
5760 bool IsLoad = FindAliasInfo(N, Ptr, Size, SrcValue, SrcValueOffset);
5763 Chains.push_back(OriginalChain);
5765 // Look at each chain and determine if it is an alias. If so, add it to the
5766 // aliases list. If not, then continue up the chain looking for the next
5768 while (!Chains.empty()) {
5769 SDValue Chain = Chains.back();
5772 // Don't bother if we've been before.
5773 if (Visited.find(Chain.getNode()) != Visited.end()) continue;
5774 Visited.insert(Chain.getNode());
5776 switch (Chain.getOpcode()) {
5777 case ISD::EntryToken:
5778 // Entry token is ideal chain operand, but handled in FindBetterChain.
5783 // Get alias information for Chain.
5786 const Value *OpSrcValue;
5787 int OpSrcValueOffset;
5788 bool IsOpLoad = FindAliasInfo(Chain.getNode(), OpPtr, OpSize,
5789 OpSrcValue, OpSrcValueOffset);
5791 // If chain is alias then stop here.
5792 if (!(IsLoad && IsOpLoad) &&
5793 isAlias(Ptr, Size, SrcValue, SrcValueOffset,
5794 OpPtr, OpSize, OpSrcValue, OpSrcValueOffset)) {
5795 Aliases.push_back(Chain);
5797 // Look further up the chain.
5798 Chains.push_back(Chain.getOperand(0));
5799 // Clean up old chain.
5800 AddToWorkList(Chain.getNode());
5805 case ISD::TokenFactor:
5806 // We have to check each of the operands of the token factor, so we queue
5807 // then up. Adding the operands to the queue (stack) in reverse order
5808 // maintains the original order and increases the likelihood that getNode
5809 // will find a matching token factor (CSE.)
5810 for (unsigned n = Chain.getNumOperands(); n;)
5811 Chains.push_back(Chain.getOperand(--n));
5812 // Eliminate the token factor if we can.
5813 AddToWorkList(Chain.getNode());
5817 // For all other instructions we will just have to take what we can get.
5818 Aliases.push_back(Chain);
5824 /// FindBetterChain - Walk up chain skipping non-aliasing memory nodes, looking
5825 /// for a better chain (aliasing node.)
5826 SDValue DAGCombiner::FindBetterChain(SDNode *N, SDValue OldChain) {
5827 SmallVector<SDValue, 8> Aliases; // Ops for replacing token factor.
5829 // Accumulate all the aliases to this node.
5830 GatherAllAliases(N, OldChain, Aliases);
5832 if (Aliases.size() == 0) {
5833 // If no operands then chain to entry token.
5834 return DAG.getEntryNode();
5835 } else if (Aliases.size() == 1) {
5836 // If a single operand then chain to it. We don't need to revisit it.
5840 // Construct a custom tailored token factor.
5841 SDValue NewChain = DAG.getNode(ISD::TokenFactor, MVT::Other,
5842 &Aliases[0], Aliases.size());
5844 // Make sure the old chain gets cleaned up.
5845 if (NewChain != OldChain) AddToWorkList(OldChain.getNode());
5850 // SelectionDAG::Combine - This is the entry point for the file.
5852 void SelectionDAG::Combine(CombineLevel Level, AliasAnalysis &AA, bool Fast) {
5853 /// run - This is the main entry point to this class.
5855 DAGCombiner(*this, AA, Fast).Run(Level);