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 // This pass is not a substitute for the LLVM IR instcombine pass. This pass is
14 // primarily intended to handle simplification opportunities that are implicit
15 // in the LLVM IR and exposed by the various codegen lowering phases.
17 //===----------------------------------------------------------------------===//
19 #define DEBUG_TYPE "dagcombine"
20 #include "llvm/CodeGen/SelectionDAG.h"
21 #include "llvm/DerivedTypes.h"
22 #include "llvm/LLVMContext.h"
23 #include "llvm/CodeGen/MachineFunction.h"
24 #include "llvm/CodeGen/MachineFrameInfo.h"
25 #include "llvm/CodeGen/PseudoSourceValue.h"
26 #include "llvm/Analysis/AliasAnalysis.h"
27 #include "llvm/Target/TargetData.h"
28 #include "llvm/Target/TargetFrameInfo.h"
29 #include "llvm/Target/TargetLowering.h"
30 #include "llvm/Target/TargetMachine.h"
31 #include "llvm/Target/TargetOptions.h"
32 #include "llvm/ADT/SmallPtrSet.h"
33 #include "llvm/ADT/Statistic.h"
34 #include "llvm/Support/CommandLine.h"
35 #include "llvm/Support/Debug.h"
36 #include "llvm/Support/ErrorHandling.h"
37 #include "llvm/Support/MathExtras.h"
38 #include "llvm/Support/raw_ostream.h"
42 STATISTIC(NodesCombined , "Number of dag nodes combined");
43 STATISTIC(PreIndexedNodes , "Number of pre-indexed nodes created");
44 STATISTIC(PostIndexedNodes, "Number of post-indexed nodes created");
45 STATISTIC(OpsNarrowed , "Number of load/op/store narrowed");
49 CombinerAA("combiner-alias-analysis", cl::Hidden,
50 cl::desc("Turn on alias analysis during testing"));
53 CombinerGlobalAA("combiner-global-alias-analysis", cl::Hidden,
54 cl::desc("Include global information in alias analysis"));
56 //------------------------------ DAGCombiner ---------------------------------//
60 const TargetLowering &TLI;
62 CodeGenOpt::Level OptLevel;
66 // Worklist of all of the nodes that need to be simplified.
67 std::vector<SDNode*> WorkList;
69 // AA - Used for DAG load/store alias analysis.
72 /// AddUsersToWorkList - When an instruction is simplified, add all users of
73 /// the instruction to the work lists because they might get more simplified
76 void AddUsersToWorkList(SDNode *N) {
77 for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
82 /// visit - call the node-specific routine that knows how to fold each
83 /// particular type of node.
84 SDValue visit(SDNode *N);
87 /// AddToWorkList - Add to the work list making sure it's instance is at the
88 /// the back (next to be processed.)
89 void AddToWorkList(SDNode *N) {
90 removeFromWorkList(N);
91 WorkList.push_back(N);
94 /// removeFromWorkList - remove all instances of N from the worklist.
96 void removeFromWorkList(SDNode *N) {
97 WorkList.erase(std::remove(WorkList.begin(), WorkList.end(), N),
101 SDValue CombineTo(SDNode *N, const SDValue *To, unsigned NumTo,
104 SDValue CombineTo(SDNode *N, SDValue Res, bool AddTo = true) {
105 return CombineTo(N, &Res, 1, AddTo);
108 SDValue CombineTo(SDNode *N, SDValue Res0, SDValue Res1,
110 SDValue To[] = { Res0, Res1 };
111 return CombineTo(N, To, 2, AddTo);
114 void CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO);
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(SDValue Op) {
122 unsigned BitWidth = Op.getValueType().getScalarType().getSizeInBits();
123 APInt Demanded = APInt::getAllOnesValue(BitWidth);
124 return SimplifyDemandedBits(Op, Demanded);
127 bool SimplifyDemandedBits(SDValue Op, const APInt &Demanded);
129 bool CombineToPreIndexedLoadStore(SDNode *N);
130 bool CombineToPostIndexedLoadStore(SDNode *N);
132 void ReplaceLoadWithPromotedLoad(SDNode *Load, SDNode *ExtLoad);
133 SDValue PromoteOperand(SDValue Op, EVT PVT, bool &Replace);
134 SDValue SExtPromoteOperand(SDValue Op, EVT PVT);
135 SDValue ZExtPromoteOperand(SDValue Op, EVT PVT);
136 SDValue PromoteIntBinOp(SDValue Op);
137 SDValue PromoteIntShiftOp(SDValue Op);
138 SDValue PromoteExtend(SDValue Op);
139 bool PromoteLoad(SDValue Op);
141 /// combine - call the node-specific routine that knows how to fold each
142 /// particular type of node. If that doesn't do anything, try the
143 /// target-specific DAG combines.
144 SDValue combine(SDNode *N);
146 // Visitation implementation - Implement dag node combining for different
147 // node types. The semantics are as follows:
149 // SDValue.getNode() == 0 - No change was made
150 // SDValue.getNode() == N - N was replaced, is dead and has been handled.
151 // otherwise - N should be replaced by the returned Operand.
153 SDValue visitTokenFactor(SDNode *N);
154 SDValue visitMERGE_VALUES(SDNode *N);
155 SDValue visitADD(SDNode *N);
156 SDValue visitSUB(SDNode *N);
157 SDValue visitADDC(SDNode *N);
158 SDValue visitADDE(SDNode *N);
159 SDValue visitMUL(SDNode *N);
160 SDValue visitSDIV(SDNode *N);
161 SDValue visitUDIV(SDNode *N);
162 SDValue visitSREM(SDNode *N);
163 SDValue visitUREM(SDNode *N);
164 SDValue visitMULHU(SDNode *N);
165 SDValue visitMULHS(SDNode *N);
166 SDValue visitSMUL_LOHI(SDNode *N);
167 SDValue visitUMUL_LOHI(SDNode *N);
168 SDValue visitSDIVREM(SDNode *N);
169 SDValue visitUDIVREM(SDNode *N);
170 SDValue visitAND(SDNode *N);
171 SDValue visitOR(SDNode *N);
172 SDValue visitXOR(SDNode *N);
173 SDValue SimplifyVBinOp(SDNode *N);
174 SDValue visitSHL(SDNode *N);
175 SDValue visitSRA(SDNode *N);
176 SDValue visitSRL(SDNode *N);
177 SDValue visitCTLZ(SDNode *N);
178 SDValue visitCTTZ(SDNode *N);
179 SDValue visitCTPOP(SDNode *N);
180 SDValue visitSELECT(SDNode *N);
181 SDValue visitSELECT_CC(SDNode *N);
182 SDValue visitSETCC(SDNode *N);
183 SDValue visitSIGN_EXTEND(SDNode *N);
184 SDValue visitZERO_EXTEND(SDNode *N);
185 SDValue visitANY_EXTEND(SDNode *N);
186 SDValue visitSIGN_EXTEND_INREG(SDNode *N);
187 SDValue visitTRUNCATE(SDNode *N);
188 SDValue visitBIT_CONVERT(SDNode *N);
189 SDValue visitBUILD_PAIR(SDNode *N);
190 SDValue visitFADD(SDNode *N);
191 SDValue visitFSUB(SDNode *N);
192 SDValue visitFMUL(SDNode *N);
193 SDValue visitFDIV(SDNode *N);
194 SDValue visitFREM(SDNode *N);
195 SDValue visitFCOPYSIGN(SDNode *N);
196 SDValue visitSINT_TO_FP(SDNode *N);
197 SDValue visitUINT_TO_FP(SDNode *N);
198 SDValue visitFP_TO_SINT(SDNode *N);
199 SDValue visitFP_TO_UINT(SDNode *N);
200 SDValue visitFP_ROUND(SDNode *N);
201 SDValue visitFP_ROUND_INREG(SDNode *N);
202 SDValue visitFP_EXTEND(SDNode *N);
203 SDValue visitFNEG(SDNode *N);
204 SDValue visitFABS(SDNode *N);
205 SDValue visitBRCOND(SDNode *N);
206 SDValue visitBR_CC(SDNode *N);
207 SDValue visitLOAD(SDNode *N);
208 SDValue visitSTORE(SDNode *N);
209 SDValue visitINSERT_VECTOR_ELT(SDNode *N);
210 SDValue visitEXTRACT_VECTOR_ELT(SDNode *N);
211 SDValue visitBUILD_VECTOR(SDNode *N);
212 SDValue visitCONCAT_VECTORS(SDNode *N);
213 SDValue visitVECTOR_SHUFFLE(SDNode *N);
215 SDValue XformToShuffleWithZero(SDNode *N);
216 SDValue ReassociateOps(unsigned Opc, DebugLoc DL, SDValue LHS, SDValue RHS);
218 SDValue visitShiftByConstant(SDNode *N, unsigned Amt);
220 bool SimplifySelectOps(SDNode *SELECT, SDValue LHS, SDValue RHS);
221 SDValue SimplifyBinOpWithSameOpcodeHands(SDNode *N);
222 SDValue SimplifySelect(DebugLoc DL, SDValue N0, SDValue N1, SDValue N2);
223 SDValue SimplifySelectCC(DebugLoc DL, SDValue N0, SDValue N1, SDValue N2,
224 SDValue N3, ISD::CondCode CC,
225 bool NotExtCompare = false);
226 SDValue SimplifySetCC(EVT VT, SDValue N0, SDValue N1, ISD::CondCode Cond,
227 DebugLoc DL, bool foldBooleans = true);
228 SDValue SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp,
230 SDValue CombineConsecutiveLoads(SDNode *N, EVT VT);
231 SDValue ConstantFoldBIT_CONVERTofBUILD_VECTOR(SDNode *, EVT);
232 SDValue BuildSDIV(SDNode *N);
233 SDValue BuildUDIV(SDNode *N);
234 SDNode *MatchRotate(SDValue LHS, SDValue RHS, DebugLoc DL);
235 SDValue ReduceLoadWidth(SDNode *N);
236 SDValue ReduceLoadOpStoreWidth(SDNode *N);
238 SDValue GetDemandedBits(SDValue V, const APInt &Mask);
240 /// GatherAllAliases - Walk up chain skipping non-aliasing memory nodes,
241 /// looking for aliasing nodes and adding them to the Aliases vector.
242 void GatherAllAliases(SDNode *N, SDValue OriginalChain,
243 SmallVector<SDValue, 8> &Aliases);
245 /// isAlias - Return true if there is any possibility that the two addresses
247 bool isAlias(SDValue Ptr1, int64_t Size1,
248 const Value *SrcValue1, int SrcValueOffset1,
249 unsigned SrcValueAlign1,
250 SDValue Ptr2, int64_t Size2,
251 const Value *SrcValue2, int SrcValueOffset2,
252 unsigned SrcValueAlign2) const;
254 /// FindAliasInfo - Extracts the relevant alias information from the memory
255 /// node. Returns true if the operand was a load.
256 bool FindAliasInfo(SDNode *N,
257 SDValue &Ptr, int64_t &Size,
258 const Value *&SrcValue, int &SrcValueOffset,
259 unsigned &SrcValueAlignment) const;
261 /// FindBetterChain - Walk up chain skipping non-aliasing memory nodes,
262 /// looking for a better chain (aliasing node.)
263 SDValue FindBetterChain(SDNode *N, SDValue Chain);
266 DAGCombiner(SelectionDAG &D, AliasAnalysis &A, CodeGenOpt::Level OL)
267 : DAG(D), TLI(D.getTargetLoweringInfo()), Level(Unrestricted),
268 OptLevel(OL), LegalOperations(false), LegalTypes(false), AA(A) {}
270 /// Run - runs the dag combiner on all nodes in the work list
271 void Run(CombineLevel AtLevel);
273 SelectionDAG &getDAG() const { return DAG; }
275 /// getShiftAmountTy - Returns a type large enough to hold any valid
276 /// shift amount - before type legalization these can be huge.
277 EVT getShiftAmountTy() {
278 return LegalTypes ? TLI.getShiftAmountTy() : TLI.getPointerTy();
281 /// isTypeLegal - This method returns true if we are running before type
282 /// legalization or if the specified VT is legal.
283 bool isTypeLegal(const EVT &VT) {
284 if (!LegalTypes) return true;
285 return TLI.isTypeLegal(VT);
292 /// WorkListRemover - This class is a DAGUpdateListener that removes any deleted
293 /// nodes from the worklist.
294 class WorkListRemover : public SelectionDAG::DAGUpdateListener {
297 explicit WorkListRemover(DAGCombiner &dc) : DC(dc) {}
299 virtual void NodeDeleted(SDNode *N, SDNode *E) {
300 DC.removeFromWorkList(N);
303 virtual void NodeUpdated(SDNode *N) {
309 //===----------------------------------------------------------------------===//
310 // TargetLowering::DAGCombinerInfo implementation
311 //===----------------------------------------------------------------------===//
313 void TargetLowering::DAGCombinerInfo::AddToWorklist(SDNode *N) {
314 ((DAGCombiner*)DC)->AddToWorkList(N);
317 SDValue TargetLowering::DAGCombinerInfo::
318 CombineTo(SDNode *N, const std::vector<SDValue> &To, bool AddTo) {
319 return ((DAGCombiner*)DC)->CombineTo(N, &To[0], To.size(), AddTo);
322 SDValue TargetLowering::DAGCombinerInfo::
323 CombineTo(SDNode *N, SDValue Res, bool AddTo) {
324 return ((DAGCombiner*)DC)->CombineTo(N, Res, AddTo);
328 SDValue TargetLowering::DAGCombinerInfo::
329 CombineTo(SDNode *N, SDValue Res0, SDValue Res1, bool AddTo) {
330 return ((DAGCombiner*)DC)->CombineTo(N, Res0, Res1, AddTo);
333 void TargetLowering::DAGCombinerInfo::
334 CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) {
335 return ((DAGCombiner*)DC)->CommitTargetLoweringOpt(TLO);
338 //===----------------------------------------------------------------------===//
340 //===----------------------------------------------------------------------===//
342 /// isNegatibleForFree - Return 1 if we can compute the negated form of the
343 /// specified expression for the same cost as the expression itself, or 2 if we
344 /// can compute the negated form more cheaply than the expression itself.
345 static char isNegatibleForFree(SDValue Op, bool LegalOperations,
346 unsigned Depth = 0) {
347 // No compile time optimizations on this type.
348 if (Op.getValueType() == MVT::ppcf128)
351 // fneg is removable even if it has multiple uses.
352 if (Op.getOpcode() == ISD::FNEG) return 2;
354 // Don't allow anything with multiple uses.
355 if (!Op.hasOneUse()) return 0;
357 // Don't recurse exponentially.
358 if (Depth > 6) return 0;
360 switch (Op.getOpcode()) {
361 default: return false;
362 case ISD::ConstantFP:
363 // Don't invert constant FP values after legalize. The negated constant
364 // isn't necessarily legal.
365 return LegalOperations ? 0 : 1;
367 // FIXME: determine better conditions for this xform.
368 if (!UnsafeFPMath) return 0;
370 // fold (fsub (fadd A, B)) -> (fsub (fneg A), B)
371 if (char V = isNegatibleForFree(Op.getOperand(0), LegalOperations, Depth+1))
373 // fold (fneg (fadd A, B)) -> (fsub (fneg B), A)
374 return isNegatibleForFree(Op.getOperand(1), LegalOperations, Depth+1);
376 // We can't turn -(A-B) into B-A when we honor signed zeros.
377 if (!UnsafeFPMath) return 0;
379 // fold (fneg (fsub A, B)) -> (fsub B, A)
384 if (HonorSignDependentRoundingFPMath()) return 0;
386 // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y) or (fmul X, (fneg Y))
387 if (char V = isNegatibleForFree(Op.getOperand(0), LegalOperations, Depth+1))
390 return isNegatibleForFree(Op.getOperand(1), LegalOperations, Depth+1);
395 return isNegatibleForFree(Op.getOperand(0), LegalOperations, Depth+1);
399 /// GetNegatedExpression - If isNegatibleForFree returns true, this function
400 /// returns the newly negated expression.
401 static SDValue GetNegatedExpression(SDValue Op, SelectionDAG &DAG,
402 bool LegalOperations, unsigned Depth = 0) {
403 // fneg is removable even if it has multiple uses.
404 if (Op.getOpcode() == ISD::FNEG) return Op.getOperand(0);
406 // Don't allow anything with multiple uses.
407 assert(Op.hasOneUse() && "Unknown reuse!");
409 assert(Depth <= 6 && "GetNegatedExpression doesn't match isNegatibleForFree");
410 switch (Op.getOpcode()) {
411 default: llvm_unreachable("Unknown code");
412 case ISD::ConstantFP: {
413 APFloat V = cast<ConstantFPSDNode>(Op)->getValueAPF();
415 return DAG.getConstantFP(V, Op.getValueType());
418 // FIXME: determine better conditions for this xform.
419 assert(UnsafeFPMath);
421 // fold (fneg (fadd A, B)) -> (fsub (fneg A), B)
422 if (isNegatibleForFree(Op.getOperand(0), LegalOperations, Depth+1))
423 return DAG.getNode(ISD::FSUB, Op.getDebugLoc(), Op.getValueType(),
424 GetNegatedExpression(Op.getOperand(0), DAG,
425 LegalOperations, Depth+1),
427 // fold (fneg (fadd A, B)) -> (fsub (fneg B), A)
428 return DAG.getNode(ISD::FSUB, Op.getDebugLoc(), Op.getValueType(),
429 GetNegatedExpression(Op.getOperand(1), DAG,
430 LegalOperations, Depth+1),
433 // We can't turn -(A-B) into B-A when we honor signed zeros.
434 assert(UnsafeFPMath);
436 // fold (fneg (fsub 0, B)) -> B
437 if (ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(Op.getOperand(0)))
438 if (N0CFP->getValueAPF().isZero())
439 return Op.getOperand(1);
441 // fold (fneg (fsub A, B)) -> (fsub B, A)
442 return DAG.getNode(ISD::FSUB, Op.getDebugLoc(), Op.getValueType(),
443 Op.getOperand(1), Op.getOperand(0));
447 assert(!HonorSignDependentRoundingFPMath());
449 // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y)
450 if (isNegatibleForFree(Op.getOperand(0), LegalOperations, Depth+1))
451 return DAG.getNode(Op.getOpcode(), Op.getDebugLoc(), Op.getValueType(),
452 GetNegatedExpression(Op.getOperand(0), DAG,
453 LegalOperations, Depth+1),
456 // fold (fneg (fmul X, Y)) -> (fmul X, (fneg Y))
457 return DAG.getNode(Op.getOpcode(), Op.getDebugLoc(), Op.getValueType(),
459 GetNegatedExpression(Op.getOperand(1), DAG,
460 LegalOperations, Depth+1));
464 return DAG.getNode(Op.getOpcode(), Op.getDebugLoc(), Op.getValueType(),
465 GetNegatedExpression(Op.getOperand(0), DAG,
466 LegalOperations, Depth+1));
468 return DAG.getNode(ISD::FP_ROUND, Op.getDebugLoc(), Op.getValueType(),
469 GetNegatedExpression(Op.getOperand(0), DAG,
470 LegalOperations, Depth+1),
476 // isSetCCEquivalent - Return true if this node is a setcc, or is a select_cc
477 // that selects between the values 1 and 0, making it equivalent to a setcc.
478 // Also, set the incoming LHS, RHS, and CC references to the appropriate
479 // nodes based on the type of node we are checking. This simplifies life a
480 // bit for the callers.
481 static bool isSetCCEquivalent(SDValue N, SDValue &LHS, SDValue &RHS,
483 if (N.getOpcode() == ISD::SETCC) {
484 LHS = N.getOperand(0);
485 RHS = N.getOperand(1);
486 CC = N.getOperand(2);
489 if (N.getOpcode() == ISD::SELECT_CC &&
490 N.getOperand(2).getOpcode() == ISD::Constant &&
491 N.getOperand(3).getOpcode() == ISD::Constant &&
492 cast<ConstantSDNode>(N.getOperand(2))->getAPIntValue() == 1 &&
493 cast<ConstantSDNode>(N.getOperand(3))->isNullValue()) {
494 LHS = N.getOperand(0);
495 RHS = N.getOperand(1);
496 CC = N.getOperand(4);
502 // isOneUseSetCC - Return true if this is a SetCC-equivalent operation with only
503 // one use. If this is true, it allows the users to invert the operation for
504 // free when it is profitable to do so.
505 static bool isOneUseSetCC(SDValue N) {
507 if (isSetCCEquivalent(N, N0, N1, N2) && N.getNode()->hasOneUse())
512 SDValue DAGCombiner::ReassociateOps(unsigned Opc, DebugLoc DL,
513 SDValue N0, SDValue N1) {
514 EVT VT = N0.getValueType();
515 if (N0.getOpcode() == Opc && isa<ConstantSDNode>(N0.getOperand(1))) {
516 if (isa<ConstantSDNode>(N1)) {
517 // reassoc. (op (op x, c1), c2) -> (op x, (op c1, c2))
519 DAG.FoldConstantArithmetic(Opc, VT,
520 cast<ConstantSDNode>(N0.getOperand(1)),
521 cast<ConstantSDNode>(N1));
522 return DAG.getNode(Opc, DL, VT, N0.getOperand(0), OpNode);
523 } else if (N0.hasOneUse()) {
524 // reassoc. (op (op x, c1), y) -> (op (op x, y), c1) iff x+c1 has one use
525 SDValue OpNode = DAG.getNode(Opc, N0.getDebugLoc(), VT,
526 N0.getOperand(0), N1);
527 AddToWorkList(OpNode.getNode());
528 return DAG.getNode(Opc, DL, VT, OpNode, N0.getOperand(1));
532 if (N1.getOpcode() == Opc && isa<ConstantSDNode>(N1.getOperand(1))) {
533 if (isa<ConstantSDNode>(N0)) {
534 // reassoc. (op c2, (op x, c1)) -> (op x, (op c1, c2))
536 DAG.FoldConstantArithmetic(Opc, VT,
537 cast<ConstantSDNode>(N1.getOperand(1)),
538 cast<ConstantSDNode>(N0));
539 return DAG.getNode(Opc, DL, VT, N1.getOperand(0), OpNode);
540 } else if (N1.hasOneUse()) {
541 // reassoc. (op y, (op x, c1)) -> (op (op x, y), c1) iff x+c1 has one use
542 SDValue OpNode = DAG.getNode(Opc, N0.getDebugLoc(), VT,
543 N1.getOperand(0), N0);
544 AddToWorkList(OpNode.getNode());
545 return DAG.getNode(Opc, DL, VT, OpNode, N1.getOperand(1));
552 SDValue DAGCombiner::CombineTo(SDNode *N, const SDValue *To, unsigned NumTo,
554 assert(N->getNumValues() == NumTo && "Broken CombineTo call!");
556 DEBUG(dbgs() << "\nReplacing.1 ";
558 dbgs() << "\nWith: ";
559 To[0].getNode()->dump(&DAG);
560 dbgs() << " and " << NumTo-1 << " other values\n";
561 for (unsigned i = 0, e = NumTo; i != e; ++i)
562 assert((!To[i].getNode() ||
563 N->getValueType(i) == To[i].getValueType()) &&
564 "Cannot combine value to value of different type!"));
565 WorkListRemover DeadNodes(*this);
566 DAG.ReplaceAllUsesWith(N, To, &DeadNodes);
569 // Push the new nodes and any users onto the worklist
570 for (unsigned i = 0, e = NumTo; i != e; ++i) {
571 if (To[i].getNode()) {
572 AddToWorkList(To[i].getNode());
573 AddUsersToWorkList(To[i].getNode());
578 // Finally, if the node is now dead, remove it from the graph. The node
579 // may not be dead if the replacement process recursively simplified to
580 // something else needing this node.
581 if (N->use_empty()) {
582 // Nodes can be reintroduced into the worklist. Make sure we do not
583 // process a node that has been replaced.
584 removeFromWorkList(N);
586 // Finally, since the node is now dead, remove it from the graph.
589 return SDValue(N, 0);
593 CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) {
594 // Replace all uses. If any nodes become isomorphic to other nodes and
595 // are deleted, make sure to remove them from our worklist.
596 WorkListRemover DeadNodes(*this);
597 DAG.ReplaceAllUsesOfValueWith(TLO.Old, TLO.New, &DeadNodes);
599 // Push the new node and any (possibly new) users onto the worklist.
600 AddToWorkList(TLO.New.getNode());
601 AddUsersToWorkList(TLO.New.getNode());
603 // Finally, if the node is now dead, remove it from the graph. The node
604 // may not be dead if the replacement process recursively simplified to
605 // something else needing this node.
606 if (TLO.Old.getNode()->use_empty()) {
607 removeFromWorkList(TLO.Old.getNode());
609 // If the operands of this node are only used by the node, they will now
610 // be dead. Make sure to visit them first to delete dead nodes early.
611 for (unsigned i = 0, e = TLO.Old.getNode()->getNumOperands(); i != e; ++i)
612 if (TLO.Old.getNode()->getOperand(i).getNode()->hasOneUse())
613 AddToWorkList(TLO.Old.getNode()->getOperand(i).getNode());
615 DAG.DeleteNode(TLO.Old.getNode());
619 /// SimplifyDemandedBits - Check the specified integer node value to see if
620 /// it can be simplified or if things it uses can be simplified by bit
621 /// propagation. If so, return true.
622 bool DAGCombiner::SimplifyDemandedBits(SDValue Op, const APInt &Demanded) {
623 TargetLowering::TargetLoweringOpt TLO(DAG, LegalTypes, LegalOperations);
624 APInt KnownZero, KnownOne;
625 if (!TLI.SimplifyDemandedBits(Op, Demanded, KnownZero, KnownOne, TLO))
629 AddToWorkList(Op.getNode());
631 // Replace the old value with the new one.
633 DEBUG(dbgs() << "\nReplacing.2 ";
634 TLO.Old.getNode()->dump(&DAG);
635 dbgs() << "\nWith: ";
636 TLO.New.getNode()->dump(&DAG);
639 CommitTargetLoweringOpt(TLO);
643 void DAGCombiner::ReplaceLoadWithPromotedLoad(SDNode *Load, SDNode *ExtLoad) {
644 DebugLoc dl = Load->getDebugLoc();
645 EVT VT = Load->getValueType(0);
646 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, dl, VT, SDValue(ExtLoad, 0));
648 DEBUG(dbgs() << "\nReplacing.9 ";
650 dbgs() << "\nWith: ";
651 Trunc.getNode()->dump(&DAG);
653 WorkListRemover DeadNodes(*this);
654 DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 0), Trunc, &DeadNodes);
655 DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 1), SDValue(ExtLoad, 1),
657 removeFromWorkList(Load);
658 DAG.DeleteNode(Load);
659 AddToWorkList(Trunc.getNode());
662 SDValue DAGCombiner::PromoteOperand(SDValue Op, EVT PVT, bool &Replace) {
664 DebugLoc dl = Op.getDebugLoc();
665 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Op)) {
666 EVT MemVT = LD->getMemoryVT();
667 ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD)
668 ? (TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT) ? ISD::ZEXTLOAD : ISD::EXTLOAD)
669 : LD->getExtensionType();
671 return DAG.getExtLoad(ExtType, dl, PVT,
672 LD->getChain(), LD->getBasePtr(),
673 LD->getSrcValue(), LD->getSrcValueOffset(),
674 MemVT, LD->isVolatile(),
675 LD->isNonTemporal(), LD->getAlignment());
678 unsigned Opc = Op.getOpcode();
681 case ISD::AssertSext:
682 return DAG.getNode(ISD::AssertSext, dl, PVT,
683 SExtPromoteOperand(Op.getOperand(0), PVT),
685 case ISD::AssertZext:
686 return DAG.getNode(ISD::AssertZext, dl, PVT,
687 ZExtPromoteOperand(Op.getOperand(0), PVT),
689 case ISD::Constant: {
691 Op.getValueType().isByteSized() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
692 return DAG.getNode(ExtOpc, dl, PVT, Op);
696 if (!TLI.isOperationLegal(ISD::ANY_EXTEND, PVT))
698 return DAG.getNode(ISD::ANY_EXTEND, dl, PVT, Op);
701 SDValue DAGCombiner::SExtPromoteOperand(SDValue Op, EVT PVT) {
702 if (!TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, PVT))
704 EVT OldVT = Op.getValueType();
705 DebugLoc dl = Op.getDebugLoc();
706 bool Replace = false;
707 SDValue NewOp = PromoteOperand(Op, PVT, Replace);
708 if (NewOp.getNode() == 0)
710 AddToWorkList(NewOp.getNode());
713 ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode());
714 return DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, NewOp.getValueType(), NewOp,
715 DAG.getValueType(OldVT));
718 SDValue DAGCombiner::ZExtPromoteOperand(SDValue Op, EVT PVT) {
719 EVT OldVT = Op.getValueType();
720 DebugLoc dl = Op.getDebugLoc();
721 bool Replace = false;
722 SDValue NewOp = PromoteOperand(Op, PVT, Replace);
723 if (NewOp.getNode() == 0)
725 AddToWorkList(NewOp.getNode());
728 ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode());
729 return DAG.getZeroExtendInReg(NewOp, dl, OldVT);
732 /// PromoteIntBinOp - Promote the specified integer binary operation if the
733 /// target indicates it is beneficial. e.g. On x86, it's usually better to
734 /// promote i16 operations to i32 since i16 instructions are longer.
735 SDValue DAGCombiner::PromoteIntBinOp(SDValue Op) {
736 if (!LegalOperations)
739 EVT VT = Op.getValueType();
740 if (VT.isVector() || !VT.isInteger())
743 // If operation type is 'undesirable', e.g. i16 on x86, consider
745 unsigned Opc = Op.getOpcode();
746 if (TLI.isTypeDesirableForOp(Opc, VT))
750 // Consult target whether it is a good idea to promote this operation and
751 // what's the right type to promote it to.
752 if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
753 assert(PVT != VT && "Don't know what type to promote to!");
755 bool Replace0 = false;
756 SDValue N0 = Op.getOperand(0);
757 SDValue NN0 = PromoteOperand(N0, PVT, Replace0);
758 if (NN0.getNode() == 0)
761 bool Replace1 = false;
762 SDValue N1 = Op.getOperand(1);
763 SDValue NN1 = PromoteOperand(N1, PVT, Replace1);
764 if (NN1.getNode() == 0)
767 AddToWorkList(NN0.getNode());
768 AddToWorkList(NN1.getNode());
771 ReplaceLoadWithPromotedLoad(N0.getNode(), NN0.getNode());
773 ReplaceLoadWithPromotedLoad(N1.getNode(), NN1.getNode());
775 DEBUG(dbgs() << "\nPromoting ";
776 Op.getNode()->dump(&DAG));
777 DebugLoc dl = Op.getDebugLoc();
778 return DAG.getNode(ISD::TRUNCATE, dl, VT,
779 DAG.getNode(Opc, dl, PVT, NN0, NN1));
784 /// PromoteIntShiftOp - Promote the specified integer shift operation if the
785 /// target indicates it is beneficial. e.g. On x86, it's usually better to
786 /// promote i16 operations to i32 since i16 instructions are longer.
787 SDValue DAGCombiner::PromoteIntShiftOp(SDValue Op) {
788 if (!LegalOperations)
791 EVT VT = Op.getValueType();
792 if (VT.isVector() || !VT.isInteger())
795 // If operation type is 'undesirable', e.g. i16 on x86, consider
797 unsigned Opc = Op.getOpcode();
798 if (TLI.isTypeDesirableForOp(Opc, VT))
802 // Consult target whether it is a good idea to promote this operation and
803 // what's the right type to promote it to.
804 if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
805 assert(PVT != VT && "Don't know what type to promote to!");
807 bool Replace = false;
808 SDValue N0 = Op.getOperand(0);
810 N0 = SExtPromoteOperand(Op.getOperand(0), PVT);
811 else if (Opc == ISD::SRL)
812 N0 = ZExtPromoteOperand(Op.getOperand(0), PVT);
814 N0 = PromoteOperand(N0, PVT, Replace);
815 if (N0.getNode() == 0)
818 AddToWorkList(N0.getNode());
820 ReplaceLoadWithPromotedLoad(Op.getOperand(0).getNode(), N0.getNode());
822 DEBUG(dbgs() << "\nPromoting ";
823 Op.getNode()->dump(&DAG));
824 DebugLoc dl = Op.getDebugLoc();
825 return DAG.getNode(ISD::TRUNCATE, dl, VT,
826 DAG.getNode(Opc, dl, PVT, N0, Op.getOperand(1)));
831 SDValue DAGCombiner::PromoteExtend(SDValue Op) {
832 if (!LegalOperations)
835 EVT VT = Op.getValueType();
836 if (VT.isVector() || !VT.isInteger())
839 // If operation type is 'undesirable', e.g. i16 on x86, consider
841 unsigned Opc = Op.getOpcode();
842 if (TLI.isTypeDesirableForOp(Opc, VT))
846 // Consult target whether it is a good idea to promote this operation and
847 // what's the right type to promote it to.
848 if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
849 assert(PVT != VT && "Don't know what type to promote to!");
850 // fold (aext (aext x)) -> (aext x)
851 // fold (aext (zext x)) -> (zext x)
852 // fold (aext (sext x)) -> (sext x)
853 DEBUG(dbgs() << "\nPromoting ";
854 Op.getNode()->dump(&DAG));
855 return DAG.getNode(Op.getOpcode(), Op.getDebugLoc(), VT, Op.getOperand(0));
860 bool DAGCombiner::PromoteLoad(SDValue Op) {
861 if (!LegalOperations)
864 EVT VT = Op.getValueType();
865 if (VT.isVector() || !VT.isInteger())
868 // If operation type is 'undesirable', e.g. i16 on x86, consider
870 unsigned Opc = Op.getOpcode();
871 if (TLI.isTypeDesirableForOp(Opc, VT))
875 // Consult target whether it is a good idea to promote this operation and
876 // what's the right type to promote it to.
877 if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
878 assert(PVT != VT && "Don't know what type to promote to!");
880 DebugLoc dl = Op.getDebugLoc();
881 SDNode *N = Op.getNode();
882 LoadSDNode *LD = cast<LoadSDNode>(N);
883 EVT MemVT = LD->getMemoryVT();
884 ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD)
885 ? (TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT) ? ISD::ZEXTLOAD : ISD::EXTLOAD)
886 : LD->getExtensionType();
887 SDValue NewLD = DAG.getExtLoad(ExtType, dl, PVT,
888 LD->getChain(), LD->getBasePtr(),
889 LD->getSrcValue(), LD->getSrcValueOffset(),
890 MemVT, LD->isVolatile(),
891 LD->isNonTemporal(), LD->getAlignment());
892 SDValue Result = DAG.getNode(ISD::TRUNCATE, dl, VT, NewLD);
894 DEBUG(dbgs() << "\nPromoting ";
897 Result.getNode()->dump(&DAG);
899 WorkListRemover DeadNodes(*this);
900 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result, &DeadNodes);
901 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), NewLD.getValue(1), &DeadNodes);
902 removeFromWorkList(N);
904 AddToWorkList(Result.getNode());
911 //===----------------------------------------------------------------------===//
912 // Main DAG Combiner implementation
913 //===----------------------------------------------------------------------===//
915 void DAGCombiner::Run(CombineLevel AtLevel) {
916 // set the instance variables, so that the various visit routines may use it.
918 LegalOperations = Level >= NoIllegalOperations;
919 LegalTypes = Level >= NoIllegalTypes;
921 // Add all the dag nodes to the worklist.
922 WorkList.reserve(DAG.allnodes_size());
923 for (SelectionDAG::allnodes_iterator I = DAG.allnodes_begin(),
924 E = DAG.allnodes_end(); I != E; ++I)
925 WorkList.push_back(I);
927 // Create a dummy node (which is not added to allnodes), that adds a reference
928 // to the root node, preventing it from being deleted, and tracking any
929 // changes of the root.
930 HandleSDNode Dummy(DAG.getRoot());
932 // The root of the dag may dangle to deleted nodes until the dag combiner is
933 // done. Set it to null to avoid confusion.
934 DAG.setRoot(SDValue());
936 // while the worklist isn't empty, inspect the node on the end of it and
937 // try and combine it.
938 while (!WorkList.empty()) {
939 SDNode *N = WorkList.back();
942 // If N has no uses, it is dead. Make sure to revisit all N's operands once
943 // N is deleted from the DAG, since they too may now be dead or may have a
944 // reduced number of uses, allowing other xforms.
945 if (N->use_empty() && N != &Dummy) {
946 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
947 AddToWorkList(N->getOperand(i).getNode());
953 SDValue RV = combine(N);
955 if (RV.getNode() == 0)
960 // If we get back the same node we passed in, rather than a new node or
961 // zero, we know that the node must have defined multiple values and
962 // CombineTo was used. Since CombineTo takes care of the worklist
963 // mechanics for us, we have no work to do in this case.
964 if (RV.getNode() == N)
967 assert(N->getOpcode() != ISD::DELETED_NODE &&
968 RV.getNode()->getOpcode() != ISD::DELETED_NODE &&
969 "Node was deleted but visit returned new node!");
971 DEBUG(dbgs() << "\nReplacing.3 ";
973 dbgs() << "\nWith: ";
974 RV.getNode()->dump(&DAG);
976 WorkListRemover DeadNodes(*this);
977 if (N->getNumValues() == RV.getNode()->getNumValues())
978 DAG.ReplaceAllUsesWith(N, RV.getNode(), &DeadNodes);
980 assert(N->getValueType(0) == RV.getValueType() &&
981 N->getNumValues() == 1 && "Type mismatch");
983 DAG.ReplaceAllUsesWith(N, &OpV, &DeadNodes);
986 // Push the new node and any users onto the worklist
987 AddToWorkList(RV.getNode());
988 AddUsersToWorkList(RV.getNode());
990 // Add any uses of the old node to the worklist in case this node is the
991 // last one that uses them. They may become dead after this node is
993 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
994 AddToWorkList(N->getOperand(i).getNode());
996 // Finally, if the node is now dead, remove it from the graph. The node
997 // may not be dead if the replacement process recursively simplified to
998 // something else needing this node.
999 if (N->use_empty()) {
1000 // Nodes can be reintroduced into the worklist. Make sure we do not
1001 // process a node that has been replaced.
1002 removeFromWorkList(N);
1004 // Finally, since the node is now dead, remove it from the graph.
1009 // If the root changed (e.g. it was a dead load, update the root).
1010 DAG.setRoot(Dummy.getValue());
1013 SDValue DAGCombiner::visit(SDNode *N) {
1014 switch (N->getOpcode()) {
1016 case ISD::TokenFactor: return visitTokenFactor(N);
1017 case ISD::MERGE_VALUES: return visitMERGE_VALUES(N);
1018 case ISD::ADD: return visitADD(N);
1019 case ISD::SUB: return visitSUB(N);
1020 case ISD::ADDC: return visitADDC(N);
1021 case ISD::ADDE: return visitADDE(N);
1022 case ISD::MUL: return visitMUL(N);
1023 case ISD::SDIV: return visitSDIV(N);
1024 case ISD::UDIV: return visitUDIV(N);
1025 case ISD::SREM: return visitSREM(N);
1026 case ISD::UREM: return visitUREM(N);
1027 case ISD::MULHU: return visitMULHU(N);
1028 case ISD::MULHS: return visitMULHS(N);
1029 case ISD::SMUL_LOHI: return visitSMUL_LOHI(N);
1030 case ISD::UMUL_LOHI: return visitUMUL_LOHI(N);
1031 case ISD::SDIVREM: return visitSDIVREM(N);
1032 case ISD::UDIVREM: return visitUDIVREM(N);
1033 case ISD::AND: return visitAND(N);
1034 case ISD::OR: return visitOR(N);
1035 case ISD::XOR: return visitXOR(N);
1036 case ISD::SHL: return visitSHL(N);
1037 case ISD::SRA: return visitSRA(N);
1038 case ISD::SRL: return visitSRL(N);
1039 case ISD::CTLZ: return visitCTLZ(N);
1040 case ISD::CTTZ: return visitCTTZ(N);
1041 case ISD::CTPOP: return visitCTPOP(N);
1042 case ISD::SELECT: return visitSELECT(N);
1043 case ISD::SELECT_CC: return visitSELECT_CC(N);
1044 case ISD::SETCC: return visitSETCC(N);
1045 case ISD::SIGN_EXTEND: return visitSIGN_EXTEND(N);
1046 case ISD::ZERO_EXTEND: return visitZERO_EXTEND(N);
1047 case ISD::ANY_EXTEND: return visitANY_EXTEND(N);
1048 case ISD::SIGN_EXTEND_INREG: return visitSIGN_EXTEND_INREG(N);
1049 case ISD::TRUNCATE: return visitTRUNCATE(N);
1050 case ISD::BIT_CONVERT: return visitBIT_CONVERT(N);
1051 case ISD::BUILD_PAIR: return visitBUILD_PAIR(N);
1052 case ISD::FADD: return visitFADD(N);
1053 case ISD::FSUB: return visitFSUB(N);
1054 case ISD::FMUL: return visitFMUL(N);
1055 case ISD::FDIV: return visitFDIV(N);
1056 case ISD::FREM: return visitFREM(N);
1057 case ISD::FCOPYSIGN: return visitFCOPYSIGN(N);
1058 case ISD::SINT_TO_FP: return visitSINT_TO_FP(N);
1059 case ISD::UINT_TO_FP: return visitUINT_TO_FP(N);
1060 case ISD::FP_TO_SINT: return visitFP_TO_SINT(N);
1061 case ISD::FP_TO_UINT: return visitFP_TO_UINT(N);
1062 case ISD::FP_ROUND: return visitFP_ROUND(N);
1063 case ISD::FP_ROUND_INREG: return visitFP_ROUND_INREG(N);
1064 case ISD::FP_EXTEND: return visitFP_EXTEND(N);
1065 case ISD::FNEG: return visitFNEG(N);
1066 case ISD::FABS: return visitFABS(N);
1067 case ISD::BRCOND: return visitBRCOND(N);
1068 case ISD::BR_CC: return visitBR_CC(N);
1069 case ISD::LOAD: return visitLOAD(N);
1070 case ISD::STORE: return visitSTORE(N);
1071 case ISD::INSERT_VECTOR_ELT: return visitINSERT_VECTOR_ELT(N);
1072 case ISD::EXTRACT_VECTOR_ELT: return visitEXTRACT_VECTOR_ELT(N);
1073 case ISD::BUILD_VECTOR: return visitBUILD_VECTOR(N);
1074 case ISD::CONCAT_VECTORS: return visitCONCAT_VECTORS(N);
1075 case ISD::VECTOR_SHUFFLE: return visitVECTOR_SHUFFLE(N);
1080 SDValue DAGCombiner::combine(SDNode *N) {
1081 SDValue RV = visit(N);
1083 // If nothing happened, try a target-specific DAG combine.
1084 if (RV.getNode() == 0) {
1085 assert(N->getOpcode() != ISD::DELETED_NODE &&
1086 "Node was deleted but visit returned NULL!");
1088 if (N->getOpcode() >= ISD::BUILTIN_OP_END ||
1089 TLI.hasTargetDAGCombine((ISD::NodeType)N->getOpcode())) {
1091 // Expose the DAG combiner to the target combiner impls.
1092 TargetLowering::DAGCombinerInfo
1093 DagCombineInfo(DAG, !LegalTypes, !LegalOperations, false, this);
1095 RV = TLI.PerformDAGCombine(N, DagCombineInfo);
1099 // If nothing happened still, try promoting the operation.
1100 if (RV.getNode() == 0) {
1101 switch (N->getOpcode()) {
1109 RV = PromoteIntBinOp(SDValue(N, 0));
1114 RV = PromoteIntShiftOp(SDValue(N, 0));
1116 case ISD::SIGN_EXTEND:
1117 case ISD::ZERO_EXTEND:
1118 case ISD::ANY_EXTEND:
1119 RV = PromoteExtend(SDValue(N, 0));
1122 if (PromoteLoad(SDValue(N, 0)))
1128 // If N is a commutative binary node, try commuting it to enable more
1130 if (RV.getNode() == 0 &&
1131 SelectionDAG::isCommutativeBinOp(N->getOpcode()) &&
1132 N->getNumValues() == 1) {
1133 SDValue N0 = N->getOperand(0);
1134 SDValue N1 = N->getOperand(1);
1136 // Constant operands are canonicalized to RHS.
1137 if (isa<ConstantSDNode>(N0) || !isa<ConstantSDNode>(N1)) {
1138 SDValue Ops[] = { N1, N0 };
1139 SDNode *CSENode = DAG.getNodeIfExists(N->getOpcode(), N->getVTList(),
1142 return SDValue(CSENode, 0);
1149 /// getInputChainForNode - Given a node, return its input chain if it has one,
1150 /// otherwise return a null sd operand.
1151 static SDValue getInputChainForNode(SDNode *N) {
1152 if (unsigned NumOps = N->getNumOperands()) {
1153 if (N->getOperand(0).getValueType() == MVT::Other)
1154 return N->getOperand(0);
1155 else if (N->getOperand(NumOps-1).getValueType() == MVT::Other)
1156 return N->getOperand(NumOps-1);
1157 for (unsigned i = 1; i < NumOps-1; ++i)
1158 if (N->getOperand(i).getValueType() == MVT::Other)
1159 return N->getOperand(i);
1164 SDValue DAGCombiner::visitTokenFactor(SDNode *N) {
1165 // If N has two operands, where one has an input chain equal to the other,
1166 // the 'other' chain is redundant.
1167 if (N->getNumOperands() == 2) {
1168 if (getInputChainForNode(N->getOperand(0).getNode()) == N->getOperand(1))
1169 return N->getOperand(0);
1170 if (getInputChainForNode(N->getOperand(1).getNode()) == N->getOperand(0))
1171 return N->getOperand(1);
1174 SmallVector<SDNode *, 8> TFs; // List of token factors to visit.
1175 SmallVector<SDValue, 8> Ops; // Ops for replacing token factor.
1176 SmallPtrSet<SDNode*, 16> SeenOps;
1177 bool Changed = false; // If we should replace this token factor.
1179 // Start out with this token factor.
1182 // Iterate through token factors. The TFs grows when new token factors are
1184 for (unsigned i = 0; i < TFs.size(); ++i) {
1185 SDNode *TF = TFs[i];
1187 // Check each of the operands.
1188 for (unsigned i = 0, ie = TF->getNumOperands(); i != ie; ++i) {
1189 SDValue Op = TF->getOperand(i);
1191 switch (Op.getOpcode()) {
1192 case ISD::EntryToken:
1193 // Entry tokens don't need to be added to the list. They are
1198 case ISD::TokenFactor:
1199 if (Op.hasOneUse() &&
1200 std::find(TFs.begin(), TFs.end(), Op.getNode()) == TFs.end()) {
1201 // Queue up for processing.
1202 TFs.push_back(Op.getNode());
1203 // Clean up in case the token factor is removed.
1204 AddToWorkList(Op.getNode());
1211 // Only add if it isn't already in the list.
1212 if (SeenOps.insert(Op.getNode()))
1223 // If we've change things around then replace token factor.
1226 // The entry token is the only possible outcome.
1227 Result = DAG.getEntryNode();
1229 // New and improved token factor.
1230 Result = DAG.getNode(ISD::TokenFactor, N->getDebugLoc(),
1231 MVT::Other, &Ops[0], Ops.size());
1234 // Don't add users to work list.
1235 return CombineTo(N, Result, false);
1241 /// MERGE_VALUES can always be eliminated.
1242 SDValue DAGCombiner::visitMERGE_VALUES(SDNode *N) {
1243 WorkListRemover DeadNodes(*this);
1244 // Replacing results may cause a different MERGE_VALUES to suddenly
1245 // be CSE'd with N, and carry its uses with it. Iterate until no
1246 // uses remain, to ensure that the node can be safely deleted.
1248 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1249 DAG.ReplaceAllUsesOfValueWith(SDValue(N, i), N->getOperand(i),
1251 } while (!N->use_empty());
1252 removeFromWorkList(N);
1254 return SDValue(N, 0); // Return N so it doesn't get rechecked!
1258 SDValue combineShlAddConstant(DebugLoc DL, SDValue N0, SDValue N1,
1259 SelectionDAG &DAG) {
1260 EVT VT = N0.getValueType();
1261 SDValue N00 = N0.getOperand(0);
1262 SDValue N01 = N0.getOperand(1);
1263 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N01);
1265 if (N01C && N00.getOpcode() == ISD::ADD && N00.getNode()->hasOneUse() &&
1266 isa<ConstantSDNode>(N00.getOperand(1))) {
1267 // fold (add (shl (add x, c1), c2), ) -> (add (add (shl x, c2), c1<<c2), )
1268 N0 = DAG.getNode(ISD::ADD, N0.getDebugLoc(), VT,
1269 DAG.getNode(ISD::SHL, N00.getDebugLoc(), VT,
1270 N00.getOperand(0), N01),
1271 DAG.getNode(ISD::SHL, N01.getDebugLoc(), VT,
1272 N00.getOperand(1), N01));
1273 return DAG.getNode(ISD::ADD, DL, VT, N0, N1);
1279 SDValue DAGCombiner::visitADD(SDNode *N) {
1280 SDValue N0 = N->getOperand(0);
1281 SDValue N1 = N->getOperand(1);
1282 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1283 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1284 EVT VT = N0.getValueType();
1287 if (VT.isVector()) {
1288 SDValue FoldedVOp = SimplifyVBinOp(N);
1289 if (FoldedVOp.getNode()) return FoldedVOp;
1292 // fold (add x, undef) -> undef
1293 if (N0.getOpcode() == ISD::UNDEF)
1295 if (N1.getOpcode() == ISD::UNDEF)
1297 // fold (add c1, c2) -> c1+c2
1299 return DAG.FoldConstantArithmetic(ISD::ADD, VT, N0C, N1C);
1300 // canonicalize constant to RHS
1302 return DAG.getNode(ISD::ADD, N->getDebugLoc(), VT, N1, N0);
1303 // fold (add x, 0) -> x
1304 if (N1C && N1C->isNullValue())
1306 // fold (add Sym, c) -> Sym+c
1307 if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N0))
1308 if (!LegalOperations && TLI.isOffsetFoldingLegal(GA) && N1C &&
1309 GA->getOpcode() == ISD::GlobalAddress)
1310 return DAG.getGlobalAddress(GA->getGlobal(), VT,
1312 (uint64_t)N1C->getSExtValue());
1313 // fold ((c1-A)+c2) -> (c1+c2)-A
1314 if (N1C && N0.getOpcode() == ISD::SUB)
1315 if (ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getOperand(0)))
1316 return DAG.getNode(ISD::SUB, N->getDebugLoc(), VT,
1317 DAG.getConstant(N1C->getAPIntValue()+
1318 N0C->getAPIntValue(), VT),
1321 SDValue RADD = ReassociateOps(ISD::ADD, N->getDebugLoc(), N0, N1);
1322 if (RADD.getNode() != 0)
1324 // fold ((0-A) + B) -> B-A
1325 if (N0.getOpcode() == ISD::SUB && isa<ConstantSDNode>(N0.getOperand(0)) &&
1326 cast<ConstantSDNode>(N0.getOperand(0))->isNullValue())
1327 return DAG.getNode(ISD::SUB, N->getDebugLoc(), VT, N1, N0.getOperand(1));
1328 // fold (A + (0-B)) -> A-B
1329 if (N1.getOpcode() == ISD::SUB && isa<ConstantSDNode>(N1.getOperand(0)) &&
1330 cast<ConstantSDNode>(N1.getOperand(0))->isNullValue())
1331 return DAG.getNode(ISD::SUB, N->getDebugLoc(), VT, N0, N1.getOperand(1));
1332 // fold (A+(B-A)) -> B
1333 if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(1))
1334 return N1.getOperand(0);
1335 // fold ((B-A)+A) -> B
1336 if (N0.getOpcode() == ISD::SUB && N1 == N0.getOperand(1))
1337 return N0.getOperand(0);
1338 // fold (A+(B-(A+C))) to (B-C)
1339 if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD &&
1340 N0 == N1.getOperand(1).getOperand(0))
1341 return DAG.getNode(ISD::SUB, N->getDebugLoc(), VT, N1.getOperand(0),
1342 N1.getOperand(1).getOperand(1));
1343 // fold (A+(B-(C+A))) to (B-C)
1344 if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD &&
1345 N0 == N1.getOperand(1).getOperand(1))
1346 return DAG.getNode(ISD::SUB, N->getDebugLoc(), VT, N1.getOperand(0),
1347 N1.getOperand(1).getOperand(0));
1348 // fold (A+((B-A)+or-C)) to (B+or-C)
1349 if ((N1.getOpcode() == ISD::SUB || N1.getOpcode() == ISD::ADD) &&
1350 N1.getOperand(0).getOpcode() == ISD::SUB &&
1351 N0 == N1.getOperand(0).getOperand(1))
1352 return DAG.getNode(N1.getOpcode(), N->getDebugLoc(), VT,
1353 N1.getOperand(0).getOperand(0), N1.getOperand(1));
1355 // fold (A-B)+(C-D) to (A+C)-(B+D) when A or C is constant
1356 if (N0.getOpcode() == ISD::SUB && N1.getOpcode() == ISD::SUB) {
1357 SDValue N00 = N0.getOperand(0);
1358 SDValue N01 = N0.getOperand(1);
1359 SDValue N10 = N1.getOperand(0);
1360 SDValue N11 = N1.getOperand(1);
1362 if (isa<ConstantSDNode>(N00) || isa<ConstantSDNode>(N10))
1363 return DAG.getNode(ISD::SUB, N->getDebugLoc(), VT,
1364 DAG.getNode(ISD::ADD, N0.getDebugLoc(), VT, N00, N10),
1365 DAG.getNode(ISD::ADD, N1.getDebugLoc(), VT, N01, N11));
1368 if (!VT.isVector() && SimplifyDemandedBits(SDValue(N, 0)))
1369 return SDValue(N, 0);
1371 // fold (a+b) -> (a|b) iff a and b share no bits.
1372 if (VT.isInteger() && !VT.isVector()) {
1373 APInt LHSZero, LHSOne;
1374 APInt RHSZero, RHSOne;
1375 APInt Mask = APInt::getAllOnesValue(VT.getScalarType().getSizeInBits());
1376 DAG.ComputeMaskedBits(N0, Mask, LHSZero, LHSOne);
1378 if (LHSZero.getBoolValue()) {
1379 DAG.ComputeMaskedBits(N1, Mask, RHSZero, RHSOne);
1381 // If all possibly-set bits on the LHS are clear on the RHS, return an OR.
1382 // If all possibly-set bits on the RHS are clear on the LHS, return an OR.
1383 if ((RHSZero & (~LHSZero & Mask)) == (~LHSZero & Mask) ||
1384 (LHSZero & (~RHSZero & Mask)) == (~RHSZero & Mask))
1385 return DAG.getNode(ISD::OR, N->getDebugLoc(), VT, N0, N1);
1389 // fold (add (shl (add x, c1), c2), ) -> (add (add (shl x, c2), c1<<c2), )
1390 if (N0.getOpcode() == ISD::SHL && N0.getNode()->hasOneUse()) {
1391 SDValue Result = combineShlAddConstant(N->getDebugLoc(), N0, N1, DAG);
1392 if (Result.getNode()) return Result;
1394 if (N1.getOpcode() == ISD::SHL && N1.getNode()->hasOneUse()) {
1395 SDValue Result = combineShlAddConstant(N->getDebugLoc(), N1, N0, DAG);
1396 if (Result.getNode()) return Result;
1399 // fold (add x, shl(0 - y, n)) -> sub(x, shl(y, n))
1400 if (N1.getOpcode() == ISD::SHL &&
1401 N1.getOperand(0).getOpcode() == ISD::SUB)
1402 if (ConstantSDNode *C =
1403 dyn_cast<ConstantSDNode>(N1.getOperand(0).getOperand(0)))
1404 if (C->getAPIntValue() == 0)
1405 return DAG.getNode(ISD::SUB, N->getDebugLoc(), VT, N0,
1406 DAG.getNode(ISD::SHL, N->getDebugLoc(), VT,
1407 N1.getOperand(0).getOperand(1),
1409 if (N0.getOpcode() == ISD::SHL &&
1410 N0.getOperand(0).getOpcode() == ISD::SUB)
1411 if (ConstantSDNode *C =
1412 dyn_cast<ConstantSDNode>(N0.getOperand(0).getOperand(0)))
1413 if (C->getAPIntValue() == 0)
1414 return DAG.getNode(ISD::SUB, N->getDebugLoc(), VT, N1,
1415 DAG.getNode(ISD::SHL, N->getDebugLoc(), VT,
1416 N0.getOperand(0).getOperand(1),
1422 SDValue DAGCombiner::visitADDC(SDNode *N) {
1423 SDValue N0 = N->getOperand(0);
1424 SDValue N1 = N->getOperand(1);
1425 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1426 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1427 EVT VT = N0.getValueType();
1429 // If the flag result is dead, turn this into an ADD.
1430 if (N->hasNUsesOfValue(0, 1))
1431 return CombineTo(N, DAG.getNode(ISD::ADD, N->getDebugLoc(), VT, N1, N0),
1432 DAG.getNode(ISD::CARRY_FALSE,
1433 N->getDebugLoc(), MVT::Flag));
1435 // canonicalize constant to RHS.
1437 return DAG.getNode(ISD::ADDC, N->getDebugLoc(), N->getVTList(), N1, N0);
1439 // fold (addc x, 0) -> x + no carry out
1440 if (N1C && N1C->isNullValue())
1441 return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE,
1442 N->getDebugLoc(), MVT::Flag));
1444 // fold (addc a, b) -> (or a, b), CARRY_FALSE iff a and b share no bits.
1445 APInt LHSZero, LHSOne;
1446 APInt RHSZero, RHSOne;
1447 APInt Mask = APInt::getAllOnesValue(VT.getScalarType().getSizeInBits());
1448 DAG.ComputeMaskedBits(N0, Mask, LHSZero, LHSOne);
1450 if (LHSZero.getBoolValue()) {
1451 DAG.ComputeMaskedBits(N1, Mask, RHSZero, RHSOne);
1453 // If all possibly-set bits on the LHS are clear on the RHS, return an OR.
1454 // If all possibly-set bits on the RHS are clear on the LHS, return an OR.
1455 if ((RHSZero & (~LHSZero & Mask)) == (~LHSZero & Mask) ||
1456 (LHSZero & (~RHSZero & Mask)) == (~RHSZero & Mask))
1457 return CombineTo(N, DAG.getNode(ISD::OR, N->getDebugLoc(), VT, N0, N1),
1458 DAG.getNode(ISD::CARRY_FALSE,
1459 N->getDebugLoc(), MVT::Flag));
1465 SDValue DAGCombiner::visitADDE(SDNode *N) {
1466 SDValue N0 = N->getOperand(0);
1467 SDValue N1 = N->getOperand(1);
1468 SDValue CarryIn = N->getOperand(2);
1469 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1470 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1472 // canonicalize constant to RHS
1474 return DAG.getNode(ISD::ADDE, N->getDebugLoc(), N->getVTList(),
1477 // fold (adde x, y, false) -> (addc x, y)
1478 if (CarryIn.getOpcode() == ISD::CARRY_FALSE)
1479 return DAG.getNode(ISD::ADDC, N->getDebugLoc(), N->getVTList(), N1, N0);
1484 SDValue DAGCombiner::visitSUB(SDNode *N) {
1485 SDValue N0 = N->getOperand(0);
1486 SDValue N1 = N->getOperand(1);
1487 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getNode());
1488 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
1489 EVT VT = N0.getValueType();
1492 if (VT.isVector()) {
1493 SDValue FoldedVOp = SimplifyVBinOp(N);
1494 if (FoldedVOp.getNode()) return FoldedVOp;
1497 // fold (sub x, x) -> 0
1499 return DAG.getConstant(0, N->getValueType(0));
1500 // fold (sub c1, c2) -> c1-c2
1502 return DAG.FoldConstantArithmetic(ISD::SUB, VT, N0C, N1C);
1503 // fold (sub x, c) -> (add x, -c)
1505 return DAG.getNode(ISD::ADD, N->getDebugLoc(), VT, N0,
1506 DAG.getConstant(-N1C->getAPIntValue(), VT));
1507 // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1)
1508 if (N0C && N0C->isAllOnesValue())
1509 return DAG.getNode(ISD::XOR, N->getDebugLoc(), VT, N1, N0);
1510 // fold (A+B)-A -> B
1511 if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1)
1512 return N0.getOperand(1);
1513 // fold (A+B)-B -> A
1514 if (N0.getOpcode() == ISD::ADD && N0.getOperand(1) == N1)
1515 return N0.getOperand(0);
1516 // fold ((A+(B+or-C))-B) -> A+or-C
1517 if (N0.getOpcode() == ISD::ADD &&
1518 (N0.getOperand(1).getOpcode() == ISD::SUB ||
1519 N0.getOperand(1).getOpcode() == ISD::ADD) &&
1520 N0.getOperand(1).getOperand(0) == N1)
1521 return DAG.getNode(N0.getOperand(1).getOpcode(), N->getDebugLoc(), VT,
1522 N0.getOperand(0), N0.getOperand(1).getOperand(1));
1523 // fold ((A+(C+B))-B) -> A+C
1524 if (N0.getOpcode() == ISD::ADD &&
1525 N0.getOperand(1).getOpcode() == ISD::ADD &&
1526 N0.getOperand(1).getOperand(1) == N1)
1527 return DAG.getNode(ISD::ADD, N->getDebugLoc(), VT,
1528 N0.getOperand(0), N0.getOperand(1).getOperand(0));
1529 // fold ((A-(B-C))-C) -> A-B
1530 if (N0.getOpcode() == ISD::SUB &&
1531 N0.getOperand(1).getOpcode() == ISD::SUB &&
1532 N0.getOperand(1).getOperand(1) == N1)
1533 return DAG.getNode(ISD::SUB, N->getDebugLoc(), VT,
1534 N0.getOperand(0), N0.getOperand(1).getOperand(0));
1536 // If either operand of a sub is undef, the result is undef
1537 if (N0.getOpcode() == ISD::UNDEF)
1539 if (N1.getOpcode() == ISD::UNDEF)
1542 // If the relocation model supports it, consider symbol offsets.
1543 if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N0))
1544 if (!LegalOperations && TLI.isOffsetFoldingLegal(GA)) {
1545 // fold (sub Sym, c) -> Sym-c
1546 if (N1C && GA->getOpcode() == ISD::GlobalAddress)
1547 return DAG.getGlobalAddress(GA->getGlobal(), VT,
1549 (uint64_t)N1C->getSExtValue());
1550 // fold (sub Sym+c1, Sym+c2) -> c1-c2
1551 if (GlobalAddressSDNode *GB = dyn_cast<GlobalAddressSDNode>(N1))
1552 if (GA->getGlobal() == GB->getGlobal())
1553 return DAG.getConstant((uint64_t)GA->getOffset() - GB->getOffset(),
1560 SDValue DAGCombiner::visitMUL(SDNode *N) {
1561 SDValue N0 = N->getOperand(0);
1562 SDValue N1 = N->getOperand(1);
1563 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1564 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1565 EVT VT = N0.getValueType();
1568 if (VT.isVector()) {
1569 SDValue FoldedVOp = SimplifyVBinOp(N);
1570 if (FoldedVOp.getNode()) return FoldedVOp;
1573 // fold (mul x, undef) -> 0
1574 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
1575 return DAG.getConstant(0, VT);
1576 // fold (mul c1, c2) -> c1*c2
1578 return DAG.FoldConstantArithmetic(ISD::MUL, VT, N0C, N1C);
1579 // canonicalize constant to RHS
1581 return DAG.getNode(ISD::MUL, N->getDebugLoc(), VT, N1, N0);
1582 // fold (mul x, 0) -> 0
1583 if (N1C && N1C->isNullValue())
1585 // fold (mul x, -1) -> 0-x
1586 if (N1C && N1C->isAllOnesValue())
1587 return DAG.getNode(ISD::SUB, N->getDebugLoc(), VT,
1588 DAG.getConstant(0, VT), N0);
1589 // fold (mul x, (1 << c)) -> x << c
1590 if (N1C && N1C->getAPIntValue().isPowerOf2())
1591 return DAG.getNode(ISD::SHL, N->getDebugLoc(), VT, N0,
1592 DAG.getConstant(N1C->getAPIntValue().logBase2(),
1593 getShiftAmountTy()));
1594 // fold (mul x, -(1 << c)) -> -(x << c) or (-x) << c
1595 if (N1C && (-N1C->getAPIntValue()).isPowerOf2()) {
1596 unsigned Log2Val = (-N1C->getAPIntValue()).logBase2();
1597 // FIXME: If the input is something that is easily negated (e.g. a
1598 // single-use add), we should put the negate there.
1599 return DAG.getNode(ISD::SUB, N->getDebugLoc(), VT,
1600 DAG.getConstant(0, VT),
1601 DAG.getNode(ISD::SHL, N->getDebugLoc(), VT, N0,
1602 DAG.getConstant(Log2Val, getShiftAmountTy())));
1604 // (mul (shl X, c1), c2) -> (mul X, c2 << c1)
1605 if (N1C && N0.getOpcode() == ISD::SHL &&
1606 isa<ConstantSDNode>(N0.getOperand(1))) {
1607 SDValue C3 = DAG.getNode(ISD::SHL, N->getDebugLoc(), VT,
1608 N1, N0.getOperand(1));
1609 AddToWorkList(C3.getNode());
1610 return DAG.getNode(ISD::MUL, N->getDebugLoc(), VT,
1611 N0.getOperand(0), C3);
1614 // Change (mul (shl X, C), Y) -> (shl (mul X, Y), C) when the shift has one
1617 SDValue Sh(0,0), Y(0,0);
1618 // Check for both (mul (shl X, C), Y) and (mul Y, (shl X, C)).
1619 if (N0.getOpcode() == ISD::SHL && isa<ConstantSDNode>(N0.getOperand(1)) &&
1620 N0.getNode()->hasOneUse()) {
1622 } else if (N1.getOpcode() == ISD::SHL &&
1623 isa<ConstantSDNode>(N1.getOperand(1)) &&
1624 N1.getNode()->hasOneUse()) {
1629 SDValue Mul = DAG.getNode(ISD::MUL, N->getDebugLoc(), VT,
1630 Sh.getOperand(0), Y);
1631 return DAG.getNode(ISD::SHL, N->getDebugLoc(), VT,
1632 Mul, Sh.getOperand(1));
1636 // fold (mul (add x, c1), c2) -> (add (mul x, c2), c1*c2)
1637 if (N1C && N0.getOpcode() == ISD::ADD && N0.getNode()->hasOneUse() &&
1638 isa<ConstantSDNode>(N0.getOperand(1)))
1639 return DAG.getNode(ISD::ADD, N->getDebugLoc(), VT,
1640 DAG.getNode(ISD::MUL, N0.getDebugLoc(), VT,
1641 N0.getOperand(0), N1),
1642 DAG.getNode(ISD::MUL, N1.getDebugLoc(), VT,
1643 N0.getOperand(1), N1));
1646 SDValue RMUL = ReassociateOps(ISD::MUL, N->getDebugLoc(), N0, N1);
1647 if (RMUL.getNode() != 0)
1653 SDValue DAGCombiner::visitSDIV(SDNode *N) {
1654 SDValue N0 = N->getOperand(0);
1655 SDValue N1 = N->getOperand(1);
1656 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getNode());
1657 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
1658 EVT VT = N->getValueType(0);
1661 if (VT.isVector()) {
1662 SDValue FoldedVOp = SimplifyVBinOp(N);
1663 if (FoldedVOp.getNode()) return FoldedVOp;
1666 // fold (sdiv c1, c2) -> c1/c2
1667 if (N0C && N1C && !N1C->isNullValue())
1668 return DAG.FoldConstantArithmetic(ISD::SDIV, VT, N0C, N1C);
1669 // fold (sdiv X, 1) -> X
1670 if (N1C && N1C->getSExtValue() == 1LL)
1672 // fold (sdiv X, -1) -> 0-X
1673 if (N1C && N1C->isAllOnesValue())
1674 return DAG.getNode(ISD::SUB, N->getDebugLoc(), VT,
1675 DAG.getConstant(0, VT), N0);
1676 // If we know the sign bits of both operands are zero, strength reduce to a
1677 // udiv instead. Handles (X&15) /s 4 -> X&15 >> 2
1678 if (!VT.isVector()) {
1679 if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
1680 return DAG.getNode(ISD::UDIV, N->getDebugLoc(), N1.getValueType(),
1683 // fold (sdiv X, pow2) -> simple ops after legalize
1684 if (N1C && !N1C->isNullValue() && !TLI.isIntDivCheap() &&
1685 (isPowerOf2_64(N1C->getSExtValue()) ||
1686 isPowerOf2_64(-N1C->getSExtValue()))) {
1687 // If dividing by powers of two is cheap, then don't perform the following
1689 if (TLI.isPow2DivCheap())
1692 int64_t pow2 = N1C->getSExtValue();
1693 int64_t abs2 = pow2 > 0 ? pow2 : -pow2;
1694 unsigned lg2 = Log2_64(abs2);
1696 // Splat the sign bit into the register
1697 SDValue SGN = DAG.getNode(ISD::SRA, N->getDebugLoc(), VT, N0,
1698 DAG.getConstant(VT.getSizeInBits()-1,
1699 getShiftAmountTy()));
1700 AddToWorkList(SGN.getNode());
1702 // Add (N0 < 0) ? abs2 - 1 : 0;
1703 SDValue SRL = DAG.getNode(ISD::SRL, N->getDebugLoc(), VT, SGN,
1704 DAG.getConstant(VT.getSizeInBits() - lg2,
1705 getShiftAmountTy()));
1706 SDValue ADD = DAG.getNode(ISD::ADD, N->getDebugLoc(), VT, N0, SRL);
1707 AddToWorkList(SRL.getNode());
1708 AddToWorkList(ADD.getNode()); // Divide by pow2
1709 SDValue SRA = DAG.getNode(ISD::SRA, N->getDebugLoc(), VT, ADD,
1710 DAG.getConstant(lg2, getShiftAmountTy()));
1712 // If we're dividing by a positive value, we're done. Otherwise, we must
1713 // negate the result.
1717 AddToWorkList(SRA.getNode());
1718 return DAG.getNode(ISD::SUB, N->getDebugLoc(), VT,
1719 DAG.getConstant(0, VT), SRA);
1722 // if integer divide is expensive and we satisfy the requirements, emit an
1723 // alternate sequence.
1724 if (N1C && (N1C->getSExtValue() < -1 || N1C->getSExtValue() > 1) &&
1725 !TLI.isIntDivCheap()) {
1726 SDValue Op = BuildSDIV(N);
1727 if (Op.getNode()) return Op;
1731 if (N0.getOpcode() == ISD::UNDEF)
1732 return DAG.getConstant(0, VT);
1733 // X / undef -> undef
1734 if (N1.getOpcode() == ISD::UNDEF)
1740 SDValue DAGCombiner::visitUDIV(SDNode *N) {
1741 SDValue N0 = N->getOperand(0);
1742 SDValue N1 = N->getOperand(1);
1743 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getNode());
1744 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
1745 EVT VT = N->getValueType(0);
1748 if (VT.isVector()) {
1749 SDValue FoldedVOp = SimplifyVBinOp(N);
1750 if (FoldedVOp.getNode()) return FoldedVOp;
1753 // fold (udiv c1, c2) -> c1/c2
1754 if (N0C && N1C && !N1C->isNullValue())
1755 return DAG.FoldConstantArithmetic(ISD::UDIV, VT, N0C, N1C);
1756 // fold (udiv x, (1 << c)) -> x >>u c
1757 if (N1C && N1C->getAPIntValue().isPowerOf2())
1758 return DAG.getNode(ISD::SRL, N->getDebugLoc(), VT, N0,
1759 DAG.getConstant(N1C->getAPIntValue().logBase2(),
1760 getShiftAmountTy()));
1761 // fold (udiv x, (shl c, y)) -> x >>u (log2(c)+y) iff c is power of 2
1762 if (N1.getOpcode() == ISD::SHL) {
1763 if (ConstantSDNode *SHC = dyn_cast<ConstantSDNode>(N1.getOperand(0))) {
1764 if (SHC->getAPIntValue().isPowerOf2()) {
1765 EVT ADDVT = N1.getOperand(1).getValueType();
1766 SDValue Add = DAG.getNode(ISD::ADD, N->getDebugLoc(), ADDVT,
1768 DAG.getConstant(SHC->getAPIntValue()
1771 AddToWorkList(Add.getNode());
1772 return DAG.getNode(ISD::SRL, N->getDebugLoc(), VT, N0, Add);
1776 // fold (udiv x, c) -> alternate
1777 if (N1C && !N1C->isNullValue() && !TLI.isIntDivCheap()) {
1778 SDValue Op = BuildUDIV(N);
1779 if (Op.getNode()) return Op;
1783 if (N0.getOpcode() == ISD::UNDEF)
1784 return DAG.getConstant(0, VT);
1785 // X / undef -> undef
1786 if (N1.getOpcode() == ISD::UNDEF)
1792 SDValue DAGCombiner::visitSREM(SDNode *N) {
1793 SDValue N0 = N->getOperand(0);
1794 SDValue N1 = N->getOperand(1);
1795 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1796 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1797 EVT VT = N->getValueType(0);
1799 // fold (srem c1, c2) -> c1%c2
1800 if (N0C && N1C && !N1C->isNullValue())
1801 return DAG.FoldConstantArithmetic(ISD::SREM, VT, N0C, N1C);
1802 // If we know the sign bits of both operands are zero, strength reduce to a
1803 // urem instead. Handles (X & 0x0FFFFFFF) %s 16 -> X&15
1804 if (!VT.isVector()) {
1805 if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
1806 return DAG.getNode(ISD::UREM, N->getDebugLoc(), VT, N0, N1);
1809 // If X/C can be simplified by the division-by-constant logic, lower
1810 // X%C to the equivalent of X-X/C*C.
1811 if (N1C && !N1C->isNullValue()) {
1812 SDValue Div = DAG.getNode(ISD::SDIV, N->getDebugLoc(), VT, N0, N1);
1813 AddToWorkList(Div.getNode());
1814 SDValue OptimizedDiv = combine(Div.getNode());
1815 if (OptimizedDiv.getNode() && OptimizedDiv.getNode() != Div.getNode()) {
1816 SDValue Mul = DAG.getNode(ISD::MUL, N->getDebugLoc(), VT,
1818 SDValue Sub = DAG.getNode(ISD::SUB, N->getDebugLoc(), VT, N0, Mul);
1819 AddToWorkList(Mul.getNode());
1825 if (N0.getOpcode() == ISD::UNDEF)
1826 return DAG.getConstant(0, VT);
1827 // X % undef -> undef
1828 if (N1.getOpcode() == ISD::UNDEF)
1834 SDValue DAGCombiner::visitUREM(SDNode *N) {
1835 SDValue N0 = N->getOperand(0);
1836 SDValue N1 = N->getOperand(1);
1837 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1838 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1839 EVT VT = N->getValueType(0);
1841 // fold (urem c1, c2) -> c1%c2
1842 if (N0C && N1C && !N1C->isNullValue())
1843 return DAG.FoldConstantArithmetic(ISD::UREM, VT, N0C, N1C);
1844 // fold (urem x, pow2) -> (and x, pow2-1)
1845 if (N1C && !N1C->isNullValue() && N1C->getAPIntValue().isPowerOf2())
1846 return DAG.getNode(ISD::AND, N->getDebugLoc(), VT, N0,
1847 DAG.getConstant(N1C->getAPIntValue()-1,VT));
1848 // fold (urem x, (shl pow2, y)) -> (and x, (add (shl pow2, y), -1))
1849 if (N1.getOpcode() == ISD::SHL) {
1850 if (ConstantSDNode *SHC = dyn_cast<ConstantSDNode>(N1.getOperand(0))) {
1851 if (SHC->getAPIntValue().isPowerOf2()) {
1853 DAG.getNode(ISD::ADD, N->getDebugLoc(), VT, N1,
1854 DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()),
1856 AddToWorkList(Add.getNode());
1857 return DAG.getNode(ISD::AND, N->getDebugLoc(), VT, N0, Add);
1862 // If X/C can be simplified by the division-by-constant logic, lower
1863 // X%C to the equivalent of X-X/C*C.
1864 if (N1C && !N1C->isNullValue()) {
1865 SDValue Div = DAG.getNode(ISD::UDIV, N->getDebugLoc(), VT, N0, N1);
1866 AddToWorkList(Div.getNode());
1867 SDValue OptimizedDiv = combine(Div.getNode());
1868 if (OptimizedDiv.getNode() && OptimizedDiv.getNode() != Div.getNode()) {
1869 SDValue Mul = DAG.getNode(ISD::MUL, N->getDebugLoc(), VT,
1871 SDValue Sub = DAG.getNode(ISD::SUB, N->getDebugLoc(), VT, N0, Mul);
1872 AddToWorkList(Mul.getNode());
1878 if (N0.getOpcode() == ISD::UNDEF)
1879 return DAG.getConstant(0, VT);
1880 // X % undef -> undef
1881 if (N1.getOpcode() == ISD::UNDEF)
1887 SDValue DAGCombiner::visitMULHS(SDNode *N) {
1888 SDValue N0 = N->getOperand(0);
1889 SDValue N1 = N->getOperand(1);
1890 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1891 EVT VT = N->getValueType(0);
1893 // fold (mulhs x, 0) -> 0
1894 if (N1C && N1C->isNullValue())
1896 // fold (mulhs x, 1) -> (sra x, size(x)-1)
1897 if (N1C && N1C->getAPIntValue() == 1)
1898 return DAG.getNode(ISD::SRA, N->getDebugLoc(), N0.getValueType(), N0,
1899 DAG.getConstant(N0.getValueType().getSizeInBits() - 1,
1900 getShiftAmountTy()));
1901 // fold (mulhs x, undef) -> 0
1902 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
1903 return DAG.getConstant(0, VT);
1908 SDValue DAGCombiner::visitMULHU(SDNode *N) {
1909 SDValue N0 = N->getOperand(0);
1910 SDValue N1 = N->getOperand(1);
1911 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1912 EVT VT = N->getValueType(0);
1914 // fold (mulhu x, 0) -> 0
1915 if (N1C && N1C->isNullValue())
1917 // fold (mulhu x, 1) -> 0
1918 if (N1C && N1C->getAPIntValue() == 1)
1919 return DAG.getConstant(0, N0.getValueType());
1920 // fold (mulhu x, undef) -> 0
1921 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
1922 return DAG.getConstant(0, VT);
1927 /// SimplifyNodeWithTwoResults - Perform optimizations common to nodes that
1928 /// compute two values. LoOp and HiOp give the opcodes for the two computations
1929 /// that are being performed. Return true if a simplification was made.
1931 SDValue DAGCombiner::SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp,
1933 // If the high half is not needed, just compute the low half.
1934 bool HiExists = N->hasAnyUseOfValue(1);
1936 (!LegalOperations ||
1937 TLI.isOperationLegal(LoOp, N->getValueType(0)))) {
1938 SDValue Res = DAG.getNode(LoOp, N->getDebugLoc(), N->getValueType(0),
1939 N->op_begin(), N->getNumOperands());
1940 return CombineTo(N, Res, Res);
1943 // If the low half is not needed, just compute the high half.
1944 bool LoExists = N->hasAnyUseOfValue(0);
1946 (!LegalOperations ||
1947 TLI.isOperationLegal(HiOp, N->getValueType(1)))) {
1948 SDValue Res = DAG.getNode(HiOp, N->getDebugLoc(), N->getValueType(1),
1949 N->op_begin(), N->getNumOperands());
1950 return CombineTo(N, Res, Res);
1953 // If both halves are used, return as it is.
1954 if (LoExists && HiExists)
1957 // If the two computed results can be simplified separately, separate them.
1959 SDValue Lo = DAG.getNode(LoOp, N->getDebugLoc(), N->getValueType(0),
1960 N->op_begin(), N->getNumOperands());
1961 AddToWorkList(Lo.getNode());
1962 SDValue LoOpt = combine(Lo.getNode());
1963 if (LoOpt.getNode() && LoOpt.getNode() != Lo.getNode() &&
1964 (!LegalOperations ||
1965 TLI.isOperationLegal(LoOpt.getOpcode(), LoOpt.getValueType())))
1966 return CombineTo(N, LoOpt, LoOpt);
1970 SDValue Hi = DAG.getNode(HiOp, N->getDebugLoc(), N->getValueType(1),
1971 N->op_begin(), N->getNumOperands());
1972 AddToWorkList(Hi.getNode());
1973 SDValue HiOpt = combine(Hi.getNode());
1974 if (HiOpt.getNode() && HiOpt != Hi &&
1975 (!LegalOperations ||
1976 TLI.isOperationLegal(HiOpt.getOpcode(), HiOpt.getValueType())))
1977 return CombineTo(N, HiOpt, HiOpt);
1983 SDValue DAGCombiner::visitSMUL_LOHI(SDNode *N) {
1984 SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHS);
1985 if (Res.getNode()) return Res;
1990 SDValue DAGCombiner::visitUMUL_LOHI(SDNode *N) {
1991 SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHU);
1992 if (Res.getNode()) return Res;
1997 SDValue DAGCombiner::visitSDIVREM(SDNode *N) {
1998 SDValue Res = SimplifyNodeWithTwoResults(N, ISD::SDIV, ISD::SREM);
1999 if (Res.getNode()) return Res;
2004 SDValue DAGCombiner::visitUDIVREM(SDNode *N) {
2005 SDValue Res = SimplifyNodeWithTwoResults(N, ISD::UDIV, ISD::UREM);
2006 if (Res.getNode()) return Res;
2011 /// SimplifyBinOpWithSameOpcodeHands - If this is a binary operator with
2012 /// two operands of the same opcode, try to simplify it.
2013 SDValue DAGCombiner::SimplifyBinOpWithSameOpcodeHands(SDNode *N) {
2014 SDValue N0 = N->getOperand(0), N1 = N->getOperand(1);
2015 EVT VT = N0.getValueType();
2016 assert(N0.getOpcode() == N1.getOpcode() && "Bad input!");
2018 // Bail early if none of these transforms apply.
2019 if (N0.getNode()->getNumOperands() == 0) return SDValue();
2021 // For each of OP in AND/OR/XOR:
2022 // fold (OP (zext x), (zext y)) -> (zext (OP x, y))
2023 // fold (OP (sext x), (sext y)) -> (sext (OP x, y))
2024 // fold (OP (aext x), (aext y)) -> (aext (OP x, y))
2025 // fold (OP (trunc x), (trunc y)) -> (trunc (OP x, y))
2027 // do not sink logical op inside of a vector extend, since it may combine
2029 EVT Op0VT = N0.getOperand(0).getValueType();
2030 if ((N0.getOpcode() == ISD::ZERO_EXTEND ||
2031 N0.getOpcode() == ISD::SIGN_EXTEND ||
2032 // Avoid infinite looping with PromoteIntBinOp.
2033 (N0.getOpcode() == ISD::ANY_EXTEND &&
2034 (!LegalTypes || TLI.isTypeDesirableForOp(N->getOpcode(), Op0VT))) ||
2035 (N0.getOpcode() == ISD::TRUNCATE && TLI.isTypeLegal(Op0VT))) &&
2037 Op0VT == N1.getOperand(0).getValueType() &&
2038 (!LegalOperations || TLI.isOperationLegal(N->getOpcode(), Op0VT))) {
2039 SDValue ORNode = DAG.getNode(N->getOpcode(), N0.getDebugLoc(),
2040 N0.getOperand(0).getValueType(),
2041 N0.getOperand(0), N1.getOperand(0));
2042 AddToWorkList(ORNode.getNode());
2043 return DAG.getNode(N0.getOpcode(), N->getDebugLoc(), VT, ORNode);
2046 // For each of OP in SHL/SRL/SRA/AND...
2047 // fold (and (OP x, z), (OP y, z)) -> (OP (and x, y), z)
2048 // fold (or (OP x, z), (OP y, z)) -> (OP (or x, y), z)
2049 // fold (xor (OP x, z), (OP y, z)) -> (OP (xor x, y), z)
2050 if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL ||
2051 N0.getOpcode() == ISD::SRA || N0.getOpcode() == ISD::AND) &&
2052 N0.getOperand(1) == N1.getOperand(1)) {
2053 SDValue ORNode = DAG.getNode(N->getOpcode(), N0.getDebugLoc(),
2054 N0.getOperand(0).getValueType(),
2055 N0.getOperand(0), N1.getOperand(0));
2056 AddToWorkList(ORNode.getNode());
2057 return DAG.getNode(N0.getOpcode(), N->getDebugLoc(), VT,
2058 ORNode, N0.getOperand(1));
2064 SDValue DAGCombiner::visitAND(SDNode *N) {
2065 SDValue N0 = N->getOperand(0);
2066 SDValue N1 = N->getOperand(1);
2067 SDValue LL, LR, RL, RR, CC0, CC1;
2068 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
2069 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2070 EVT VT = N1.getValueType();
2071 unsigned BitWidth = VT.getScalarType().getSizeInBits();
2074 if (VT.isVector()) {
2075 SDValue FoldedVOp = SimplifyVBinOp(N);
2076 if (FoldedVOp.getNode()) return FoldedVOp;
2079 // fold (and x, undef) -> 0
2080 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2081 return DAG.getConstant(0, VT);
2082 // fold (and c1, c2) -> c1&c2
2084 return DAG.FoldConstantArithmetic(ISD::AND, VT, N0C, N1C);
2085 // canonicalize constant to RHS
2087 return DAG.getNode(ISD::AND, N->getDebugLoc(), VT, N1, N0);
2088 // fold (and x, -1) -> x
2089 if (N1C && N1C->isAllOnesValue())
2091 // if (and x, c) is known to be zero, return 0
2092 if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0),
2093 APInt::getAllOnesValue(BitWidth)))
2094 return DAG.getConstant(0, VT);
2096 SDValue RAND = ReassociateOps(ISD::AND, N->getDebugLoc(), N0, N1);
2097 if (RAND.getNode() != 0)
2099 // fold (and (or x, C), D) -> D if (C & D) == D
2100 if (N1C && N0.getOpcode() == ISD::OR)
2101 if (ConstantSDNode *ORI = dyn_cast<ConstantSDNode>(N0.getOperand(1)))
2102 if ((ORI->getAPIntValue() & N1C->getAPIntValue()) == N1C->getAPIntValue())
2104 // fold (and (any_ext V), c) -> (zero_ext V) if 'and' only clears top bits.
2105 if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
2106 SDValue N0Op0 = N0.getOperand(0);
2107 APInt Mask = ~N1C->getAPIntValue();
2108 Mask.trunc(N0Op0.getValueSizeInBits());
2109 if (DAG.MaskedValueIsZero(N0Op0, Mask)) {
2110 SDValue Zext = DAG.getNode(ISD::ZERO_EXTEND, N->getDebugLoc(),
2111 N0.getValueType(), N0Op0);
2113 // Replace uses of the AND with uses of the Zero extend node.
2116 // We actually want to replace all uses of the any_extend with the
2117 // zero_extend, to avoid duplicating things. This will later cause this
2118 // AND to be folded.
2119 CombineTo(N0.getNode(), Zext);
2120 return SDValue(N, 0); // Return N so it doesn't get rechecked!
2123 // fold (and (setcc x), (setcc y)) -> (setcc (and x, y))
2124 if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){
2125 ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get();
2126 ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get();
2128 if (LR == RR && isa<ConstantSDNode>(LR) && Op0 == Op1 &&
2129 LL.getValueType().isInteger()) {
2130 // fold (and (seteq X, 0), (seteq Y, 0)) -> (seteq (or X, Y), 0)
2131 if (cast<ConstantSDNode>(LR)->isNullValue() && Op1 == ISD::SETEQ) {
2132 SDValue ORNode = DAG.getNode(ISD::OR, N0.getDebugLoc(),
2133 LR.getValueType(), LL, RL);
2134 AddToWorkList(ORNode.getNode());
2135 return DAG.getSetCC(N->getDebugLoc(), VT, ORNode, LR, Op1);
2137 // fold (and (seteq X, -1), (seteq Y, -1)) -> (seteq (and X, Y), -1)
2138 if (cast<ConstantSDNode>(LR)->isAllOnesValue() && Op1 == ISD::SETEQ) {
2139 SDValue ANDNode = DAG.getNode(ISD::AND, N0.getDebugLoc(),
2140 LR.getValueType(), LL, RL);
2141 AddToWorkList(ANDNode.getNode());
2142 return DAG.getSetCC(N->getDebugLoc(), VT, ANDNode, LR, Op1);
2144 // fold (and (setgt X, -1), (setgt Y, -1)) -> (setgt (or X, Y), -1)
2145 if (cast<ConstantSDNode>(LR)->isAllOnesValue() && Op1 == ISD::SETGT) {
2146 SDValue ORNode = DAG.getNode(ISD::OR, N0.getDebugLoc(),
2147 LR.getValueType(), LL, RL);
2148 AddToWorkList(ORNode.getNode());
2149 return DAG.getSetCC(N->getDebugLoc(), VT, ORNode, LR, Op1);
2152 // canonicalize equivalent to ll == rl
2153 if (LL == RR && LR == RL) {
2154 Op1 = ISD::getSetCCSwappedOperands(Op1);
2157 if (LL == RL && LR == RR) {
2158 bool isInteger = LL.getValueType().isInteger();
2159 ISD::CondCode Result = ISD::getSetCCAndOperation(Op0, Op1, isInteger);
2160 if (Result != ISD::SETCC_INVALID &&
2161 (!LegalOperations || TLI.isCondCodeLegal(Result, LL.getValueType())))
2162 return DAG.getSetCC(N->getDebugLoc(), N0.getValueType(),
2167 // Simplify: (and (op x...), (op y...)) -> (op (and x, y))
2168 if (N0.getOpcode() == N1.getOpcode()) {
2169 SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
2170 if (Tmp.getNode()) return Tmp;
2173 // fold (and (sign_extend_inreg x, i16 to i32), 1) -> (and x, 1)
2174 // fold (and (sra)) -> (and (srl)) when possible.
2175 if (!VT.isVector() &&
2176 SimplifyDemandedBits(SDValue(N, 0)))
2177 return SDValue(N, 0);
2179 // fold (zext_inreg (extload x)) -> (zextload x)
2180 if (ISD::isEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode())) {
2181 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
2182 EVT MemVT = LN0->getMemoryVT();
2183 // If we zero all the possible extended bits, then we can turn this into
2184 // a zextload if we are running before legalize or the operation is legal.
2185 unsigned BitWidth = N1.getValueType().getScalarType().getSizeInBits();
2186 if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth,
2187 BitWidth - MemVT.getScalarType().getSizeInBits())) &&
2188 ((!LegalOperations && !LN0->isVolatile()) ||
2189 TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT))) {
2190 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, N0.getDebugLoc(), VT,
2191 LN0->getChain(), LN0->getBasePtr(),
2193 LN0->getSrcValueOffset(), MemVT,
2194 LN0->isVolatile(), LN0->isNonTemporal(),
2195 LN0->getAlignment());
2197 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
2198 return SDValue(N, 0); // Return N so it doesn't get rechecked!
2201 // fold (zext_inreg (sextload x)) -> (zextload x) iff load has one use
2202 if (ISD::isSEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
2204 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
2205 EVT MemVT = LN0->getMemoryVT();
2206 // If we zero all the possible extended bits, then we can turn this into
2207 // a zextload if we are running before legalize or the operation is legal.
2208 unsigned BitWidth = N1.getValueType().getScalarType().getSizeInBits();
2209 if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth,
2210 BitWidth - MemVT.getScalarType().getSizeInBits())) &&
2211 ((!LegalOperations && !LN0->isVolatile()) ||
2212 TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT))) {
2213 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, N0.getDebugLoc(), VT,
2215 LN0->getBasePtr(), LN0->getSrcValue(),
2216 LN0->getSrcValueOffset(), MemVT,
2217 LN0->isVolatile(), LN0->isNonTemporal(),
2218 LN0->getAlignment());
2220 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
2221 return SDValue(N, 0); // Return N so it doesn't get rechecked!
2225 // fold (and (load x), 255) -> (zextload x, i8)
2226 // fold (and (extload x, i16), 255) -> (zextload x, i8)
2227 // fold (and (any_ext (extload x, i16)), 255) -> (zextload x, i8)
2228 if (N1C && (N0.getOpcode() == ISD::LOAD ||
2229 (N0.getOpcode() == ISD::ANY_EXTEND &&
2230 N0.getOperand(0).getOpcode() == ISD::LOAD))) {
2231 bool HasAnyExt = N0.getOpcode() == ISD::ANY_EXTEND;
2232 LoadSDNode *LN0 = HasAnyExt
2233 ? cast<LoadSDNode>(N0.getOperand(0))
2234 : cast<LoadSDNode>(N0);
2235 if (LN0->getExtensionType() != ISD::SEXTLOAD &&
2236 LN0->isUnindexed() && N0.hasOneUse() && LN0->hasOneUse()) {
2237 uint32_t ActiveBits = N1C->getAPIntValue().getActiveBits();
2238 if (ActiveBits > 0 && APIntOps::isMask(ActiveBits, N1C->getAPIntValue())){
2239 EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), ActiveBits);
2240 EVT LoadedVT = LN0->getMemoryVT();
2242 if (ExtVT == LoadedVT &&
2243 (!LegalOperations || TLI.isLoadExtLegal(ISD::ZEXTLOAD, ExtVT))) {
2244 EVT LoadResultTy = HasAnyExt ? LN0->getValueType(0) : VT;
2247 DAG.getExtLoad(ISD::ZEXTLOAD, LN0->getDebugLoc(), LoadResultTy,
2248 LN0->getChain(), LN0->getBasePtr(),
2249 LN0->getSrcValue(), LN0->getSrcValueOffset(),
2250 ExtVT, LN0->isVolatile(), LN0->isNonTemporal(),
2251 LN0->getAlignment());
2253 CombineTo(LN0, NewLoad, NewLoad.getValue(1));
2254 return SDValue(N, 0); // Return N so it doesn't get rechecked!
2257 // Do not change the width of a volatile load.
2258 // Do not generate loads of non-round integer types since these can
2259 // be expensive (and would be wrong if the type is not byte sized).
2260 if (!LN0->isVolatile() && LoadedVT.bitsGT(ExtVT) && ExtVT.isRound() &&
2261 (!LegalOperations || TLI.isLoadExtLegal(ISD::ZEXTLOAD, ExtVT))) {
2262 EVT PtrType = LN0->getOperand(1).getValueType();
2264 unsigned Alignment = LN0->getAlignment();
2265 SDValue NewPtr = LN0->getBasePtr();
2267 // For big endian targets, we need to add an offset to the pointer
2268 // to load the correct bytes. For little endian systems, we merely
2269 // need to read fewer bytes from the same pointer.
2270 if (TLI.isBigEndian()) {
2271 unsigned LVTStoreBytes = LoadedVT.getStoreSize();
2272 unsigned EVTStoreBytes = ExtVT.getStoreSize();
2273 unsigned PtrOff = LVTStoreBytes - EVTStoreBytes;
2274 NewPtr = DAG.getNode(ISD::ADD, LN0->getDebugLoc(), PtrType,
2275 NewPtr, DAG.getConstant(PtrOff, PtrType));
2276 Alignment = MinAlign(Alignment, PtrOff);
2279 AddToWorkList(NewPtr.getNode());
2281 EVT LoadResultTy = HasAnyExt ? LN0->getValueType(0) : VT;
2283 DAG.getExtLoad(ISD::ZEXTLOAD, LN0->getDebugLoc(), LoadResultTy,
2284 LN0->getChain(), NewPtr,
2285 LN0->getSrcValue(), LN0->getSrcValueOffset(),
2286 ExtVT, LN0->isVolatile(), LN0->isNonTemporal(),
2289 CombineTo(LN0, Load, Load.getValue(1));
2290 return SDValue(N, 0); // Return N so it doesn't get rechecked!
2299 SDValue DAGCombiner::visitOR(SDNode *N) {
2300 SDValue N0 = N->getOperand(0);
2301 SDValue N1 = N->getOperand(1);
2302 SDValue LL, LR, RL, RR, CC0, CC1;
2303 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
2304 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2305 EVT VT = N1.getValueType();
2308 if (VT.isVector()) {
2309 SDValue FoldedVOp = SimplifyVBinOp(N);
2310 if (FoldedVOp.getNode()) return FoldedVOp;
2313 // fold (or x, undef) -> -1
2314 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF) {
2315 EVT EltVT = VT.isVector() ? VT.getVectorElementType() : VT;
2316 return DAG.getConstant(APInt::getAllOnesValue(EltVT.getSizeInBits()), VT);
2318 // fold (or c1, c2) -> c1|c2
2320 return DAG.FoldConstantArithmetic(ISD::OR, VT, N0C, N1C);
2321 // canonicalize constant to RHS
2323 return DAG.getNode(ISD::OR, N->getDebugLoc(), VT, N1, N0);
2324 // fold (or x, 0) -> x
2325 if (N1C && N1C->isNullValue())
2327 // fold (or x, -1) -> -1
2328 if (N1C && N1C->isAllOnesValue())
2330 // fold (or x, c) -> c iff (x & ~c) == 0
2331 if (N1C && DAG.MaskedValueIsZero(N0, ~N1C->getAPIntValue()))
2334 SDValue ROR = ReassociateOps(ISD::OR, N->getDebugLoc(), N0, N1);
2335 if (ROR.getNode() != 0)
2337 // Canonicalize (or (and X, c1), c2) -> (and (or X, c2), c1|c2)
2338 // iff (c1 & c2) == 0.
2339 if (N1C && N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() &&
2340 isa<ConstantSDNode>(N0.getOperand(1))) {
2341 ConstantSDNode *C1 = cast<ConstantSDNode>(N0.getOperand(1));
2342 if ((C1->getAPIntValue() & N1C->getAPIntValue()) != 0)
2343 return DAG.getNode(ISD::AND, N->getDebugLoc(), VT,
2344 DAG.getNode(ISD::OR, N0.getDebugLoc(), VT,
2345 N0.getOperand(0), N1),
2346 DAG.FoldConstantArithmetic(ISD::OR, VT, N1C, C1));
2348 // fold (or (setcc x), (setcc y)) -> (setcc (or x, y))
2349 if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){
2350 ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get();
2351 ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get();
2353 if (LR == RR && isa<ConstantSDNode>(LR) && Op0 == Op1 &&
2354 LL.getValueType().isInteger()) {
2355 // fold (or (setne X, 0), (setne Y, 0)) -> (setne (or X, Y), 0)
2356 // fold (or (setlt X, 0), (setlt Y, 0)) -> (setne (or X, Y), 0)
2357 if (cast<ConstantSDNode>(LR)->isNullValue() &&
2358 (Op1 == ISD::SETNE || Op1 == ISD::SETLT)) {
2359 SDValue ORNode = DAG.getNode(ISD::OR, LR.getDebugLoc(),
2360 LR.getValueType(), LL, RL);
2361 AddToWorkList(ORNode.getNode());
2362 return DAG.getSetCC(N->getDebugLoc(), VT, ORNode, LR, Op1);
2364 // fold (or (setne X, -1), (setne Y, -1)) -> (setne (and X, Y), -1)
2365 // fold (or (setgt X, -1), (setgt Y -1)) -> (setgt (and X, Y), -1)
2366 if (cast<ConstantSDNode>(LR)->isAllOnesValue() &&
2367 (Op1 == ISD::SETNE || Op1 == ISD::SETGT)) {
2368 SDValue ANDNode = DAG.getNode(ISD::AND, LR.getDebugLoc(),
2369 LR.getValueType(), LL, RL);
2370 AddToWorkList(ANDNode.getNode());
2371 return DAG.getSetCC(N->getDebugLoc(), VT, ANDNode, LR, Op1);
2374 // canonicalize equivalent to ll == rl
2375 if (LL == RR && LR == RL) {
2376 Op1 = ISD::getSetCCSwappedOperands(Op1);
2379 if (LL == RL && LR == RR) {
2380 bool isInteger = LL.getValueType().isInteger();
2381 ISD::CondCode Result = ISD::getSetCCOrOperation(Op0, Op1, isInteger);
2382 if (Result != ISD::SETCC_INVALID &&
2383 (!LegalOperations || TLI.isCondCodeLegal(Result, LL.getValueType())))
2384 return DAG.getSetCC(N->getDebugLoc(), N0.getValueType(),
2389 // Simplify: (or (op x...), (op y...)) -> (op (or x, y))
2390 if (N0.getOpcode() == N1.getOpcode()) {
2391 SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
2392 if (Tmp.getNode()) return Tmp;
2395 // (or (and X, C1), (and Y, C2)) -> (and (or X, Y), C3) if possible.
2396 if (N0.getOpcode() == ISD::AND &&
2397 N1.getOpcode() == ISD::AND &&
2398 N0.getOperand(1).getOpcode() == ISD::Constant &&
2399 N1.getOperand(1).getOpcode() == ISD::Constant &&
2400 // Don't increase # computations.
2401 (N0.getNode()->hasOneUse() || N1.getNode()->hasOneUse())) {
2402 // We can only do this xform if we know that bits from X that are set in C2
2403 // but not in C1 are already zero. Likewise for Y.
2404 const APInt &LHSMask =
2405 cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
2406 const APInt &RHSMask =
2407 cast<ConstantSDNode>(N1.getOperand(1))->getAPIntValue();
2409 if (DAG.MaskedValueIsZero(N0.getOperand(0), RHSMask&~LHSMask) &&
2410 DAG.MaskedValueIsZero(N1.getOperand(0), LHSMask&~RHSMask)) {
2411 SDValue X = DAG.getNode(ISD::OR, N0.getDebugLoc(), VT,
2412 N0.getOperand(0), N1.getOperand(0));
2413 return DAG.getNode(ISD::AND, N->getDebugLoc(), VT, X,
2414 DAG.getConstant(LHSMask | RHSMask, VT));
2418 // See if this is some rotate idiom.
2419 if (SDNode *Rot = MatchRotate(N0, N1, N->getDebugLoc()))
2420 return SDValue(Rot, 0);
2425 /// MatchRotateHalf - Match "(X shl/srl V1) & V2" where V2 may not be present.
2426 static bool MatchRotateHalf(SDValue Op, SDValue &Shift, SDValue &Mask) {
2427 if (Op.getOpcode() == ISD::AND) {
2428 if (isa<ConstantSDNode>(Op.getOperand(1))) {
2429 Mask = Op.getOperand(1);
2430 Op = Op.getOperand(0);
2436 if (Op.getOpcode() == ISD::SRL || Op.getOpcode() == ISD::SHL) {
2444 // MatchRotate - Handle an 'or' of two operands. If this is one of the many
2445 // idioms for rotate, and if the target supports rotation instructions, generate
2447 SDNode *DAGCombiner::MatchRotate(SDValue LHS, SDValue RHS, DebugLoc DL) {
2448 // Must be a legal type. Expanded 'n promoted things won't work with rotates.
2449 EVT VT = LHS.getValueType();
2450 if (!TLI.isTypeLegal(VT)) return 0;
2452 // The target must have at least one rotate flavor.
2453 bool HasROTL = TLI.isOperationLegalOrCustom(ISD::ROTL, VT);
2454 bool HasROTR = TLI.isOperationLegalOrCustom(ISD::ROTR, VT);
2455 if (!HasROTL && !HasROTR) return 0;
2457 // Match "(X shl/srl V1) & V2" where V2 may not be present.
2458 SDValue LHSShift; // The shift.
2459 SDValue LHSMask; // AND value if any.
2460 if (!MatchRotateHalf(LHS, LHSShift, LHSMask))
2461 return 0; // Not part of a rotate.
2463 SDValue RHSShift; // The shift.
2464 SDValue RHSMask; // AND value if any.
2465 if (!MatchRotateHalf(RHS, RHSShift, RHSMask))
2466 return 0; // Not part of a rotate.
2468 if (LHSShift.getOperand(0) != RHSShift.getOperand(0))
2469 return 0; // Not shifting the same value.
2471 if (LHSShift.getOpcode() == RHSShift.getOpcode())
2472 return 0; // Shifts must disagree.
2474 // Canonicalize shl to left side in a shl/srl pair.
2475 if (RHSShift.getOpcode() == ISD::SHL) {
2476 std::swap(LHS, RHS);
2477 std::swap(LHSShift, RHSShift);
2478 std::swap(LHSMask , RHSMask );
2481 unsigned OpSizeInBits = VT.getSizeInBits();
2482 SDValue LHSShiftArg = LHSShift.getOperand(0);
2483 SDValue LHSShiftAmt = LHSShift.getOperand(1);
2484 SDValue RHSShiftAmt = RHSShift.getOperand(1);
2486 // fold (or (shl x, C1), (srl x, C2)) -> (rotl x, C1)
2487 // fold (or (shl x, C1), (srl x, C2)) -> (rotr x, C2)
2488 if (LHSShiftAmt.getOpcode() == ISD::Constant &&
2489 RHSShiftAmt.getOpcode() == ISD::Constant) {
2490 uint64_t LShVal = cast<ConstantSDNode>(LHSShiftAmt)->getZExtValue();
2491 uint64_t RShVal = cast<ConstantSDNode>(RHSShiftAmt)->getZExtValue();
2492 if ((LShVal + RShVal) != OpSizeInBits)
2497 Rot = DAG.getNode(ISD::ROTL, DL, VT, LHSShiftArg, LHSShiftAmt);
2499 Rot = DAG.getNode(ISD::ROTR, DL, VT, LHSShiftArg, RHSShiftAmt);
2501 // If there is an AND of either shifted operand, apply it to the result.
2502 if (LHSMask.getNode() || RHSMask.getNode()) {
2503 APInt Mask = APInt::getAllOnesValue(OpSizeInBits);
2505 if (LHSMask.getNode()) {
2506 APInt RHSBits = APInt::getLowBitsSet(OpSizeInBits, LShVal);
2507 Mask &= cast<ConstantSDNode>(LHSMask)->getAPIntValue() | RHSBits;
2509 if (RHSMask.getNode()) {
2510 APInt LHSBits = APInt::getHighBitsSet(OpSizeInBits, RShVal);
2511 Mask &= cast<ConstantSDNode>(RHSMask)->getAPIntValue() | LHSBits;
2514 Rot = DAG.getNode(ISD::AND, DL, VT, Rot, DAG.getConstant(Mask, VT));
2517 return Rot.getNode();
2520 // If there is a mask here, and we have a variable shift, we can't be sure
2521 // that we're masking out the right stuff.
2522 if (LHSMask.getNode() || RHSMask.getNode())
2525 // fold (or (shl x, y), (srl x, (sub 32, y))) -> (rotl x, y)
2526 // fold (or (shl x, y), (srl x, (sub 32, y))) -> (rotr x, (sub 32, y))
2527 if (RHSShiftAmt.getOpcode() == ISD::SUB &&
2528 LHSShiftAmt == RHSShiftAmt.getOperand(1)) {
2529 if (ConstantSDNode *SUBC =
2530 dyn_cast<ConstantSDNode>(RHSShiftAmt.getOperand(0))) {
2531 if (SUBC->getAPIntValue() == OpSizeInBits) {
2533 return DAG.getNode(ISD::ROTL, DL, VT,
2534 LHSShiftArg, LHSShiftAmt).getNode();
2536 return DAG.getNode(ISD::ROTR, DL, VT,
2537 LHSShiftArg, RHSShiftAmt).getNode();
2542 // fold (or (shl x, (sub 32, y)), (srl x, r)) -> (rotr x, y)
2543 // fold (or (shl x, (sub 32, y)), (srl x, r)) -> (rotl x, (sub 32, y))
2544 if (LHSShiftAmt.getOpcode() == ISD::SUB &&
2545 RHSShiftAmt == LHSShiftAmt.getOperand(1)) {
2546 if (ConstantSDNode *SUBC =
2547 dyn_cast<ConstantSDNode>(LHSShiftAmt.getOperand(0))) {
2548 if (SUBC->getAPIntValue() == OpSizeInBits) {
2550 return DAG.getNode(ISD::ROTR, DL, VT,
2551 LHSShiftArg, RHSShiftAmt).getNode();
2553 return DAG.getNode(ISD::ROTL, DL, VT,
2554 LHSShiftArg, LHSShiftAmt).getNode();
2559 // Look for sign/zext/any-extended or truncate cases:
2560 if ((LHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND
2561 || LHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND
2562 || LHSShiftAmt.getOpcode() == ISD::ANY_EXTEND
2563 || LHSShiftAmt.getOpcode() == ISD::TRUNCATE) &&
2564 (RHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND
2565 || RHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND
2566 || RHSShiftAmt.getOpcode() == ISD::ANY_EXTEND
2567 || RHSShiftAmt.getOpcode() == ISD::TRUNCATE)) {
2568 SDValue LExtOp0 = LHSShiftAmt.getOperand(0);
2569 SDValue RExtOp0 = RHSShiftAmt.getOperand(0);
2570 if (RExtOp0.getOpcode() == ISD::SUB &&
2571 RExtOp0.getOperand(1) == LExtOp0) {
2572 // fold (or (shl x, (*ext y)), (srl x, (*ext (sub 32, y)))) ->
2574 // fold (or (shl x, (*ext y)), (srl x, (*ext (sub 32, y)))) ->
2575 // (rotr x, (sub 32, y))
2576 if (ConstantSDNode *SUBC =
2577 dyn_cast<ConstantSDNode>(RExtOp0.getOperand(0))) {
2578 if (SUBC->getAPIntValue() == OpSizeInBits) {
2579 return DAG.getNode(HasROTL ? ISD::ROTL : ISD::ROTR, DL, VT,
2581 HasROTL ? LHSShiftAmt : RHSShiftAmt).getNode();
2584 } else if (LExtOp0.getOpcode() == ISD::SUB &&
2585 RExtOp0 == LExtOp0.getOperand(1)) {
2586 // fold (or (shl x, (*ext (sub 32, y))), (srl x, (*ext y))) ->
2588 // fold (or (shl x, (*ext (sub 32, y))), (srl x, (*ext y))) ->
2589 // (rotl x, (sub 32, y))
2590 if (ConstantSDNode *SUBC =
2591 dyn_cast<ConstantSDNode>(LExtOp0.getOperand(0))) {
2592 if (SUBC->getAPIntValue() == OpSizeInBits) {
2593 return DAG.getNode(HasROTR ? ISD::ROTR : ISD::ROTL, DL, VT,
2595 HasROTR ? RHSShiftAmt : LHSShiftAmt).getNode();
2604 SDValue DAGCombiner::visitXOR(SDNode *N) {
2605 SDValue N0 = N->getOperand(0);
2606 SDValue N1 = N->getOperand(1);
2607 SDValue LHS, RHS, CC;
2608 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
2609 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2610 EVT VT = N0.getValueType();
2613 if (VT.isVector()) {
2614 SDValue FoldedVOp = SimplifyVBinOp(N);
2615 if (FoldedVOp.getNode()) return FoldedVOp;
2618 // fold (xor undef, undef) -> 0. This is a common idiom (misuse).
2619 if (N0.getOpcode() == ISD::UNDEF && N1.getOpcode() == ISD::UNDEF)
2620 return DAG.getConstant(0, VT);
2621 // fold (xor x, undef) -> undef
2622 if (N0.getOpcode() == ISD::UNDEF)
2624 if (N1.getOpcode() == ISD::UNDEF)
2626 // fold (xor c1, c2) -> c1^c2
2628 return DAG.FoldConstantArithmetic(ISD::XOR, VT, N0C, N1C);
2629 // canonicalize constant to RHS
2631 return DAG.getNode(ISD::XOR, N->getDebugLoc(), VT, N1, N0);
2632 // fold (xor x, 0) -> x
2633 if (N1C && N1C->isNullValue())
2636 SDValue RXOR = ReassociateOps(ISD::XOR, N->getDebugLoc(), N0, N1);
2637 if (RXOR.getNode() != 0)
2640 // fold !(x cc y) -> (x !cc y)
2641 if (N1C && N1C->getAPIntValue() == 1 && isSetCCEquivalent(N0, LHS, RHS, CC)) {
2642 bool isInt = LHS.getValueType().isInteger();
2643 ISD::CondCode NotCC = ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(),
2646 if (!LegalOperations || TLI.isCondCodeLegal(NotCC, LHS.getValueType())) {
2647 switch (N0.getOpcode()) {
2649 llvm_unreachable("Unhandled SetCC Equivalent!");
2651 return DAG.getSetCC(N->getDebugLoc(), VT, LHS, RHS, NotCC);
2652 case ISD::SELECT_CC:
2653 return DAG.getSelectCC(N->getDebugLoc(), LHS, RHS, N0.getOperand(2),
2654 N0.getOperand(3), NotCC);
2659 // fold (not (zext (setcc x, y))) -> (zext (not (setcc x, y)))
2660 if (N1C && N1C->getAPIntValue() == 1 && N0.getOpcode() == ISD::ZERO_EXTEND &&
2661 N0.getNode()->hasOneUse() &&
2662 isSetCCEquivalent(N0.getOperand(0), LHS, RHS, CC)){
2663 SDValue V = N0.getOperand(0);
2664 V = DAG.getNode(ISD::XOR, N0.getDebugLoc(), V.getValueType(), V,
2665 DAG.getConstant(1, V.getValueType()));
2666 AddToWorkList(V.getNode());
2667 return DAG.getNode(ISD::ZERO_EXTEND, N->getDebugLoc(), VT, V);
2670 // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are setcc
2671 if (N1C && N1C->getAPIntValue() == 1 && VT == MVT::i1 &&
2672 (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
2673 SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
2674 if (isOneUseSetCC(RHS) || isOneUseSetCC(LHS)) {
2675 unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
2676 LHS = DAG.getNode(ISD::XOR, LHS.getDebugLoc(), VT, LHS, N1); // LHS = ~LHS
2677 RHS = DAG.getNode(ISD::XOR, RHS.getDebugLoc(), VT, RHS, N1); // RHS = ~RHS
2678 AddToWorkList(LHS.getNode()); AddToWorkList(RHS.getNode());
2679 return DAG.getNode(NewOpcode, N->getDebugLoc(), VT, LHS, RHS);
2682 // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are constants
2683 if (N1C && N1C->isAllOnesValue() &&
2684 (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
2685 SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
2686 if (isa<ConstantSDNode>(RHS) || isa<ConstantSDNode>(LHS)) {
2687 unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
2688 LHS = DAG.getNode(ISD::XOR, LHS.getDebugLoc(), VT, LHS, N1); // LHS = ~LHS
2689 RHS = DAG.getNode(ISD::XOR, RHS.getDebugLoc(), VT, RHS, N1); // RHS = ~RHS
2690 AddToWorkList(LHS.getNode()); AddToWorkList(RHS.getNode());
2691 return DAG.getNode(NewOpcode, N->getDebugLoc(), VT, LHS, RHS);
2694 // fold (xor (xor x, c1), c2) -> (xor x, (xor c1, c2))
2695 if (N1C && N0.getOpcode() == ISD::XOR) {
2696 ConstantSDNode *N00C = dyn_cast<ConstantSDNode>(N0.getOperand(0));
2697 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
2699 return DAG.getNode(ISD::XOR, N->getDebugLoc(), VT, N0.getOperand(1),
2700 DAG.getConstant(N1C->getAPIntValue() ^
2701 N00C->getAPIntValue(), VT));
2703 return DAG.getNode(ISD::XOR, N->getDebugLoc(), VT, N0.getOperand(0),
2704 DAG.getConstant(N1C->getAPIntValue() ^
2705 N01C->getAPIntValue(), VT));
2707 // fold (xor x, x) -> 0
2709 if (!VT.isVector()) {
2710 return DAG.getConstant(0, VT);
2711 } else if (!LegalOperations || TLI.isOperationLegal(ISD::BUILD_VECTOR, VT)){
2712 // Produce a vector of zeros.
2713 SDValue El = DAG.getConstant(0, VT.getVectorElementType());
2714 std::vector<SDValue> Ops(VT.getVectorNumElements(), El);
2715 return DAG.getNode(ISD::BUILD_VECTOR, N->getDebugLoc(), VT,
2716 &Ops[0], Ops.size());
2720 // Simplify: xor (op x...), (op y...) -> (op (xor x, y))
2721 if (N0.getOpcode() == N1.getOpcode()) {
2722 SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
2723 if (Tmp.getNode()) return Tmp;
2726 // Simplify the expression using non-local knowledge.
2727 if (!VT.isVector() &&
2728 SimplifyDemandedBits(SDValue(N, 0)))
2729 return SDValue(N, 0);
2734 /// visitShiftByConstant - Handle transforms common to the three shifts, when
2735 /// the shift amount is a constant.
2736 SDValue DAGCombiner::visitShiftByConstant(SDNode *N, unsigned Amt) {
2737 SDNode *LHS = N->getOperand(0).getNode();
2738 if (!LHS->hasOneUse()) return SDValue();
2740 // We want to pull some binops through shifts, so that we have (and (shift))
2741 // instead of (shift (and)), likewise for add, or, xor, etc. This sort of
2742 // thing happens with address calculations, so it's important to canonicalize
2744 bool HighBitSet = false; // Can we transform this if the high bit is set?
2746 switch (LHS->getOpcode()) {
2747 default: return SDValue();
2750 HighBitSet = false; // We can only transform sra if the high bit is clear.
2753 HighBitSet = true; // We can only transform sra if the high bit is set.
2756 if (N->getOpcode() != ISD::SHL)
2757 return SDValue(); // only shl(add) not sr[al](add).
2758 HighBitSet = false; // We can only transform sra if the high bit is clear.
2762 // We require the RHS of the binop to be a constant as well.
2763 ConstantSDNode *BinOpCst = dyn_cast<ConstantSDNode>(LHS->getOperand(1));
2764 if (!BinOpCst) return SDValue();
2766 // FIXME: disable this unless the input to the binop is a shift by a constant.
2767 // If it is not a shift, it pessimizes some common cases like:
2769 // void foo(int *X, int i) { X[i & 1235] = 1; }
2770 // int bar(int *X, int i) { return X[i & 255]; }
2771 SDNode *BinOpLHSVal = LHS->getOperand(0).getNode();
2772 if ((BinOpLHSVal->getOpcode() != ISD::SHL &&
2773 BinOpLHSVal->getOpcode() != ISD::SRA &&
2774 BinOpLHSVal->getOpcode() != ISD::SRL) ||
2775 !isa<ConstantSDNode>(BinOpLHSVal->getOperand(1)))
2778 EVT VT = N->getValueType(0);
2780 // If this is a signed shift right, and the high bit is modified by the
2781 // logical operation, do not perform the transformation. The highBitSet
2782 // boolean indicates the value of the high bit of the constant which would
2783 // cause it to be modified for this operation.
2784 if (N->getOpcode() == ISD::SRA) {
2785 bool BinOpRHSSignSet = BinOpCst->getAPIntValue().isNegative();
2786 if (BinOpRHSSignSet != HighBitSet)
2790 // Fold the constants, shifting the binop RHS by the shift amount.
2791 SDValue NewRHS = DAG.getNode(N->getOpcode(), LHS->getOperand(1).getDebugLoc(),
2793 LHS->getOperand(1), N->getOperand(1));
2795 // Create the new shift.
2796 SDValue NewShift = DAG.getNode(N->getOpcode(), LHS->getOperand(0).getDebugLoc(),
2797 VT, LHS->getOperand(0), N->getOperand(1));
2799 // Create the new binop.
2800 return DAG.getNode(LHS->getOpcode(), N->getDebugLoc(), VT, NewShift, NewRHS);
2803 SDValue DAGCombiner::visitSHL(SDNode *N) {
2804 SDValue N0 = N->getOperand(0);
2805 SDValue N1 = N->getOperand(1);
2806 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
2807 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2808 EVT VT = N0.getValueType();
2809 unsigned OpSizeInBits = VT.getScalarType().getSizeInBits();
2811 // fold (shl c1, c2) -> c1<<c2
2813 return DAG.FoldConstantArithmetic(ISD::SHL, VT, N0C, N1C);
2814 // fold (shl 0, x) -> 0
2815 if (N0C && N0C->isNullValue())
2817 // fold (shl x, c >= size(x)) -> undef
2818 if (N1C && N1C->getZExtValue() >= OpSizeInBits)
2819 return DAG.getUNDEF(VT);
2820 // fold (shl x, 0) -> x
2821 if (N1C && N1C->isNullValue())
2823 // if (shl x, c) is known to be zero, return 0
2824 if (DAG.MaskedValueIsZero(SDValue(N, 0),
2825 APInt::getAllOnesValue(OpSizeInBits)))
2826 return DAG.getConstant(0, VT);
2827 // fold (shl x, (trunc (and y, c))) -> (shl x, (and (trunc y), (trunc c))).
2828 if (N1.getOpcode() == ISD::TRUNCATE &&
2829 N1.getOperand(0).getOpcode() == ISD::AND &&
2830 N1.hasOneUse() && N1.getOperand(0).hasOneUse()) {
2831 SDValue N101 = N1.getOperand(0).getOperand(1);
2832 if (ConstantSDNode *N101C = dyn_cast<ConstantSDNode>(N101)) {
2833 EVT TruncVT = N1.getValueType();
2834 SDValue N100 = N1.getOperand(0).getOperand(0);
2835 APInt TruncC = N101C->getAPIntValue();
2836 TruncC.trunc(TruncVT.getSizeInBits());
2837 return DAG.getNode(ISD::SHL, N->getDebugLoc(), VT, N0,
2838 DAG.getNode(ISD::AND, N->getDebugLoc(), TruncVT,
2839 DAG.getNode(ISD::TRUNCATE,
2842 DAG.getConstant(TruncC, TruncVT)));
2846 if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
2847 return SDValue(N, 0);
2849 // fold (shl (shl x, c1), c2) -> 0 or (shl x, (add c1, c2))
2850 if (N1C && N0.getOpcode() == ISD::SHL &&
2851 N0.getOperand(1).getOpcode() == ISD::Constant) {
2852 uint64_t c1 = cast<ConstantSDNode>(N0.getOperand(1))->getZExtValue();
2853 uint64_t c2 = N1C->getZExtValue();
2854 if (c1 + c2 > OpSizeInBits)
2855 return DAG.getConstant(0, VT);
2856 return DAG.getNode(ISD::SHL, N->getDebugLoc(), VT, N0.getOperand(0),
2857 DAG.getConstant(c1 + c2, N1.getValueType()));
2859 // fold (shl (srl x, c1), c2) -> (shl (and x, (shl -1, c1)), (sub c2, c1)) or
2860 // (srl (and x, (shl -1, c1)), (sub c1, c2))
2861 if (N1C && N0.getOpcode() == ISD::SRL &&
2862 N0.getOperand(1).getOpcode() == ISD::Constant) {
2863 uint64_t c1 = cast<ConstantSDNode>(N0.getOperand(1))->getZExtValue();
2864 if (c1 < VT.getSizeInBits()) {
2865 uint64_t c2 = N1C->getZExtValue();
2866 SDValue HiBitsMask =
2867 DAG.getConstant(APInt::getHighBitsSet(VT.getSizeInBits(),
2868 VT.getSizeInBits() - c1),
2870 SDValue Mask = DAG.getNode(ISD::AND, N0.getDebugLoc(), VT,
2874 return DAG.getNode(ISD::SHL, N->getDebugLoc(), VT, Mask,
2875 DAG.getConstant(c2-c1, N1.getValueType()));
2877 return DAG.getNode(ISD::SRL, N->getDebugLoc(), VT, Mask,
2878 DAG.getConstant(c1-c2, N1.getValueType()));
2881 // fold (shl (sra x, c1), c1) -> (and x, (shl -1, c1))
2882 if (N1C && N0.getOpcode() == ISD::SRA && N1 == N0.getOperand(1)) {
2883 SDValue HiBitsMask =
2884 DAG.getConstant(APInt::getHighBitsSet(VT.getSizeInBits(),
2885 VT.getSizeInBits() -
2886 N1C->getZExtValue()),
2888 return DAG.getNode(ISD::AND, N->getDebugLoc(), VT, N0.getOperand(0),
2893 SDValue NewSHL = visitShiftByConstant(N, N1C->getZExtValue());
2894 if (NewSHL.getNode())
2901 SDValue DAGCombiner::visitSRA(SDNode *N) {
2902 SDValue N0 = N->getOperand(0);
2903 SDValue N1 = N->getOperand(1);
2904 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
2905 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2906 EVT VT = N0.getValueType();
2907 unsigned OpSizeInBits = VT.getScalarType().getSizeInBits();
2909 // fold (sra c1, c2) -> (sra c1, c2)
2911 return DAG.FoldConstantArithmetic(ISD::SRA, VT, N0C, N1C);
2912 // fold (sra 0, x) -> 0
2913 if (N0C && N0C->isNullValue())
2915 // fold (sra -1, x) -> -1
2916 if (N0C && N0C->isAllOnesValue())
2918 // fold (sra x, (setge c, size(x))) -> undef
2919 if (N1C && N1C->getZExtValue() >= OpSizeInBits)
2920 return DAG.getUNDEF(VT);
2921 // fold (sra x, 0) -> x
2922 if (N1C && N1C->isNullValue())
2924 // fold (sra (shl x, c1), c1) -> sext_inreg for some c1 and target supports
2926 if (N1C && N0.getOpcode() == ISD::SHL && N1 == N0.getOperand(1)) {
2927 unsigned LowBits = OpSizeInBits - (unsigned)N1C->getZExtValue();
2928 EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), LowBits);
2930 ExtVT = EVT::getVectorVT(*DAG.getContext(),
2931 ExtVT, VT.getVectorNumElements());
2932 if ((!LegalOperations ||
2933 TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, ExtVT)))
2934 return DAG.getNode(ISD::SIGN_EXTEND_INREG, N->getDebugLoc(), VT,
2935 N0.getOperand(0), DAG.getValueType(ExtVT));
2938 // fold (sra (sra x, c1), c2) -> (sra x, (add c1, c2))
2939 if (N1C && N0.getOpcode() == ISD::SRA) {
2940 if (ConstantSDNode *C1 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
2941 unsigned Sum = N1C->getZExtValue() + C1->getZExtValue();
2942 if (Sum >= OpSizeInBits) Sum = OpSizeInBits-1;
2943 return DAG.getNode(ISD::SRA, N->getDebugLoc(), VT, N0.getOperand(0),
2944 DAG.getConstant(Sum, N1C->getValueType(0)));
2948 // fold (sra (shl X, m), (sub result_size, n))
2949 // -> (sign_extend (trunc (shl X, (sub (sub result_size, n), m)))) for
2950 // result_size - n != m.
2951 // If truncate is free for the target sext(shl) is likely to result in better
2953 if (N0.getOpcode() == ISD::SHL) {
2954 // Get the two constanst of the shifts, CN0 = m, CN = n.
2955 const ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
2957 // Determine what the truncate's result bitsize and type would be.
2959 EVT::getIntegerVT(*DAG.getContext(), OpSizeInBits - N1C->getZExtValue());
2960 // Determine the residual right-shift amount.
2961 signed ShiftAmt = N1C->getZExtValue() - N01C->getZExtValue();
2963 // If the shift is not a no-op (in which case this should be just a sign
2964 // extend already), the truncated to type is legal, sign_extend is legal
2965 // on that type, and the truncate to that type is both legal and free,
2966 // perform the transform.
2967 if ((ShiftAmt > 0) &&
2968 TLI.isOperationLegalOrCustom(ISD::SIGN_EXTEND, TruncVT) &&
2969 TLI.isOperationLegalOrCustom(ISD::TRUNCATE, VT) &&
2970 TLI.isTruncateFree(VT, TruncVT)) {
2972 SDValue Amt = DAG.getConstant(ShiftAmt, getShiftAmountTy());
2973 SDValue Shift = DAG.getNode(ISD::SRL, N0.getDebugLoc(), VT,
2974 N0.getOperand(0), Amt);
2975 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, N0.getDebugLoc(), TruncVT,
2977 return DAG.getNode(ISD::SIGN_EXTEND, N->getDebugLoc(),
2978 N->getValueType(0), Trunc);
2983 // fold (sra x, (trunc (and y, c))) -> (sra x, (and (trunc y), (trunc c))).
2984 if (N1.getOpcode() == ISD::TRUNCATE &&
2985 N1.getOperand(0).getOpcode() == ISD::AND &&
2986 N1.hasOneUse() && N1.getOperand(0).hasOneUse()) {
2987 SDValue N101 = N1.getOperand(0).getOperand(1);
2988 if (ConstantSDNode *N101C = dyn_cast<ConstantSDNode>(N101)) {
2989 EVT TruncVT = N1.getValueType();
2990 SDValue N100 = N1.getOperand(0).getOperand(0);
2991 APInt TruncC = N101C->getAPIntValue();
2992 TruncC.trunc(TruncVT.getScalarType().getSizeInBits());
2993 return DAG.getNode(ISD::SRA, N->getDebugLoc(), VT, N0,
2994 DAG.getNode(ISD::AND, N->getDebugLoc(),
2996 DAG.getNode(ISD::TRUNCATE,
2999 DAG.getConstant(TruncC, TruncVT)));
3003 // Simplify, based on bits shifted out of the LHS.
3004 if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
3005 return SDValue(N, 0);
3008 // If the sign bit is known to be zero, switch this to a SRL.
3009 if (DAG.SignBitIsZero(N0))
3010 return DAG.getNode(ISD::SRL, N->getDebugLoc(), VT, N0, N1);
3013 SDValue NewSRA = visitShiftByConstant(N, N1C->getZExtValue());
3014 if (NewSRA.getNode())
3021 SDValue DAGCombiner::visitSRL(SDNode *N) {
3022 SDValue N0 = N->getOperand(0);
3023 SDValue N1 = N->getOperand(1);
3024 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
3025 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
3026 EVT VT = N0.getValueType();
3027 unsigned OpSizeInBits = VT.getScalarType().getSizeInBits();
3029 // fold (srl c1, c2) -> c1 >>u c2
3031 return DAG.FoldConstantArithmetic(ISD::SRL, VT, N0C, N1C);
3032 // fold (srl 0, x) -> 0
3033 if (N0C && N0C->isNullValue())
3035 // fold (srl x, c >= size(x)) -> undef
3036 if (N1C && N1C->getZExtValue() >= OpSizeInBits)
3037 return DAG.getUNDEF(VT);
3038 // fold (srl x, 0) -> x
3039 if (N1C && N1C->isNullValue())
3041 // if (srl x, c) is known to be zero, return 0
3042 if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0),
3043 APInt::getAllOnesValue(OpSizeInBits)))
3044 return DAG.getConstant(0, VT);
3046 // fold (srl (srl x, c1), c2) -> 0 or (srl x, (add c1, c2))
3047 if (N1C && N0.getOpcode() == ISD::SRL &&
3048 N0.getOperand(1).getOpcode() == ISD::Constant) {
3049 uint64_t c1 = cast<ConstantSDNode>(N0.getOperand(1))->getZExtValue();
3050 uint64_t c2 = N1C->getZExtValue();
3051 if (c1 + c2 > OpSizeInBits)
3052 return DAG.getConstant(0, VT);
3053 return DAG.getNode(ISD::SRL, N->getDebugLoc(), VT, N0.getOperand(0),
3054 DAG.getConstant(c1 + c2, N1.getValueType()));
3057 // fold (srl (shl x, c), c) -> (and x, cst2)
3058 if (N1C && N0.getOpcode() == ISD::SHL && N0.getOperand(1) == N1 &&
3059 N0.getValueSizeInBits() <= 64) {
3060 uint64_t ShAmt = N1C->getZExtValue()+64-N0.getValueSizeInBits();
3061 return DAG.getNode(ISD::AND, N->getDebugLoc(), VT, N0.getOperand(0),
3062 DAG.getConstant(~0ULL >> ShAmt, VT));
3066 // fold (srl (anyextend x), c) -> (anyextend (srl x, c))
3067 if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
3068 // Shifting in all undef bits?
3069 EVT SmallVT = N0.getOperand(0).getValueType();
3070 if (N1C->getZExtValue() >= SmallVT.getSizeInBits())
3071 return DAG.getUNDEF(VT);
3073 if (!LegalTypes || TLI.isTypeDesirableForOp(ISD::SRL, SmallVT)) {
3074 SDValue SmallShift = DAG.getNode(ISD::SRL, N0.getDebugLoc(), SmallVT,
3075 N0.getOperand(0), N1);
3076 AddToWorkList(SmallShift.getNode());
3077 return DAG.getNode(ISD::ANY_EXTEND, N->getDebugLoc(), VT, SmallShift);
3081 // fold (srl (sra X, Y), 31) -> (srl X, 31). This srl only looks at the sign
3082 // bit, which is unmodified by sra.
3083 if (N1C && N1C->getZExtValue() + 1 == VT.getSizeInBits()) {
3084 if (N0.getOpcode() == ISD::SRA)
3085 return DAG.getNode(ISD::SRL, N->getDebugLoc(), VT, N0.getOperand(0), N1);
3088 // fold (srl (ctlz x), "5") -> x iff x has one bit set (the low bit).
3089 if (N1C && N0.getOpcode() == ISD::CTLZ &&
3090 N1C->getAPIntValue() == Log2_32(VT.getSizeInBits())) {
3091 APInt KnownZero, KnownOne;
3092 APInt Mask = APInt::getAllOnesValue(VT.getScalarType().getSizeInBits());
3093 DAG.ComputeMaskedBits(N0.getOperand(0), Mask, KnownZero, KnownOne);
3095 // If any of the input bits are KnownOne, then the input couldn't be all
3096 // zeros, thus the result of the srl will always be zero.
3097 if (KnownOne.getBoolValue()) return DAG.getConstant(0, VT);
3099 // If all of the bits input the to ctlz node are known to be zero, then
3100 // the result of the ctlz is "32" and the result of the shift is one.
3101 APInt UnknownBits = ~KnownZero & Mask;
3102 if (UnknownBits == 0) return DAG.getConstant(1, VT);
3104 // Otherwise, check to see if there is exactly one bit input to the ctlz.
3105 if ((UnknownBits & (UnknownBits - 1)) == 0) {
3106 // Okay, we know that only that the single bit specified by UnknownBits
3107 // could be set on input to the CTLZ node. If this bit is set, the SRL
3108 // will return 0, if it is clear, it returns 1. Change the CTLZ/SRL pair
3109 // to an SRL/XOR pair, which is likely to simplify more.
3110 unsigned ShAmt = UnknownBits.countTrailingZeros();
3111 SDValue Op = N0.getOperand(0);
3114 Op = DAG.getNode(ISD::SRL, N0.getDebugLoc(), VT, Op,
3115 DAG.getConstant(ShAmt, getShiftAmountTy()));
3116 AddToWorkList(Op.getNode());
3119 return DAG.getNode(ISD::XOR, N->getDebugLoc(), VT,
3120 Op, DAG.getConstant(1, VT));
3124 // fold (srl x, (trunc (and y, c))) -> (srl x, (and (trunc y), (trunc c))).
3125 if (N1.getOpcode() == ISD::TRUNCATE &&
3126 N1.getOperand(0).getOpcode() == ISD::AND &&
3127 N1.hasOneUse() && N1.getOperand(0).hasOneUse()) {
3128 SDValue N101 = N1.getOperand(0).getOperand(1);
3129 if (ConstantSDNode *N101C = dyn_cast<ConstantSDNode>(N101)) {
3130 EVT TruncVT = N1.getValueType();
3131 SDValue N100 = N1.getOperand(0).getOperand(0);
3132 APInt TruncC = N101C->getAPIntValue();
3133 TruncC.trunc(TruncVT.getSizeInBits());
3134 return DAG.getNode(ISD::SRL, N->getDebugLoc(), VT, N0,
3135 DAG.getNode(ISD::AND, N->getDebugLoc(),
3137 DAG.getNode(ISD::TRUNCATE,
3140 DAG.getConstant(TruncC, TruncVT)));
3144 // fold operands of srl based on knowledge that the low bits are not
3146 if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
3147 return SDValue(N, 0);
3150 SDValue NewSRL = visitShiftByConstant(N, N1C->getZExtValue());
3151 if (NewSRL.getNode())
3155 // Here is a common situation. We want to optimize:
3158 // %b = and i32 %a, 2
3159 // %c = srl i32 %b, 1
3160 // brcond i32 %c ...
3166 // %c = setcc eq %b, 0
3169 // However when after the source operand of SRL is optimized into AND, the SRL
3170 // itself may not be optimized further. Look for it and add the BRCOND into
3172 if (N->hasOneUse()) {
3173 SDNode *Use = *N->use_begin();
3174 if (Use->getOpcode() == ISD::BRCOND)
3176 else if (Use->getOpcode() == ISD::TRUNCATE && Use->hasOneUse()) {
3177 // Also look pass the truncate.
3178 Use = *Use->use_begin();
3179 if (Use->getOpcode() == ISD::BRCOND)
3187 SDValue DAGCombiner::visitCTLZ(SDNode *N) {
3188 SDValue N0 = N->getOperand(0);
3189 EVT VT = N->getValueType(0);
3191 // fold (ctlz c1) -> c2
3192 if (isa<ConstantSDNode>(N0))
3193 return DAG.getNode(ISD::CTLZ, N->getDebugLoc(), VT, N0);
3197 SDValue DAGCombiner::visitCTTZ(SDNode *N) {
3198 SDValue N0 = N->getOperand(0);
3199 EVT VT = N->getValueType(0);
3201 // fold (cttz c1) -> c2
3202 if (isa<ConstantSDNode>(N0))
3203 return DAG.getNode(ISD::CTTZ, N->getDebugLoc(), VT, N0);
3207 SDValue DAGCombiner::visitCTPOP(SDNode *N) {
3208 SDValue N0 = N->getOperand(0);
3209 EVT VT = N->getValueType(0);
3211 // fold (ctpop c1) -> c2
3212 if (isa<ConstantSDNode>(N0))
3213 return DAG.getNode(ISD::CTPOP, N->getDebugLoc(), VT, N0);
3217 SDValue DAGCombiner::visitSELECT(SDNode *N) {
3218 SDValue N0 = N->getOperand(0);
3219 SDValue N1 = N->getOperand(1);
3220 SDValue N2 = N->getOperand(2);
3221 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
3222 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
3223 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2);
3224 EVT VT = N->getValueType(0);
3225 EVT VT0 = N0.getValueType();
3227 // fold (select C, X, X) -> X
3230 // fold (select true, X, Y) -> X
3231 if (N0C && !N0C->isNullValue())
3233 // fold (select false, X, Y) -> Y
3234 if (N0C && N0C->isNullValue())
3236 // fold (select C, 1, X) -> (or C, X)
3237 if (VT == MVT::i1 && N1C && N1C->getAPIntValue() == 1)
3238 return DAG.getNode(ISD::OR, N->getDebugLoc(), VT, N0, N2);
3239 // fold (select C, 0, 1) -> (xor C, 1)
3240 if (VT.isInteger() &&
3243 TLI.getBooleanContents() == TargetLowering::ZeroOrOneBooleanContent)) &&
3244 N1C && N2C && N1C->isNullValue() && N2C->getAPIntValue() == 1) {
3247 return DAG.getNode(ISD::XOR, N->getDebugLoc(), VT0,
3248 N0, DAG.getConstant(1, VT0));
3249 XORNode = DAG.getNode(ISD::XOR, N0.getDebugLoc(), VT0,
3250 N0, DAG.getConstant(1, VT0));
3251 AddToWorkList(XORNode.getNode());
3253 return DAG.getNode(ISD::ZERO_EXTEND, N->getDebugLoc(), VT, XORNode);
3254 return DAG.getNode(ISD::TRUNCATE, N->getDebugLoc(), VT, XORNode);
3256 // fold (select C, 0, X) -> (and (not C), X)
3257 if (VT == VT0 && VT == MVT::i1 && N1C && N1C->isNullValue()) {
3258 SDValue NOTNode = DAG.getNOT(N0.getDebugLoc(), N0, VT);
3259 AddToWorkList(NOTNode.getNode());
3260 return DAG.getNode(ISD::AND, N->getDebugLoc(), VT, NOTNode, N2);
3262 // fold (select C, X, 1) -> (or (not C), X)
3263 if (VT == VT0 && VT == MVT::i1 && N2C && N2C->getAPIntValue() == 1) {
3264 SDValue NOTNode = DAG.getNOT(N0.getDebugLoc(), N0, VT);
3265 AddToWorkList(NOTNode.getNode());
3266 return DAG.getNode(ISD::OR, N->getDebugLoc(), VT, NOTNode, N1);
3268 // fold (select C, X, 0) -> (and C, X)
3269 if (VT == MVT::i1 && N2C && N2C->isNullValue())
3270 return DAG.getNode(ISD::AND, N->getDebugLoc(), VT, N0, N1);
3271 // fold (select X, X, Y) -> (or X, Y)
3272 // fold (select X, 1, Y) -> (or X, Y)
3273 if (VT == MVT::i1 && (N0 == N1 || (N1C && N1C->getAPIntValue() == 1)))
3274 return DAG.getNode(ISD::OR, N->getDebugLoc(), VT, N0, N2);
3275 // fold (select X, Y, X) -> (and X, Y)
3276 // fold (select X, Y, 0) -> (and X, Y)
3277 if (VT == MVT::i1 && (N0 == N2 || (N2C && N2C->getAPIntValue() == 0)))
3278 return DAG.getNode(ISD::AND, N->getDebugLoc(), VT, N0, N1);
3280 // If we can fold this based on the true/false value, do so.
3281 if (SimplifySelectOps(N, N1, N2))
3282 return SDValue(N, 0); // Don't revisit N.
3284 // fold selects based on a setcc into other things, such as min/max/abs
3285 if (N0.getOpcode() == ISD::SETCC) {
3287 // Check against MVT::Other for SELECT_CC, which is a workaround for targets
3288 // having to say they don't support SELECT_CC on every type the DAG knows
3289 // about, since there is no way to mark an opcode illegal at all value types
3290 if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, MVT::Other) &&
3291 TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT))
3292 return DAG.getNode(ISD::SELECT_CC, N->getDebugLoc(), VT,
3293 N0.getOperand(0), N0.getOperand(1),
3294 N1, N2, N0.getOperand(2));
3295 return SimplifySelect(N->getDebugLoc(), N0, N1, N2);
3301 SDValue DAGCombiner::visitSELECT_CC(SDNode *N) {
3302 SDValue N0 = N->getOperand(0);
3303 SDValue N1 = N->getOperand(1);
3304 SDValue N2 = N->getOperand(2);
3305 SDValue N3 = N->getOperand(3);
3306 SDValue N4 = N->getOperand(4);
3307 ISD::CondCode CC = cast<CondCodeSDNode>(N4)->get();
3309 // fold select_cc lhs, rhs, x, x, cc -> x
3313 // Determine if the condition we're dealing with is constant
3314 SDValue SCC = SimplifySetCC(TLI.getSetCCResultType(N0.getValueType()),
3315 N0, N1, CC, N->getDebugLoc(), false);
3316 if (SCC.getNode()) AddToWorkList(SCC.getNode());
3318 if (ConstantSDNode *SCCC = dyn_cast_or_null<ConstantSDNode>(SCC.getNode())) {
3319 if (!SCCC->isNullValue())
3320 return N2; // cond always true -> true val
3322 return N3; // cond always false -> false val
3325 // Fold to a simpler select_cc
3326 if (SCC.getNode() && SCC.getOpcode() == ISD::SETCC)
3327 return DAG.getNode(ISD::SELECT_CC, N->getDebugLoc(), N2.getValueType(),
3328 SCC.getOperand(0), SCC.getOperand(1), N2, N3,
3331 // If we can fold this based on the true/false value, do so.
3332 if (SimplifySelectOps(N, N2, N3))
3333 return SDValue(N, 0); // Don't revisit N.
3335 // fold select_cc into other things, such as min/max/abs
3336 return SimplifySelectCC(N->getDebugLoc(), N0, N1, N2, N3, CC);
3339 SDValue DAGCombiner::visitSETCC(SDNode *N) {
3340 return SimplifySetCC(N->getValueType(0), N->getOperand(0), N->getOperand(1),
3341 cast<CondCodeSDNode>(N->getOperand(2))->get(),
3345 // ExtendUsesToFormExtLoad - Trying to extend uses of a load to enable this:
3346 // "fold ({s|z|a}ext (load x)) -> ({s|z|a}ext (truncate ({s|z|a}extload x)))"
3347 // transformation. Returns true if extension are possible and the above
3348 // mentioned transformation is profitable.
3349 static bool ExtendUsesToFormExtLoad(SDNode *N, SDValue N0,
3351 SmallVector<SDNode*, 4> &ExtendNodes,
3352 const TargetLowering &TLI) {
3353 bool HasCopyToRegUses = false;
3354 bool isTruncFree = TLI.isTruncateFree(N->getValueType(0), N0.getValueType());
3355 for (SDNode::use_iterator UI = N0.getNode()->use_begin(),
3356 UE = N0.getNode()->use_end();
3361 if (UI.getUse().getResNo() != N0.getResNo())
3363 // FIXME: Only extend SETCC N, N and SETCC N, c for now.
3364 if (ExtOpc != ISD::ANY_EXTEND && User->getOpcode() == ISD::SETCC) {
3365 ISD::CondCode CC = cast<CondCodeSDNode>(User->getOperand(2))->get();
3366 if (ExtOpc == ISD::ZERO_EXTEND && ISD::isSignedIntSetCC(CC))
3367 // Sign bits will be lost after a zext.
3370 for (unsigned i = 0; i != 2; ++i) {
3371 SDValue UseOp = User->getOperand(i);
3374 if (!isa<ConstantSDNode>(UseOp))
3379 ExtendNodes.push_back(User);
3382 // If truncates aren't free and there are users we can't
3383 // extend, it isn't worthwhile.
3386 // Remember if this value is live-out.
3387 if (User->getOpcode() == ISD::CopyToReg)
3388 HasCopyToRegUses = true;
3391 if (HasCopyToRegUses) {
3392 bool BothLiveOut = false;
3393 for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
3395 SDUse &Use = UI.getUse();
3396 if (Use.getResNo() == 0 && Use.getUser()->getOpcode() == ISD::CopyToReg) {
3402 // Both unextended and extended values are live out. There had better be
3403 // good a reason for the transformation.
3404 return ExtendNodes.size();
3409 SDValue DAGCombiner::visitSIGN_EXTEND(SDNode *N) {
3410 SDValue N0 = N->getOperand(0);
3411 EVT VT = N->getValueType(0);
3413 // fold (sext c1) -> c1
3414 if (isa<ConstantSDNode>(N0))
3415 return DAG.getNode(ISD::SIGN_EXTEND, N->getDebugLoc(), VT, N0);
3417 // fold (sext (sext x)) -> (sext x)
3418 // fold (sext (aext x)) -> (sext x)
3419 if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
3420 return DAG.getNode(ISD::SIGN_EXTEND, N->getDebugLoc(), VT,
3423 if (N0.getOpcode() == ISD::TRUNCATE) {
3424 // fold (sext (truncate (load x))) -> (sext (smaller load x))
3425 // fold (sext (truncate (srl (load x), c))) -> (sext (smaller load (x+c/n)))
3426 SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
3427 if (NarrowLoad.getNode()) {
3428 if (NarrowLoad.getNode() != N0.getNode())
3429 CombineTo(N0.getNode(), NarrowLoad);
3430 return SDValue(N, 0); // Return N so it doesn't get rechecked!
3433 // See if the value being truncated is already sign extended. If so, just
3434 // eliminate the trunc/sext pair.
3435 SDValue Op = N0.getOperand(0);
3436 unsigned OpBits = Op.getValueType().getScalarType().getSizeInBits();
3437 unsigned MidBits = N0.getValueType().getScalarType().getSizeInBits();
3438 unsigned DestBits = VT.getScalarType().getSizeInBits();
3439 unsigned NumSignBits = DAG.ComputeNumSignBits(Op);
3441 if (OpBits == DestBits) {
3442 // Op is i32, Mid is i8, and Dest is i32. If Op has more than 24 sign
3443 // bits, it is already ready.
3444 if (NumSignBits > DestBits-MidBits)
3446 } else if (OpBits < DestBits) {
3447 // Op is i32, Mid is i8, and Dest is i64. If Op has more than 24 sign
3448 // bits, just sext from i32.
3449 if (NumSignBits > OpBits-MidBits)
3450 return DAG.getNode(ISD::SIGN_EXTEND, N->getDebugLoc(), VT, Op);
3452 // Op is i64, Mid is i8, and Dest is i32. If Op has more than 56 sign
3453 // bits, just truncate to i32.
3454 if (NumSignBits > OpBits-MidBits)
3455 return DAG.getNode(ISD::TRUNCATE, N->getDebugLoc(), VT, Op);
3458 // fold (sext (truncate x)) -> (sextinreg x).
3459 if (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG,
3460 N0.getValueType())) {
3461 if (OpBits < DestBits)
3462 Op = DAG.getNode(ISD::ANY_EXTEND, N0.getDebugLoc(), VT, Op);
3463 else if (OpBits > DestBits)
3464 Op = DAG.getNode(ISD::TRUNCATE, N0.getDebugLoc(), VT, Op);
3465 return DAG.getNode(ISD::SIGN_EXTEND_INREG, N->getDebugLoc(), VT, Op,
3466 DAG.getValueType(N0.getValueType()));
3470 // fold (sext (load x)) -> (sext (truncate (sextload x)))
3471 if (ISD::isNON_EXTLoad(N0.getNode()) &&
3472 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
3473 TLI.isLoadExtLegal(ISD::SEXTLOAD, N0.getValueType()))) {
3474 bool DoXform = true;
3475 SmallVector<SDNode*, 4> SetCCs;
3476 if (!N0.hasOneUse())
3477 DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::SIGN_EXTEND, SetCCs, TLI);
3479 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
3480 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, N->getDebugLoc(), VT,
3482 LN0->getBasePtr(), LN0->getSrcValue(),
3483 LN0->getSrcValueOffset(),
3485 LN0->isVolatile(), LN0->isNonTemporal(),
3486 LN0->getAlignment());
3487 CombineTo(N, ExtLoad);
3488 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, N0.getDebugLoc(),
3489 N0.getValueType(), ExtLoad);
3490 CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
3492 // Extend SetCC uses if necessary.
3493 for (unsigned i = 0, e = SetCCs.size(); i != e; ++i) {
3494 SDNode *SetCC = SetCCs[i];
3495 SmallVector<SDValue, 4> Ops;
3497 for (unsigned j = 0; j != 2; ++j) {
3498 SDValue SOp = SetCC->getOperand(j);
3500 Ops.push_back(ExtLoad);
3502 Ops.push_back(DAG.getNode(ISD::SIGN_EXTEND,
3503 N->getDebugLoc(), VT, SOp));
3506 Ops.push_back(SetCC->getOperand(2));
3507 CombineTo(SetCC, DAG.getNode(ISD::SETCC, N->getDebugLoc(),
3508 SetCC->getValueType(0),
3509 &Ops[0], Ops.size()));
3512 return SDValue(N, 0); // Return N so it doesn't get rechecked!
3516 // fold (sext (sextload x)) -> (sext (truncate (sextload x)))
3517 // fold (sext ( extload x)) -> (sext (truncate (sextload x)))
3518 if ((ISD::isSEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) &&
3519 ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) {
3520 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
3521 EVT MemVT = LN0->getMemoryVT();
3522 if ((!LegalOperations && !LN0->isVolatile()) ||
3523 TLI.isLoadExtLegal(ISD::SEXTLOAD, MemVT)) {
3524 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, N->getDebugLoc(), VT,
3526 LN0->getBasePtr(), LN0->getSrcValue(),
3527 LN0->getSrcValueOffset(), MemVT,
3528 LN0->isVolatile(), LN0->isNonTemporal(),
3529 LN0->getAlignment());
3530 CombineTo(N, ExtLoad);
3531 CombineTo(N0.getNode(),
3532 DAG.getNode(ISD::TRUNCATE, N0.getDebugLoc(),
3533 N0.getValueType(), ExtLoad),
3534 ExtLoad.getValue(1));
3535 return SDValue(N, 0); // Return N so it doesn't get rechecked!
3539 if (N0.getOpcode() == ISD::SETCC) {
3540 // sext(setcc) -> sext_in_reg(vsetcc) for vectors.
3541 if (VT.isVector() &&
3542 // We know that the # elements of the results is the same as the
3543 // # elements of the compare (and the # elements of the compare result
3544 // for that matter). Check to see that they are the same size. If so,
3545 // we know that the element size of the sext'd result matches the
3546 // element size of the compare operands.
3547 VT.getSizeInBits() == N0.getOperand(0).getValueType().getSizeInBits() &&
3549 // Only do this before legalize for now.
3551 return DAG.getVSetCC(N->getDebugLoc(), VT, N0.getOperand(0),
3553 cast<CondCodeSDNode>(N0.getOperand(2))->get());
3556 // sext(setcc x, y, cc) -> (select_cc x, y, -1, 0, cc)
3557 unsigned ElementWidth = VT.getScalarType().getSizeInBits();
3559 DAG.getConstant(APInt::getAllOnesValue(ElementWidth), VT);
3561 SimplifySelectCC(N->getDebugLoc(), N0.getOperand(0), N0.getOperand(1),
3562 NegOne, DAG.getConstant(0, VT),
3563 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
3564 if (SCC.getNode()) return SCC;
3565 if (!LegalOperations ||
3566 TLI.isOperationLegal(ISD::SETCC, TLI.getSetCCResultType(VT)))
3567 return DAG.getNode(ISD::SELECT, N->getDebugLoc(), VT,
3568 DAG.getSetCC(N->getDebugLoc(),
3569 TLI.getSetCCResultType(VT),
3570 N0.getOperand(0), N0.getOperand(1),
3571 cast<CondCodeSDNode>(N0.getOperand(2))->get()),
3572 NegOne, DAG.getConstant(0, VT));
3577 // fold (sext x) -> (zext x) if the sign bit is known zero.
3578 if ((!LegalOperations || TLI.isOperationLegal(ISD::ZERO_EXTEND, VT)) &&
3579 DAG.SignBitIsZero(N0))
3580 return DAG.getNode(ISD::ZERO_EXTEND, N->getDebugLoc(), VT, N0);
3585 SDValue DAGCombiner::visitZERO_EXTEND(SDNode *N) {
3586 SDValue N0 = N->getOperand(0);
3587 EVT VT = N->getValueType(0);
3589 // fold (zext c1) -> c1
3590 if (isa<ConstantSDNode>(N0))
3591 return DAG.getNode(ISD::ZERO_EXTEND, N->getDebugLoc(), VT, N0);
3592 // fold (zext (zext x)) -> (zext x)
3593 // fold (zext (aext x)) -> (zext x)
3594 if (N0.getOpcode() == ISD::ZERO_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
3595 return DAG.getNode(ISD::ZERO_EXTEND, N->getDebugLoc(), VT,
3598 // fold (zext (truncate (load x))) -> (zext (smaller load x))
3599 // fold (zext (truncate (srl (load x), c))) -> (zext (small load (x+c/n)))
3600 if (N0.getOpcode() == ISD::TRUNCATE) {
3601 SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
3602 if (NarrowLoad.getNode()) {
3603 if (NarrowLoad.getNode() != N0.getNode())
3604 CombineTo(N0.getNode(), NarrowLoad);
3605 return DAG.getNode(ISD::ZERO_EXTEND, N->getDebugLoc(), VT, NarrowLoad);
3609 // fold (zext (truncate x)) -> (and x, mask)
3610 if (N0.getOpcode() == ISD::TRUNCATE &&
3611 (!LegalOperations || TLI.isOperationLegal(ISD::AND, VT)) &&
3612 (!TLI.isTruncateFree(N0.getOperand(0).getValueType(),
3613 N0.getValueType()) ||
3614 !TLI.isZExtFree(N0.getValueType(), VT))) {
3615 SDValue Op = N0.getOperand(0);
3616 if (Op.getValueType().bitsLT(VT)) {
3617 Op = DAG.getNode(ISD::ANY_EXTEND, N->getDebugLoc(), VT, Op);
3618 } else if (Op.getValueType().bitsGT(VT)) {
3619 Op = DAG.getNode(ISD::TRUNCATE, N->getDebugLoc(), VT, Op);
3621 return DAG.getZeroExtendInReg(Op, N->getDebugLoc(),
3622 N0.getValueType().getScalarType());
3625 // Fold (zext (and (trunc x), cst)) -> (and x, cst),
3626 // if either of the casts is not free.
3627 if (N0.getOpcode() == ISD::AND &&
3628 N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
3629 N0.getOperand(1).getOpcode() == ISD::Constant &&
3630 (!TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(),
3631 N0.getValueType()) ||
3632 !TLI.isZExtFree(N0.getValueType(), VT))) {
3633 SDValue X = N0.getOperand(0).getOperand(0);
3634 if (X.getValueType().bitsLT(VT)) {
3635 X = DAG.getNode(ISD::ANY_EXTEND, X.getDebugLoc(), VT, X);
3636 } else if (X.getValueType().bitsGT(VT)) {
3637 X = DAG.getNode(ISD::TRUNCATE, X.getDebugLoc(), VT, X);
3639 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
3640 Mask.zext(VT.getSizeInBits());
3641 return DAG.getNode(ISD::AND, N->getDebugLoc(), VT,
3642 X, DAG.getConstant(Mask, VT));
3645 // fold (zext (load x)) -> (zext (truncate (zextload x)))
3646 if (ISD::isNON_EXTLoad(N0.getNode()) &&
3647 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
3648 TLI.isLoadExtLegal(ISD::ZEXTLOAD, N0.getValueType()))) {
3649 bool DoXform = true;
3650 SmallVector<SDNode*, 4> SetCCs;
3651 if (!N0.hasOneUse())
3652 DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ZERO_EXTEND, SetCCs, TLI);
3654 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
3655 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, N->getDebugLoc(), VT,
3657 LN0->getBasePtr(), LN0->getSrcValue(),
3658 LN0->getSrcValueOffset(),
3660 LN0->isVolatile(), LN0->isNonTemporal(),
3661 LN0->getAlignment());
3662 CombineTo(N, ExtLoad);
3663 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, N0.getDebugLoc(),
3664 N0.getValueType(), ExtLoad);
3665 CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
3667 // Extend SetCC uses if necessary.
3668 for (unsigned i = 0, e = SetCCs.size(); i != e; ++i) {
3669 SDNode *SetCC = SetCCs[i];
3670 SmallVector<SDValue, 4> Ops;
3672 for (unsigned j = 0; j != 2; ++j) {
3673 SDValue SOp = SetCC->getOperand(j);
3675 Ops.push_back(ExtLoad);
3677 Ops.push_back(DAG.getNode(ISD::ZERO_EXTEND,
3678 N->getDebugLoc(), VT, SOp));
3681 Ops.push_back(SetCC->getOperand(2));
3682 CombineTo(SetCC, DAG.getNode(ISD::SETCC, N->getDebugLoc(),
3683 SetCC->getValueType(0),
3684 &Ops[0], Ops.size()));
3687 return SDValue(N, 0); // Return N so it doesn't get rechecked!
3691 // fold (zext (zextload x)) -> (zext (truncate (zextload x)))
3692 // fold (zext ( extload x)) -> (zext (truncate (zextload x)))
3693 if ((ISD::isZEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) &&
3694 ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) {
3695 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
3696 EVT MemVT = LN0->getMemoryVT();
3697 if ((!LegalOperations && !LN0->isVolatile()) ||
3698 TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT)) {
3699 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, N->getDebugLoc(), VT,
3701 LN0->getBasePtr(), LN0->getSrcValue(),
3702 LN0->getSrcValueOffset(), MemVT,
3703 LN0->isVolatile(), LN0->isNonTemporal(),
3704 LN0->getAlignment());
3705 CombineTo(N, ExtLoad);
3706 CombineTo(N0.getNode(),
3707 DAG.getNode(ISD::TRUNCATE, N0.getDebugLoc(), N0.getValueType(),
3709 ExtLoad.getValue(1));
3710 return SDValue(N, 0); // Return N so it doesn't get rechecked!
3714 // zext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
3715 if (N0.getOpcode() == ISD::SETCC) {
3717 SimplifySelectCC(N->getDebugLoc(), N0.getOperand(0), N0.getOperand(1),
3718 DAG.getConstant(1, VT), DAG.getConstant(0, VT),
3719 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
3720 if (SCC.getNode()) return SCC;
3723 // (zext (shl (zext x), cst)) -> (shl (zext x), cst)
3724 if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL) &&
3725 isa<ConstantSDNode>(N0.getOperand(1)) &&
3726 N0.getOperand(0).getOpcode() == ISD::ZERO_EXTEND &&
3728 if (N0.getOpcode() == ISD::SHL) {
3729 // If the original shl may be shifting out bits, do not perform this
3731 unsigned ShAmt = cast<ConstantSDNode>(N0.getOperand(1))->getZExtValue();
3732 unsigned KnownZeroBits = N0.getOperand(0).getValueType().getSizeInBits() -
3733 N0.getOperand(0).getOperand(0).getValueType().getSizeInBits();
3734 if (ShAmt > KnownZeroBits)
3737 DebugLoc dl = N->getDebugLoc();
3738 return DAG.getNode(N0.getOpcode(), dl, VT,
3739 DAG.getNode(ISD::ZERO_EXTEND, dl, VT, N0.getOperand(0)),
3740 DAG.getNode(ISD::ZERO_EXTEND, dl,
3741 N0.getOperand(1).getValueType(),
3748 SDValue DAGCombiner::visitANY_EXTEND(SDNode *N) {
3749 SDValue N0 = N->getOperand(0);
3750 EVT VT = N->getValueType(0);
3752 // fold (aext c1) -> c1
3753 if (isa<ConstantSDNode>(N0))
3754 return DAG.getNode(ISD::ANY_EXTEND, N->getDebugLoc(), VT, N0);
3755 // fold (aext (aext x)) -> (aext x)
3756 // fold (aext (zext x)) -> (zext x)
3757 // fold (aext (sext x)) -> (sext x)
3758 if (N0.getOpcode() == ISD::ANY_EXTEND ||
3759 N0.getOpcode() == ISD::ZERO_EXTEND ||
3760 N0.getOpcode() == ISD::SIGN_EXTEND)
3761 return DAG.getNode(N0.getOpcode(), N->getDebugLoc(), VT, N0.getOperand(0));
3763 // fold (aext (truncate (load x))) -> (aext (smaller load x))
3764 // fold (aext (truncate (srl (load x), c))) -> (aext (small load (x+c/n)))
3765 if (N0.getOpcode() == ISD::TRUNCATE) {
3766 SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
3767 if (NarrowLoad.getNode()) {
3768 if (NarrowLoad.getNode() != N0.getNode())
3769 CombineTo(N0.getNode(), NarrowLoad);
3770 return DAG.getNode(ISD::ANY_EXTEND, N->getDebugLoc(), VT, NarrowLoad);
3774 // fold (aext (truncate x))
3775 if (N0.getOpcode() == ISD::TRUNCATE) {
3776 SDValue TruncOp = N0.getOperand(0);
3777 if (TruncOp.getValueType() == VT)
3778 return TruncOp; // x iff x size == zext size.
3779 if (TruncOp.getValueType().bitsGT(VT))
3780 return DAG.getNode(ISD::TRUNCATE, N->getDebugLoc(), VT, TruncOp);
3781 return DAG.getNode(ISD::ANY_EXTEND, N->getDebugLoc(), VT, TruncOp);
3784 // Fold (aext (and (trunc x), cst)) -> (and x, cst)
3785 // if the trunc is not free.
3786 if (N0.getOpcode() == ISD::AND &&
3787 N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
3788 N0.getOperand(1).getOpcode() == ISD::Constant &&
3789 !TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(),
3790 N0.getValueType())) {
3791 SDValue X = N0.getOperand(0).getOperand(0);
3792 if (X.getValueType().bitsLT(VT)) {
3793 X = DAG.getNode(ISD::ANY_EXTEND, N->getDebugLoc(), VT, X);
3794 } else if (X.getValueType().bitsGT(VT)) {
3795 X = DAG.getNode(ISD::TRUNCATE, N->getDebugLoc(), VT, X);
3797 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
3798 Mask.zext(VT.getSizeInBits());
3799 return DAG.getNode(ISD::AND, N->getDebugLoc(), VT,
3800 X, DAG.getConstant(Mask, VT));
3803 // fold (aext (load x)) -> (aext (truncate (extload x)))
3804 if (ISD::isNON_EXTLoad(N0.getNode()) &&
3805 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
3806 TLI.isLoadExtLegal(ISD::EXTLOAD, N0.getValueType()))) {
3807 bool DoXform = true;
3808 SmallVector<SDNode*, 4> SetCCs;
3809 if (!N0.hasOneUse())
3810 DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ANY_EXTEND, SetCCs, TLI);
3812 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
3813 SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, N->getDebugLoc(), VT,
3815 LN0->getBasePtr(), LN0->getSrcValue(),
3816 LN0->getSrcValueOffset(),
3818 LN0->isVolatile(), LN0->isNonTemporal(),
3819 LN0->getAlignment());
3820 CombineTo(N, ExtLoad);
3821 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, N0.getDebugLoc(),
3822 N0.getValueType(), ExtLoad);
3823 CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
3825 // Extend SetCC uses if necessary.
3826 for (unsigned i = 0, e = SetCCs.size(); i != e; ++i) {
3827 SDNode *SetCC = SetCCs[i];
3828 SmallVector<SDValue, 4> Ops;
3830 for (unsigned j = 0; j != 2; ++j) {
3831 SDValue SOp = SetCC->getOperand(j);
3833 Ops.push_back(ExtLoad);
3835 Ops.push_back(DAG.getNode(ISD::ANY_EXTEND,
3836 N->getDebugLoc(), VT, SOp));
3839 Ops.push_back(SetCC->getOperand(2));
3840 CombineTo(SetCC, DAG.getNode(ISD::SETCC, N->getDebugLoc(),
3841 SetCC->getValueType(0),
3842 &Ops[0], Ops.size()));
3845 return SDValue(N, 0); // Return N so it doesn't get rechecked!
3849 // fold (aext (zextload x)) -> (aext (truncate (zextload x)))
3850 // fold (aext (sextload x)) -> (aext (truncate (sextload x)))
3851 // fold (aext ( extload x)) -> (aext (truncate (extload x)))
3852 if (N0.getOpcode() == ISD::LOAD &&
3853 !ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
3855 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
3856 EVT MemVT = LN0->getMemoryVT();
3857 SDValue ExtLoad = DAG.getExtLoad(LN0->getExtensionType(), N->getDebugLoc(),
3858 VT, LN0->getChain(), LN0->getBasePtr(),
3860 LN0->getSrcValueOffset(), MemVT,
3861 LN0->isVolatile(), LN0->isNonTemporal(),
3862 LN0->getAlignment());
3863 CombineTo(N, ExtLoad);
3864 CombineTo(N0.getNode(),
3865 DAG.getNode(ISD::TRUNCATE, N0.getDebugLoc(),
3866 N0.getValueType(), ExtLoad),
3867 ExtLoad.getValue(1));
3868 return SDValue(N, 0); // Return N so it doesn't get rechecked!
3871 // aext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
3872 if (N0.getOpcode() == ISD::SETCC) {
3874 SimplifySelectCC(N->getDebugLoc(), N0.getOperand(0), N0.getOperand(1),
3875 DAG.getConstant(1, VT), DAG.getConstant(0, VT),
3876 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
3884 /// GetDemandedBits - See if the specified operand can be simplified with the
3885 /// knowledge that only the bits specified by Mask are used. If so, return the
3886 /// simpler operand, otherwise return a null SDValue.
3887 SDValue DAGCombiner::GetDemandedBits(SDValue V, const APInt &Mask) {
3888 switch (V.getOpcode()) {
3892 // If the LHS or RHS don't contribute bits to the or, drop them.
3893 if (DAG.MaskedValueIsZero(V.getOperand(0), Mask))
3894 return V.getOperand(1);
3895 if (DAG.MaskedValueIsZero(V.getOperand(1), Mask))
3896 return V.getOperand(0);
3899 // Only look at single-use SRLs.
3900 if (!V.getNode()->hasOneUse())
3902 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(V.getOperand(1))) {
3903 // See if we can recursively simplify the LHS.
3904 unsigned Amt = RHSC->getZExtValue();
3906 // Watch out for shift count overflow though.
3907 if (Amt >= Mask.getBitWidth()) break;
3908 APInt NewMask = Mask << Amt;
3909 SDValue SimplifyLHS = GetDemandedBits(V.getOperand(0), NewMask);
3910 if (SimplifyLHS.getNode())
3911 return DAG.getNode(ISD::SRL, V.getDebugLoc(), V.getValueType(),
3912 SimplifyLHS, V.getOperand(1));
3918 /// ReduceLoadWidth - If the result of a wider load is shifted to right of N
3919 /// bits and then truncated to a narrower type and where N is a multiple
3920 /// of number of bits of the narrower type, transform it to a narrower load
3921 /// from address + N / num of bits of new type. If the result is to be
3922 /// extended, also fold the extension to form a extending load.
3923 SDValue DAGCombiner::ReduceLoadWidth(SDNode *N) {
3924 unsigned Opc = N->getOpcode();
3925 ISD::LoadExtType ExtType = ISD::NON_EXTLOAD;
3926 SDValue N0 = N->getOperand(0);
3927 EVT VT = N->getValueType(0);
3930 // This transformation isn't valid for vector loads.
3934 // Special case: SIGN_EXTEND_INREG is basically truncating to ExtVT then
3936 if (Opc == ISD::SIGN_EXTEND_INREG) {
3937 ExtType = ISD::SEXTLOAD;
3938 ExtVT = cast<VTSDNode>(N->getOperand(1))->getVT();
3939 if (LegalOperations && !TLI.isLoadExtLegal(ISD::SEXTLOAD, ExtVT))
3943 unsigned EVTBits = ExtVT.getSizeInBits();
3945 if (N0.getOpcode() == ISD::SRL && N0.hasOneUse() && ExtVT.isRound()) {
3946 if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
3947 ShAmt = N01->getZExtValue();
3948 // Is the shift amount a multiple of size of VT?
3949 if ((ShAmt & (EVTBits-1)) == 0) {
3950 N0 = N0.getOperand(0);
3951 // Is the load width a multiple of size of VT?
3952 if ((N0.getValueType().getSizeInBits() & (EVTBits-1)) != 0)
3958 // Do not generate loads of non-round integer types since these can
3959 // be expensive (and would be wrong if the type is not byte sized).
3960 if (isa<LoadSDNode>(N0) && N0.hasOneUse() && ExtVT.isRound() &&
3961 cast<LoadSDNode>(N0)->getMemoryVT().getSizeInBits() >= EVTBits &&
3962 // Do not change the width of a volatile load.
3963 !cast<LoadSDNode>(N0)->isVolatile()) {
3964 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
3965 EVT PtrType = N0.getOperand(1).getValueType();
3967 // For big endian targets, we need to adjust the offset to the pointer to
3968 // load the correct bytes.
3969 if (TLI.isBigEndian()) {
3970 unsigned LVTStoreBits = LN0->getMemoryVT().getStoreSizeInBits();
3971 unsigned EVTStoreBits = ExtVT.getStoreSizeInBits();
3972 ShAmt = LVTStoreBits - EVTStoreBits - ShAmt;
3975 uint64_t PtrOff = ShAmt / 8;
3976 unsigned NewAlign = MinAlign(LN0->getAlignment(), PtrOff);
3977 SDValue NewPtr = DAG.getNode(ISD::ADD, LN0->getDebugLoc(),
3978 PtrType, LN0->getBasePtr(),
3979 DAG.getConstant(PtrOff, PtrType));
3980 AddToWorkList(NewPtr.getNode());
3982 SDValue Load = (ExtType == ISD::NON_EXTLOAD)
3983 ? DAG.getLoad(VT, N0.getDebugLoc(), LN0->getChain(), NewPtr,
3984 LN0->getSrcValue(), LN0->getSrcValueOffset() + PtrOff,
3985 LN0->isVolatile(), LN0->isNonTemporal(), NewAlign)
3986 : DAG.getExtLoad(ExtType, N0.getDebugLoc(), VT, LN0->getChain(), NewPtr,
3987 LN0->getSrcValue(), LN0->getSrcValueOffset() + PtrOff,
3988 ExtVT, LN0->isVolatile(), LN0->isNonTemporal(),
3991 // Replace the old load's chain with the new load's chain.
3992 WorkListRemover DeadNodes(*this);
3993 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1),
3996 // Return the new loaded value.
4003 SDValue DAGCombiner::visitSIGN_EXTEND_INREG(SDNode *N) {
4004 SDValue N0 = N->getOperand(0);
4005 SDValue N1 = N->getOperand(1);
4006 EVT VT = N->getValueType(0);
4007 EVT EVT = cast<VTSDNode>(N1)->getVT();
4008 unsigned VTBits = VT.getScalarType().getSizeInBits();
4009 unsigned EVTBits = EVT.getScalarType().getSizeInBits();
4011 // fold (sext_in_reg c1) -> c1
4012 if (isa<ConstantSDNode>(N0) || N0.getOpcode() == ISD::UNDEF)
4013 return DAG.getNode(ISD::SIGN_EXTEND_INREG, N->getDebugLoc(), VT, N0, N1);
4015 // If the input is already sign extended, just drop the extension.
4016 if (DAG.ComputeNumSignBits(N0) >= VTBits-EVTBits+1)
4019 // fold (sext_in_reg (sext_in_reg x, VT2), VT1) -> (sext_in_reg x, minVT) pt2
4020 if (N0.getOpcode() == ISD::SIGN_EXTEND_INREG &&
4021 EVT.bitsLT(cast<VTSDNode>(N0.getOperand(1))->getVT())) {
4022 return DAG.getNode(ISD::SIGN_EXTEND_INREG, N->getDebugLoc(), VT,
4023 N0.getOperand(0), N1);
4026 // fold (sext_in_reg (sext x)) -> (sext x)
4027 // fold (sext_in_reg (aext x)) -> (sext x)
4028 // if x is small enough.
4029 if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND) {
4030 SDValue N00 = N0.getOperand(0);
4031 if (N00.getValueType().getScalarType().getSizeInBits() <= EVTBits &&
4032 (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND, VT)))
4033 return DAG.getNode(ISD::SIGN_EXTEND, N->getDebugLoc(), VT, N00, N1);
4036 // fold (sext_in_reg x) -> (zext_in_reg x) if the sign bit is known zero.
4037 if (DAG.MaskedValueIsZero(N0, APInt::getBitsSet(VTBits, EVTBits-1, EVTBits)))
4038 return DAG.getZeroExtendInReg(N0, N->getDebugLoc(), EVT);
4040 // fold operands of sext_in_reg based on knowledge that the top bits are not
4042 if (SimplifyDemandedBits(SDValue(N, 0)))
4043 return SDValue(N, 0);
4045 // fold (sext_in_reg (load x)) -> (smaller sextload x)
4046 // fold (sext_in_reg (srl (load x), c)) -> (smaller sextload (x+c/evtbits))
4047 SDValue NarrowLoad = ReduceLoadWidth(N);
4048 if (NarrowLoad.getNode())
4051 // fold (sext_in_reg (srl X, 24), i8) -> (sra X, 24)
4052 // fold (sext_in_reg (srl X, 23), i8) -> (sra X, 23) iff possible.
4053 // We already fold "(sext_in_reg (srl X, 25), i8) -> srl X, 25" above.
4054 if (N0.getOpcode() == ISD::SRL) {
4055 if (ConstantSDNode *ShAmt = dyn_cast<ConstantSDNode>(N0.getOperand(1)))
4056 if (ShAmt->getZExtValue()+EVTBits <= VTBits) {
4057 // We can turn this into an SRA iff the input to the SRL is already sign
4059 unsigned InSignBits = DAG.ComputeNumSignBits(N0.getOperand(0));
4060 if (VTBits-(ShAmt->getZExtValue()+EVTBits) < InSignBits)
4061 return DAG.getNode(ISD::SRA, N->getDebugLoc(), VT,
4062 N0.getOperand(0), N0.getOperand(1));
4066 // fold (sext_inreg (extload x)) -> (sextload x)
4067 if (ISD::isEXTLoad(N0.getNode()) &&
4068 ISD::isUNINDEXEDLoad(N0.getNode()) &&
4069 EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
4070 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
4071 TLI.isLoadExtLegal(ISD::SEXTLOAD, EVT))) {
4072 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
4073 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, N->getDebugLoc(), VT,
4075 LN0->getBasePtr(), LN0->getSrcValue(),
4076 LN0->getSrcValueOffset(), EVT,
4077 LN0->isVolatile(), LN0->isNonTemporal(),
4078 LN0->getAlignment());
4079 CombineTo(N, ExtLoad);
4080 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
4081 return SDValue(N, 0); // Return N so it doesn't get rechecked!
4083 // fold (sext_inreg (zextload x)) -> (sextload x) iff load has one use
4084 if (ISD::isZEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
4086 EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
4087 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
4088 TLI.isLoadExtLegal(ISD::SEXTLOAD, EVT))) {
4089 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
4090 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, N->getDebugLoc(), VT,
4092 LN0->getBasePtr(), LN0->getSrcValue(),
4093 LN0->getSrcValueOffset(), EVT,
4094 LN0->isVolatile(), LN0->isNonTemporal(),
4095 LN0->getAlignment());
4096 CombineTo(N, ExtLoad);
4097 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
4098 return SDValue(N, 0); // Return N so it doesn't get rechecked!
4103 SDValue DAGCombiner::visitTRUNCATE(SDNode *N) {
4104 SDValue N0 = N->getOperand(0);
4105 EVT VT = N->getValueType(0);
4108 if (N0.getValueType() == N->getValueType(0))
4110 // fold (truncate c1) -> c1
4111 if (isa<ConstantSDNode>(N0))
4112 return DAG.getNode(ISD::TRUNCATE, N->getDebugLoc(), VT, N0);
4113 // fold (truncate (truncate x)) -> (truncate x)
4114 if (N0.getOpcode() == ISD::TRUNCATE)
4115 return DAG.getNode(ISD::TRUNCATE, N->getDebugLoc(), VT, N0.getOperand(0));
4116 // fold (truncate (ext x)) -> (ext x) or (truncate x) or x
4117 if (N0.getOpcode() == ISD::ZERO_EXTEND ||
4118 N0.getOpcode() == ISD::SIGN_EXTEND ||
4119 N0.getOpcode() == ISD::ANY_EXTEND) {
4120 if (N0.getOperand(0).getValueType().bitsLT(VT))
4121 // if the source is smaller than the dest, we still need an extend
4122 return DAG.getNode(N0.getOpcode(), N->getDebugLoc(), VT,
4124 else if (N0.getOperand(0).getValueType().bitsGT(VT))
4125 // if the source is larger than the dest, than we just need the truncate
4126 return DAG.getNode(ISD::TRUNCATE, N->getDebugLoc(), VT, N0.getOperand(0));
4128 // if the source and dest are the same type, we can drop both the extend
4129 // and the truncate.
4130 return N0.getOperand(0);
4133 // See if we can simplify the input to this truncate through knowledge that
4134 // only the low bits are being used. For example "trunc (or (shl x, 8), y)"
4137 GetDemandedBits(N0, APInt::getLowBitsSet(N0.getValueSizeInBits(),
4138 VT.getSizeInBits()));
4139 if (Shorter.getNode())
4140 return DAG.getNode(ISD::TRUNCATE, N->getDebugLoc(), VT, Shorter);
4142 // fold (truncate (load x)) -> (smaller load x)
4143 // fold (truncate (srl (load x), c)) -> (smaller load (x+c/evtbits))
4144 if (!LegalTypes || TLI.isTypeDesirableForOp(N0.getOpcode(), VT))
4145 return ReduceLoadWidth(N);
4149 static SDNode *getBuildPairElt(SDNode *N, unsigned i) {
4150 SDValue Elt = N->getOperand(i);
4151 if (Elt.getOpcode() != ISD::MERGE_VALUES)
4152 return Elt.getNode();
4153 return Elt.getOperand(Elt.getResNo()).getNode();
4156 /// CombineConsecutiveLoads - build_pair (load, load) -> load
4157 /// if load locations are consecutive.
4158 SDValue DAGCombiner::CombineConsecutiveLoads(SDNode *N, EVT VT) {
4159 assert(N->getOpcode() == ISD::BUILD_PAIR);
4161 LoadSDNode *LD1 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 0));
4162 LoadSDNode *LD2 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 1));
4163 if (!LD1 || !LD2 || !ISD::isNON_EXTLoad(LD1) || !LD1->hasOneUse())
4165 EVT LD1VT = LD1->getValueType(0);
4167 if (ISD::isNON_EXTLoad(LD2) &&
4169 // If both are volatile this would reduce the number of volatile loads.
4170 // If one is volatile it might be ok, but play conservative and bail out.
4171 !LD1->isVolatile() &&
4172 !LD2->isVolatile() &&
4173 DAG.isConsecutiveLoad(LD2, LD1, LD1VT.getSizeInBits()/8, 1)) {
4174 unsigned Align = LD1->getAlignment();
4175 unsigned NewAlign = TLI.getTargetData()->
4176 getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
4178 if (NewAlign <= Align &&
4179 (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT)))
4180 return DAG.getLoad(VT, N->getDebugLoc(), LD1->getChain(),
4181 LD1->getBasePtr(), LD1->getSrcValue(),
4182 LD1->getSrcValueOffset(), false, false, Align);
4188 SDValue DAGCombiner::visitBIT_CONVERT(SDNode *N) {
4189 SDValue N0 = N->getOperand(0);
4190 EVT VT = N->getValueType(0);
4192 // If the input is a BUILD_VECTOR with all constant elements, fold this now.
4193 // Only do this before legalize, since afterward the target may be depending
4194 // on the bitconvert.
4195 // First check to see if this is all constant.
4197 N0.getOpcode() == ISD::BUILD_VECTOR && N0.getNode()->hasOneUse() &&
4199 bool isSimple = true;
4200 for (unsigned i = 0, e = N0.getNumOperands(); i != e; ++i)
4201 if (N0.getOperand(i).getOpcode() != ISD::UNDEF &&
4202 N0.getOperand(i).getOpcode() != ISD::Constant &&
4203 N0.getOperand(i).getOpcode() != ISD::ConstantFP) {
4208 EVT DestEltVT = N->getValueType(0).getVectorElementType();
4209 assert(!DestEltVT.isVector() &&
4210 "Element type of vector ValueType must not be vector!");
4212 return ConstantFoldBIT_CONVERTofBUILD_VECTOR(N0.getNode(), DestEltVT);
4215 // If the input is a constant, let getNode fold it.
4216 if (isa<ConstantSDNode>(N0) || isa<ConstantFPSDNode>(N0)) {
4217 SDValue Res = DAG.getNode(ISD::BIT_CONVERT, N->getDebugLoc(), VT, N0);
4218 if (Res.getNode() != N) {
4219 if (!LegalOperations ||
4220 TLI.isOperationLegal(Res.getNode()->getOpcode(), VT))
4223 // Folding it resulted in an illegal node, and it's too late to
4224 // do that. Clean up the old node and forego the transformation.
4225 // Ideally this won't happen very often, because instcombine
4226 // and the earlier dagcombine runs (where illegal nodes are
4227 // permitted) should have folded most of them already.
4228 DAG.DeleteNode(Res.getNode());
4232 // (conv (conv x, t1), t2) -> (conv x, t2)
4233 if (N0.getOpcode() == ISD::BIT_CONVERT)
4234 return DAG.getNode(ISD::BIT_CONVERT, N->getDebugLoc(), VT,
4237 // fold (conv (load x)) -> (load (conv*)x)
4238 // If the resultant load doesn't need a higher alignment than the original!
4239 if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
4240 // Do not change the width of a volatile load.
4241 !cast<LoadSDNode>(N0)->isVolatile() &&
4242 (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT))) {
4243 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
4244 unsigned Align = TLI.getTargetData()->
4245 getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
4246 unsigned OrigAlign = LN0->getAlignment();
4248 if (Align <= OrigAlign) {
4249 SDValue Load = DAG.getLoad(VT, N->getDebugLoc(), LN0->getChain(),
4251 LN0->getSrcValue(), LN0->getSrcValueOffset(),
4252 LN0->isVolatile(), LN0->isNonTemporal(),
4255 CombineTo(N0.getNode(),
4256 DAG.getNode(ISD::BIT_CONVERT, N0.getDebugLoc(),
4257 N0.getValueType(), Load),
4263 // fold (bitconvert (fneg x)) -> (xor (bitconvert x), signbit)
4264 // fold (bitconvert (fabs x)) -> (and (bitconvert x), (not signbit))
4265 // This often reduces constant pool loads.
4266 if ((N0.getOpcode() == ISD::FNEG || N0.getOpcode() == ISD::FABS) &&
4267 N0.getNode()->hasOneUse() && VT.isInteger() && !VT.isVector()) {
4268 SDValue NewConv = DAG.getNode(ISD::BIT_CONVERT, N0.getDebugLoc(), VT,
4270 AddToWorkList(NewConv.getNode());
4272 APInt SignBit = APInt::getSignBit(VT.getSizeInBits());
4273 if (N0.getOpcode() == ISD::FNEG)
4274 return DAG.getNode(ISD::XOR, N->getDebugLoc(), VT,
4275 NewConv, DAG.getConstant(SignBit, VT));
4276 assert(N0.getOpcode() == ISD::FABS);
4277 return DAG.getNode(ISD::AND, N->getDebugLoc(), VT,
4278 NewConv, DAG.getConstant(~SignBit, VT));
4281 // fold (bitconvert (fcopysign cst, x)) ->
4282 // (or (and (bitconvert x), sign), (and cst, (not sign)))
4283 // Note that we don't handle (copysign x, cst) because this can always be
4284 // folded to an fneg or fabs.
4285 if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse() &&
4286 isa<ConstantFPSDNode>(N0.getOperand(0)) &&
4287 VT.isInteger() && !VT.isVector()) {
4288 unsigned OrigXWidth = N0.getOperand(1).getValueType().getSizeInBits();
4289 EVT IntXVT = EVT::getIntegerVT(*DAG.getContext(), OrigXWidth);
4290 if (isTypeLegal(IntXVT)) {
4291 SDValue X = DAG.getNode(ISD::BIT_CONVERT, N0.getDebugLoc(),
4292 IntXVT, N0.getOperand(1));
4293 AddToWorkList(X.getNode());
4295 // If X has a different width than the result/lhs, sext it or truncate it.
4296 unsigned VTWidth = VT.getSizeInBits();
4297 if (OrigXWidth < VTWidth) {
4298 X = DAG.getNode(ISD::SIGN_EXTEND, N->getDebugLoc(), VT, X);
4299 AddToWorkList(X.getNode());
4300 } else if (OrigXWidth > VTWidth) {
4301 // To get the sign bit in the right place, we have to shift it right
4302 // before truncating.
4303 X = DAG.getNode(ISD::SRL, X.getDebugLoc(),
4304 X.getValueType(), X,
4305 DAG.getConstant(OrigXWidth-VTWidth, X.getValueType()));
4306 AddToWorkList(X.getNode());
4307 X = DAG.getNode(ISD::TRUNCATE, X.getDebugLoc(), VT, X);
4308 AddToWorkList(X.getNode());
4311 APInt SignBit = APInt::getSignBit(VT.getSizeInBits());
4312 X = DAG.getNode(ISD::AND, X.getDebugLoc(), VT,
4313 X, DAG.getConstant(SignBit, VT));
4314 AddToWorkList(X.getNode());
4316 SDValue Cst = DAG.getNode(ISD::BIT_CONVERT, N0.getDebugLoc(),
4317 VT, N0.getOperand(0));
4318 Cst = DAG.getNode(ISD::AND, Cst.getDebugLoc(), VT,
4319 Cst, DAG.getConstant(~SignBit, VT));
4320 AddToWorkList(Cst.getNode());
4322 return DAG.getNode(ISD::OR, N->getDebugLoc(), VT, X, Cst);
4326 // bitconvert(build_pair(ld, ld)) -> ld iff load locations are consecutive.
4327 if (N0.getOpcode() == ISD::BUILD_PAIR) {
4328 SDValue CombineLD = CombineConsecutiveLoads(N0.getNode(), VT);
4329 if (CombineLD.getNode())
4336 SDValue DAGCombiner::visitBUILD_PAIR(SDNode *N) {
4337 EVT VT = N->getValueType(0);
4338 return CombineConsecutiveLoads(N, VT);
4341 /// ConstantFoldBIT_CONVERTofBUILD_VECTOR - We know that BV is a build_vector
4342 /// node with Constant, ConstantFP or Undef operands. DstEltVT indicates the
4343 /// destination element value type.
4344 SDValue DAGCombiner::
4345 ConstantFoldBIT_CONVERTofBUILD_VECTOR(SDNode *BV, EVT DstEltVT) {
4346 EVT SrcEltVT = BV->getValueType(0).getVectorElementType();
4348 // If this is already the right type, we're done.
4349 if (SrcEltVT == DstEltVT) return SDValue(BV, 0);
4351 unsigned SrcBitSize = SrcEltVT.getSizeInBits();
4352 unsigned DstBitSize = DstEltVT.getSizeInBits();
4354 // If this is a conversion of N elements of one type to N elements of another
4355 // type, convert each element. This handles FP<->INT cases.
4356 if (SrcBitSize == DstBitSize) {
4357 SmallVector<SDValue, 8> Ops;
4358 for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) {
4359 SDValue Op = BV->getOperand(i);
4360 // If the vector element type is not legal, the BUILD_VECTOR operands
4361 // are promoted and implicitly truncated. Make that explicit here.
4362 if (Op.getValueType() != SrcEltVT)
4363 Op = DAG.getNode(ISD::TRUNCATE, BV->getDebugLoc(), SrcEltVT, Op);
4364 Ops.push_back(DAG.getNode(ISD::BIT_CONVERT, BV->getDebugLoc(),
4366 AddToWorkList(Ops.back().getNode());
4368 EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT,
4369 BV->getValueType(0).getVectorNumElements());
4370 return DAG.getNode(ISD::BUILD_VECTOR, BV->getDebugLoc(), VT,
4371 &Ops[0], Ops.size());
4374 // Otherwise, we're growing or shrinking the elements. To avoid having to
4375 // handle annoying details of growing/shrinking FP values, we convert them to
4377 if (SrcEltVT.isFloatingPoint()) {
4378 // Convert the input float vector to a int vector where the elements are the
4380 assert((SrcEltVT == MVT::f32 || SrcEltVT == MVT::f64) && "Unknown FP VT!");
4381 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), SrcEltVT.getSizeInBits());
4382 BV = ConstantFoldBIT_CONVERTofBUILD_VECTOR(BV, IntVT).getNode();
4386 // Now we know the input is an integer vector. If the output is a FP type,
4387 // convert to integer first, then to FP of the right size.
4388 if (DstEltVT.isFloatingPoint()) {
4389 assert((DstEltVT == MVT::f32 || DstEltVT == MVT::f64) && "Unknown FP VT!");
4390 EVT TmpVT = EVT::getIntegerVT(*DAG.getContext(), DstEltVT.getSizeInBits());
4391 SDNode *Tmp = ConstantFoldBIT_CONVERTofBUILD_VECTOR(BV, TmpVT).getNode();
4393 // Next, convert to FP elements of the same size.
4394 return ConstantFoldBIT_CONVERTofBUILD_VECTOR(Tmp, DstEltVT);
4397 // Okay, we know the src/dst types are both integers of differing types.
4398 // Handling growing first.
4399 assert(SrcEltVT.isInteger() && DstEltVT.isInteger());
4400 if (SrcBitSize < DstBitSize) {
4401 unsigned NumInputsPerOutput = DstBitSize/SrcBitSize;
4403 SmallVector<SDValue, 8> Ops;
4404 for (unsigned i = 0, e = BV->getNumOperands(); i != e;
4405 i += NumInputsPerOutput) {
4406 bool isLE = TLI.isLittleEndian();
4407 APInt NewBits = APInt(DstBitSize, 0);
4408 bool EltIsUndef = true;
4409 for (unsigned j = 0; j != NumInputsPerOutput; ++j) {
4410 // Shift the previously computed bits over.
4411 NewBits <<= SrcBitSize;
4412 SDValue Op = BV->getOperand(i+ (isLE ? (NumInputsPerOutput-j-1) : j));
4413 if (Op.getOpcode() == ISD::UNDEF) continue;
4416 NewBits |= APInt(cast<ConstantSDNode>(Op)->getAPIntValue()).
4417 zextOrTrunc(SrcBitSize).zext(DstBitSize);
4421 Ops.push_back(DAG.getUNDEF(DstEltVT));
4423 Ops.push_back(DAG.getConstant(NewBits, DstEltVT));
4426 EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT, Ops.size());
4427 return DAG.getNode(ISD::BUILD_VECTOR, BV->getDebugLoc(), VT,
4428 &Ops[0], Ops.size());
4431 // Finally, this must be the case where we are shrinking elements: each input
4432 // turns into multiple outputs.
4433 bool isS2V = ISD::isScalarToVector(BV);
4434 unsigned NumOutputsPerInput = SrcBitSize/DstBitSize;
4435 EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT,
4436 NumOutputsPerInput*BV->getNumOperands());
4437 SmallVector<SDValue, 8> Ops;
4439 for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) {
4440 if (BV->getOperand(i).getOpcode() == ISD::UNDEF) {
4441 for (unsigned j = 0; j != NumOutputsPerInput; ++j)
4442 Ops.push_back(DAG.getUNDEF(DstEltVT));
4446 APInt OpVal = APInt(cast<ConstantSDNode>(BV->getOperand(i))->
4447 getAPIntValue()).zextOrTrunc(SrcBitSize);
4449 for (unsigned j = 0; j != NumOutputsPerInput; ++j) {
4450 APInt ThisVal = APInt(OpVal).trunc(DstBitSize);
4451 Ops.push_back(DAG.getConstant(ThisVal, DstEltVT));
4452 if (isS2V && i == 0 && j == 0 && APInt(ThisVal).zext(SrcBitSize) == OpVal)
4453 // Simply turn this into a SCALAR_TO_VECTOR of the new type.
4454 return DAG.getNode(ISD::SCALAR_TO_VECTOR, BV->getDebugLoc(), VT,
4456 OpVal = OpVal.lshr(DstBitSize);
4459 // For big endian targets, swap the order of the pieces of each element.
4460 if (TLI.isBigEndian())
4461 std::reverse(Ops.end()-NumOutputsPerInput, Ops.end());
4464 return DAG.getNode(ISD::BUILD_VECTOR, BV->getDebugLoc(), VT,
4465 &Ops[0], Ops.size());
4468 SDValue DAGCombiner::visitFADD(SDNode *N) {
4469 SDValue N0 = N->getOperand(0);
4470 SDValue N1 = N->getOperand(1);
4471 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
4472 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
4473 EVT VT = N->getValueType(0);
4476 if (VT.isVector()) {
4477 SDValue FoldedVOp = SimplifyVBinOp(N);
4478 if (FoldedVOp.getNode()) return FoldedVOp;
4481 // fold (fadd c1, c2) -> (fadd c1, c2)
4482 if (N0CFP && N1CFP && VT != MVT::ppcf128)
4483 return DAG.getNode(ISD::FADD, N->getDebugLoc(), VT, N0, N1);
4484 // canonicalize constant to RHS
4485 if (N0CFP && !N1CFP)
4486 return DAG.getNode(ISD::FADD, N->getDebugLoc(), VT, N1, N0);
4487 // fold (fadd A, 0) -> A
4488 if (UnsafeFPMath && N1CFP && N1CFP->getValueAPF().isZero())
4490 // fold (fadd A, (fneg B)) -> (fsub A, B)
4491 if (isNegatibleForFree(N1, LegalOperations) == 2)
4492 return DAG.getNode(ISD::FSUB, N->getDebugLoc(), VT, N0,
4493 GetNegatedExpression(N1, DAG, LegalOperations));
4494 // fold (fadd (fneg A), B) -> (fsub B, A)
4495 if (isNegatibleForFree(N0, LegalOperations) == 2)
4496 return DAG.getNode(ISD::FSUB, N->getDebugLoc(), VT, N1,
4497 GetNegatedExpression(N0, DAG, LegalOperations));
4499 // If allowed, fold (fadd (fadd x, c1), c2) -> (fadd x, (fadd c1, c2))
4500 if (UnsafeFPMath && N1CFP && N0.getOpcode() == ISD::FADD &&
4501 N0.getNode()->hasOneUse() && isa<ConstantFPSDNode>(N0.getOperand(1)))
4502 return DAG.getNode(ISD::FADD, N->getDebugLoc(), VT, N0.getOperand(0),
4503 DAG.getNode(ISD::FADD, N->getDebugLoc(), VT,
4504 N0.getOperand(1), N1));
4509 SDValue DAGCombiner::visitFSUB(SDNode *N) {
4510 SDValue N0 = N->getOperand(0);
4511 SDValue N1 = N->getOperand(1);
4512 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
4513 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
4514 EVT VT = N->getValueType(0);
4517 if (VT.isVector()) {
4518 SDValue FoldedVOp = SimplifyVBinOp(N);
4519 if (FoldedVOp.getNode()) return FoldedVOp;
4522 // fold (fsub c1, c2) -> c1-c2
4523 if (N0CFP && N1CFP && VT != MVT::ppcf128)
4524 return DAG.getNode(ISD::FSUB, N->getDebugLoc(), VT, N0, N1);
4525 // fold (fsub A, 0) -> A
4526 if (UnsafeFPMath && N1CFP && N1CFP->getValueAPF().isZero())
4528 // fold (fsub 0, B) -> -B
4529 if (UnsafeFPMath && N0CFP && N0CFP->getValueAPF().isZero()) {
4530 if (isNegatibleForFree(N1, LegalOperations))
4531 return GetNegatedExpression(N1, DAG, LegalOperations);
4532 if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
4533 return DAG.getNode(ISD::FNEG, N->getDebugLoc(), VT, N1);
4535 // fold (fsub A, (fneg B)) -> (fadd A, B)
4536 if (isNegatibleForFree(N1, LegalOperations))
4537 return DAG.getNode(ISD::FADD, N->getDebugLoc(), VT, N0,
4538 GetNegatedExpression(N1, DAG, LegalOperations));
4543 SDValue DAGCombiner::visitFMUL(SDNode *N) {
4544 SDValue N0 = N->getOperand(0);
4545 SDValue N1 = N->getOperand(1);
4546 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
4547 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
4548 EVT VT = N->getValueType(0);
4551 if (VT.isVector()) {
4552 SDValue FoldedVOp = SimplifyVBinOp(N);
4553 if (FoldedVOp.getNode()) return FoldedVOp;
4556 // fold (fmul c1, c2) -> c1*c2
4557 if (N0CFP && N1CFP && VT != MVT::ppcf128)
4558 return DAG.getNode(ISD::FMUL, N->getDebugLoc(), VT, N0, N1);
4559 // canonicalize constant to RHS
4560 if (N0CFP && !N1CFP)
4561 return DAG.getNode(ISD::FMUL, N->getDebugLoc(), VT, N1, N0);
4562 // fold (fmul A, 0) -> 0
4563 if (UnsafeFPMath && N1CFP && N1CFP->getValueAPF().isZero())
4565 // fold (fmul A, 0) -> 0, vector edition.
4566 if (UnsafeFPMath && ISD::isBuildVectorAllZeros(N1.getNode()))
4568 // fold (fmul X, 2.0) -> (fadd X, X)
4569 if (N1CFP && N1CFP->isExactlyValue(+2.0))
4570 return DAG.getNode(ISD::FADD, N->getDebugLoc(), VT, N0, N0);
4571 // fold (fmul X, -1.0) -> (fneg X)
4572 if (N1CFP && N1CFP->isExactlyValue(-1.0))
4573 if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
4574 return DAG.getNode(ISD::FNEG, N->getDebugLoc(), VT, N0);
4576 // fold (fmul (fneg X), (fneg Y)) -> (fmul X, Y)
4577 if (char LHSNeg = isNegatibleForFree(N0, LegalOperations)) {
4578 if (char RHSNeg = isNegatibleForFree(N1, LegalOperations)) {
4579 // Both can be negated for free, check to see if at least one is cheaper
4581 if (LHSNeg == 2 || RHSNeg == 2)
4582 return DAG.getNode(ISD::FMUL, N->getDebugLoc(), VT,
4583 GetNegatedExpression(N0, DAG, LegalOperations),
4584 GetNegatedExpression(N1, DAG, LegalOperations));
4588 // If allowed, fold (fmul (fmul x, c1), c2) -> (fmul x, (fmul c1, c2))
4589 if (UnsafeFPMath && N1CFP && N0.getOpcode() == ISD::FMUL &&
4590 N0.getNode()->hasOneUse() && isa<ConstantFPSDNode>(N0.getOperand(1)))
4591 return DAG.getNode(ISD::FMUL, N->getDebugLoc(), VT, N0.getOperand(0),
4592 DAG.getNode(ISD::FMUL, N->getDebugLoc(), VT,
4593 N0.getOperand(1), N1));
4598 SDValue DAGCombiner::visitFDIV(SDNode *N) {
4599 SDValue N0 = N->getOperand(0);
4600 SDValue N1 = N->getOperand(1);
4601 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
4602 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
4603 EVT VT = N->getValueType(0);
4606 if (VT.isVector()) {
4607 SDValue FoldedVOp = SimplifyVBinOp(N);
4608 if (FoldedVOp.getNode()) return FoldedVOp;
4611 // fold (fdiv c1, c2) -> c1/c2
4612 if (N0CFP && N1CFP && VT != MVT::ppcf128)
4613 return DAG.getNode(ISD::FDIV, N->getDebugLoc(), VT, N0, N1);
4616 // (fdiv (fneg X), (fneg Y)) -> (fdiv X, Y)
4617 if (char LHSNeg = isNegatibleForFree(N0, LegalOperations)) {
4618 if (char RHSNeg = isNegatibleForFree(N1, LegalOperations)) {
4619 // Both can be negated for free, check to see if at least one is cheaper
4621 if (LHSNeg == 2 || RHSNeg == 2)
4622 return DAG.getNode(ISD::FDIV, N->getDebugLoc(), VT,
4623 GetNegatedExpression(N0, DAG, LegalOperations),
4624 GetNegatedExpression(N1, DAG, LegalOperations));
4631 SDValue DAGCombiner::visitFREM(SDNode *N) {
4632 SDValue N0 = N->getOperand(0);
4633 SDValue N1 = N->getOperand(1);
4634 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
4635 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
4636 EVT VT = N->getValueType(0);
4638 // fold (frem c1, c2) -> fmod(c1,c2)
4639 if (N0CFP && N1CFP && VT != MVT::ppcf128)
4640 return DAG.getNode(ISD::FREM, N->getDebugLoc(), VT, N0, N1);
4645 SDValue DAGCombiner::visitFCOPYSIGN(SDNode *N) {
4646 SDValue N0 = N->getOperand(0);
4647 SDValue N1 = N->getOperand(1);
4648 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
4649 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
4650 EVT VT = N->getValueType(0);
4652 if (N0CFP && N1CFP && VT != MVT::ppcf128) // Constant fold
4653 return DAG.getNode(ISD::FCOPYSIGN, N->getDebugLoc(), VT, N0, N1);
4656 const APFloat& V = N1CFP->getValueAPF();
4657 // copysign(x, c1) -> fabs(x) iff ispos(c1)
4658 // copysign(x, c1) -> fneg(fabs(x)) iff isneg(c1)
4659 if (!V.isNegative()) {
4660 if (!LegalOperations || TLI.isOperationLegal(ISD::FABS, VT))
4661 return DAG.getNode(ISD::FABS, N->getDebugLoc(), VT, N0);
4663 if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
4664 return DAG.getNode(ISD::FNEG, N->getDebugLoc(), VT,
4665 DAG.getNode(ISD::FABS, N0.getDebugLoc(), VT, N0));
4669 // copysign(fabs(x), y) -> copysign(x, y)
4670 // copysign(fneg(x), y) -> copysign(x, y)
4671 // copysign(copysign(x,z), y) -> copysign(x, y)
4672 if (N0.getOpcode() == ISD::FABS || N0.getOpcode() == ISD::FNEG ||
4673 N0.getOpcode() == ISD::FCOPYSIGN)
4674 return DAG.getNode(ISD::FCOPYSIGN, N->getDebugLoc(), VT,
4675 N0.getOperand(0), N1);
4677 // copysign(x, abs(y)) -> abs(x)
4678 if (N1.getOpcode() == ISD::FABS)
4679 return DAG.getNode(ISD::FABS, N->getDebugLoc(), VT, N0);
4681 // copysign(x, copysign(y,z)) -> copysign(x, z)
4682 if (N1.getOpcode() == ISD::FCOPYSIGN)
4683 return DAG.getNode(ISD::FCOPYSIGN, N->getDebugLoc(), VT,
4684 N0, N1.getOperand(1));
4686 // copysign(x, fp_extend(y)) -> copysign(x, y)
4687 // copysign(x, fp_round(y)) -> copysign(x, y)
4688 if (N1.getOpcode() == ISD::FP_EXTEND || N1.getOpcode() == ISD::FP_ROUND)
4689 return DAG.getNode(ISD::FCOPYSIGN, N->getDebugLoc(), VT,
4690 N0, N1.getOperand(0));
4695 SDValue DAGCombiner::visitSINT_TO_FP(SDNode *N) {
4696 SDValue N0 = N->getOperand(0);
4697 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
4698 EVT VT = N->getValueType(0);
4699 EVT OpVT = N0.getValueType();
4701 // fold (sint_to_fp c1) -> c1fp
4702 if (N0C && OpVT != MVT::ppcf128)
4703 return DAG.getNode(ISD::SINT_TO_FP, N->getDebugLoc(), VT, N0);
4705 // If the input is a legal type, and SINT_TO_FP is not legal on this target,
4706 // but UINT_TO_FP is legal on this target, try to convert.
4707 if (!TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT) &&
4708 TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT)) {
4709 // If the sign bit is known to be zero, we can change this to UINT_TO_FP.
4710 if (DAG.SignBitIsZero(N0))
4711 return DAG.getNode(ISD::UINT_TO_FP, N->getDebugLoc(), VT, N0);
4717 SDValue DAGCombiner::visitUINT_TO_FP(SDNode *N) {
4718 SDValue N0 = N->getOperand(0);
4719 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
4720 EVT VT = N->getValueType(0);
4721 EVT OpVT = N0.getValueType();
4723 // fold (uint_to_fp c1) -> c1fp
4724 if (N0C && OpVT != MVT::ppcf128)
4725 return DAG.getNode(ISD::UINT_TO_FP, N->getDebugLoc(), VT, N0);
4727 // If the input is a legal type, and UINT_TO_FP is not legal on this target,
4728 // but SINT_TO_FP is legal on this target, try to convert.
4729 if (!TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT) &&
4730 TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT)) {
4731 // If the sign bit is known to be zero, we can change this to SINT_TO_FP.
4732 if (DAG.SignBitIsZero(N0))
4733 return DAG.getNode(ISD::SINT_TO_FP, N->getDebugLoc(), VT, N0);
4739 SDValue DAGCombiner::visitFP_TO_SINT(SDNode *N) {
4740 SDValue N0 = N->getOperand(0);
4741 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
4742 EVT VT = N->getValueType(0);
4744 // fold (fp_to_sint c1fp) -> c1
4746 return DAG.getNode(ISD::FP_TO_SINT, N->getDebugLoc(), VT, N0);
4751 SDValue DAGCombiner::visitFP_TO_UINT(SDNode *N) {
4752 SDValue N0 = N->getOperand(0);
4753 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
4754 EVT VT = N->getValueType(0);
4756 // fold (fp_to_uint c1fp) -> c1
4757 if (N0CFP && VT != MVT::ppcf128)
4758 return DAG.getNode(ISD::FP_TO_UINT, N->getDebugLoc(), VT, N0);
4763 SDValue DAGCombiner::visitFP_ROUND(SDNode *N) {
4764 SDValue N0 = N->getOperand(0);
4765 SDValue N1 = N->getOperand(1);
4766 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
4767 EVT VT = N->getValueType(0);
4769 // fold (fp_round c1fp) -> c1fp
4770 if (N0CFP && N0.getValueType() != MVT::ppcf128)
4771 return DAG.getNode(ISD::FP_ROUND, N->getDebugLoc(), VT, N0, N1);
4773 // fold (fp_round (fp_extend x)) -> x
4774 if (N0.getOpcode() == ISD::FP_EXTEND && VT == N0.getOperand(0).getValueType())
4775 return N0.getOperand(0);
4777 // fold (fp_round (fp_round x)) -> (fp_round x)
4778 if (N0.getOpcode() == ISD::FP_ROUND) {
4779 // This is a value preserving truncation if both round's are.
4780 bool IsTrunc = N->getConstantOperandVal(1) == 1 &&
4781 N0.getNode()->getConstantOperandVal(1) == 1;
4782 return DAG.getNode(ISD::FP_ROUND, N->getDebugLoc(), VT, N0.getOperand(0),
4783 DAG.getIntPtrConstant(IsTrunc));
4786 // fold (fp_round (copysign X, Y)) -> (copysign (fp_round X), Y)
4787 if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse()) {
4788 SDValue Tmp = DAG.getNode(ISD::FP_ROUND, N0.getDebugLoc(), VT,
4789 N0.getOperand(0), N1);
4790 AddToWorkList(Tmp.getNode());
4791 return DAG.getNode(ISD::FCOPYSIGN, N->getDebugLoc(), VT,
4792 Tmp, N0.getOperand(1));
4798 SDValue DAGCombiner::visitFP_ROUND_INREG(SDNode *N) {
4799 SDValue N0 = N->getOperand(0);
4800 EVT VT = N->getValueType(0);
4801 EVT EVT = cast<VTSDNode>(N->getOperand(1))->getVT();
4802 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
4804 // fold (fp_round_inreg c1fp) -> c1fp
4805 if (N0CFP && isTypeLegal(EVT)) {
4806 SDValue Round = DAG.getConstantFP(*N0CFP->getConstantFPValue(), EVT);
4807 return DAG.getNode(ISD::FP_EXTEND, N->getDebugLoc(), VT, Round);
4813 SDValue DAGCombiner::visitFP_EXTEND(SDNode *N) {
4814 SDValue N0 = N->getOperand(0);
4815 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
4816 EVT VT = N->getValueType(0);
4818 // If this is fp_round(fpextend), don't fold it, allow ourselves to be folded.
4819 if (N->hasOneUse() &&
4820 N->use_begin()->getOpcode() == ISD::FP_ROUND)
4823 // fold (fp_extend c1fp) -> c1fp
4824 if (N0CFP && VT != MVT::ppcf128)
4825 return DAG.getNode(ISD::FP_EXTEND, N->getDebugLoc(), VT, N0);
4827 // Turn fp_extend(fp_round(X, 1)) -> x since the fp_round doesn't affect the
4829 if (N0.getOpcode() == ISD::FP_ROUND
4830 && N0.getNode()->getConstantOperandVal(1) == 1) {
4831 SDValue In = N0.getOperand(0);
4832 if (In.getValueType() == VT) return In;
4833 if (VT.bitsLT(In.getValueType()))
4834 return DAG.getNode(ISD::FP_ROUND, N->getDebugLoc(), VT,
4835 In, N0.getOperand(1));
4836 return DAG.getNode(ISD::FP_EXTEND, N->getDebugLoc(), VT, In);
4839 // fold (fpext (load x)) -> (fpext (fptrunc (extload x)))
4840 if (ISD::isNON_EXTLoad(N0.getNode()) && N0.hasOneUse() &&
4841 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
4842 TLI.isLoadExtLegal(ISD::EXTLOAD, N0.getValueType()))) {
4843 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
4844 SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, N->getDebugLoc(), VT,
4846 LN0->getBasePtr(), LN0->getSrcValue(),
4847 LN0->getSrcValueOffset(),
4849 LN0->isVolatile(), LN0->isNonTemporal(),
4850 LN0->getAlignment());
4851 CombineTo(N, ExtLoad);
4852 CombineTo(N0.getNode(),
4853 DAG.getNode(ISD::FP_ROUND, N0.getDebugLoc(),
4854 N0.getValueType(), ExtLoad, DAG.getIntPtrConstant(1)),
4855 ExtLoad.getValue(1));
4856 return SDValue(N, 0); // Return N so it doesn't get rechecked!
4862 SDValue DAGCombiner::visitFNEG(SDNode *N) {
4863 SDValue N0 = N->getOperand(0);
4864 EVT VT = N->getValueType(0);
4866 if (isNegatibleForFree(N0, LegalOperations))
4867 return GetNegatedExpression(N0, DAG, LegalOperations);
4869 // Transform fneg(bitconvert(x)) -> bitconvert(x^sign) to avoid loading
4870 // constant pool values.
4871 if (N0.getOpcode() == ISD::BIT_CONVERT &&
4873 N0.getNode()->hasOneUse() &&
4874 N0.getOperand(0).getValueType().isInteger()) {
4875 SDValue Int = N0.getOperand(0);
4876 EVT IntVT = Int.getValueType();
4877 if (IntVT.isInteger() && !IntVT.isVector()) {
4878 Int = DAG.getNode(ISD::XOR, N0.getDebugLoc(), IntVT, Int,
4879 DAG.getConstant(APInt::getSignBit(IntVT.getSizeInBits()), IntVT));
4880 AddToWorkList(Int.getNode());
4881 return DAG.getNode(ISD::BIT_CONVERT, N->getDebugLoc(),
4889 SDValue DAGCombiner::visitFABS(SDNode *N) {
4890 SDValue N0 = N->getOperand(0);
4891 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
4892 EVT VT = N->getValueType(0);
4894 // fold (fabs c1) -> fabs(c1)
4895 if (N0CFP && VT != MVT::ppcf128)
4896 return DAG.getNode(ISD::FABS, N->getDebugLoc(), VT, N0);
4897 // fold (fabs (fabs x)) -> (fabs x)
4898 if (N0.getOpcode() == ISD::FABS)
4899 return N->getOperand(0);
4900 // fold (fabs (fneg x)) -> (fabs x)
4901 // fold (fabs (fcopysign x, y)) -> (fabs x)
4902 if (N0.getOpcode() == ISD::FNEG || N0.getOpcode() == ISD::FCOPYSIGN)
4903 return DAG.getNode(ISD::FABS, N->getDebugLoc(), VT, N0.getOperand(0));
4905 // Transform fabs(bitconvert(x)) -> bitconvert(x&~sign) to avoid loading
4906 // constant pool values.
4907 if (N0.getOpcode() == ISD::BIT_CONVERT && N0.getNode()->hasOneUse() &&
4908 N0.getOperand(0).getValueType().isInteger() &&
4909 !N0.getOperand(0).getValueType().isVector()) {
4910 SDValue Int = N0.getOperand(0);
4911 EVT IntVT = Int.getValueType();
4912 if (IntVT.isInteger() && !IntVT.isVector()) {
4913 Int = DAG.getNode(ISD::AND, N0.getDebugLoc(), IntVT, Int,
4914 DAG.getConstant(~APInt::getSignBit(IntVT.getSizeInBits()), IntVT));
4915 AddToWorkList(Int.getNode());
4916 return DAG.getNode(ISD::BIT_CONVERT, N->getDebugLoc(),
4917 N->getValueType(0), Int);
4924 SDValue DAGCombiner::visitBRCOND(SDNode *N) {
4925 SDValue Chain = N->getOperand(0);
4926 SDValue N1 = N->getOperand(1);
4927 SDValue N2 = N->getOperand(2);
4929 // If N is a constant we could fold this into a fallthrough or unconditional
4930 // branch. However that doesn't happen very often in normal code, because
4931 // Instcombine/SimplifyCFG should have handled the available opportunities.
4932 // If we did this folding here, it would be necessary to update the
4933 // MachineBasicBlock CFG, which is awkward.
4935 // fold a brcond with a setcc condition into a BR_CC node if BR_CC is legal
4937 if (N1.getOpcode() == ISD::SETCC &&
4938 TLI.isOperationLegalOrCustom(ISD::BR_CC, MVT::Other)) {
4939 return DAG.getNode(ISD::BR_CC, N->getDebugLoc(), MVT::Other,
4940 Chain, N1.getOperand(2),
4941 N1.getOperand(0), N1.getOperand(1), N2);
4945 if (N1.getOpcode() == ISD::TRUNCATE && N1.hasOneUse()) {
4946 // Look past truncate.
4947 Trunc = N1.getNode();
4948 N1 = N1.getOperand(0);
4951 if (N1.hasOneUse() && N1.getOpcode() == ISD::SRL) {
4952 // Match this pattern so that we can generate simpler code:
4955 // %b = and i32 %a, 2
4956 // %c = srl i32 %b, 1
4957 // brcond i32 %c ...
4962 // %b = and i32 %a, 2
4963 // %c = setcc eq %b, 0
4966 // This applies only when the AND constant value has one bit set and the
4967 // SRL constant is equal to the log2 of the AND constant. The back-end is
4968 // smart enough to convert the result into a TEST/JMP sequence.
4969 SDValue Op0 = N1.getOperand(0);
4970 SDValue Op1 = N1.getOperand(1);
4972 if (Op0.getOpcode() == ISD::AND &&
4973 Op1.getOpcode() == ISD::Constant) {
4974 SDValue AndOp1 = Op0.getOperand(1);
4976 if (AndOp1.getOpcode() == ISD::Constant) {
4977 const APInt &AndConst = cast<ConstantSDNode>(AndOp1)->getAPIntValue();
4979 if (AndConst.isPowerOf2() &&
4980 cast<ConstantSDNode>(Op1)->getAPIntValue()==AndConst.logBase2()) {
4982 DAG.getSetCC(N->getDebugLoc(),
4983 TLI.getSetCCResultType(Op0.getValueType()),
4984 Op0, DAG.getConstant(0, Op0.getValueType()),
4987 SDValue NewBRCond = DAG.getNode(ISD::BRCOND, N->getDebugLoc(),
4988 MVT::Other, Chain, SetCC, N2);
4989 // Don't add the new BRCond into the worklist or else SimplifySelectCC
4990 // will convert it back to (X & C1) >> C2.
4991 CombineTo(N, NewBRCond, false);
4992 // Truncate is dead.
4994 removeFromWorkList(Trunc);
4995 DAG.DeleteNode(Trunc);
4997 // Replace the uses of SRL with SETCC
4998 WorkListRemover DeadNodes(*this);
4999 DAG.ReplaceAllUsesOfValueWith(N1, SetCC, &DeadNodes);
5000 removeFromWorkList(N1.getNode());
5001 DAG.DeleteNode(N1.getNode());
5002 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5008 // Transform br(xor(x, y)) -> br(x != y)
5009 // Transform br(xor(xor(x,y), 1)) -> br (x == y)
5010 if (N1.hasOneUse() && N1.getOpcode() == ISD::XOR) {
5011 SDNode *TheXor = N1.getNode();
5012 SDValue Op0 = TheXor->getOperand(0);
5013 SDValue Op1 = TheXor->getOperand(1);
5014 if (Op0.getOpcode() == Op1.getOpcode()) {
5015 // Avoid missing important xor optimizations.
5016 SDValue Tmp = visitXOR(TheXor);
5017 if (Tmp.getNode() && Tmp.getNode() != TheXor) {
5018 DEBUG(dbgs() << "\nReplacing.8 ";
5020 dbgs() << "\nWith: ";
5021 Tmp.getNode()->dump(&DAG);
5023 WorkListRemover DeadNodes(*this);
5024 DAG.ReplaceAllUsesOfValueWith(N1, Tmp, &DeadNodes);
5025 removeFromWorkList(TheXor);
5026 DAG.DeleteNode(TheXor);
5027 return DAG.getNode(ISD::BRCOND, N->getDebugLoc(),
5028 MVT::Other, Chain, Tmp, N2);
5032 if (Op0.getOpcode() != ISD::SETCC && Op1.getOpcode() != ISD::SETCC) {
5034 if (ConstantSDNode *RHSCI = dyn_cast<ConstantSDNode>(Op0))
5035 if (RHSCI->getAPIntValue() == 1 && Op0.hasOneUse() &&
5036 Op0.getOpcode() == ISD::XOR) {
5037 TheXor = Op0.getNode();
5041 SDValue NodeToReplace = Trunc ? SDValue(Trunc, 0) : N1;
5043 EVT SetCCVT = NodeToReplace.getValueType();
5045 SetCCVT = TLI.getSetCCResultType(SetCCVT);
5046 SDValue SetCC = DAG.getSetCC(TheXor->getDebugLoc(),
5049 Equal ? ISD::SETEQ : ISD::SETNE);
5050 // Replace the uses of XOR with SETCC
5051 WorkListRemover DeadNodes(*this);
5052 DAG.ReplaceAllUsesOfValueWith(NodeToReplace, SetCC, &DeadNodes);
5053 removeFromWorkList(NodeToReplace.getNode());
5054 DAG.DeleteNode(NodeToReplace.getNode());
5055 return DAG.getNode(ISD::BRCOND, N->getDebugLoc(),
5056 MVT::Other, Chain, SetCC, N2);
5063 // Operand List for BR_CC: Chain, CondCC, CondLHS, CondRHS, DestBB.
5065 SDValue DAGCombiner::visitBR_CC(SDNode *N) {
5066 CondCodeSDNode *CC = cast<CondCodeSDNode>(N->getOperand(1));
5067 SDValue CondLHS = N->getOperand(2), CondRHS = N->getOperand(3);
5069 // If N is a constant we could fold this into a fallthrough or unconditional
5070 // branch. However that doesn't happen very often in normal code, because
5071 // Instcombine/SimplifyCFG should have handled the available opportunities.
5072 // If we did this folding here, it would be necessary to update the
5073 // MachineBasicBlock CFG, which is awkward.
5075 // Use SimplifySetCC to simplify SETCC's.
5076 SDValue Simp = SimplifySetCC(TLI.getSetCCResultType(CondLHS.getValueType()),
5077 CondLHS, CondRHS, CC->get(), N->getDebugLoc(),
5079 if (Simp.getNode()) AddToWorkList(Simp.getNode());
5081 // fold to a simpler setcc
5082 if (Simp.getNode() && Simp.getOpcode() == ISD::SETCC)
5083 return DAG.getNode(ISD::BR_CC, N->getDebugLoc(), MVT::Other,
5084 N->getOperand(0), Simp.getOperand(2),
5085 Simp.getOperand(0), Simp.getOperand(1),
5091 /// CombineToPreIndexedLoadStore - Try turning a load / store into a
5092 /// pre-indexed load / store when the base pointer is an add or subtract
5093 /// and it has other uses besides the load / store. After the
5094 /// transformation, the new indexed load / store has effectively folded
5095 /// the add / subtract in and all of its other uses are redirected to the
5096 /// new load / store.
5097 bool DAGCombiner::CombineToPreIndexedLoadStore(SDNode *N) {
5098 if (!LegalOperations)
5104 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
5105 if (LD->isIndexed())
5107 VT = LD->getMemoryVT();
5108 if (!TLI.isIndexedLoadLegal(ISD::PRE_INC, VT) &&
5109 !TLI.isIndexedLoadLegal(ISD::PRE_DEC, VT))
5111 Ptr = LD->getBasePtr();
5112 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
5113 if (ST->isIndexed())
5115 VT = ST->getMemoryVT();
5116 if (!TLI.isIndexedStoreLegal(ISD::PRE_INC, VT) &&
5117 !TLI.isIndexedStoreLegal(ISD::PRE_DEC, VT))
5119 Ptr = ST->getBasePtr();
5125 // If the pointer is not an add/sub, or if it doesn't have multiple uses, bail
5126 // out. There is no reason to make this a preinc/predec.
5127 if ((Ptr.getOpcode() != ISD::ADD && Ptr.getOpcode() != ISD::SUB) ||
5128 Ptr.getNode()->hasOneUse())
5131 // Ask the target to do addressing mode selection.
5134 ISD::MemIndexedMode AM = ISD::UNINDEXED;
5135 if (!TLI.getPreIndexedAddressParts(N, BasePtr, Offset, AM, DAG))
5137 // Don't create a indexed load / store with zero offset.
5138 if (isa<ConstantSDNode>(Offset) &&
5139 cast<ConstantSDNode>(Offset)->isNullValue())
5142 // Try turning it into a pre-indexed load / store except when:
5143 // 1) The new base ptr is a frame index.
5144 // 2) If N is a store and the new base ptr is either the same as or is a
5145 // predecessor of the value being stored.
5146 // 3) Another use of old base ptr is a predecessor of N. If ptr is folded
5147 // that would create a cycle.
5148 // 4) All uses are load / store ops that use it as old base ptr.
5150 // Check #1. Preinc'ing a frame index would require copying the stack pointer
5151 // (plus the implicit offset) to a register to preinc anyway.
5152 if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr))
5157 SDValue Val = cast<StoreSDNode>(N)->getValue();
5158 if (Val == BasePtr || BasePtr.getNode()->isPredecessorOf(Val.getNode()))
5162 // Now check for #3 and #4.
5163 bool RealUse = false;
5164 for (SDNode::use_iterator I = Ptr.getNode()->use_begin(),
5165 E = Ptr.getNode()->use_end(); I != E; ++I) {
5169 if (Use->isPredecessorOf(N))
5172 if (!((Use->getOpcode() == ISD::LOAD &&
5173 cast<LoadSDNode>(Use)->getBasePtr() == Ptr) ||
5174 (Use->getOpcode() == ISD::STORE &&
5175 cast<StoreSDNode>(Use)->getBasePtr() == Ptr)))
5184 Result = DAG.getIndexedLoad(SDValue(N,0), N->getDebugLoc(),
5185 BasePtr, Offset, AM);
5187 Result = DAG.getIndexedStore(SDValue(N,0), N->getDebugLoc(),
5188 BasePtr, Offset, AM);
5191 DEBUG(dbgs() << "\nReplacing.4 ";
5193 dbgs() << "\nWith: ";
5194 Result.getNode()->dump(&DAG);
5196 WorkListRemover DeadNodes(*this);
5198 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0),
5200 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2),
5203 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1),
5207 // Finally, since the node is now dead, remove it from the graph.
5210 // Replace the uses of Ptr with uses of the updated base value.
5211 DAG.ReplaceAllUsesOfValueWith(Ptr, Result.getValue(isLoad ? 1 : 0),
5213 removeFromWorkList(Ptr.getNode());
5214 DAG.DeleteNode(Ptr.getNode());
5219 /// CombineToPostIndexedLoadStore - Try to combine a load / store with a
5220 /// add / sub of the base pointer node into a post-indexed load / store.
5221 /// The transformation folded the add / subtract into the new indexed
5222 /// load / store effectively and all of its uses are redirected to the
5223 /// new load / store.
5224 bool DAGCombiner::CombineToPostIndexedLoadStore(SDNode *N) {
5225 if (!LegalOperations)
5231 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
5232 if (LD->isIndexed())
5234 VT = LD->getMemoryVT();
5235 if (!TLI.isIndexedLoadLegal(ISD::POST_INC, VT) &&
5236 !TLI.isIndexedLoadLegal(ISD::POST_DEC, VT))
5238 Ptr = LD->getBasePtr();
5239 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
5240 if (ST->isIndexed())
5242 VT = ST->getMemoryVT();
5243 if (!TLI.isIndexedStoreLegal(ISD::POST_INC, VT) &&
5244 !TLI.isIndexedStoreLegal(ISD::POST_DEC, VT))
5246 Ptr = ST->getBasePtr();
5252 if (Ptr.getNode()->hasOneUse())
5255 for (SDNode::use_iterator I = Ptr.getNode()->use_begin(),
5256 E = Ptr.getNode()->use_end(); I != E; ++I) {
5259 (Op->getOpcode() != ISD::ADD && Op->getOpcode() != ISD::SUB))
5264 ISD::MemIndexedMode AM = ISD::UNINDEXED;
5265 if (TLI.getPostIndexedAddressParts(N, Op, BasePtr, Offset, AM, DAG)) {
5266 if (Ptr == Offset && Op->getOpcode() == ISD::ADD)
5267 std::swap(BasePtr, Offset);
5270 // Don't create a indexed load / store with zero offset.
5271 if (isa<ConstantSDNode>(Offset) &&
5272 cast<ConstantSDNode>(Offset)->isNullValue())
5275 // Try turning it into a post-indexed load / store except when
5276 // 1) All uses are load / store ops that use it as base ptr.
5277 // 2) Op must be independent of N, i.e. Op is neither a predecessor
5278 // nor a successor of N. Otherwise, if Op is folded that would
5281 if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr))
5285 bool TryNext = false;
5286 for (SDNode::use_iterator II = BasePtr.getNode()->use_begin(),
5287 EE = BasePtr.getNode()->use_end(); II != EE; ++II) {
5289 if (Use == Ptr.getNode())
5292 // If all the uses are load / store addresses, then don't do the
5294 if (Use->getOpcode() == ISD::ADD || Use->getOpcode() == ISD::SUB){
5295 bool RealUse = false;
5296 for (SDNode::use_iterator III = Use->use_begin(),
5297 EEE = Use->use_end(); III != EEE; ++III) {
5298 SDNode *UseUse = *III;
5299 if (!((UseUse->getOpcode() == ISD::LOAD &&
5300 cast<LoadSDNode>(UseUse)->getBasePtr().getNode() == Use) ||
5301 (UseUse->getOpcode() == ISD::STORE &&
5302 cast<StoreSDNode>(UseUse)->getBasePtr().getNode() == Use)))
5317 if (!Op->isPredecessorOf(N) && !N->isPredecessorOf(Op)) {
5318 SDValue Result = isLoad
5319 ? DAG.getIndexedLoad(SDValue(N,0), N->getDebugLoc(),
5320 BasePtr, Offset, AM)
5321 : DAG.getIndexedStore(SDValue(N,0), N->getDebugLoc(),
5322 BasePtr, Offset, AM);
5325 DEBUG(dbgs() << "\nReplacing.5 ";
5327 dbgs() << "\nWith: ";
5328 Result.getNode()->dump(&DAG);
5330 WorkListRemover DeadNodes(*this);
5332 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0),
5334 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2),
5337 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1),
5341 // Finally, since the node is now dead, remove it from the graph.
5344 // Replace the uses of Use with uses of the updated base value.
5345 DAG.ReplaceAllUsesOfValueWith(SDValue(Op, 0),
5346 Result.getValue(isLoad ? 1 : 0),
5348 removeFromWorkList(Op);
5358 SDValue DAGCombiner::visitLOAD(SDNode *N) {
5359 LoadSDNode *LD = cast<LoadSDNode>(N);
5360 SDValue Chain = LD->getChain();
5361 SDValue Ptr = LD->getBasePtr();
5363 // If load is not volatile and there are no uses of the loaded value (and
5364 // the updated indexed value in case of indexed loads), change uses of the
5365 // chain value into uses of the chain input (i.e. delete the dead load).
5366 if (!LD->isVolatile()) {
5367 if (N->getValueType(1) == MVT::Other) {
5369 if (N->hasNUsesOfValue(0, 0)) {
5370 // It's not safe to use the two value CombineTo variant here. e.g.
5371 // v1, chain2 = load chain1, loc
5372 // v2, chain3 = load chain2, loc
5374 // Now we replace use of chain2 with chain1. This makes the second load
5375 // isomorphic to the one we are deleting, and thus makes this load live.
5376 DEBUG(dbgs() << "\nReplacing.6 ";
5378 dbgs() << "\nWith chain: ";
5379 Chain.getNode()->dump(&DAG);
5381 WorkListRemover DeadNodes(*this);
5382 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain, &DeadNodes);
5384 if (N->use_empty()) {
5385 removeFromWorkList(N);
5389 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5393 assert(N->getValueType(2) == MVT::Other && "Malformed indexed loads?");
5394 if (N->hasNUsesOfValue(0, 0) && N->hasNUsesOfValue(0, 1)) {
5395 SDValue Undef = DAG.getUNDEF(N->getValueType(0));
5396 DEBUG(dbgs() << "\nReplacing.7 ";
5398 dbgs() << "\nWith: ";
5399 Undef.getNode()->dump(&DAG);
5400 dbgs() << " and 2 other values\n");
5401 WorkListRemover DeadNodes(*this);
5402 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Undef, &DeadNodes);
5403 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1),
5404 DAG.getUNDEF(N->getValueType(1)),
5406 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 2), Chain, &DeadNodes);
5407 removeFromWorkList(N);
5409 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5414 // If this load is directly stored, replace the load value with the stored
5416 // TODO: Handle store large -> read small portion.
5417 // TODO: Handle TRUNCSTORE/LOADEXT
5418 if (LD->getExtensionType() == ISD::NON_EXTLOAD &&
5419 !LD->isVolatile()) {
5420 if (ISD::isNON_TRUNCStore(Chain.getNode())) {
5421 StoreSDNode *PrevST = cast<StoreSDNode>(Chain);
5422 if (PrevST->getBasePtr() == Ptr &&
5423 PrevST->getValue().getValueType() == N->getValueType(0))
5424 return CombineTo(N, Chain.getOperand(1), Chain);
5428 // Try to infer better alignment information than the load already has.
5429 if (OptLevel != CodeGenOpt::None && LD->isUnindexed()) {
5430 if (unsigned Align = DAG.InferPtrAlignment(Ptr)) {
5431 if (Align > LD->getAlignment())
5432 return DAG.getExtLoad(LD->getExtensionType(), N->getDebugLoc(),
5433 LD->getValueType(0),
5434 Chain, Ptr, LD->getSrcValue(),
5435 LD->getSrcValueOffset(), LD->getMemoryVT(),
5436 LD->isVolatile(), LD->isNonTemporal(), Align);
5441 // Walk up chain skipping non-aliasing memory nodes.
5442 SDValue BetterChain = FindBetterChain(N, Chain);
5444 // If there is a better chain.
5445 if (Chain != BetterChain) {
5448 // Replace the chain to void dependency.
5449 if (LD->getExtensionType() == ISD::NON_EXTLOAD) {
5450 ReplLoad = DAG.getLoad(N->getValueType(0), LD->getDebugLoc(),
5452 LD->getSrcValue(), LD->getSrcValueOffset(),
5453 LD->isVolatile(), LD->isNonTemporal(),
5454 LD->getAlignment());
5456 ReplLoad = DAG.getExtLoad(LD->getExtensionType(), LD->getDebugLoc(),
5457 LD->getValueType(0),
5458 BetterChain, Ptr, LD->getSrcValue(),
5459 LD->getSrcValueOffset(),
5462 LD->isNonTemporal(),
5463 LD->getAlignment());
5466 // Create token factor to keep old chain connected.
5467 SDValue Token = DAG.getNode(ISD::TokenFactor, N->getDebugLoc(),
5468 MVT::Other, Chain, ReplLoad.getValue(1));
5470 // Make sure the new and old chains are cleaned up.
5471 AddToWorkList(Token.getNode());
5473 // Replace uses with load result and token factor. Don't add users
5475 return CombineTo(N, ReplLoad.getValue(0), Token, false);
5479 // Try transforming N to an indexed load.
5480 if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
5481 return SDValue(N, 0);
5486 /// CheckForMaskedLoad - Check to see if V is (and load (ptr), imm), where the
5487 /// load is having specific bytes cleared out. If so, return the byte size
5488 /// being masked out and the shift amount.
5489 static std::pair<unsigned, unsigned>
5490 CheckForMaskedLoad(SDValue V, SDValue Ptr, SDValue Chain) {
5491 std::pair<unsigned, unsigned> Result(0, 0);
5493 // Check for the structure we're looking for.
5494 if (V->getOpcode() != ISD::AND ||
5495 !isa<ConstantSDNode>(V->getOperand(1)) ||
5496 !ISD::isNormalLoad(V->getOperand(0).getNode()))
5499 // Check the chain and pointer.
5500 LoadSDNode *LD = cast<LoadSDNode>(V->getOperand(0));
5501 if (LD->getBasePtr() != Ptr) return Result; // Not from same pointer.
5503 // The store should be chained directly to the load or be an operand of a
5505 if (LD == Chain.getNode())
5507 else if (Chain->getOpcode() != ISD::TokenFactor)
5508 return Result; // Fail.
5511 for (unsigned i = 0, e = Chain->getNumOperands(); i != e; ++i)
5512 if (Chain->getOperand(i).getNode() == LD) {
5516 if (!isOk) return Result;
5519 // This only handles simple types.
5520 if (V.getValueType() != MVT::i16 &&
5521 V.getValueType() != MVT::i32 &&
5522 V.getValueType() != MVT::i64)
5525 // Check the constant mask. Invert it so that the bits being masked out are
5526 // 0 and the bits being kept are 1. Use getSExtValue so that leading bits
5527 // follow the sign bit for uniformity.
5528 uint64_t NotMask = ~cast<ConstantSDNode>(V->getOperand(1))->getSExtValue();
5529 unsigned NotMaskLZ = CountLeadingZeros_64(NotMask);
5530 if (NotMaskLZ & 7) return Result; // Must be multiple of a byte.
5531 unsigned NotMaskTZ = CountTrailingZeros_64(NotMask);
5532 if (NotMaskTZ & 7) return Result; // Must be multiple of a byte.
5533 if (NotMaskLZ == 64) return Result; // All zero mask.
5535 // See if we have a continuous run of bits. If so, we have 0*1+0*
5536 if (CountTrailingOnes_64(NotMask >> NotMaskTZ)+NotMaskTZ+NotMaskLZ != 64)
5539 // Adjust NotMaskLZ down to be from the actual size of the int instead of i64.
5540 if (V.getValueType() != MVT::i64 && NotMaskLZ)
5541 NotMaskLZ -= 64-V.getValueSizeInBits();
5543 unsigned MaskedBytes = (V.getValueSizeInBits()-NotMaskLZ-NotMaskTZ)/8;
5544 switch (MaskedBytes) {
5548 default: return Result; // All one mask, or 5-byte mask.
5551 // Verify that the first bit starts at a multiple of mask so that the access
5552 // is aligned the same as the access width.
5553 if (NotMaskTZ && NotMaskTZ/8 % MaskedBytes) return Result;
5555 Result.first = MaskedBytes;
5556 Result.second = NotMaskTZ/8;
5561 /// ShrinkLoadReplaceStoreWithStore - Check to see if IVal is something that
5562 /// provides a value as specified by MaskInfo. If so, replace the specified
5563 /// store with a narrower store of truncated IVal.
5565 ShrinkLoadReplaceStoreWithStore(const std::pair<unsigned, unsigned> &MaskInfo,
5566 SDValue IVal, StoreSDNode *St,
5568 unsigned NumBytes = MaskInfo.first;
5569 unsigned ByteShift = MaskInfo.second;
5570 SelectionDAG &DAG = DC->getDAG();
5572 // Check to see if IVal is all zeros in the part being masked in by the 'or'
5573 // that uses this. If not, this is not a replacement.
5574 APInt Mask = ~APInt::getBitsSet(IVal.getValueSizeInBits(),
5575 ByteShift*8, (ByteShift+NumBytes)*8);
5576 if (!DAG.MaskedValueIsZero(IVal, Mask)) return 0;
5578 // Check that it is legal on the target to do this. It is legal if the new
5579 // VT we're shrinking to (i8/i16/i32) is legal or we're still before type
5581 MVT VT = MVT::getIntegerVT(NumBytes*8);
5582 if (!DC->isTypeLegal(VT))
5585 // Okay, we can do this! Replace the 'St' store with a store of IVal that is
5586 // shifted by ByteShift and truncated down to NumBytes.
5588 IVal = DAG.getNode(ISD::SRL, IVal->getDebugLoc(), IVal.getValueType(), IVal,
5589 DAG.getConstant(ByteShift*8, DC->getShiftAmountTy()));
5591 // Figure out the offset for the store and the alignment of the access.
5593 unsigned NewAlign = St->getAlignment();
5595 if (DAG.getTargetLoweringInfo().isLittleEndian())
5596 StOffset = ByteShift;
5598 StOffset = IVal.getValueType().getStoreSize() - ByteShift - NumBytes;
5600 SDValue Ptr = St->getBasePtr();
5602 Ptr = DAG.getNode(ISD::ADD, IVal->getDebugLoc(), Ptr.getValueType(),
5603 Ptr, DAG.getConstant(StOffset, Ptr.getValueType()));
5604 NewAlign = MinAlign(NewAlign, StOffset);
5607 // Truncate down to the new size.
5608 IVal = DAG.getNode(ISD::TRUNCATE, IVal->getDebugLoc(), VT, IVal);
5611 return DAG.getStore(St->getChain(), St->getDebugLoc(), IVal, Ptr,
5612 St->getSrcValue(), St->getSrcValueOffset()+StOffset,
5613 false, false, NewAlign).getNode();
5617 /// ReduceLoadOpStoreWidth - Look for sequence of load / op / store where op is
5618 /// one of 'or', 'xor', and 'and' of immediates. If 'op' is only touching some
5619 /// of the loaded bits, try narrowing the load and store if it would end up
5620 /// being a win for performance or code size.
5621 SDValue DAGCombiner::ReduceLoadOpStoreWidth(SDNode *N) {
5622 StoreSDNode *ST = cast<StoreSDNode>(N);
5623 if (ST->isVolatile())
5626 SDValue Chain = ST->getChain();
5627 SDValue Value = ST->getValue();
5628 SDValue Ptr = ST->getBasePtr();
5629 EVT VT = Value.getValueType();
5631 if (ST->isTruncatingStore() || VT.isVector() || !Value.hasOneUse())
5634 unsigned Opc = Value.getOpcode();
5636 // If this is "store (or X, Y), P" and X is "(and (load P), cst)", where cst
5637 // is a byte mask indicating a consecutive number of bytes, check to see if
5638 // Y is known to provide just those bytes. If so, we try to replace the
5639 // load + replace + store sequence with a single (narrower) store, which makes
5641 if (Opc == ISD::OR) {
5642 std::pair<unsigned, unsigned> MaskedLoad;
5643 MaskedLoad = CheckForMaskedLoad(Value.getOperand(0), Ptr, Chain);
5644 if (MaskedLoad.first)
5645 if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad,
5646 Value.getOperand(1), ST,this))
5647 return SDValue(NewST, 0);
5649 // Or is commutative, so try swapping X and Y.
5650 MaskedLoad = CheckForMaskedLoad(Value.getOperand(1), Ptr, Chain);
5651 if (MaskedLoad.first)
5652 if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad,
5653 Value.getOperand(0), ST,this))
5654 return SDValue(NewST, 0);
5657 if ((Opc != ISD::OR && Opc != ISD::XOR && Opc != ISD::AND) ||
5658 Value.getOperand(1).getOpcode() != ISD::Constant)
5661 SDValue N0 = Value.getOperand(0);
5662 if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse()) {
5663 LoadSDNode *LD = cast<LoadSDNode>(N0);
5664 if (LD->getBasePtr() != Ptr)
5667 // Find the type to narrow it the load / op / store to.
5668 SDValue N1 = Value.getOperand(1);
5669 unsigned BitWidth = N1.getValueSizeInBits();
5670 APInt Imm = cast<ConstantSDNode>(N1)->getAPIntValue();
5671 if (Opc == ISD::AND)
5672 Imm ^= APInt::getAllOnesValue(BitWidth);
5673 if (Imm == 0 || Imm.isAllOnesValue())
5675 unsigned ShAmt = Imm.countTrailingZeros();
5676 unsigned MSB = BitWidth - Imm.countLeadingZeros() - 1;
5677 unsigned NewBW = NextPowerOf2(MSB - ShAmt);
5678 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW);
5679 while (NewBW < BitWidth &&
5680 !(TLI.isOperationLegalOrCustom(Opc, NewVT) &&
5681 TLI.isNarrowingProfitable(VT, NewVT))) {
5682 NewBW = NextPowerOf2(NewBW);
5683 NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW);
5685 if (NewBW >= BitWidth)
5688 // If the lsb changed does not start at the type bitwidth boundary,
5689 // start at the previous one.
5691 ShAmt = (((ShAmt + NewBW - 1) / NewBW) * NewBW) - NewBW;
5692 APInt Mask = APInt::getBitsSet(BitWidth, ShAmt, ShAmt + NewBW);
5693 if ((Imm & Mask) == Imm) {
5694 APInt NewImm = (Imm & Mask).lshr(ShAmt).trunc(NewBW);
5695 if (Opc == ISD::AND)
5696 NewImm ^= APInt::getAllOnesValue(NewBW);
5697 uint64_t PtrOff = ShAmt / 8;
5698 // For big endian targets, we need to adjust the offset to the pointer to
5699 // load the correct bytes.
5700 if (TLI.isBigEndian())
5701 PtrOff = (BitWidth + 7 - NewBW) / 8 - PtrOff;
5703 unsigned NewAlign = MinAlign(LD->getAlignment(), PtrOff);
5704 const Type *NewVTTy = NewVT.getTypeForEVT(*DAG.getContext());
5705 if (NewAlign < TLI.getTargetData()->getABITypeAlignment(NewVTTy))
5708 SDValue NewPtr = DAG.getNode(ISD::ADD, LD->getDebugLoc(),
5709 Ptr.getValueType(), Ptr,
5710 DAG.getConstant(PtrOff, Ptr.getValueType()));
5711 SDValue NewLD = DAG.getLoad(NewVT, N0.getDebugLoc(),
5712 LD->getChain(), NewPtr,
5713 LD->getSrcValue(), LD->getSrcValueOffset(),
5714 LD->isVolatile(), LD->isNonTemporal(),
5716 SDValue NewVal = DAG.getNode(Opc, Value.getDebugLoc(), NewVT, NewLD,
5717 DAG.getConstant(NewImm, NewVT));
5718 SDValue NewST = DAG.getStore(Chain, N->getDebugLoc(),
5720 ST->getSrcValue(), ST->getSrcValueOffset(),
5721 false, false, NewAlign);
5723 AddToWorkList(NewPtr.getNode());
5724 AddToWorkList(NewLD.getNode());
5725 AddToWorkList(NewVal.getNode());
5726 WorkListRemover DeadNodes(*this);
5727 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLD.getValue(1),
5737 SDValue DAGCombiner::visitSTORE(SDNode *N) {
5738 StoreSDNode *ST = cast<StoreSDNode>(N);
5739 SDValue Chain = ST->getChain();
5740 SDValue Value = ST->getValue();
5741 SDValue Ptr = ST->getBasePtr();
5743 // If this is a store of a bit convert, store the input value if the
5744 // resultant store does not need a higher alignment than the original.
5745 if (Value.getOpcode() == ISD::BIT_CONVERT && !ST->isTruncatingStore() &&
5746 ST->isUnindexed()) {
5747 unsigned OrigAlign = ST->getAlignment();
5748 EVT SVT = Value.getOperand(0).getValueType();
5749 unsigned Align = TLI.getTargetData()->
5750 getABITypeAlignment(SVT.getTypeForEVT(*DAG.getContext()));
5751 if (Align <= OrigAlign &&
5752 ((!LegalOperations && !ST->isVolatile()) ||
5753 TLI.isOperationLegalOrCustom(ISD::STORE, SVT)))
5754 return DAG.getStore(Chain, N->getDebugLoc(), Value.getOperand(0),
5755 Ptr, ST->getSrcValue(),
5756 ST->getSrcValueOffset(), ST->isVolatile(),
5757 ST->isNonTemporal(), OrigAlign);
5760 // Turn 'store float 1.0, Ptr' -> 'store int 0x12345678, Ptr'
5761 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Value)) {
5762 // NOTE: If the original store is volatile, this transform must not increase
5763 // the number of stores. For example, on x86-32 an f64 can be stored in one
5764 // processor operation but an i64 (which is not legal) requires two. So the
5765 // transform should not be done in this case.
5766 if (Value.getOpcode() != ISD::TargetConstantFP) {
5768 switch (CFP->getValueType(0).getSimpleVT().SimpleTy) {
5769 default: llvm_unreachable("Unknown FP type");
5770 case MVT::f80: // We don't do this for these yet.
5775 if ((isTypeLegal(MVT::i32) && !LegalOperations && !ST->isVolatile()) ||
5776 TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) {
5777 Tmp = DAG.getConstant((uint32_t)CFP->getValueAPF().
5778 bitcastToAPInt().getZExtValue(), MVT::i32);
5779 return DAG.getStore(Chain, N->getDebugLoc(), Tmp,
5780 Ptr, ST->getSrcValue(),
5781 ST->getSrcValueOffset(), ST->isVolatile(),
5782 ST->isNonTemporal(), ST->getAlignment());
5786 if ((TLI.isTypeLegal(MVT::i64) && !LegalOperations &&
5787 !ST->isVolatile()) ||
5788 TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i64)) {
5789 Tmp = DAG.getConstant(CFP->getValueAPF().bitcastToAPInt().
5790 getZExtValue(), MVT::i64);
5791 return DAG.getStore(Chain, N->getDebugLoc(), Tmp,
5792 Ptr, ST->getSrcValue(),
5793 ST->getSrcValueOffset(), ST->isVolatile(),
5794 ST->isNonTemporal(), ST->getAlignment());
5795 } else if (!ST->isVolatile() &&
5796 TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) {
5797 // Many FP stores are not made apparent until after legalize, e.g. for
5798 // argument passing. Since this is so common, custom legalize the
5799 // 64-bit integer store into two 32-bit stores.
5800 uint64_t Val = CFP->getValueAPF().bitcastToAPInt().getZExtValue();
5801 SDValue Lo = DAG.getConstant(Val & 0xFFFFFFFF, MVT::i32);
5802 SDValue Hi = DAG.getConstant(Val >> 32, MVT::i32);
5803 if (TLI.isBigEndian()) std::swap(Lo, Hi);
5805 int SVOffset = ST->getSrcValueOffset();
5806 unsigned Alignment = ST->getAlignment();
5807 bool isVolatile = ST->isVolatile();
5808 bool isNonTemporal = ST->isNonTemporal();
5810 SDValue St0 = DAG.getStore(Chain, ST->getDebugLoc(), Lo,
5811 Ptr, ST->getSrcValue(),
5812 ST->getSrcValueOffset(),
5813 isVolatile, isNonTemporal,
5814 ST->getAlignment());
5815 Ptr = DAG.getNode(ISD::ADD, N->getDebugLoc(), Ptr.getValueType(), Ptr,
5816 DAG.getConstant(4, Ptr.getValueType()));
5818 Alignment = MinAlign(Alignment, 4U);
5819 SDValue St1 = DAG.getStore(Chain, ST->getDebugLoc(), Hi,
5820 Ptr, ST->getSrcValue(),
5821 SVOffset, isVolatile, isNonTemporal,
5823 return DAG.getNode(ISD::TokenFactor, N->getDebugLoc(), MVT::Other,
5832 // Try to infer better alignment information than the store already has.
5833 if (OptLevel != CodeGenOpt::None && ST->isUnindexed()) {
5834 if (unsigned Align = DAG.InferPtrAlignment(Ptr)) {
5835 if (Align > ST->getAlignment())
5836 return DAG.getTruncStore(Chain, N->getDebugLoc(), Value,
5837 Ptr, ST->getSrcValue(),
5838 ST->getSrcValueOffset(), ST->getMemoryVT(),
5839 ST->isVolatile(), ST->isNonTemporal(), Align);
5844 // Walk up chain skipping non-aliasing memory nodes.
5845 SDValue BetterChain = FindBetterChain(N, Chain);
5847 // If there is a better chain.
5848 if (Chain != BetterChain) {
5851 // Replace the chain to avoid dependency.
5852 if (ST->isTruncatingStore()) {
5853 ReplStore = DAG.getTruncStore(BetterChain, N->getDebugLoc(), Value, Ptr,
5854 ST->getSrcValue(),ST->getSrcValueOffset(),
5855 ST->getMemoryVT(), ST->isVolatile(),
5856 ST->isNonTemporal(), ST->getAlignment());
5858 ReplStore = DAG.getStore(BetterChain, N->getDebugLoc(), Value, Ptr,
5859 ST->getSrcValue(), ST->getSrcValueOffset(),
5860 ST->isVolatile(), ST->isNonTemporal(),
5861 ST->getAlignment());
5864 // Create token to keep both nodes around.
5865 SDValue Token = DAG.getNode(ISD::TokenFactor, N->getDebugLoc(),
5866 MVT::Other, Chain, ReplStore);
5868 // Make sure the new and old chains are cleaned up.
5869 AddToWorkList(Token.getNode());
5871 // Don't add users to work list.
5872 return CombineTo(N, Token, false);
5876 // Try transforming N to an indexed store.
5877 if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
5878 return SDValue(N, 0);
5880 // FIXME: is there such a thing as a truncating indexed store?
5881 if (ST->isTruncatingStore() && ST->isUnindexed() &&
5882 Value.getValueType().isInteger()) {
5883 // See if we can simplify the input to this truncstore with knowledge that
5884 // only the low bits are being used. For example:
5885 // "truncstore (or (shl x, 8), y), i8" -> "truncstore y, i8"
5887 GetDemandedBits(Value,
5888 APInt::getLowBitsSet(Value.getValueSizeInBits(),
5889 ST->getMemoryVT().getSizeInBits()));
5890 AddToWorkList(Value.getNode());
5891 if (Shorter.getNode())
5892 return DAG.getTruncStore(Chain, N->getDebugLoc(), Shorter,
5893 Ptr, ST->getSrcValue(),
5894 ST->getSrcValueOffset(), ST->getMemoryVT(),
5895 ST->isVolatile(), ST->isNonTemporal(),
5896 ST->getAlignment());
5898 // Otherwise, see if we can simplify the operation with
5899 // SimplifyDemandedBits, which only works if the value has a single use.
5900 if (SimplifyDemandedBits(Value,
5901 APInt::getLowBitsSet(
5902 Value.getValueType().getScalarType().getSizeInBits(),
5903 ST->getMemoryVT().getScalarType().getSizeInBits())))
5904 return SDValue(N, 0);
5907 // If this is a load followed by a store to the same location, then the store
5909 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Value)) {
5910 if (Ld->getBasePtr() == Ptr && ST->getMemoryVT() == Ld->getMemoryVT() &&
5911 ST->isUnindexed() && !ST->isVolatile() &&
5912 // There can't be any side effects between the load and store, such as
5914 Chain.reachesChainWithoutSideEffects(SDValue(Ld, 1))) {
5915 // The store is dead, remove it.
5920 // If this is an FP_ROUND or TRUNC followed by a store, fold this into a
5921 // truncating store. We can do this even if this is already a truncstore.
5922 if ((Value.getOpcode() == ISD::FP_ROUND || Value.getOpcode() == ISD::TRUNCATE)
5923 && Value.getNode()->hasOneUse() && ST->isUnindexed() &&
5924 TLI.isTruncStoreLegal(Value.getOperand(0).getValueType(),
5925 ST->getMemoryVT())) {
5926 return DAG.getTruncStore(Chain, N->getDebugLoc(), Value.getOperand(0),
5927 Ptr, ST->getSrcValue(),
5928 ST->getSrcValueOffset(), ST->getMemoryVT(),
5929 ST->isVolatile(), ST->isNonTemporal(),
5930 ST->getAlignment());
5933 return ReduceLoadOpStoreWidth(N);
5936 SDValue DAGCombiner::visitINSERT_VECTOR_ELT(SDNode *N) {
5937 SDValue InVec = N->getOperand(0);
5938 SDValue InVal = N->getOperand(1);
5939 SDValue EltNo = N->getOperand(2);
5941 // If the invec is a BUILD_VECTOR and if EltNo is a constant, build a new
5942 // vector with the inserted element.
5943 if (InVec.getOpcode() == ISD::BUILD_VECTOR && isa<ConstantSDNode>(EltNo)) {
5944 unsigned Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
5945 SmallVector<SDValue, 8> Ops(InVec.getNode()->op_begin(),
5946 InVec.getNode()->op_end());
5947 if (Elt < Ops.size())
5949 return DAG.getNode(ISD::BUILD_VECTOR, N->getDebugLoc(),
5950 InVec.getValueType(), &Ops[0], Ops.size());
5952 // If the invec is an UNDEF and if EltNo is a constant, create a new
5953 // BUILD_VECTOR with undef elements and the inserted element.
5954 if (!LegalOperations && InVec.getOpcode() == ISD::UNDEF &&
5955 isa<ConstantSDNode>(EltNo)) {
5956 EVT VT = InVec.getValueType();
5957 EVT EltVT = VT.getVectorElementType();
5958 unsigned NElts = VT.getVectorNumElements();
5959 SmallVector<SDValue, 8> Ops(NElts, DAG.getUNDEF(EltVT));
5961 unsigned Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
5962 if (Elt < Ops.size())
5964 return DAG.getNode(ISD::BUILD_VECTOR, N->getDebugLoc(),
5965 InVec.getValueType(), &Ops[0], Ops.size());
5970 SDValue DAGCombiner::visitEXTRACT_VECTOR_ELT(SDNode *N) {
5971 // (vextract (scalar_to_vector val, 0) -> val
5972 SDValue InVec = N->getOperand(0);
5974 if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR) {
5975 // Check if the result type doesn't match the inserted element type. A
5976 // SCALAR_TO_VECTOR may truncate the inserted element and the
5977 // EXTRACT_VECTOR_ELT may widen the extracted vector.
5978 EVT EltVT = InVec.getValueType().getVectorElementType();
5979 SDValue InOp = InVec.getOperand(0);
5980 EVT NVT = N->getValueType(0);
5981 if (InOp.getValueType() != NVT) {
5982 assert(InOp.getValueType().isInteger() && NVT.isInteger());
5983 return DAG.getSExtOrTrunc(InOp, InVec.getDebugLoc(), NVT);
5988 // Perform only after legalization to ensure build_vector / vector_shuffle
5989 // optimizations have already been done.
5990 if (!LegalOperations) return SDValue();
5992 // (vextract (v4f32 load $addr), c) -> (f32 load $addr+c*size)
5993 // (vextract (v4f32 s2v (f32 load $addr)), c) -> (f32 load $addr+c*size)
5994 // (vextract (v4f32 shuffle (load $addr), <1,u,u,u>), 0) -> (f32 load $addr)
5995 SDValue EltNo = N->getOperand(1);
5997 if (isa<ConstantSDNode>(EltNo)) {
5998 unsigned Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
5999 bool NewLoad = false;
6000 bool BCNumEltsChanged = false;
6001 EVT VT = InVec.getValueType();
6002 EVT ExtVT = VT.getVectorElementType();
6005 if (InVec.getOpcode() == ISD::BIT_CONVERT) {
6006 EVT BCVT = InVec.getOperand(0).getValueType();
6007 if (!BCVT.isVector() || ExtVT.bitsGT(BCVT.getVectorElementType()))
6009 if (VT.getVectorNumElements() != BCVT.getVectorNumElements())
6010 BCNumEltsChanged = true;
6011 InVec = InVec.getOperand(0);
6012 ExtVT = BCVT.getVectorElementType();
6016 LoadSDNode *LN0 = NULL;
6017 const ShuffleVectorSDNode *SVN = NULL;
6018 if (ISD::isNormalLoad(InVec.getNode())) {
6019 LN0 = cast<LoadSDNode>(InVec);
6020 } else if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR &&
6021 InVec.getOperand(0).getValueType() == ExtVT &&
6022 ISD::isNormalLoad(InVec.getOperand(0).getNode())) {
6023 LN0 = cast<LoadSDNode>(InVec.getOperand(0));
6024 } else if ((SVN = dyn_cast<ShuffleVectorSDNode>(InVec))) {
6025 // (vextract (vector_shuffle (load $addr), v2, <1, u, u, u>), 1)
6027 // (load $addr+1*size)
6029 // If the bit convert changed the number of elements, it is unsafe
6030 // to examine the mask.
6031 if (BCNumEltsChanged)
6034 // Select the input vector, guarding against out of range extract vector.
6035 unsigned NumElems = VT.getVectorNumElements();
6036 int Idx = (Elt > NumElems) ? -1 : SVN->getMaskElt(Elt);
6037 InVec = (Idx < (int)NumElems) ? InVec.getOperand(0) : InVec.getOperand(1);
6039 if (InVec.getOpcode() == ISD::BIT_CONVERT)
6040 InVec = InVec.getOperand(0);
6041 if (ISD::isNormalLoad(InVec.getNode())) {
6042 LN0 = cast<LoadSDNode>(InVec);
6043 Elt = (Idx < (int)NumElems) ? Idx : Idx - (int)NumElems;
6047 if (!LN0 || !LN0->hasOneUse() || LN0->isVolatile())
6050 unsigned Align = LN0->getAlignment();
6052 // Check the resultant load doesn't need a higher alignment than the
6055 TLI.getTargetData()->getABITypeAlignment(LVT.getTypeForEVT(*DAG.getContext()));
6057 if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, LVT))
6063 SDValue NewPtr = LN0->getBasePtr();
6065 unsigned PtrOff = LVT.getSizeInBits() * Elt / 8;
6066 EVT PtrType = NewPtr.getValueType();
6067 if (TLI.isBigEndian())
6068 PtrOff = VT.getSizeInBits() / 8 - PtrOff;
6069 NewPtr = DAG.getNode(ISD::ADD, N->getDebugLoc(), PtrType, NewPtr,
6070 DAG.getConstant(PtrOff, PtrType));
6073 return DAG.getLoad(LVT, N->getDebugLoc(), LN0->getChain(), NewPtr,
6074 LN0->getSrcValue(), LN0->getSrcValueOffset(),
6075 LN0->isVolatile(), LN0->isNonTemporal(), Align);
6081 SDValue DAGCombiner::visitBUILD_VECTOR(SDNode *N) {
6082 unsigned NumInScalars = N->getNumOperands();
6083 EVT VT = N->getValueType(0);
6085 // Check to see if this is a BUILD_VECTOR of a bunch of EXTRACT_VECTOR_ELT
6086 // operations. If so, and if the EXTRACT_VECTOR_ELT vector inputs come from
6087 // at most two distinct vectors, turn this into a shuffle node.
6088 SDValue VecIn1, VecIn2;
6089 for (unsigned i = 0; i != NumInScalars; ++i) {
6090 // Ignore undef inputs.
6091 if (N->getOperand(i).getOpcode() == ISD::UNDEF) continue;
6093 // If this input is something other than a EXTRACT_VECTOR_ELT with a
6094 // constant index, bail out.
6095 if (N->getOperand(i).getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
6096 !isa<ConstantSDNode>(N->getOperand(i).getOperand(1))) {
6097 VecIn1 = VecIn2 = SDValue(0, 0);
6101 // If the input vector type disagrees with the result of the build_vector,
6102 // we can't make a shuffle.
6103 SDValue ExtractedFromVec = N->getOperand(i).getOperand(0);
6104 if (ExtractedFromVec.getValueType() != VT) {
6105 VecIn1 = VecIn2 = SDValue(0, 0);
6109 // Otherwise, remember this. We allow up to two distinct input vectors.
6110 if (ExtractedFromVec == VecIn1 || ExtractedFromVec == VecIn2)
6113 if (VecIn1.getNode() == 0) {
6114 VecIn1 = ExtractedFromVec;
6115 } else if (VecIn2.getNode() == 0) {
6116 VecIn2 = ExtractedFromVec;
6119 VecIn1 = VecIn2 = SDValue(0, 0);
6124 // If everything is good, we can make a shuffle operation.
6125 if (VecIn1.getNode()) {
6126 SmallVector<int, 8> Mask;
6127 for (unsigned i = 0; i != NumInScalars; ++i) {
6128 if (N->getOperand(i).getOpcode() == ISD::UNDEF) {
6133 // If extracting from the first vector, just use the index directly.
6134 SDValue Extract = N->getOperand(i);
6135 SDValue ExtVal = Extract.getOperand(1);
6136 if (Extract.getOperand(0) == VecIn1) {
6137 unsigned ExtIndex = cast<ConstantSDNode>(ExtVal)->getZExtValue();
6138 if (ExtIndex > VT.getVectorNumElements())
6141 Mask.push_back(ExtIndex);
6145 // Otherwise, use InIdx + VecSize
6146 unsigned Idx = cast<ConstantSDNode>(ExtVal)->getZExtValue();
6147 Mask.push_back(Idx+NumInScalars);
6150 // Add count and size info.
6151 if (!isTypeLegal(VT))
6154 // Return the new VECTOR_SHUFFLE node.
6157 Ops[1] = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(VT);
6158 return DAG.getVectorShuffle(VT, N->getDebugLoc(), Ops[0], Ops[1], &Mask[0]);
6164 SDValue DAGCombiner::visitCONCAT_VECTORS(SDNode *N) {
6165 // TODO: Check to see if this is a CONCAT_VECTORS of a bunch of
6166 // EXTRACT_SUBVECTOR operations. If so, and if the EXTRACT_SUBVECTOR vector
6167 // inputs come from at most two distinct vectors, turn this into a shuffle
6170 // If we only have one input vector, we don't need to do any concatenation.
6171 if (N->getNumOperands() == 1)
6172 return N->getOperand(0);
6177 SDValue DAGCombiner::visitVECTOR_SHUFFLE(SDNode *N) {
6180 EVT VT = N->getValueType(0);
6181 unsigned NumElts = VT.getVectorNumElements();
6183 SDValue N0 = N->getOperand(0);
6185 assert(N0.getValueType().getVectorNumElements() == NumElts &&
6186 "Vector shuffle must be normalized in DAG");
6188 // FIXME: implement canonicalizations from DAG.getVectorShuffle()
6190 // If it is a splat, check if the argument vector is a build_vector with
6191 // all scalar elements the same.
6192 if (cast<ShuffleVectorSDNode>(N)->isSplat()) {
6193 SDNode *V = N0.getNode();
6196 // If this is a bit convert that changes the element type of the vector but
6197 // not the number of vector elements, look through it. Be careful not to
6198 // look though conversions that change things like v4f32 to v2f64.
6199 if (V->getOpcode() == ISD::BIT_CONVERT) {
6200 SDValue ConvInput = V->getOperand(0);
6201 if (ConvInput.getValueType().isVector() &&
6202 ConvInput.getValueType().getVectorNumElements() == NumElts)
6203 V = ConvInput.getNode();
6206 if (V->getOpcode() == ISD::BUILD_VECTOR) {
6207 unsigned NumElems = V->getNumOperands();
6208 unsigned BaseIdx = cast<ShuffleVectorSDNode>(N)->getSplatIndex();
6209 if (NumElems > BaseIdx) {
6211 bool AllSame = true;
6212 for (unsigned i = 0; i != NumElems; ++i) {
6213 if (V->getOperand(i).getOpcode() != ISD::UNDEF) {
6214 Base = V->getOperand(i);
6218 // Splat of <u, u, u, u>, return <u, u, u, u>
6219 if (!Base.getNode())
6221 for (unsigned i = 0; i != NumElems; ++i) {
6222 if (V->getOperand(i) != Base) {
6227 // Splat of <x, x, x, x>, return <x, x, x, x>
6236 /// XformToShuffleWithZero - Returns a vector_shuffle if it able to transform
6237 /// an AND to a vector_shuffle with the destination vector and a zero vector.
6238 /// e.g. AND V, <0xffffffff, 0, 0xffffffff, 0>. ==>
6239 /// vector_shuffle V, Zero, <0, 4, 2, 4>
6240 SDValue DAGCombiner::XformToShuffleWithZero(SDNode *N) {
6241 EVT VT = N->getValueType(0);
6242 DebugLoc dl = N->getDebugLoc();
6243 SDValue LHS = N->getOperand(0);
6244 SDValue RHS = N->getOperand(1);
6245 if (N->getOpcode() == ISD::AND) {
6246 if (RHS.getOpcode() == ISD::BIT_CONVERT)
6247 RHS = RHS.getOperand(0);
6248 if (RHS.getOpcode() == ISD::BUILD_VECTOR) {
6249 SmallVector<int, 8> Indices;
6250 unsigned NumElts = RHS.getNumOperands();
6251 for (unsigned i = 0; i != NumElts; ++i) {
6252 SDValue Elt = RHS.getOperand(i);
6253 if (!isa<ConstantSDNode>(Elt))
6255 else if (cast<ConstantSDNode>(Elt)->isAllOnesValue())
6256 Indices.push_back(i);
6257 else if (cast<ConstantSDNode>(Elt)->isNullValue())
6258 Indices.push_back(NumElts);
6263 // Let's see if the target supports this vector_shuffle.
6264 EVT RVT = RHS.getValueType();
6265 if (!TLI.isVectorClearMaskLegal(Indices, RVT))
6268 // Return the new VECTOR_SHUFFLE node.
6269 EVT EltVT = RVT.getVectorElementType();
6270 SmallVector<SDValue,8> ZeroOps(RVT.getVectorNumElements(),
6271 DAG.getConstant(0, EltVT));
6272 SDValue Zero = DAG.getNode(ISD::BUILD_VECTOR, N->getDebugLoc(),
6273 RVT, &ZeroOps[0], ZeroOps.size());
6274 LHS = DAG.getNode(ISD::BIT_CONVERT, dl, RVT, LHS);
6275 SDValue Shuf = DAG.getVectorShuffle(RVT, dl, LHS, Zero, &Indices[0]);
6276 return DAG.getNode(ISD::BIT_CONVERT, dl, VT, Shuf);
6283 /// SimplifyVBinOp - Visit a binary vector operation, like ADD.
6284 SDValue DAGCombiner::SimplifyVBinOp(SDNode *N) {
6285 // After legalize, the target may be depending on adds and other
6286 // binary ops to provide legal ways to construct constants or other
6287 // things. Simplifying them may result in a loss of legality.
6288 if (LegalOperations) return SDValue();
6290 EVT VT = N->getValueType(0);
6291 assert(VT.isVector() && "SimplifyVBinOp only works on vectors!");
6293 EVT EltType = VT.getVectorElementType();
6294 SDValue LHS = N->getOperand(0);
6295 SDValue RHS = N->getOperand(1);
6296 SDValue Shuffle = XformToShuffleWithZero(N);
6297 if (Shuffle.getNode()) return Shuffle;
6299 // If the LHS and RHS are BUILD_VECTOR nodes, see if we can constant fold
6301 if (LHS.getOpcode() == ISD::BUILD_VECTOR &&
6302 RHS.getOpcode() == ISD::BUILD_VECTOR) {
6303 SmallVector<SDValue, 8> Ops;
6304 for (unsigned i = 0, e = LHS.getNumOperands(); i != e; ++i) {
6305 SDValue LHSOp = LHS.getOperand(i);
6306 SDValue RHSOp = RHS.getOperand(i);
6307 // If these two elements can't be folded, bail out.
6308 if ((LHSOp.getOpcode() != ISD::UNDEF &&
6309 LHSOp.getOpcode() != ISD::Constant &&
6310 LHSOp.getOpcode() != ISD::ConstantFP) ||
6311 (RHSOp.getOpcode() != ISD::UNDEF &&
6312 RHSOp.getOpcode() != ISD::Constant &&
6313 RHSOp.getOpcode() != ISD::ConstantFP))
6316 // Can't fold divide by zero.
6317 if (N->getOpcode() == ISD::SDIV || N->getOpcode() == ISD::UDIV ||
6318 N->getOpcode() == ISD::FDIV) {
6319 if ((RHSOp.getOpcode() == ISD::Constant &&
6320 cast<ConstantSDNode>(RHSOp.getNode())->isNullValue()) ||
6321 (RHSOp.getOpcode() == ISD::ConstantFP &&
6322 cast<ConstantFPSDNode>(RHSOp.getNode())->getValueAPF().isZero()))
6326 Ops.push_back(DAG.getNode(N->getOpcode(), LHS.getDebugLoc(),
6327 EltType, LHSOp, RHSOp));
6328 AddToWorkList(Ops.back().getNode());
6329 assert((Ops.back().getOpcode() == ISD::UNDEF ||
6330 Ops.back().getOpcode() == ISD::Constant ||
6331 Ops.back().getOpcode() == ISD::ConstantFP) &&
6332 "Scalar binop didn't fold!");
6335 if (Ops.size() == LHS.getNumOperands()) {
6336 EVT VT = LHS.getValueType();
6337 return DAG.getNode(ISD::BUILD_VECTOR, N->getDebugLoc(), VT,
6338 &Ops[0], Ops.size());
6345 SDValue DAGCombiner::SimplifySelect(DebugLoc DL, SDValue N0,
6346 SDValue N1, SDValue N2){
6347 assert(N0.getOpcode() ==ISD::SETCC && "First argument must be a SetCC node!");
6349 SDValue SCC = SimplifySelectCC(DL, N0.getOperand(0), N0.getOperand(1), N1, N2,
6350 cast<CondCodeSDNode>(N0.getOperand(2))->get());
6352 // If we got a simplified select_cc node back from SimplifySelectCC, then
6353 // break it down into a new SETCC node, and a new SELECT node, and then return
6354 // the SELECT node, since we were called with a SELECT node.
6355 if (SCC.getNode()) {
6356 // Check to see if we got a select_cc back (to turn into setcc/select).
6357 // Otherwise, just return whatever node we got back, like fabs.
6358 if (SCC.getOpcode() == ISD::SELECT_CC) {
6359 SDValue SETCC = DAG.getNode(ISD::SETCC, N0.getDebugLoc(),
6361 SCC.getOperand(0), SCC.getOperand(1),
6363 AddToWorkList(SETCC.getNode());
6364 return DAG.getNode(ISD::SELECT, SCC.getDebugLoc(), SCC.getValueType(),
6365 SCC.getOperand(2), SCC.getOperand(3), SETCC);
6373 /// SimplifySelectOps - Given a SELECT or a SELECT_CC node, where LHS and RHS
6374 /// are the two values being selected between, see if we can simplify the
6375 /// select. Callers of this should assume that TheSelect is deleted if this
6376 /// returns true. As such, they should return the appropriate thing (e.g. the
6377 /// node) back to the top-level of the DAG combiner loop to avoid it being
6379 bool DAGCombiner::SimplifySelectOps(SDNode *TheSelect, SDValue LHS,
6382 // If this is a select from two identical things, try to pull the operation
6383 // through the select.
6384 if (LHS.getOpcode() == RHS.getOpcode() && LHS.hasOneUse() && RHS.hasOneUse()){
6385 // If this is a load and the token chain is identical, replace the select
6386 // of two loads with a load through a select of the address to load from.
6387 // This triggers in things like "select bool X, 10.0, 123.0" after the FP
6388 // constants have been dropped into the constant pool.
6389 if (LHS.getOpcode() == ISD::LOAD &&
6390 // Do not let this transformation reduce the number of volatile loads.
6391 !cast<LoadSDNode>(LHS)->isVolatile() &&
6392 !cast<LoadSDNode>(RHS)->isVolatile() &&
6393 // Token chains must be identical.
6394 LHS.getOperand(0) == RHS.getOperand(0)) {
6395 LoadSDNode *LLD = cast<LoadSDNode>(LHS);
6396 LoadSDNode *RLD = cast<LoadSDNode>(RHS);
6398 // If this is an EXTLOAD, the VT's must match.
6399 if (LLD->getMemoryVT() == RLD->getMemoryVT()) {
6400 // FIXME: this discards src value information. This is
6401 // over-conservative. It would be beneficial to be able to remember
6402 // both potential memory locations. Since we are discarding
6403 // src value info, don't do the transformation if the memory
6404 // locations are not in the default address space.
6405 unsigned LLDAddrSpace = 0, RLDAddrSpace = 0;
6406 if (const Value *LLDVal = LLD->getMemOperand()->getValue()) {
6407 if (const PointerType *PT = dyn_cast<PointerType>(LLDVal->getType()))
6408 LLDAddrSpace = PT->getAddressSpace();
6410 if (const Value *RLDVal = RLD->getMemOperand()->getValue()) {
6411 if (const PointerType *PT = dyn_cast<PointerType>(RLDVal->getType()))
6412 RLDAddrSpace = PT->getAddressSpace();
6415 if (LLDAddrSpace == 0 && RLDAddrSpace == 0) {
6416 if (TheSelect->getOpcode() == ISD::SELECT) {
6417 // Check that the condition doesn't reach either load. If so, folding
6418 // this will induce a cycle into the DAG.
6419 if ((!LLD->hasAnyUseOfValue(1) ||
6420 !LLD->isPredecessorOf(TheSelect->getOperand(0).getNode())) &&
6421 (!RLD->hasAnyUseOfValue(1) ||
6422 !RLD->isPredecessorOf(TheSelect->getOperand(0).getNode()))) {
6423 Addr = DAG.getNode(ISD::SELECT, TheSelect->getDebugLoc(),
6424 LLD->getBasePtr().getValueType(),
6425 TheSelect->getOperand(0), LLD->getBasePtr(),
6429 // Check that the condition doesn't reach either load. If so, folding
6430 // this will induce a cycle into the DAG.
6431 if ((!LLD->hasAnyUseOfValue(1) ||
6432 (!LLD->isPredecessorOf(TheSelect->getOperand(0).getNode()) &&
6433 !LLD->isPredecessorOf(TheSelect->getOperand(1).getNode()))) &&
6434 (!RLD->hasAnyUseOfValue(1) ||
6435 (!RLD->isPredecessorOf(TheSelect->getOperand(0).getNode()) &&
6436 !RLD->isPredecessorOf(TheSelect->getOperand(1).getNode())))) {
6437 Addr = DAG.getNode(ISD::SELECT_CC, TheSelect->getDebugLoc(),
6438 LLD->getBasePtr().getValueType(),
6439 TheSelect->getOperand(0),
6440 TheSelect->getOperand(1),
6441 LLD->getBasePtr(), RLD->getBasePtr(),
6442 TheSelect->getOperand(4));
6447 if (Addr.getNode()) {
6449 if (LLD->getExtensionType() == ISD::NON_EXTLOAD) {
6450 Load = DAG.getLoad(TheSelect->getValueType(0),
6451 TheSelect->getDebugLoc(),
6455 LLD->isNonTemporal(),
6456 LLD->getAlignment());
6458 Load = DAG.getExtLoad(LLD->getExtensionType(),
6459 TheSelect->getDebugLoc(),
6460 TheSelect->getValueType(0),
6461 LLD->getChain(), Addr, 0, 0,
6464 LLD->isNonTemporal(),
6465 LLD->getAlignment());
6468 // Users of the select now use the result of the load.
6469 CombineTo(TheSelect, Load);
6471 // Users of the old loads now use the new load's chain. We know the
6472 // old-load value is dead now.
6473 CombineTo(LHS.getNode(), Load.getValue(0), Load.getValue(1));
6474 CombineTo(RHS.getNode(), Load.getValue(0), Load.getValue(1));
6484 /// SimplifySelectCC - Simplify an expression of the form (N0 cond N1) ? N2 : N3
6485 /// where 'cond' is the comparison specified by CC.
6486 SDValue DAGCombiner::SimplifySelectCC(DebugLoc DL, SDValue N0, SDValue N1,
6487 SDValue N2, SDValue N3,
6488 ISD::CondCode CC, bool NotExtCompare) {
6489 // (x ? y : y) -> y.
6490 if (N2 == N3) return N2;
6492 EVT VT = N2.getValueType();
6493 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
6494 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2.getNode());
6495 ConstantSDNode *N3C = dyn_cast<ConstantSDNode>(N3.getNode());
6497 // Determine if the condition we're dealing with is constant
6498 SDValue SCC = SimplifySetCC(TLI.getSetCCResultType(N0.getValueType()),
6499 N0, N1, CC, DL, false);
6500 if (SCC.getNode()) AddToWorkList(SCC.getNode());
6501 ConstantSDNode *SCCC = dyn_cast_or_null<ConstantSDNode>(SCC.getNode());
6503 // fold select_cc true, x, y -> x
6504 if (SCCC && !SCCC->isNullValue())
6506 // fold select_cc false, x, y -> y
6507 if (SCCC && SCCC->isNullValue())
6510 // Check to see if we can simplify the select into an fabs node
6511 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N1)) {
6512 // Allow either -0.0 or 0.0
6513 if (CFP->getValueAPF().isZero()) {
6514 // select (setg[te] X, +/-0.0), X, fneg(X) -> fabs
6515 if ((CC == ISD::SETGE || CC == ISD::SETGT) &&
6516 N0 == N2 && N3.getOpcode() == ISD::FNEG &&
6517 N2 == N3.getOperand(0))
6518 return DAG.getNode(ISD::FABS, DL, VT, N0);
6520 // select (setl[te] X, +/-0.0), fneg(X), X -> fabs
6521 if ((CC == ISD::SETLT || CC == ISD::SETLE) &&
6522 N0 == N3 && N2.getOpcode() == ISD::FNEG &&
6523 N2.getOperand(0) == N3)
6524 return DAG.getNode(ISD::FABS, DL, VT, N3);
6528 // Turn "(a cond b) ? 1.0f : 2.0f" into "load (tmp + ((a cond b) ? 0 : 4)"
6529 // where "tmp" is a constant pool entry containing an array with 1.0 and 2.0
6530 // in it. This is a win when the constant is not otherwise available because
6531 // it replaces two constant pool loads with one. We only do this if the FP
6532 // type is known to be legal, because if it isn't, then we are before legalize
6533 // types an we want the other legalization to happen first (e.g. to avoid
6534 // messing with soft float) and if the ConstantFP is not legal, because if
6535 // it is legal, we may not need to store the FP constant in a constant pool.
6536 if (ConstantFPSDNode *TV = dyn_cast<ConstantFPSDNode>(N2))
6537 if (ConstantFPSDNode *FV = dyn_cast<ConstantFPSDNode>(N3)) {
6538 if (TLI.isTypeLegal(N2.getValueType()) &&
6539 (TLI.getOperationAction(ISD::ConstantFP, N2.getValueType()) !=
6540 TargetLowering::Legal) &&
6541 // If both constants have multiple uses, then we won't need to do an
6542 // extra load, they are likely around in registers for other users.
6543 (TV->hasOneUse() || FV->hasOneUse())) {
6544 Constant *Elts[] = {
6545 const_cast<ConstantFP*>(FV->getConstantFPValue()),
6546 const_cast<ConstantFP*>(TV->getConstantFPValue())
6548 const Type *FPTy = Elts[0]->getType();
6549 const TargetData &TD = *TLI.getTargetData();
6551 // Create a ConstantArray of the two constants.
6552 Constant *CA = ConstantArray::get(ArrayType::get(FPTy, 2), Elts, 2);
6553 SDValue CPIdx = DAG.getConstantPool(CA, TLI.getPointerTy(),
6554 TD.getPrefTypeAlignment(FPTy));
6555 unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
6557 // Get the offsets to the 0 and 1 element of the array so that we can
6558 // select between them.
6559 SDValue Zero = DAG.getIntPtrConstant(0);
6560 unsigned EltSize = (unsigned)TD.getTypeAllocSize(Elts[0]->getType());
6561 SDValue One = DAG.getIntPtrConstant(EltSize);
6563 SDValue Cond = DAG.getSetCC(DL,
6564 TLI.getSetCCResultType(N0.getValueType()),
6566 SDValue CstOffset = DAG.getNode(ISD::SELECT, DL, Zero.getValueType(),
6568 CPIdx = DAG.getNode(ISD::ADD, DL, TLI.getPointerTy(), CPIdx,
6570 return DAG.getLoad(TV->getValueType(0), DL, DAG.getEntryNode(), CPIdx,
6571 PseudoSourceValue::getConstantPool(), 0, false,
6577 // Check to see if we can perform the "gzip trick", transforming
6578 // (select_cc setlt X, 0, A, 0) -> (and (sra X, (sub size(X), 1), A)
6579 if (N1C && N3C && N3C->isNullValue() && CC == ISD::SETLT &&
6580 N0.getValueType().isInteger() &&
6581 N2.getValueType().isInteger() &&
6582 (N1C->isNullValue() || // (a < 0) ? b : 0
6583 (N1C->getAPIntValue() == 1 && N0 == N2))) { // (a < 1) ? a : 0
6584 EVT XType = N0.getValueType();
6585 EVT AType = N2.getValueType();
6586 if (XType.bitsGE(AType)) {
6587 // and (sra X, size(X)-1, A) -> "and (srl X, C2), A" iff A is a
6588 // single-bit constant.
6589 if (N2C && ((N2C->getAPIntValue() & (N2C->getAPIntValue()-1)) == 0)) {
6590 unsigned ShCtV = N2C->getAPIntValue().logBase2();
6591 ShCtV = XType.getSizeInBits()-ShCtV-1;
6592 SDValue ShCt = DAG.getConstant(ShCtV, getShiftAmountTy());
6593 SDValue Shift = DAG.getNode(ISD::SRL, N0.getDebugLoc(),
6595 AddToWorkList(Shift.getNode());
6597 if (XType.bitsGT(AType)) {
6598 Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift);
6599 AddToWorkList(Shift.getNode());
6602 return DAG.getNode(ISD::AND, DL, AType, Shift, N2);
6605 SDValue Shift = DAG.getNode(ISD::SRA, N0.getDebugLoc(),
6607 DAG.getConstant(XType.getSizeInBits()-1,
6608 getShiftAmountTy()));
6609 AddToWorkList(Shift.getNode());
6611 if (XType.bitsGT(AType)) {
6612 Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift);
6613 AddToWorkList(Shift.getNode());
6616 return DAG.getNode(ISD::AND, DL, AType, Shift, N2);
6620 // fold select C, 16, 0 -> shl C, 4
6621 if (N2C && N3C && N3C->isNullValue() && N2C->getAPIntValue().isPowerOf2() &&
6622 TLI.getBooleanContents() == TargetLowering::ZeroOrOneBooleanContent) {
6624 // If the caller doesn't want us to simplify this into a zext of a compare,
6626 if (NotExtCompare && N2C->getAPIntValue() == 1)
6629 // Get a SetCC of the condition
6630 // FIXME: Should probably make sure that setcc is legal if we ever have a
6631 // target where it isn't.
6633 // cast from setcc result type to select result type
6635 SCC = DAG.getSetCC(DL, TLI.getSetCCResultType(N0.getValueType()),
6637 if (N2.getValueType().bitsLT(SCC.getValueType()))
6638 Temp = DAG.getZeroExtendInReg(SCC, N2.getDebugLoc(), N2.getValueType());
6640 Temp = DAG.getNode(ISD::ZERO_EXTEND, N2.getDebugLoc(),
6641 N2.getValueType(), SCC);
6643 SCC = DAG.getSetCC(N0.getDebugLoc(), MVT::i1, N0, N1, CC);
6644 Temp = DAG.getNode(ISD::ZERO_EXTEND, N2.getDebugLoc(),
6645 N2.getValueType(), SCC);
6648 AddToWorkList(SCC.getNode());
6649 AddToWorkList(Temp.getNode());
6651 if (N2C->getAPIntValue() == 1)
6654 // shl setcc result by log2 n2c
6655 return DAG.getNode(ISD::SHL, DL, N2.getValueType(), Temp,
6656 DAG.getConstant(N2C->getAPIntValue().logBase2(),
6657 getShiftAmountTy()));
6660 // Check to see if this is the equivalent of setcc
6661 // FIXME: Turn all of these into setcc if setcc if setcc is legal
6662 // otherwise, go ahead with the folds.
6663 if (0 && N3C && N3C->isNullValue() && N2C && (N2C->getAPIntValue() == 1ULL)) {
6664 EVT XType = N0.getValueType();
6665 if (!LegalOperations ||
6666 TLI.isOperationLegal(ISD::SETCC, TLI.getSetCCResultType(XType))) {
6667 SDValue Res = DAG.getSetCC(DL, TLI.getSetCCResultType(XType), N0, N1, CC);
6668 if (Res.getValueType() != VT)
6669 Res = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, Res);
6673 // fold (seteq X, 0) -> (srl (ctlz X, log2(size(X))))
6674 if (N1C && N1C->isNullValue() && CC == ISD::SETEQ &&
6675 (!LegalOperations ||
6676 TLI.isOperationLegal(ISD::CTLZ, XType))) {
6677 SDValue Ctlz = DAG.getNode(ISD::CTLZ, N0.getDebugLoc(), XType, N0);
6678 return DAG.getNode(ISD::SRL, DL, XType, Ctlz,
6679 DAG.getConstant(Log2_32(XType.getSizeInBits()),
6680 getShiftAmountTy()));
6682 // fold (setgt X, 0) -> (srl (and (-X, ~X), size(X)-1))
6683 if (N1C && N1C->isNullValue() && CC == ISD::SETGT) {
6684 SDValue NegN0 = DAG.getNode(ISD::SUB, N0.getDebugLoc(),
6685 XType, DAG.getConstant(0, XType), N0);
6686 SDValue NotN0 = DAG.getNOT(N0.getDebugLoc(), N0, XType);
6687 return DAG.getNode(ISD::SRL, DL, XType,
6688 DAG.getNode(ISD::AND, DL, XType, NegN0, NotN0),
6689 DAG.getConstant(XType.getSizeInBits()-1,
6690 getShiftAmountTy()));
6692 // fold (setgt X, -1) -> (xor (srl (X, size(X)-1), 1))
6693 if (N1C && N1C->isAllOnesValue() && CC == ISD::SETGT) {
6694 SDValue Sign = DAG.getNode(ISD::SRL, N0.getDebugLoc(), XType, N0,
6695 DAG.getConstant(XType.getSizeInBits()-1,
6696 getShiftAmountTy()));
6697 return DAG.getNode(ISD::XOR, DL, XType, Sign, DAG.getConstant(1, XType));
6701 // Check to see if this is an integer abs. select_cc setl[te] X, 0, -X, X ->
6702 // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
6703 if (N1C && N1C->isNullValue() && (CC == ISD::SETLT || CC == ISD::SETLE) &&
6704 N0 == N3 && N2.getOpcode() == ISD::SUB && N0 == N2.getOperand(1) &&
6705 N2.getOperand(0) == N1 && N0.getValueType().isInteger()) {
6706 EVT XType = N0.getValueType();
6707 SDValue Shift = DAG.getNode(ISD::SRA, N0.getDebugLoc(), XType, N0,
6708 DAG.getConstant(XType.getSizeInBits()-1,
6709 getShiftAmountTy()));
6710 SDValue Add = DAG.getNode(ISD::ADD, N0.getDebugLoc(), XType,
6712 AddToWorkList(Shift.getNode());
6713 AddToWorkList(Add.getNode());
6714 return DAG.getNode(ISD::XOR, DL, XType, Add, Shift);
6716 // Check to see if this is an integer abs. select_cc setgt X, -1, X, -X ->
6717 // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
6718 if (N1C && N1C->isAllOnesValue() && CC == ISD::SETGT &&
6719 N0 == N2 && N3.getOpcode() == ISD::SUB && N0 == N3.getOperand(1)) {
6720 if (ConstantSDNode *SubC = dyn_cast<ConstantSDNode>(N3.getOperand(0))) {
6721 EVT XType = N0.getValueType();
6722 if (SubC->isNullValue() && XType.isInteger()) {
6723 SDValue Shift = DAG.getNode(ISD::SRA, N0.getDebugLoc(), XType,
6725 DAG.getConstant(XType.getSizeInBits()-1,
6726 getShiftAmountTy()));
6727 SDValue Add = DAG.getNode(ISD::ADD, N0.getDebugLoc(),
6729 AddToWorkList(Shift.getNode());
6730 AddToWorkList(Add.getNode());
6731 return DAG.getNode(ISD::XOR, DL, XType, Add, Shift);
6739 /// SimplifySetCC - This is a stub for TargetLowering::SimplifySetCC.
6740 SDValue DAGCombiner::SimplifySetCC(EVT VT, SDValue N0,
6741 SDValue N1, ISD::CondCode Cond,
6742 DebugLoc DL, bool foldBooleans) {
6743 TargetLowering::DAGCombinerInfo
6744 DagCombineInfo(DAG, !LegalTypes, !LegalOperations, false, this);
6745 return TLI.SimplifySetCC(VT, N0, N1, Cond, foldBooleans, DagCombineInfo, DL);
6748 /// BuildSDIVSequence - Given an ISD::SDIV node expressing a divide by constant,
6749 /// return a DAG expression to select that will generate the same value by
6750 /// multiplying by a magic number. See:
6751 /// <http://the.wall.riscom.net/books/proc/ppc/cwg/code2.html>
6752 SDValue DAGCombiner::BuildSDIV(SDNode *N) {
6753 std::vector<SDNode*> Built;
6754 SDValue S = TLI.BuildSDIV(N, DAG, &Built);
6756 for (std::vector<SDNode*>::iterator ii = Built.begin(), ee = Built.end();
6762 /// BuildUDIVSequence - Given an ISD::UDIV node expressing a divide by constant,
6763 /// return a DAG expression to select that will generate the same value by
6764 /// multiplying by a magic number. See:
6765 /// <http://the.wall.riscom.net/books/proc/ppc/cwg/code2.html>
6766 SDValue DAGCombiner::BuildUDIV(SDNode *N) {
6767 std::vector<SDNode*> Built;
6768 SDValue S = TLI.BuildUDIV(N, DAG, &Built);
6770 for (std::vector<SDNode*>::iterator ii = Built.begin(), ee = Built.end();
6776 /// FindBaseOffset - Return true if base is a frame index, which is known not
6777 // to alias with anything but itself. Provides base object and offset as results.
6778 static bool FindBaseOffset(SDValue Ptr, SDValue &Base, int64_t &Offset,
6779 const GlobalValue *&GV, void *&CV) {
6780 // Assume it is a primitive operation.
6781 Base = Ptr; Offset = 0; GV = 0; CV = 0;
6783 // If it's an adding a simple constant then integrate the offset.
6784 if (Base.getOpcode() == ISD::ADD) {
6785 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Base.getOperand(1))) {
6786 Base = Base.getOperand(0);
6787 Offset += C->getZExtValue();
6791 // Return the underlying GlobalValue, and update the Offset. Return false
6792 // for GlobalAddressSDNode since the same GlobalAddress may be represented
6793 // by multiple nodes with different offsets.
6794 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Base)) {
6795 GV = G->getGlobal();
6796 Offset += G->getOffset();
6800 // Return the underlying Constant value, and update the Offset. Return false
6801 // for ConstantSDNodes since the same constant pool entry may be represented
6802 // by multiple nodes with different offsets.
6803 if (ConstantPoolSDNode *C = dyn_cast<ConstantPoolSDNode>(Base)) {
6804 CV = C->isMachineConstantPoolEntry() ? (void *)C->getMachineCPVal()
6805 : (void *)C->getConstVal();
6806 Offset += C->getOffset();
6809 // If it's any of the following then it can't alias with anything but itself.
6810 return isa<FrameIndexSDNode>(Base);
6813 /// isAlias - Return true if there is any possibility that the two addresses
6815 bool DAGCombiner::isAlias(SDValue Ptr1, int64_t Size1,
6816 const Value *SrcValue1, int SrcValueOffset1,
6817 unsigned SrcValueAlign1,
6818 SDValue Ptr2, int64_t Size2,
6819 const Value *SrcValue2, int SrcValueOffset2,
6820 unsigned SrcValueAlign2) const {
6821 // If they are the same then they must be aliases.
6822 if (Ptr1 == Ptr2) return true;
6824 // Gather base node and offset information.
6825 SDValue Base1, Base2;
6826 int64_t Offset1, Offset2;
6827 const GlobalValue *GV1, *GV2;
6829 bool isFrameIndex1 = FindBaseOffset(Ptr1, Base1, Offset1, GV1, CV1);
6830 bool isFrameIndex2 = FindBaseOffset(Ptr2, Base2, Offset2, GV2, CV2);
6832 // If they have a same base address then check to see if they overlap.
6833 if (Base1 == Base2 || (GV1 && (GV1 == GV2)) || (CV1 && (CV1 == CV2)))
6834 return !((Offset1 + Size1) <= Offset2 || (Offset2 + Size2) <= Offset1);
6836 // If we know what the bases are, and they aren't identical, then we know they
6838 if ((isFrameIndex1 || CV1 || GV1) && (isFrameIndex2 || CV2 || GV2))
6841 // If we know required SrcValue1 and SrcValue2 have relatively large alignment
6842 // compared to the size and offset of the access, we may be able to prove they
6843 // do not alias. This check is conservative for now to catch cases created by
6844 // splitting vector types.
6845 if ((SrcValueAlign1 == SrcValueAlign2) &&
6846 (SrcValueOffset1 != SrcValueOffset2) &&
6847 (Size1 == Size2) && (SrcValueAlign1 > Size1)) {
6848 int64_t OffAlign1 = SrcValueOffset1 % SrcValueAlign1;
6849 int64_t OffAlign2 = SrcValueOffset2 % SrcValueAlign1;
6851 // There is no overlap between these relatively aligned accesses of similar
6852 // size, return no alias.
6853 if ((OffAlign1 + Size1) <= OffAlign2 || (OffAlign2 + Size2) <= OffAlign1)
6857 if (CombinerGlobalAA) {
6858 // Use alias analysis information.
6859 int64_t MinOffset = std::min(SrcValueOffset1, SrcValueOffset2);
6860 int64_t Overlap1 = Size1 + SrcValueOffset1 - MinOffset;
6861 int64_t Overlap2 = Size2 + SrcValueOffset2 - MinOffset;
6862 AliasAnalysis::AliasResult AAResult =
6863 AA.alias(SrcValue1, Overlap1, SrcValue2, Overlap2);
6864 if (AAResult == AliasAnalysis::NoAlias)
6868 // Otherwise we have to assume they alias.
6872 /// FindAliasInfo - Extracts the relevant alias information from the memory
6873 /// node. Returns true if the operand was a load.
6874 bool DAGCombiner::FindAliasInfo(SDNode *N,
6875 SDValue &Ptr, int64_t &Size,
6876 const Value *&SrcValue,
6877 int &SrcValueOffset,
6878 unsigned &SrcValueAlign) const {
6879 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
6880 Ptr = LD->getBasePtr();
6881 Size = LD->getMemoryVT().getSizeInBits() >> 3;
6882 SrcValue = LD->getSrcValue();
6883 SrcValueOffset = LD->getSrcValueOffset();
6884 SrcValueAlign = LD->getOriginalAlignment();
6886 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
6887 Ptr = ST->getBasePtr();
6888 Size = ST->getMemoryVT().getSizeInBits() >> 3;
6889 SrcValue = ST->getSrcValue();
6890 SrcValueOffset = ST->getSrcValueOffset();
6891 SrcValueAlign = ST->getOriginalAlignment();
6893 llvm_unreachable("FindAliasInfo expected a memory operand");
6899 /// GatherAllAliases - Walk up chain skipping non-aliasing memory nodes,
6900 /// looking for aliasing nodes and adding them to the Aliases vector.
6901 void DAGCombiner::GatherAllAliases(SDNode *N, SDValue OriginalChain,
6902 SmallVector<SDValue, 8> &Aliases) {
6903 SmallVector<SDValue, 8> Chains; // List of chains to visit.
6904 SmallPtrSet<SDNode *, 16> Visited; // Visited node set.
6906 // Get alias information for node.
6909 const Value *SrcValue;
6911 unsigned SrcValueAlign;
6912 bool IsLoad = FindAliasInfo(N, Ptr, Size, SrcValue, SrcValueOffset,
6916 Chains.push_back(OriginalChain);
6919 // Look at each chain and determine if it is an alias. If so, add it to the
6920 // aliases list. If not, then continue up the chain looking for the next
6922 while (!Chains.empty()) {
6923 SDValue Chain = Chains.back();
6926 // For TokenFactor nodes, look at each operand and only continue up the
6927 // chain until we find two aliases. If we've seen two aliases, assume we'll
6928 // find more and revert to original chain since the xform is unlikely to be
6931 // FIXME: The depth check could be made to return the last non-aliasing
6932 // chain we found before we hit a tokenfactor rather than the original
6934 if (Depth > 6 || Aliases.size() == 2) {
6936 Aliases.push_back(OriginalChain);
6940 // Don't bother if we've been before.
6941 if (!Visited.insert(Chain.getNode()))
6944 switch (Chain.getOpcode()) {
6945 case ISD::EntryToken:
6946 // Entry token is ideal chain operand, but handled in FindBetterChain.
6951 // Get alias information for Chain.
6954 const Value *OpSrcValue;
6955 int OpSrcValueOffset;
6956 unsigned OpSrcValueAlign;
6957 bool IsOpLoad = FindAliasInfo(Chain.getNode(), OpPtr, OpSize,
6958 OpSrcValue, OpSrcValueOffset,
6961 // If chain is alias then stop here.
6962 if (!(IsLoad && IsOpLoad) &&
6963 isAlias(Ptr, Size, SrcValue, SrcValueOffset, SrcValueAlign,
6964 OpPtr, OpSize, OpSrcValue, OpSrcValueOffset,
6966 Aliases.push_back(Chain);
6968 // Look further up the chain.
6969 Chains.push_back(Chain.getOperand(0));
6975 case ISD::TokenFactor:
6976 // We have to check each of the operands of the token factor for "small"
6977 // token factors, so we queue them up. Adding the operands to the queue
6978 // (stack) in reverse order maintains the original order and increases the
6979 // likelihood that getNode will find a matching token factor (CSE.)
6980 if (Chain.getNumOperands() > 16) {
6981 Aliases.push_back(Chain);
6984 for (unsigned n = Chain.getNumOperands(); n;)
6985 Chains.push_back(Chain.getOperand(--n));
6990 // For all other instructions we will just have to take what we can get.
6991 Aliases.push_back(Chain);
6997 /// FindBetterChain - Walk up chain skipping non-aliasing memory nodes, looking
6998 /// for a better chain (aliasing node.)
6999 SDValue DAGCombiner::FindBetterChain(SDNode *N, SDValue OldChain) {
7000 SmallVector<SDValue, 8> Aliases; // Ops for replacing token factor.
7002 // Accumulate all the aliases to this node.
7003 GatherAllAliases(N, OldChain, Aliases);
7005 if (Aliases.size() == 0) {
7006 // If no operands then chain to entry token.
7007 return DAG.getEntryNode();
7008 } else if (Aliases.size() == 1) {
7009 // If a single operand then chain to it. We don't need to revisit it.
7013 // Construct a custom tailored token factor.
7014 return DAG.getNode(ISD::TokenFactor, N->getDebugLoc(), MVT::Other,
7015 &Aliases[0], Aliases.size());
7018 // SelectionDAG::Combine - This is the entry point for the file.
7020 void SelectionDAG::Combine(CombineLevel Level, AliasAnalysis &AA,
7021 CodeGenOpt::Level OptLevel) {
7022 /// run - This is the main entry point to this class.
7024 DAGCombiner(*this, AA, OptLevel).Run(Level);