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"
34 STATISTIC(NodesCombined , "Number of dag nodes combined");
35 STATISTIC(PreIndexedNodes , "Number of pre-indexed nodes created");
36 STATISTIC(PostIndexedNodes, "Number of post-indexed nodes created");
41 ViewDAGCombine1("view-dag-combine1-dags", cl::Hidden,
42 cl::desc("Pop up a window to show dags before the first "
45 ViewDAGCombine2("view-dag-combine2-dags", cl::Hidden,
46 cl::desc("Pop up a window to show dags before the second "
49 static const bool ViewDAGCombine1 = false;
50 static const bool ViewDAGCombine2 = false;
54 CombinerAA("combiner-alias-analysis", cl::Hidden,
55 cl::desc("Turn on alias analysis during testing"));
58 CombinerGlobalAA("combiner-global-alias-analysis", cl::Hidden,
59 cl::desc("Include global information in alias analysis"));
61 //------------------------------ DAGCombiner ---------------------------------//
63 class VISIBILITY_HIDDEN DAGCombiner {
68 // Worklist of all of the nodes that need to be simplified.
69 std::vector<SDNode*> WorkList;
71 // AA - Used for DAG load/store alias analysis.
74 /// AddUsersToWorkList - When an instruction is simplified, add all users of
75 /// the instruction to the work lists because they might get more simplified
78 void AddUsersToWorkList(SDNode *N) {
79 for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
84 /// visit - call the node-specific routine that knows how to fold each
85 /// particular type of node.
86 SDOperand visit(SDNode *N);
89 /// AddToWorkList - Add to the work list making sure it's instance is at the
90 /// the back (next to be processed.)
91 void AddToWorkList(SDNode *N) {
92 removeFromWorkList(N);
93 WorkList.push_back(N);
96 /// removeFromWorkList - remove all instances of N from the worklist.
98 void removeFromWorkList(SDNode *N) {
99 WorkList.erase(std::remove(WorkList.begin(), WorkList.end(), N),
103 SDOperand CombineTo(SDNode *N, const SDOperand *To, unsigned NumTo,
106 SDOperand CombineTo(SDNode *N, SDOperand Res, bool AddTo = true) {
107 return CombineTo(N, &Res, 1, AddTo);
110 SDOperand CombineTo(SDNode *N, SDOperand Res0, SDOperand Res1,
112 SDOperand To[] = { Res0, Res1 };
113 return CombineTo(N, To, 2, AddTo);
118 /// SimplifyDemandedBits - Check the specified integer node value to see if
119 /// it can be simplified or if things it uses can be simplified by bit
120 /// propagation. If so, return true.
121 bool SimplifyDemandedBits(SDOperand Op, uint64_t Demanded = ~0ULL);
123 bool CombineToPreIndexedLoadStore(SDNode *N);
124 bool CombineToPostIndexedLoadStore(SDNode *N);
127 /// combine - call the node-specific routine that knows how to fold each
128 /// particular type of node. If that doesn't do anything, try the
129 /// target-specific DAG combines.
130 SDOperand combine(SDNode *N);
132 // Visitation implementation - Implement dag node combining for different
133 // node types. The semantics are as follows:
135 // SDOperand.Val == 0 - No change was made
136 // SDOperand.Val == N - N was replaced, is dead, and is already handled.
137 // otherwise - N should be replaced by the returned Operand.
139 SDOperand visitTokenFactor(SDNode *N);
140 SDOperand visitMERGE_VALUES(SDNode *N);
141 SDOperand visitADD(SDNode *N);
142 SDOperand visitSUB(SDNode *N);
143 SDOperand visitADDC(SDNode *N);
144 SDOperand visitADDE(SDNode *N);
145 SDOperand visitMUL(SDNode *N);
146 SDOperand visitSDIV(SDNode *N);
147 SDOperand visitUDIV(SDNode *N);
148 SDOperand visitSREM(SDNode *N);
149 SDOperand visitUREM(SDNode *N);
150 SDOperand visitMULHU(SDNode *N);
151 SDOperand visitMULHS(SDNode *N);
152 SDOperand visitSMUL_LOHI(SDNode *N);
153 SDOperand visitUMUL_LOHI(SDNode *N);
154 SDOperand visitSDIVREM(SDNode *N);
155 SDOperand visitUDIVREM(SDNode *N);
156 SDOperand visitAND(SDNode *N);
157 SDOperand visitOR(SDNode *N);
158 SDOperand visitXOR(SDNode *N);
159 SDOperand SimplifyVBinOp(SDNode *N);
160 SDOperand visitSHL(SDNode *N);
161 SDOperand visitSRA(SDNode *N);
162 SDOperand visitSRL(SDNode *N);
163 SDOperand visitCTLZ(SDNode *N);
164 SDOperand visitCTTZ(SDNode *N);
165 SDOperand visitCTPOP(SDNode *N);
166 SDOperand visitSELECT(SDNode *N);
167 SDOperand visitSELECT_CC(SDNode *N);
168 SDOperand visitSETCC(SDNode *N);
169 SDOperand visitSIGN_EXTEND(SDNode *N);
170 SDOperand visitZERO_EXTEND(SDNode *N);
171 SDOperand visitANY_EXTEND(SDNode *N);
172 SDOperand visitSIGN_EXTEND_INREG(SDNode *N);
173 SDOperand visitTRUNCATE(SDNode *N);
174 SDOperand visitBIT_CONVERT(SDNode *N);
175 SDOperand visitFADD(SDNode *N);
176 SDOperand visitFSUB(SDNode *N);
177 SDOperand visitFMUL(SDNode *N);
178 SDOperand visitFDIV(SDNode *N);
179 SDOperand visitFREM(SDNode *N);
180 SDOperand visitFCOPYSIGN(SDNode *N);
181 SDOperand visitSINT_TO_FP(SDNode *N);
182 SDOperand visitUINT_TO_FP(SDNode *N);
183 SDOperand visitFP_TO_SINT(SDNode *N);
184 SDOperand visitFP_TO_UINT(SDNode *N);
185 SDOperand visitFP_ROUND(SDNode *N);
186 SDOperand visitFP_ROUND_INREG(SDNode *N);
187 SDOperand visitFP_EXTEND(SDNode *N);
188 SDOperand visitFNEG(SDNode *N);
189 SDOperand visitFABS(SDNode *N);
190 SDOperand visitBRCOND(SDNode *N);
191 SDOperand visitBR_CC(SDNode *N);
192 SDOperand visitLOAD(SDNode *N);
193 SDOperand visitSTORE(SDNode *N);
194 SDOperand visitINSERT_VECTOR_ELT(SDNode *N);
195 SDOperand visitEXTRACT_VECTOR_ELT(SDNode *N);
196 SDOperand visitBUILD_VECTOR(SDNode *N);
197 SDOperand visitCONCAT_VECTORS(SDNode *N);
198 SDOperand visitVECTOR_SHUFFLE(SDNode *N);
200 SDOperand XformToShuffleWithZero(SDNode *N);
201 SDOperand ReassociateOps(unsigned Opc, SDOperand LHS, SDOperand RHS);
203 SDOperand visitShiftByConstant(SDNode *N, unsigned Amt);
205 bool SimplifySelectOps(SDNode *SELECT, SDOperand LHS, SDOperand RHS);
206 SDOperand SimplifyBinOpWithSameOpcodeHands(SDNode *N);
207 SDOperand SimplifySelect(SDOperand N0, SDOperand N1, SDOperand N2);
208 SDOperand SimplifySelectCC(SDOperand N0, SDOperand N1, SDOperand N2,
209 SDOperand N3, ISD::CondCode CC,
210 bool NotExtCompare = false);
211 SDOperand SimplifySetCC(MVT::ValueType VT, SDOperand N0, SDOperand N1,
212 ISD::CondCode Cond, bool foldBooleans = true);
213 SDOperand SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp,
215 SDOperand ConstantFoldBIT_CONVERTofBUILD_VECTOR(SDNode *, MVT::ValueType);
216 SDOperand BuildSDIV(SDNode *N);
217 SDOperand BuildUDIV(SDNode *N);
218 SDNode *MatchRotate(SDOperand LHS, SDOperand RHS);
219 SDOperand ReduceLoadWidth(SDNode *N);
221 SDOperand GetDemandedBits(SDOperand V, const APInt &Mask);
223 /// GatherAllAliases - Walk up chain skipping non-aliasing memory nodes,
224 /// looking for aliasing nodes and adding them to the Aliases vector.
225 void GatherAllAliases(SDNode *N, SDOperand OriginalChain,
226 SmallVector<SDOperand, 8> &Aliases);
228 /// isAlias - Return true if there is any possibility that the two addresses
230 bool isAlias(SDOperand Ptr1, int64_t Size1,
231 const Value *SrcValue1, int SrcValueOffset1,
232 SDOperand Ptr2, int64_t Size2,
233 const Value *SrcValue2, int SrcValueOffset2);
235 /// FindAliasInfo - Extracts the relevant alias information from the memory
236 /// node. Returns true if the operand was a load.
237 bool FindAliasInfo(SDNode *N,
238 SDOperand &Ptr, int64_t &Size,
239 const Value *&SrcValue, int &SrcValueOffset);
241 /// FindBetterChain - Walk up chain skipping non-aliasing memory nodes,
242 /// looking for a better chain (aliasing node.)
243 SDOperand FindBetterChain(SDNode *N, SDOperand Chain);
246 DAGCombiner(SelectionDAG &D, AliasAnalysis &A)
248 TLI(D.getTargetLoweringInfo()),
249 AfterLegalize(false),
252 /// Run - runs the dag combiner on all nodes in the work list
253 void Run(bool RunningAfterLegalize);
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) {
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 SDOperand TargetLowering::DAGCombinerInfo::
286 CombineTo(SDNode *N, const std::vector<SDOperand> &To) {
287 return ((DAGCombiner*)DC)->CombineTo(N, &To[0], To.size());
290 SDOperand TargetLowering::DAGCombinerInfo::
291 CombineTo(SDNode *N, SDOperand Res) {
292 return ((DAGCombiner*)DC)->CombineTo(N, Res);
296 SDOperand TargetLowering::DAGCombinerInfo::
297 CombineTo(SDNode *N, SDOperand Res0, SDOperand 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(SDOperand Op, bool AfterLegalize,
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 AfterLegalize ? 0 : 1;
331 // FIXME: determine better conditions for this xform.
332 if (!UnsafeFPMath) return 0;
335 if (char V = isNegatibleForFree(Op.getOperand(0), AfterLegalize, Depth+1))
338 return isNegatibleForFree(Op.getOperand(1), AfterLegalize, 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), AfterLegalize, Depth+1))
354 return isNegatibleForFree(Op.getOperand(1), AfterLegalize, Depth+1);
359 return isNegatibleForFree(Op.getOperand(0), AfterLegalize, Depth+1);
363 /// GetNegatedExpression - If isNegatibleForFree returns true, this function
364 /// returns the newly negated expression.
365 static SDOperand GetNegatedExpression(SDOperand Op, SelectionDAG &DAG,
366 bool AfterLegalize, 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), AfterLegalize, Depth+1))
387 return DAG.getNode(ISD::FSUB, Op.getValueType(),
388 GetNegatedExpression(Op.getOperand(0), DAG,
389 AfterLegalize, Depth+1),
392 return DAG.getNode(ISD::FSUB, Op.getValueType(),
393 GetNegatedExpression(Op.getOperand(1), DAG,
394 AfterLegalize, 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), AfterLegalize, Depth+1))
415 return DAG.getNode(Op.getOpcode(), Op.getValueType(),
416 GetNegatedExpression(Op.getOperand(0), DAG,
417 AfterLegalize, Depth+1),
421 return DAG.getNode(Op.getOpcode(), Op.getValueType(),
423 GetNegatedExpression(Op.getOperand(1), DAG,
424 AfterLegalize, Depth+1));
428 return DAG.getNode(Op.getOpcode(), Op.getValueType(),
429 GetNegatedExpression(Op.getOperand(0), DAG,
430 AfterLegalize, Depth+1));
432 return DAG.getNode(ISD::FP_ROUND, Op.getValueType(),
433 GetNegatedExpression(Op.getOperand(0), DAG,
434 AfterLegalize, 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(SDOperand N, SDOperand &LHS, SDOperand &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))->getValue() == 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(SDOperand N) {
470 SDOperand N0, N1, N2;
471 if (isSetCCEquivalent(N, N0, N1, N2) && N.Val->hasOneUse())
476 SDOperand DAGCombiner::ReassociateOps(unsigned Opc, SDOperand N0, SDOperand N1){
477 MVT::ValueType 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 SDOperand OpNode = DAG.getNode(Opc, VT, N0.getOperand(1), N1);
483 AddToWorkList(OpNode.Val);
484 return DAG.getNode(Opc, VT, OpNode, N0.getOperand(0));
485 } else if (N0.hasOneUse()) {
486 SDOperand OpNode = DAG.getNode(Opc, VT, N0.getOperand(0), N1);
487 AddToWorkList(OpNode.Val);
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 SDOperand OpNode = DAG.getNode(Opc, VT, N1.getOperand(1), N0);
496 AddToWorkList(OpNode.Val);
497 return DAG.getNode(Opc, VT, OpNode, N1.getOperand(0));
498 } else if (N1.hasOneUse()) {
499 SDOperand OpNode = DAG.getNode(Opc, VT, N1.getOperand(0), N0);
500 AddToWorkList(OpNode.Val);
501 return DAG.getNode(Opc, VT, OpNode, N1.getOperand(1));
507 SDOperand DAGCombiner::CombineTo(SDNode *N, const SDOperand *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].Val->dump(&DAG));
513 DOUT << " and " << NumTo-1 << " other values\n";
514 WorkListRemover DeadNodes(*this);
515 DAG.ReplaceAllUsesWith(N, To, &DeadNodes);
518 // Push the new nodes and any users onto the worklist
519 for (unsigned i = 0, e = NumTo; i != e; ++i) {
520 AddToWorkList(To[i].Val);
521 AddUsersToWorkList(To[i].Val);
525 // Nodes can be reintroduced into the worklist. Make sure we do not
526 // process a node that has been replaced.
527 removeFromWorkList(N);
529 // Finally, since the node is now dead, remove it from the graph.
531 return SDOperand(N, 0);
534 /// SimplifyDemandedBits - Check the specified integer node value to see if
535 /// it can be simplified or if things it uses can be simplified by bit
536 /// propagation. If so, return true.
537 bool DAGCombiner::SimplifyDemandedBits(SDOperand Op, uint64_t Demanded) {
538 TargetLowering::TargetLoweringOpt TLO(DAG, AfterLegalize);
539 uint64_t KnownZero, KnownOne;
540 Demanded &= MVT::getIntVTBitMask(Op.getValueType());
541 if (!TLI.SimplifyDemandedBits(Op, Demanded, KnownZero, KnownOne, TLO))
545 AddToWorkList(Op.Val);
547 // Replace the old value with the new one.
549 DOUT << "\nReplacing.2 "; DEBUG(TLO.Old.Val->dump(&DAG));
550 DOUT << "\nWith: "; DEBUG(TLO.New.Val->dump(&DAG));
553 // Replace all uses. If any nodes become isomorphic to other nodes and
554 // are deleted, make sure to remove them from our worklist.
555 WorkListRemover DeadNodes(*this);
556 DAG.ReplaceAllUsesOfValueWith(TLO.Old, TLO.New, &DeadNodes);
558 // Push the new node and any (possibly new) users onto the worklist.
559 AddToWorkList(TLO.New.Val);
560 AddUsersToWorkList(TLO.New.Val);
562 // Finally, if the node is now dead, remove it from the graph. The node
563 // may not be dead if the replacement process recursively simplified to
564 // something else needing this node.
565 if (TLO.Old.Val->use_empty()) {
566 removeFromWorkList(TLO.Old.Val);
568 // If the operands of this node are only used by the node, they will now
569 // be dead. Make sure to visit them first to delete dead nodes early.
570 for (unsigned i = 0, e = TLO.Old.Val->getNumOperands(); i != e; ++i)
571 if (TLO.Old.Val->getOperand(i).Val->hasOneUse())
572 AddToWorkList(TLO.Old.Val->getOperand(i).Val);
574 DAG.DeleteNode(TLO.Old.Val);
579 //===----------------------------------------------------------------------===//
580 // Main DAG Combiner implementation
581 //===----------------------------------------------------------------------===//
583 void DAGCombiner::Run(bool RunningAfterLegalize) {
584 // set the instance variable, so that the various visit routines may use it.
585 AfterLegalize = RunningAfterLegalize;
587 // Add all the dag nodes to the worklist.
588 for (SelectionDAG::allnodes_iterator I = DAG.allnodes_begin(),
589 E = DAG.allnodes_end(); I != E; ++I)
590 WorkList.push_back(I);
592 // Create a dummy node (which is not added to allnodes), that adds a reference
593 // to the root node, preventing it from being deleted, and tracking any
594 // changes of the root.
595 HandleSDNode Dummy(DAG.getRoot());
597 // The root of the dag may dangle to deleted nodes until the dag combiner is
598 // done. Set it to null to avoid confusion.
599 DAG.setRoot(SDOperand());
601 // while the worklist isn't empty, inspect the node on the end of it and
602 // try and combine it.
603 while (!WorkList.empty()) {
604 SDNode *N = WorkList.back();
607 // If N has no uses, it is dead. Make sure to revisit all N's operands once
608 // N is deleted from the DAG, since they too may now be dead or may have a
609 // reduced number of uses, allowing other xforms.
610 if (N->use_empty() && N != &Dummy) {
611 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
612 AddToWorkList(N->getOperand(i).Val);
618 SDOperand RV = combine(N);
625 // If we get back the same node we passed in, rather than a new node or
626 // zero, we know that the node must have defined multiple values and
627 // CombineTo was used. Since CombineTo takes care of the worklist
628 // mechanics for us, we have no work to do in this case.
632 assert(N->getOpcode() != ISD::DELETED_NODE &&
633 RV.Val->getOpcode() != ISD::DELETED_NODE &&
634 "Node was deleted but visit returned new node!");
636 DOUT << "\nReplacing.3 "; DEBUG(N->dump(&DAG));
637 DOUT << "\nWith: "; DEBUG(RV.Val->dump(&DAG));
639 WorkListRemover DeadNodes(*this);
640 if (N->getNumValues() == RV.Val->getNumValues())
641 DAG.ReplaceAllUsesWith(N, RV.Val, &DeadNodes);
643 assert(N->getValueType(0) == RV.getValueType() &&
644 N->getNumValues() == 1 && "Type mismatch");
646 DAG.ReplaceAllUsesWith(N, &OpV, &DeadNodes);
649 // Push the new node and any users onto the worklist
650 AddToWorkList(RV.Val);
651 AddUsersToWorkList(RV.Val);
653 // Add any uses of the old node to the worklist in case this node is the
654 // last one that uses them. They may become dead after this node is
656 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
657 AddToWorkList(N->getOperand(i).Val);
659 // Nodes can be reintroduced into the worklist. Make sure we do not
660 // process a node that has been replaced.
661 removeFromWorkList(N);
663 // Finally, since the node is now dead, remove it from the graph.
667 // If the root changed (e.g. it was a dead load, update the root).
668 DAG.setRoot(Dummy.getValue());
671 SDOperand DAGCombiner::visit(SDNode *N) {
672 switch(N->getOpcode()) {
674 case ISD::TokenFactor: return visitTokenFactor(N);
675 case ISD::MERGE_VALUES: return visitMERGE_VALUES(N);
676 case ISD::ADD: return visitADD(N);
677 case ISD::SUB: return visitSUB(N);
678 case ISD::ADDC: return visitADDC(N);
679 case ISD::ADDE: return visitADDE(N);
680 case ISD::MUL: return visitMUL(N);
681 case ISD::SDIV: return visitSDIV(N);
682 case ISD::UDIV: return visitUDIV(N);
683 case ISD::SREM: return visitSREM(N);
684 case ISD::UREM: return visitUREM(N);
685 case ISD::MULHU: return visitMULHU(N);
686 case ISD::MULHS: return visitMULHS(N);
687 case ISD::SMUL_LOHI: return visitSMUL_LOHI(N);
688 case ISD::UMUL_LOHI: return visitUMUL_LOHI(N);
689 case ISD::SDIVREM: return visitSDIVREM(N);
690 case ISD::UDIVREM: return visitUDIVREM(N);
691 case ISD::AND: return visitAND(N);
692 case ISD::OR: return visitOR(N);
693 case ISD::XOR: return visitXOR(N);
694 case ISD::SHL: return visitSHL(N);
695 case ISD::SRA: return visitSRA(N);
696 case ISD::SRL: return visitSRL(N);
697 case ISD::CTLZ: return visitCTLZ(N);
698 case ISD::CTTZ: return visitCTTZ(N);
699 case ISD::CTPOP: return visitCTPOP(N);
700 case ISD::SELECT: return visitSELECT(N);
701 case ISD::SELECT_CC: return visitSELECT_CC(N);
702 case ISD::SETCC: return visitSETCC(N);
703 case ISD::SIGN_EXTEND: return visitSIGN_EXTEND(N);
704 case ISD::ZERO_EXTEND: return visitZERO_EXTEND(N);
705 case ISD::ANY_EXTEND: return visitANY_EXTEND(N);
706 case ISD::SIGN_EXTEND_INREG: return visitSIGN_EXTEND_INREG(N);
707 case ISD::TRUNCATE: return visitTRUNCATE(N);
708 case ISD::BIT_CONVERT: return visitBIT_CONVERT(N);
709 case ISD::FADD: return visitFADD(N);
710 case ISD::FSUB: return visitFSUB(N);
711 case ISD::FMUL: return visitFMUL(N);
712 case ISD::FDIV: return visitFDIV(N);
713 case ISD::FREM: return visitFREM(N);
714 case ISD::FCOPYSIGN: return visitFCOPYSIGN(N);
715 case ISD::SINT_TO_FP: return visitSINT_TO_FP(N);
716 case ISD::UINT_TO_FP: return visitUINT_TO_FP(N);
717 case ISD::FP_TO_SINT: return visitFP_TO_SINT(N);
718 case ISD::FP_TO_UINT: return visitFP_TO_UINT(N);
719 case ISD::FP_ROUND: return visitFP_ROUND(N);
720 case ISD::FP_ROUND_INREG: return visitFP_ROUND_INREG(N);
721 case ISD::FP_EXTEND: return visitFP_EXTEND(N);
722 case ISD::FNEG: return visitFNEG(N);
723 case ISD::FABS: return visitFABS(N);
724 case ISD::BRCOND: return visitBRCOND(N);
725 case ISD::BR_CC: return visitBR_CC(N);
726 case ISD::LOAD: return visitLOAD(N);
727 case ISD::STORE: return visitSTORE(N);
728 case ISD::INSERT_VECTOR_ELT: return visitINSERT_VECTOR_ELT(N);
729 case ISD::EXTRACT_VECTOR_ELT: return visitEXTRACT_VECTOR_ELT(N);
730 case ISD::BUILD_VECTOR: return visitBUILD_VECTOR(N);
731 case ISD::CONCAT_VECTORS: return visitCONCAT_VECTORS(N);
732 case ISD::VECTOR_SHUFFLE: return visitVECTOR_SHUFFLE(N);
737 SDOperand DAGCombiner::combine(SDNode *N) {
739 SDOperand RV = visit(N);
741 // If nothing happened, try a target-specific DAG combine.
743 assert(N->getOpcode() != ISD::DELETED_NODE &&
744 "Node was deleted but visit returned NULL!");
746 if (N->getOpcode() >= ISD::BUILTIN_OP_END ||
747 TLI.hasTargetDAGCombine((ISD::NodeType)N->getOpcode())) {
749 // Expose the DAG combiner to the target combiner impls.
750 TargetLowering::DAGCombinerInfo
751 DagCombineInfo(DAG, !AfterLegalize, false, this);
753 RV = TLI.PerformDAGCombine(N, DagCombineInfo);
760 /// getInputChainForNode - Given a node, return its input chain if it has one,
761 /// otherwise return a null sd operand.
762 static SDOperand getInputChainForNode(SDNode *N) {
763 if (unsigned NumOps = N->getNumOperands()) {
764 if (N->getOperand(0).getValueType() == MVT::Other)
765 return N->getOperand(0);
766 else if (N->getOperand(NumOps-1).getValueType() == MVT::Other)
767 return N->getOperand(NumOps-1);
768 for (unsigned i = 1; i < NumOps-1; ++i)
769 if (N->getOperand(i).getValueType() == MVT::Other)
770 return N->getOperand(i);
772 return SDOperand(0, 0);
775 SDOperand DAGCombiner::visitTokenFactor(SDNode *N) {
776 // If N has two operands, where one has an input chain equal to the other,
777 // the 'other' chain is redundant.
778 if (N->getNumOperands() == 2) {
779 if (getInputChainForNode(N->getOperand(0).Val) == N->getOperand(1))
780 return N->getOperand(0);
781 if (getInputChainForNode(N->getOperand(1).Val) == N->getOperand(0))
782 return N->getOperand(1);
785 SmallVector<SDNode *, 8> TFs; // List of token factors to visit.
786 SmallVector<SDOperand, 8> Ops; // Ops for replacing token factor.
787 SmallPtrSet<SDNode*, 16> SeenOps;
788 bool Changed = false; // If we should replace this token factor.
790 // Start out with this token factor.
793 // Iterate through token factors. The TFs grows when new token factors are
795 for (unsigned i = 0; i < TFs.size(); ++i) {
798 // Check each of the operands.
799 for (unsigned i = 0, ie = TF->getNumOperands(); i != ie; ++i) {
800 SDOperand Op = TF->getOperand(i);
802 switch (Op.getOpcode()) {
803 case ISD::EntryToken:
804 // Entry tokens don't need to be added to the list. They are
809 case ISD::TokenFactor:
810 if ((CombinerAA || Op.hasOneUse()) &&
811 std::find(TFs.begin(), TFs.end(), Op.Val) == TFs.end()) {
812 // Queue up for processing.
813 TFs.push_back(Op.Val);
814 // Clean up in case the token factor is removed.
815 AddToWorkList(Op.Val);
822 // Only add if it isn't already in the list.
823 if (SeenOps.insert(Op.Val))
834 // If we've change things around then replace token factor.
837 // The entry token is the only possible outcome.
838 Result = DAG.getEntryNode();
840 // New and improved token factor.
841 Result = DAG.getNode(ISD::TokenFactor, MVT::Other, &Ops[0], Ops.size());
844 // Don't add users to work list.
845 return CombineTo(N, Result, false);
851 /// MERGE_VALUES can always be eliminated.
852 SDOperand DAGCombiner::visitMERGE_VALUES(SDNode *N) {
853 WorkListRemover DeadNodes(*this);
854 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
855 DAG.ReplaceAllUsesOfValueWith(SDOperand(N, i), N->getOperand(i),
857 removeFromWorkList(N);
859 return SDOperand(N, 0); // Return N so it doesn't get rechecked!
864 SDOperand combineShlAddConstant(SDOperand N0, SDOperand N1, SelectionDAG &DAG) {
865 MVT::ValueType VT = N0.getValueType();
866 SDOperand N00 = N0.getOperand(0);
867 SDOperand N01 = N0.getOperand(1);
868 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N01);
869 if (N01C && N00.getOpcode() == ISD::ADD && N00.Val->hasOneUse() &&
870 isa<ConstantSDNode>(N00.getOperand(1))) {
871 N0 = DAG.getNode(ISD::ADD, VT,
872 DAG.getNode(ISD::SHL, VT, N00.getOperand(0), N01),
873 DAG.getNode(ISD::SHL, VT, N00.getOperand(1), N01));
874 return DAG.getNode(ISD::ADD, VT, N0, N1);
880 SDOperand combineSelectAndUse(SDNode *N, SDOperand Slct, SDOperand OtherOp,
882 MVT::ValueType VT = N->getValueType(0);
883 unsigned Opc = N->getOpcode();
884 bool isSlctCC = Slct.getOpcode() == ISD::SELECT_CC;
885 SDOperand LHS = isSlctCC ? Slct.getOperand(2) : Slct.getOperand(1);
886 SDOperand RHS = isSlctCC ? Slct.getOperand(3) : Slct.getOperand(2);
887 ISD::CondCode CC = ISD::SETCC_INVALID;
889 CC = cast<CondCodeSDNode>(Slct.getOperand(4))->get();
891 SDOperand CCOp = Slct.getOperand(0);
892 if (CCOp.getOpcode() == ISD::SETCC)
893 CC = cast<CondCodeSDNode>(CCOp.getOperand(2))->get();
896 bool DoXform = false;
898 assert ((Opc == ISD::ADD || (Opc == ISD::SUB && Slct == N->getOperand(1))) &&
900 if (LHS.getOpcode() == ISD::Constant &&
901 cast<ConstantSDNode>(LHS)->isNullValue())
903 else if (CC != ISD::SETCC_INVALID &&
904 RHS.getOpcode() == ISD::Constant &&
905 cast<ConstantSDNode>(RHS)->isNullValue()) {
907 SDOperand Op0 = Slct.getOperand(0);
908 bool isInt = MVT::isInteger(isSlctCC ? Op0.getValueType()
909 : Op0.getOperand(0).getValueType());
910 CC = ISD::getSetCCInverse(CC, isInt);
916 SDOperand Result = DAG.getNode(Opc, VT, OtherOp, RHS);
918 return DAG.getSelectCC(OtherOp, Result,
919 Slct.getOperand(0), Slct.getOperand(1), CC);
920 SDOperand CCOp = Slct.getOperand(0);
922 CCOp = DAG.getSetCC(CCOp.getValueType(), CCOp.getOperand(0),
923 CCOp.getOperand(1), CC);
924 return DAG.getNode(ISD::SELECT, VT, CCOp, OtherOp, Result);
929 SDOperand DAGCombiner::visitADD(SDNode *N) {
930 SDOperand N0 = N->getOperand(0);
931 SDOperand N1 = N->getOperand(1);
932 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
933 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
934 MVT::ValueType VT = N0.getValueType();
937 if (MVT::isVector(VT)) {
938 SDOperand FoldedVOp = SimplifyVBinOp(N);
939 if (FoldedVOp.Val) return FoldedVOp;
942 // fold (add x, undef) -> undef
943 if (N0.getOpcode() == ISD::UNDEF)
945 if (N1.getOpcode() == ISD::UNDEF)
947 // fold (add c1, c2) -> c1+c2
949 return DAG.getConstant(N0C->getValue() + N1C->getValue(), VT);
950 // canonicalize constant to RHS
952 return DAG.getNode(ISD::ADD, VT, N1, N0);
953 // fold (add x, 0) -> x
954 if (N1C && N1C->isNullValue())
956 // fold ((c1-A)+c2) -> (c1+c2)-A
957 if (N1C && N0.getOpcode() == ISD::SUB)
958 if (ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getOperand(0)))
959 return DAG.getNode(ISD::SUB, VT,
960 DAG.getConstant(N1C->getValue()+N0C->getValue(), VT),
963 SDOperand RADD = ReassociateOps(ISD::ADD, N0, N1);
966 // fold ((0-A) + B) -> B-A
967 if (N0.getOpcode() == ISD::SUB && isa<ConstantSDNode>(N0.getOperand(0)) &&
968 cast<ConstantSDNode>(N0.getOperand(0))->isNullValue())
969 return DAG.getNode(ISD::SUB, VT, N1, N0.getOperand(1));
970 // fold (A + (0-B)) -> A-B
971 if (N1.getOpcode() == ISD::SUB && isa<ConstantSDNode>(N1.getOperand(0)) &&
972 cast<ConstantSDNode>(N1.getOperand(0))->isNullValue())
973 return DAG.getNode(ISD::SUB, VT, N0, N1.getOperand(1));
974 // fold (A+(B-A)) -> B
975 if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(1))
976 return N1.getOperand(0);
978 if (!MVT::isVector(VT) && SimplifyDemandedBits(SDOperand(N, 0)))
979 return SDOperand(N, 0);
981 // fold (a+b) -> (a|b) iff a and b share no bits.
982 if (MVT::isInteger(VT) && !MVT::isVector(VT)) {
983 APInt LHSZero, LHSOne;
984 APInt RHSZero, RHSOne;
985 APInt Mask = APInt::getAllOnesValue(MVT::getSizeInBits(VT));
986 DAG.ComputeMaskedBits(N0, Mask, LHSZero, LHSOne);
987 if (LHSZero.getBoolValue()) {
988 DAG.ComputeMaskedBits(N1, Mask, RHSZero, RHSOne);
990 // If all possibly-set bits on the LHS are clear on the RHS, return an OR.
991 // If all possibly-set bits on the RHS are clear on the LHS, return an OR.
992 if ((RHSZero & (~LHSZero & Mask)) == (~LHSZero & Mask) ||
993 (LHSZero & (~RHSZero & Mask)) == (~RHSZero & Mask))
994 return DAG.getNode(ISD::OR, VT, N0, N1);
998 // fold (add (shl (add x, c1), c2), ) -> (add (add (shl x, c2), c1<<c2), )
999 if (N0.getOpcode() == ISD::SHL && N0.Val->hasOneUse()) {
1000 SDOperand Result = combineShlAddConstant(N0, N1, DAG);
1001 if (Result.Val) return Result;
1003 if (N1.getOpcode() == ISD::SHL && N1.Val->hasOneUse()) {
1004 SDOperand Result = combineShlAddConstant(N1, N0, DAG);
1005 if (Result.Val) return Result;
1008 // fold (add (select cc, 0, c), x) -> (select cc, x, (add, x, c))
1009 if (N0.getOpcode() == ISD::SELECT && N0.Val->hasOneUse()) {
1010 SDOperand Result = combineSelectAndUse(N, N0, N1, DAG);
1011 if (Result.Val) return Result;
1013 if (N1.getOpcode() == ISD::SELECT && N1.Val->hasOneUse()) {
1014 SDOperand Result = combineSelectAndUse(N, N1, N0, DAG);
1015 if (Result.Val) return Result;
1021 SDOperand DAGCombiner::visitADDC(SDNode *N) {
1022 SDOperand N0 = N->getOperand(0);
1023 SDOperand N1 = N->getOperand(1);
1024 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1025 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1026 MVT::ValueType VT = N0.getValueType();
1028 // If the flag result is dead, turn this into an ADD.
1029 if (N->hasNUsesOfValue(0, 1))
1030 return CombineTo(N, DAG.getNode(ISD::ADD, VT, N1, N0),
1031 DAG.getNode(ISD::CARRY_FALSE, MVT::Flag));
1033 // canonicalize constant to RHS.
1035 SDOperand Ops[] = { N1, N0 };
1036 return DAG.getNode(ISD::ADDC, N->getVTList(), Ops, 2);
1039 // fold (addc x, 0) -> x + no carry out
1040 if (N1C && N1C->isNullValue())
1041 return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE, MVT::Flag));
1043 // fold (addc a, b) -> (or a, b), CARRY_FALSE iff a and b share no bits.
1044 APInt LHSZero, LHSOne;
1045 APInt RHSZero, RHSOne;
1046 APInt Mask = APInt::getAllOnesValue(MVT::getSizeInBits(VT));
1047 DAG.ComputeMaskedBits(N0, Mask, LHSZero, LHSOne);
1048 if (LHSZero.getBoolValue()) {
1049 DAG.ComputeMaskedBits(N1, Mask, RHSZero, RHSOne);
1051 // If all possibly-set bits on the LHS are clear on the RHS, return an OR.
1052 // If all possibly-set bits on the RHS are clear on the LHS, return an OR.
1053 if ((RHSZero & (~LHSZero & Mask)) == (~LHSZero & Mask) ||
1054 (LHSZero & (~RHSZero & Mask)) == (~RHSZero & Mask))
1055 return CombineTo(N, DAG.getNode(ISD::OR, VT, N0, N1),
1056 DAG.getNode(ISD::CARRY_FALSE, MVT::Flag));
1062 SDOperand DAGCombiner::visitADDE(SDNode *N) {
1063 SDOperand N0 = N->getOperand(0);
1064 SDOperand N1 = N->getOperand(1);
1065 SDOperand CarryIn = N->getOperand(2);
1066 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1067 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1068 //MVT::ValueType VT = N0.getValueType();
1070 // canonicalize constant to RHS
1072 SDOperand Ops[] = { N1, N0, CarryIn };
1073 return DAG.getNode(ISD::ADDE, N->getVTList(), Ops, 3);
1076 // fold (adde x, y, false) -> (addc x, y)
1077 if (CarryIn.getOpcode() == ISD::CARRY_FALSE) {
1078 SDOperand Ops[] = { N1, N0 };
1079 return DAG.getNode(ISD::ADDC, N->getVTList(), Ops, 2);
1087 SDOperand DAGCombiner::visitSUB(SDNode *N) {
1088 SDOperand N0 = N->getOperand(0);
1089 SDOperand N1 = N->getOperand(1);
1090 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.Val);
1091 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.Val);
1092 MVT::ValueType VT = N0.getValueType();
1095 if (MVT::isVector(VT)) {
1096 SDOperand FoldedVOp = SimplifyVBinOp(N);
1097 if (FoldedVOp.Val) return FoldedVOp;
1100 // fold (sub x, x) -> 0
1102 return DAG.getConstant(0, N->getValueType(0));
1103 // fold (sub c1, c2) -> c1-c2
1105 return DAG.getNode(ISD::SUB, VT, N0, N1);
1106 // fold (sub x, c) -> (add x, -c)
1108 return DAG.getNode(ISD::ADD, VT, N0, DAG.getConstant(-N1C->getValue(), VT));
1109 // fold (A+B)-A -> B
1110 if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1)
1111 return N0.getOperand(1);
1112 // fold (A+B)-B -> A
1113 if (N0.getOpcode() == ISD::ADD && N0.getOperand(1) == N1)
1114 return N0.getOperand(0);
1115 // fold (sub x, (select cc, 0, c)) -> (select cc, x, (sub, x, c))
1116 if (N1.getOpcode() == ISD::SELECT && N1.Val->hasOneUse()) {
1117 SDOperand Result = combineSelectAndUse(N, N1, N0, DAG);
1118 if (Result.Val) return Result;
1120 // If either operand of a sub is undef, the result is undef
1121 if (N0.getOpcode() == ISD::UNDEF)
1123 if (N1.getOpcode() == ISD::UNDEF)
1129 SDOperand DAGCombiner::visitMUL(SDNode *N) {
1130 SDOperand N0 = N->getOperand(0);
1131 SDOperand N1 = N->getOperand(1);
1132 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1133 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1134 MVT::ValueType VT = N0.getValueType();
1137 if (MVT::isVector(VT)) {
1138 SDOperand FoldedVOp = SimplifyVBinOp(N);
1139 if (FoldedVOp.Val) return FoldedVOp;
1142 // fold (mul x, undef) -> 0
1143 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
1144 return DAG.getConstant(0, VT);
1145 // fold (mul c1, c2) -> c1*c2
1147 return DAG.getNode(ISD::MUL, VT, N0, N1);
1148 // canonicalize constant to RHS
1150 return DAG.getNode(ISD::MUL, VT, N1, N0);
1151 // fold (mul x, 0) -> 0
1152 if (N1C && N1C->isNullValue())
1154 // fold (mul x, -1) -> 0-x
1155 if (N1C && N1C->isAllOnesValue())
1156 return DAG.getNode(ISD::SUB, VT, DAG.getConstant(0, VT), N0);
1157 // fold (mul x, (1 << c)) -> x << c
1158 if (N1C && isPowerOf2_64(N1C->getValue()))
1159 return DAG.getNode(ISD::SHL, VT, N0,
1160 DAG.getConstant(Log2_64(N1C->getValue()),
1161 TLI.getShiftAmountTy()));
1162 // fold (mul x, -(1 << c)) -> -(x << c) or (-x) << c
1163 if (N1C && isPowerOf2_64(-N1C->getSignExtended())) {
1164 // FIXME: If the input is something that is easily negated (e.g. a
1165 // single-use add), we should put the negate there.
1166 return DAG.getNode(ISD::SUB, VT, DAG.getConstant(0, VT),
1167 DAG.getNode(ISD::SHL, VT, N0,
1168 DAG.getConstant(Log2_64(-N1C->getSignExtended()),
1169 TLI.getShiftAmountTy())));
1172 // (mul (shl X, c1), c2) -> (mul X, c2 << c1)
1173 if (N1C && N0.getOpcode() == ISD::SHL &&
1174 isa<ConstantSDNode>(N0.getOperand(1))) {
1175 SDOperand C3 = DAG.getNode(ISD::SHL, VT, N1, N0.getOperand(1));
1176 AddToWorkList(C3.Val);
1177 return DAG.getNode(ISD::MUL, VT, N0.getOperand(0), C3);
1180 // Change (mul (shl X, C), Y) -> (shl (mul X, Y), C) when the shift has one
1183 SDOperand Sh(0,0), Y(0,0);
1184 // Check for both (mul (shl X, C), Y) and (mul Y, (shl X, C)).
1185 if (N0.getOpcode() == ISD::SHL && isa<ConstantSDNode>(N0.getOperand(1)) &&
1186 N0.Val->hasOneUse()) {
1188 } else if (N1.getOpcode() == ISD::SHL &&
1189 isa<ConstantSDNode>(N1.getOperand(1)) && N1.Val->hasOneUse()) {
1193 SDOperand Mul = DAG.getNode(ISD::MUL, VT, Sh.getOperand(0), Y);
1194 return DAG.getNode(ISD::SHL, VT, Mul, Sh.getOperand(1));
1197 // fold (mul (add x, c1), c2) -> (add (mul x, c2), c1*c2)
1198 if (N1C && N0.getOpcode() == ISD::ADD && N0.Val->hasOneUse() &&
1199 isa<ConstantSDNode>(N0.getOperand(1))) {
1200 return DAG.getNode(ISD::ADD, VT,
1201 DAG.getNode(ISD::MUL, VT, N0.getOperand(0), N1),
1202 DAG.getNode(ISD::MUL, VT, N0.getOperand(1), N1));
1206 SDOperand RMUL = ReassociateOps(ISD::MUL, N0, N1);
1213 SDOperand DAGCombiner::visitSDIV(SDNode *N) {
1214 SDOperand N0 = N->getOperand(0);
1215 SDOperand N1 = N->getOperand(1);
1216 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.Val);
1217 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.Val);
1218 MVT::ValueType VT = N->getValueType(0);
1221 if (MVT::isVector(VT)) {
1222 SDOperand FoldedVOp = SimplifyVBinOp(N);
1223 if (FoldedVOp.Val) return FoldedVOp;
1226 // fold (sdiv c1, c2) -> c1/c2
1227 if (N0C && N1C && !N1C->isNullValue())
1228 return DAG.getNode(ISD::SDIV, VT, N0, N1);
1229 // fold (sdiv X, 1) -> X
1230 if (N1C && N1C->getSignExtended() == 1LL)
1232 // fold (sdiv X, -1) -> 0-X
1233 if (N1C && N1C->isAllOnesValue())
1234 return DAG.getNode(ISD::SUB, VT, DAG.getConstant(0, VT), N0);
1235 // If we know the sign bits of both operands are zero, strength reduce to a
1236 // udiv instead. Handles (X&15) /s 4 -> X&15 >> 2
1237 if (!MVT::isVector(VT)) {
1238 if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
1239 return DAG.getNode(ISD::UDIV, N1.getValueType(), N0, N1);
1241 // fold (sdiv X, pow2) -> simple ops after legalize
1242 if (N1C && N1C->getValue() && !TLI.isIntDivCheap() &&
1243 (isPowerOf2_64(N1C->getSignExtended()) ||
1244 isPowerOf2_64(-N1C->getSignExtended()))) {
1245 // If dividing by powers of two is cheap, then don't perform the following
1247 if (TLI.isPow2DivCheap())
1249 int64_t pow2 = N1C->getSignExtended();
1250 int64_t abs2 = pow2 > 0 ? pow2 : -pow2;
1251 unsigned lg2 = Log2_64(abs2);
1252 // Splat the sign bit into the register
1253 SDOperand SGN = DAG.getNode(ISD::SRA, VT, N0,
1254 DAG.getConstant(MVT::getSizeInBits(VT)-1,
1255 TLI.getShiftAmountTy()));
1256 AddToWorkList(SGN.Val);
1257 // Add (N0 < 0) ? abs2 - 1 : 0;
1258 SDOperand SRL = DAG.getNode(ISD::SRL, VT, SGN,
1259 DAG.getConstant(MVT::getSizeInBits(VT)-lg2,
1260 TLI.getShiftAmountTy()));
1261 SDOperand ADD = DAG.getNode(ISD::ADD, VT, N0, SRL);
1262 AddToWorkList(SRL.Val);
1263 AddToWorkList(ADD.Val); // Divide by pow2
1264 SDOperand SRA = DAG.getNode(ISD::SRA, VT, ADD,
1265 DAG.getConstant(lg2, TLI.getShiftAmountTy()));
1266 // If we're dividing by a positive value, we're done. Otherwise, we must
1267 // negate the result.
1270 AddToWorkList(SRA.Val);
1271 return DAG.getNode(ISD::SUB, VT, DAG.getConstant(0, VT), SRA);
1273 // if integer divide is expensive and we satisfy the requirements, emit an
1274 // alternate sequence.
1275 if (N1C && (N1C->getSignExtended() < -1 || N1C->getSignExtended() > 1) &&
1276 !TLI.isIntDivCheap()) {
1277 SDOperand Op = BuildSDIV(N);
1278 if (Op.Val) return Op;
1282 if (N0.getOpcode() == ISD::UNDEF)
1283 return DAG.getConstant(0, VT);
1284 // X / undef -> undef
1285 if (N1.getOpcode() == ISD::UNDEF)
1291 SDOperand DAGCombiner::visitUDIV(SDNode *N) {
1292 SDOperand N0 = N->getOperand(0);
1293 SDOperand N1 = N->getOperand(1);
1294 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.Val);
1295 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.Val);
1296 MVT::ValueType VT = N->getValueType(0);
1299 if (MVT::isVector(VT)) {
1300 SDOperand FoldedVOp = SimplifyVBinOp(N);
1301 if (FoldedVOp.Val) return FoldedVOp;
1304 // fold (udiv c1, c2) -> c1/c2
1305 if (N0C && N1C && !N1C->isNullValue())
1306 return DAG.getNode(ISD::UDIV, VT, N0, N1);
1307 // fold (udiv x, (1 << c)) -> x >>u c
1308 if (N1C && isPowerOf2_64(N1C->getValue()))
1309 return DAG.getNode(ISD::SRL, VT, N0,
1310 DAG.getConstant(Log2_64(N1C->getValue()),
1311 TLI.getShiftAmountTy()));
1312 // fold (udiv x, (shl c, y)) -> x >>u (log2(c)+y) iff c is power of 2
1313 if (N1.getOpcode() == ISD::SHL) {
1314 if (ConstantSDNode *SHC = dyn_cast<ConstantSDNode>(N1.getOperand(0))) {
1315 if (isPowerOf2_64(SHC->getValue())) {
1316 MVT::ValueType ADDVT = N1.getOperand(1).getValueType();
1317 SDOperand Add = DAG.getNode(ISD::ADD, ADDVT, N1.getOperand(1),
1318 DAG.getConstant(Log2_64(SHC->getValue()),
1320 AddToWorkList(Add.Val);
1321 return DAG.getNode(ISD::SRL, VT, N0, Add);
1325 // fold (udiv x, c) -> alternate
1326 if (N1C && N1C->getValue() && !TLI.isIntDivCheap()) {
1327 SDOperand Op = BuildUDIV(N);
1328 if (Op.Val) return Op;
1332 if (N0.getOpcode() == ISD::UNDEF)
1333 return DAG.getConstant(0, VT);
1334 // X / undef -> undef
1335 if (N1.getOpcode() == ISD::UNDEF)
1341 SDOperand DAGCombiner::visitSREM(SDNode *N) {
1342 SDOperand N0 = N->getOperand(0);
1343 SDOperand N1 = N->getOperand(1);
1344 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1345 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1346 MVT::ValueType VT = N->getValueType(0);
1348 // fold (srem c1, c2) -> c1%c2
1349 if (N0C && N1C && !N1C->isNullValue())
1350 return DAG.getNode(ISD::SREM, VT, N0, N1);
1351 // If we know the sign bits of both operands are zero, strength reduce to a
1352 // urem instead. Handles (X & 0x0FFFFFFF) %s 16 -> X&15
1353 if (!MVT::isVector(VT)) {
1354 if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
1355 return DAG.getNode(ISD::UREM, VT, N0, N1);
1358 // If X/C can be simplified by the division-by-constant logic, lower
1359 // X%C to the equivalent of X-X/C*C.
1360 if (N1C && !N1C->isNullValue()) {
1361 SDOperand Div = DAG.getNode(ISD::SDIV, VT, N0, N1);
1362 AddToWorkList(Div.Val);
1363 SDOperand OptimizedDiv = combine(Div.Val);
1364 if (OptimizedDiv.Val && OptimizedDiv.Val != Div.Val) {
1365 SDOperand Mul = DAG.getNode(ISD::MUL, VT, OptimizedDiv, N1);
1366 SDOperand Sub = DAG.getNode(ISD::SUB, VT, N0, Mul);
1367 AddToWorkList(Mul.Val);
1373 if (N0.getOpcode() == ISD::UNDEF)
1374 return DAG.getConstant(0, VT);
1375 // X % undef -> undef
1376 if (N1.getOpcode() == ISD::UNDEF)
1382 SDOperand DAGCombiner::visitUREM(SDNode *N) {
1383 SDOperand N0 = N->getOperand(0);
1384 SDOperand N1 = N->getOperand(1);
1385 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1386 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1387 MVT::ValueType VT = N->getValueType(0);
1389 // fold (urem c1, c2) -> c1%c2
1390 if (N0C && N1C && !N1C->isNullValue())
1391 return DAG.getNode(ISD::UREM, VT, N0, N1);
1392 // fold (urem x, pow2) -> (and x, pow2-1)
1393 if (N1C && !N1C->isNullValue() && isPowerOf2_64(N1C->getValue()))
1394 return DAG.getNode(ISD::AND, VT, N0, DAG.getConstant(N1C->getValue()-1,VT));
1395 // fold (urem x, (shl pow2, y)) -> (and x, (add (shl pow2, y), -1))
1396 if (N1.getOpcode() == ISD::SHL) {
1397 if (ConstantSDNode *SHC = dyn_cast<ConstantSDNode>(N1.getOperand(0))) {
1398 if (isPowerOf2_64(SHC->getValue())) {
1399 SDOperand Add = DAG.getNode(ISD::ADD, VT, N1,DAG.getConstant(~0ULL,VT));
1400 AddToWorkList(Add.Val);
1401 return DAG.getNode(ISD::AND, VT, N0, Add);
1406 // If X/C can be simplified by the division-by-constant logic, lower
1407 // X%C to the equivalent of X-X/C*C.
1408 if (N1C && !N1C->isNullValue()) {
1409 SDOperand Div = DAG.getNode(ISD::UDIV, VT, N0, N1);
1410 SDOperand OptimizedDiv = combine(Div.Val);
1411 if (OptimizedDiv.Val && OptimizedDiv.Val != Div.Val) {
1412 SDOperand Mul = DAG.getNode(ISD::MUL, VT, OptimizedDiv, N1);
1413 SDOperand Sub = DAG.getNode(ISD::SUB, VT, N0, Mul);
1414 AddToWorkList(Mul.Val);
1420 if (N0.getOpcode() == ISD::UNDEF)
1421 return DAG.getConstant(0, VT);
1422 // X % undef -> undef
1423 if (N1.getOpcode() == ISD::UNDEF)
1429 SDOperand DAGCombiner::visitMULHS(SDNode *N) {
1430 SDOperand N0 = N->getOperand(0);
1431 SDOperand N1 = N->getOperand(1);
1432 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1433 MVT::ValueType VT = N->getValueType(0);
1435 // fold (mulhs x, 0) -> 0
1436 if (N1C && N1C->isNullValue())
1438 // fold (mulhs x, 1) -> (sra x, size(x)-1)
1439 if (N1C && N1C->getValue() == 1)
1440 return DAG.getNode(ISD::SRA, N0.getValueType(), N0,
1441 DAG.getConstant(MVT::getSizeInBits(N0.getValueType())-1,
1442 TLI.getShiftAmountTy()));
1443 // fold (mulhs x, undef) -> 0
1444 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
1445 return DAG.getConstant(0, VT);
1450 SDOperand DAGCombiner::visitMULHU(SDNode *N) {
1451 SDOperand N0 = N->getOperand(0);
1452 SDOperand N1 = N->getOperand(1);
1453 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1454 MVT::ValueType VT = N->getValueType(0);
1456 // fold (mulhu x, 0) -> 0
1457 if (N1C && N1C->isNullValue())
1459 // fold (mulhu x, 1) -> 0
1460 if (N1C && N1C->getValue() == 1)
1461 return DAG.getConstant(0, N0.getValueType());
1462 // fold (mulhu x, undef) -> 0
1463 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
1464 return DAG.getConstant(0, VT);
1469 /// SimplifyNodeWithTwoResults - Perform optimizations common to nodes that
1470 /// compute two values. LoOp and HiOp give the opcodes for the two computations
1471 /// that are being performed. Return true if a simplification was made.
1473 SDOperand DAGCombiner::SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp,
1475 // If the high half is not needed, just compute the low half.
1476 bool HiExists = N->hasAnyUseOfValue(1);
1479 TLI.isOperationLegal(LoOp, N->getValueType(0)))) {
1480 SDOperand Res = DAG.getNode(LoOp, N->getValueType(0), N->op_begin(),
1481 N->getNumOperands());
1482 return CombineTo(N, Res, Res);
1485 // If the low half is not needed, just compute the high half.
1486 bool LoExists = N->hasAnyUseOfValue(0);
1489 TLI.isOperationLegal(HiOp, N->getValueType(1)))) {
1490 SDOperand Res = DAG.getNode(HiOp, N->getValueType(1), N->op_begin(),
1491 N->getNumOperands());
1492 return CombineTo(N, Res, Res);
1495 // If both halves are used, return as it is.
1496 if (LoExists && HiExists)
1499 // If the two computed results can be simplified separately, separate them.
1501 SDOperand Lo = DAG.getNode(LoOp, N->getValueType(0),
1502 N->op_begin(), N->getNumOperands());
1503 AddToWorkList(Lo.Val);
1504 SDOperand LoOpt = combine(Lo.Val);
1505 if (LoOpt.Val && LoOpt.Val != Lo.Val &&
1506 TLI.isOperationLegal(LoOpt.getOpcode(), LoOpt.getValueType()))
1507 return CombineTo(N, LoOpt, LoOpt);
1511 SDOperand Hi = DAG.getNode(HiOp, N->getValueType(1),
1512 N->op_begin(), N->getNumOperands());
1513 AddToWorkList(Hi.Val);
1514 SDOperand HiOpt = combine(Hi.Val);
1515 if (HiOpt.Val && HiOpt != Hi &&
1516 TLI.isOperationLegal(HiOpt.getOpcode(), HiOpt.getValueType()))
1517 return CombineTo(N, HiOpt, HiOpt);
1522 SDOperand DAGCombiner::visitSMUL_LOHI(SDNode *N) {
1523 SDOperand Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHS);
1524 if (Res.Val) return Res;
1529 SDOperand DAGCombiner::visitUMUL_LOHI(SDNode *N) {
1530 SDOperand Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHU);
1531 if (Res.Val) return Res;
1536 SDOperand DAGCombiner::visitSDIVREM(SDNode *N) {
1537 SDOperand Res = SimplifyNodeWithTwoResults(N, ISD::SDIV, ISD::SREM);
1538 if (Res.Val) return Res;
1543 SDOperand DAGCombiner::visitUDIVREM(SDNode *N) {
1544 SDOperand Res = SimplifyNodeWithTwoResults(N, ISD::UDIV, ISD::UREM);
1545 if (Res.Val) return Res;
1550 /// SimplifyBinOpWithSameOpcodeHands - If this is a binary operator with
1551 /// two operands of the same opcode, try to simplify it.
1552 SDOperand DAGCombiner::SimplifyBinOpWithSameOpcodeHands(SDNode *N) {
1553 SDOperand N0 = N->getOperand(0), N1 = N->getOperand(1);
1554 MVT::ValueType VT = N0.getValueType();
1555 assert(N0.getOpcode() == N1.getOpcode() && "Bad input!");
1557 // For each of OP in AND/OR/XOR:
1558 // fold (OP (zext x), (zext y)) -> (zext (OP x, y))
1559 // fold (OP (sext x), (sext y)) -> (sext (OP x, y))
1560 // fold (OP (aext x), (aext y)) -> (aext (OP x, y))
1561 // fold (OP (trunc x), (trunc y)) -> (trunc (OP x, y))
1562 if ((N0.getOpcode() == ISD::ZERO_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND||
1563 N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::TRUNCATE) &&
1564 N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType()) {
1565 SDOperand ORNode = DAG.getNode(N->getOpcode(),
1566 N0.getOperand(0).getValueType(),
1567 N0.getOperand(0), N1.getOperand(0));
1568 AddToWorkList(ORNode.Val);
1569 return DAG.getNode(N0.getOpcode(), VT, ORNode);
1572 // For each of OP in SHL/SRL/SRA/AND...
1573 // fold (and (OP x, z), (OP y, z)) -> (OP (and x, y), z)
1574 // fold (or (OP x, z), (OP y, z)) -> (OP (or x, y), z)
1575 // fold (xor (OP x, z), (OP y, z)) -> (OP (xor x, y), z)
1576 if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL ||
1577 N0.getOpcode() == ISD::SRA || N0.getOpcode() == ISD::AND) &&
1578 N0.getOperand(1) == N1.getOperand(1)) {
1579 SDOperand ORNode = DAG.getNode(N->getOpcode(),
1580 N0.getOperand(0).getValueType(),
1581 N0.getOperand(0), N1.getOperand(0));
1582 AddToWorkList(ORNode.Val);
1583 return DAG.getNode(N0.getOpcode(), VT, ORNode, N0.getOperand(1));
1589 SDOperand DAGCombiner::visitAND(SDNode *N) {
1590 SDOperand N0 = N->getOperand(0);
1591 SDOperand N1 = N->getOperand(1);
1592 SDOperand LL, LR, RL, RR, CC0, CC1;
1593 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1594 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1595 MVT::ValueType VT = N1.getValueType();
1596 unsigned BitWidth = MVT::getSizeInBits(VT);
1599 if (MVT::isVector(VT)) {
1600 SDOperand FoldedVOp = SimplifyVBinOp(N);
1601 if (FoldedVOp.Val) return FoldedVOp;
1604 // fold (and x, undef) -> 0
1605 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
1606 return DAG.getConstant(0, VT);
1607 // fold (and c1, c2) -> c1&c2
1609 return DAG.getNode(ISD::AND, VT, N0, N1);
1610 // canonicalize constant to RHS
1612 return DAG.getNode(ISD::AND, VT, N1, N0);
1613 // fold (and x, -1) -> x
1614 if (N1C && N1C->isAllOnesValue())
1616 // if (and x, c) is known to be zero, return 0
1617 if (N1C && DAG.MaskedValueIsZero(SDOperand(N, 0),
1618 APInt::getAllOnesValue(BitWidth)))
1619 return DAG.getConstant(0, VT);
1621 SDOperand RAND = ReassociateOps(ISD::AND, N0, N1);
1624 // fold (and (or x, 0xFFFF), 0xFF) -> 0xFF
1625 if (N1C && N0.getOpcode() == ISD::OR)
1626 if (ConstantSDNode *ORI = dyn_cast<ConstantSDNode>(N0.getOperand(1)))
1627 if ((ORI->getValue() & N1C->getValue()) == N1C->getValue())
1629 // fold (and (any_ext V), c) -> (zero_ext V) if 'and' only clears top bits.
1630 if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
1631 SDOperand N0Op0 = N0.getOperand(0);
1632 APInt Mask = ~N1C->getAPIntValue();
1633 Mask.trunc(N0Op0.getValueSizeInBits());
1634 if (DAG.MaskedValueIsZero(N0Op0, Mask)) {
1635 SDOperand Zext = DAG.getNode(ISD::ZERO_EXTEND, N0.getValueType(),
1638 // Replace uses of the AND with uses of the Zero extend node.
1641 // We actually want to replace all uses of the any_extend with the
1642 // zero_extend, to avoid duplicating things. This will later cause this
1643 // AND to be folded.
1644 CombineTo(N0.Val, Zext);
1645 return SDOperand(N, 0); // Return N so it doesn't get rechecked!
1648 // fold (and (setcc x), (setcc y)) -> (setcc (and x, y))
1649 if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){
1650 ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get();
1651 ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get();
1653 if (LR == RR && isa<ConstantSDNode>(LR) && Op0 == Op1 &&
1654 MVT::isInteger(LL.getValueType())) {
1655 // fold (X == 0) & (Y == 0) -> (X|Y == 0)
1656 if (cast<ConstantSDNode>(LR)->getValue() == 0 && Op1 == ISD::SETEQ) {
1657 SDOperand ORNode = DAG.getNode(ISD::OR, LR.getValueType(), LL, RL);
1658 AddToWorkList(ORNode.Val);
1659 return DAG.getSetCC(VT, ORNode, LR, Op1);
1661 // fold (X == -1) & (Y == -1) -> (X&Y == -1)
1662 if (cast<ConstantSDNode>(LR)->isAllOnesValue() && Op1 == ISD::SETEQ) {
1663 SDOperand ANDNode = DAG.getNode(ISD::AND, LR.getValueType(), LL, RL);
1664 AddToWorkList(ANDNode.Val);
1665 return DAG.getSetCC(VT, ANDNode, LR, Op1);
1667 // fold (X > -1) & (Y > -1) -> (X|Y > -1)
1668 if (cast<ConstantSDNode>(LR)->isAllOnesValue() && Op1 == ISD::SETGT) {
1669 SDOperand ORNode = DAG.getNode(ISD::OR, LR.getValueType(), LL, RL);
1670 AddToWorkList(ORNode.Val);
1671 return DAG.getSetCC(VT, ORNode, LR, Op1);
1674 // canonicalize equivalent to ll == rl
1675 if (LL == RR && LR == RL) {
1676 Op1 = ISD::getSetCCSwappedOperands(Op1);
1679 if (LL == RL && LR == RR) {
1680 bool isInteger = MVT::isInteger(LL.getValueType());
1681 ISD::CondCode Result = ISD::getSetCCAndOperation(Op0, Op1, isInteger);
1682 if (Result != ISD::SETCC_INVALID)
1683 return DAG.getSetCC(N0.getValueType(), LL, LR, Result);
1687 // Simplify: and (op x...), (op y...) -> (op (and x, y))
1688 if (N0.getOpcode() == N1.getOpcode()) {
1689 SDOperand Tmp = SimplifyBinOpWithSameOpcodeHands(N);
1690 if (Tmp.Val) return Tmp;
1693 // fold (and (sign_extend_inreg x, i16 to i32), 1) -> (and x, 1)
1694 // fold (and (sra)) -> (and (srl)) when possible.
1695 if (!MVT::isVector(VT) &&
1696 SimplifyDemandedBits(SDOperand(N, 0)))
1697 return SDOperand(N, 0);
1698 // fold (zext_inreg (extload x)) -> (zextload x)
1699 if (ISD::isEXTLoad(N0.Val) && ISD::isUNINDEXEDLoad(N0.Val)) {
1700 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
1701 MVT::ValueType EVT = LN0->getMemoryVT();
1702 // If we zero all the possible extended bits, then we can turn this into
1703 // a zextload if we are running before legalize or the operation is legal.
1704 unsigned BitWidth = N1.getValueSizeInBits();
1705 if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth,
1706 BitWidth - MVT::getSizeInBits(EVT))) &&
1707 (!AfterLegalize || TLI.isLoadXLegal(ISD::ZEXTLOAD, EVT))) {
1708 SDOperand ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, VT, LN0->getChain(),
1709 LN0->getBasePtr(), LN0->getSrcValue(),
1710 LN0->getSrcValueOffset(), EVT,
1712 LN0->getAlignment());
1714 CombineTo(N0.Val, ExtLoad, ExtLoad.getValue(1));
1715 return SDOperand(N, 0); // Return N so it doesn't get rechecked!
1718 // fold (zext_inreg (sextload x)) -> (zextload x) iff load has one use
1719 if (ISD::isSEXTLoad(N0.Val) && ISD::isUNINDEXEDLoad(N0.Val) &&
1721 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
1722 MVT::ValueType EVT = LN0->getMemoryVT();
1723 // If we zero all the possible extended bits, then we can turn this into
1724 // a zextload if we are running before legalize or the operation is legal.
1725 unsigned BitWidth = N1.getValueSizeInBits();
1726 if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth,
1727 BitWidth - MVT::getSizeInBits(EVT))) &&
1728 (!AfterLegalize || TLI.isLoadXLegal(ISD::ZEXTLOAD, EVT))) {
1729 SDOperand ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, VT, LN0->getChain(),
1730 LN0->getBasePtr(), LN0->getSrcValue(),
1731 LN0->getSrcValueOffset(), EVT,
1733 LN0->getAlignment());
1735 CombineTo(N0.Val, ExtLoad, ExtLoad.getValue(1));
1736 return SDOperand(N, 0); // Return N so it doesn't get rechecked!
1740 // fold (and (load x), 255) -> (zextload x, i8)
1741 // fold (and (extload x, i16), 255) -> (zextload x, i8)
1742 if (N1C && N0.getOpcode() == ISD::LOAD) {
1743 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
1744 if (LN0->getExtensionType() != ISD::SEXTLOAD &&
1745 LN0->isUnindexed() && N0.hasOneUse()) {
1746 MVT::ValueType EVT, LoadedVT;
1747 if (N1C->getValue() == 255)
1749 else if (N1C->getValue() == 65535)
1751 else if (N1C->getValue() == ~0U)
1756 LoadedVT = LN0->getMemoryVT();
1757 if (EVT != MVT::Other && LoadedVT > EVT &&
1758 (!AfterLegalize || TLI.isLoadXLegal(ISD::ZEXTLOAD, EVT))) {
1759 MVT::ValueType PtrType = N0.getOperand(1).getValueType();
1760 // For big endian targets, we need to add an offset to the pointer to
1761 // load the correct bytes. For little endian systems, we merely need to
1762 // read fewer bytes from the same pointer.
1763 unsigned LVTStoreBytes = MVT::getStoreSizeInBits(LoadedVT)/8;
1764 unsigned EVTStoreBytes = MVT::getStoreSizeInBits(EVT)/8;
1765 unsigned PtrOff = LVTStoreBytes - EVTStoreBytes;
1766 unsigned Alignment = LN0->getAlignment();
1767 SDOperand NewPtr = LN0->getBasePtr();
1768 if (TLI.isBigEndian()) {
1769 NewPtr = DAG.getNode(ISD::ADD, PtrType, NewPtr,
1770 DAG.getConstant(PtrOff, PtrType));
1771 Alignment = MinAlign(Alignment, PtrOff);
1773 AddToWorkList(NewPtr.Val);
1775 DAG.getExtLoad(ISD::ZEXTLOAD, VT, LN0->getChain(), NewPtr,
1776 LN0->getSrcValue(), LN0->getSrcValueOffset(), EVT,
1777 LN0->isVolatile(), Alignment);
1779 CombineTo(N0.Val, Load, Load.getValue(1));
1780 return SDOperand(N, 0); // Return N so it doesn't get rechecked!
1788 SDOperand DAGCombiner::visitOR(SDNode *N) {
1789 SDOperand N0 = N->getOperand(0);
1790 SDOperand N1 = N->getOperand(1);
1791 SDOperand LL, LR, RL, RR, CC0, CC1;
1792 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1793 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1794 MVT::ValueType VT = N1.getValueType();
1797 if (MVT::isVector(VT)) {
1798 SDOperand FoldedVOp = SimplifyVBinOp(N);
1799 if (FoldedVOp.Val) return FoldedVOp;
1802 // fold (or x, undef) -> -1
1803 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
1804 return DAG.getConstant(~0ULL, VT);
1805 // fold (or c1, c2) -> c1|c2
1807 return DAG.getNode(ISD::OR, VT, N0, N1);
1808 // canonicalize constant to RHS
1810 return DAG.getNode(ISD::OR, VT, N1, N0);
1811 // fold (or x, 0) -> x
1812 if (N1C && N1C->isNullValue())
1814 // fold (or x, -1) -> -1
1815 if (N1C && N1C->isAllOnesValue())
1817 // fold (or x, c) -> c iff (x & ~c) == 0
1818 if (N1C && DAG.MaskedValueIsZero(N0, ~N1C->getAPIntValue()))
1821 SDOperand ROR = ReassociateOps(ISD::OR, N0, N1);
1824 // Canonicalize (or (and X, c1), c2) -> (and (or X, c2), c1|c2)
1825 if (N1C && N0.getOpcode() == ISD::AND && N0.Val->hasOneUse() &&
1826 isa<ConstantSDNode>(N0.getOperand(1))) {
1827 ConstantSDNode *C1 = cast<ConstantSDNode>(N0.getOperand(1));
1828 return DAG.getNode(ISD::AND, VT, DAG.getNode(ISD::OR, VT, N0.getOperand(0),
1830 DAG.getConstant(N1C->getValue() | C1->getValue(), VT));
1832 // fold (or (setcc x), (setcc y)) -> (setcc (or x, y))
1833 if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){
1834 ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get();
1835 ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get();
1837 if (LR == RR && isa<ConstantSDNode>(LR) && Op0 == Op1 &&
1838 MVT::isInteger(LL.getValueType())) {
1839 // fold (X != 0) | (Y != 0) -> (X|Y != 0)
1840 // fold (X < 0) | (Y < 0) -> (X|Y < 0)
1841 if (cast<ConstantSDNode>(LR)->getValue() == 0 &&
1842 (Op1 == ISD::SETNE || Op1 == ISD::SETLT)) {
1843 SDOperand ORNode = DAG.getNode(ISD::OR, LR.getValueType(), LL, RL);
1844 AddToWorkList(ORNode.Val);
1845 return DAG.getSetCC(VT, ORNode, LR, Op1);
1847 // fold (X != -1) | (Y != -1) -> (X&Y != -1)
1848 // fold (X > -1) | (Y > -1) -> (X&Y > -1)
1849 if (cast<ConstantSDNode>(LR)->isAllOnesValue() &&
1850 (Op1 == ISD::SETNE || Op1 == ISD::SETGT)) {
1851 SDOperand ANDNode = DAG.getNode(ISD::AND, LR.getValueType(), LL, RL);
1852 AddToWorkList(ANDNode.Val);
1853 return DAG.getSetCC(VT, ANDNode, LR, Op1);
1856 // canonicalize equivalent to ll == rl
1857 if (LL == RR && LR == RL) {
1858 Op1 = ISD::getSetCCSwappedOperands(Op1);
1861 if (LL == RL && LR == RR) {
1862 bool isInteger = MVT::isInteger(LL.getValueType());
1863 ISD::CondCode Result = ISD::getSetCCOrOperation(Op0, Op1, isInteger);
1864 if (Result != ISD::SETCC_INVALID)
1865 return DAG.getSetCC(N0.getValueType(), LL, LR, Result);
1869 // Simplify: or (op x...), (op y...) -> (op (or x, y))
1870 if (N0.getOpcode() == N1.getOpcode()) {
1871 SDOperand Tmp = SimplifyBinOpWithSameOpcodeHands(N);
1872 if (Tmp.Val) return Tmp;
1875 // (X & C1) | (Y & C2) -> (X|Y) & C3 if possible.
1876 if (N0.getOpcode() == ISD::AND &&
1877 N1.getOpcode() == ISD::AND &&
1878 N0.getOperand(1).getOpcode() == ISD::Constant &&
1879 N1.getOperand(1).getOpcode() == ISD::Constant &&
1880 // Don't increase # computations.
1881 (N0.Val->hasOneUse() || N1.Val->hasOneUse())) {
1882 // We can only do this xform if we know that bits from X that are set in C2
1883 // but not in C1 are already zero. Likewise for Y.
1884 const APInt &LHSMask =
1885 cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
1886 const APInt &RHSMask =
1887 cast<ConstantSDNode>(N1.getOperand(1))->getAPIntValue();
1889 if (DAG.MaskedValueIsZero(N0.getOperand(0), RHSMask&~LHSMask) &&
1890 DAG.MaskedValueIsZero(N1.getOperand(0), LHSMask&~RHSMask)) {
1891 SDOperand X =DAG.getNode(ISD::OR, VT, N0.getOperand(0), N1.getOperand(0));
1892 return DAG.getNode(ISD::AND, VT, X, DAG.getConstant(LHSMask|RHSMask, VT));
1897 // See if this is some rotate idiom.
1898 if (SDNode *Rot = MatchRotate(N0, N1))
1899 return SDOperand(Rot, 0);
1905 /// MatchRotateHalf - Match "(X shl/srl V1) & V2" where V2 may not be present.
1906 static bool MatchRotateHalf(SDOperand Op, SDOperand &Shift, SDOperand &Mask) {
1907 if (Op.getOpcode() == ISD::AND) {
1908 if (isa<ConstantSDNode>(Op.getOperand(1))) {
1909 Mask = Op.getOperand(1);
1910 Op = Op.getOperand(0);
1916 if (Op.getOpcode() == ISD::SRL || Op.getOpcode() == ISD::SHL) {
1924 // MatchRotate - Handle an 'or' of two operands. If this is one of the many
1925 // idioms for rotate, and if the target supports rotation instructions, generate
1927 SDNode *DAGCombiner::MatchRotate(SDOperand LHS, SDOperand RHS) {
1928 // Must be a legal type. Expanded an promoted things won't work with rotates.
1929 MVT::ValueType VT = LHS.getValueType();
1930 if (!TLI.isTypeLegal(VT)) return 0;
1932 // The target must have at least one rotate flavor.
1933 bool HasROTL = TLI.isOperationLegal(ISD::ROTL, VT);
1934 bool HasROTR = TLI.isOperationLegal(ISD::ROTR, VT);
1935 if (!HasROTL && !HasROTR) return 0;
1937 // Match "(X shl/srl V1) & V2" where V2 may not be present.
1938 SDOperand LHSShift; // The shift.
1939 SDOperand LHSMask; // AND value if any.
1940 if (!MatchRotateHalf(LHS, LHSShift, LHSMask))
1941 return 0; // Not part of a rotate.
1943 SDOperand RHSShift; // The shift.
1944 SDOperand RHSMask; // AND value if any.
1945 if (!MatchRotateHalf(RHS, RHSShift, RHSMask))
1946 return 0; // Not part of a rotate.
1948 if (LHSShift.getOperand(0) != RHSShift.getOperand(0))
1949 return 0; // Not shifting the same value.
1951 if (LHSShift.getOpcode() == RHSShift.getOpcode())
1952 return 0; // Shifts must disagree.
1954 // Canonicalize shl to left side in a shl/srl pair.
1955 if (RHSShift.getOpcode() == ISD::SHL) {
1956 std::swap(LHS, RHS);
1957 std::swap(LHSShift, RHSShift);
1958 std::swap(LHSMask , RHSMask );
1961 unsigned OpSizeInBits = MVT::getSizeInBits(VT);
1962 SDOperand LHSShiftArg = LHSShift.getOperand(0);
1963 SDOperand LHSShiftAmt = LHSShift.getOperand(1);
1964 SDOperand RHSShiftAmt = RHSShift.getOperand(1);
1966 // fold (or (shl x, C1), (srl x, C2)) -> (rotl x, C1)
1967 // fold (or (shl x, C1), (srl x, C2)) -> (rotr x, C2)
1968 if (LHSShiftAmt.getOpcode() == ISD::Constant &&
1969 RHSShiftAmt.getOpcode() == ISD::Constant) {
1970 uint64_t LShVal = cast<ConstantSDNode>(LHSShiftAmt)->getValue();
1971 uint64_t RShVal = cast<ConstantSDNode>(RHSShiftAmt)->getValue();
1972 if ((LShVal + RShVal) != OpSizeInBits)
1977 Rot = DAG.getNode(ISD::ROTL, VT, LHSShiftArg, LHSShiftAmt);
1979 Rot = DAG.getNode(ISD::ROTR, VT, LHSShiftArg, RHSShiftAmt);
1981 // If there is an AND of either shifted operand, apply it to the result.
1982 if (LHSMask.Val || RHSMask.Val) {
1983 uint64_t Mask = MVT::getIntVTBitMask(VT);
1986 uint64_t RHSBits = (1ULL << LShVal)-1;
1987 Mask &= cast<ConstantSDNode>(LHSMask)->getValue() | RHSBits;
1990 uint64_t LHSBits = ~((1ULL << (OpSizeInBits-RShVal))-1);
1991 Mask &= cast<ConstantSDNode>(RHSMask)->getValue() | LHSBits;
1994 Rot = DAG.getNode(ISD::AND, VT, Rot, DAG.getConstant(Mask, VT));
2000 // If there is a mask here, and we have a variable shift, we can't be sure
2001 // that we're masking out the right stuff.
2002 if (LHSMask.Val || RHSMask.Val)
2005 // fold (or (shl x, y), (srl x, (sub 32, y))) -> (rotl x, y)
2006 // fold (or (shl x, y), (srl x, (sub 32, y))) -> (rotr x, (sub 32, y))
2007 if (RHSShiftAmt.getOpcode() == ISD::SUB &&
2008 LHSShiftAmt == RHSShiftAmt.getOperand(1)) {
2009 if (ConstantSDNode *SUBC =
2010 dyn_cast<ConstantSDNode>(RHSShiftAmt.getOperand(0))) {
2011 if (SUBC->getValue() == OpSizeInBits) {
2013 return DAG.getNode(ISD::ROTL, VT, LHSShiftArg, LHSShiftAmt).Val;
2015 return DAG.getNode(ISD::ROTR, VT, LHSShiftArg, RHSShiftAmt).Val;
2020 // fold (or (shl x, (sub 32, y)), (srl x, r)) -> (rotr x, y)
2021 // fold (or (shl x, (sub 32, y)), (srl x, r)) -> (rotl x, (sub 32, y))
2022 if (LHSShiftAmt.getOpcode() == ISD::SUB &&
2023 RHSShiftAmt == LHSShiftAmt.getOperand(1)) {
2024 if (ConstantSDNode *SUBC =
2025 dyn_cast<ConstantSDNode>(LHSShiftAmt.getOperand(0))) {
2026 if (SUBC->getValue() == OpSizeInBits) {
2028 return DAG.getNode(ISD::ROTL, VT, LHSShiftArg, LHSShiftAmt).Val;
2030 return DAG.getNode(ISD::ROTR, VT, LHSShiftArg, RHSShiftAmt).Val;
2035 // Look for sign/zext/any-extended cases:
2036 if ((LHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND
2037 || LHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND
2038 || LHSShiftAmt.getOpcode() == ISD::ANY_EXTEND) &&
2039 (RHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND
2040 || RHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND
2041 || RHSShiftAmt.getOpcode() == ISD::ANY_EXTEND)) {
2042 SDOperand LExtOp0 = LHSShiftAmt.getOperand(0);
2043 SDOperand RExtOp0 = RHSShiftAmt.getOperand(0);
2044 if (RExtOp0.getOpcode() == ISD::SUB &&
2045 RExtOp0.getOperand(1) == LExtOp0) {
2046 // fold (or (shl x, (*ext y)), (srl x, (*ext (sub 32, y)))) ->
2048 // fold (or (shl x, (*ext y)), (srl x, (*ext (sub 32, y)))) ->
2049 // (rotl x, (sub 32, y))
2050 if (ConstantSDNode *SUBC = cast<ConstantSDNode>(RExtOp0.getOperand(0))) {
2051 if (SUBC->getValue() == OpSizeInBits) {
2053 return DAG.getNode(ISD::ROTL, VT, LHSShiftArg, LHSShiftAmt).Val;
2055 return DAG.getNode(ISD::ROTR, VT, LHSShiftArg, RHSShiftAmt).Val;
2058 } else if (LExtOp0.getOpcode() == ISD::SUB &&
2059 RExtOp0 == LExtOp0.getOperand(1)) {
2060 // fold (or (shl x, (*ext (sub 32, y))), (srl x, (*ext r))) ->
2062 // fold (or (shl x, (*ext (sub 32, y))), (srl x, (*ext r))) ->
2063 // (rotr x, (sub 32, y))
2064 if (ConstantSDNode *SUBC = cast<ConstantSDNode>(LExtOp0.getOperand(0))) {
2065 if (SUBC->getValue() == OpSizeInBits) {
2067 return DAG.getNode(ISD::ROTL, VT, LHSShiftArg, RHSShiftAmt).Val;
2069 return DAG.getNode(ISD::ROTL, VT, LHSShiftArg, LHSShiftAmt).Val;
2079 SDOperand DAGCombiner::visitXOR(SDNode *N) {
2080 SDOperand N0 = N->getOperand(0);
2081 SDOperand N1 = N->getOperand(1);
2082 SDOperand LHS, RHS, CC;
2083 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
2084 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2085 MVT::ValueType VT = N0.getValueType();
2088 if (MVT::isVector(VT)) {
2089 SDOperand FoldedVOp = SimplifyVBinOp(N);
2090 if (FoldedVOp.Val) return FoldedVOp;
2093 // fold (xor x, undef) -> undef
2094 if (N0.getOpcode() == ISD::UNDEF)
2096 if (N1.getOpcode() == ISD::UNDEF)
2098 // fold (xor c1, c2) -> c1^c2
2100 return DAG.getNode(ISD::XOR, VT, N0, N1);
2101 // canonicalize constant to RHS
2103 return DAG.getNode(ISD::XOR, VT, N1, N0);
2104 // fold (xor x, 0) -> x
2105 if (N1C && N1C->isNullValue())
2108 SDOperand RXOR = ReassociateOps(ISD::XOR, N0, N1);
2111 // fold !(x cc y) -> (x !cc y)
2112 if (N1C && N1C->getValue() == 1 && isSetCCEquivalent(N0, LHS, RHS, CC)) {
2113 bool isInt = MVT::isInteger(LHS.getValueType());
2114 ISD::CondCode NotCC = ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(),
2116 if (N0.getOpcode() == ISD::SETCC)
2117 return DAG.getSetCC(VT, LHS, RHS, NotCC);
2118 if (N0.getOpcode() == ISD::SELECT_CC)
2119 return DAG.getSelectCC(LHS, RHS, N0.getOperand(2),N0.getOperand(3),NotCC);
2120 assert(0 && "Unhandled SetCC Equivalent!");
2123 // fold (not (zext (setcc x, y))) -> (zext (not (setcc x, y)))
2124 if (N1C && N1C->getValue() == 1 && N0.getOpcode() == ISD::ZERO_EXTEND &&
2125 N0.Val->hasOneUse() && isSetCCEquivalent(N0.getOperand(0), LHS, RHS, CC)){
2126 SDOperand V = N0.getOperand(0);
2127 V = DAG.getNode(ISD::XOR, V.getValueType(), V,
2128 DAG.getConstant(1, V.getValueType()));
2129 AddToWorkList(V.Val);
2130 return DAG.getNode(ISD::ZERO_EXTEND, VT, V);
2133 // fold !(x or y) -> (!x and !y) iff x or y are setcc
2134 if (N1C && N1C->getValue() == 1 && VT == MVT::i1 &&
2135 (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
2136 SDOperand LHS = N0.getOperand(0), RHS = N0.getOperand(1);
2137 if (isOneUseSetCC(RHS) || isOneUseSetCC(LHS)) {
2138 unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
2139 LHS = DAG.getNode(ISD::XOR, VT, LHS, N1); // RHS = ~LHS
2140 RHS = DAG.getNode(ISD::XOR, VT, RHS, N1); // RHS = ~RHS
2141 AddToWorkList(LHS.Val); AddToWorkList(RHS.Val);
2142 return DAG.getNode(NewOpcode, VT, LHS, RHS);
2145 // fold !(x or y) -> (!x and !y) iff x or y are constants
2146 if (N1C && N1C->isAllOnesValue() &&
2147 (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
2148 SDOperand LHS = N0.getOperand(0), RHS = N0.getOperand(1);
2149 if (isa<ConstantSDNode>(RHS) || isa<ConstantSDNode>(LHS)) {
2150 unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
2151 LHS = DAG.getNode(ISD::XOR, VT, LHS, N1); // RHS = ~LHS
2152 RHS = DAG.getNode(ISD::XOR, VT, RHS, N1); // RHS = ~RHS
2153 AddToWorkList(LHS.Val); AddToWorkList(RHS.Val);
2154 return DAG.getNode(NewOpcode, VT, LHS, RHS);
2157 // fold (xor (xor x, c1), c2) -> (xor x, c1^c2)
2158 if (N1C && N0.getOpcode() == ISD::XOR) {
2159 ConstantSDNode *N00C = dyn_cast<ConstantSDNode>(N0.getOperand(0));
2160 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
2162 return DAG.getNode(ISD::XOR, VT, N0.getOperand(1),
2163 DAG.getConstant(N1C->getValue()^N00C->getValue(), VT));
2165 return DAG.getNode(ISD::XOR, VT, N0.getOperand(0),
2166 DAG.getConstant(N1C->getValue()^N01C->getValue(), VT));
2168 // fold (xor x, x) -> 0
2170 if (!MVT::isVector(VT)) {
2171 return DAG.getConstant(0, VT);
2172 } else if (!AfterLegalize || TLI.isOperationLegal(ISD::BUILD_VECTOR, VT)) {
2173 // Produce a vector of zeros.
2174 SDOperand El = DAG.getConstant(0, MVT::getVectorElementType(VT));
2175 std::vector<SDOperand> Ops(MVT::getVectorNumElements(VT), El);
2176 return DAG.getNode(ISD::BUILD_VECTOR, VT, &Ops[0], Ops.size());
2180 // Simplify: xor (op x...), (op y...) -> (op (xor x, y))
2181 if (N0.getOpcode() == N1.getOpcode()) {
2182 SDOperand Tmp = SimplifyBinOpWithSameOpcodeHands(N);
2183 if (Tmp.Val) return Tmp;
2186 // Simplify the expression using non-local knowledge.
2187 if (!MVT::isVector(VT) &&
2188 SimplifyDemandedBits(SDOperand(N, 0)))
2189 return SDOperand(N, 0);
2194 /// visitShiftByConstant - Handle transforms common to the three shifts, when
2195 /// the shift amount is a constant.
2196 SDOperand DAGCombiner::visitShiftByConstant(SDNode *N, unsigned Amt) {
2197 SDNode *LHS = N->getOperand(0).Val;
2198 if (!LHS->hasOneUse()) return SDOperand();
2200 // We want to pull some binops through shifts, so that we have (and (shift))
2201 // instead of (shift (and)), likewise for add, or, xor, etc. This sort of
2202 // thing happens with address calculations, so it's important to canonicalize
2204 bool HighBitSet = false; // Can we transform this if the high bit is set?
2206 switch (LHS->getOpcode()) {
2207 default: return SDOperand();
2210 HighBitSet = false; // We can only transform sra if the high bit is clear.
2213 HighBitSet = true; // We can only transform sra if the high bit is set.
2216 if (N->getOpcode() != ISD::SHL)
2217 return SDOperand(); // only shl(add) not sr[al](add).
2218 HighBitSet = false; // We can only transform sra if the high bit is clear.
2222 // We require the RHS of the binop to be a constant as well.
2223 ConstantSDNode *BinOpCst = dyn_cast<ConstantSDNode>(LHS->getOperand(1));
2224 if (!BinOpCst) return SDOperand();
2227 // FIXME: disable this for unless the input to the binop is a shift by a
2228 // constant. If it is not a shift, it pessimizes some common cases like:
2230 //void foo(int *X, int i) { X[i & 1235] = 1; }
2231 //int bar(int *X, int i) { return X[i & 255]; }
2232 SDNode *BinOpLHSVal = LHS->getOperand(0).Val;
2233 if ((BinOpLHSVal->getOpcode() != ISD::SHL &&
2234 BinOpLHSVal->getOpcode() != ISD::SRA &&
2235 BinOpLHSVal->getOpcode() != ISD::SRL) ||
2236 !isa<ConstantSDNode>(BinOpLHSVal->getOperand(1)))
2239 MVT::ValueType VT = N->getValueType(0);
2241 // If this is a signed shift right, and the high bit is modified
2242 // by the logical operation, do not perform the transformation.
2243 // The highBitSet boolean indicates the value of the high bit of
2244 // the constant which would cause it to be modified for this
2246 if (N->getOpcode() == ISD::SRA) {
2247 uint64_t BinOpRHSSign = BinOpCst->getValue() >> (MVT::getSizeInBits(VT)-1);
2248 if ((bool)BinOpRHSSign != HighBitSet)
2252 // Fold the constants, shifting the binop RHS by the shift amount.
2253 SDOperand NewRHS = DAG.getNode(N->getOpcode(), N->getValueType(0),
2254 LHS->getOperand(1), N->getOperand(1));
2256 // Create the new shift.
2257 SDOperand NewShift = DAG.getNode(N->getOpcode(), VT, LHS->getOperand(0),
2260 // Create the new binop.
2261 return DAG.getNode(LHS->getOpcode(), VT, NewShift, NewRHS);
2265 SDOperand DAGCombiner::visitSHL(SDNode *N) {
2266 SDOperand N0 = N->getOperand(0);
2267 SDOperand N1 = N->getOperand(1);
2268 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
2269 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2270 MVT::ValueType VT = N0.getValueType();
2271 unsigned OpSizeInBits = MVT::getSizeInBits(VT);
2273 // fold (shl c1, c2) -> c1<<c2
2275 return DAG.getNode(ISD::SHL, VT, N0, N1);
2276 // fold (shl 0, x) -> 0
2277 if (N0C && N0C->isNullValue())
2279 // fold (shl x, c >= size(x)) -> undef
2280 if (N1C && N1C->getValue() >= OpSizeInBits)
2281 return DAG.getNode(ISD::UNDEF, VT);
2282 // fold (shl x, 0) -> x
2283 if (N1C && N1C->isNullValue())
2285 // if (shl x, c) is known to be zero, return 0
2286 if (DAG.MaskedValueIsZero(SDOperand(N, 0),
2287 APInt::getAllOnesValue(MVT::getSizeInBits(VT))))
2288 return DAG.getConstant(0, VT);
2289 if (N1C && SimplifyDemandedBits(SDOperand(N, 0)))
2290 return SDOperand(N, 0);
2291 // fold (shl (shl x, c1), c2) -> 0 or (shl x, c1+c2)
2292 if (N1C && N0.getOpcode() == ISD::SHL &&
2293 N0.getOperand(1).getOpcode() == ISD::Constant) {
2294 uint64_t c1 = cast<ConstantSDNode>(N0.getOperand(1))->getValue();
2295 uint64_t c2 = N1C->getValue();
2296 if (c1 + c2 > OpSizeInBits)
2297 return DAG.getConstant(0, VT);
2298 return DAG.getNode(ISD::SHL, VT, N0.getOperand(0),
2299 DAG.getConstant(c1 + c2, N1.getValueType()));
2301 // fold (shl (srl x, c1), c2) -> (shl (and x, -1 << c1), c2-c1) or
2302 // (srl (and x, -1 << c1), c1-c2)
2303 if (N1C && N0.getOpcode() == ISD::SRL &&
2304 N0.getOperand(1).getOpcode() == ISD::Constant) {
2305 uint64_t c1 = cast<ConstantSDNode>(N0.getOperand(1))->getValue();
2306 uint64_t c2 = N1C->getValue();
2307 SDOperand Mask = DAG.getNode(ISD::AND, VT, N0.getOperand(0),
2308 DAG.getConstant(~0ULL << c1, VT));
2310 return DAG.getNode(ISD::SHL, VT, Mask,
2311 DAG.getConstant(c2-c1, N1.getValueType()));
2313 return DAG.getNode(ISD::SRL, VT, Mask,
2314 DAG.getConstant(c1-c2, N1.getValueType()));
2316 // fold (shl (sra x, c1), c1) -> (and x, -1 << c1)
2317 if (N1C && N0.getOpcode() == ISD::SRA && N1 == N0.getOperand(1))
2318 return DAG.getNode(ISD::AND, VT, N0.getOperand(0),
2319 DAG.getConstant(~0ULL << N1C->getValue(), VT));
2321 return N1C ? visitShiftByConstant(N, N1C->getValue()) : SDOperand();
2324 SDOperand DAGCombiner::visitSRA(SDNode *N) {
2325 SDOperand N0 = N->getOperand(0);
2326 SDOperand N1 = N->getOperand(1);
2327 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
2328 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2329 MVT::ValueType VT = N0.getValueType();
2331 // fold (sra c1, c2) -> c1>>c2
2333 return DAG.getNode(ISD::SRA, VT, N0, N1);
2334 // fold (sra 0, x) -> 0
2335 if (N0C && N0C->isNullValue())
2337 // fold (sra -1, x) -> -1
2338 if (N0C && N0C->isAllOnesValue())
2340 // fold (sra x, c >= size(x)) -> undef
2341 if (N1C && N1C->getValue() >= MVT::getSizeInBits(VT))
2342 return DAG.getNode(ISD::UNDEF, VT);
2343 // fold (sra x, 0) -> x
2344 if (N1C && N1C->isNullValue())
2346 // fold (sra (shl x, c1), c1) -> sext_inreg for some c1 and target supports
2348 if (N1C && N0.getOpcode() == ISD::SHL && N1 == N0.getOperand(1)) {
2349 unsigned LowBits = MVT::getSizeInBits(VT) - (unsigned)N1C->getValue();
2352 default: EVT = MVT::Other; break;
2353 case 1: EVT = MVT::i1; break;
2354 case 8: EVT = MVT::i8; break;
2355 case 16: EVT = MVT::i16; break;
2356 case 32: EVT = MVT::i32; break;
2358 if (EVT > MVT::Other && TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, EVT))
2359 return DAG.getNode(ISD::SIGN_EXTEND_INREG, VT, N0.getOperand(0),
2360 DAG.getValueType(EVT));
2363 // fold (sra (sra x, c1), c2) -> (sra x, c1+c2)
2364 if (N1C && N0.getOpcode() == ISD::SRA) {
2365 if (ConstantSDNode *C1 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
2366 unsigned Sum = N1C->getValue() + C1->getValue();
2367 if (Sum >= MVT::getSizeInBits(VT)) Sum = MVT::getSizeInBits(VT)-1;
2368 return DAG.getNode(ISD::SRA, VT, N0.getOperand(0),
2369 DAG.getConstant(Sum, N1C->getValueType(0)));
2373 // Simplify, based on bits shifted out of the LHS.
2374 if (N1C && SimplifyDemandedBits(SDOperand(N, 0)))
2375 return SDOperand(N, 0);
2378 // If the sign bit is known to be zero, switch this to a SRL.
2379 if (DAG.SignBitIsZero(N0))
2380 return DAG.getNode(ISD::SRL, VT, N0, N1);
2382 return N1C ? visitShiftByConstant(N, N1C->getValue()) : SDOperand();
2385 SDOperand DAGCombiner::visitSRL(SDNode *N) {
2386 SDOperand N0 = N->getOperand(0);
2387 SDOperand N1 = N->getOperand(1);
2388 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
2389 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2390 MVT::ValueType VT = N0.getValueType();
2391 unsigned OpSizeInBits = MVT::getSizeInBits(VT);
2393 // fold (srl c1, c2) -> c1 >>u c2
2395 return DAG.getNode(ISD::SRL, VT, N0, N1);
2396 // fold (srl 0, x) -> 0
2397 if (N0C && N0C->isNullValue())
2399 // fold (srl x, c >= size(x)) -> undef
2400 if (N1C && N1C->getValue() >= OpSizeInBits)
2401 return DAG.getNode(ISD::UNDEF, VT);
2402 // fold (srl x, 0) -> x
2403 if (N1C && N1C->isNullValue())
2405 // if (srl x, c) is known to be zero, return 0
2406 if (N1C && DAG.MaskedValueIsZero(SDOperand(N, 0),
2407 APInt::getAllOnesValue(OpSizeInBits)))
2408 return DAG.getConstant(0, VT);
2410 // fold (srl (srl x, c1), c2) -> 0 or (srl x, c1+c2)
2411 if (N1C && N0.getOpcode() == ISD::SRL &&
2412 N0.getOperand(1).getOpcode() == ISD::Constant) {
2413 uint64_t c1 = cast<ConstantSDNode>(N0.getOperand(1))->getValue();
2414 uint64_t c2 = N1C->getValue();
2415 if (c1 + c2 > OpSizeInBits)
2416 return DAG.getConstant(0, VT);
2417 return DAG.getNode(ISD::SRL, VT, N0.getOperand(0),
2418 DAG.getConstant(c1 + c2, N1.getValueType()));
2421 // fold (srl (anyextend x), c) -> (anyextend (srl x, c))
2422 if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
2423 // Shifting in all undef bits?
2424 MVT::ValueType SmallVT = N0.getOperand(0).getValueType();
2425 if (N1C->getValue() >= MVT::getSizeInBits(SmallVT))
2426 return DAG.getNode(ISD::UNDEF, VT);
2428 SDOperand SmallShift = DAG.getNode(ISD::SRL, SmallVT, N0.getOperand(0), N1);
2429 AddToWorkList(SmallShift.Val);
2430 return DAG.getNode(ISD::ANY_EXTEND, VT, SmallShift);
2433 // fold (srl (sra X, Y), 31) -> (srl X, 31). This srl only looks at the sign
2434 // bit, which is unmodified by sra.
2435 if (N1C && N1C->getValue()+1 == MVT::getSizeInBits(VT)) {
2436 if (N0.getOpcode() == ISD::SRA)
2437 return DAG.getNode(ISD::SRL, VT, N0.getOperand(0), N1);
2440 // fold (srl (ctlz x), "5") -> x iff x has one bit set (the low bit).
2441 if (N1C && N0.getOpcode() == ISD::CTLZ &&
2442 N1C->getValue() == Log2_32(MVT::getSizeInBits(VT))) {
2443 APInt KnownZero, KnownOne;
2444 APInt Mask = APInt::getAllOnesValue(MVT::getSizeInBits(VT));
2445 DAG.ComputeMaskedBits(N0.getOperand(0), Mask, KnownZero, KnownOne);
2447 // If any of the input bits are KnownOne, then the input couldn't be all
2448 // zeros, thus the result of the srl will always be zero.
2449 if (KnownOne.getBoolValue()) return DAG.getConstant(0, VT);
2451 // If all of the bits input the to ctlz node are known to be zero, then
2452 // the result of the ctlz is "32" and the result of the shift is one.
2453 APInt UnknownBits = ~KnownZero & Mask;
2454 if (UnknownBits == 0) return DAG.getConstant(1, VT);
2456 // Otherwise, check to see if there is exactly one bit input to the ctlz.
2457 if ((UnknownBits & (UnknownBits-1)) == 0) {
2458 // Okay, we know that only that the single bit specified by UnknownBits
2459 // could be set on input to the CTLZ node. If this bit is set, the SRL
2460 // will return 0, if it is clear, it returns 1. Change the CTLZ/SRL pair
2461 // to an SRL,XOR pair, which is likely to simplify more.
2462 unsigned ShAmt = UnknownBits.countTrailingZeros();
2463 SDOperand Op = N0.getOperand(0);
2465 Op = DAG.getNode(ISD::SRL, VT, Op,
2466 DAG.getConstant(ShAmt, TLI.getShiftAmountTy()));
2467 AddToWorkList(Op.Val);
2469 return DAG.getNode(ISD::XOR, VT, Op, DAG.getConstant(1, VT));
2473 // fold operands of srl based on knowledge that the low bits are not
2475 if (N1C && SimplifyDemandedBits(SDOperand(N, 0)))
2476 return SDOperand(N, 0);
2478 return N1C ? visitShiftByConstant(N, N1C->getValue()) : SDOperand();
2481 SDOperand DAGCombiner::visitCTLZ(SDNode *N) {
2482 SDOperand N0 = N->getOperand(0);
2483 MVT::ValueType VT = N->getValueType(0);
2485 // fold (ctlz c1) -> c2
2486 if (isa<ConstantSDNode>(N0))
2487 return DAG.getNode(ISD::CTLZ, VT, N0);
2491 SDOperand DAGCombiner::visitCTTZ(SDNode *N) {
2492 SDOperand N0 = N->getOperand(0);
2493 MVT::ValueType VT = N->getValueType(0);
2495 // fold (cttz c1) -> c2
2496 if (isa<ConstantSDNode>(N0))
2497 return DAG.getNode(ISD::CTTZ, VT, N0);
2501 SDOperand DAGCombiner::visitCTPOP(SDNode *N) {
2502 SDOperand N0 = N->getOperand(0);
2503 MVT::ValueType VT = N->getValueType(0);
2505 // fold (ctpop c1) -> c2
2506 if (isa<ConstantSDNode>(N0))
2507 return DAG.getNode(ISD::CTPOP, VT, N0);
2511 SDOperand DAGCombiner::visitSELECT(SDNode *N) {
2512 SDOperand N0 = N->getOperand(0);
2513 SDOperand N1 = N->getOperand(1);
2514 SDOperand N2 = N->getOperand(2);
2515 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
2516 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2517 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2);
2518 MVT::ValueType VT = N->getValueType(0);
2519 MVT::ValueType VT0 = N0.getValueType();
2521 // fold select C, X, X -> X
2524 // fold select true, X, Y -> X
2525 if (N0C && !N0C->isNullValue())
2527 // fold select false, X, Y -> Y
2528 if (N0C && N0C->isNullValue())
2530 // fold select C, 1, X -> C | X
2531 if (MVT::i1 == VT && N1C && N1C->getValue() == 1)
2532 return DAG.getNode(ISD::OR, VT, N0, N2);
2533 // fold select C, 0, 1 -> ~C
2534 if (MVT::isInteger(VT) && MVT::isInteger(VT0) &&
2535 N1C && N2C && N1C->isNullValue() && N2C->getValue() == 1) {
2536 SDOperand XORNode = DAG.getNode(ISD::XOR, VT0, N0, DAG.getConstant(1, VT0));
2539 AddToWorkList(XORNode.Val);
2540 if (MVT::getSizeInBits(VT) > MVT::getSizeInBits(VT0))
2541 return DAG.getNode(ISD::ZERO_EXTEND, VT, XORNode);
2542 return DAG.getNode(ISD::TRUNCATE, VT, XORNode);
2544 // fold select C, 0, X -> ~C & X
2545 if (VT == VT0 && VT == MVT::i1 && N1C && N1C->isNullValue()) {
2546 SDOperand XORNode = DAG.getNode(ISD::XOR, VT, N0, DAG.getConstant(1, VT));
2547 AddToWorkList(XORNode.Val);
2548 return DAG.getNode(ISD::AND, VT, XORNode, N2);
2550 // fold select C, X, 1 -> ~C | X
2551 if (VT == VT0 && VT == MVT::i1 && N2C && N2C->getValue() == 1) {
2552 SDOperand XORNode = DAG.getNode(ISD::XOR, VT, N0, DAG.getConstant(1, VT));
2553 AddToWorkList(XORNode.Val);
2554 return DAG.getNode(ISD::OR, VT, XORNode, N1);
2556 // fold select C, X, 0 -> C & X
2557 // FIXME: this should check for C type == X type, not i1?
2558 if (MVT::i1 == VT && N2C && N2C->isNullValue())
2559 return DAG.getNode(ISD::AND, VT, N0, N1);
2560 // fold X ? X : Y --> X ? 1 : Y --> X | Y
2561 if (MVT::i1 == VT && N0 == N1)
2562 return DAG.getNode(ISD::OR, VT, N0, N2);
2563 // fold X ? Y : X --> X ? Y : 0 --> X & Y
2564 if (MVT::i1 == VT && N0 == N2)
2565 return DAG.getNode(ISD::AND, VT, N0, N1);
2567 // If we can fold this based on the true/false value, do so.
2568 if (SimplifySelectOps(N, N1, N2))
2569 return SDOperand(N, 0); // Don't revisit N.
2571 // fold selects based on a setcc into other things, such as min/max/abs
2572 if (N0.getOpcode() == ISD::SETCC) {
2574 // Check against MVT::Other for SELECT_CC, which is a workaround for targets
2575 // having to say they don't support SELECT_CC on every type the DAG knows
2576 // about, since there is no way to mark an opcode illegal at all value types
2577 if (TLI.isOperationLegal(ISD::SELECT_CC, MVT::Other))
2578 return DAG.getNode(ISD::SELECT_CC, VT, N0.getOperand(0), N0.getOperand(1),
2579 N1, N2, N0.getOperand(2));
2581 return SimplifySelect(N0, N1, N2);
2586 SDOperand DAGCombiner::visitSELECT_CC(SDNode *N) {
2587 SDOperand N0 = N->getOperand(0);
2588 SDOperand N1 = N->getOperand(1);
2589 SDOperand N2 = N->getOperand(2);
2590 SDOperand N3 = N->getOperand(3);
2591 SDOperand N4 = N->getOperand(4);
2592 ISD::CondCode CC = cast<CondCodeSDNode>(N4)->get();
2594 // fold select_cc lhs, rhs, x, x, cc -> x
2598 // Determine if the condition we're dealing with is constant
2599 SDOperand SCC = SimplifySetCC(TLI.getSetCCResultTy(), N0, N1, CC, false);
2600 if (SCC.Val) AddToWorkList(SCC.Val);
2602 if (ConstantSDNode *SCCC = dyn_cast_or_null<ConstantSDNode>(SCC.Val)) {
2603 if (SCCC->getValue())
2604 return N2; // cond always true -> true val
2606 return N3; // cond always false -> false val
2609 // Fold to a simpler select_cc
2610 if (SCC.Val && SCC.getOpcode() == ISD::SETCC)
2611 return DAG.getNode(ISD::SELECT_CC, N2.getValueType(),
2612 SCC.getOperand(0), SCC.getOperand(1), N2, N3,
2615 // If we can fold this based on the true/false value, do so.
2616 if (SimplifySelectOps(N, N2, N3))
2617 return SDOperand(N, 0); // Don't revisit N.
2619 // fold select_cc into other things, such as min/max/abs
2620 return SimplifySelectCC(N0, N1, N2, N3, CC);
2623 SDOperand DAGCombiner::visitSETCC(SDNode *N) {
2624 return SimplifySetCC(N->getValueType(0), N->getOperand(0), N->getOperand(1),
2625 cast<CondCodeSDNode>(N->getOperand(2))->get());
2628 // ExtendUsesToFormExtLoad - Trying to extend uses of a load to enable this:
2629 // "fold ({s|z}ext (load x)) -> ({s|z}ext (truncate ({s|z}extload x)))"
2630 // transformation. Returns true if extension are possible and the above
2631 // mentioned transformation is profitable.
2632 static bool ExtendUsesToFormExtLoad(SDNode *N, SDOperand N0,
2634 SmallVector<SDNode*, 4> &ExtendNodes,
2635 TargetLowering &TLI) {
2636 bool HasCopyToRegUses = false;
2637 bool isTruncFree = TLI.isTruncateFree(N->getValueType(0), N0.getValueType());
2638 for (SDNode::use_iterator UI = N0.Val->use_begin(), UE = N0.Val->use_end();
2643 // FIXME: Only extend SETCC N, N and SETCC N, c for now.
2644 if (User->getOpcode() == ISD::SETCC) {
2645 ISD::CondCode CC = cast<CondCodeSDNode>(User->getOperand(2))->get();
2646 if (ExtOpc == ISD::ZERO_EXTEND && ISD::isSignedIntSetCC(CC))
2647 // Sign bits will be lost after a zext.
2650 for (unsigned i = 0; i != 2; ++i) {
2651 SDOperand UseOp = User->getOperand(i);
2654 if (!isa<ConstantSDNode>(UseOp))
2659 ExtendNodes.push_back(User);
2661 for (unsigned i = 0, e = User->getNumOperands(); i != e; ++i) {
2662 SDOperand UseOp = User->getOperand(i);
2664 // If truncate from extended type to original load type is free
2665 // on this target, then it's ok to extend a CopyToReg.
2666 if (isTruncFree && User->getOpcode() == ISD::CopyToReg)
2667 HasCopyToRegUses = true;
2675 if (HasCopyToRegUses) {
2676 bool BothLiveOut = false;
2677 for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
2680 for (unsigned i = 0, e = User->getNumOperands(); i != e; ++i) {
2681 SDOperand UseOp = User->getOperand(i);
2682 if (UseOp.Val == N && UseOp.ResNo == 0) {
2689 // Both unextended and extended values are live out. There had better be
2690 // good a reason for the transformation.
2691 return ExtendNodes.size();
2696 SDOperand DAGCombiner::visitSIGN_EXTEND(SDNode *N) {
2697 SDOperand N0 = N->getOperand(0);
2698 MVT::ValueType VT = N->getValueType(0);
2700 // fold (sext c1) -> c1
2701 if (isa<ConstantSDNode>(N0))
2702 return DAG.getNode(ISD::SIGN_EXTEND, VT, N0);
2704 // fold (sext (sext x)) -> (sext x)
2705 // fold (sext (aext x)) -> (sext x)
2706 if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
2707 return DAG.getNode(ISD::SIGN_EXTEND, VT, N0.getOperand(0));
2709 // fold (sext (truncate (load x))) -> (sext (smaller load x))
2710 // fold (sext (truncate (srl (load x), c))) -> (sext (smaller load (x+c/n)))
2711 if (N0.getOpcode() == ISD::TRUNCATE) {
2712 SDOperand NarrowLoad = ReduceLoadWidth(N0.Val);
2713 if (NarrowLoad.Val) {
2714 if (NarrowLoad.Val != N0.Val)
2715 CombineTo(N0.Val, NarrowLoad);
2716 return DAG.getNode(ISD::SIGN_EXTEND, VT, NarrowLoad);
2720 // See if the value being truncated is already sign extended. If so, just
2721 // eliminate the trunc/sext pair.
2722 if (N0.getOpcode() == ISD::TRUNCATE) {
2723 SDOperand Op = N0.getOperand(0);
2724 unsigned OpBits = MVT::getSizeInBits(Op.getValueType());
2725 unsigned MidBits = MVT::getSizeInBits(N0.getValueType());
2726 unsigned DestBits = MVT::getSizeInBits(VT);
2727 unsigned NumSignBits = DAG.ComputeNumSignBits(Op);
2729 if (OpBits == DestBits) {
2730 // Op is i32, Mid is i8, and Dest is i32. If Op has more than 24 sign
2731 // bits, it is already ready.
2732 if (NumSignBits > DestBits-MidBits)
2734 } else if (OpBits < DestBits) {
2735 // Op is i32, Mid is i8, and Dest is i64. If Op has more than 24 sign
2736 // bits, just sext from i32.
2737 if (NumSignBits > OpBits-MidBits)
2738 return DAG.getNode(ISD::SIGN_EXTEND, VT, Op);
2740 // Op is i64, Mid is i8, and Dest is i32. If Op has more than 56 sign
2741 // bits, just truncate to i32.
2742 if (NumSignBits > OpBits-MidBits)
2743 return DAG.getNode(ISD::TRUNCATE, VT, Op);
2746 // fold (sext (truncate x)) -> (sextinreg x).
2747 if (!AfterLegalize || TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG,
2748 N0.getValueType())) {
2749 if (Op.getValueType() < VT)
2750 Op = DAG.getNode(ISD::ANY_EXTEND, VT, Op);
2751 else if (Op.getValueType() > VT)
2752 Op = DAG.getNode(ISD::TRUNCATE, VT, Op);
2753 return DAG.getNode(ISD::SIGN_EXTEND_INREG, VT, Op,
2754 DAG.getValueType(N0.getValueType()));
2758 // fold (sext (load x)) -> (sext (truncate (sextload x)))
2759 if (ISD::isNON_EXTLoad(N0.Val) &&
2760 (!AfterLegalize||TLI.isLoadXLegal(ISD::SEXTLOAD, N0.getValueType()))){
2761 bool DoXform = true;
2762 SmallVector<SDNode*, 4> SetCCs;
2763 if (!N0.hasOneUse())
2764 DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::SIGN_EXTEND, SetCCs, TLI);
2766 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
2767 SDOperand ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, VT, LN0->getChain(),
2768 LN0->getBasePtr(), LN0->getSrcValue(),
2769 LN0->getSrcValueOffset(),
2772 LN0->getAlignment());
2773 CombineTo(N, ExtLoad);
2774 SDOperand Trunc = DAG.getNode(ISD::TRUNCATE, N0.getValueType(), ExtLoad);
2775 CombineTo(N0.Val, Trunc, ExtLoad.getValue(1));
2776 // Extend SetCC uses if necessary.
2777 for (unsigned i = 0, e = SetCCs.size(); i != e; ++i) {
2778 SDNode *SetCC = SetCCs[i];
2779 SmallVector<SDOperand, 4> Ops;
2780 for (unsigned j = 0; j != 2; ++j) {
2781 SDOperand SOp = SetCC->getOperand(j);
2783 Ops.push_back(ExtLoad);
2785 Ops.push_back(DAG.getNode(ISD::SIGN_EXTEND, VT, SOp));
2787 Ops.push_back(SetCC->getOperand(2));
2788 CombineTo(SetCC, DAG.getNode(ISD::SETCC, SetCC->getValueType(0),
2789 &Ops[0], Ops.size()));
2791 return SDOperand(N, 0); // Return N so it doesn't get rechecked!
2795 // fold (sext (sextload x)) -> (sext (truncate (sextload x)))
2796 // fold (sext ( extload x)) -> (sext (truncate (sextload x)))
2797 if ((ISD::isSEXTLoad(N0.Val) || ISD::isEXTLoad(N0.Val)) &&
2798 ISD::isUNINDEXEDLoad(N0.Val) && N0.hasOneUse()) {
2799 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
2800 MVT::ValueType EVT = LN0->getMemoryVT();
2801 if (!AfterLegalize || TLI.isLoadXLegal(ISD::SEXTLOAD, EVT)) {
2802 SDOperand ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, VT, LN0->getChain(),
2803 LN0->getBasePtr(), LN0->getSrcValue(),
2804 LN0->getSrcValueOffset(), EVT,
2806 LN0->getAlignment());
2807 CombineTo(N, ExtLoad);
2808 CombineTo(N0.Val, DAG.getNode(ISD::TRUNCATE, N0.getValueType(), ExtLoad),
2809 ExtLoad.getValue(1));
2810 return SDOperand(N, 0); // Return N so it doesn't get rechecked!
2814 // sext(setcc x,y,cc) -> select_cc x, y, -1, 0, cc
2815 if (N0.getOpcode() == ISD::SETCC) {
2817 SimplifySelectCC(N0.getOperand(0), N0.getOperand(1),
2818 DAG.getConstant(~0ULL, VT), DAG.getConstant(0, VT),
2819 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
2820 if (SCC.Val) return SCC;
2826 SDOperand DAGCombiner::visitZERO_EXTEND(SDNode *N) {
2827 SDOperand N0 = N->getOperand(0);
2828 MVT::ValueType VT = N->getValueType(0);
2830 // fold (zext c1) -> c1
2831 if (isa<ConstantSDNode>(N0))
2832 return DAG.getNode(ISD::ZERO_EXTEND, VT, N0);
2833 // fold (zext (zext x)) -> (zext x)
2834 // fold (zext (aext x)) -> (zext x)
2835 if (N0.getOpcode() == ISD::ZERO_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
2836 return DAG.getNode(ISD::ZERO_EXTEND, VT, N0.getOperand(0));
2838 // fold (zext (truncate (load x))) -> (zext (smaller load x))
2839 // fold (zext (truncate (srl (load x), c))) -> (zext (small load (x+c/n)))
2840 if (N0.getOpcode() == ISD::TRUNCATE) {
2841 SDOperand NarrowLoad = ReduceLoadWidth(N0.Val);
2842 if (NarrowLoad.Val) {
2843 if (NarrowLoad.Val != N0.Val)
2844 CombineTo(N0.Val, NarrowLoad);
2845 return DAG.getNode(ISD::ZERO_EXTEND, VT, NarrowLoad);
2849 // fold (zext (truncate x)) -> (and x, mask)
2850 if (N0.getOpcode() == ISD::TRUNCATE &&
2851 (!AfterLegalize || TLI.isOperationLegal(ISD::AND, VT))) {
2852 SDOperand Op = N0.getOperand(0);
2853 if (Op.getValueType() < VT) {
2854 Op = DAG.getNode(ISD::ANY_EXTEND, VT, Op);
2855 } else if (Op.getValueType() > VT) {
2856 Op = DAG.getNode(ISD::TRUNCATE, VT, Op);
2858 return DAG.getZeroExtendInReg(Op, N0.getValueType());
2861 // fold (zext (and (trunc x), cst)) -> (and x, cst).
2862 if (N0.getOpcode() == ISD::AND &&
2863 N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
2864 N0.getOperand(1).getOpcode() == ISD::Constant) {
2865 SDOperand X = N0.getOperand(0).getOperand(0);
2866 if (X.getValueType() < VT) {
2867 X = DAG.getNode(ISD::ANY_EXTEND, VT, X);
2868 } else if (X.getValueType() > VT) {
2869 X = DAG.getNode(ISD::TRUNCATE, VT, X);
2871 uint64_t Mask = cast<ConstantSDNode>(N0.getOperand(1))->getValue();
2872 return DAG.getNode(ISD::AND, VT, X, DAG.getConstant(Mask, VT));
2875 // fold (zext (load x)) -> (zext (truncate (zextload x)))
2876 if (ISD::isNON_EXTLoad(N0.Val) &&
2877 (!AfterLegalize||TLI.isLoadXLegal(ISD::ZEXTLOAD, N0.getValueType()))) {
2878 bool DoXform = true;
2879 SmallVector<SDNode*, 4> SetCCs;
2880 if (!N0.hasOneUse())
2881 DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ZERO_EXTEND, SetCCs, TLI);
2883 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
2884 SDOperand ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, VT, LN0->getChain(),
2885 LN0->getBasePtr(), LN0->getSrcValue(),
2886 LN0->getSrcValueOffset(),
2889 LN0->getAlignment());
2890 CombineTo(N, ExtLoad);
2891 SDOperand Trunc = DAG.getNode(ISD::TRUNCATE, N0.getValueType(), ExtLoad);
2892 CombineTo(N0.Val, Trunc, ExtLoad.getValue(1));
2893 // Extend SetCC uses if necessary.
2894 for (unsigned i = 0, e = SetCCs.size(); i != e; ++i) {
2895 SDNode *SetCC = SetCCs[i];
2896 SmallVector<SDOperand, 4> Ops;
2897 for (unsigned j = 0; j != 2; ++j) {
2898 SDOperand SOp = SetCC->getOperand(j);
2900 Ops.push_back(ExtLoad);
2902 Ops.push_back(DAG.getNode(ISD::ZERO_EXTEND, VT, SOp));
2904 Ops.push_back(SetCC->getOperand(2));
2905 CombineTo(SetCC, DAG.getNode(ISD::SETCC, SetCC->getValueType(0),
2906 &Ops[0], Ops.size()));
2908 return SDOperand(N, 0); // Return N so it doesn't get rechecked!
2912 // fold (zext (zextload x)) -> (zext (truncate (zextload x)))
2913 // fold (zext ( extload x)) -> (zext (truncate (zextload x)))
2914 if ((ISD::isZEXTLoad(N0.Val) || ISD::isEXTLoad(N0.Val)) &&
2915 ISD::isUNINDEXEDLoad(N0.Val) && N0.hasOneUse()) {
2916 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
2917 MVT::ValueType EVT = LN0->getMemoryVT();
2918 SDOperand ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, VT, LN0->getChain(),
2919 LN0->getBasePtr(), LN0->getSrcValue(),
2920 LN0->getSrcValueOffset(), EVT,
2922 LN0->getAlignment());
2923 CombineTo(N, ExtLoad);
2924 CombineTo(N0.Val, DAG.getNode(ISD::TRUNCATE, N0.getValueType(), ExtLoad),
2925 ExtLoad.getValue(1));
2926 return SDOperand(N, 0); // Return N so it doesn't get rechecked!
2929 // zext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
2930 if (N0.getOpcode() == ISD::SETCC) {
2932 SimplifySelectCC(N0.getOperand(0), N0.getOperand(1),
2933 DAG.getConstant(1, VT), DAG.getConstant(0, VT),
2934 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
2935 if (SCC.Val) return SCC;
2941 SDOperand DAGCombiner::visitANY_EXTEND(SDNode *N) {
2942 SDOperand N0 = N->getOperand(0);
2943 MVT::ValueType VT = N->getValueType(0);
2945 // fold (aext c1) -> c1
2946 if (isa<ConstantSDNode>(N0))
2947 return DAG.getNode(ISD::ANY_EXTEND, VT, N0);
2948 // fold (aext (aext x)) -> (aext x)
2949 // fold (aext (zext x)) -> (zext x)
2950 // fold (aext (sext x)) -> (sext x)
2951 if (N0.getOpcode() == ISD::ANY_EXTEND ||
2952 N0.getOpcode() == ISD::ZERO_EXTEND ||
2953 N0.getOpcode() == ISD::SIGN_EXTEND)
2954 return DAG.getNode(N0.getOpcode(), VT, N0.getOperand(0));
2956 // fold (aext (truncate (load x))) -> (aext (smaller load x))
2957 // fold (aext (truncate (srl (load x), c))) -> (aext (small load (x+c/n)))
2958 if (N0.getOpcode() == ISD::TRUNCATE) {
2959 SDOperand NarrowLoad = ReduceLoadWidth(N0.Val);
2960 if (NarrowLoad.Val) {
2961 if (NarrowLoad.Val != N0.Val)
2962 CombineTo(N0.Val, NarrowLoad);
2963 return DAG.getNode(ISD::ANY_EXTEND, VT, NarrowLoad);
2967 // fold (aext (truncate x))
2968 if (N0.getOpcode() == ISD::TRUNCATE) {
2969 SDOperand TruncOp = N0.getOperand(0);
2970 if (TruncOp.getValueType() == VT)
2971 return TruncOp; // x iff x size == zext size.
2972 if (TruncOp.getValueType() > VT)
2973 return DAG.getNode(ISD::TRUNCATE, VT, TruncOp);
2974 return DAG.getNode(ISD::ANY_EXTEND, VT, TruncOp);
2977 // fold (aext (and (trunc x), cst)) -> (and x, cst).
2978 if (N0.getOpcode() == ISD::AND &&
2979 N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
2980 N0.getOperand(1).getOpcode() == ISD::Constant) {
2981 SDOperand X = N0.getOperand(0).getOperand(0);
2982 if (X.getValueType() < VT) {
2983 X = DAG.getNode(ISD::ANY_EXTEND, VT, X);
2984 } else if (X.getValueType() > VT) {
2985 X = DAG.getNode(ISD::TRUNCATE, VT, X);
2987 uint64_t Mask = cast<ConstantSDNode>(N0.getOperand(1))->getValue();
2988 return DAG.getNode(ISD::AND, VT, X, DAG.getConstant(Mask, VT));
2991 // fold (aext (load x)) -> (aext (truncate (extload x)))
2992 if (ISD::isNON_EXTLoad(N0.Val) && N0.hasOneUse() &&
2993 (!AfterLegalize||TLI.isLoadXLegal(ISD::EXTLOAD, N0.getValueType()))) {
2994 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
2995 SDOperand ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, VT, LN0->getChain(),
2996 LN0->getBasePtr(), LN0->getSrcValue(),
2997 LN0->getSrcValueOffset(),
3000 LN0->getAlignment());
3001 CombineTo(N, ExtLoad);
3002 CombineTo(N0.Val, DAG.getNode(ISD::TRUNCATE, N0.getValueType(), ExtLoad),
3003 ExtLoad.getValue(1));
3004 return SDOperand(N, 0); // Return N so it doesn't get rechecked!
3007 // fold (aext (zextload x)) -> (aext (truncate (zextload x)))
3008 // fold (aext (sextload x)) -> (aext (truncate (sextload x)))
3009 // fold (aext ( extload x)) -> (aext (truncate (extload x)))
3010 if (N0.getOpcode() == ISD::LOAD &&
3011 !ISD::isNON_EXTLoad(N0.Val) && ISD::isUNINDEXEDLoad(N0.Val) &&
3013 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
3014 MVT::ValueType EVT = LN0->getMemoryVT();
3015 SDOperand ExtLoad = DAG.getExtLoad(LN0->getExtensionType(), VT,
3016 LN0->getChain(), LN0->getBasePtr(),
3018 LN0->getSrcValueOffset(), EVT,
3020 LN0->getAlignment());
3021 CombineTo(N, ExtLoad);
3022 CombineTo(N0.Val, DAG.getNode(ISD::TRUNCATE, N0.getValueType(), ExtLoad),
3023 ExtLoad.getValue(1));
3024 return SDOperand(N, 0); // Return N so it doesn't get rechecked!
3027 // aext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
3028 if (N0.getOpcode() == ISD::SETCC) {
3030 SimplifySelectCC(N0.getOperand(0), N0.getOperand(1),
3031 DAG.getConstant(1, VT), DAG.getConstant(0, VT),
3032 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
3040 /// GetDemandedBits - See if the specified operand can be simplified with the
3041 /// knowledge that only the bits specified by Mask are used. If so, return the
3042 /// simpler operand, otherwise return a null SDOperand.
3043 SDOperand DAGCombiner::GetDemandedBits(SDOperand V, const APInt &Mask) {
3044 switch (V.getOpcode()) {
3048 // If the LHS or RHS don't contribute bits to the or, drop them.
3049 if (DAG.MaskedValueIsZero(V.getOperand(0), Mask))
3050 return V.getOperand(1);
3051 if (DAG.MaskedValueIsZero(V.getOperand(1), Mask))
3052 return V.getOperand(0);
3055 // Only look at single-use SRLs.
3056 if (!V.Val->hasOneUse())
3058 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(V.getOperand(1))) {
3059 // See if we can recursively simplify the LHS.
3060 unsigned Amt = RHSC->getValue();
3061 APInt NewMask = Mask << Amt;
3062 SDOperand SimplifyLHS = GetDemandedBits(V.getOperand(0), NewMask);
3063 if (SimplifyLHS.Val) {
3064 return DAG.getNode(ISD::SRL, V.getValueType(),
3065 SimplifyLHS, V.getOperand(1));
3072 /// ReduceLoadWidth - If the result of a wider load is shifted to right of N
3073 /// bits and then truncated to a narrower type and where N is a multiple
3074 /// of number of bits of the narrower type, transform it to a narrower load
3075 /// from address + N / num of bits of new type. If the result is to be
3076 /// extended, also fold the extension to form a extending load.
3077 SDOperand DAGCombiner::ReduceLoadWidth(SDNode *N) {
3078 unsigned Opc = N->getOpcode();
3079 ISD::LoadExtType ExtType = ISD::NON_EXTLOAD;
3080 SDOperand N0 = N->getOperand(0);
3081 MVT::ValueType VT = N->getValueType(0);
3082 MVT::ValueType EVT = N->getValueType(0);
3084 // Special case: SIGN_EXTEND_INREG is basically truncating to EVT then
3086 if (Opc == ISD::SIGN_EXTEND_INREG) {
3087 ExtType = ISD::SEXTLOAD;
3088 EVT = cast<VTSDNode>(N->getOperand(1))->getVT();
3089 if (AfterLegalize && !TLI.isLoadXLegal(ISD::SEXTLOAD, EVT))
3093 unsigned EVTBits = MVT::getSizeInBits(EVT);
3095 bool CombineSRL = false;
3096 if (N0.getOpcode() == ISD::SRL && N0.hasOneUse()) {
3097 if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
3098 ShAmt = N01->getValue();
3099 // Is the shift amount a multiple of size of VT?
3100 if ((ShAmt & (EVTBits-1)) == 0) {
3101 N0 = N0.getOperand(0);
3102 if (MVT::getSizeInBits(N0.getValueType()) <= EVTBits)
3109 if (ISD::isNON_EXTLoad(N0.Val) && N0.hasOneUse() &&
3110 // Do not allow folding to i1 here. i1 is implicitly stored in memory in
3111 // zero extended form: by shrinking the load, we lose track of the fact
3112 // that it is already zero extended.
3113 // FIXME: This should be reevaluated.
3115 assert(MVT::getSizeInBits(N0.getValueType()) > EVTBits &&
3116 "Cannot truncate to larger type!");
3117 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
3118 MVT::ValueType PtrType = N0.getOperand(1).getValueType();
3119 // For big endian targets, we need to adjust the offset to the pointer to
3120 // load the correct bytes.
3121 if (TLI.isBigEndian()) {
3122 unsigned LVTStoreBits = MVT::getStoreSizeInBits(N0.getValueType());
3123 unsigned EVTStoreBits = MVT::getStoreSizeInBits(EVT);
3124 ShAmt = LVTStoreBits - EVTStoreBits - ShAmt;
3126 uint64_t PtrOff = ShAmt / 8;
3127 unsigned NewAlign = MinAlign(LN0->getAlignment(), PtrOff);
3128 SDOperand NewPtr = DAG.getNode(ISD::ADD, PtrType, LN0->getBasePtr(),
3129 DAG.getConstant(PtrOff, PtrType));
3130 AddToWorkList(NewPtr.Val);
3131 SDOperand Load = (ExtType == ISD::NON_EXTLOAD)
3132 ? DAG.getLoad(VT, LN0->getChain(), NewPtr,
3133 LN0->getSrcValue(), LN0->getSrcValueOffset(),
3134 LN0->isVolatile(), NewAlign)
3135 : DAG.getExtLoad(ExtType, VT, LN0->getChain(), NewPtr,
3136 LN0->getSrcValue(), LN0->getSrcValueOffset(), EVT,
3137 LN0->isVolatile(), NewAlign);
3140 WorkListRemover DeadNodes(*this);
3141 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1),
3143 CombineTo(N->getOperand(0).Val, Load);
3145 CombineTo(N0.Val, Load, Load.getValue(1));
3147 if (Opc == ISD::SIGN_EXTEND_INREG)
3148 return DAG.getNode(Opc, VT, Load, N->getOperand(1));
3150 return DAG.getNode(Opc, VT, Load);
3152 return SDOperand(N, 0); // Return N so it doesn't get rechecked!
3159 SDOperand DAGCombiner::visitSIGN_EXTEND_INREG(SDNode *N) {
3160 SDOperand N0 = N->getOperand(0);
3161 SDOperand N1 = N->getOperand(1);
3162 MVT::ValueType VT = N->getValueType(0);
3163 MVT::ValueType EVT = cast<VTSDNode>(N1)->getVT();
3164 unsigned VTBits = MVT::getSizeInBits(VT);
3165 unsigned EVTBits = MVT::getSizeInBits(EVT);
3167 // fold (sext_in_reg c1) -> c1
3168 if (isa<ConstantSDNode>(N0) || N0.getOpcode() == ISD::UNDEF)
3169 return DAG.getNode(ISD::SIGN_EXTEND_INREG, VT, N0, N1);
3171 // If the input is already sign extended, just drop the extension.
3172 if (DAG.ComputeNumSignBits(N0) >= MVT::getSizeInBits(VT)-EVTBits+1)
3175 // fold (sext_in_reg (sext_in_reg x, VT2), VT1) -> (sext_in_reg x, minVT) pt2
3176 if (N0.getOpcode() == ISD::SIGN_EXTEND_INREG &&
3177 EVT < cast<VTSDNode>(N0.getOperand(1))->getVT()) {
3178 return DAG.getNode(ISD::SIGN_EXTEND_INREG, VT, N0.getOperand(0), N1);
3181 // fold (sext_in_reg x) -> (zext_in_reg x) if the sign bit is known zero.
3182 if (DAG.MaskedValueIsZero(N0, APInt::getBitsSet(VTBits, EVTBits-1, EVTBits)))
3183 return DAG.getZeroExtendInReg(N0, EVT);
3185 // fold operands of sext_in_reg based on knowledge that the top bits are not
3187 if (SimplifyDemandedBits(SDOperand(N, 0)))
3188 return SDOperand(N, 0);
3190 // fold (sext_in_reg (load x)) -> (smaller sextload x)
3191 // fold (sext_in_reg (srl (load x), c)) -> (smaller sextload (x+c/evtbits))
3192 SDOperand NarrowLoad = ReduceLoadWidth(N);
3196 // fold (sext_in_reg (srl X, 24), i8) -> sra X, 24
3197 // fold (sext_in_reg (srl X, 23), i8) -> sra X, 23 iff possible.
3198 // We already fold "(sext_in_reg (srl X, 25), i8) -> srl X, 25" above.
3199 if (N0.getOpcode() == ISD::SRL) {
3200 if (ConstantSDNode *ShAmt = dyn_cast<ConstantSDNode>(N0.getOperand(1)))
3201 if (ShAmt->getValue()+EVTBits <= MVT::getSizeInBits(VT)) {
3202 // We can turn this into an SRA iff the input to the SRL is already sign
3204 unsigned InSignBits = DAG.ComputeNumSignBits(N0.getOperand(0));
3205 if (MVT::getSizeInBits(VT)-(ShAmt->getValue()+EVTBits) < InSignBits)
3206 return DAG.getNode(ISD::SRA, VT, N0.getOperand(0), N0.getOperand(1));
3210 // fold (sext_inreg (extload x)) -> (sextload x)
3211 if (ISD::isEXTLoad(N0.Val) &&
3212 ISD::isUNINDEXEDLoad(N0.Val) &&
3213 EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
3214 (!AfterLegalize || TLI.isLoadXLegal(ISD::SEXTLOAD, EVT))) {
3215 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
3216 SDOperand ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, VT, LN0->getChain(),
3217 LN0->getBasePtr(), LN0->getSrcValue(),
3218 LN0->getSrcValueOffset(), EVT,
3220 LN0->getAlignment());
3221 CombineTo(N, ExtLoad);
3222 CombineTo(N0.Val, ExtLoad, ExtLoad.getValue(1));
3223 return SDOperand(N, 0); // Return N so it doesn't get rechecked!
3225 // fold (sext_inreg (zextload x)) -> (sextload x) iff load has one use
3226 if (ISD::isZEXTLoad(N0.Val) && ISD::isUNINDEXEDLoad(N0.Val) &&
3228 EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
3229 (!AfterLegalize || TLI.isLoadXLegal(ISD::SEXTLOAD, EVT))) {
3230 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
3231 SDOperand ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, VT, LN0->getChain(),
3232 LN0->getBasePtr(), LN0->getSrcValue(),
3233 LN0->getSrcValueOffset(), EVT,
3235 LN0->getAlignment());
3236 CombineTo(N, ExtLoad);
3237 CombineTo(N0.Val, ExtLoad, ExtLoad.getValue(1));
3238 return SDOperand(N, 0); // Return N so it doesn't get rechecked!
3243 SDOperand DAGCombiner::visitTRUNCATE(SDNode *N) {
3244 SDOperand N0 = N->getOperand(0);
3245 MVT::ValueType VT = N->getValueType(0);
3248 if (N0.getValueType() == N->getValueType(0))
3250 // fold (truncate c1) -> c1
3251 if (isa<ConstantSDNode>(N0))
3252 return DAG.getNode(ISD::TRUNCATE, VT, N0);
3253 // fold (truncate (truncate x)) -> (truncate x)
3254 if (N0.getOpcode() == ISD::TRUNCATE)
3255 return DAG.getNode(ISD::TRUNCATE, VT, N0.getOperand(0));
3256 // fold (truncate (ext x)) -> (ext x) or (truncate x) or x
3257 if (N0.getOpcode() == ISD::ZERO_EXTEND || N0.getOpcode() == ISD::SIGN_EXTEND||
3258 N0.getOpcode() == ISD::ANY_EXTEND) {
3259 if (N0.getOperand(0).getValueType() < VT)
3260 // if the source is smaller than the dest, we still need an extend
3261 return DAG.getNode(N0.getOpcode(), VT, N0.getOperand(0));
3262 else if (N0.getOperand(0).getValueType() > VT)
3263 // if the source is larger than the dest, than we just need the truncate
3264 return DAG.getNode(ISD::TRUNCATE, VT, N0.getOperand(0));
3266 // if the source and dest are the same type, we can drop both the extend
3268 return N0.getOperand(0);
3271 // See if we can simplify the input to this truncate through knowledge that
3272 // only the low bits are being used. For example "trunc (or (shl x, 8), y)"
3275 GetDemandedBits(N0, APInt::getLowBitsSet(N0.getValueSizeInBits(),
3276 MVT::getSizeInBits(VT)));
3278 return DAG.getNode(ISD::TRUNCATE, VT, Shorter);
3280 // fold (truncate (load x)) -> (smaller load x)
3281 // fold (truncate (srl (load x), c)) -> (smaller load (x+c/evtbits))
3282 return ReduceLoadWidth(N);
3285 SDOperand DAGCombiner::visitBIT_CONVERT(SDNode *N) {
3286 SDOperand N0 = N->getOperand(0);
3287 MVT::ValueType VT = N->getValueType(0);
3289 // If the input is a BUILD_VECTOR with all constant elements, fold this now.
3290 // Only do this before legalize, since afterward the target may be depending
3291 // on the bitconvert.
3292 // First check to see if this is all constant.
3293 if (!AfterLegalize &&
3294 N0.getOpcode() == ISD::BUILD_VECTOR && N0.Val->hasOneUse() &&
3295 MVT::isVector(VT)) {
3296 bool isSimple = true;
3297 for (unsigned i = 0, e = N0.getNumOperands(); i != e; ++i)
3298 if (N0.getOperand(i).getOpcode() != ISD::UNDEF &&
3299 N0.getOperand(i).getOpcode() != ISD::Constant &&
3300 N0.getOperand(i).getOpcode() != ISD::ConstantFP) {
3305 MVT::ValueType DestEltVT = MVT::getVectorElementType(N->getValueType(0));
3306 assert(!MVT::isVector(DestEltVT) &&
3307 "Element type of vector ValueType must not be vector!");
3309 return ConstantFoldBIT_CONVERTofBUILD_VECTOR(N0.Val, DestEltVT);
3313 // If the input is a constant, let getNode() fold it.
3314 if (isa<ConstantSDNode>(N0) || isa<ConstantFPSDNode>(N0)) {
3315 SDOperand Res = DAG.getNode(ISD::BIT_CONVERT, VT, N0);
3316 if (Res.Val != N) return Res;
3319 if (N0.getOpcode() == ISD::BIT_CONVERT) // conv(conv(x,t1),t2) -> conv(x,t2)
3320 return DAG.getNode(ISD::BIT_CONVERT, VT, N0.getOperand(0));
3322 // fold (conv (load x)) -> (load (conv*)x)
3323 // If the resultant load doesn't need a higher alignment than the original!
3324 if (ISD::isNormalLoad(N0.Val) && N0.hasOneUse() &&
3325 TLI.isOperationLegal(ISD::LOAD, VT)) {
3326 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
3327 unsigned Align = TLI.getTargetMachine().getTargetData()->
3328 getABITypeAlignment(MVT::getTypeForValueType(VT));
3329 unsigned OrigAlign = LN0->getAlignment();
3330 if (Align <= OrigAlign) {
3331 SDOperand Load = DAG.getLoad(VT, LN0->getChain(), LN0->getBasePtr(),
3332 LN0->getSrcValue(), LN0->getSrcValueOffset(),
3333 LN0->isVolatile(), Align);
3335 CombineTo(N0.Val, DAG.getNode(ISD::BIT_CONVERT, N0.getValueType(), Load),
3341 // Fold bitconvert(fneg(x)) -> xor(bitconvert(x), signbit)
3342 // Fold bitconvert(fabs(x)) -> and(bitconvert(x), ~signbit)
3343 // This often reduces constant pool loads.
3344 if ((N0.getOpcode() == ISD::FNEG || N0.getOpcode() == ISD::FABS) &&
3345 N0.Val->hasOneUse() && MVT::isInteger(VT) && !MVT::isVector(VT)) {
3346 SDOperand NewConv = DAG.getNode(ISD::BIT_CONVERT, VT, N0.getOperand(0));
3347 AddToWorkList(NewConv.Val);
3349 uint64_t SignBit = MVT::getIntVTSignBit(VT);
3350 if (N0.getOpcode() == ISD::FNEG)
3351 return DAG.getNode(ISD::XOR, VT, NewConv, DAG.getConstant(SignBit, VT));
3352 assert(N0.getOpcode() == ISD::FABS);
3353 return DAG.getNode(ISD::AND, VT, NewConv, DAG.getConstant(~SignBit, VT));
3356 // Fold bitconvert(fcopysign(cst, x)) -> bitconvert(x)&sign | cst&~sign'
3357 // Note that we don't handle copysign(x,cst) because this can always be folded
3358 // to an fneg or fabs.
3359 if (N0.getOpcode() == ISD::FCOPYSIGN && N0.Val->hasOneUse() &&
3360 isa<ConstantFPSDNode>(N0.getOperand(0)) &&
3361 MVT::isInteger(VT) && !MVT::isVector(VT)) {
3362 unsigned OrigXWidth = MVT::getSizeInBits(N0.getOperand(1).getValueType());
3363 SDOperand X = DAG.getNode(ISD::BIT_CONVERT, MVT::getIntegerType(OrigXWidth),
3365 AddToWorkList(X.Val);
3367 // If X has a different width than the result/lhs, sext it or truncate it.
3368 unsigned VTWidth = MVT::getSizeInBits(VT);
3369 if (OrigXWidth < VTWidth) {
3370 X = DAG.getNode(ISD::SIGN_EXTEND, VT, X);
3371 AddToWorkList(X.Val);
3372 } else if (OrigXWidth > VTWidth) {
3373 // To get the sign bit in the right place, we have to shift it right
3374 // before truncating.
3375 X = DAG.getNode(ISD::SRL, X.getValueType(), X,
3376 DAG.getConstant(OrigXWidth-VTWidth, X.getValueType()));
3377 AddToWorkList(X.Val);
3378 X = DAG.getNode(ISD::TRUNCATE, VT, X);
3379 AddToWorkList(X.Val);
3382 uint64_t SignBit = MVT::getIntVTSignBit(VT);
3383 X = DAG.getNode(ISD::AND, VT, X, DAG.getConstant(SignBit, VT));
3384 AddToWorkList(X.Val);
3386 SDOperand Cst = DAG.getNode(ISD::BIT_CONVERT, VT, N0.getOperand(0));
3387 Cst = DAG.getNode(ISD::AND, VT, Cst, DAG.getConstant(~SignBit, VT));
3388 AddToWorkList(Cst.Val);
3390 return DAG.getNode(ISD::OR, VT, X, Cst);
3396 /// ConstantFoldBIT_CONVERTofBUILD_VECTOR - We know that BV is a build_vector
3397 /// node with Constant, ConstantFP or Undef operands. DstEltVT indicates the
3398 /// destination element value type.
3399 SDOperand DAGCombiner::
3400 ConstantFoldBIT_CONVERTofBUILD_VECTOR(SDNode *BV, MVT::ValueType DstEltVT) {
3401 MVT::ValueType SrcEltVT = BV->getOperand(0).getValueType();
3403 // If this is already the right type, we're done.
3404 if (SrcEltVT == DstEltVT) return SDOperand(BV, 0);
3406 unsigned SrcBitSize = MVT::getSizeInBits(SrcEltVT);
3407 unsigned DstBitSize = MVT::getSizeInBits(DstEltVT);
3409 // If this is a conversion of N elements of one type to N elements of another
3410 // type, convert each element. This handles FP<->INT cases.
3411 if (SrcBitSize == DstBitSize) {
3412 SmallVector<SDOperand, 8> Ops;
3413 for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) {
3414 Ops.push_back(DAG.getNode(ISD::BIT_CONVERT, DstEltVT, BV->getOperand(i)));
3415 AddToWorkList(Ops.back().Val);
3418 MVT::getVectorType(DstEltVT,
3419 MVT::getVectorNumElements(BV->getValueType(0)));
3420 return DAG.getNode(ISD::BUILD_VECTOR, VT, &Ops[0], Ops.size());
3423 // Otherwise, we're growing or shrinking the elements. To avoid having to
3424 // handle annoying details of growing/shrinking FP values, we convert them to
3426 if (MVT::isFloatingPoint(SrcEltVT)) {
3427 // Convert the input float vector to a int vector where the elements are the
3429 assert((SrcEltVT == MVT::f32 || SrcEltVT == MVT::f64) && "Unknown FP VT!");
3430 MVT::ValueType IntVT = SrcEltVT == MVT::f32 ? MVT::i32 : MVT::i64;
3431 BV = ConstantFoldBIT_CONVERTofBUILD_VECTOR(BV, IntVT).Val;
3435 // Now we know the input is an integer vector. If the output is a FP type,
3436 // convert to integer first, then to FP of the right size.
3437 if (MVT::isFloatingPoint(DstEltVT)) {
3438 assert((DstEltVT == MVT::f32 || DstEltVT == MVT::f64) && "Unknown FP VT!");
3439 MVT::ValueType TmpVT = DstEltVT == MVT::f32 ? MVT::i32 : MVT::i64;
3440 SDNode *Tmp = ConstantFoldBIT_CONVERTofBUILD_VECTOR(BV, TmpVT).Val;
3442 // Next, convert to FP elements of the same size.
3443 return ConstantFoldBIT_CONVERTofBUILD_VECTOR(Tmp, DstEltVT);
3446 // Okay, we know the src/dst types are both integers of differing types.
3447 // Handling growing first.
3448 assert(MVT::isInteger(SrcEltVT) && MVT::isInteger(DstEltVT));
3449 if (SrcBitSize < DstBitSize) {
3450 unsigned NumInputsPerOutput = DstBitSize/SrcBitSize;
3452 SmallVector<SDOperand, 8> Ops;
3453 for (unsigned i = 0, e = BV->getNumOperands(); i != e;
3454 i += NumInputsPerOutput) {
3455 bool isLE = TLI.isLittleEndian();
3456 uint64_t NewBits = 0;
3457 bool EltIsUndef = true;
3458 for (unsigned j = 0; j != NumInputsPerOutput; ++j) {
3459 // Shift the previously computed bits over.
3460 NewBits <<= SrcBitSize;
3461 SDOperand Op = BV->getOperand(i+ (isLE ? (NumInputsPerOutput-j-1) : j));
3462 if (Op.getOpcode() == ISD::UNDEF) continue;
3465 NewBits |= cast<ConstantSDNode>(Op)->getValue();
3469 Ops.push_back(DAG.getNode(ISD::UNDEF, DstEltVT));
3471 Ops.push_back(DAG.getConstant(NewBits, DstEltVT));
3474 MVT::ValueType VT = MVT::getVectorType(DstEltVT, Ops.size());
3475 return DAG.getNode(ISD::BUILD_VECTOR, VT, &Ops[0], Ops.size());
3478 // Finally, this must be the case where we are shrinking elements: each input
3479 // turns into multiple outputs.
3480 bool isS2V = ISD::isScalarToVector(BV);
3481 unsigned NumOutputsPerInput = SrcBitSize/DstBitSize;
3482 MVT::ValueType VT = MVT::getVectorType(DstEltVT,
3483 NumOutputsPerInput * BV->getNumOperands());
3484 SmallVector<SDOperand, 8> Ops;
3485 for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) {
3486 if (BV->getOperand(i).getOpcode() == ISD::UNDEF) {
3487 for (unsigned j = 0; j != NumOutputsPerInput; ++j)
3488 Ops.push_back(DAG.getNode(ISD::UNDEF, DstEltVT));
3491 uint64_t OpVal = cast<ConstantSDNode>(BV->getOperand(i))->getValue();
3492 for (unsigned j = 0; j != NumOutputsPerInput; ++j) {
3493 unsigned ThisVal = OpVal & ((1ULL << DstBitSize)-1);
3494 Ops.push_back(DAG.getConstant(ThisVal, DstEltVT));
3495 if (isS2V && i == 0 && j == 0 && ThisVal == OpVal)
3496 // Simply turn this into a SCALAR_TO_VECTOR of the new type.
3497 return DAG.getNode(ISD::SCALAR_TO_VECTOR, VT, Ops[0]);
3498 OpVal >>= DstBitSize;
3501 // For big endian targets, swap the order of the pieces of each element.
3502 if (TLI.isBigEndian())
3503 std::reverse(Ops.end()-NumOutputsPerInput, Ops.end());
3505 return DAG.getNode(ISD::BUILD_VECTOR, VT, &Ops[0], Ops.size());
3510 SDOperand DAGCombiner::visitFADD(SDNode *N) {
3511 SDOperand N0 = N->getOperand(0);
3512 SDOperand N1 = N->getOperand(1);
3513 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
3514 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
3515 MVT::ValueType VT = N->getValueType(0);
3518 if (MVT::isVector(VT)) {
3519 SDOperand FoldedVOp = SimplifyVBinOp(N);
3520 if (FoldedVOp.Val) return FoldedVOp;
3523 // fold (fadd c1, c2) -> c1+c2
3524 if (N0CFP && N1CFP && VT != MVT::ppcf128)
3525 return DAG.getNode(ISD::FADD, VT, N0, N1);
3526 // canonicalize constant to RHS
3527 if (N0CFP && !N1CFP)
3528 return DAG.getNode(ISD::FADD, VT, N1, N0);
3529 // fold (A + (-B)) -> A-B
3530 if (isNegatibleForFree(N1, AfterLegalize) == 2)
3531 return DAG.getNode(ISD::FSUB, VT, N0,
3532 GetNegatedExpression(N1, DAG, AfterLegalize));
3533 // fold ((-A) + B) -> B-A
3534 if (isNegatibleForFree(N0, AfterLegalize) == 2)
3535 return DAG.getNode(ISD::FSUB, VT, N1,
3536 GetNegatedExpression(N0, DAG, AfterLegalize));
3538 // If allowed, fold (fadd (fadd x, c1), c2) -> (fadd x, (fadd c1, c2))
3539 if (UnsafeFPMath && N1CFP && N0.getOpcode() == ISD::FADD &&
3540 N0.Val->hasOneUse() && isa<ConstantFPSDNode>(N0.getOperand(1)))
3541 return DAG.getNode(ISD::FADD, VT, N0.getOperand(0),
3542 DAG.getNode(ISD::FADD, VT, N0.getOperand(1), N1));
3547 SDOperand DAGCombiner::visitFSUB(SDNode *N) {
3548 SDOperand N0 = N->getOperand(0);
3549 SDOperand N1 = N->getOperand(1);
3550 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
3551 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
3552 MVT::ValueType VT = N->getValueType(0);
3555 if (MVT::isVector(VT)) {
3556 SDOperand FoldedVOp = SimplifyVBinOp(N);
3557 if (FoldedVOp.Val) return FoldedVOp;
3560 // fold (fsub c1, c2) -> c1-c2
3561 if (N0CFP && N1CFP && VT != MVT::ppcf128)
3562 return DAG.getNode(ISD::FSUB, VT, N0, N1);
3564 if (UnsafeFPMath && N0CFP && N0CFP->getValueAPF().isZero()) {
3565 if (isNegatibleForFree(N1, AfterLegalize))
3566 return GetNegatedExpression(N1, DAG, AfterLegalize);
3567 return DAG.getNode(ISD::FNEG, VT, N1);
3569 // fold (A-(-B)) -> A+B
3570 if (isNegatibleForFree(N1, AfterLegalize))
3571 return DAG.getNode(ISD::FADD, VT, N0,
3572 GetNegatedExpression(N1, DAG, AfterLegalize));
3577 SDOperand DAGCombiner::visitFMUL(SDNode *N) {
3578 SDOperand N0 = N->getOperand(0);
3579 SDOperand N1 = N->getOperand(1);
3580 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
3581 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
3582 MVT::ValueType VT = N->getValueType(0);
3585 if (MVT::isVector(VT)) {
3586 SDOperand FoldedVOp = SimplifyVBinOp(N);
3587 if (FoldedVOp.Val) return FoldedVOp;
3590 // fold (fmul c1, c2) -> c1*c2
3591 if (N0CFP && N1CFP && VT != MVT::ppcf128)
3592 return DAG.getNode(ISD::FMUL, VT, N0, N1);
3593 // canonicalize constant to RHS
3594 if (N0CFP && !N1CFP)
3595 return DAG.getNode(ISD::FMUL, VT, N1, N0);
3596 // fold (fmul X, 2.0) -> (fadd X, X)
3597 if (N1CFP && N1CFP->isExactlyValue(+2.0))
3598 return DAG.getNode(ISD::FADD, VT, N0, N0);
3599 // fold (fmul X, -1.0) -> (fneg X)
3600 if (N1CFP && N1CFP->isExactlyValue(-1.0))
3601 return DAG.getNode(ISD::FNEG, VT, N0);
3604 if (char LHSNeg = isNegatibleForFree(N0, AfterLegalize)) {
3605 if (char RHSNeg = isNegatibleForFree(N1, AfterLegalize)) {
3606 // Both can be negated for free, check to see if at least one is cheaper
3608 if (LHSNeg == 2 || RHSNeg == 2)
3609 return DAG.getNode(ISD::FMUL, VT,
3610 GetNegatedExpression(N0, DAG, AfterLegalize),
3611 GetNegatedExpression(N1, DAG, AfterLegalize));
3615 // If allowed, fold (fmul (fmul x, c1), c2) -> (fmul x, (fmul c1, c2))
3616 if (UnsafeFPMath && N1CFP && N0.getOpcode() == ISD::FMUL &&
3617 N0.Val->hasOneUse() && isa<ConstantFPSDNode>(N0.getOperand(1)))
3618 return DAG.getNode(ISD::FMUL, VT, N0.getOperand(0),
3619 DAG.getNode(ISD::FMUL, VT, N0.getOperand(1), N1));
3624 SDOperand DAGCombiner::visitFDIV(SDNode *N) {
3625 SDOperand N0 = N->getOperand(0);
3626 SDOperand N1 = N->getOperand(1);
3627 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
3628 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
3629 MVT::ValueType VT = N->getValueType(0);
3632 if (MVT::isVector(VT)) {
3633 SDOperand FoldedVOp = SimplifyVBinOp(N);
3634 if (FoldedVOp.Val) return FoldedVOp;
3637 // fold (fdiv c1, c2) -> c1/c2
3638 if (N0CFP && N1CFP && VT != MVT::ppcf128)
3639 return DAG.getNode(ISD::FDIV, VT, N0, N1);
3643 if (char LHSNeg = isNegatibleForFree(N0, AfterLegalize)) {
3644 if (char RHSNeg = isNegatibleForFree(N1, AfterLegalize)) {
3645 // Both can be negated for free, check to see if at least one is cheaper
3647 if (LHSNeg == 2 || RHSNeg == 2)
3648 return DAG.getNode(ISD::FDIV, VT,
3649 GetNegatedExpression(N0, DAG, AfterLegalize),
3650 GetNegatedExpression(N1, DAG, AfterLegalize));
3657 SDOperand DAGCombiner::visitFREM(SDNode *N) {
3658 SDOperand N0 = N->getOperand(0);
3659 SDOperand N1 = N->getOperand(1);
3660 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
3661 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
3662 MVT::ValueType VT = N->getValueType(0);
3664 // fold (frem c1, c2) -> fmod(c1,c2)
3665 if (N0CFP && N1CFP && VT != MVT::ppcf128)
3666 return DAG.getNode(ISD::FREM, VT, N0, N1);
3671 SDOperand DAGCombiner::visitFCOPYSIGN(SDNode *N) {
3672 SDOperand N0 = N->getOperand(0);
3673 SDOperand N1 = N->getOperand(1);
3674 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
3675 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
3676 MVT::ValueType VT = N->getValueType(0);
3678 if (N0CFP && N1CFP && VT != MVT::ppcf128) // Constant fold
3679 return DAG.getNode(ISD::FCOPYSIGN, VT, N0, N1);
3682 const APFloat& V = N1CFP->getValueAPF();
3683 // copysign(x, c1) -> fabs(x) iff ispos(c1)
3684 // copysign(x, c1) -> fneg(fabs(x)) iff isneg(c1)
3685 if (!V.isNegative())
3686 return DAG.getNode(ISD::FABS, VT, N0);
3688 return DAG.getNode(ISD::FNEG, VT, DAG.getNode(ISD::FABS, VT, N0));
3691 // copysign(fabs(x), y) -> copysign(x, y)
3692 // copysign(fneg(x), y) -> copysign(x, y)
3693 // copysign(copysign(x,z), y) -> copysign(x, y)
3694 if (N0.getOpcode() == ISD::FABS || N0.getOpcode() == ISD::FNEG ||
3695 N0.getOpcode() == ISD::FCOPYSIGN)
3696 return DAG.getNode(ISD::FCOPYSIGN, VT, N0.getOperand(0), N1);
3698 // copysign(x, abs(y)) -> abs(x)
3699 if (N1.getOpcode() == ISD::FABS)
3700 return DAG.getNode(ISD::FABS, VT, N0);
3702 // copysign(x, copysign(y,z)) -> copysign(x, z)
3703 if (N1.getOpcode() == ISD::FCOPYSIGN)
3704 return DAG.getNode(ISD::FCOPYSIGN, VT, N0, N1.getOperand(1));
3706 // copysign(x, fp_extend(y)) -> copysign(x, y)
3707 // copysign(x, fp_round(y)) -> copysign(x, y)
3708 if (N1.getOpcode() == ISD::FP_EXTEND || N1.getOpcode() == ISD::FP_ROUND)
3709 return DAG.getNode(ISD::FCOPYSIGN, VT, N0, N1.getOperand(0));
3716 SDOperand DAGCombiner::visitSINT_TO_FP(SDNode *N) {
3717 SDOperand N0 = N->getOperand(0);
3718 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
3719 MVT::ValueType VT = N->getValueType(0);
3721 // fold (sint_to_fp c1) -> c1fp
3722 if (N0C && N0.getValueType() != MVT::ppcf128)
3723 return DAG.getNode(ISD::SINT_TO_FP, VT, N0);
3727 SDOperand DAGCombiner::visitUINT_TO_FP(SDNode *N) {
3728 SDOperand N0 = N->getOperand(0);
3729 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
3730 MVT::ValueType VT = N->getValueType(0);
3732 // fold (uint_to_fp c1) -> c1fp
3733 if (N0C && N0.getValueType() != MVT::ppcf128)
3734 return DAG.getNode(ISD::UINT_TO_FP, VT, N0);
3738 SDOperand DAGCombiner::visitFP_TO_SINT(SDNode *N) {
3739 SDOperand N0 = N->getOperand(0);
3740 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
3741 MVT::ValueType VT = N->getValueType(0);
3743 // fold (fp_to_sint c1fp) -> c1
3745 return DAG.getNode(ISD::FP_TO_SINT, VT, N0);
3749 SDOperand DAGCombiner::visitFP_TO_UINT(SDNode *N) {
3750 SDOperand N0 = N->getOperand(0);
3751 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
3752 MVT::ValueType VT = N->getValueType(0);
3754 // fold (fp_to_uint c1fp) -> c1
3755 if (N0CFP && VT != MVT::ppcf128)
3756 return DAG.getNode(ISD::FP_TO_UINT, VT, N0);
3760 SDOperand DAGCombiner::visitFP_ROUND(SDNode *N) {
3761 SDOperand N0 = N->getOperand(0);
3762 SDOperand N1 = N->getOperand(1);
3763 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
3764 MVT::ValueType VT = N->getValueType(0);
3766 // fold (fp_round c1fp) -> c1fp
3767 if (N0CFP && N0.getValueType() != MVT::ppcf128)
3768 return DAG.getNode(ISD::FP_ROUND, VT, N0, N1);
3770 // fold (fp_round (fp_extend x)) -> x
3771 if (N0.getOpcode() == ISD::FP_EXTEND && VT == N0.getOperand(0).getValueType())
3772 return N0.getOperand(0);
3774 // fold (fp_round (fp_round x)) -> (fp_round x)
3775 if (N0.getOpcode() == ISD::FP_ROUND) {
3776 // This is a value preserving truncation if both round's are.
3777 bool IsTrunc = N->getConstantOperandVal(1) == 1 &&
3778 N0.Val->getConstantOperandVal(1) == 1;
3779 return DAG.getNode(ISD::FP_ROUND, VT, N0.getOperand(0),
3780 DAG.getIntPtrConstant(IsTrunc));
3783 // fold (fp_round (copysign X, Y)) -> (copysign (fp_round X), Y)
3784 if (N0.getOpcode() == ISD::FCOPYSIGN && N0.Val->hasOneUse()) {
3785 SDOperand Tmp = DAG.getNode(ISD::FP_ROUND, VT, N0.getOperand(0), N1);
3786 AddToWorkList(Tmp.Val);
3787 return DAG.getNode(ISD::FCOPYSIGN, VT, Tmp, N0.getOperand(1));
3793 SDOperand DAGCombiner::visitFP_ROUND_INREG(SDNode *N) {
3794 SDOperand N0 = N->getOperand(0);
3795 MVT::ValueType VT = N->getValueType(0);
3796 MVT::ValueType EVT = cast<VTSDNode>(N->getOperand(1))->getVT();
3797 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
3799 // fold (fp_round_inreg c1fp) -> c1fp
3801 SDOperand Round = DAG.getConstantFP(N0CFP->getValueAPF(), EVT);
3802 return DAG.getNode(ISD::FP_EXTEND, VT, Round);
3807 SDOperand DAGCombiner::visitFP_EXTEND(SDNode *N) {
3808 SDOperand N0 = N->getOperand(0);
3809 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
3810 MVT::ValueType VT = N->getValueType(0);
3812 // If this is fp_round(fpextend), don't fold it, allow ourselves to be folded.
3813 if (N->hasOneUse() && (*N->use_begin())->getOpcode() == ISD::FP_ROUND)
3816 // fold (fp_extend c1fp) -> c1fp
3817 if (N0CFP && VT != MVT::ppcf128)
3818 return DAG.getNode(ISD::FP_EXTEND, VT, N0);
3820 // Turn fp_extend(fp_round(X, 1)) -> x since the fp_round doesn't affect the
3822 if (N0.getOpcode() == ISD::FP_ROUND && N0.Val->getConstantOperandVal(1) == 1){
3823 SDOperand In = N0.getOperand(0);
3824 if (In.getValueType() == VT) return In;
3825 if (VT < In.getValueType())
3826 return DAG.getNode(ISD::FP_ROUND, VT, In, N0.getOperand(1));
3827 return DAG.getNode(ISD::FP_EXTEND, VT, In);
3830 // fold (fpext (load x)) -> (fpext (fptrunc (extload x)))
3831 if (ISD::isNON_EXTLoad(N0.Val) && N0.hasOneUse() &&
3832 (!AfterLegalize||TLI.isLoadXLegal(ISD::EXTLOAD, N0.getValueType()))) {
3833 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
3834 SDOperand ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, VT, LN0->getChain(),
3835 LN0->getBasePtr(), LN0->getSrcValue(),
3836 LN0->getSrcValueOffset(),
3839 LN0->getAlignment());
3840 CombineTo(N, ExtLoad);
3841 CombineTo(N0.Val, DAG.getNode(ISD::FP_ROUND, N0.getValueType(), ExtLoad,
3842 DAG.getIntPtrConstant(1)),
3843 ExtLoad.getValue(1));
3844 return SDOperand(N, 0); // Return N so it doesn't get rechecked!
3851 SDOperand DAGCombiner::visitFNEG(SDNode *N) {
3852 SDOperand N0 = N->getOperand(0);
3854 if (isNegatibleForFree(N0, AfterLegalize))
3855 return GetNegatedExpression(N0, DAG, AfterLegalize);
3857 // Transform fneg(bitconvert(x)) -> bitconvert(x^sign) to avoid loading
3858 // constant pool values.
3859 if (N0.getOpcode() == ISD::BIT_CONVERT && N0.Val->hasOneUse() &&
3860 MVT::isInteger(N0.getOperand(0).getValueType()) &&
3861 !MVT::isVector(N0.getOperand(0).getValueType())) {
3862 SDOperand Int = N0.getOperand(0);
3863 MVT::ValueType IntVT = Int.getValueType();
3864 if (MVT::isInteger(IntVT) && !MVT::isVector(IntVT)) {
3865 Int = DAG.getNode(ISD::XOR, IntVT, Int,
3866 DAG.getConstant(MVT::getIntVTSignBit(IntVT), IntVT));
3867 AddToWorkList(Int.Val);
3868 return DAG.getNode(ISD::BIT_CONVERT, N->getValueType(0), Int);
3875 SDOperand DAGCombiner::visitFABS(SDNode *N) {
3876 SDOperand N0 = N->getOperand(0);
3877 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
3878 MVT::ValueType VT = N->getValueType(0);
3880 // fold (fabs c1) -> fabs(c1)
3881 if (N0CFP && VT != MVT::ppcf128)
3882 return DAG.getNode(ISD::FABS, VT, N0);
3883 // fold (fabs (fabs x)) -> (fabs x)
3884 if (N0.getOpcode() == ISD::FABS)
3885 return N->getOperand(0);
3886 // fold (fabs (fneg x)) -> (fabs x)
3887 // fold (fabs (fcopysign x, y)) -> (fabs x)
3888 if (N0.getOpcode() == ISD::FNEG || N0.getOpcode() == ISD::FCOPYSIGN)
3889 return DAG.getNode(ISD::FABS, VT, N0.getOperand(0));
3891 // Transform fabs(bitconvert(x)) -> bitconvert(x&~sign) to avoid loading
3892 // constant pool values.
3893 if (N0.getOpcode() == ISD::BIT_CONVERT && N0.Val->hasOneUse() &&
3894 MVT::isInteger(N0.getOperand(0).getValueType()) &&
3895 !MVT::isVector(N0.getOperand(0).getValueType())) {
3896 SDOperand Int = N0.getOperand(0);
3897 MVT::ValueType IntVT = Int.getValueType();
3898 if (MVT::isInteger(IntVT) && !MVT::isVector(IntVT)) {
3899 Int = DAG.getNode(ISD::AND, IntVT, Int,
3900 DAG.getConstant(~MVT::getIntVTSignBit(IntVT), IntVT));
3901 AddToWorkList(Int.Val);
3902 return DAG.getNode(ISD::BIT_CONVERT, N->getValueType(0), Int);
3909 SDOperand DAGCombiner::visitBRCOND(SDNode *N) {
3910 SDOperand Chain = N->getOperand(0);
3911 SDOperand N1 = N->getOperand(1);
3912 SDOperand N2 = N->getOperand(2);
3913 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
3915 // never taken branch, fold to chain
3916 if (N1C && N1C->isNullValue())
3918 // unconditional branch
3919 if (N1C && N1C->getValue() == 1)
3920 return DAG.getNode(ISD::BR, MVT::Other, Chain, N2);
3921 // fold a brcond with a setcc condition into a BR_CC node if BR_CC is legal
3923 if (N1.getOpcode() == ISD::SETCC &&
3924 TLI.isOperationLegal(ISD::BR_CC, MVT::Other)) {
3925 return DAG.getNode(ISD::BR_CC, MVT::Other, Chain, N1.getOperand(2),
3926 N1.getOperand(0), N1.getOperand(1), N2);
3931 // Operand List for BR_CC: Chain, CondCC, CondLHS, CondRHS, DestBB.
3933 SDOperand DAGCombiner::visitBR_CC(SDNode *N) {
3934 CondCodeSDNode *CC = cast<CondCodeSDNode>(N->getOperand(1));
3935 SDOperand CondLHS = N->getOperand(2), CondRHS = N->getOperand(3);
3937 // Use SimplifySetCC to simplify SETCC's.
3938 SDOperand Simp = SimplifySetCC(MVT::i1, CondLHS, CondRHS, CC->get(), false);
3939 if (Simp.Val) AddToWorkList(Simp.Val);
3941 ConstantSDNode *SCCC = dyn_cast_or_null<ConstantSDNode>(Simp.Val);
3943 // fold br_cc true, dest -> br dest (unconditional branch)
3944 if (SCCC && SCCC->getValue())
3945 return DAG.getNode(ISD::BR, MVT::Other, N->getOperand(0),
3947 // fold br_cc false, dest -> unconditional fall through
3948 if (SCCC && SCCC->isNullValue())
3949 return N->getOperand(0);
3951 // fold to a simpler setcc
3952 if (Simp.Val && Simp.getOpcode() == ISD::SETCC)
3953 return DAG.getNode(ISD::BR_CC, MVT::Other, N->getOperand(0),
3954 Simp.getOperand(2), Simp.getOperand(0),
3955 Simp.getOperand(1), N->getOperand(4));
3960 /// CombineToPreIndexedLoadStore - Try turning a load / store and a
3961 /// pre-indexed load / store when the base pointer is a add or subtract
3962 /// and it has other uses besides the load / store. After the
3963 /// transformation, the new indexed load / store has effectively folded
3964 /// the add / subtract in and all of its other uses are redirected to the
3965 /// new load / store.
3966 bool DAGCombiner::CombineToPreIndexedLoadStore(SDNode *N) {
3973 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
3974 if (LD->isIndexed())
3976 VT = LD->getMemoryVT();
3977 if (!TLI.isIndexedLoadLegal(ISD::PRE_INC, VT) &&
3978 !TLI.isIndexedLoadLegal(ISD::PRE_DEC, VT))
3980 Ptr = LD->getBasePtr();
3981 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
3982 if (ST->isIndexed())
3984 VT = ST->getMemoryVT();
3985 if (!TLI.isIndexedStoreLegal(ISD::PRE_INC, VT) &&
3986 !TLI.isIndexedStoreLegal(ISD::PRE_DEC, VT))
3988 Ptr = ST->getBasePtr();
3993 // If the pointer is not an add/sub, or if it doesn't have multiple uses, bail
3994 // out. There is no reason to make this a preinc/predec.
3995 if ((Ptr.getOpcode() != ISD::ADD && Ptr.getOpcode() != ISD::SUB) ||
3996 Ptr.Val->hasOneUse())
3999 // Ask the target to do addressing mode selection.
4002 ISD::MemIndexedMode AM = ISD::UNINDEXED;
4003 if (!TLI.getPreIndexedAddressParts(N, BasePtr, Offset, AM, DAG))
4005 // Don't create a indexed load / store with zero offset.
4006 if (isa<ConstantSDNode>(Offset) &&
4007 cast<ConstantSDNode>(Offset)->getValue() == 0)
4010 // Try turning it into a pre-indexed load / store except when:
4011 // 1) The new base ptr is a frame index.
4012 // 2) If N is a store and the new base ptr is either the same as or is a
4013 // predecessor of the value being stored.
4014 // 3) Another use of old base ptr is a predecessor of N. If ptr is folded
4015 // that would create a cycle.
4016 // 4) All uses are load / store ops that use it as old base ptr.
4018 // Check #1. Preinc'ing a frame index would require copying the stack pointer
4019 // (plus the implicit offset) to a register to preinc anyway.
4020 if (isa<FrameIndexSDNode>(BasePtr))
4025 SDOperand Val = cast<StoreSDNode>(N)->getValue();
4026 if (Val == BasePtr || BasePtr.Val->isPredecessor(Val.Val))
4030 // Now check for #3 and #4.
4031 bool RealUse = false;
4032 for (SDNode::use_iterator I = Ptr.Val->use_begin(),
4033 E = Ptr.Val->use_end(); I != E; ++I) {
4037 if (Use->isPredecessor(N))
4040 if (!((Use->getOpcode() == ISD::LOAD &&
4041 cast<LoadSDNode>(Use)->getBasePtr() == Ptr) ||
4042 (Use->getOpcode() == ISD::STORE &&
4043 cast<StoreSDNode>(Use)->getBasePtr() == Ptr)))
4051 Result = DAG.getIndexedLoad(SDOperand(N,0), BasePtr, Offset, AM);
4053 Result = DAG.getIndexedStore(SDOperand(N,0), BasePtr, Offset, AM);
4056 DOUT << "\nReplacing.4 "; DEBUG(N->dump(&DAG));
4057 DOUT << "\nWith: "; DEBUG(Result.Val->dump(&DAG));
4059 WorkListRemover DeadNodes(*this);
4061 DAG.ReplaceAllUsesOfValueWith(SDOperand(N, 0), Result.getValue(0),
4063 DAG.ReplaceAllUsesOfValueWith(SDOperand(N, 1), Result.getValue(2),
4066 DAG.ReplaceAllUsesOfValueWith(SDOperand(N, 0), Result.getValue(1),
4070 // Finally, since the node is now dead, remove it from the graph.
4073 // Replace the uses of Ptr with uses of the updated base value.
4074 DAG.ReplaceAllUsesOfValueWith(Ptr, Result.getValue(isLoad ? 1 : 0),
4076 removeFromWorkList(Ptr.Val);
4077 DAG.DeleteNode(Ptr.Val);
4082 /// CombineToPostIndexedLoadStore - Try combine a load / store with a
4083 /// add / sub of the base pointer node into a post-indexed load / store.
4084 /// The transformation folded the add / subtract into the new indexed
4085 /// load / store effectively and all of its uses are redirected to the
4086 /// new load / store.
4087 bool DAGCombiner::CombineToPostIndexedLoadStore(SDNode *N) {
4094 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
4095 if (LD->isIndexed())
4097 VT = LD->getMemoryVT();
4098 if (!TLI.isIndexedLoadLegal(ISD::POST_INC, VT) &&
4099 !TLI.isIndexedLoadLegal(ISD::POST_DEC, VT))
4101 Ptr = LD->getBasePtr();
4102 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
4103 if (ST->isIndexed())
4105 VT = ST->getMemoryVT();
4106 if (!TLI.isIndexedStoreLegal(ISD::POST_INC, VT) &&
4107 !TLI.isIndexedStoreLegal(ISD::POST_DEC, VT))
4109 Ptr = ST->getBasePtr();
4114 if (Ptr.Val->hasOneUse())
4117 for (SDNode::use_iterator I = Ptr.Val->use_begin(),
4118 E = Ptr.Val->use_end(); I != E; ++I) {
4121 (Op->getOpcode() != ISD::ADD && Op->getOpcode() != ISD::SUB))
4126 ISD::MemIndexedMode AM = ISD::UNINDEXED;
4127 if (TLI.getPostIndexedAddressParts(N, Op, BasePtr, Offset, AM, DAG)) {
4129 std::swap(BasePtr, Offset);
4132 // Don't create a indexed load / store with zero offset.
4133 if (isa<ConstantSDNode>(Offset) &&
4134 cast<ConstantSDNode>(Offset)->getValue() == 0)
4137 // Try turning it into a post-indexed load / store except when
4138 // 1) All uses are load / store ops that use it as base ptr.
4139 // 2) Op must be independent of N, i.e. Op is neither a predecessor
4140 // nor a successor of N. Otherwise, if Op is folded that would
4144 bool TryNext = false;
4145 for (SDNode::use_iterator II = BasePtr.Val->use_begin(),
4146 EE = BasePtr.Val->use_end(); II != EE; ++II) {
4151 // If all the uses are load / store addresses, then don't do the
4153 if (Use->getOpcode() == ISD::ADD || Use->getOpcode() == ISD::SUB){
4154 bool RealUse = false;
4155 for (SDNode::use_iterator III = Use->use_begin(),
4156 EEE = Use->use_end(); III != EEE; ++III) {
4157 SDNode *UseUse = *III;
4158 if (!((UseUse->getOpcode() == ISD::LOAD &&
4159 cast<LoadSDNode>(UseUse)->getBasePtr().Val == Use) ||
4160 (UseUse->getOpcode() == ISD::STORE &&
4161 cast<StoreSDNode>(UseUse)->getBasePtr().Val == Use)))
4175 if (!Op->isPredecessor(N) && !N->isPredecessor(Op)) {
4176 SDOperand Result = isLoad
4177 ? DAG.getIndexedLoad(SDOperand(N,0), BasePtr, Offset, AM)
4178 : DAG.getIndexedStore(SDOperand(N,0), BasePtr, Offset, AM);
4181 DOUT << "\nReplacing.5 "; DEBUG(N->dump(&DAG));
4182 DOUT << "\nWith: "; DEBUG(Result.Val->dump(&DAG));
4184 WorkListRemover DeadNodes(*this);
4186 DAG.ReplaceAllUsesOfValueWith(SDOperand(N, 0), Result.getValue(0),
4188 DAG.ReplaceAllUsesOfValueWith(SDOperand(N, 1), Result.getValue(2),
4191 DAG.ReplaceAllUsesOfValueWith(SDOperand(N, 0), Result.getValue(1),
4195 // Finally, since the node is now dead, remove it from the graph.
4198 // Replace the uses of Use with uses of the updated base value.
4199 DAG.ReplaceAllUsesOfValueWith(SDOperand(Op, 0),
4200 Result.getValue(isLoad ? 1 : 0),
4202 removeFromWorkList(Op);
4211 /// InferAlignment - If we can infer some alignment information from this
4212 /// pointer, return it.
4213 static unsigned InferAlignment(SDOperand Ptr, SelectionDAG &DAG) {
4214 // If this is a direct reference to a stack slot, use information about the
4215 // stack slot's alignment.
4216 int FrameIdx = 1 << 31;
4217 int64_t FrameOffset = 0;
4218 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Ptr)) {
4219 FrameIdx = FI->getIndex();
4220 } else if (Ptr.getOpcode() == ISD::ADD &&
4221 isa<ConstantSDNode>(Ptr.getOperand(1)) &&
4222 isa<FrameIndexSDNode>(Ptr.getOperand(0))) {
4223 FrameIdx = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
4224 FrameOffset = Ptr.getConstantOperandVal(1);
4227 if (FrameIdx != (1 << 31)) {
4228 // FIXME: Handle FI+CST.
4229 const MachineFrameInfo &MFI = *DAG.getMachineFunction().getFrameInfo();
4230 if (MFI.isFixedObjectIndex(FrameIdx)) {
4231 int64_t ObjectOffset = MFI.getObjectOffset(FrameIdx);
4233 // The alignment of the frame index can be determined from its offset from
4234 // the incoming frame position. If the frame object is at offset 32 and
4235 // the stack is guaranteed to be 16-byte aligned, then we know that the
4236 // object is 16-byte aligned.
4237 unsigned StackAlign = DAG.getTarget().getFrameInfo()->getStackAlignment();
4238 unsigned Align = MinAlign(ObjectOffset, StackAlign);
4240 // Finally, the frame object itself may have a known alignment. Factor
4241 // the alignment + offset into a new alignment. For example, if we know
4242 // the FI is 8 byte aligned, but the pointer is 4 off, we really have a
4243 // 4-byte alignment of the resultant pointer. Likewise align 4 + 4-byte
4244 // offset = 4-byte alignment, align 4 + 1-byte offset = align 1, etc.
4245 unsigned FIInfoAlign = MinAlign(MFI.getObjectAlignment(FrameIdx),
4247 return std::max(Align, FIInfoAlign);
4254 SDOperand DAGCombiner::visitLOAD(SDNode *N) {
4255 LoadSDNode *LD = cast<LoadSDNode>(N);
4256 SDOperand Chain = LD->getChain();
4257 SDOperand Ptr = LD->getBasePtr();
4259 // Try to infer better alignment information than the load already has.
4260 if (LD->isUnindexed()) {
4261 if (unsigned Align = InferAlignment(Ptr, DAG)) {
4262 if (Align > LD->getAlignment())
4263 return DAG.getExtLoad(LD->getExtensionType(), LD->getValueType(0),
4264 Chain, Ptr, LD->getSrcValue(),
4265 LD->getSrcValueOffset(), LD->getMemoryVT(),
4266 LD->isVolatile(), Align);
4271 // If load is not volatile and there are no uses of the loaded value (and
4272 // the updated indexed value in case of indexed loads), change uses of the
4273 // chain value into uses of the chain input (i.e. delete the dead load).
4274 if (!LD->isVolatile()) {
4275 if (N->getValueType(1) == MVT::Other) {
4277 if (N->hasNUsesOfValue(0, 0)) {
4278 // It's not safe to use the two value CombineTo variant here. e.g.
4279 // v1, chain2 = load chain1, loc
4280 // v2, chain3 = load chain2, loc
4282 // Now we replace use of chain2 with chain1. This makes the second load
4283 // isomorphic to the one we are deleting, and thus makes this load live.
4284 DOUT << "\nReplacing.6 "; DEBUG(N->dump(&DAG));
4285 DOUT << "\nWith chain: "; DEBUG(Chain.Val->dump(&DAG));
4287 WorkListRemover DeadNodes(*this);
4288 DAG.ReplaceAllUsesOfValueWith(SDOperand(N, 1), Chain, &DeadNodes);
4289 if (N->use_empty()) {
4290 removeFromWorkList(N);
4293 return SDOperand(N, 0); // Return N so it doesn't get rechecked!
4297 assert(N->getValueType(2) == MVT::Other && "Malformed indexed loads?");
4298 if (N->hasNUsesOfValue(0, 0) && N->hasNUsesOfValue(0, 1)) {
4299 SDOperand Undef = DAG.getNode(ISD::UNDEF, N->getValueType(0));
4300 DOUT << "\nReplacing.6 "; DEBUG(N->dump(&DAG));
4301 DOUT << "\nWith: "; DEBUG(Undef.Val->dump(&DAG));
4302 DOUT << " and 2 other values\n";
4303 WorkListRemover DeadNodes(*this);
4304 DAG.ReplaceAllUsesOfValueWith(SDOperand(N, 0), Undef, &DeadNodes);
4305 DAG.ReplaceAllUsesOfValueWith(SDOperand(N, 1),
4306 DAG.getNode(ISD::UNDEF, N->getValueType(1)),
4308 DAG.ReplaceAllUsesOfValueWith(SDOperand(N, 2), Chain, &DeadNodes);
4309 removeFromWorkList(N);
4311 return SDOperand(N, 0); // Return N so it doesn't get rechecked!
4316 // If this load is directly stored, replace the load value with the stored
4318 // TODO: Handle store large -> read small portion.
4319 // TODO: Handle TRUNCSTORE/LOADEXT
4320 if (LD->getExtensionType() == ISD::NON_EXTLOAD) {
4321 if (ISD::isNON_TRUNCStore(Chain.Val)) {
4322 StoreSDNode *PrevST = cast<StoreSDNode>(Chain);
4323 if (PrevST->getBasePtr() == Ptr &&
4324 PrevST->getValue().getValueType() == N->getValueType(0))
4325 return CombineTo(N, Chain.getOperand(1), Chain);
4330 // Walk up chain skipping non-aliasing memory nodes.
4331 SDOperand BetterChain = FindBetterChain(N, Chain);
4333 // If there is a better chain.
4334 if (Chain != BetterChain) {
4337 // Replace the chain to void dependency.
4338 if (LD->getExtensionType() == ISD::NON_EXTLOAD) {
4339 ReplLoad = DAG.getLoad(N->getValueType(0), BetterChain, Ptr,
4340 LD->getSrcValue(), LD->getSrcValueOffset(),
4341 LD->isVolatile(), LD->getAlignment());
4343 ReplLoad = DAG.getExtLoad(LD->getExtensionType(),
4344 LD->getValueType(0),
4345 BetterChain, Ptr, LD->getSrcValue(),
4346 LD->getSrcValueOffset(),
4349 LD->getAlignment());
4352 // Create token factor to keep old chain connected.
4353 SDOperand Token = DAG.getNode(ISD::TokenFactor, MVT::Other,
4354 Chain, ReplLoad.getValue(1));
4356 // Replace uses with load result and token factor. Don't add users
4358 return CombineTo(N, ReplLoad.getValue(0), Token, false);
4362 // Try transforming N to an indexed load.
4363 if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
4364 return SDOperand(N, 0);
4370 SDOperand DAGCombiner::visitSTORE(SDNode *N) {
4371 StoreSDNode *ST = cast<StoreSDNode>(N);
4372 SDOperand Chain = ST->getChain();
4373 SDOperand Value = ST->getValue();
4374 SDOperand Ptr = ST->getBasePtr();
4376 // Try to infer better alignment information than the store already has.
4377 if (ST->isUnindexed()) {
4378 if (unsigned Align = InferAlignment(Ptr, DAG)) {
4379 if (Align > ST->getAlignment())
4380 return DAG.getTruncStore(Chain, Value, Ptr, ST->getSrcValue(),
4381 ST->getSrcValueOffset(), ST->getMemoryVT(),
4382 ST->isVolatile(), Align);
4386 // If this is a store of a bit convert, store the input value if the
4387 // resultant store does not need a higher alignment than the original.
4388 if (Value.getOpcode() == ISD::BIT_CONVERT && !ST->isTruncatingStore() &&
4389 ST->isUnindexed()) {
4390 unsigned Align = ST->getAlignment();
4391 MVT::ValueType SVT = Value.getOperand(0).getValueType();
4392 unsigned OrigAlign = TLI.getTargetMachine().getTargetData()->
4393 getABITypeAlignment(MVT::getTypeForValueType(SVT));
4394 if (Align <= OrigAlign && TLI.isOperationLegal(ISD::STORE, SVT))
4395 return DAG.getStore(Chain, Value.getOperand(0), Ptr, ST->getSrcValue(),
4396 ST->getSrcValueOffset(), ST->isVolatile(), Align);
4399 // Turn 'store float 1.0, Ptr' -> 'store int 0x12345678, Ptr'
4400 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Value)) {
4401 if (Value.getOpcode() != ISD::TargetConstantFP) {
4403 switch (CFP->getValueType(0)) {
4404 default: assert(0 && "Unknown FP type");
4405 case MVT::f80: // We don't do this for these yet.
4410 if (!AfterLegalize || TLI.isTypeLegal(MVT::i32)) {
4411 Tmp = DAG.getConstant((uint32_t)CFP->getValueAPF().
4412 convertToAPInt().getZExtValue(), MVT::i32);
4413 return DAG.getStore(Chain, Tmp, Ptr, ST->getSrcValue(),
4414 ST->getSrcValueOffset(), ST->isVolatile(),
4415 ST->getAlignment());
4419 if (!AfterLegalize || TLI.isTypeLegal(MVT::i64)) {
4420 Tmp = DAG.getConstant(CFP->getValueAPF().convertToAPInt().
4421 getZExtValue(), MVT::i64);
4422 return DAG.getStore(Chain, Tmp, Ptr, ST->getSrcValue(),
4423 ST->getSrcValueOffset(), ST->isVolatile(),
4424 ST->getAlignment());
4425 } else if (TLI.isTypeLegal(MVT::i32)) {
4426 // Many FP stores are not made apparent until after legalize, e.g. for
4427 // argument passing. Since this is so common, custom legalize the
4428 // 64-bit integer store into two 32-bit stores.
4429 uint64_t Val = CFP->getValueAPF().convertToAPInt().getZExtValue();
4430 SDOperand Lo = DAG.getConstant(Val & 0xFFFFFFFF, MVT::i32);
4431 SDOperand Hi = DAG.getConstant(Val >> 32, MVT::i32);
4432 if (TLI.isBigEndian()) std::swap(Lo, Hi);
4434 int SVOffset = ST->getSrcValueOffset();
4435 unsigned Alignment = ST->getAlignment();
4436 bool isVolatile = ST->isVolatile();
4438 SDOperand St0 = DAG.getStore(Chain, Lo, Ptr, ST->getSrcValue(),
4439 ST->getSrcValueOffset(),
4440 isVolatile, ST->getAlignment());
4441 Ptr = DAG.getNode(ISD::ADD, Ptr.getValueType(), Ptr,
4442 DAG.getConstant(4, Ptr.getValueType()));
4444 Alignment = MinAlign(Alignment, 4U);
4445 SDOperand St1 = DAG.getStore(Chain, Hi, Ptr, ST->getSrcValue(),
4446 SVOffset, isVolatile, Alignment);
4447 return DAG.getNode(ISD::TokenFactor, MVT::Other, St0, St1);
4455 // Walk up chain skipping non-aliasing memory nodes.
4456 SDOperand BetterChain = FindBetterChain(N, Chain);
4458 // If there is a better chain.
4459 if (Chain != BetterChain) {
4460 // Replace the chain to avoid dependency.
4461 SDOperand ReplStore;
4462 if (ST->isTruncatingStore()) {
4463 ReplStore = DAG.getTruncStore(BetterChain, Value, Ptr,
4464 ST->getSrcValue(),ST->getSrcValueOffset(),
4466 ST->isVolatile(), ST->getAlignment());
4468 ReplStore = DAG.getStore(BetterChain, Value, Ptr,
4469 ST->getSrcValue(), ST->getSrcValueOffset(),
4470 ST->isVolatile(), ST->getAlignment());
4473 // Create token to keep both nodes around.
4475 DAG.getNode(ISD::TokenFactor, MVT::Other, Chain, ReplStore);
4477 // Don't add users to work list.
4478 return CombineTo(N, Token, false);
4482 // Try transforming N to an indexed store.
4483 if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
4484 return SDOperand(N, 0);
4486 // FIXME: is there such a thing as a truncating indexed store?
4487 if (ST->isTruncatingStore() && ST->isUnindexed() &&
4488 MVT::isInteger(Value.getValueType())) {
4489 // See if we can simplify the input to this truncstore with knowledge that
4490 // only the low bits are being used. For example:
4491 // "truncstore (or (shl x, 8), y), i8" -> "truncstore y, i8"
4493 GetDemandedBits(Value,
4494 APInt::getLowBitsSet(Value.getValueSizeInBits(),
4495 MVT::getSizeInBits(ST->getMemoryVT())));
4496 AddToWorkList(Value.Val);
4498 return DAG.getTruncStore(Chain, Shorter, Ptr, ST->getSrcValue(),
4499 ST->getSrcValueOffset(), ST->getMemoryVT(),
4500 ST->isVolatile(), ST->getAlignment());
4502 // Otherwise, see if we can simplify the operation with
4503 // SimplifyDemandedBits, which only works if the value has a single use.
4504 if (SimplifyDemandedBits(Value, MVT::getIntVTBitMask(ST->getMemoryVT())))
4505 return SDOperand(N, 0);
4508 // If this is a load followed by a store to the same location, then the store
4510 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Value)) {
4511 if (Ld->getBasePtr() == Ptr && ST->getMemoryVT() == Ld->getMemoryVT() &&
4512 ST->isUnindexed() && !ST->isVolatile() &&
4513 // There can't be any side effects between the load and store, such as
4515 Chain.reachesChainWithoutSideEffects(SDOperand(Ld, 1))) {
4516 // The store is dead, remove it.
4521 // If this is an FP_ROUND or TRUNC followed by a store, fold this into a
4522 // truncating store. We can do this even if this is already a truncstore.
4523 if ((Value.getOpcode() == ISD::FP_ROUND || Value.getOpcode() == ISD::TRUNCATE)
4524 && TLI.isTypeLegal(Value.getOperand(0).getValueType()) &&
4525 Value.Val->hasOneUse() && ST->isUnindexed() &&
4526 TLI.isTruncStoreLegal(Value.getOperand(0).getValueType(),
4527 ST->getMemoryVT())) {
4528 return DAG.getTruncStore(Chain, Value.getOperand(0), Ptr, ST->getSrcValue(),
4529 ST->getSrcValueOffset(), ST->getMemoryVT(),
4530 ST->isVolatile(), ST->getAlignment());
4536 SDOperand DAGCombiner::visitINSERT_VECTOR_ELT(SDNode *N) {
4537 SDOperand InVec = N->getOperand(0);
4538 SDOperand InVal = N->getOperand(1);
4539 SDOperand EltNo = N->getOperand(2);
4541 // If the invec is a BUILD_VECTOR and if EltNo is a constant, build a new
4542 // vector with the inserted element.
4543 if (InVec.getOpcode() == ISD::BUILD_VECTOR && isa<ConstantSDNode>(EltNo)) {
4544 unsigned Elt = cast<ConstantSDNode>(EltNo)->getValue();
4545 SmallVector<SDOperand, 8> Ops(InVec.Val->op_begin(), InVec.Val->op_end());
4546 if (Elt < Ops.size())
4548 return DAG.getNode(ISD::BUILD_VECTOR, InVec.getValueType(),
4549 &Ops[0], Ops.size());
4555 SDOperand DAGCombiner::visitEXTRACT_VECTOR_ELT(SDNode *N) {
4556 SDOperand InVec = N->getOperand(0);
4557 SDOperand EltNo = N->getOperand(1);
4559 // (vextract (v4f32 s2v (f32 load $addr)), 0) -> (f32 load $addr)
4560 // (vextract (v4i32 bc (v4f32 s2v (f32 load $addr))), 0) -> (i32 load $addr)
4561 if (isa<ConstantSDNode>(EltNo)) {
4562 unsigned Elt = cast<ConstantSDNode>(EltNo)->getValue();
4563 bool NewLoad = false;
4565 MVT::ValueType VT = InVec.getValueType();
4566 MVT::ValueType EVT = MVT::getVectorElementType(VT);
4567 MVT::ValueType LVT = EVT;
4568 unsigned NumElts = MVT::getVectorNumElements(VT);
4569 if (InVec.getOpcode() == ISD::BIT_CONVERT) {
4570 MVT::ValueType BCVT = InVec.getOperand(0).getValueType();
4571 if (!MVT::isVector(BCVT) ||
4572 NumElts != MVT::getVectorNumElements(BCVT))
4574 InVec = InVec.getOperand(0);
4575 EVT = MVT::getVectorElementType(BCVT);
4578 if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR &&
4579 InVec.getOperand(0).getValueType() == EVT &&
4580 ISD::isNormalLoad(InVec.getOperand(0).Val) &&
4581 InVec.getOperand(0).hasOneUse()) {
4582 LoadSDNode *LN0 = cast<LoadSDNode>(InVec.getOperand(0));
4583 unsigned Align = LN0->getAlignment();
4585 // Check the resultant load doesn't need a higher alignment than the
4587 unsigned NewAlign = TLI.getTargetMachine().getTargetData()->
4588 getABITypeAlignment(MVT::getTypeForValueType(LVT));
4589 if (!TLI.isOperationLegal(ISD::LOAD, LVT) || NewAlign > Align)
4594 return DAG.getLoad(LVT, LN0->getChain(), LN0->getBasePtr(),
4595 LN0->getSrcValue(), LN0->getSrcValueOffset(),
4596 LN0->isVolatile(), Align);
4604 SDOperand DAGCombiner::visitBUILD_VECTOR(SDNode *N) {
4605 unsigned NumInScalars = N->getNumOperands();
4606 MVT::ValueType VT = N->getValueType(0);
4607 unsigned NumElts = MVT::getVectorNumElements(VT);
4608 MVT::ValueType EltType = MVT::getVectorElementType(VT);
4610 // Check to see if this is a BUILD_VECTOR of a bunch of EXTRACT_VECTOR_ELT
4611 // operations. If so, and if the EXTRACT_VECTOR_ELT vector inputs come from
4612 // at most two distinct vectors, turn this into a shuffle node.
4613 SDOperand VecIn1, VecIn2;
4614 for (unsigned i = 0; i != NumInScalars; ++i) {
4615 // Ignore undef inputs.
4616 if (N->getOperand(i).getOpcode() == ISD::UNDEF) continue;
4618 // If this input is something other than a EXTRACT_VECTOR_ELT with a
4619 // constant index, bail out.
4620 if (N->getOperand(i).getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
4621 !isa<ConstantSDNode>(N->getOperand(i).getOperand(1))) {
4622 VecIn1 = VecIn2 = SDOperand(0, 0);
4626 // If the input vector type disagrees with the result of the build_vector,
4627 // we can't make a shuffle.
4628 SDOperand ExtractedFromVec = N->getOperand(i).getOperand(0);
4629 if (ExtractedFromVec.getValueType() != VT) {
4630 VecIn1 = VecIn2 = SDOperand(0, 0);
4634 // Otherwise, remember this. We allow up to two distinct input vectors.
4635 if (ExtractedFromVec == VecIn1 || ExtractedFromVec == VecIn2)
4638 if (VecIn1.Val == 0) {
4639 VecIn1 = ExtractedFromVec;
4640 } else if (VecIn2.Val == 0) {
4641 VecIn2 = ExtractedFromVec;
4644 VecIn1 = VecIn2 = SDOperand(0, 0);
4649 // If everything is good, we can make a shuffle operation.
4651 SmallVector<SDOperand, 8> BuildVecIndices;
4652 for (unsigned i = 0; i != NumInScalars; ++i) {
4653 if (N->getOperand(i).getOpcode() == ISD::UNDEF) {
4654 BuildVecIndices.push_back(DAG.getNode(ISD::UNDEF, TLI.getPointerTy()));
4658 SDOperand Extract = N->getOperand(i);
4660 // If extracting from the first vector, just use the index directly.
4661 if (Extract.getOperand(0) == VecIn1) {
4662 BuildVecIndices.push_back(Extract.getOperand(1));
4666 // Otherwise, use InIdx + VecSize
4667 unsigned Idx = cast<ConstantSDNode>(Extract.getOperand(1))->getValue();
4668 BuildVecIndices.push_back(DAG.getIntPtrConstant(Idx+NumInScalars));
4671 // Add count and size info.
4672 MVT::ValueType BuildVecVT = MVT::getVectorType(TLI.getPointerTy(), NumElts);
4674 // Return the new VECTOR_SHUFFLE node.
4680 // Use an undef build_vector as input for the second operand.
4681 std::vector<SDOperand> UnOps(NumInScalars,
4682 DAG.getNode(ISD::UNDEF,
4684 Ops[1] = DAG.getNode(ISD::BUILD_VECTOR, VT,
4685 &UnOps[0], UnOps.size());
4686 AddToWorkList(Ops[1].Val);
4688 Ops[2] = DAG.getNode(ISD::BUILD_VECTOR, BuildVecVT,
4689 &BuildVecIndices[0], BuildVecIndices.size());
4690 return DAG.getNode(ISD::VECTOR_SHUFFLE, VT, Ops, 3);
4696 SDOperand DAGCombiner::visitCONCAT_VECTORS(SDNode *N) {
4697 // TODO: Check to see if this is a CONCAT_VECTORS of a bunch of
4698 // EXTRACT_SUBVECTOR operations. If so, and if the EXTRACT_SUBVECTOR vector
4699 // inputs come from at most two distinct vectors, turn this into a shuffle
4702 // If we only have one input vector, we don't need to do any concatenation.
4703 if (N->getNumOperands() == 1) {
4704 return N->getOperand(0);
4710 SDOperand DAGCombiner::visitVECTOR_SHUFFLE(SDNode *N) {
4711 SDOperand ShufMask = N->getOperand(2);
4712 unsigned NumElts = ShufMask.getNumOperands();
4714 // If the shuffle mask is an identity operation on the LHS, return the LHS.
4715 bool isIdentity = true;
4716 for (unsigned i = 0; i != NumElts; ++i) {
4717 if (ShufMask.getOperand(i).getOpcode() != ISD::UNDEF &&
4718 cast<ConstantSDNode>(ShufMask.getOperand(i))->getValue() != i) {
4723 if (isIdentity) return N->getOperand(0);
4725 // If the shuffle mask is an identity operation on the RHS, return the RHS.
4727 for (unsigned i = 0; i != NumElts; ++i) {
4728 if (ShufMask.getOperand(i).getOpcode() != ISD::UNDEF &&
4729 cast<ConstantSDNode>(ShufMask.getOperand(i))->getValue() != i+NumElts) {
4734 if (isIdentity) return N->getOperand(1);
4736 // Check if the shuffle is a unary shuffle, i.e. one of the vectors is not
4738 bool isUnary = true;
4739 bool isSplat = true;
4741 unsigned BaseIdx = 0;
4742 for (unsigned i = 0; i != NumElts; ++i)
4743 if (ShufMask.getOperand(i).getOpcode() != ISD::UNDEF) {
4744 unsigned Idx = cast<ConstantSDNode>(ShufMask.getOperand(i))->getValue();
4745 int V = (Idx < NumElts) ? 0 : 1;
4759 SDOperand N0 = N->getOperand(0);
4760 SDOperand N1 = N->getOperand(1);
4761 // Normalize unary shuffle so the RHS is undef.
4762 if (isUnary && VecNum == 1)
4765 // If it is a splat, check if the argument vector is a build_vector with
4766 // all scalar elements the same.
4770 // If this is a bit convert that changes the element type of the vector but
4771 // not the number of vector elements, look through it. Be careful not to
4772 // look though conversions that change things like v4f32 to v2f64.
4773 if (V->getOpcode() == ISD::BIT_CONVERT) {
4774 SDOperand ConvInput = V->getOperand(0);
4775 if (MVT::getVectorNumElements(ConvInput.getValueType()) == NumElts)
4779 if (V->getOpcode() == ISD::BUILD_VECTOR) {
4780 unsigned NumElems = V->getNumOperands();
4781 if (NumElems > BaseIdx) {
4783 bool AllSame = true;
4784 for (unsigned i = 0; i != NumElems; ++i) {
4785 if (V->getOperand(i).getOpcode() != ISD::UNDEF) {
4786 Base = V->getOperand(i);
4790 // Splat of <u, u, u, u>, return <u, u, u, u>
4793 for (unsigned i = 0; i != NumElems; ++i) {
4794 if (V->getOperand(i) != Base) {
4799 // Splat of <x, x, x, x>, return <x, x, x, x>
4806 // If it is a unary or the LHS and the RHS are the same node, turn the RHS
4808 if (isUnary || N0 == N1) {
4809 // Check the SHUFFLE mask, mapping any inputs from the 2nd operand into the
4811 SmallVector<SDOperand, 8> MappedOps;
4812 for (unsigned i = 0; i != NumElts; ++i) {
4813 if (ShufMask.getOperand(i).getOpcode() == ISD::UNDEF ||
4814 cast<ConstantSDNode>(ShufMask.getOperand(i))->getValue() < NumElts) {
4815 MappedOps.push_back(ShufMask.getOperand(i));
4818 cast<ConstantSDNode>(ShufMask.getOperand(i))->getValue() - NumElts;
4819 MappedOps.push_back(DAG.getConstant(NewIdx, MVT::i32));
4822 ShufMask = DAG.getNode(ISD::BUILD_VECTOR, ShufMask.getValueType(),
4823 &MappedOps[0], MappedOps.size());
4824 AddToWorkList(ShufMask.Val);
4825 return DAG.getNode(ISD::VECTOR_SHUFFLE, N->getValueType(0),
4827 DAG.getNode(ISD::UNDEF, N->getValueType(0)),
4834 /// XformToShuffleWithZero - Returns a vector_shuffle if it able to transform
4835 /// an AND to a vector_shuffle with the destination vector and a zero vector.
4836 /// e.g. AND V, <0xffffffff, 0, 0xffffffff, 0>. ==>
4837 /// vector_shuffle V, Zero, <0, 4, 2, 4>
4838 SDOperand DAGCombiner::XformToShuffleWithZero(SDNode *N) {
4839 SDOperand LHS = N->getOperand(0);
4840 SDOperand RHS = N->getOperand(1);
4841 if (N->getOpcode() == ISD::AND) {
4842 if (RHS.getOpcode() == ISD::BIT_CONVERT)
4843 RHS = RHS.getOperand(0);
4844 if (RHS.getOpcode() == ISD::BUILD_VECTOR) {
4845 std::vector<SDOperand> IdxOps;
4846 unsigned NumOps = RHS.getNumOperands();
4847 unsigned NumElts = NumOps;
4848 MVT::ValueType EVT = MVT::getVectorElementType(RHS.getValueType());
4849 for (unsigned i = 0; i != NumElts; ++i) {
4850 SDOperand Elt = RHS.getOperand(i);
4851 if (!isa<ConstantSDNode>(Elt))
4853 else if (cast<ConstantSDNode>(Elt)->isAllOnesValue())
4854 IdxOps.push_back(DAG.getConstant(i, EVT));
4855 else if (cast<ConstantSDNode>(Elt)->isNullValue())
4856 IdxOps.push_back(DAG.getConstant(NumElts, EVT));
4861 // Let's see if the target supports this vector_shuffle.
4862 if (!TLI.isVectorClearMaskLegal(IdxOps, EVT, DAG))
4865 // Return the new VECTOR_SHUFFLE node.
4866 MVT::ValueType VT = MVT::getVectorType(EVT, NumElts);
4867 std::vector<SDOperand> Ops;
4868 LHS = DAG.getNode(ISD::BIT_CONVERT, VT, LHS);
4870 AddToWorkList(LHS.Val);
4871 std::vector<SDOperand> ZeroOps(NumElts, DAG.getConstant(0, EVT));
4872 Ops.push_back(DAG.getNode(ISD::BUILD_VECTOR, VT,
4873 &ZeroOps[0], ZeroOps.size()));
4874 Ops.push_back(DAG.getNode(ISD::BUILD_VECTOR, VT,
4875 &IdxOps[0], IdxOps.size()));
4876 SDOperand Result = DAG.getNode(ISD::VECTOR_SHUFFLE, VT,
4877 &Ops[0], Ops.size());
4878 if (VT != LHS.getValueType()) {
4879 Result = DAG.getNode(ISD::BIT_CONVERT, LHS.getValueType(), Result);
4887 /// SimplifyVBinOp - Visit a binary vector operation, like ADD.
4888 SDOperand DAGCombiner::SimplifyVBinOp(SDNode *N) {
4889 // After legalize, the target may be depending on adds and other
4890 // binary ops to provide legal ways to construct constants or other
4891 // things. Simplifying them may result in a loss of legality.
4892 if (AfterLegalize) return SDOperand();
4894 MVT::ValueType VT = N->getValueType(0);
4895 assert(MVT::isVector(VT) && "SimplifyVBinOp only works on vectors!");
4897 MVT::ValueType EltType = MVT::getVectorElementType(VT);
4898 SDOperand LHS = N->getOperand(0);
4899 SDOperand RHS = N->getOperand(1);
4900 SDOperand Shuffle = XformToShuffleWithZero(N);
4901 if (Shuffle.Val) return Shuffle;
4903 // If the LHS and RHS are BUILD_VECTOR nodes, see if we can constant fold
4905 if (LHS.getOpcode() == ISD::BUILD_VECTOR &&
4906 RHS.getOpcode() == ISD::BUILD_VECTOR) {
4907 SmallVector<SDOperand, 8> Ops;
4908 for (unsigned i = 0, e = LHS.getNumOperands(); i != e; ++i) {
4909 SDOperand LHSOp = LHS.getOperand(i);
4910 SDOperand RHSOp = RHS.getOperand(i);
4911 // If these two elements can't be folded, bail out.
4912 if ((LHSOp.getOpcode() != ISD::UNDEF &&
4913 LHSOp.getOpcode() != ISD::Constant &&
4914 LHSOp.getOpcode() != ISD::ConstantFP) ||
4915 (RHSOp.getOpcode() != ISD::UNDEF &&
4916 RHSOp.getOpcode() != ISD::Constant &&
4917 RHSOp.getOpcode() != ISD::ConstantFP))
4919 // Can't fold divide by zero.
4920 if (N->getOpcode() == ISD::SDIV || N->getOpcode() == ISD::UDIV ||
4921 N->getOpcode() == ISD::FDIV) {
4922 if ((RHSOp.getOpcode() == ISD::Constant &&
4923 cast<ConstantSDNode>(RHSOp.Val)->isNullValue()) ||
4924 (RHSOp.getOpcode() == ISD::ConstantFP &&
4925 cast<ConstantFPSDNode>(RHSOp.Val)->getValueAPF().isZero()))
4928 Ops.push_back(DAG.getNode(N->getOpcode(), EltType, LHSOp, RHSOp));
4929 AddToWorkList(Ops.back().Val);
4930 assert((Ops.back().getOpcode() == ISD::UNDEF ||
4931 Ops.back().getOpcode() == ISD::Constant ||
4932 Ops.back().getOpcode() == ISD::ConstantFP) &&
4933 "Scalar binop didn't fold!");
4936 if (Ops.size() == LHS.getNumOperands()) {
4937 MVT::ValueType VT = LHS.getValueType();
4938 return DAG.getNode(ISD::BUILD_VECTOR, VT, &Ops[0], Ops.size());
4945 SDOperand DAGCombiner::SimplifySelect(SDOperand N0, SDOperand N1, SDOperand N2){
4946 assert(N0.getOpcode() ==ISD::SETCC && "First argument must be a SetCC node!");
4948 SDOperand SCC = SimplifySelectCC(N0.getOperand(0), N0.getOperand(1), N1, N2,
4949 cast<CondCodeSDNode>(N0.getOperand(2))->get());
4950 // If we got a simplified select_cc node back from SimplifySelectCC, then
4951 // break it down into a new SETCC node, and a new SELECT node, and then return
4952 // the SELECT node, since we were called with a SELECT node.
4954 // Check to see if we got a select_cc back (to turn into setcc/select).
4955 // Otherwise, just return whatever node we got back, like fabs.
4956 if (SCC.getOpcode() == ISD::SELECT_CC) {
4957 SDOperand SETCC = DAG.getNode(ISD::SETCC, N0.getValueType(),
4958 SCC.getOperand(0), SCC.getOperand(1),
4960 AddToWorkList(SETCC.Val);
4961 return DAG.getNode(ISD::SELECT, SCC.getValueType(), SCC.getOperand(2),
4962 SCC.getOperand(3), SETCC);
4969 /// SimplifySelectOps - Given a SELECT or a SELECT_CC node, where LHS and RHS
4970 /// are the two values being selected between, see if we can simplify the
4971 /// select. Callers of this should assume that TheSelect is deleted if this
4972 /// returns true. As such, they should return the appropriate thing (e.g. the
4973 /// node) back to the top-level of the DAG combiner loop to avoid it being
4976 bool DAGCombiner::SimplifySelectOps(SDNode *TheSelect, SDOperand LHS,
4979 // If this is a select from two identical things, try to pull the operation
4980 // through the select.
4981 if (LHS.getOpcode() == RHS.getOpcode() && LHS.hasOneUse() && RHS.hasOneUse()){
4982 // If this is a load and the token chain is identical, replace the select
4983 // of two loads with a load through a select of the address to load from.
4984 // This triggers in things like "select bool X, 10.0, 123.0" after the FP
4985 // constants have been dropped into the constant pool.
4986 if (LHS.getOpcode() == ISD::LOAD &&
4987 // Token chains must be identical.
4988 LHS.getOperand(0) == RHS.getOperand(0)) {
4989 LoadSDNode *LLD = cast<LoadSDNode>(LHS);
4990 LoadSDNode *RLD = cast<LoadSDNode>(RHS);
4992 // If this is an EXTLOAD, the VT's must match.
4993 if (LLD->getMemoryVT() == RLD->getMemoryVT()) {
4994 // FIXME: this conflates two src values, discarding one. This is not
4995 // the right thing to do, but nothing uses srcvalues now. When they do,
4996 // turn SrcValue into a list of locations.
4998 if (TheSelect->getOpcode() == ISD::SELECT) {
4999 // Check that the condition doesn't reach either load. If so, folding
5000 // this will induce a cycle into the DAG.
5001 if (!LLD->isPredecessor(TheSelect->getOperand(0).Val) &&
5002 !RLD->isPredecessor(TheSelect->getOperand(0).Val)) {
5003 Addr = DAG.getNode(ISD::SELECT, LLD->getBasePtr().getValueType(),
5004 TheSelect->getOperand(0), LLD->getBasePtr(),
5008 // Check that the condition doesn't reach either load. If so, folding
5009 // this will induce a cycle into the DAG.
5010 if (!LLD->isPredecessor(TheSelect->getOperand(0).Val) &&
5011 !RLD->isPredecessor(TheSelect->getOperand(0).Val) &&
5012 !LLD->isPredecessor(TheSelect->getOperand(1).Val) &&
5013 !RLD->isPredecessor(TheSelect->getOperand(1).Val)) {
5014 Addr = DAG.getNode(ISD::SELECT_CC, LLD->getBasePtr().getValueType(),
5015 TheSelect->getOperand(0),
5016 TheSelect->getOperand(1),
5017 LLD->getBasePtr(), RLD->getBasePtr(),
5018 TheSelect->getOperand(4));
5024 if (LLD->getExtensionType() == ISD::NON_EXTLOAD)
5025 Load = DAG.getLoad(TheSelect->getValueType(0), LLD->getChain(),
5026 Addr,LLD->getSrcValue(),
5027 LLD->getSrcValueOffset(),
5029 LLD->getAlignment());
5031 Load = DAG.getExtLoad(LLD->getExtensionType(),
5032 TheSelect->getValueType(0),
5033 LLD->getChain(), Addr, LLD->getSrcValue(),
5034 LLD->getSrcValueOffset(),
5037 LLD->getAlignment());
5039 // Users of the select now use the result of the load.
5040 CombineTo(TheSelect, Load);
5042 // Users of the old loads now use the new load's chain. We know the
5043 // old-load value is dead now.
5044 CombineTo(LHS.Val, Load.getValue(0), Load.getValue(1));
5045 CombineTo(RHS.Val, Load.getValue(0), Load.getValue(1));
5055 SDOperand DAGCombiner::SimplifySelectCC(SDOperand N0, SDOperand N1,
5056 SDOperand N2, SDOperand N3,
5057 ISD::CondCode CC, bool NotExtCompare) {
5059 MVT::ValueType VT = N2.getValueType();
5060 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.Val);
5061 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2.Val);
5062 ConstantSDNode *N3C = dyn_cast<ConstantSDNode>(N3.Val);
5064 // Determine if the condition we're dealing with is constant
5065 SDOperand SCC = SimplifySetCC(TLI.getSetCCResultTy(), N0, N1, CC, false);
5066 if (SCC.Val) AddToWorkList(SCC.Val);
5067 ConstantSDNode *SCCC = dyn_cast_or_null<ConstantSDNode>(SCC.Val);
5069 // fold select_cc true, x, y -> x
5070 if (SCCC && SCCC->getValue())
5072 // fold select_cc false, x, y -> y
5073 if (SCCC && SCCC->getValue() == 0)
5076 // Check to see if we can simplify the select into an fabs node
5077 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N1)) {
5078 // Allow either -0.0 or 0.0
5079 if (CFP->getValueAPF().isZero()) {
5080 // select (setg[te] X, +/-0.0), X, fneg(X) -> fabs
5081 if ((CC == ISD::SETGE || CC == ISD::SETGT) &&
5082 N0 == N2 && N3.getOpcode() == ISD::FNEG &&
5083 N2 == N3.getOperand(0))
5084 return DAG.getNode(ISD::FABS, VT, N0);
5086 // select (setl[te] X, +/-0.0), fneg(X), X -> fabs
5087 if ((CC == ISD::SETLT || CC == ISD::SETLE) &&
5088 N0 == N3 && N2.getOpcode() == ISD::FNEG &&
5089 N2.getOperand(0) == N3)
5090 return DAG.getNode(ISD::FABS, VT, N3);
5094 // Check to see if we can perform the "gzip trick", transforming
5095 // select_cc setlt X, 0, A, 0 -> and (sra X, size(X)-1), A
5096 if (N1C && N3C && N3C->isNullValue() && CC == ISD::SETLT &&
5097 MVT::isInteger(N0.getValueType()) &&
5098 MVT::isInteger(N2.getValueType()) &&
5099 (N1C->isNullValue() || // (a < 0) ? b : 0
5100 (N1C->getValue() == 1 && N0 == N2))) { // (a < 1) ? a : 0
5101 MVT::ValueType XType = N0.getValueType();
5102 MVT::ValueType AType = N2.getValueType();
5103 if (XType >= AType) {
5104 // and (sra X, size(X)-1, A) -> "and (srl X, C2), A" iff A is a
5105 // single-bit constant.
5106 if (N2C && ((N2C->getValue() & (N2C->getValue()-1)) == 0)) {
5107 unsigned ShCtV = Log2_64(N2C->getValue());
5108 ShCtV = MVT::getSizeInBits(XType)-ShCtV-1;
5109 SDOperand ShCt = DAG.getConstant(ShCtV, TLI.getShiftAmountTy());
5110 SDOperand Shift = DAG.getNode(ISD::SRL, XType, N0, ShCt);
5111 AddToWorkList(Shift.Val);
5112 if (XType > AType) {
5113 Shift = DAG.getNode(ISD::TRUNCATE, AType, Shift);
5114 AddToWorkList(Shift.Val);
5116 return DAG.getNode(ISD::AND, AType, Shift, N2);
5118 SDOperand Shift = DAG.getNode(ISD::SRA, XType, N0,
5119 DAG.getConstant(MVT::getSizeInBits(XType)-1,
5120 TLI.getShiftAmountTy()));
5121 AddToWorkList(Shift.Val);
5122 if (XType > AType) {
5123 Shift = DAG.getNode(ISD::TRUNCATE, AType, Shift);
5124 AddToWorkList(Shift.Val);
5126 return DAG.getNode(ISD::AND, AType, Shift, N2);
5130 // fold select C, 16, 0 -> shl C, 4
5131 if (N2C && N3C && N3C->isNullValue() && isPowerOf2_64(N2C->getValue()) &&
5132 TLI.getSetCCResultContents() == TargetLowering::ZeroOrOneSetCCResult) {
5134 // If the caller doesn't want us to simplify this into a zext of a compare,
5136 if (NotExtCompare && N2C->getValue() == 1)
5139 // Get a SetCC of the condition
5140 // FIXME: Should probably make sure that setcc is legal if we ever have a
5141 // target where it isn't.
5142 SDOperand Temp, SCC;
5143 // cast from setcc result type to select result type
5144 if (AfterLegalize) {
5145 SCC = DAG.getSetCC(TLI.getSetCCResultTy(), N0, N1, CC);
5146 if (N2.getValueType() < SCC.getValueType())
5147 Temp = DAG.getZeroExtendInReg(SCC, N2.getValueType());
5149 Temp = DAG.getNode(ISD::ZERO_EXTEND, N2.getValueType(), SCC);
5151 SCC = DAG.getSetCC(MVT::i1, N0, N1, CC);
5152 Temp = DAG.getNode(ISD::ZERO_EXTEND, N2.getValueType(), SCC);
5154 AddToWorkList(SCC.Val);
5155 AddToWorkList(Temp.Val);
5157 if (N2C->getValue() == 1)
5159 // shl setcc result by log2 n2c
5160 return DAG.getNode(ISD::SHL, N2.getValueType(), Temp,
5161 DAG.getConstant(Log2_64(N2C->getValue()),
5162 TLI.getShiftAmountTy()));
5165 // Check to see if this is the equivalent of setcc
5166 // FIXME: Turn all of these into setcc if setcc if setcc is legal
5167 // otherwise, go ahead with the folds.
5168 if (0 && N3C && N3C->isNullValue() && N2C && (N2C->getValue() == 1ULL)) {
5169 MVT::ValueType XType = N0.getValueType();
5170 if (TLI.isOperationLegal(ISD::SETCC, TLI.getSetCCResultTy())) {
5171 SDOperand Res = DAG.getSetCC(TLI.getSetCCResultTy(), N0, N1, CC);
5172 if (Res.getValueType() != VT)
5173 Res = DAG.getNode(ISD::ZERO_EXTEND, VT, Res);
5177 // seteq X, 0 -> srl (ctlz X, log2(size(X)))
5178 if (N1C && N1C->isNullValue() && CC == ISD::SETEQ &&
5179 TLI.isOperationLegal(ISD::CTLZ, XType)) {
5180 SDOperand Ctlz = DAG.getNode(ISD::CTLZ, XType, N0);
5181 return DAG.getNode(ISD::SRL, XType, Ctlz,
5182 DAG.getConstant(Log2_32(MVT::getSizeInBits(XType)),
5183 TLI.getShiftAmountTy()));
5185 // setgt X, 0 -> srl (and (-X, ~X), size(X)-1)
5186 if (N1C && N1C->isNullValue() && CC == ISD::SETGT) {
5187 SDOperand NegN0 = DAG.getNode(ISD::SUB, XType, DAG.getConstant(0, XType),
5189 SDOperand NotN0 = DAG.getNode(ISD::XOR, XType, N0,
5190 DAG.getConstant(~0ULL, XType));
5191 return DAG.getNode(ISD::SRL, XType,
5192 DAG.getNode(ISD::AND, XType, NegN0, NotN0),
5193 DAG.getConstant(MVT::getSizeInBits(XType)-1,
5194 TLI.getShiftAmountTy()));
5196 // setgt X, -1 -> xor (srl (X, size(X)-1), 1)
5197 if (N1C && N1C->isAllOnesValue() && CC == ISD::SETGT) {
5198 SDOperand Sign = DAG.getNode(ISD::SRL, XType, N0,
5199 DAG.getConstant(MVT::getSizeInBits(XType)-1,
5200 TLI.getShiftAmountTy()));
5201 return DAG.getNode(ISD::XOR, XType, Sign, DAG.getConstant(1, XType));
5205 // Check to see if this is an integer abs. select_cc setl[te] X, 0, -X, X ->
5206 // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
5207 if (N1C && N1C->isNullValue() && (CC == ISD::SETLT || CC == ISD::SETLE) &&
5208 N0 == N3 && N2.getOpcode() == ISD::SUB && N0 == N2.getOperand(1) &&
5209 N2.getOperand(0) == N1 && MVT::isInteger(N0.getValueType())) {
5210 MVT::ValueType XType = N0.getValueType();
5211 SDOperand Shift = DAG.getNode(ISD::SRA, XType, N0,
5212 DAG.getConstant(MVT::getSizeInBits(XType)-1,
5213 TLI.getShiftAmountTy()));
5214 SDOperand Add = DAG.getNode(ISD::ADD, XType, N0, Shift);
5215 AddToWorkList(Shift.Val);
5216 AddToWorkList(Add.Val);
5217 return DAG.getNode(ISD::XOR, XType, Add, Shift);
5219 // Check to see if this is an integer abs. select_cc setgt X, -1, X, -X ->
5220 // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
5221 if (N1C && N1C->isAllOnesValue() && CC == ISD::SETGT &&
5222 N0 == N2 && N3.getOpcode() == ISD::SUB && N0 == N3.getOperand(1)) {
5223 if (ConstantSDNode *SubC = dyn_cast<ConstantSDNode>(N3.getOperand(0))) {
5224 MVT::ValueType XType = N0.getValueType();
5225 if (SubC->isNullValue() && MVT::isInteger(XType)) {
5226 SDOperand Shift = DAG.getNode(ISD::SRA, XType, N0,
5227 DAG.getConstant(MVT::getSizeInBits(XType)-1,
5228 TLI.getShiftAmountTy()));
5229 SDOperand Add = DAG.getNode(ISD::ADD, XType, N0, Shift);
5230 AddToWorkList(Shift.Val);
5231 AddToWorkList(Add.Val);
5232 return DAG.getNode(ISD::XOR, XType, Add, Shift);
5240 /// SimplifySetCC - This is a stub for TargetLowering::SimplifySetCC.
5241 SDOperand DAGCombiner::SimplifySetCC(MVT::ValueType VT, SDOperand N0,
5242 SDOperand N1, ISD::CondCode Cond,
5243 bool foldBooleans) {
5244 TargetLowering::DAGCombinerInfo
5245 DagCombineInfo(DAG, !AfterLegalize, false, this);
5246 return TLI.SimplifySetCC(VT, N0, N1, Cond, foldBooleans, DagCombineInfo);
5249 /// BuildSDIVSequence - Given an ISD::SDIV node expressing a divide by constant,
5250 /// return a DAG expression to select that will generate the same value by
5251 /// multiplying by a magic number. See:
5252 /// <http://the.wall.riscom.net/books/proc/ppc/cwg/code2.html>
5253 SDOperand DAGCombiner::BuildSDIV(SDNode *N) {
5254 std::vector<SDNode*> Built;
5255 SDOperand S = TLI.BuildSDIV(N, DAG, &Built);
5257 for (std::vector<SDNode*>::iterator ii = Built.begin(), ee = Built.end();
5263 /// BuildUDIVSequence - Given an ISD::UDIV node expressing a divide by constant,
5264 /// return a DAG expression to select that will generate the same value by
5265 /// multiplying by a magic number. See:
5266 /// <http://the.wall.riscom.net/books/proc/ppc/cwg/code2.html>
5267 SDOperand DAGCombiner::BuildUDIV(SDNode *N) {
5268 std::vector<SDNode*> Built;
5269 SDOperand S = TLI.BuildUDIV(N, DAG, &Built);
5271 for (std::vector<SDNode*>::iterator ii = Built.begin(), ee = Built.end();
5277 /// FindBaseOffset - Return true if base is known not to alias with anything
5278 /// but itself. Provides base object and offset as results.
5279 static bool FindBaseOffset(SDOperand Ptr, SDOperand &Base, int64_t &Offset) {
5280 // Assume it is a primitive operation.
5281 Base = Ptr; Offset = 0;
5283 // If it's an adding a simple constant then integrate the offset.
5284 if (Base.getOpcode() == ISD::ADD) {
5285 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Base.getOperand(1))) {
5286 Base = Base.getOperand(0);
5287 Offset += C->getValue();
5291 // If it's any of the following then it can't alias with anything but itself.
5292 return isa<FrameIndexSDNode>(Base) ||
5293 isa<ConstantPoolSDNode>(Base) ||
5294 isa<GlobalAddressSDNode>(Base);
5297 /// isAlias - Return true if there is any possibility that the two addresses
5299 bool DAGCombiner::isAlias(SDOperand Ptr1, int64_t Size1,
5300 const Value *SrcValue1, int SrcValueOffset1,
5301 SDOperand Ptr2, int64_t Size2,
5302 const Value *SrcValue2, int SrcValueOffset2)
5304 // If they are the same then they must be aliases.
5305 if (Ptr1 == Ptr2) return true;
5307 // Gather base node and offset information.
5308 SDOperand Base1, Base2;
5309 int64_t Offset1, Offset2;
5310 bool KnownBase1 = FindBaseOffset(Ptr1, Base1, Offset1);
5311 bool KnownBase2 = FindBaseOffset(Ptr2, Base2, Offset2);
5313 // If they have a same base address then...
5314 if (Base1 == Base2) {
5315 // Check to see if the addresses overlap.
5316 return!((Offset1 + Size1) <= Offset2 || (Offset2 + Size2) <= Offset1);
5319 // If we know both bases then they can't alias.
5320 if (KnownBase1 && KnownBase2) return false;
5322 if (CombinerGlobalAA) {
5323 // Use alias analysis information.
5324 int64_t MinOffset = std::min(SrcValueOffset1, SrcValueOffset2);
5325 int64_t Overlap1 = Size1 + SrcValueOffset1 - MinOffset;
5326 int64_t Overlap2 = Size2 + SrcValueOffset2 - MinOffset;
5327 AliasAnalysis::AliasResult AAResult =
5328 AA.alias(SrcValue1, Overlap1, SrcValue2, Overlap2);
5329 if (AAResult == AliasAnalysis::NoAlias)
5333 // Otherwise we have to assume they alias.
5337 /// FindAliasInfo - Extracts the relevant alias information from the memory
5338 /// node. Returns true if the operand was a load.
5339 bool DAGCombiner::FindAliasInfo(SDNode *N,
5340 SDOperand &Ptr, int64_t &Size,
5341 const Value *&SrcValue, int &SrcValueOffset) {
5342 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
5343 Ptr = LD->getBasePtr();
5344 Size = MVT::getSizeInBits(LD->getMemoryVT()) >> 3;
5345 SrcValue = LD->getSrcValue();
5346 SrcValueOffset = LD->getSrcValueOffset();
5348 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
5349 Ptr = ST->getBasePtr();
5350 Size = MVT::getSizeInBits(ST->getMemoryVT()) >> 3;
5351 SrcValue = ST->getSrcValue();
5352 SrcValueOffset = ST->getSrcValueOffset();
5354 assert(0 && "FindAliasInfo expected a memory operand");
5360 /// GatherAllAliases - Walk up chain skipping non-aliasing memory nodes,
5361 /// looking for aliasing nodes and adding them to the Aliases vector.
5362 void DAGCombiner::GatherAllAliases(SDNode *N, SDOperand OriginalChain,
5363 SmallVector<SDOperand, 8> &Aliases) {
5364 SmallVector<SDOperand, 8> Chains; // List of chains to visit.
5365 std::set<SDNode *> Visited; // Visited node set.
5367 // Get alias information for node.
5370 const Value *SrcValue;
5372 bool IsLoad = FindAliasInfo(N, Ptr, Size, SrcValue, SrcValueOffset);
5375 Chains.push_back(OriginalChain);
5377 // Look at each chain and determine if it is an alias. If so, add it to the
5378 // aliases list. If not, then continue up the chain looking for the next
5380 while (!Chains.empty()) {
5381 SDOperand Chain = Chains.back();
5384 // Don't bother if we've been before.
5385 if (Visited.find(Chain.Val) != Visited.end()) continue;
5386 Visited.insert(Chain.Val);
5388 switch (Chain.getOpcode()) {
5389 case ISD::EntryToken:
5390 // Entry token is ideal chain operand, but handled in FindBetterChain.
5395 // Get alias information for Chain.
5398 const Value *OpSrcValue;
5399 int OpSrcValueOffset;
5400 bool IsOpLoad = FindAliasInfo(Chain.Val, OpPtr, OpSize,
5401 OpSrcValue, OpSrcValueOffset);
5403 // If chain is alias then stop here.
5404 if (!(IsLoad && IsOpLoad) &&
5405 isAlias(Ptr, Size, SrcValue, SrcValueOffset,
5406 OpPtr, OpSize, OpSrcValue, OpSrcValueOffset)) {
5407 Aliases.push_back(Chain);
5409 // Look further up the chain.
5410 Chains.push_back(Chain.getOperand(0));
5411 // Clean up old chain.
5412 AddToWorkList(Chain.Val);
5417 case ISD::TokenFactor:
5418 // We have to check each of the operands of the token factor, so we queue
5419 // then up. Adding the operands to the queue (stack) in reverse order
5420 // maintains the original order and increases the likelihood that getNode
5421 // will find a matching token factor (CSE.)
5422 for (unsigned n = Chain.getNumOperands(); n;)
5423 Chains.push_back(Chain.getOperand(--n));
5424 // Eliminate the token factor if we can.
5425 AddToWorkList(Chain.Val);
5429 // For all other instructions we will just have to take what we can get.
5430 Aliases.push_back(Chain);
5436 /// FindBetterChain - Walk up chain skipping non-aliasing memory nodes, looking
5437 /// for a better chain (aliasing node.)
5438 SDOperand DAGCombiner::FindBetterChain(SDNode *N, SDOperand OldChain) {
5439 SmallVector<SDOperand, 8> Aliases; // Ops for replacing token factor.
5441 // Accumulate all the aliases to this node.
5442 GatherAllAliases(N, OldChain, Aliases);
5444 if (Aliases.size() == 0) {
5445 // If no operands then chain to entry token.
5446 return DAG.getEntryNode();
5447 } else if (Aliases.size() == 1) {
5448 // If a single operand then chain to it. We don't need to revisit it.
5452 // Construct a custom tailored token factor.
5453 SDOperand NewChain = DAG.getNode(ISD::TokenFactor, MVT::Other,
5454 &Aliases[0], Aliases.size());
5456 // Make sure the old chain gets cleaned up.
5457 if (NewChain != OldChain) AddToWorkList(OldChain.Val);
5462 // SelectionDAG::Combine - This is the entry point for the file.
5464 void SelectionDAG::Combine(bool RunningAfterLegalize, AliasAnalysis &AA) {
5465 if (!RunningAfterLegalize && ViewDAGCombine1)
5467 if (RunningAfterLegalize && ViewDAGCombine2)
5469 /// run - This is the main entry point to this class.
5471 DAGCombiner(*this, AA).Run(RunningAfterLegalize);