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/TargetLowering.h"
29 #include "llvm/Target/TargetMachine.h"
30 #include "llvm/Target/TargetOptions.h"
31 #include "llvm/ADT/SmallPtrSet.h"
32 #include "llvm/ADT/Statistic.h"
33 #include "llvm/Support/CommandLine.h"
34 #include "llvm/Support/Debug.h"
35 #include "llvm/Support/ErrorHandling.h"
36 #include "llvm/Support/MathExtras.h"
37 #include "llvm/Support/raw_ostream.h"
41 STATISTIC(NodesCombined , "Number of dag nodes combined");
42 STATISTIC(PreIndexedNodes , "Number of pre-indexed nodes created");
43 STATISTIC(PostIndexedNodes, "Number of post-indexed nodes created");
44 STATISTIC(OpsNarrowed , "Number of load/op/store narrowed");
45 STATISTIC(LdStFP2Int , "Number of fp load/store pairs transformed to int");
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 visitBITCAST(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);
214 SDValue visitMEMBARRIER(SDNode *N);
216 SDValue XformToShuffleWithZero(SDNode *N);
217 SDValue ReassociateOps(unsigned Opc, DebugLoc DL, SDValue LHS, SDValue RHS);
219 SDValue visitShiftByConstant(SDNode *N, unsigned Amt);
221 bool SimplifySelectOps(SDNode *SELECT, SDValue LHS, SDValue RHS);
222 SDValue SimplifyBinOpWithSameOpcodeHands(SDNode *N);
223 SDValue SimplifySelect(DebugLoc DL, SDValue N0, SDValue N1, SDValue N2);
224 SDValue SimplifySelectCC(DebugLoc DL, SDValue N0, SDValue N1, SDValue N2,
225 SDValue N3, ISD::CondCode CC,
226 bool NotExtCompare = false);
227 SDValue SimplifySetCC(EVT VT, SDValue N0, SDValue N1, ISD::CondCode Cond,
228 DebugLoc DL, bool foldBooleans = true);
229 SDValue SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp,
231 SDValue CombineConsecutiveLoads(SDNode *N, EVT VT);
232 SDValue ConstantFoldBITCASTofBUILD_VECTOR(SDNode *, EVT);
233 SDValue BuildSDIV(SDNode *N);
234 SDValue BuildUDIV(SDNode *N);
235 SDNode *MatchRotate(SDValue LHS, SDValue RHS, DebugLoc DL);
236 SDValue ReduceLoadWidth(SDNode *N);
237 SDValue ReduceLoadOpStoreWidth(SDNode *N);
238 SDValue TransformFPLoadStorePair(SDNode *N);
240 SDValue GetDemandedBits(SDValue V, const APInt &Mask);
242 /// GatherAllAliases - Walk up chain skipping non-aliasing memory nodes,
243 /// looking for aliasing nodes and adding them to the Aliases vector.
244 void GatherAllAliases(SDNode *N, SDValue OriginalChain,
245 SmallVector<SDValue, 8> &Aliases);
247 /// isAlias - Return true if there is any possibility that the two addresses
249 bool isAlias(SDValue Ptr1, int64_t Size1,
250 const Value *SrcValue1, int SrcValueOffset1,
251 unsigned SrcValueAlign1,
252 const MDNode *TBAAInfo1,
253 SDValue Ptr2, int64_t Size2,
254 const Value *SrcValue2, int SrcValueOffset2,
255 unsigned SrcValueAlign2,
256 const MDNode *TBAAInfo2) const;
258 /// FindAliasInfo - Extracts the relevant alias information from the memory
259 /// node. Returns true if the operand was a load.
260 bool FindAliasInfo(SDNode *N,
261 SDValue &Ptr, int64_t &Size,
262 const Value *&SrcValue, int &SrcValueOffset,
263 unsigned &SrcValueAlignment,
264 const MDNode *&TBAAInfo) const;
266 /// FindBetterChain - Walk up chain skipping non-aliasing memory nodes,
267 /// looking for a better chain (aliasing node.)
268 SDValue FindBetterChain(SDNode *N, SDValue Chain);
271 DAGCombiner(SelectionDAG &D, AliasAnalysis &A, CodeGenOpt::Level OL)
272 : DAG(D), TLI(D.getTargetLoweringInfo()), Level(Unrestricted),
273 OptLevel(OL), LegalOperations(false), LegalTypes(false), AA(A) {}
275 /// Run - runs the dag combiner on all nodes in the work list
276 void Run(CombineLevel AtLevel);
278 SelectionDAG &getDAG() const { return DAG; }
280 /// getShiftAmountTy - Returns a type large enough to hold any valid
281 /// shift amount - before type legalization these can be huge.
282 EVT getShiftAmountTy(EVT LHSTy) {
283 return LegalTypes ? TLI.getShiftAmountTy(LHSTy) : TLI.getPointerTy();
286 /// isTypeLegal - This method returns true if we are running before type
287 /// legalization or if the specified VT is legal.
288 bool isTypeLegal(const EVT &VT) {
289 if (!LegalTypes) return true;
290 return TLI.isTypeLegal(VT);
297 /// WorkListRemover - This class is a DAGUpdateListener that removes any deleted
298 /// nodes from the worklist.
299 class WorkListRemover : public SelectionDAG::DAGUpdateListener {
302 explicit WorkListRemover(DAGCombiner &dc) : DC(dc) {}
304 virtual void NodeDeleted(SDNode *N, SDNode *E) {
305 DC.removeFromWorkList(N);
308 virtual void NodeUpdated(SDNode *N) {
314 //===----------------------------------------------------------------------===//
315 // TargetLowering::DAGCombinerInfo implementation
316 //===----------------------------------------------------------------------===//
318 void TargetLowering::DAGCombinerInfo::AddToWorklist(SDNode *N) {
319 ((DAGCombiner*)DC)->AddToWorkList(N);
322 SDValue TargetLowering::DAGCombinerInfo::
323 CombineTo(SDNode *N, const std::vector<SDValue> &To, bool AddTo) {
324 return ((DAGCombiner*)DC)->CombineTo(N, &To[0], To.size(), AddTo);
327 SDValue TargetLowering::DAGCombinerInfo::
328 CombineTo(SDNode *N, SDValue Res, bool AddTo) {
329 return ((DAGCombiner*)DC)->CombineTo(N, Res, AddTo);
333 SDValue TargetLowering::DAGCombinerInfo::
334 CombineTo(SDNode *N, SDValue Res0, SDValue Res1, bool AddTo) {
335 return ((DAGCombiner*)DC)->CombineTo(N, Res0, Res1, AddTo);
338 void TargetLowering::DAGCombinerInfo::
339 CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) {
340 return ((DAGCombiner*)DC)->CommitTargetLoweringOpt(TLO);
343 //===----------------------------------------------------------------------===//
345 //===----------------------------------------------------------------------===//
347 /// isNegatibleForFree - Return 1 if we can compute the negated form of the
348 /// specified expression for the same cost as the expression itself, or 2 if we
349 /// can compute the negated form more cheaply than the expression itself.
350 static char isNegatibleForFree(SDValue Op, bool LegalOperations,
351 unsigned Depth = 0) {
352 // No compile time optimizations on this type.
353 if (Op.getValueType() == MVT::ppcf128)
356 // fneg is removable even if it has multiple uses.
357 if (Op.getOpcode() == ISD::FNEG) return 2;
359 // Don't allow anything with multiple uses.
360 if (!Op.hasOneUse()) return 0;
362 // Don't recurse exponentially.
363 if (Depth > 6) return 0;
365 switch (Op.getOpcode()) {
366 default: return false;
367 case ISD::ConstantFP:
368 // Don't invert constant FP values after legalize. The negated constant
369 // isn't necessarily legal.
370 return LegalOperations ? 0 : 1;
372 // FIXME: determine better conditions for this xform.
373 if (!UnsafeFPMath) return 0;
375 // fold (fsub (fadd A, B)) -> (fsub (fneg A), B)
376 if (char V = isNegatibleForFree(Op.getOperand(0), LegalOperations, Depth+1))
378 // fold (fneg (fadd A, B)) -> (fsub (fneg B), A)
379 return isNegatibleForFree(Op.getOperand(1), LegalOperations, Depth+1);
381 // We can't turn -(A-B) into B-A when we honor signed zeros.
382 if (!UnsafeFPMath) return 0;
384 // fold (fneg (fsub A, B)) -> (fsub B, A)
389 if (HonorSignDependentRoundingFPMath()) return 0;
391 // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y) or (fmul X, (fneg Y))
392 if (char V = isNegatibleForFree(Op.getOperand(0), LegalOperations, Depth+1))
395 return isNegatibleForFree(Op.getOperand(1), LegalOperations, Depth+1);
400 return isNegatibleForFree(Op.getOperand(0), LegalOperations, Depth+1);
404 /// GetNegatedExpression - If isNegatibleForFree returns true, this function
405 /// returns the newly negated expression.
406 static SDValue GetNegatedExpression(SDValue Op, SelectionDAG &DAG,
407 bool LegalOperations, unsigned Depth = 0) {
408 // fneg is removable even if it has multiple uses.
409 if (Op.getOpcode() == ISD::FNEG) return Op.getOperand(0);
411 // Don't allow anything with multiple uses.
412 assert(Op.hasOneUse() && "Unknown reuse!");
414 assert(Depth <= 6 && "GetNegatedExpression doesn't match isNegatibleForFree");
415 switch (Op.getOpcode()) {
416 default: llvm_unreachable("Unknown code");
417 case ISD::ConstantFP: {
418 APFloat V = cast<ConstantFPSDNode>(Op)->getValueAPF();
420 return DAG.getConstantFP(V, Op.getValueType());
423 // FIXME: determine better conditions for this xform.
424 assert(UnsafeFPMath);
426 // fold (fneg (fadd A, B)) -> (fsub (fneg A), B)
427 if (isNegatibleForFree(Op.getOperand(0), LegalOperations, Depth+1))
428 return DAG.getNode(ISD::FSUB, Op.getDebugLoc(), Op.getValueType(),
429 GetNegatedExpression(Op.getOperand(0), DAG,
430 LegalOperations, Depth+1),
432 // fold (fneg (fadd A, B)) -> (fsub (fneg B), A)
433 return DAG.getNode(ISD::FSUB, Op.getDebugLoc(), Op.getValueType(),
434 GetNegatedExpression(Op.getOperand(1), DAG,
435 LegalOperations, Depth+1),
438 // We can't turn -(A-B) into B-A when we honor signed zeros.
439 assert(UnsafeFPMath);
441 // fold (fneg (fsub 0, B)) -> B
442 if (ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(Op.getOperand(0)))
443 if (N0CFP->getValueAPF().isZero())
444 return Op.getOperand(1);
446 // fold (fneg (fsub A, B)) -> (fsub B, A)
447 return DAG.getNode(ISD::FSUB, Op.getDebugLoc(), Op.getValueType(),
448 Op.getOperand(1), Op.getOperand(0));
452 assert(!HonorSignDependentRoundingFPMath());
454 // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y)
455 if (isNegatibleForFree(Op.getOperand(0), LegalOperations, Depth+1))
456 return DAG.getNode(Op.getOpcode(), Op.getDebugLoc(), Op.getValueType(),
457 GetNegatedExpression(Op.getOperand(0), DAG,
458 LegalOperations, Depth+1),
461 // fold (fneg (fmul X, Y)) -> (fmul X, (fneg Y))
462 return DAG.getNode(Op.getOpcode(), Op.getDebugLoc(), Op.getValueType(),
464 GetNegatedExpression(Op.getOperand(1), DAG,
465 LegalOperations, Depth+1));
469 return DAG.getNode(Op.getOpcode(), Op.getDebugLoc(), Op.getValueType(),
470 GetNegatedExpression(Op.getOperand(0), DAG,
471 LegalOperations, Depth+1));
473 return DAG.getNode(ISD::FP_ROUND, Op.getDebugLoc(), Op.getValueType(),
474 GetNegatedExpression(Op.getOperand(0), DAG,
475 LegalOperations, Depth+1),
481 // isSetCCEquivalent - Return true if this node is a setcc, or is a select_cc
482 // that selects between the values 1 and 0, making it equivalent to a setcc.
483 // Also, set the incoming LHS, RHS, and CC references to the appropriate
484 // nodes based on the type of node we are checking. This simplifies life a
485 // bit for the callers.
486 static bool isSetCCEquivalent(SDValue N, SDValue &LHS, SDValue &RHS,
488 if (N.getOpcode() == ISD::SETCC) {
489 LHS = N.getOperand(0);
490 RHS = N.getOperand(1);
491 CC = N.getOperand(2);
494 if (N.getOpcode() == ISD::SELECT_CC &&
495 N.getOperand(2).getOpcode() == ISD::Constant &&
496 N.getOperand(3).getOpcode() == ISD::Constant &&
497 cast<ConstantSDNode>(N.getOperand(2))->getAPIntValue() == 1 &&
498 cast<ConstantSDNode>(N.getOperand(3))->isNullValue()) {
499 LHS = N.getOperand(0);
500 RHS = N.getOperand(1);
501 CC = N.getOperand(4);
507 // isOneUseSetCC - Return true if this is a SetCC-equivalent operation with only
508 // one use. If this is true, it allows the users to invert the operation for
509 // free when it is profitable to do so.
510 static bool isOneUseSetCC(SDValue N) {
512 if (isSetCCEquivalent(N, N0, N1, N2) && N.getNode()->hasOneUse())
517 SDValue DAGCombiner::ReassociateOps(unsigned Opc, DebugLoc DL,
518 SDValue N0, SDValue N1) {
519 EVT VT = N0.getValueType();
520 if (N0.getOpcode() == Opc && isa<ConstantSDNode>(N0.getOperand(1))) {
521 if (isa<ConstantSDNode>(N1)) {
522 // reassoc. (op (op x, c1), c2) -> (op x, (op c1, c2))
524 DAG.FoldConstantArithmetic(Opc, VT,
525 cast<ConstantSDNode>(N0.getOperand(1)),
526 cast<ConstantSDNode>(N1));
527 return DAG.getNode(Opc, DL, VT, N0.getOperand(0), OpNode);
528 } else if (N0.hasOneUse()) {
529 // reassoc. (op (op x, c1), y) -> (op (op x, y), c1) iff x+c1 has one use
530 SDValue OpNode = DAG.getNode(Opc, N0.getDebugLoc(), VT,
531 N0.getOperand(0), N1);
532 AddToWorkList(OpNode.getNode());
533 return DAG.getNode(Opc, DL, VT, OpNode, N0.getOperand(1));
537 if (N1.getOpcode() == Opc && isa<ConstantSDNode>(N1.getOperand(1))) {
538 if (isa<ConstantSDNode>(N0)) {
539 // reassoc. (op c2, (op x, c1)) -> (op x, (op c1, c2))
541 DAG.FoldConstantArithmetic(Opc, VT,
542 cast<ConstantSDNode>(N1.getOperand(1)),
543 cast<ConstantSDNode>(N0));
544 return DAG.getNode(Opc, DL, VT, N1.getOperand(0), OpNode);
545 } else if (N1.hasOneUse()) {
546 // reassoc. (op y, (op x, c1)) -> (op (op x, y), c1) iff x+c1 has one use
547 SDValue OpNode = DAG.getNode(Opc, N0.getDebugLoc(), VT,
548 N1.getOperand(0), N0);
549 AddToWorkList(OpNode.getNode());
550 return DAG.getNode(Opc, DL, VT, OpNode, N1.getOperand(1));
557 SDValue DAGCombiner::CombineTo(SDNode *N, const SDValue *To, unsigned NumTo,
559 assert(N->getNumValues() == NumTo && "Broken CombineTo call!");
561 DEBUG(dbgs() << "\nReplacing.1 ";
563 dbgs() << "\nWith: ";
564 To[0].getNode()->dump(&DAG);
565 dbgs() << " and " << NumTo-1 << " other values\n";
566 for (unsigned i = 0, e = NumTo; i != e; ++i)
567 assert((!To[i].getNode() ||
568 N->getValueType(i) == To[i].getValueType()) &&
569 "Cannot combine value to value of different type!"));
570 WorkListRemover DeadNodes(*this);
571 DAG.ReplaceAllUsesWith(N, To, &DeadNodes);
574 // Push the new nodes and any users onto the worklist
575 for (unsigned i = 0, e = NumTo; i != e; ++i) {
576 if (To[i].getNode()) {
577 AddToWorkList(To[i].getNode());
578 AddUsersToWorkList(To[i].getNode());
583 // Finally, if the node is now dead, remove it from the graph. The node
584 // may not be dead if the replacement process recursively simplified to
585 // something else needing this node.
586 if (N->use_empty()) {
587 // Nodes can be reintroduced into the worklist. Make sure we do not
588 // process a node that has been replaced.
589 removeFromWorkList(N);
591 // Finally, since the node is now dead, remove it from the graph.
594 return SDValue(N, 0);
598 CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) {
599 // Replace all uses. If any nodes become isomorphic to other nodes and
600 // are deleted, make sure to remove them from our worklist.
601 WorkListRemover DeadNodes(*this);
602 DAG.ReplaceAllUsesOfValueWith(TLO.Old, TLO.New, &DeadNodes);
604 // Push the new node and any (possibly new) users onto the worklist.
605 AddToWorkList(TLO.New.getNode());
606 AddUsersToWorkList(TLO.New.getNode());
608 // Finally, if the node is now dead, remove it from the graph. The node
609 // may not be dead if the replacement process recursively simplified to
610 // something else needing this node.
611 if (TLO.Old.getNode()->use_empty()) {
612 removeFromWorkList(TLO.Old.getNode());
614 // If the operands of this node are only used by the node, they will now
615 // be dead. Make sure to visit them first to delete dead nodes early.
616 for (unsigned i = 0, e = TLO.Old.getNode()->getNumOperands(); i != e; ++i)
617 if (TLO.Old.getNode()->getOperand(i).getNode()->hasOneUse())
618 AddToWorkList(TLO.Old.getNode()->getOperand(i).getNode());
620 DAG.DeleteNode(TLO.Old.getNode());
624 /// SimplifyDemandedBits - Check the specified integer node value to see if
625 /// it can be simplified or if things it uses can be simplified by bit
626 /// propagation. If so, return true.
627 bool DAGCombiner::SimplifyDemandedBits(SDValue Op, const APInt &Demanded) {
628 TargetLowering::TargetLoweringOpt TLO(DAG, LegalTypes, LegalOperations);
629 APInt KnownZero, KnownOne;
630 if (!TLI.SimplifyDemandedBits(Op, Demanded, KnownZero, KnownOne, TLO))
634 AddToWorkList(Op.getNode());
636 // Replace the old value with the new one.
638 DEBUG(dbgs() << "\nReplacing.2 ";
639 TLO.Old.getNode()->dump(&DAG);
640 dbgs() << "\nWith: ";
641 TLO.New.getNode()->dump(&DAG);
644 CommitTargetLoweringOpt(TLO);
648 void DAGCombiner::ReplaceLoadWithPromotedLoad(SDNode *Load, SDNode *ExtLoad) {
649 DebugLoc dl = Load->getDebugLoc();
650 EVT VT = Load->getValueType(0);
651 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, dl, VT, SDValue(ExtLoad, 0));
653 DEBUG(dbgs() << "\nReplacing.9 ";
655 dbgs() << "\nWith: ";
656 Trunc.getNode()->dump(&DAG);
658 WorkListRemover DeadNodes(*this);
659 DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 0), Trunc, &DeadNodes);
660 DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 1), SDValue(ExtLoad, 1),
662 removeFromWorkList(Load);
663 DAG.DeleteNode(Load);
664 AddToWorkList(Trunc.getNode());
667 SDValue DAGCombiner::PromoteOperand(SDValue Op, EVT PVT, bool &Replace) {
669 DebugLoc dl = Op.getDebugLoc();
670 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Op)) {
671 EVT MemVT = LD->getMemoryVT();
672 ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD)
673 ? (TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT) ? ISD::ZEXTLOAD
675 : LD->getExtensionType();
677 return DAG.getExtLoad(ExtType, dl, PVT,
678 LD->getChain(), LD->getBasePtr(),
679 LD->getPointerInfo(),
680 MemVT, LD->isVolatile(),
681 LD->isNonTemporal(), LD->getAlignment());
684 unsigned Opc = Op.getOpcode();
687 case ISD::AssertSext:
688 return DAG.getNode(ISD::AssertSext, dl, PVT,
689 SExtPromoteOperand(Op.getOperand(0), PVT),
691 case ISD::AssertZext:
692 return DAG.getNode(ISD::AssertZext, dl, PVT,
693 ZExtPromoteOperand(Op.getOperand(0), PVT),
695 case ISD::Constant: {
697 Op.getValueType().isByteSized() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
698 return DAG.getNode(ExtOpc, dl, PVT, Op);
702 if (!TLI.isOperationLegal(ISD::ANY_EXTEND, PVT))
704 return DAG.getNode(ISD::ANY_EXTEND, dl, PVT, Op);
707 SDValue DAGCombiner::SExtPromoteOperand(SDValue Op, EVT PVT) {
708 if (!TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, PVT))
710 EVT OldVT = Op.getValueType();
711 DebugLoc dl = Op.getDebugLoc();
712 bool Replace = false;
713 SDValue NewOp = PromoteOperand(Op, PVT, Replace);
714 if (NewOp.getNode() == 0)
716 AddToWorkList(NewOp.getNode());
719 ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode());
720 return DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, NewOp.getValueType(), NewOp,
721 DAG.getValueType(OldVT));
724 SDValue DAGCombiner::ZExtPromoteOperand(SDValue Op, EVT PVT) {
725 EVT OldVT = Op.getValueType();
726 DebugLoc dl = Op.getDebugLoc();
727 bool Replace = false;
728 SDValue NewOp = PromoteOperand(Op, PVT, Replace);
729 if (NewOp.getNode() == 0)
731 AddToWorkList(NewOp.getNode());
734 ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode());
735 return DAG.getZeroExtendInReg(NewOp, dl, OldVT);
738 /// PromoteIntBinOp - Promote the specified integer binary operation if the
739 /// target indicates it is beneficial. e.g. On x86, it's usually better to
740 /// promote i16 operations to i32 since i16 instructions are longer.
741 SDValue DAGCombiner::PromoteIntBinOp(SDValue Op) {
742 if (!LegalOperations)
745 EVT VT = Op.getValueType();
746 if (VT.isVector() || !VT.isInteger())
749 // If operation type is 'undesirable', e.g. i16 on x86, consider
751 unsigned Opc = Op.getOpcode();
752 if (TLI.isTypeDesirableForOp(Opc, VT))
756 // Consult target whether it is a good idea to promote this operation and
757 // what's the right type to promote it to.
758 if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
759 assert(PVT != VT && "Don't know what type to promote to!");
761 bool Replace0 = false;
762 SDValue N0 = Op.getOperand(0);
763 SDValue NN0 = PromoteOperand(N0, PVT, Replace0);
764 if (NN0.getNode() == 0)
767 bool Replace1 = false;
768 SDValue N1 = Op.getOperand(1);
773 NN1 = PromoteOperand(N1, PVT, Replace1);
774 if (NN1.getNode() == 0)
778 AddToWorkList(NN0.getNode());
780 AddToWorkList(NN1.getNode());
783 ReplaceLoadWithPromotedLoad(N0.getNode(), NN0.getNode());
785 ReplaceLoadWithPromotedLoad(N1.getNode(), NN1.getNode());
787 DEBUG(dbgs() << "\nPromoting ";
788 Op.getNode()->dump(&DAG));
789 DebugLoc dl = Op.getDebugLoc();
790 return DAG.getNode(ISD::TRUNCATE, dl, VT,
791 DAG.getNode(Opc, dl, PVT, NN0, NN1));
796 /// PromoteIntShiftOp - Promote the specified integer shift operation if the
797 /// target indicates it is beneficial. e.g. On x86, it's usually better to
798 /// promote i16 operations to i32 since i16 instructions are longer.
799 SDValue DAGCombiner::PromoteIntShiftOp(SDValue Op) {
800 if (!LegalOperations)
803 EVT VT = Op.getValueType();
804 if (VT.isVector() || !VT.isInteger())
807 // If operation type is 'undesirable', e.g. i16 on x86, consider
809 unsigned Opc = Op.getOpcode();
810 if (TLI.isTypeDesirableForOp(Opc, VT))
814 // Consult target whether it is a good idea to promote this operation and
815 // what's the right type to promote it to.
816 if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
817 assert(PVT != VT && "Don't know what type to promote to!");
819 bool Replace = false;
820 SDValue N0 = Op.getOperand(0);
822 N0 = SExtPromoteOperand(Op.getOperand(0), PVT);
823 else if (Opc == ISD::SRL)
824 N0 = ZExtPromoteOperand(Op.getOperand(0), PVT);
826 N0 = PromoteOperand(N0, PVT, Replace);
827 if (N0.getNode() == 0)
830 AddToWorkList(N0.getNode());
832 ReplaceLoadWithPromotedLoad(Op.getOperand(0).getNode(), N0.getNode());
834 DEBUG(dbgs() << "\nPromoting ";
835 Op.getNode()->dump(&DAG));
836 DebugLoc dl = Op.getDebugLoc();
837 return DAG.getNode(ISD::TRUNCATE, dl, VT,
838 DAG.getNode(Opc, dl, PVT, N0, Op.getOperand(1)));
843 SDValue DAGCombiner::PromoteExtend(SDValue Op) {
844 if (!LegalOperations)
847 EVT VT = Op.getValueType();
848 if (VT.isVector() || !VT.isInteger())
851 // If operation type is 'undesirable', e.g. i16 on x86, consider
853 unsigned Opc = Op.getOpcode();
854 if (TLI.isTypeDesirableForOp(Opc, VT))
858 // Consult target whether it is a good idea to promote this operation and
859 // what's the right type to promote it to.
860 if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
861 assert(PVT != VT && "Don't know what type to promote to!");
862 // fold (aext (aext x)) -> (aext x)
863 // fold (aext (zext x)) -> (zext x)
864 // fold (aext (sext x)) -> (sext x)
865 DEBUG(dbgs() << "\nPromoting ";
866 Op.getNode()->dump(&DAG));
867 return DAG.getNode(Op.getOpcode(), Op.getDebugLoc(), VT, Op.getOperand(0));
872 bool DAGCombiner::PromoteLoad(SDValue Op) {
873 if (!LegalOperations)
876 EVT VT = Op.getValueType();
877 if (VT.isVector() || !VT.isInteger())
880 // If operation type is 'undesirable', e.g. i16 on x86, consider
882 unsigned Opc = Op.getOpcode();
883 if (TLI.isTypeDesirableForOp(Opc, VT))
887 // Consult target whether it is a good idea to promote this operation and
888 // what's the right type to promote it to.
889 if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
890 assert(PVT != VT && "Don't know what type to promote to!");
892 DebugLoc dl = Op.getDebugLoc();
893 SDNode *N = Op.getNode();
894 LoadSDNode *LD = cast<LoadSDNode>(N);
895 EVT MemVT = LD->getMemoryVT();
896 ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD)
897 ? (TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT) ? ISD::ZEXTLOAD
899 : LD->getExtensionType();
900 SDValue NewLD = DAG.getExtLoad(ExtType, dl, PVT,
901 LD->getChain(), LD->getBasePtr(),
902 LD->getPointerInfo(),
903 MemVT, LD->isVolatile(),
904 LD->isNonTemporal(), LD->getAlignment());
905 SDValue Result = DAG.getNode(ISD::TRUNCATE, dl, VT, NewLD);
907 DEBUG(dbgs() << "\nPromoting ";
910 Result.getNode()->dump(&DAG);
912 WorkListRemover DeadNodes(*this);
913 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result, &DeadNodes);
914 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), NewLD.getValue(1), &DeadNodes);
915 removeFromWorkList(N);
917 AddToWorkList(Result.getNode());
924 //===----------------------------------------------------------------------===//
925 // Main DAG Combiner implementation
926 //===----------------------------------------------------------------------===//
928 void DAGCombiner::Run(CombineLevel AtLevel) {
929 // set the instance variables, so that the various visit routines may use it.
931 LegalOperations = Level >= NoIllegalOperations;
932 LegalTypes = Level >= NoIllegalTypes;
934 // Add all the dag nodes to the worklist.
935 WorkList.reserve(DAG.allnodes_size());
936 for (SelectionDAG::allnodes_iterator I = DAG.allnodes_begin(),
937 E = DAG.allnodes_end(); I != E; ++I)
938 WorkList.push_back(I);
940 // Create a dummy node (which is not added to allnodes), that adds a reference
941 // to the root node, preventing it from being deleted, and tracking any
942 // changes of the root.
943 HandleSDNode Dummy(DAG.getRoot());
945 // The root of the dag may dangle to deleted nodes until the dag combiner is
946 // done. Set it to null to avoid confusion.
947 DAG.setRoot(SDValue());
949 // while the worklist isn't empty, inspect the node on the end of it and
950 // try and combine it.
951 while (!WorkList.empty()) {
952 SDNode *N = WorkList.back();
955 // If N has no uses, it is dead. Make sure to revisit all N's operands once
956 // N is deleted from the DAG, since they too may now be dead or may have a
957 // reduced number of uses, allowing other xforms.
958 if (N->use_empty() && N != &Dummy) {
959 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
960 AddToWorkList(N->getOperand(i).getNode());
966 SDValue RV = combine(N);
968 if (RV.getNode() == 0)
973 // If we get back the same node we passed in, rather than a new node or
974 // zero, we know that the node must have defined multiple values and
975 // CombineTo was used. Since CombineTo takes care of the worklist
976 // mechanics for us, we have no work to do in this case.
977 if (RV.getNode() == N)
980 assert(N->getOpcode() != ISD::DELETED_NODE &&
981 RV.getNode()->getOpcode() != ISD::DELETED_NODE &&
982 "Node was deleted but visit returned new node!");
984 DEBUG(dbgs() << "\nReplacing.3 ";
986 dbgs() << "\nWith: ";
987 RV.getNode()->dump(&DAG);
989 WorkListRemover DeadNodes(*this);
990 if (N->getNumValues() == RV.getNode()->getNumValues())
991 DAG.ReplaceAllUsesWith(N, RV.getNode(), &DeadNodes);
993 assert(N->getValueType(0) == RV.getValueType() &&
994 N->getNumValues() == 1 && "Type mismatch");
996 DAG.ReplaceAllUsesWith(N, &OpV, &DeadNodes);
999 // Push the new node and any users onto the worklist
1000 AddToWorkList(RV.getNode());
1001 AddUsersToWorkList(RV.getNode());
1003 // Add any uses of the old node to the worklist in case this node is the
1004 // last one that uses them. They may become dead after this node is
1006 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1007 AddToWorkList(N->getOperand(i).getNode());
1009 // Finally, if the node is now dead, remove it from the graph. The node
1010 // may not be dead if the replacement process recursively simplified to
1011 // something else needing this node.
1012 if (N->use_empty()) {
1013 // Nodes can be reintroduced into the worklist. Make sure we do not
1014 // process a node that has been replaced.
1015 removeFromWorkList(N);
1017 // Finally, since the node is now dead, remove it from the graph.
1022 // If the root changed (e.g. it was a dead load, update the root).
1023 DAG.setRoot(Dummy.getValue());
1026 SDValue DAGCombiner::visit(SDNode *N) {
1027 switch (N->getOpcode()) {
1029 case ISD::TokenFactor: return visitTokenFactor(N);
1030 case ISD::MERGE_VALUES: return visitMERGE_VALUES(N);
1031 case ISD::ADD: return visitADD(N);
1032 case ISD::SUB: return visitSUB(N);
1033 case ISD::ADDC: return visitADDC(N);
1034 case ISD::ADDE: return visitADDE(N);
1035 case ISD::MUL: return visitMUL(N);
1036 case ISD::SDIV: return visitSDIV(N);
1037 case ISD::UDIV: return visitUDIV(N);
1038 case ISD::SREM: return visitSREM(N);
1039 case ISD::UREM: return visitUREM(N);
1040 case ISD::MULHU: return visitMULHU(N);
1041 case ISD::MULHS: return visitMULHS(N);
1042 case ISD::SMUL_LOHI: return visitSMUL_LOHI(N);
1043 case ISD::UMUL_LOHI: return visitUMUL_LOHI(N);
1044 case ISD::SDIVREM: return visitSDIVREM(N);
1045 case ISD::UDIVREM: return visitUDIVREM(N);
1046 case ISD::AND: return visitAND(N);
1047 case ISD::OR: return visitOR(N);
1048 case ISD::XOR: return visitXOR(N);
1049 case ISD::SHL: return visitSHL(N);
1050 case ISD::SRA: return visitSRA(N);
1051 case ISD::SRL: return visitSRL(N);
1052 case ISD::CTLZ: return visitCTLZ(N);
1053 case ISD::CTTZ: return visitCTTZ(N);
1054 case ISD::CTPOP: return visitCTPOP(N);
1055 case ISD::SELECT: return visitSELECT(N);
1056 case ISD::SELECT_CC: return visitSELECT_CC(N);
1057 case ISD::SETCC: return visitSETCC(N);
1058 case ISD::SIGN_EXTEND: return visitSIGN_EXTEND(N);
1059 case ISD::ZERO_EXTEND: return visitZERO_EXTEND(N);
1060 case ISD::ANY_EXTEND: return visitANY_EXTEND(N);
1061 case ISD::SIGN_EXTEND_INREG: return visitSIGN_EXTEND_INREG(N);
1062 case ISD::TRUNCATE: return visitTRUNCATE(N);
1063 case ISD::BITCAST: return visitBITCAST(N);
1064 case ISD::BUILD_PAIR: return visitBUILD_PAIR(N);
1065 case ISD::FADD: return visitFADD(N);
1066 case ISD::FSUB: return visitFSUB(N);
1067 case ISD::FMUL: return visitFMUL(N);
1068 case ISD::FDIV: return visitFDIV(N);
1069 case ISD::FREM: return visitFREM(N);
1070 case ISD::FCOPYSIGN: return visitFCOPYSIGN(N);
1071 case ISD::SINT_TO_FP: return visitSINT_TO_FP(N);
1072 case ISD::UINT_TO_FP: return visitUINT_TO_FP(N);
1073 case ISD::FP_TO_SINT: return visitFP_TO_SINT(N);
1074 case ISD::FP_TO_UINT: return visitFP_TO_UINT(N);
1075 case ISD::FP_ROUND: return visitFP_ROUND(N);
1076 case ISD::FP_ROUND_INREG: return visitFP_ROUND_INREG(N);
1077 case ISD::FP_EXTEND: return visitFP_EXTEND(N);
1078 case ISD::FNEG: return visitFNEG(N);
1079 case ISD::FABS: return visitFABS(N);
1080 case ISD::BRCOND: return visitBRCOND(N);
1081 case ISD::BR_CC: return visitBR_CC(N);
1082 case ISD::LOAD: return visitLOAD(N);
1083 case ISD::STORE: return visitSTORE(N);
1084 case ISD::INSERT_VECTOR_ELT: return visitINSERT_VECTOR_ELT(N);
1085 case ISD::EXTRACT_VECTOR_ELT: return visitEXTRACT_VECTOR_ELT(N);
1086 case ISD::BUILD_VECTOR: return visitBUILD_VECTOR(N);
1087 case ISD::CONCAT_VECTORS: return visitCONCAT_VECTORS(N);
1088 case ISD::VECTOR_SHUFFLE: return visitVECTOR_SHUFFLE(N);
1089 case ISD::MEMBARRIER: return visitMEMBARRIER(N);
1094 SDValue DAGCombiner::combine(SDNode *N) {
1095 SDValue RV = visit(N);
1097 // If nothing happened, try a target-specific DAG combine.
1098 if (RV.getNode() == 0) {
1099 assert(N->getOpcode() != ISD::DELETED_NODE &&
1100 "Node was deleted but visit returned NULL!");
1102 if (N->getOpcode() >= ISD::BUILTIN_OP_END ||
1103 TLI.hasTargetDAGCombine((ISD::NodeType)N->getOpcode())) {
1105 // Expose the DAG combiner to the target combiner impls.
1106 TargetLowering::DAGCombinerInfo
1107 DagCombineInfo(DAG, !LegalTypes, !LegalOperations, false, this);
1109 RV = TLI.PerformDAGCombine(N, DagCombineInfo);
1113 // If nothing happened still, try promoting the operation.
1114 if (RV.getNode() == 0) {
1115 switch (N->getOpcode()) {
1123 RV = PromoteIntBinOp(SDValue(N, 0));
1128 RV = PromoteIntShiftOp(SDValue(N, 0));
1130 case ISD::SIGN_EXTEND:
1131 case ISD::ZERO_EXTEND:
1132 case ISD::ANY_EXTEND:
1133 RV = PromoteExtend(SDValue(N, 0));
1136 if (PromoteLoad(SDValue(N, 0)))
1142 // If N is a commutative binary node, try commuting it to enable more
1144 if (RV.getNode() == 0 &&
1145 SelectionDAG::isCommutativeBinOp(N->getOpcode()) &&
1146 N->getNumValues() == 1) {
1147 SDValue N0 = N->getOperand(0);
1148 SDValue N1 = N->getOperand(1);
1150 // Constant operands are canonicalized to RHS.
1151 if (isa<ConstantSDNode>(N0) || !isa<ConstantSDNode>(N1)) {
1152 SDValue Ops[] = { N1, N0 };
1153 SDNode *CSENode = DAG.getNodeIfExists(N->getOpcode(), N->getVTList(),
1156 return SDValue(CSENode, 0);
1163 /// getInputChainForNode - Given a node, return its input chain if it has one,
1164 /// otherwise return a null sd operand.
1165 static SDValue getInputChainForNode(SDNode *N) {
1166 if (unsigned NumOps = N->getNumOperands()) {
1167 if (N->getOperand(0).getValueType() == MVT::Other)
1168 return N->getOperand(0);
1169 else if (N->getOperand(NumOps-1).getValueType() == MVT::Other)
1170 return N->getOperand(NumOps-1);
1171 for (unsigned i = 1; i < NumOps-1; ++i)
1172 if (N->getOperand(i).getValueType() == MVT::Other)
1173 return N->getOperand(i);
1178 SDValue DAGCombiner::visitTokenFactor(SDNode *N) {
1179 // If N has two operands, where one has an input chain equal to the other,
1180 // the 'other' chain is redundant.
1181 if (N->getNumOperands() == 2) {
1182 if (getInputChainForNode(N->getOperand(0).getNode()) == N->getOperand(1))
1183 return N->getOperand(0);
1184 if (getInputChainForNode(N->getOperand(1).getNode()) == N->getOperand(0))
1185 return N->getOperand(1);
1188 SmallVector<SDNode *, 8> TFs; // List of token factors to visit.
1189 SmallVector<SDValue, 8> Ops; // Ops for replacing token factor.
1190 SmallPtrSet<SDNode*, 16> SeenOps;
1191 bool Changed = false; // If we should replace this token factor.
1193 // Start out with this token factor.
1196 // Iterate through token factors. The TFs grows when new token factors are
1198 for (unsigned i = 0; i < TFs.size(); ++i) {
1199 SDNode *TF = TFs[i];
1201 // Check each of the operands.
1202 for (unsigned i = 0, ie = TF->getNumOperands(); i != ie; ++i) {
1203 SDValue Op = TF->getOperand(i);
1205 switch (Op.getOpcode()) {
1206 case ISD::EntryToken:
1207 // Entry tokens don't need to be added to the list. They are
1212 case ISD::TokenFactor:
1213 if (Op.hasOneUse() &&
1214 std::find(TFs.begin(), TFs.end(), Op.getNode()) == TFs.end()) {
1215 // Queue up for processing.
1216 TFs.push_back(Op.getNode());
1217 // Clean up in case the token factor is removed.
1218 AddToWorkList(Op.getNode());
1225 // Only add if it isn't already in the list.
1226 if (SeenOps.insert(Op.getNode()))
1237 // If we've change things around then replace token factor.
1240 // The entry token is the only possible outcome.
1241 Result = DAG.getEntryNode();
1243 // New and improved token factor.
1244 Result = DAG.getNode(ISD::TokenFactor, N->getDebugLoc(),
1245 MVT::Other, &Ops[0], Ops.size());
1248 // Don't add users to work list.
1249 return CombineTo(N, Result, false);
1255 /// MERGE_VALUES can always be eliminated.
1256 SDValue DAGCombiner::visitMERGE_VALUES(SDNode *N) {
1257 WorkListRemover DeadNodes(*this);
1258 // Replacing results may cause a different MERGE_VALUES to suddenly
1259 // be CSE'd with N, and carry its uses with it. Iterate until no
1260 // uses remain, to ensure that the node can be safely deleted.
1262 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1263 DAG.ReplaceAllUsesOfValueWith(SDValue(N, i), N->getOperand(i),
1265 } while (!N->use_empty());
1266 removeFromWorkList(N);
1268 return SDValue(N, 0); // Return N so it doesn't get rechecked!
1272 SDValue combineShlAddConstant(DebugLoc DL, SDValue N0, SDValue N1,
1273 SelectionDAG &DAG) {
1274 EVT VT = N0.getValueType();
1275 SDValue N00 = N0.getOperand(0);
1276 SDValue N01 = N0.getOperand(1);
1277 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N01);
1279 if (N01C && N00.getOpcode() == ISD::ADD && N00.getNode()->hasOneUse() &&
1280 isa<ConstantSDNode>(N00.getOperand(1))) {
1281 // fold (add (shl (add x, c1), c2), ) -> (add (add (shl x, c2), c1<<c2), )
1282 N0 = DAG.getNode(ISD::ADD, N0.getDebugLoc(), VT,
1283 DAG.getNode(ISD::SHL, N00.getDebugLoc(), VT,
1284 N00.getOperand(0), N01),
1285 DAG.getNode(ISD::SHL, N01.getDebugLoc(), VT,
1286 N00.getOperand(1), N01));
1287 return DAG.getNode(ISD::ADD, DL, VT, N0, N1);
1293 /// isCarryMaterialization - Returns true if V is an ADDE node that is known to
1294 /// return 0 or 1 depending on the carry flag.
1295 static bool isCarryMaterialization(SDValue V) {
1296 if (V.getOpcode() != ISD::ADDE)
1299 ConstantSDNode *C = dyn_cast<ConstantSDNode>(V.getOperand(0));
1300 return C && C->isNullValue() && V.getOperand(0) == V.getOperand(1);
1303 SDValue DAGCombiner::visitADD(SDNode *N) {
1304 SDValue N0 = N->getOperand(0);
1305 SDValue N1 = N->getOperand(1);
1306 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1307 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1308 EVT VT = N0.getValueType();
1311 if (VT.isVector()) {
1312 SDValue FoldedVOp = SimplifyVBinOp(N);
1313 if (FoldedVOp.getNode()) return FoldedVOp;
1316 // fold (add x, undef) -> undef
1317 if (N0.getOpcode() == ISD::UNDEF)
1319 if (N1.getOpcode() == ISD::UNDEF)
1321 // fold (add c1, c2) -> c1+c2
1323 return DAG.FoldConstantArithmetic(ISD::ADD, VT, N0C, N1C);
1324 // canonicalize constant to RHS
1326 return DAG.getNode(ISD::ADD, N->getDebugLoc(), VT, N1, N0);
1327 // fold (add x, 0) -> x
1328 if (N1C && N1C->isNullValue())
1330 // fold (add Sym, c) -> Sym+c
1331 if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N0))
1332 if (!LegalOperations && TLI.isOffsetFoldingLegal(GA) && N1C &&
1333 GA->getOpcode() == ISD::GlobalAddress)
1334 return DAG.getGlobalAddress(GA->getGlobal(), N1C->getDebugLoc(), VT,
1336 (uint64_t)N1C->getSExtValue());
1337 // fold ((c1-A)+c2) -> (c1+c2)-A
1338 if (N1C && N0.getOpcode() == ISD::SUB)
1339 if (ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getOperand(0)))
1340 return DAG.getNode(ISD::SUB, N->getDebugLoc(), VT,
1341 DAG.getConstant(N1C->getAPIntValue()+
1342 N0C->getAPIntValue(), VT),
1345 SDValue RADD = ReassociateOps(ISD::ADD, N->getDebugLoc(), N0, N1);
1346 if (RADD.getNode() != 0)
1348 // fold ((0-A) + B) -> B-A
1349 if (N0.getOpcode() == ISD::SUB && isa<ConstantSDNode>(N0.getOperand(0)) &&
1350 cast<ConstantSDNode>(N0.getOperand(0))->isNullValue())
1351 return DAG.getNode(ISD::SUB, N->getDebugLoc(), VT, N1, N0.getOperand(1));
1352 // fold (A + (0-B)) -> A-B
1353 if (N1.getOpcode() == ISD::SUB && isa<ConstantSDNode>(N1.getOperand(0)) &&
1354 cast<ConstantSDNode>(N1.getOperand(0))->isNullValue())
1355 return DAG.getNode(ISD::SUB, N->getDebugLoc(), VT, N0, N1.getOperand(1));
1356 // fold (A+(B-A)) -> B
1357 if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(1))
1358 return N1.getOperand(0);
1359 // fold ((B-A)+A) -> B
1360 if (N0.getOpcode() == ISD::SUB && N1 == N0.getOperand(1))
1361 return N0.getOperand(0);
1362 // fold (A+(B-(A+C))) to (B-C)
1363 if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD &&
1364 N0 == N1.getOperand(1).getOperand(0))
1365 return DAG.getNode(ISD::SUB, N->getDebugLoc(), VT, N1.getOperand(0),
1366 N1.getOperand(1).getOperand(1));
1367 // fold (A+(B-(C+A))) to (B-C)
1368 if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD &&
1369 N0 == N1.getOperand(1).getOperand(1))
1370 return DAG.getNode(ISD::SUB, N->getDebugLoc(), VT, N1.getOperand(0),
1371 N1.getOperand(1).getOperand(0));
1372 // fold (A+((B-A)+or-C)) to (B+or-C)
1373 if ((N1.getOpcode() == ISD::SUB || N1.getOpcode() == ISD::ADD) &&
1374 N1.getOperand(0).getOpcode() == ISD::SUB &&
1375 N0 == N1.getOperand(0).getOperand(1))
1376 return DAG.getNode(N1.getOpcode(), N->getDebugLoc(), VT,
1377 N1.getOperand(0).getOperand(0), N1.getOperand(1));
1379 // fold (A-B)+(C-D) to (A+C)-(B+D) when A or C is constant
1380 if (N0.getOpcode() == ISD::SUB && N1.getOpcode() == ISD::SUB) {
1381 SDValue N00 = N0.getOperand(0);
1382 SDValue N01 = N0.getOperand(1);
1383 SDValue N10 = N1.getOperand(0);
1384 SDValue N11 = N1.getOperand(1);
1386 if (isa<ConstantSDNode>(N00) || isa<ConstantSDNode>(N10))
1387 return DAG.getNode(ISD::SUB, N->getDebugLoc(), VT,
1388 DAG.getNode(ISD::ADD, N0.getDebugLoc(), VT, N00, N10),
1389 DAG.getNode(ISD::ADD, N1.getDebugLoc(), VT, N01, N11));
1392 if (!VT.isVector() && SimplifyDemandedBits(SDValue(N, 0)))
1393 return SDValue(N, 0);
1395 // fold (a+b) -> (a|b) iff a and b share no bits.
1396 if (VT.isInteger() && !VT.isVector()) {
1397 APInt LHSZero, LHSOne;
1398 APInt RHSZero, RHSOne;
1399 APInt Mask = APInt::getAllOnesValue(VT.getScalarType().getSizeInBits());
1400 DAG.ComputeMaskedBits(N0, Mask, LHSZero, LHSOne);
1402 if (LHSZero.getBoolValue()) {
1403 DAG.ComputeMaskedBits(N1, Mask, RHSZero, RHSOne);
1405 // If all possibly-set bits on the LHS are clear on the RHS, return an OR.
1406 // If all possibly-set bits on the RHS are clear on the LHS, return an OR.
1407 if ((RHSZero & (~LHSZero & Mask)) == (~LHSZero & Mask) ||
1408 (LHSZero & (~RHSZero & Mask)) == (~RHSZero & Mask))
1409 return DAG.getNode(ISD::OR, N->getDebugLoc(), VT, N0, N1);
1413 // fold (add (shl (add x, c1), c2), ) -> (add (add (shl x, c2), c1<<c2), )
1414 if (N0.getOpcode() == ISD::SHL && N0.getNode()->hasOneUse()) {
1415 SDValue Result = combineShlAddConstant(N->getDebugLoc(), N0, N1, DAG);
1416 if (Result.getNode()) return Result;
1418 if (N1.getOpcode() == ISD::SHL && N1.getNode()->hasOneUse()) {
1419 SDValue Result = combineShlAddConstant(N->getDebugLoc(), N1, N0, DAG);
1420 if (Result.getNode()) return Result;
1423 // fold (add x, shl(0 - y, n)) -> sub(x, shl(y, n))
1424 if (N1.getOpcode() == ISD::SHL &&
1425 N1.getOperand(0).getOpcode() == ISD::SUB)
1426 if (ConstantSDNode *C =
1427 dyn_cast<ConstantSDNode>(N1.getOperand(0).getOperand(0)))
1428 if (C->getAPIntValue() == 0)
1429 return DAG.getNode(ISD::SUB, N->getDebugLoc(), VT, N0,
1430 DAG.getNode(ISD::SHL, N->getDebugLoc(), VT,
1431 N1.getOperand(0).getOperand(1),
1433 if (N0.getOpcode() == ISD::SHL &&
1434 N0.getOperand(0).getOpcode() == ISD::SUB)
1435 if (ConstantSDNode *C =
1436 dyn_cast<ConstantSDNode>(N0.getOperand(0).getOperand(0)))
1437 if (C->getAPIntValue() == 0)
1438 return DAG.getNode(ISD::SUB, N->getDebugLoc(), VT, N1,
1439 DAG.getNode(ISD::SHL, N->getDebugLoc(), VT,
1440 N0.getOperand(0).getOperand(1),
1443 if (N1.getOpcode() == ISD::AND) {
1444 SDValue AndOp0 = N1.getOperand(0);
1445 ConstantSDNode *AndOp1 = dyn_cast<ConstantSDNode>(N1->getOperand(1));
1446 unsigned NumSignBits = DAG.ComputeNumSignBits(AndOp0);
1447 unsigned DestBits = VT.getScalarType().getSizeInBits();
1449 // (add z, (and (sbbl x, x), 1)) -> (sub z, (sbbl x, x))
1450 // and similar xforms where the inner op is either ~0 or 0.
1451 if (NumSignBits == DestBits && AndOp1 && AndOp1->isOne()) {
1452 DebugLoc DL = N->getDebugLoc();
1453 return DAG.getNode(ISD::SUB, DL, VT, N->getOperand(0), AndOp0);
1457 // add (sext i1), X -> sub X, (zext i1)
1458 if (N0.getOpcode() == ISD::SIGN_EXTEND &&
1459 N0.getOperand(0).getValueType() == MVT::i1 &&
1460 !TLI.isOperationLegal(ISD::SIGN_EXTEND, MVT::i1)) {
1461 DebugLoc DL = N->getDebugLoc();
1462 SDValue ZExt = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0));
1463 return DAG.getNode(ISD::SUB, DL, VT, N1, ZExt);
1466 // add (adde 0, 0, glue), X -> adde X, 0, glue
1467 if (N0->hasOneUse() && isCarryMaterialization(N0))
1468 return DAG.getNode(ISD::ADDE, N->getDebugLoc(),
1469 DAG.getVTList(VT, MVT::Glue), N1, N0.getOperand(0),
1472 // add X, (adde 0, 0, glue) -> adde X, 0, glue
1473 if (N1->hasOneUse() && isCarryMaterialization(N1))
1474 return DAG.getNode(ISD::ADDE, N->getDebugLoc(),
1475 DAG.getVTList(VT, MVT::Glue), N0, N1.getOperand(0),
1481 SDValue DAGCombiner::visitADDC(SDNode *N) {
1482 SDValue N0 = N->getOperand(0);
1483 SDValue N1 = N->getOperand(1);
1484 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1485 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1486 EVT VT = N0.getValueType();
1488 // If the flag result is dead, turn this into an ADD.
1489 if (N->hasNUsesOfValue(0, 1))
1490 return CombineTo(N, DAG.getNode(ISD::ADD, N->getDebugLoc(), VT, N1, N0),
1491 DAG.getNode(ISD::CARRY_FALSE,
1492 N->getDebugLoc(), MVT::Glue));
1494 // canonicalize constant to RHS.
1496 return DAG.getNode(ISD::ADDC, N->getDebugLoc(), N->getVTList(), N1, N0);
1498 // fold (addc x, 0) -> x + no carry out
1499 if (N1C && N1C->isNullValue())
1500 return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE,
1501 N->getDebugLoc(), MVT::Glue));
1503 // fold (addc a, b) -> (or a, b), CARRY_FALSE iff a and b share no bits.
1504 APInt LHSZero, LHSOne;
1505 APInt RHSZero, RHSOne;
1506 APInt Mask = APInt::getAllOnesValue(VT.getScalarType().getSizeInBits());
1507 DAG.ComputeMaskedBits(N0, Mask, LHSZero, LHSOne);
1509 if (LHSZero.getBoolValue()) {
1510 DAG.ComputeMaskedBits(N1, Mask, RHSZero, RHSOne);
1512 // If all possibly-set bits on the LHS are clear on the RHS, return an OR.
1513 // If all possibly-set bits on the RHS are clear on the LHS, return an OR.
1514 if ((RHSZero & (~LHSZero & Mask)) == (~LHSZero & Mask) ||
1515 (LHSZero & (~RHSZero & Mask)) == (~RHSZero & Mask))
1516 return CombineTo(N, DAG.getNode(ISD::OR, N->getDebugLoc(), VT, N0, N1),
1517 DAG.getNode(ISD::CARRY_FALSE,
1518 N->getDebugLoc(), MVT::Glue));
1521 // addc (adde 0, 0, glue), X -> adde X, 0, glue
1522 if (N0->hasOneUse() && isCarryMaterialization(N0))
1523 return DAG.getNode(ISD::ADDE, N->getDebugLoc(), N->getVTList(), N1,
1524 DAG.getConstant(0, VT), N0.getOperand(2));
1526 // addc X, (adde 0, 0, glue) -> adde X, 0, glue
1527 if (N1->hasOneUse() && isCarryMaterialization(N1))
1528 return DAG.getNode(ISD::ADDE, N->getDebugLoc(), N->getVTList(), N0,
1529 DAG.getConstant(0, VT), N1.getOperand(2));
1534 SDValue DAGCombiner::visitADDE(SDNode *N) {
1535 SDValue N0 = N->getOperand(0);
1536 SDValue N1 = N->getOperand(1);
1537 SDValue CarryIn = N->getOperand(2);
1538 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1539 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1541 // If both operands are null we know that carry out will always be false.
1542 if (N0C && N0C->isNullValue() && N0 == N1)
1543 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), DAG.getNode(ISD::CARRY_FALSE,
1547 // canonicalize constant to RHS
1549 return DAG.getNode(ISD::ADDE, N->getDebugLoc(), N->getVTList(),
1552 // fold (adde x, y, false) -> (addc x, y)
1553 if (CarryIn.getOpcode() == ISD::CARRY_FALSE)
1554 return DAG.getNode(ISD::ADDC, N->getDebugLoc(), N->getVTList(), N1, N0);
1559 // Since it may not be valid to emit a fold to zero for vector initializers
1560 // check if we can before folding.
1561 static SDValue tryFoldToZero(DebugLoc DL, const TargetLowering &TLI, EVT VT,
1562 SelectionDAG &DAG, bool LegalOperations) {
1563 if (!VT.isVector()) {
1564 return DAG.getConstant(0, VT);
1565 } else if (!LegalOperations || TLI.isOperationLegal(ISD::BUILD_VECTOR, VT)) {
1566 // Produce a vector of zeros.
1567 SDValue El = DAG.getConstant(0, VT.getVectorElementType());
1568 std::vector<SDValue> Ops(VT.getVectorNumElements(), El);
1569 return DAG.getNode(ISD::BUILD_VECTOR, DL, VT,
1570 &Ops[0], Ops.size());
1575 SDValue DAGCombiner::visitSUB(SDNode *N) {
1576 SDValue N0 = N->getOperand(0);
1577 SDValue N1 = N->getOperand(1);
1578 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getNode());
1579 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
1580 EVT VT = N0.getValueType();
1583 if (VT.isVector()) {
1584 SDValue FoldedVOp = SimplifyVBinOp(N);
1585 if (FoldedVOp.getNode()) return FoldedVOp;
1588 // fold (sub x, x) -> 0
1589 // FIXME: Refactor this and xor and other similar operations together.
1591 return tryFoldToZero(N->getDebugLoc(), TLI, VT, DAG, LegalOperations);
1592 // fold (sub c1, c2) -> c1-c2
1594 return DAG.FoldConstantArithmetic(ISD::SUB, VT, N0C, N1C);
1595 // fold (sub x, c) -> (add x, -c)
1597 return DAG.getNode(ISD::ADD, N->getDebugLoc(), VT, N0,
1598 DAG.getConstant(-N1C->getAPIntValue(), VT));
1599 // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1)
1600 if (N0C && N0C->isAllOnesValue())
1601 return DAG.getNode(ISD::XOR, N->getDebugLoc(), VT, N1, N0);
1602 // fold A-(A-B) -> B
1603 if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(0))
1604 return N1.getOperand(1);
1605 // fold (A+B)-A -> B
1606 if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1)
1607 return N0.getOperand(1);
1608 // fold (A+B)-B -> A
1609 if (N0.getOpcode() == ISD::ADD && N0.getOperand(1) == N1)
1610 return N0.getOperand(0);
1611 // fold ((A+(B+or-C))-B) -> A+or-C
1612 if (N0.getOpcode() == ISD::ADD &&
1613 (N0.getOperand(1).getOpcode() == ISD::SUB ||
1614 N0.getOperand(1).getOpcode() == ISD::ADD) &&
1615 N0.getOperand(1).getOperand(0) == N1)
1616 return DAG.getNode(N0.getOperand(1).getOpcode(), N->getDebugLoc(), VT,
1617 N0.getOperand(0), N0.getOperand(1).getOperand(1));
1618 // fold ((A+(C+B))-B) -> A+C
1619 if (N0.getOpcode() == ISD::ADD &&
1620 N0.getOperand(1).getOpcode() == ISD::ADD &&
1621 N0.getOperand(1).getOperand(1) == N1)
1622 return DAG.getNode(ISD::ADD, N->getDebugLoc(), VT,
1623 N0.getOperand(0), N0.getOperand(1).getOperand(0));
1624 // fold ((A-(B-C))-C) -> A-B
1625 if (N0.getOpcode() == ISD::SUB &&
1626 N0.getOperand(1).getOpcode() == ISD::SUB &&
1627 N0.getOperand(1).getOperand(1) == N1)
1628 return DAG.getNode(ISD::SUB, N->getDebugLoc(), VT,
1629 N0.getOperand(0), N0.getOperand(1).getOperand(0));
1631 // If either operand of a sub is undef, the result is undef
1632 if (N0.getOpcode() == ISD::UNDEF)
1634 if (N1.getOpcode() == ISD::UNDEF)
1637 // If the relocation model supports it, consider symbol offsets.
1638 if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N0))
1639 if (!LegalOperations && TLI.isOffsetFoldingLegal(GA)) {
1640 // fold (sub Sym, c) -> Sym-c
1641 if (N1C && GA->getOpcode() == ISD::GlobalAddress)
1642 return DAG.getGlobalAddress(GA->getGlobal(), N1C->getDebugLoc(), VT,
1644 (uint64_t)N1C->getSExtValue());
1645 // fold (sub Sym+c1, Sym+c2) -> c1-c2
1646 if (GlobalAddressSDNode *GB = dyn_cast<GlobalAddressSDNode>(N1))
1647 if (GA->getGlobal() == GB->getGlobal())
1648 return DAG.getConstant((uint64_t)GA->getOffset() - GB->getOffset(),
1655 SDValue DAGCombiner::visitMUL(SDNode *N) {
1656 SDValue N0 = N->getOperand(0);
1657 SDValue N1 = N->getOperand(1);
1658 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1659 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1660 EVT VT = N0.getValueType();
1663 if (VT.isVector()) {
1664 SDValue FoldedVOp = SimplifyVBinOp(N);
1665 if (FoldedVOp.getNode()) return FoldedVOp;
1668 // fold (mul x, undef) -> 0
1669 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
1670 return DAG.getConstant(0, VT);
1671 // fold (mul c1, c2) -> c1*c2
1673 return DAG.FoldConstantArithmetic(ISD::MUL, VT, N0C, N1C);
1674 // canonicalize constant to RHS
1676 return DAG.getNode(ISD::MUL, N->getDebugLoc(), VT, N1, N0);
1677 // fold (mul x, 0) -> 0
1678 if (N1C && N1C->isNullValue())
1680 // fold (mul x, -1) -> 0-x
1681 if (N1C && N1C->isAllOnesValue())
1682 return DAG.getNode(ISD::SUB, N->getDebugLoc(), VT,
1683 DAG.getConstant(0, VT), N0);
1684 // fold (mul x, (1 << c)) -> x << c
1685 if (N1C && N1C->getAPIntValue().isPowerOf2())
1686 return DAG.getNode(ISD::SHL, N->getDebugLoc(), VT, N0,
1687 DAG.getConstant(N1C->getAPIntValue().logBase2(),
1688 getShiftAmountTy(N0.getValueType())));
1689 // fold (mul x, -(1 << c)) -> -(x << c) or (-x) << c
1690 if (N1C && (-N1C->getAPIntValue()).isPowerOf2()) {
1691 unsigned Log2Val = (-N1C->getAPIntValue()).logBase2();
1692 // FIXME: If the input is something that is easily negated (e.g. a
1693 // single-use add), we should put the negate there.
1694 return DAG.getNode(ISD::SUB, N->getDebugLoc(), VT,
1695 DAG.getConstant(0, VT),
1696 DAG.getNode(ISD::SHL, N->getDebugLoc(), VT, N0,
1697 DAG.getConstant(Log2Val,
1698 getShiftAmountTy(N0.getValueType()))));
1700 // (mul (shl X, c1), c2) -> (mul X, c2 << c1)
1701 if (N1C && N0.getOpcode() == ISD::SHL &&
1702 isa<ConstantSDNode>(N0.getOperand(1))) {
1703 SDValue C3 = DAG.getNode(ISD::SHL, N->getDebugLoc(), VT,
1704 N1, N0.getOperand(1));
1705 AddToWorkList(C3.getNode());
1706 return DAG.getNode(ISD::MUL, N->getDebugLoc(), VT,
1707 N0.getOperand(0), C3);
1710 // Change (mul (shl X, C), Y) -> (shl (mul X, Y), C) when the shift has one
1713 SDValue Sh(0,0), Y(0,0);
1714 // Check for both (mul (shl X, C), Y) and (mul Y, (shl X, C)).
1715 if (N0.getOpcode() == ISD::SHL && isa<ConstantSDNode>(N0.getOperand(1)) &&
1716 N0.getNode()->hasOneUse()) {
1718 } else if (N1.getOpcode() == ISD::SHL &&
1719 isa<ConstantSDNode>(N1.getOperand(1)) &&
1720 N1.getNode()->hasOneUse()) {
1725 SDValue Mul = DAG.getNode(ISD::MUL, N->getDebugLoc(), VT,
1726 Sh.getOperand(0), Y);
1727 return DAG.getNode(ISD::SHL, N->getDebugLoc(), VT,
1728 Mul, Sh.getOperand(1));
1732 // fold (mul (add x, c1), c2) -> (add (mul x, c2), c1*c2)
1733 if (N1C && N0.getOpcode() == ISD::ADD && N0.getNode()->hasOneUse() &&
1734 isa<ConstantSDNode>(N0.getOperand(1)))
1735 return DAG.getNode(ISD::ADD, N->getDebugLoc(), VT,
1736 DAG.getNode(ISD::MUL, N0.getDebugLoc(), VT,
1737 N0.getOperand(0), N1),
1738 DAG.getNode(ISD::MUL, N1.getDebugLoc(), VT,
1739 N0.getOperand(1), N1));
1742 SDValue RMUL = ReassociateOps(ISD::MUL, N->getDebugLoc(), N0, N1);
1743 if (RMUL.getNode() != 0)
1749 SDValue DAGCombiner::visitSDIV(SDNode *N) {
1750 SDValue N0 = N->getOperand(0);
1751 SDValue N1 = N->getOperand(1);
1752 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getNode());
1753 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
1754 EVT VT = N->getValueType(0);
1757 if (VT.isVector()) {
1758 SDValue FoldedVOp = SimplifyVBinOp(N);
1759 if (FoldedVOp.getNode()) return FoldedVOp;
1762 // fold (sdiv c1, c2) -> c1/c2
1763 if (N0C && N1C && !N1C->isNullValue())
1764 return DAG.FoldConstantArithmetic(ISD::SDIV, VT, N0C, N1C);
1765 // fold (sdiv X, 1) -> X
1766 if (N1C && N1C->getSExtValue() == 1LL)
1768 // fold (sdiv X, -1) -> 0-X
1769 if (N1C && N1C->isAllOnesValue())
1770 return DAG.getNode(ISD::SUB, N->getDebugLoc(), VT,
1771 DAG.getConstant(0, VT), N0);
1772 // If we know the sign bits of both operands are zero, strength reduce to a
1773 // udiv instead. Handles (X&15) /s 4 -> X&15 >> 2
1774 if (!VT.isVector()) {
1775 if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
1776 return DAG.getNode(ISD::UDIV, N->getDebugLoc(), N1.getValueType(),
1779 // fold (sdiv X, pow2) -> simple ops after legalize
1780 if (N1C && !N1C->isNullValue() && !TLI.isIntDivCheap() &&
1781 (isPowerOf2_64(N1C->getSExtValue()) ||
1782 isPowerOf2_64(-N1C->getSExtValue()))) {
1783 // If dividing by powers of two is cheap, then don't perform the following
1785 if (TLI.isPow2DivCheap())
1788 int64_t pow2 = N1C->getSExtValue();
1789 int64_t abs2 = pow2 > 0 ? pow2 : -pow2;
1790 unsigned lg2 = Log2_64(abs2);
1792 // Splat the sign bit into the register
1793 SDValue SGN = DAG.getNode(ISD::SRA, N->getDebugLoc(), VT, N0,
1794 DAG.getConstant(VT.getSizeInBits()-1,
1795 getShiftAmountTy(N0.getValueType())));
1796 AddToWorkList(SGN.getNode());
1798 // Add (N0 < 0) ? abs2 - 1 : 0;
1799 SDValue SRL = DAG.getNode(ISD::SRL, N->getDebugLoc(), VT, SGN,
1800 DAG.getConstant(VT.getSizeInBits() - lg2,
1801 getShiftAmountTy(SGN.getValueType())));
1802 SDValue ADD = DAG.getNode(ISD::ADD, N->getDebugLoc(), VT, N0, SRL);
1803 AddToWorkList(SRL.getNode());
1804 AddToWorkList(ADD.getNode()); // Divide by pow2
1805 SDValue SRA = DAG.getNode(ISD::SRA, N->getDebugLoc(), VT, ADD,
1806 DAG.getConstant(lg2, getShiftAmountTy(ADD.getValueType())));
1808 // If we're dividing by a positive value, we're done. Otherwise, we must
1809 // negate the result.
1813 AddToWorkList(SRA.getNode());
1814 return DAG.getNode(ISD::SUB, N->getDebugLoc(), VT,
1815 DAG.getConstant(0, VT), SRA);
1818 // if integer divide is expensive and we satisfy the requirements, emit an
1819 // alternate sequence.
1820 if (N1C && (N1C->getSExtValue() < -1 || N1C->getSExtValue() > 1) &&
1821 !TLI.isIntDivCheap()) {
1822 SDValue Op = BuildSDIV(N);
1823 if (Op.getNode()) return Op;
1827 if (N0.getOpcode() == ISD::UNDEF)
1828 return DAG.getConstant(0, VT);
1829 // X / undef -> undef
1830 if (N1.getOpcode() == ISD::UNDEF)
1836 SDValue DAGCombiner::visitUDIV(SDNode *N) {
1837 SDValue N0 = N->getOperand(0);
1838 SDValue N1 = N->getOperand(1);
1839 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getNode());
1840 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
1841 EVT VT = N->getValueType(0);
1844 if (VT.isVector()) {
1845 SDValue FoldedVOp = SimplifyVBinOp(N);
1846 if (FoldedVOp.getNode()) return FoldedVOp;
1849 // fold (udiv c1, c2) -> c1/c2
1850 if (N0C && N1C && !N1C->isNullValue())
1851 return DAG.FoldConstantArithmetic(ISD::UDIV, VT, N0C, N1C);
1852 // fold (udiv x, (1 << c)) -> x >>u c
1853 if (N1C && N1C->getAPIntValue().isPowerOf2())
1854 return DAG.getNode(ISD::SRL, N->getDebugLoc(), VT, N0,
1855 DAG.getConstant(N1C->getAPIntValue().logBase2(),
1856 getShiftAmountTy(N0.getValueType())));
1857 // fold (udiv x, (shl c, y)) -> x >>u (log2(c)+y) iff c is power of 2
1858 if (N1.getOpcode() == ISD::SHL) {
1859 if (ConstantSDNode *SHC = dyn_cast<ConstantSDNode>(N1.getOperand(0))) {
1860 if (SHC->getAPIntValue().isPowerOf2()) {
1861 EVT ADDVT = N1.getOperand(1).getValueType();
1862 SDValue Add = DAG.getNode(ISD::ADD, N->getDebugLoc(), ADDVT,
1864 DAG.getConstant(SHC->getAPIntValue()
1867 AddToWorkList(Add.getNode());
1868 return DAG.getNode(ISD::SRL, N->getDebugLoc(), VT, N0, Add);
1872 // fold (udiv x, c) -> alternate
1873 if (N1C && !N1C->isNullValue() && !TLI.isIntDivCheap()) {
1874 SDValue Op = BuildUDIV(N);
1875 if (Op.getNode()) return Op;
1879 if (N0.getOpcode() == ISD::UNDEF)
1880 return DAG.getConstant(0, VT);
1881 // X / undef -> undef
1882 if (N1.getOpcode() == ISD::UNDEF)
1888 SDValue DAGCombiner::visitSREM(SDNode *N) {
1889 SDValue N0 = N->getOperand(0);
1890 SDValue N1 = N->getOperand(1);
1891 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1892 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1893 EVT VT = N->getValueType(0);
1895 // fold (srem c1, c2) -> c1%c2
1896 if (N0C && N1C && !N1C->isNullValue())
1897 return DAG.FoldConstantArithmetic(ISD::SREM, VT, N0C, N1C);
1898 // If we know the sign bits of both operands are zero, strength reduce to a
1899 // urem instead. Handles (X & 0x0FFFFFFF) %s 16 -> X&15
1900 if (!VT.isVector()) {
1901 if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
1902 return DAG.getNode(ISD::UREM, N->getDebugLoc(), VT, N0, N1);
1905 // If X/C can be simplified by the division-by-constant logic, lower
1906 // X%C to the equivalent of X-X/C*C.
1907 if (N1C && !N1C->isNullValue()) {
1908 SDValue Div = DAG.getNode(ISD::SDIV, N->getDebugLoc(), VT, N0, N1);
1909 AddToWorkList(Div.getNode());
1910 SDValue OptimizedDiv = combine(Div.getNode());
1911 if (OptimizedDiv.getNode() && OptimizedDiv.getNode() != Div.getNode()) {
1912 SDValue Mul = DAG.getNode(ISD::MUL, N->getDebugLoc(), VT,
1914 SDValue Sub = DAG.getNode(ISD::SUB, N->getDebugLoc(), VT, N0, Mul);
1915 AddToWorkList(Mul.getNode());
1921 if (N0.getOpcode() == ISD::UNDEF)
1922 return DAG.getConstant(0, VT);
1923 // X % undef -> undef
1924 if (N1.getOpcode() == ISD::UNDEF)
1930 SDValue DAGCombiner::visitUREM(SDNode *N) {
1931 SDValue N0 = N->getOperand(0);
1932 SDValue N1 = N->getOperand(1);
1933 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1934 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1935 EVT VT = N->getValueType(0);
1937 // fold (urem c1, c2) -> c1%c2
1938 if (N0C && N1C && !N1C->isNullValue())
1939 return DAG.FoldConstantArithmetic(ISD::UREM, VT, N0C, N1C);
1940 // fold (urem x, pow2) -> (and x, pow2-1)
1941 if (N1C && !N1C->isNullValue() && N1C->getAPIntValue().isPowerOf2())
1942 return DAG.getNode(ISD::AND, N->getDebugLoc(), VT, N0,
1943 DAG.getConstant(N1C->getAPIntValue()-1,VT));
1944 // fold (urem x, (shl pow2, y)) -> (and x, (add (shl pow2, y), -1))
1945 if (N1.getOpcode() == ISD::SHL) {
1946 if (ConstantSDNode *SHC = dyn_cast<ConstantSDNode>(N1.getOperand(0))) {
1947 if (SHC->getAPIntValue().isPowerOf2()) {
1949 DAG.getNode(ISD::ADD, N->getDebugLoc(), VT, N1,
1950 DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()),
1952 AddToWorkList(Add.getNode());
1953 return DAG.getNode(ISD::AND, N->getDebugLoc(), VT, N0, Add);
1958 // If X/C can be simplified by the division-by-constant logic, lower
1959 // X%C to the equivalent of X-X/C*C.
1960 if (N1C && !N1C->isNullValue()) {
1961 SDValue Div = DAG.getNode(ISD::UDIV, N->getDebugLoc(), VT, N0, N1);
1962 AddToWorkList(Div.getNode());
1963 SDValue OptimizedDiv = combine(Div.getNode());
1964 if (OptimizedDiv.getNode() && OptimizedDiv.getNode() != Div.getNode()) {
1965 SDValue Mul = DAG.getNode(ISD::MUL, N->getDebugLoc(), VT,
1967 SDValue Sub = DAG.getNode(ISD::SUB, N->getDebugLoc(), VT, N0, Mul);
1968 AddToWorkList(Mul.getNode());
1974 if (N0.getOpcode() == ISD::UNDEF)
1975 return DAG.getConstant(0, VT);
1976 // X % undef -> undef
1977 if (N1.getOpcode() == ISD::UNDEF)
1983 SDValue DAGCombiner::visitMULHS(SDNode *N) {
1984 SDValue N0 = N->getOperand(0);
1985 SDValue N1 = N->getOperand(1);
1986 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1987 EVT VT = N->getValueType(0);
1988 DebugLoc DL = N->getDebugLoc();
1990 // fold (mulhs x, 0) -> 0
1991 if (N1C && N1C->isNullValue())
1993 // fold (mulhs x, 1) -> (sra x, size(x)-1)
1994 if (N1C && N1C->getAPIntValue() == 1)
1995 return DAG.getNode(ISD::SRA, N->getDebugLoc(), N0.getValueType(), N0,
1996 DAG.getConstant(N0.getValueType().getSizeInBits() - 1,
1997 getShiftAmountTy(N0.getValueType())));
1998 // fold (mulhs x, undef) -> 0
1999 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2000 return DAG.getConstant(0, VT);
2002 // If the type twice as wide is legal, transform the mulhs to a wider multiply
2004 if (VT.isSimple() && !VT.isVector()) {
2005 MVT Simple = VT.getSimpleVT();
2006 unsigned SimpleSize = Simple.getSizeInBits();
2007 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2008 if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2009 N0 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N0);
2010 N1 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N1);
2011 N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1);
2012 N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1,
2013 DAG.getConstant(SimpleSize, getShiftAmountTy(N1.getValueType())));
2014 return DAG.getNode(ISD::TRUNCATE, DL, VT, N1);
2021 SDValue DAGCombiner::visitMULHU(SDNode *N) {
2022 SDValue N0 = N->getOperand(0);
2023 SDValue N1 = N->getOperand(1);
2024 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2025 EVT VT = N->getValueType(0);
2026 DebugLoc DL = N->getDebugLoc();
2028 // fold (mulhu x, 0) -> 0
2029 if (N1C && N1C->isNullValue())
2031 // fold (mulhu x, 1) -> 0
2032 if (N1C && N1C->getAPIntValue() == 1)
2033 return DAG.getConstant(0, N0.getValueType());
2034 // fold (mulhu x, undef) -> 0
2035 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2036 return DAG.getConstant(0, VT);
2038 // If the type twice as wide is legal, transform the mulhu to a wider multiply
2040 if (VT.isSimple() && !VT.isVector()) {
2041 MVT Simple = VT.getSimpleVT();
2042 unsigned SimpleSize = Simple.getSizeInBits();
2043 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2044 if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2045 N0 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N0);
2046 N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N1);
2047 N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1);
2048 N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1,
2049 DAG.getConstant(SimpleSize, getShiftAmountTy(N1.getValueType())));
2050 return DAG.getNode(ISD::TRUNCATE, DL, VT, N1);
2057 /// SimplifyNodeWithTwoResults - Perform optimizations common to nodes that
2058 /// compute two values. LoOp and HiOp give the opcodes for the two computations
2059 /// that are being performed. Return true if a simplification was made.
2061 SDValue DAGCombiner::SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp,
2063 // If the high half is not needed, just compute the low half.
2064 bool HiExists = N->hasAnyUseOfValue(1);
2066 (!LegalOperations ||
2067 TLI.isOperationLegal(LoOp, N->getValueType(0)))) {
2068 SDValue Res = DAG.getNode(LoOp, N->getDebugLoc(), N->getValueType(0),
2069 N->op_begin(), N->getNumOperands());
2070 return CombineTo(N, Res, Res);
2073 // If the low half is not needed, just compute the high half.
2074 bool LoExists = N->hasAnyUseOfValue(0);
2076 (!LegalOperations ||
2077 TLI.isOperationLegal(HiOp, N->getValueType(1)))) {
2078 SDValue Res = DAG.getNode(HiOp, N->getDebugLoc(), N->getValueType(1),
2079 N->op_begin(), N->getNumOperands());
2080 return CombineTo(N, Res, Res);
2083 // If both halves are used, return as it is.
2084 if (LoExists && HiExists)
2087 // If the two computed results can be simplified separately, separate them.
2089 SDValue Lo = DAG.getNode(LoOp, N->getDebugLoc(), N->getValueType(0),
2090 N->op_begin(), N->getNumOperands());
2091 AddToWorkList(Lo.getNode());
2092 SDValue LoOpt = combine(Lo.getNode());
2093 if (LoOpt.getNode() && LoOpt.getNode() != Lo.getNode() &&
2094 (!LegalOperations ||
2095 TLI.isOperationLegal(LoOpt.getOpcode(), LoOpt.getValueType())))
2096 return CombineTo(N, LoOpt, LoOpt);
2100 SDValue Hi = DAG.getNode(HiOp, N->getDebugLoc(), N->getValueType(1),
2101 N->op_begin(), N->getNumOperands());
2102 AddToWorkList(Hi.getNode());
2103 SDValue HiOpt = combine(Hi.getNode());
2104 if (HiOpt.getNode() && HiOpt != Hi &&
2105 (!LegalOperations ||
2106 TLI.isOperationLegal(HiOpt.getOpcode(), HiOpt.getValueType())))
2107 return CombineTo(N, HiOpt, HiOpt);
2113 SDValue DAGCombiner::visitSMUL_LOHI(SDNode *N) {
2114 SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHS);
2115 if (Res.getNode()) return Res;
2117 EVT VT = N->getValueType(0);
2118 DebugLoc DL = N->getDebugLoc();
2120 // If the type twice as wide is legal, transform the mulhu to a wider multiply
2122 if (VT.isSimple() && !VT.isVector()) {
2123 MVT Simple = VT.getSimpleVT();
2124 unsigned SimpleSize = Simple.getSizeInBits();
2125 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2126 if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2127 SDValue Lo = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(0));
2128 SDValue Hi = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(1));
2129 Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi);
2130 // Compute the high part as N1.
2131 Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo,
2132 DAG.getConstant(SimpleSize, getShiftAmountTy(Lo.getValueType())));
2133 Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi);
2134 // Compute the low part as N0.
2135 Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo);
2136 return CombineTo(N, Lo, Hi);
2143 SDValue DAGCombiner::visitUMUL_LOHI(SDNode *N) {
2144 SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHU);
2145 if (Res.getNode()) return Res;
2147 EVT VT = N->getValueType(0);
2148 DebugLoc DL = N->getDebugLoc();
2150 // If the type twice as wide is legal, transform the mulhu to a wider multiply
2152 if (VT.isSimple() && !VT.isVector()) {
2153 MVT Simple = VT.getSimpleVT();
2154 unsigned SimpleSize = Simple.getSizeInBits();
2155 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2156 if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2157 SDValue Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(0));
2158 SDValue Hi = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(1));
2159 Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi);
2160 // Compute the high part as N1.
2161 Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo,
2162 DAG.getConstant(SimpleSize, getShiftAmountTy(Lo.getValueType())));
2163 Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi);
2164 // Compute the low part as N0.
2165 Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo);
2166 return CombineTo(N, Lo, Hi);
2173 SDValue DAGCombiner::visitSDIVREM(SDNode *N) {
2174 SDValue Res = SimplifyNodeWithTwoResults(N, ISD::SDIV, ISD::SREM);
2175 if (Res.getNode()) return Res;
2180 SDValue DAGCombiner::visitUDIVREM(SDNode *N) {
2181 SDValue Res = SimplifyNodeWithTwoResults(N, ISD::UDIV, ISD::UREM);
2182 if (Res.getNode()) return Res;
2187 /// SimplifyBinOpWithSameOpcodeHands - If this is a binary operator with
2188 /// two operands of the same opcode, try to simplify it.
2189 SDValue DAGCombiner::SimplifyBinOpWithSameOpcodeHands(SDNode *N) {
2190 SDValue N0 = N->getOperand(0), N1 = N->getOperand(1);
2191 EVT VT = N0.getValueType();
2192 assert(N0.getOpcode() == N1.getOpcode() && "Bad input!");
2194 // Bail early if none of these transforms apply.
2195 if (N0.getNode()->getNumOperands() == 0) return SDValue();
2197 // For each of OP in AND/OR/XOR:
2198 // fold (OP (zext x), (zext y)) -> (zext (OP x, y))
2199 // fold (OP (sext x), (sext y)) -> (sext (OP x, y))
2200 // fold (OP (aext x), (aext y)) -> (aext (OP x, y))
2201 // fold (OP (trunc x), (trunc y)) -> (trunc (OP x, y)) (if trunc isn't free)
2203 // do not sink logical op inside of a vector extend, since it may combine
2205 EVT Op0VT = N0.getOperand(0).getValueType();
2206 if ((N0.getOpcode() == ISD::ZERO_EXTEND ||
2207 N0.getOpcode() == ISD::SIGN_EXTEND ||
2208 // Avoid infinite looping with PromoteIntBinOp.
2209 (N0.getOpcode() == ISD::ANY_EXTEND &&
2210 (!LegalTypes || TLI.isTypeDesirableForOp(N->getOpcode(), Op0VT))) ||
2211 (N0.getOpcode() == ISD::TRUNCATE &&
2212 (!TLI.isZExtFree(VT, Op0VT) ||
2213 !TLI.isTruncateFree(Op0VT, VT)) &&
2214 TLI.isTypeLegal(Op0VT))) &&
2216 Op0VT == N1.getOperand(0).getValueType() &&
2217 (!LegalOperations || TLI.isOperationLegal(N->getOpcode(), Op0VT))) {
2218 SDValue ORNode = DAG.getNode(N->getOpcode(), N0.getDebugLoc(),
2219 N0.getOperand(0).getValueType(),
2220 N0.getOperand(0), N1.getOperand(0));
2221 AddToWorkList(ORNode.getNode());
2222 return DAG.getNode(N0.getOpcode(), N->getDebugLoc(), VT, ORNode);
2225 // For each of OP in SHL/SRL/SRA/AND...
2226 // fold (and (OP x, z), (OP y, z)) -> (OP (and x, y), z)
2227 // fold (or (OP x, z), (OP y, z)) -> (OP (or x, y), z)
2228 // fold (xor (OP x, z), (OP y, z)) -> (OP (xor x, y), z)
2229 if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL ||
2230 N0.getOpcode() == ISD::SRA || N0.getOpcode() == ISD::AND) &&
2231 N0.getOperand(1) == N1.getOperand(1)) {
2232 SDValue ORNode = DAG.getNode(N->getOpcode(), N0.getDebugLoc(),
2233 N0.getOperand(0).getValueType(),
2234 N0.getOperand(0), N1.getOperand(0));
2235 AddToWorkList(ORNode.getNode());
2236 return DAG.getNode(N0.getOpcode(), N->getDebugLoc(), VT,
2237 ORNode, N0.getOperand(1));
2243 SDValue DAGCombiner::visitAND(SDNode *N) {
2244 SDValue N0 = N->getOperand(0);
2245 SDValue N1 = N->getOperand(1);
2246 SDValue LL, LR, RL, RR, CC0, CC1;
2247 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
2248 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2249 EVT VT = N1.getValueType();
2250 unsigned BitWidth = VT.getScalarType().getSizeInBits();
2253 if (VT.isVector()) {
2254 SDValue FoldedVOp = SimplifyVBinOp(N);
2255 if (FoldedVOp.getNode()) return FoldedVOp;
2258 // fold (and x, undef) -> 0
2259 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2260 return DAG.getConstant(0, VT);
2261 // fold (and c1, c2) -> c1&c2
2263 return DAG.FoldConstantArithmetic(ISD::AND, VT, N0C, N1C);
2264 // canonicalize constant to RHS
2266 return DAG.getNode(ISD::AND, N->getDebugLoc(), VT, N1, N0);
2267 // fold (and x, -1) -> x
2268 if (N1C && N1C->isAllOnesValue())
2270 // if (and x, c) is known to be zero, return 0
2271 if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0),
2272 APInt::getAllOnesValue(BitWidth)))
2273 return DAG.getConstant(0, VT);
2275 SDValue RAND = ReassociateOps(ISD::AND, N->getDebugLoc(), N0, N1);
2276 if (RAND.getNode() != 0)
2278 // fold (and (or x, C), D) -> D if (C & D) == D
2279 if (N1C && N0.getOpcode() == ISD::OR)
2280 if (ConstantSDNode *ORI = dyn_cast<ConstantSDNode>(N0.getOperand(1)))
2281 if ((ORI->getAPIntValue() & N1C->getAPIntValue()) == N1C->getAPIntValue())
2283 // fold (and (any_ext V), c) -> (zero_ext V) if 'and' only clears top bits.
2284 if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
2285 SDValue N0Op0 = N0.getOperand(0);
2286 APInt Mask = ~N1C->getAPIntValue();
2287 Mask = Mask.trunc(N0Op0.getValueSizeInBits());
2288 if (DAG.MaskedValueIsZero(N0Op0, Mask)) {
2289 SDValue Zext = DAG.getNode(ISD::ZERO_EXTEND, N->getDebugLoc(),
2290 N0.getValueType(), N0Op0);
2292 // Replace uses of the AND with uses of the Zero extend node.
2295 // We actually want to replace all uses of the any_extend with the
2296 // zero_extend, to avoid duplicating things. This will later cause this
2297 // AND to be folded.
2298 CombineTo(N0.getNode(), Zext);
2299 return SDValue(N, 0); // Return N so it doesn't get rechecked!
2302 // fold (and (setcc x), (setcc y)) -> (setcc (and x, y))
2303 if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){
2304 ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get();
2305 ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get();
2307 if (LR == RR && isa<ConstantSDNode>(LR) && Op0 == Op1 &&
2308 LL.getValueType().isInteger()) {
2309 // fold (and (seteq X, 0), (seteq Y, 0)) -> (seteq (or X, Y), 0)
2310 if (cast<ConstantSDNode>(LR)->isNullValue() && Op1 == ISD::SETEQ) {
2311 SDValue ORNode = DAG.getNode(ISD::OR, N0.getDebugLoc(),
2312 LR.getValueType(), LL, RL);
2313 AddToWorkList(ORNode.getNode());
2314 return DAG.getSetCC(N->getDebugLoc(), VT, ORNode, LR, Op1);
2316 // fold (and (seteq X, -1), (seteq Y, -1)) -> (seteq (and X, Y), -1)
2317 if (cast<ConstantSDNode>(LR)->isAllOnesValue() && Op1 == ISD::SETEQ) {
2318 SDValue ANDNode = DAG.getNode(ISD::AND, N0.getDebugLoc(),
2319 LR.getValueType(), LL, RL);
2320 AddToWorkList(ANDNode.getNode());
2321 return DAG.getSetCC(N->getDebugLoc(), VT, ANDNode, LR, Op1);
2323 // fold (and (setgt X, -1), (setgt Y, -1)) -> (setgt (or X, Y), -1)
2324 if (cast<ConstantSDNode>(LR)->isAllOnesValue() && Op1 == ISD::SETGT) {
2325 SDValue ORNode = DAG.getNode(ISD::OR, N0.getDebugLoc(),
2326 LR.getValueType(), LL, RL);
2327 AddToWorkList(ORNode.getNode());
2328 return DAG.getSetCC(N->getDebugLoc(), VT, ORNode, LR, Op1);
2331 // canonicalize equivalent to ll == rl
2332 if (LL == RR && LR == RL) {
2333 Op1 = ISD::getSetCCSwappedOperands(Op1);
2336 if (LL == RL && LR == RR) {
2337 bool isInteger = LL.getValueType().isInteger();
2338 ISD::CondCode Result = ISD::getSetCCAndOperation(Op0, Op1, isInteger);
2339 if (Result != ISD::SETCC_INVALID &&
2340 (!LegalOperations || TLI.isCondCodeLegal(Result, LL.getValueType())))
2341 return DAG.getSetCC(N->getDebugLoc(), N0.getValueType(),
2346 // Simplify: (and (op x...), (op y...)) -> (op (and x, y))
2347 if (N0.getOpcode() == N1.getOpcode()) {
2348 SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
2349 if (Tmp.getNode()) return Tmp;
2352 // fold (and (sign_extend_inreg x, i16 to i32), 1) -> (and x, 1)
2353 // fold (and (sra)) -> (and (srl)) when possible.
2354 if (!VT.isVector() &&
2355 SimplifyDemandedBits(SDValue(N, 0)))
2356 return SDValue(N, 0);
2358 // fold (zext_inreg (extload x)) -> (zextload x)
2359 if (ISD::isEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode())) {
2360 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
2361 EVT MemVT = LN0->getMemoryVT();
2362 // If we zero all the possible extended bits, then we can turn this into
2363 // a zextload if we are running before legalize or the operation is legal.
2364 unsigned BitWidth = N1.getValueType().getScalarType().getSizeInBits();
2365 if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth,
2366 BitWidth - MemVT.getScalarType().getSizeInBits())) &&
2367 ((!LegalOperations && !LN0->isVolatile()) ||
2368 TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT))) {
2369 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, N0.getDebugLoc(), VT,
2370 LN0->getChain(), LN0->getBasePtr(),
2371 LN0->getPointerInfo(), MemVT,
2372 LN0->isVolatile(), LN0->isNonTemporal(),
2373 LN0->getAlignment());
2375 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
2376 return SDValue(N, 0); // Return N so it doesn't get rechecked!
2379 // fold (zext_inreg (sextload x)) -> (zextload x) iff load has one use
2380 if (ISD::isSEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
2382 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
2383 EVT MemVT = LN0->getMemoryVT();
2384 // If we zero all the possible extended bits, then we can turn this into
2385 // a zextload if we are running before legalize or the operation is legal.
2386 unsigned BitWidth = N1.getValueType().getScalarType().getSizeInBits();
2387 if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth,
2388 BitWidth - MemVT.getScalarType().getSizeInBits())) &&
2389 ((!LegalOperations && !LN0->isVolatile()) ||
2390 TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT))) {
2391 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, N0.getDebugLoc(), VT,
2393 LN0->getBasePtr(), LN0->getPointerInfo(),
2395 LN0->isVolatile(), LN0->isNonTemporal(),
2396 LN0->getAlignment());
2398 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
2399 return SDValue(N, 0); // Return N so it doesn't get rechecked!
2403 // fold (and (load x), 255) -> (zextload x, i8)
2404 // fold (and (extload x, i16), 255) -> (zextload x, i8)
2405 // fold (and (any_ext (extload x, i16)), 255) -> (zextload x, i8)
2406 if (N1C && (N0.getOpcode() == ISD::LOAD ||
2407 (N0.getOpcode() == ISD::ANY_EXTEND &&
2408 N0.getOperand(0).getOpcode() == ISD::LOAD))) {
2409 bool HasAnyExt = N0.getOpcode() == ISD::ANY_EXTEND;
2410 LoadSDNode *LN0 = HasAnyExt
2411 ? cast<LoadSDNode>(N0.getOperand(0))
2412 : cast<LoadSDNode>(N0);
2413 if (LN0->getExtensionType() != ISD::SEXTLOAD &&
2414 LN0->isUnindexed() && N0.hasOneUse() && LN0->hasOneUse()) {
2415 uint32_t ActiveBits = N1C->getAPIntValue().getActiveBits();
2416 if (ActiveBits > 0 && APIntOps::isMask(ActiveBits, N1C->getAPIntValue())){
2417 EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), ActiveBits);
2418 EVT LoadedVT = LN0->getMemoryVT();
2420 if (ExtVT == LoadedVT &&
2421 (!LegalOperations || TLI.isLoadExtLegal(ISD::ZEXTLOAD, ExtVT))) {
2422 EVT LoadResultTy = HasAnyExt ? LN0->getValueType(0) : VT;
2425 DAG.getExtLoad(ISD::ZEXTLOAD, LN0->getDebugLoc(), LoadResultTy,
2426 LN0->getChain(), LN0->getBasePtr(),
2427 LN0->getPointerInfo(),
2428 ExtVT, LN0->isVolatile(), LN0->isNonTemporal(),
2429 LN0->getAlignment());
2431 CombineTo(LN0, NewLoad, NewLoad.getValue(1));
2432 return SDValue(N, 0); // Return N so it doesn't get rechecked!
2435 // Do not change the width of a volatile load.
2436 // Do not generate loads of non-round integer types since these can
2437 // be expensive (and would be wrong if the type is not byte sized).
2438 if (!LN0->isVolatile() && LoadedVT.bitsGT(ExtVT) && ExtVT.isRound() &&
2439 (!LegalOperations || TLI.isLoadExtLegal(ISD::ZEXTLOAD, ExtVT))) {
2440 EVT PtrType = LN0->getOperand(1).getValueType();
2442 unsigned Alignment = LN0->getAlignment();
2443 SDValue NewPtr = LN0->getBasePtr();
2445 // For big endian targets, we need to add an offset to the pointer
2446 // to load the correct bytes. For little endian systems, we merely
2447 // need to read fewer bytes from the same pointer.
2448 if (TLI.isBigEndian()) {
2449 unsigned LVTStoreBytes = LoadedVT.getStoreSize();
2450 unsigned EVTStoreBytes = ExtVT.getStoreSize();
2451 unsigned PtrOff = LVTStoreBytes - EVTStoreBytes;
2452 NewPtr = DAG.getNode(ISD::ADD, LN0->getDebugLoc(), PtrType,
2453 NewPtr, DAG.getConstant(PtrOff, PtrType));
2454 Alignment = MinAlign(Alignment, PtrOff);
2457 AddToWorkList(NewPtr.getNode());
2459 EVT LoadResultTy = HasAnyExt ? LN0->getValueType(0) : VT;
2461 DAG.getExtLoad(ISD::ZEXTLOAD, LN0->getDebugLoc(), LoadResultTy,
2462 LN0->getChain(), NewPtr,
2463 LN0->getPointerInfo(),
2464 ExtVT, LN0->isVolatile(), LN0->isNonTemporal(),
2467 CombineTo(LN0, Load, Load.getValue(1));
2468 return SDValue(N, 0); // Return N so it doesn't get rechecked!
2477 SDValue DAGCombiner::visitOR(SDNode *N) {
2478 SDValue N0 = N->getOperand(0);
2479 SDValue N1 = N->getOperand(1);
2480 SDValue LL, LR, RL, RR, CC0, CC1;
2481 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
2482 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2483 EVT VT = N1.getValueType();
2486 if (VT.isVector()) {
2487 SDValue FoldedVOp = SimplifyVBinOp(N);
2488 if (FoldedVOp.getNode()) return FoldedVOp;
2491 // fold (or x, undef) -> -1
2492 if (!LegalOperations &&
2493 (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)) {
2494 EVT EltVT = VT.isVector() ? VT.getVectorElementType() : VT;
2495 return DAG.getConstant(APInt::getAllOnesValue(EltVT.getSizeInBits()), VT);
2497 // fold (or c1, c2) -> c1|c2
2499 return DAG.FoldConstantArithmetic(ISD::OR, VT, N0C, N1C);
2500 // canonicalize constant to RHS
2502 return DAG.getNode(ISD::OR, N->getDebugLoc(), VT, N1, N0);
2503 // fold (or x, 0) -> x
2504 if (N1C && N1C->isNullValue())
2506 // fold (or x, -1) -> -1
2507 if (N1C && N1C->isAllOnesValue())
2509 // fold (or x, c) -> c iff (x & ~c) == 0
2510 if (N1C && DAG.MaskedValueIsZero(N0, ~N1C->getAPIntValue()))
2513 SDValue ROR = ReassociateOps(ISD::OR, N->getDebugLoc(), N0, N1);
2514 if (ROR.getNode() != 0)
2516 // Canonicalize (or (and X, c1), c2) -> (and (or X, c2), c1|c2)
2517 // iff (c1 & c2) == 0.
2518 if (N1C && N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() &&
2519 isa<ConstantSDNode>(N0.getOperand(1))) {
2520 ConstantSDNode *C1 = cast<ConstantSDNode>(N0.getOperand(1));
2521 if ((C1->getAPIntValue() & N1C->getAPIntValue()) != 0)
2522 return DAG.getNode(ISD::AND, N->getDebugLoc(), VT,
2523 DAG.getNode(ISD::OR, N0.getDebugLoc(), VT,
2524 N0.getOperand(0), N1),
2525 DAG.FoldConstantArithmetic(ISD::OR, VT, N1C, C1));
2527 // fold (or (setcc x), (setcc y)) -> (setcc (or x, y))
2528 if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){
2529 ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get();
2530 ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get();
2532 if (LR == RR && isa<ConstantSDNode>(LR) && Op0 == Op1 &&
2533 LL.getValueType().isInteger()) {
2534 // fold (or (setne X, 0), (setne Y, 0)) -> (setne (or X, Y), 0)
2535 // fold (or (setlt X, 0), (setlt Y, 0)) -> (setne (or X, Y), 0)
2536 if (cast<ConstantSDNode>(LR)->isNullValue() &&
2537 (Op1 == ISD::SETNE || Op1 == ISD::SETLT)) {
2538 SDValue ORNode = DAG.getNode(ISD::OR, LR.getDebugLoc(),
2539 LR.getValueType(), LL, RL);
2540 AddToWorkList(ORNode.getNode());
2541 return DAG.getSetCC(N->getDebugLoc(), VT, ORNode, LR, Op1);
2543 // fold (or (setne X, -1), (setne Y, -1)) -> (setne (and X, Y), -1)
2544 // fold (or (setgt X, -1), (setgt Y -1)) -> (setgt (and X, Y), -1)
2545 if (cast<ConstantSDNode>(LR)->isAllOnesValue() &&
2546 (Op1 == ISD::SETNE || Op1 == ISD::SETGT)) {
2547 SDValue ANDNode = DAG.getNode(ISD::AND, LR.getDebugLoc(),
2548 LR.getValueType(), LL, RL);
2549 AddToWorkList(ANDNode.getNode());
2550 return DAG.getSetCC(N->getDebugLoc(), VT, ANDNode, LR, Op1);
2553 // canonicalize equivalent to ll == rl
2554 if (LL == RR && LR == RL) {
2555 Op1 = ISD::getSetCCSwappedOperands(Op1);
2558 if (LL == RL && LR == RR) {
2559 bool isInteger = LL.getValueType().isInteger();
2560 ISD::CondCode Result = ISD::getSetCCOrOperation(Op0, Op1, isInteger);
2561 if (Result != ISD::SETCC_INVALID &&
2562 (!LegalOperations || TLI.isCondCodeLegal(Result, LL.getValueType())))
2563 return DAG.getSetCC(N->getDebugLoc(), N0.getValueType(),
2568 // Simplify: (or (op x...), (op y...)) -> (op (or x, y))
2569 if (N0.getOpcode() == N1.getOpcode()) {
2570 SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
2571 if (Tmp.getNode()) return Tmp;
2574 // (or (and X, C1), (and Y, C2)) -> (and (or X, Y), C3) if possible.
2575 if (N0.getOpcode() == ISD::AND &&
2576 N1.getOpcode() == ISD::AND &&
2577 N0.getOperand(1).getOpcode() == ISD::Constant &&
2578 N1.getOperand(1).getOpcode() == ISD::Constant &&
2579 // Don't increase # computations.
2580 (N0.getNode()->hasOneUse() || N1.getNode()->hasOneUse())) {
2581 // We can only do this xform if we know that bits from X that are set in C2
2582 // but not in C1 are already zero. Likewise for Y.
2583 const APInt &LHSMask =
2584 cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
2585 const APInt &RHSMask =
2586 cast<ConstantSDNode>(N1.getOperand(1))->getAPIntValue();
2588 if (DAG.MaskedValueIsZero(N0.getOperand(0), RHSMask&~LHSMask) &&
2589 DAG.MaskedValueIsZero(N1.getOperand(0), LHSMask&~RHSMask)) {
2590 SDValue X = DAG.getNode(ISD::OR, N0.getDebugLoc(), VT,
2591 N0.getOperand(0), N1.getOperand(0));
2592 return DAG.getNode(ISD::AND, N->getDebugLoc(), VT, X,
2593 DAG.getConstant(LHSMask | RHSMask, VT));
2597 // See if this is some rotate idiom.
2598 if (SDNode *Rot = MatchRotate(N0, N1, N->getDebugLoc()))
2599 return SDValue(Rot, 0);
2601 // Simplify the operands using demanded-bits information.
2602 if (!VT.isVector() &&
2603 SimplifyDemandedBits(SDValue(N, 0)))
2604 return SDValue(N, 0);
2609 /// MatchRotateHalf - Match "(X shl/srl V1) & V2" where V2 may not be present.
2610 static bool MatchRotateHalf(SDValue Op, SDValue &Shift, SDValue &Mask) {
2611 if (Op.getOpcode() == ISD::AND) {
2612 if (isa<ConstantSDNode>(Op.getOperand(1))) {
2613 Mask = Op.getOperand(1);
2614 Op = Op.getOperand(0);
2620 if (Op.getOpcode() == ISD::SRL || Op.getOpcode() == ISD::SHL) {
2628 // MatchRotate - Handle an 'or' of two operands. If this is one of the many
2629 // idioms for rotate, and if the target supports rotation instructions, generate
2631 SDNode *DAGCombiner::MatchRotate(SDValue LHS, SDValue RHS, DebugLoc DL) {
2632 // Must be a legal type. Expanded 'n promoted things won't work with rotates.
2633 EVT VT = LHS.getValueType();
2634 if (!TLI.isTypeLegal(VT)) return 0;
2636 // The target must have at least one rotate flavor.
2637 bool HasROTL = TLI.isOperationLegalOrCustom(ISD::ROTL, VT);
2638 bool HasROTR = TLI.isOperationLegalOrCustom(ISD::ROTR, VT);
2639 if (!HasROTL && !HasROTR) return 0;
2641 // Match "(X shl/srl V1) & V2" where V2 may not be present.
2642 SDValue LHSShift; // The shift.
2643 SDValue LHSMask; // AND value if any.
2644 if (!MatchRotateHalf(LHS, LHSShift, LHSMask))
2645 return 0; // Not part of a rotate.
2647 SDValue RHSShift; // The shift.
2648 SDValue RHSMask; // AND value if any.
2649 if (!MatchRotateHalf(RHS, RHSShift, RHSMask))
2650 return 0; // Not part of a rotate.
2652 if (LHSShift.getOperand(0) != RHSShift.getOperand(0))
2653 return 0; // Not shifting the same value.
2655 if (LHSShift.getOpcode() == RHSShift.getOpcode())
2656 return 0; // Shifts must disagree.
2658 // Canonicalize shl to left side in a shl/srl pair.
2659 if (RHSShift.getOpcode() == ISD::SHL) {
2660 std::swap(LHS, RHS);
2661 std::swap(LHSShift, RHSShift);
2662 std::swap(LHSMask , RHSMask );
2665 unsigned OpSizeInBits = VT.getSizeInBits();
2666 SDValue LHSShiftArg = LHSShift.getOperand(0);
2667 SDValue LHSShiftAmt = LHSShift.getOperand(1);
2668 SDValue RHSShiftAmt = RHSShift.getOperand(1);
2670 // fold (or (shl x, C1), (srl x, C2)) -> (rotl x, C1)
2671 // fold (or (shl x, C1), (srl x, C2)) -> (rotr x, C2)
2672 if (LHSShiftAmt.getOpcode() == ISD::Constant &&
2673 RHSShiftAmt.getOpcode() == ISD::Constant) {
2674 uint64_t LShVal = cast<ConstantSDNode>(LHSShiftAmt)->getZExtValue();
2675 uint64_t RShVal = cast<ConstantSDNode>(RHSShiftAmt)->getZExtValue();
2676 if ((LShVal + RShVal) != OpSizeInBits)
2681 Rot = DAG.getNode(ISD::ROTL, DL, VT, LHSShiftArg, LHSShiftAmt);
2683 Rot = DAG.getNode(ISD::ROTR, DL, VT, LHSShiftArg, RHSShiftAmt);
2685 // If there is an AND of either shifted operand, apply it to the result.
2686 if (LHSMask.getNode() || RHSMask.getNode()) {
2687 APInt Mask = APInt::getAllOnesValue(OpSizeInBits);
2689 if (LHSMask.getNode()) {
2690 APInt RHSBits = APInt::getLowBitsSet(OpSizeInBits, LShVal);
2691 Mask &= cast<ConstantSDNode>(LHSMask)->getAPIntValue() | RHSBits;
2693 if (RHSMask.getNode()) {
2694 APInt LHSBits = APInt::getHighBitsSet(OpSizeInBits, RShVal);
2695 Mask &= cast<ConstantSDNode>(RHSMask)->getAPIntValue() | LHSBits;
2698 Rot = DAG.getNode(ISD::AND, DL, VT, Rot, DAG.getConstant(Mask, VT));
2701 return Rot.getNode();
2704 // If there is a mask here, and we have a variable shift, we can't be sure
2705 // that we're masking out the right stuff.
2706 if (LHSMask.getNode() || RHSMask.getNode())
2709 // fold (or (shl x, y), (srl x, (sub 32, y))) -> (rotl x, y)
2710 // fold (or (shl x, y), (srl x, (sub 32, y))) -> (rotr x, (sub 32, y))
2711 if (RHSShiftAmt.getOpcode() == ISD::SUB &&
2712 LHSShiftAmt == RHSShiftAmt.getOperand(1)) {
2713 if (ConstantSDNode *SUBC =
2714 dyn_cast<ConstantSDNode>(RHSShiftAmt.getOperand(0))) {
2715 if (SUBC->getAPIntValue() == OpSizeInBits) {
2717 return DAG.getNode(ISD::ROTL, DL, VT,
2718 LHSShiftArg, LHSShiftAmt).getNode();
2720 return DAG.getNode(ISD::ROTR, DL, VT,
2721 LHSShiftArg, RHSShiftAmt).getNode();
2726 // fold (or (shl x, (sub 32, y)), (srl x, r)) -> (rotr x, y)
2727 // fold (or (shl x, (sub 32, y)), (srl x, r)) -> (rotl x, (sub 32, y))
2728 if (LHSShiftAmt.getOpcode() == ISD::SUB &&
2729 RHSShiftAmt == LHSShiftAmt.getOperand(1)) {
2730 if (ConstantSDNode *SUBC =
2731 dyn_cast<ConstantSDNode>(LHSShiftAmt.getOperand(0))) {
2732 if (SUBC->getAPIntValue() == OpSizeInBits) {
2734 return DAG.getNode(ISD::ROTR, DL, VT,
2735 LHSShiftArg, RHSShiftAmt).getNode();
2737 return DAG.getNode(ISD::ROTL, DL, VT,
2738 LHSShiftArg, LHSShiftAmt).getNode();
2743 // Look for sign/zext/any-extended or truncate cases:
2744 if ((LHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND
2745 || LHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND
2746 || LHSShiftAmt.getOpcode() == ISD::ANY_EXTEND
2747 || LHSShiftAmt.getOpcode() == ISD::TRUNCATE) &&
2748 (RHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND
2749 || RHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND
2750 || RHSShiftAmt.getOpcode() == ISD::ANY_EXTEND
2751 || RHSShiftAmt.getOpcode() == ISD::TRUNCATE)) {
2752 SDValue LExtOp0 = LHSShiftAmt.getOperand(0);
2753 SDValue RExtOp0 = RHSShiftAmt.getOperand(0);
2754 if (RExtOp0.getOpcode() == ISD::SUB &&
2755 RExtOp0.getOperand(1) == LExtOp0) {
2756 // fold (or (shl x, (*ext y)), (srl x, (*ext (sub 32, y)))) ->
2758 // fold (or (shl x, (*ext y)), (srl x, (*ext (sub 32, y)))) ->
2759 // (rotr x, (sub 32, y))
2760 if (ConstantSDNode *SUBC =
2761 dyn_cast<ConstantSDNode>(RExtOp0.getOperand(0))) {
2762 if (SUBC->getAPIntValue() == OpSizeInBits) {
2763 return DAG.getNode(HasROTL ? ISD::ROTL : ISD::ROTR, DL, VT,
2765 HasROTL ? LHSShiftAmt : RHSShiftAmt).getNode();
2768 } else if (LExtOp0.getOpcode() == ISD::SUB &&
2769 RExtOp0 == LExtOp0.getOperand(1)) {
2770 // fold (or (shl x, (*ext (sub 32, y))), (srl x, (*ext y))) ->
2772 // fold (or (shl x, (*ext (sub 32, y))), (srl x, (*ext y))) ->
2773 // (rotl x, (sub 32, y))
2774 if (ConstantSDNode *SUBC =
2775 dyn_cast<ConstantSDNode>(LExtOp0.getOperand(0))) {
2776 if (SUBC->getAPIntValue() == OpSizeInBits) {
2777 return DAG.getNode(HasROTR ? ISD::ROTR : ISD::ROTL, DL, VT,
2779 HasROTR ? RHSShiftAmt : LHSShiftAmt).getNode();
2788 SDValue DAGCombiner::visitXOR(SDNode *N) {
2789 SDValue N0 = N->getOperand(0);
2790 SDValue N1 = N->getOperand(1);
2791 SDValue LHS, RHS, CC;
2792 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
2793 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2794 EVT VT = N0.getValueType();
2797 if (VT.isVector()) {
2798 SDValue FoldedVOp = SimplifyVBinOp(N);
2799 if (FoldedVOp.getNode()) return FoldedVOp;
2802 // fold (xor undef, undef) -> 0. This is a common idiom (misuse).
2803 if (N0.getOpcode() == ISD::UNDEF && N1.getOpcode() == ISD::UNDEF)
2804 return DAG.getConstant(0, VT);
2805 // fold (xor x, undef) -> undef
2806 if (N0.getOpcode() == ISD::UNDEF)
2808 if (N1.getOpcode() == ISD::UNDEF)
2810 // fold (xor c1, c2) -> c1^c2
2812 return DAG.FoldConstantArithmetic(ISD::XOR, VT, N0C, N1C);
2813 // canonicalize constant to RHS
2815 return DAG.getNode(ISD::XOR, N->getDebugLoc(), VT, N1, N0);
2816 // fold (xor x, 0) -> x
2817 if (N1C && N1C->isNullValue())
2820 SDValue RXOR = ReassociateOps(ISD::XOR, N->getDebugLoc(), N0, N1);
2821 if (RXOR.getNode() != 0)
2824 // fold !(x cc y) -> (x !cc y)
2825 if (N1C && N1C->getAPIntValue() == 1 && isSetCCEquivalent(N0, LHS, RHS, CC)) {
2826 bool isInt = LHS.getValueType().isInteger();
2827 ISD::CondCode NotCC = ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(),
2830 if (!LegalOperations || TLI.isCondCodeLegal(NotCC, LHS.getValueType())) {
2831 switch (N0.getOpcode()) {
2833 llvm_unreachable("Unhandled SetCC Equivalent!");
2835 return DAG.getSetCC(N->getDebugLoc(), VT, LHS, RHS, NotCC);
2836 case ISD::SELECT_CC:
2837 return DAG.getSelectCC(N->getDebugLoc(), LHS, RHS, N0.getOperand(2),
2838 N0.getOperand(3), NotCC);
2843 // fold (not (zext (setcc x, y))) -> (zext (not (setcc x, y)))
2844 if (N1C && N1C->getAPIntValue() == 1 && N0.getOpcode() == ISD::ZERO_EXTEND &&
2845 N0.getNode()->hasOneUse() &&
2846 isSetCCEquivalent(N0.getOperand(0), LHS, RHS, CC)){
2847 SDValue V = N0.getOperand(0);
2848 V = DAG.getNode(ISD::XOR, N0.getDebugLoc(), V.getValueType(), V,
2849 DAG.getConstant(1, V.getValueType()));
2850 AddToWorkList(V.getNode());
2851 return DAG.getNode(ISD::ZERO_EXTEND, N->getDebugLoc(), VT, V);
2854 // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are setcc
2855 if (N1C && N1C->getAPIntValue() == 1 && VT == MVT::i1 &&
2856 (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
2857 SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
2858 if (isOneUseSetCC(RHS) || isOneUseSetCC(LHS)) {
2859 unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
2860 LHS = DAG.getNode(ISD::XOR, LHS.getDebugLoc(), VT, LHS, N1); // LHS = ~LHS
2861 RHS = DAG.getNode(ISD::XOR, RHS.getDebugLoc(), VT, RHS, N1); // RHS = ~RHS
2862 AddToWorkList(LHS.getNode()); AddToWorkList(RHS.getNode());
2863 return DAG.getNode(NewOpcode, N->getDebugLoc(), VT, LHS, RHS);
2866 // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are constants
2867 if (N1C && N1C->isAllOnesValue() &&
2868 (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
2869 SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
2870 if (isa<ConstantSDNode>(RHS) || isa<ConstantSDNode>(LHS)) {
2871 unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
2872 LHS = DAG.getNode(ISD::XOR, LHS.getDebugLoc(), VT, LHS, N1); // LHS = ~LHS
2873 RHS = DAG.getNode(ISD::XOR, RHS.getDebugLoc(), VT, RHS, N1); // RHS = ~RHS
2874 AddToWorkList(LHS.getNode()); AddToWorkList(RHS.getNode());
2875 return DAG.getNode(NewOpcode, N->getDebugLoc(), VT, LHS, RHS);
2878 // fold (xor (xor x, c1), c2) -> (xor x, (xor c1, c2))
2879 if (N1C && N0.getOpcode() == ISD::XOR) {
2880 ConstantSDNode *N00C = dyn_cast<ConstantSDNode>(N0.getOperand(0));
2881 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
2883 return DAG.getNode(ISD::XOR, N->getDebugLoc(), VT, N0.getOperand(1),
2884 DAG.getConstant(N1C->getAPIntValue() ^
2885 N00C->getAPIntValue(), VT));
2887 return DAG.getNode(ISD::XOR, N->getDebugLoc(), VT, N0.getOperand(0),
2888 DAG.getConstant(N1C->getAPIntValue() ^
2889 N01C->getAPIntValue(), VT));
2891 // fold (xor x, x) -> 0
2893 return tryFoldToZero(N->getDebugLoc(), TLI, VT, DAG, LegalOperations);
2895 // Simplify: xor (op x...), (op y...) -> (op (xor x, y))
2896 if (N0.getOpcode() == N1.getOpcode()) {
2897 SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
2898 if (Tmp.getNode()) return Tmp;
2901 // Simplify the expression using non-local knowledge.
2902 if (!VT.isVector() &&
2903 SimplifyDemandedBits(SDValue(N, 0)))
2904 return SDValue(N, 0);
2909 /// visitShiftByConstant - Handle transforms common to the three shifts, when
2910 /// the shift amount is a constant.
2911 SDValue DAGCombiner::visitShiftByConstant(SDNode *N, unsigned Amt) {
2912 SDNode *LHS = N->getOperand(0).getNode();
2913 if (!LHS->hasOneUse()) return SDValue();
2915 // We want to pull some binops through shifts, so that we have (and (shift))
2916 // instead of (shift (and)), likewise for add, or, xor, etc. This sort of
2917 // thing happens with address calculations, so it's important to canonicalize
2919 bool HighBitSet = false; // Can we transform this if the high bit is set?
2921 switch (LHS->getOpcode()) {
2922 default: return SDValue();
2925 HighBitSet = false; // We can only transform sra if the high bit is clear.
2928 HighBitSet = true; // We can only transform sra if the high bit is set.
2931 if (N->getOpcode() != ISD::SHL)
2932 return SDValue(); // only shl(add) not sr[al](add).
2933 HighBitSet = false; // We can only transform sra if the high bit is clear.
2937 // We require the RHS of the binop to be a constant as well.
2938 ConstantSDNode *BinOpCst = dyn_cast<ConstantSDNode>(LHS->getOperand(1));
2939 if (!BinOpCst) return SDValue();
2941 // FIXME: disable this unless the input to the binop is a shift by a constant.
2942 // If it is not a shift, it pessimizes some common cases like:
2944 // void foo(int *X, int i) { X[i & 1235] = 1; }
2945 // int bar(int *X, int i) { return X[i & 255]; }
2946 SDNode *BinOpLHSVal = LHS->getOperand(0).getNode();
2947 if ((BinOpLHSVal->getOpcode() != ISD::SHL &&
2948 BinOpLHSVal->getOpcode() != ISD::SRA &&
2949 BinOpLHSVal->getOpcode() != ISD::SRL) ||
2950 !isa<ConstantSDNode>(BinOpLHSVal->getOperand(1)))
2953 EVT VT = N->getValueType(0);
2955 // If this is a signed shift right, and the high bit is modified by the
2956 // logical operation, do not perform the transformation. The highBitSet
2957 // boolean indicates the value of the high bit of the constant which would
2958 // cause it to be modified for this operation.
2959 if (N->getOpcode() == ISD::SRA) {
2960 bool BinOpRHSSignSet = BinOpCst->getAPIntValue().isNegative();
2961 if (BinOpRHSSignSet != HighBitSet)
2965 // Fold the constants, shifting the binop RHS by the shift amount.
2966 SDValue NewRHS = DAG.getNode(N->getOpcode(), LHS->getOperand(1).getDebugLoc(),
2968 LHS->getOperand(1), N->getOperand(1));
2970 // Create the new shift.
2971 SDValue NewShift = DAG.getNode(N->getOpcode(),
2972 LHS->getOperand(0).getDebugLoc(),
2973 VT, LHS->getOperand(0), N->getOperand(1));
2975 // Create the new binop.
2976 return DAG.getNode(LHS->getOpcode(), N->getDebugLoc(), VT, NewShift, NewRHS);
2979 SDValue DAGCombiner::visitSHL(SDNode *N) {
2980 SDValue N0 = N->getOperand(0);
2981 SDValue N1 = N->getOperand(1);
2982 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
2983 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2984 EVT VT = N0.getValueType();
2985 unsigned OpSizeInBits = VT.getScalarType().getSizeInBits();
2987 // fold (shl c1, c2) -> c1<<c2
2989 return DAG.FoldConstantArithmetic(ISD::SHL, VT, N0C, N1C);
2990 // fold (shl 0, x) -> 0
2991 if (N0C && N0C->isNullValue())
2993 // fold (shl x, c >= size(x)) -> undef
2994 if (N1C && N1C->getZExtValue() >= OpSizeInBits)
2995 return DAG.getUNDEF(VT);
2996 // fold (shl x, 0) -> x
2997 if (N1C && N1C->isNullValue())
2999 // if (shl x, c) is known to be zero, return 0
3000 if (DAG.MaskedValueIsZero(SDValue(N, 0),
3001 APInt::getAllOnesValue(OpSizeInBits)))
3002 return DAG.getConstant(0, VT);
3003 // fold (shl x, (trunc (and y, c))) -> (shl x, (and (trunc y), (trunc c))).
3004 if (N1.getOpcode() == ISD::TRUNCATE &&
3005 N1.getOperand(0).getOpcode() == ISD::AND &&
3006 N1.hasOneUse() && N1.getOperand(0).hasOneUse()) {
3007 SDValue N101 = N1.getOperand(0).getOperand(1);
3008 if (ConstantSDNode *N101C = dyn_cast<ConstantSDNode>(N101)) {
3009 EVT TruncVT = N1.getValueType();
3010 SDValue N100 = N1.getOperand(0).getOperand(0);
3011 APInt TruncC = N101C->getAPIntValue();
3012 TruncC = TruncC.trunc(TruncVT.getSizeInBits());
3013 return DAG.getNode(ISD::SHL, N->getDebugLoc(), VT, N0,
3014 DAG.getNode(ISD::AND, N->getDebugLoc(), TruncVT,
3015 DAG.getNode(ISD::TRUNCATE,
3018 DAG.getConstant(TruncC, TruncVT)));
3022 if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
3023 return SDValue(N, 0);
3025 // fold (shl (shl x, c1), c2) -> 0 or (shl x, (add c1, c2))
3026 if (N1C && N0.getOpcode() == ISD::SHL &&
3027 N0.getOperand(1).getOpcode() == ISD::Constant) {
3028 uint64_t c1 = cast<ConstantSDNode>(N0.getOperand(1))->getZExtValue();
3029 uint64_t c2 = N1C->getZExtValue();
3030 if (c1 + c2 >= OpSizeInBits)
3031 return DAG.getConstant(0, VT);
3032 return DAG.getNode(ISD::SHL, N->getDebugLoc(), VT, N0.getOperand(0),
3033 DAG.getConstant(c1 + c2, N1.getValueType()));
3036 // fold (shl (ext (shl x, c1)), c2) -> (ext (shl x, (add c1, c2)))
3037 // For this to be valid, the second form must not preserve any of the bits
3038 // that are shifted out by the inner shift in the first form. This means
3039 // the outer shift size must be >= the number of bits added by the ext.
3040 // As a corollary, we don't care what kind of ext it is.
3041 if (N1C && (N0.getOpcode() == ISD::ZERO_EXTEND ||
3042 N0.getOpcode() == ISD::ANY_EXTEND ||
3043 N0.getOpcode() == ISD::SIGN_EXTEND) &&
3044 N0.getOperand(0).getOpcode() == ISD::SHL &&
3045 isa<ConstantSDNode>(N0.getOperand(0)->getOperand(1))) {
3047 cast<ConstantSDNode>(N0.getOperand(0)->getOperand(1))->getZExtValue();
3048 uint64_t c2 = N1C->getZExtValue();
3049 EVT InnerShiftVT = N0.getOperand(0).getValueType();
3050 uint64_t InnerShiftSize = InnerShiftVT.getScalarType().getSizeInBits();
3051 if (c2 >= OpSizeInBits - InnerShiftSize) {
3052 if (c1 + c2 >= OpSizeInBits)
3053 return DAG.getConstant(0, VT);
3054 return DAG.getNode(ISD::SHL, N0->getDebugLoc(), VT,
3055 DAG.getNode(N0.getOpcode(), N0->getDebugLoc(), VT,
3056 N0.getOperand(0)->getOperand(0)),
3057 DAG.getConstant(c1 + c2, N1.getValueType()));
3061 // fold (shl (srl x, c1), c2) -> (shl (and x, (shl -1, c1)), (sub c2, c1)) or
3062 // (srl (and x, (shl -1, c1)), (sub c1, c2))
3063 if (N1C && N0.getOpcode() == ISD::SRL &&
3064 N0.getOperand(1).getOpcode() == ISD::Constant) {
3065 uint64_t c1 = cast<ConstantSDNode>(N0.getOperand(1))->getZExtValue();
3066 if (c1 < VT.getSizeInBits()) {
3067 uint64_t c2 = N1C->getZExtValue();
3068 SDValue HiBitsMask =
3069 DAG.getConstant(APInt::getHighBitsSet(VT.getSizeInBits(),
3070 VT.getSizeInBits() - c1),
3072 SDValue Mask = DAG.getNode(ISD::AND, N0.getDebugLoc(), VT,
3076 return DAG.getNode(ISD::SHL, N->getDebugLoc(), VT, Mask,
3077 DAG.getConstant(c2-c1, N1.getValueType()));
3079 return DAG.getNode(ISD::SRL, N->getDebugLoc(), VT, Mask,
3080 DAG.getConstant(c1-c2, N1.getValueType()));
3083 // fold (shl (sra x, c1), c1) -> (and x, (shl -1, c1))
3084 if (N1C && N0.getOpcode() == ISD::SRA && N1 == N0.getOperand(1)) {
3085 SDValue HiBitsMask =
3086 DAG.getConstant(APInt::getHighBitsSet(VT.getSizeInBits(),
3087 VT.getSizeInBits() -
3088 N1C->getZExtValue()),
3090 return DAG.getNode(ISD::AND, N->getDebugLoc(), VT, N0.getOperand(0),
3095 SDValue NewSHL = visitShiftByConstant(N, N1C->getZExtValue());
3096 if (NewSHL.getNode())
3103 SDValue DAGCombiner::visitSRA(SDNode *N) {
3104 SDValue N0 = N->getOperand(0);
3105 SDValue N1 = N->getOperand(1);
3106 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
3107 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
3108 EVT VT = N0.getValueType();
3109 unsigned OpSizeInBits = VT.getScalarType().getSizeInBits();
3111 // fold (sra c1, c2) -> (sra c1, c2)
3113 return DAG.FoldConstantArithmetic(ISD::SRA, VT, N0C, N1C);
3114 // fold (sra 0, x) -> 0
3115 if (N0C && N0C->isNullValue())
3117 // fold (sra -1, x) -> -1
3118 if (N0C && N0C->isAllOnesValue())
3120 // fold (sra x, (setge c, size(x))) -> undef
3121 if (N1C && N1C->getZExtValue() >= OpSizeInBits)
3122 return DAG.getUNDEF(VT);
3123 // fold (sra x, 0) -> x
3124 if (N1C && N1C->isNullValue())
3126 // fold (sra (shl x, c1), c1) -> sext_inreg for some c1 and target supports
3128 if (N1C && N0.getOpcode() == ISD::SHL && N1 == N0.getOperand(1)) {
3129 unsigned LowBits = OpSizeInBits - (unsigned)N1C->getZExtValue();
3130 EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), LowBits);
3132 ExtVT = EVT::getVectorVT(*DAG.getContext(),
3133 ExtVT, VT.getVectorNumElements());
3134 if ((!LegalOperations ||
3135 TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, ExtVT)))
3136 return DAG.getNode(ISD::SIGN_EXTEND_INREG, N->getDebugLoc(), VT,
3137 N0.getOperand(0), DAG.getValueType(ExtVT));
3140 // fold (sra (sra x, c1), c2) -> (sra x, (add c1, c2))
3141 if (N1C && N0.getOpcode() == ISD::SRA) {
3142 if (ConstantSDNode *C1 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
3143 unsigned Sum = N1C->getZExtValue() + C1->getZExtValue();
3144 if (Sum >= OpSizeInBits) Sum = OpSizeInBits-1;
3145 return DAG.getNode(ISD::SRA, N->getDebugLoc(), VT, N0.getOperand(0),
3146 DAG.getConstant(Sum, N1C->getValueType(0)));
3150 // fold (sra (shl X, m), (sub result_size, n))
3151 // -> (sign_extend (trunc (shl X, (sub (sub result_size, n), m)))) for
3152 // result_size - n != m.
3153 // If truncate is free for the target sext(shl) is likely to result in better
3155 if (N0.getOpcode() == ISD::SHL) {
3156 // Get the two constanst of the shifts, CN0 = m, CN = n.
3157 const ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3159 // Determine what the truncate's result bitsize and type would be.
3161 EVT::getIntegerVT(*DAG.getContext(),
3162 OpSizeInBits - N1C->getZExtValue());
3163 // Determine the residual right-shift amount.
3164 signed ShiftAmt = N1C->getZExtValue() - N01C->getZExtValue();
3166 // If the shift is not a no-op (in which case this should be just a sign
3167 // extend already), the truncated to type is legal, sign_extend is legal
3168 // on that type, and the truncate to that type is both legal and free,
3169 // perform the transform.
3170 if ((ShiftAmt > 0) &&
3171 TLI.isOperationLegalOrCustom(ISD::SIGN_EXTEND, TruncVT) &&
3172 TLI.isOperationLegalOrCustom(ISD::TRUNCATE, VT) &&
3173 TLI.isTruncateFree(VT, TruncVT)) {
3175 SDValue Amt = DAG.getConstant(ShiftAmt,
3176 getShiftAmountTy(N0.getOperand(0).getValueType()));
3177 SDValue Shift = DAG.getNode(ISD::SRL, N0.getDebugLoc(), VT,
3178 N0.getOperand(0), Amt);
3179 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, N0.getDebugLoc(), TruncVT,
3181 return DAG.getNode(ISD::SIGN_EXTEND, N->getDebugLoc(),
3182 N->getValueType(0), Trunc);
3187 // fold (sra x, (trunc (and y, c))) -> (sra x, (and (trunc y), (trunc c))).
3188 if (N1.getOpcode() == ISD::TRUNCATE &&
3189 N1.getOperand(0).getOpcode() == ISD::AND &&
3190 N1.hasOneUse() && N1.getOperand(0).hasOneUse()) {
3191 SDValue N101 = N1.getOperand(0).getOperand(1);
3192 if (ConstantSDNode *N101C = dyn_cast<ConstantSDNode>(N101)) {
3193 EVT TruncVT = N1.getValueType();
3194 SDValue N100 = N1.getOperand(0).getOperand(0);
3195 APInt TruncC = N101C->getAPIntValue();
3196 TruncC = TruncC.trunc(TruncVT.getScalarType().getSizeInBits());
3197 return DAG.getNode(ISD::SRA, N->getDebugLoc(), VT, N0,
3198 DAG.getNode(ISD::AND, N->getDebugLoc(),
3200 DAG.getNode(ISD::TRUNCATE,
3203 DAG.getConstant(TruncC, TruncVT)));
3207 // fold (sra (trunc (sr x, c1)), c2) -> (trunc (sra x, c1+c2))
3208 // if c1 is equal to the number of bits the trunc removes
3209 if (N0.getOpcode() == ISD::TRUNCATE &&
3210 (N0.getOperand(0).getOpcode() == ISD::SRL ||
3211 N0.getOperand(0).getOpcode() == ISD::SRA) &&
3212 N0.getOperand(0).hasOneUse() &&
3213 N0.getOperand(0).getOperand(1).hasOneUse() &&
3214 N1C && isa<ConstantSDNode>(N0.getOperand(0).getOperand(1))) {
3215 EVT LargeVT = N0.getOperand(0).getValueType();
3216 ConstantSDNode *LargeShiftAmt =
3217 cast<ConstantSDNode>(N0.getOperand(0).getOperand(1));
3219 if (LargeVT.getScalarType().getSizeInBits() - OpSizeInBits ==
3220 LargeShiftAmt->getZExtValue()) {
3222 DAG.getConstant(LargeShiftAmt->getZExtValue() + N1C->getZExtValue(),
3223 getShiftAmountTy(N0.getOperand(0).getOperand(0).getValueType()));
3224 SDValue SRA = DAG.getNode(ISD::SRA, N->getDebugLoc(), LargeVT,
3225 N0.getOperand(0).getOperand(0), Amt);
3226 return DAG.getNode(ISD::TRUNCATE, N->getDebugLoc(), VT, SRA);
3230 // Simplify, based on bits shifted out of the LHS.
3231 if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
3232 return SDValue(N, 0);
3235 // If the sign bit is known to be zero, switch this to a SRL.
3236 if (DAG.SignBitIsZero(N0))
3237 return DAG.getNode(ISD::SRL, N->getDebugLoc(), VT, N0, N1);
3240 SDValue NewSRA = visitShiftByConstant(N, N1C->getZExtValue());
3241 if (NewSRA.getNode())
3248 SDValue DAGCombiner::visitSRL(SDNode *N) {
3249 SDValue N0 = N->getOperand(0);
3250 SDValue N1 = N->getOperand(1);
3251 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
3252 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
3253 EVT VT = N0.getValueType();
3254 unsigned OpSizeInBits = VT.getScalarType().getSizeInBits();
3256 // fold (srl c1, c2) -> c1 >>u c2
3258 return DAG.FoldConstantArithmetic(ISD::SRL, VT, N0C, N1C);
3259 // fold (srl 0, x) -> 0
3260 if (N0C && N0C->isNullValue())
3262 // fold (srl x, c >= size(x)) -> undef
3263 if (N1C && N1C->getZExtValue() >= OpSizeInBits)
3264 return DAG.getUNDEF(VT);
3265 // fold (srl x, 0) -> x
3266 if (N1C && N1C->isNullValue())
3268 // if (srl x, c) is known to be zero, return 0
3269 if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0),
3270 APInt::getAllOnesValue(OpSizeInBits)))
3271 return DAG.getConstant(0, VT);
3273 // fold (srl (srl x, c1), c2) -> 0 or (srl x, (add c1, c2))
3274 if (N1C && N0.getOpcode() == ISD::SRL &&
3275 N0.getOperand(1).getOpcode() == ISD::Constant) {
3276 uint64_t c1 = cast<ConstantSDNode>(N0.getOperand(1))->getZExtValue();
3277 uint64_t c2 = N1C->getZExtValue();
3278 if (c1 + c2 >= OpSizeInBits)
3279 return DAG.getConstant(0, VT);
3280 return DAG.getNode(ISD::SRL, N->getDebugLoc(), VT, N0.getOperand(0),
3281 DAG.getConstant(c1 + c2, N1.getValueType()));
3284 // fold (srl (trunc (srl x, c1)), c2) -> 0 or (trunc (srl x, (add c1, c2)))
3285 if (N1C && N0.getOpcode() == ISD::TRUNCATE &&
3286 N0.getOperand(0).getOpcode() == ISD::SRL &&
3287 isa<ConstantSDNode>(N0.getOperand(0)->getOperand(1))) {
3289 cast<ConstantSDNode>(N0.getOperand(0)->getOperand(1))->getZExtValue();
3290 uint64_t c2 = N1C->getZExtValue();
3291 EVT InnerShiftVT = N0.getOperand(0).getValueType();
3292 EVT ShiftCountVT = N0.getOperand(0)->getOperand(1).getValueType();
3293 uint64_t InnerShiftSize = InnerShiftVT.getScalarType().getSizeInBits();
3294 // This is only valid if the OpSizeInBits + c1 = size of inner shift.
3295 if (c1 + OpSizeInBits == InnerShiftSize) {
3296 if (c1 + c2 >= InnerShiftSize)
3297 return DAG.getConstant(0, VT);
3298 return DAG.getNode(ISD::TRUNCATE, N0->getDebugLoc(), VT,
3299 DAG.getNode(ISD::SRL, N0->getDebugLoc(), InnerShiftVT,
3300 N0.getOperand(0)->getOperand(0),
3301 DAG.getConstant(c1 + c2, ShiftCountVT)));
3305 // fold (srl (shl x, c), c) -> (and x, cst2)
3306 if (N1C && N0.getOpcode() == ISD::SHL && N0.getOperand(1) == N1 &&
3307 N0.getValueSizeInBits() <= 64) {
3308 uint64_t ShAmt = N1C->getZExtValue()+64-N0.getValueSizeInBits();
3309 return DAG.getNode(ISD::AND, N->getDebugLoc(), VT, N0.getOperand(0),
3310 DAG.getConstant(~0ULL >> ShAmt, VT));
3314 // fold (srl (anyextend x), c) -> (anyextend (srl x, c))
3315 if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
3316 // Shifting in all undef bits?
3317 EVT SmallVT = N0.getOperand(0).getValueType();
3318 if (N1C->getZExtValue() >= SmallVT.getSizeInBits())
3319 return DAG.getUNDEF(VT);
3321 if (!LegalTypes || TLI.isTypeDesirableForOp(ISD::SRL, SmallVT)) {
3322 SDValue SmallShift = DAG.getNode(ISD::SRL, N0.getDebugLoc(), SmallVT,
3323 N0.getOperand(0), N1);
3324 AddToWorkList(SmallShift.getNode());
3325 return DAG.getNode(ISD::ANY_EXTEND, N->getDebugLoc(), VT, SmallShift);
3329 // fold (srl (sra X, Y), 31) -> (srl X, 31). This srl only looks at the sign
3330 // bit, which is unmodified by sra.
3331 if (N1C && N1C->getZExtValue() + 1 == VT.getSizeInBits()) {
3332 if (N0.getOpcode() == ISD::SRA)
3333 return DAG.getNode(ISD::SRL, N->getDebugLoc(), VT, N0.getOperand(0), N1);
3336 // fold (srl (ctlz x), "5") -> x iff x has one bit set (the low bit).
3337 if (N1C && N0.getOpcode() == ISD::CTLZ &&
3338 N1C->getAPIntValue() == Log2_32(VT.getSizeInBits())) {
3339 APInt KnownZero, KnownOne;
3340 APInt Mask = APInt::getAllOnesValue(VT.getScalarType().getSizeInBits());
3341 DAG.ComputeMaskedBits(N0.getOperand(0), Mask, KnownZero, KnownOne);
3343 // If any of the input bits are KnownOne, then the input couldn't be all
3344 // zeros, thus the result of the srl will always be zero.
3345 if (KnownOne.getBoolValue()) return DAG.getConstant(0, VT);
3347 // If all of the bits input the to ctlz node are known to be zero, then
3348 // the result of the ctlz is "32" and the result of the shift is one.
3349 APInt UnknownBits = ~KnownZero & Mask;
3350 if (UnknownBits == 0) return DAG.getConstant(1, VT);
3352 // Otherwise, check to see if there is exactly one bit input to the ctlz.
3353 if ((UnknownBits & (UnknownBits - 1)) == 0) {
3354 // Okay, we know that only that the single bit specified by UnknownBits
3355 // could be set on input to the CTLZ node. If this bit is set, the SRL
3356 // will return 0, if it is clear, it returns 1. Change the CTLZ/SRL pair
3357 // to an SRL/XOR pair, which is likely to simplify more.
3358 unsigned ShAmt = UnknownBits.countTrailingZeros();
3359 SDValue Op = N0.getOperand(0);
3362 Op = DAG.getNode(ISD::SRL, N0.getDebugLoc(), VT, Op,
3363 DAG.getConstant(ShAmt, getShiftAmountTy(Op.getValueType())));
3364 AddToWorkList(Op.getNode());
3367 return DAG.getNode(ISD::XOR, N->getDebugLoc(), VT,
3368 Op, DAG.getConstant(1, VT));
3372 // fold (srl x, (trunc (and y, c))) -> (srl x, (and (trunc y), (trunc c))).
3373 if (N1.getOpcode() == ISD::TRUNCATE &&
3374 N1.getOperand(0).getOpcode() == ISD::AND &&
3375 N1.hasOneUse() && N1.getOperand(0).hasOneUse()) {
3376 SDValue N101 = N1.getOperand(0).getOperand(1);
3377 if (ConstantSDNode *N101C = dyn_cast<ConstantSDNode>(N101)) {
3378 EVT TruncVT = N1.getValueType();
3379 SDValue N100 = N1.getOperand(0).getOperand(0);
3380 APInt TruncC = N101C->getAPIntValue();
3381 TruncC = TruncC.trunc(TruncVT.getSizeInBits());
3382 return DAG.getNode(ISD::SRL, N->getDebugLoc(), VT, N0,
3383 DAG.getNode(ISD::AND, N->getDebugLoc(),
3385 DAG.getNode(ISD::TRUNCATE,
3388 DAG.getConstant(TruncC, TruncVT)));
3392 // fold operands of srl based on knowledge that the low bits are not
3394 if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
3395 return SDValue(N, 0);
3398 SDValue NewSRL = visitShiftByConstant(N, N1C->getZExtValue());
3399 if (NewSRL.getNode())
3403 // Attempt to convert a srl of a load into a narrower zero-extending load.
3404 SDValue NarrowLoad = ReduceLoadWidth(N);
3405 if (NarrowLoad.getNode())
3408 // Here is a common situation. We want to optimize:
3411 // %b = and i32 %a, 2
3412 // %c = srl i32 %b, 1
3413 // brcond i32 %c ...
3419 // %c = setcc eq %b, 0
3422 // However when after the source operand of SRL is optimized into AND, the SRL
3423 // itself may not be optimized further. Look for it and add the BRCOND into
3425 if (N->hasOneUse()) {
3426 SDNode *Use = *N->use_begin();
3427 if (Use->getOpcode() == ISD::BRCOND)
3429 else if (Use->getOpcode() == ISD::TRUNCATE && Use->hasOneUse()) {
3430 // Also look pass the truncate.
3431 Use = *Use->use_begin();
3432 if (Use->getOpcode() == ISD::BRCOND)
3440 SDValue DAGCombiner::visitCTLZ(SDNode *N) {
3441 SDValue N0 = N->getOperand(0);
3442 EVT VT = N->getValueType(0);
3444 // fold (ctlz c1) -> c2
3445 if (isa<ConstantSDNode>(N0))
3446 return DAG.getNode(ISD::CTLZ, N->getDebugLoc(), VT, N0);
3450 SDValue DAGCombiner::visitCTTZ(SDNode *N) {
3451 SDValue N0 = N->getOperand(0);
3452 EVT VT = N->getValueType(0);
3454 // fold (cttz c1) -> c2
3455 if (isa<ConstantSDNode>(N0))
3456 return DAG.getNode(ISD::CTTZ, N->getDebugLoc(), VT, N0);
3460 SDValue DAGCombiner::visitCTPOP(SDNode *N) {
3461 SDValue N0 = N->getOperand(0);
3462 EVT VT = N->getValueType(0);
3464 // fold (ctpop c1) -> c2
3465 if (isa<ConstantSDNode>(N0))
3466 return DAG.getNode(ISD::CTPOP, N->getDebugLoc(), VT, N0);
3470 SDValue DAGCombiner::visitSELECT(SDNode *N) {
3471 SDValue N0 = N->getOperand(0);
3472 SDValue N1 = N->getOperand(1);
3473 SDValue N2 = N->getOperand(2);
3474 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
3475 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
3476 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2);
3477 EVT VT = N->getValueType(0);
3478 EVT VT0 = N0.getValueType();
3480 // fold (select C, X, X) -> X
3483 // fold (select true, X, Y) -> X
3484 if (N0C && !N0C->isNullValue())
3486 // fold (select false, X, Y) -> Y
3487 if (N0C && N0C->isNullValue())
3489 // fold (select C, 1, X) -> (or C, X)
3490 if (VT == MVT::i1 && N1C && N1C->getAPIntValue() == 1)
3491 return DAG.getNode(ISD::OR, N->getDebugLoc(), VT, N0, N2);
3492 // fold (select C, 0, 1) -> (xor C, 1)
3493 if (VT.isInteger() &&
3496 TLI.getBooleanContents() == TargetLowering::ZeroOrOneBooleanContent)) &&
3497 N1C && N2C && N1C->isNullValue() && N2C->getAPIntValue() == 1) {
3500 return DAG.getNode(ISD::XOR, N->getDebugLoc(), VT0,
3501 N0, DAG.getConstant(1, VT0));
3502 XORNode = DAG.getNode(ISD::XOR, N0.getDebugLoc(), VT0,
3503 N0, DAG.getConstant(1, VT0));
3504 AddToWorkList(XORNode.getNode());
3506 return DAG.getNode(ISD::ZERO_EXTEND, N->getDebugLoc(), VT, XORNode);
3507 return DAG.getNode(ISD::TRUNCATE, N->getDebugLoc(), VT, XORNode);
3509 // fold (select C, 0, X) -> (and (not C), X)
3510 if (VT == VT0 && VT == MVT::i1 && N1C && N1C->isNullValue()) {
3511 SDValue NOTNode = DAG.getNOT(N0.getDebugLoc(), N0, VT);
3512 AddToWorkList(NOTNode.getNode());
3513 return DAG.getNode(ISD::AND, N->getDebugLoc(), VT, NOTNode, N2);
3515 // fold (select C, X, 1) -> (or (not C), X)
3516 if (VT == VT0 && VT == MVT::i1 && N2C && N2C->getAPIntValue() == 1) {
3517 SDValue NOTNode = DAG.getNOT(N0.getDebugLoc(), N0, VT);
3518 AddToWorkList(NOTNode.getNode());
3519 return DAG.getNode(ISD::OR, N->getDebugLoc(), VT, NOTNode, N1);
3521 // fold (select C, X, 0) -> (and C, X)
3522 if (VT == MVT::i1 && N2C && N2C->isNullValue())
3523 return DAG.getNode(ISD::AND, N->getDebugLoc(), VT, N0, N1);
3524 // fold (select X, X, Y) -> (or X, Y)
3525 // fold (select X, 1, Y) -> (or X, Y)
3526 if (VT == MVT::i1 && (N0 == N1 || (N1C && N1C->getAPIntValue() == 1)))
3527 return DAG.getNode(ISD::OR, N->getDebugLoc(), VT, N0, N2);
3528 // fold (select X, Y, X) -> (and X, Y)
3529 // fold (select X, Y, 0) -> (and X, Y)
3530 if (VT == MVT::i1 && (N0 == N2 || (N2C && N2C->getAPIntValue() == 0)))
3531 return DAG.getNode(ISD::AND, N->getDebugLoc(), VT, N0, N1);
3533 // If we can fold this based on the true/false value, do so.
3534 if (SimplifySelectOps(N, N1, N2))
3535 return SDValue(N, 0); // Don't revisit N.
3537 // fold selects based on a setcc into other things, such as min/max/abs
3538 if (N0.getOpcode() == ISD::SETCC) {
3540 // Check against MVT::Other for SELECT_CC, which is a workaround for targets
3541 // having to say they don't support SELECT_CC on every type the DAG knows
3542 // about, since there is no way to mark an opcode illegal at all value types
3543 if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, MVT::Other) &&
3544 TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT))
3545 return DAG.getNode(ISD::SELECT_CC, N->getDebugLoc(), VT,
3546 N0.getOperand(0), N0.getOperand(1),
3547 N1, N2, N0.getOperand(2));
3548 return SimplifySelect(N->getDebugLoc(), N0, N1, N2);
3554 SDValue DAGCombiner::visitSELECT_CC(SDNode *N) {
3555 SDValue N0 = N->getOperand(0);
3556 SDValue N1 = N->getOperand(1);
3557 SDValue N2 = N->getOperand(2);
3558 SDValue N3 = N->getOperand(3);
3559 SDValue N4 = N->getOperand(4);
3560 ISD::CondCode CC = cast<CondCodeSDNode>(N4)->get();
3562 // fold select_cc lhs, rhs, x, x, cc -> x
3566 // Determine if the condition we're dealing with is constant
3567 SDValue SCC = SimplifySetCC(TLI.getSetCCResultType(N0.getValueType()),
3568 N0, N1, CC, N->getDebugLoc(), false);
3569 if (SCC.getNode()) AddToWorkList(SCC.getNode());
3571 if (ConstantSDNode *SCCC = dyn_cast_or_null<ConstantSDNode>(SCC.getNode())) {
3572 if (!SCCC->isNullValue())
3573 return N2; // cond always true -> true val
3575 return N3; // cond always false -> false val
3578 // Fold to a simpler select_cc
3579 if (SCC.getNode() && SCC.getOpcode() == ISD::SETCC)
3580 return DAG.getNode(ISD::SELECT_CC, N->getDebugLoc(), N2.getValueType(),
3581 SCC.getOperand(0), SCC.getOperand(1), N2, N3,
3584 // If we can fold this based on the true/false value, do so.
3585 if (SimplifySelectOps(N, N2, N3))
3586 return SDValue(N, 0); // Don't revisit N.
3588 // fold select_cc into other things, such as min/max/abs
3589 return SimplifySelectCC(N->getDebugLoc(), N0, N1, N2, N3, CC);
3592 SDValue DAGCombiner::visitSETCC(SDNode *N) {
3593 return SimplifySetCC(N->getValueType(0), N->getOperand(0), N->getOperand(1),
3594 cast<CondCodeSDNode>(N->getOperand(2))->get(),
3598 // ExtendUsesToFormExtLoad - Trying to extend uses of a load to enable this:
3599 // "fold ({s|z|a}ext (load x)) -> ({s|z|a}ext (truncate ({s|z|a}extload x)))"
3600 // transformation. Returns true if extension are possible and the above
3601 // mentioned transformation is profitable.
3602 static bool ExtendUsesToFormExtLoad(SDNode *N, SDValue N0,
3604 SmallVector<SDNode*, 4> &ExtendNodes,
3605 const TargetLowering &TLI) {
3606 bool HasCopyToRegUses = false;
3607 bool isTruncFree = TLI.isTruncateFree(N->getValueType(0), N0.getValueType());
3608 for (SDNode::use_iterator UI = N0.getNode()->use_begin(),
3609 UE = N0.getNode()->use_end();
3614 if (UI.getUse().getResNo() != N0.getResNo())
3616 // FIXME: Only extend SETCC N, N and SETCC N, c for now.
3617 if (ExtOpc != ISD::ANY_EXTEND && User->getOpcode() == ISD::SETCC) {
3618 ISD::CondCode CC = cast<CondCodeSDNode>(User->getOperand(2))->get();
3619 if (ExtOpc == ISD::ZERO_EXTEND && ISD::isSignedIntSetCC(CC))
3620 // Sign bits will be lost after a zext.
3623 for (unsigned i = 0; i != 2; ++i) {
3624 SDValue UseOp = User->getOperand(i);
3627 if (!isa<ConstantSDNode>(UseOp))
3632 ExtendNodes.push_back(User);
3635 // If truncates aren't free and there are users we can't
3636 // extend, it isn't worthwhile.
3639 // Remember if this value is live-out.
3640 if (User->getOpcode() == ISD::CopyToReg)
3641 HasCopyToRegUses = true;
3644 if (HasCopyToRegUses) {
3645 bool BothLiveOut = false;
3646 for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
3648 SDUse &Use = UI.getUse();
3649 if (Use.getResNo() == 0 && Use.getUser()->getOpcode() == ISD::CopyToReg) {
3655 // Both unextended and extended values are live out. There had better be
3656 // a good reason for the transformation.
3657 return ExtendNodes.size();
3662 SDValue DAGCombiner::visitSIGN_EXTEND(SDNode *N) {
3663 SDValue N0 = N->getOperand(0);
3664 EVT VT = N->getValueType(0);
3666 // fold (sext c1) -> c1
3667 if (isa<ConstantSDNode>(N0))
3668 return DAG.getNode(ISD::SIGN_EXTEND, N->getDebugLoc(), VT, N0);
3670 // fold (sext (sext x)) -> (sext x)
3671 // fold (sext (aext x)) -> (sext x)
3672 if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
3673 return DAG.getNode(ISD::SIGN_EXTEND, N->getDebugLoc(), VT,
3676 if (N0.getOpcode() == ISD::TRUNCATE) {
3677 // fold (sext (truncate (load x))) -> (sext (smaller load x))
3678 // fold (sext (truncate (srl (load x), c))) -> (sext (smaller load (x+c/n)))
3679 SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
3680 if (NarrowLoad.getNode()) {
3681 SDNode* oye = N0.getNode()->getOperand(0).getNode();
3682 if (NarrowLoad.getNode() != N0.getNode()) {
3683 CombineTo(N0.getNode(), NarrowLoad);
3684 // CombineTo deleted the truncate, if needed, but not what's under it.
3687 return SDValue(N, 0); // Return N so it doesn't get rechecked!
3690 // See if the value being truncated is already sign extended. If so, just
3691 // eliminate the trunc/sext pair.
3692 SDValue Op = N0.getOperand(0);
3693 unsigned OpBits = Op.getValueType().getScalarType().getSizeInBits();
3694 unsigned MidBits = N0.getValueType().getScalarType().getSizeInBits();
3695 unsigned DestBits = VT.getScalarType().getSizeInBits();
3696 unsigned NumSignBits = DAG.ComputeNumSignBits(Op);
3698 if (OpBits == DestBits) {
3699 // Op is i32, Mid is i8, and Dest is i32. If Op has more than 24 sign
3700 // bits, it is already ready.
3701 if (NumSignBits > DestBits-MidBits)
3703 } else if (OpBits < DestBits) {
3704 // Op is i32, Mid is i8, and Dest is i64. If Op has more than 24 sign
3705 // bits, just sext from i32.
3706 if (NumSignBits > OpBits-MidBits)
3707 return DAG.getNode(ISD::SIGN_EXTEND, N->getDebugLoc(), VT, Op);
3709 // Op is i64, Mid is i8, and Dest is i32. If Op has more than 56 sign
3710 // bits, just truncate to i32.
3711 if (NumSignBits > OpBits-MidBits)
3712 return DAG.getNode(ISD::TRUNCATE, N->getDebugLoc(), VT, Op);
3715 // fold (sext (truncate x)) -> (sextinreg x).
3716 if (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG,
3717 N0.getValueType())) {
3718 if (OpBits < DestBits)
3719 Op = DAG.getNode(ISD::ANY_EXTEND, N0.getDebugLoc(), VT, Op);
3720 else if (OpBits > DestBits)
3721 Op = DAG.getNode(ISD::TRUNCATE, N0.getDebugLoc(), VT, Op);
3722 return DAG.getNode(ISD::SIGN_EXTEND_INREG, N->getDebugLoc(), VT, Op,
3723 DAG.getValueType(N0.getValueType()));
3727 // fold (sext (load x)) -> (sext (truncate (sextload x)))
3728 // None of the supported targets knows how to perform load and sign extend
3729 // on vectors in one instruction. We only perform this transformation on
3731 if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() &&
3732 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
3733 TLI.isLoadExtLegal(ISD::SEXTLOAD, N0.getValueType()))) {
3734 bool DoXform = true;
3735 SmallVector<SDNode*, 4> SetCCs;
3736 if (!N0.hasOneUse())
3737 DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::SIGN_EXTEND, SetCCs, TLI);
3739 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
3740 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, N->getDebugLoc(), VT,
3742 LN0->getBasePtr(), LN0->getPointerInfo(),
3744 LN0->isVolatile(), LN0->isNonTemporal(),
3745 LN0->getAlignment());
3746 CombineTo(N, ExtLoad);
3747 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, N0.getDebugLoc(),
3748 N0.getValueType(), ExtLoad);
3749 CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
3751 // Extend SetCC uses if necessary.
3752 for (unsigned i = 0, e = SetCCs.size(); i != e; ++i) {
3753 SDNode *SetCC = SetCCs[i];
3754 SmallVector<SDValue, 4> Ops;
3756 for (unsigned j = 0; j != 2; ++j) {
3757 SDValue SOp = SetCC->getOperand(j);
3759 Ops.push_back(ExtLoad);
3761 Ops.push_back(DAG.getNode(ISD::SIGN_EXTEND,
3762 N->getDebugLoc(), VT, SOp));
3765 Ops.push_back(SetCC->getOperand(2));
3766 CombineTo(SetCC, DAG.getNode(ISD::SETCC, N->getDebugLoc(),
3767 SetCC->getValueType(0),
3768 &Ops[0], Ops.size()));
3771 return SDValue(N, 0); // Return N so it doesn't get rechecked!
3775 // fold (sext (sextload x)) -> (sext (truncate (sextload x)))
3776 // fold (sext ( extload x)) -> (sext (truncate (sextload x)))
3777 if ((ISD::isSEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) &&
3778 ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) {
3779 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
3780 EVT MemVT = LN0->getMemoryVT();
3781 if ((!LegalOperations && !LN0->isVolatile()) ||
3782 TLI.isLoadExtLegal(ISD::SEXTLOAD, MemVT)) {
3783 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, N->getDebugLoc(), VT,
3785 LN0->getBasePtr(), LN0->getPointerInfo(),
3787 LN0->isVolatile(), LN0->isNonTemporal(),
3788 LN0->getAlignment());
3789 CombineTo(N, ExtLoad);
3790 CombineTo(N0.getNode(),
3791 DAG.getNode(ISD::TRUNCATE, N0.getDebugLoc(),
3792 N0.getValueType(), ExtLoad),
3793 ExtLoad.getValue(1));
3794 return SDValue(N, 0); // Return N so it doesn't get rechecked!
3798 if (N0.getOpcode() == ISD::SETCC) {
3799 // sext(setcc) -> sext_in_reg(vsetcc) for vectors.
3800 // Only do this before legalize for now.
3801 if (VT.isVector() && !LegalOperations) {
3802 EVT N0VT = N0.getOperand(0).getValueType();
3803 // We know that the # elements of the results is the same as the
3804 // # elements of the compare (and the # elements of the compare result
3805 // for that matter). Check to see that they are the same size. If so,
3806 // we know that the element size of the sext'd result matches the
3807 // element size of the compare operands.
3808 if (VT.getSizeInBits() == N0VT.getSizeInBits())
3809 return DAG.getVSetCC(N->getDebugLoc(), VT, N0.getOperand(0),
3811 cast<CondCodeSDNode>(N0.getOperand(2))->get());
3812 // If the desired elements are smaller or larger than the source
3813 // elements we can use a matching integer vector type and then
3814 // truncate/sign extend
3816 EVT MatchingElementType =
3817 EVT::getIntegerVT(*DAG.getContext(),
3818 N0VT.getScalarType().getSizeInBits());
3819 EVT MatchingVectorType =
3820 EVT::getVectorVT(*DAG.getContext(), MatchingElementType,
3821 N0VT.getVectorNumElements());
3823 DAG.getVSetCC(N->getDebugLoc(), MatchingVectorType, N0.getOperand(0),
3825 cast<CondCodeSDNode>(N0.getOperand(2))->get());
3826 return DAG.getSExtOrTrunc(VsetCC, N->getDebugLoc(), VT);
3830 // sext(setcc x, y, cc) -> (select_cc x, y, -1, 0, cc)
3831 unsigned ElementWidth = VT.getScalarType().getSizeInBits();
3833 DAG.getConstant(APInt::getAllOnesValue(ElementWidth), VT);
3835 SimplifySelectCC(N->getDebugLoc(), N0.getOperand(0), N0.getOperand(1),
3836 NegOne, DAG.getConstant(0, VT),
3837 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
3838 if (SCC.getNode()) return SCC;
3839 if (!LegalOperations ||
3840 TLI.isOperationLegal(ISD::SETCC, TLI.getSetCCResultType(VT)))
3841 return DAG.getNode(ISD::SELECT, N->getDebugLoc(), VT,
3842 DAG.getSetCC(N->getDebugLoc(),
3843 TLI.getSetCCResultType(VT),
3844 N0.getOperand(0), N0.getOperand(1),
3845 cast<CondCodeSDNode>(N0.getOperand(2))->get()),
3846 NegOne, DAG.getConstant(0, VT));
3849 // fold (sext x) -> (zext x) if the sign bit is known zero.
3850 if ((!LegalOperations || TLI.isOperationLegal(ISD::ZERO_EXTEND, VT)) &&
3851 DAG.SignBitIsZero(N0))
3852 return DAG.getNode(ISD::ZERO_EXTEND, N->getDebugLoc(), VT, N0);
3857 SDValue DAGCombiner::visitZERO_EXTEND(SDNode *N) {
3858 SDValue N0 = N->getOperand(0);
3859 EVT VT = N->getValueType(0);
3861 // fold (zext c1) -> c1
3862 if (isa<ConstantSDNode>(N0))
3863 return DAG.getNode(ISD::ZERO_EXTEND, N->getDebugLoc(), VT, N0);
3864 // fold (zext (zext x)) -> (zext x)
3865 // fold (zext (aext x)) -> (zext x)
3866 if (N0.getOpcode() == ISD::ZERO_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
3867 return DAG.getNode(ISD::ZERO_EXTEND, N->getDebugLoc(), VT,
3870 // fold (zext (truncate (load x))) -> (zext (smaller load x))
3871 // fold (zext (truncate (srl (load x), c))) -> (zext (small load (x+c/n)))
3872 if (N0.getOpcode() == ISD::TRUNCATE) {
3873 SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
3874 if (NarrowLoad.getNode()) {
3875 SDNode* oye = N0.getNode()->getOperand(0).getNode();
3876 if (NarrowLoad.getNode() != N0.getNode()) {
3877 CombineTo(N0.getNode(), NarrowLoad);
3878 // CombineTo deleted the truncate, if needed, but not what's under it.
3881 return DAG.getNode(ISD::ZERO_EXTEND, N->getDebugLoc(), VT, NarrowLoad);
3885 // fold (zext (truncate x)) -> (and x, mask)
3886 if (N0.getOpcode() == ISD::TRUNCATE &&
3887 (!LegalOperations || TLI.isOperationLegal(ISD::AND, VT))) {
3889 // fold (zext (truncate (load x))) -> (zext (smaller load x))
3890 // fold (zext (truncate (srl (load x), c))) -> (zext (smaller load (x+c/n)))
3891 SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
3892 if (NarrowLoad.getNode()) {
3893 SDNode* oye = N0.getNode()->getOperand(0).getNode();
3894 if (NarrowLoad.getNode() != N0.getNode()) {
3895 CombineTo(N0.getNode(), NarrowLoad);
3896 // CombineTo deleted the truncate, if needed, but not what's under it.
3899 return SDValue(N, 0); // Return N so it doesn't get rechecked!
3902 SDValue Op = N0.getOperand(0);
3903 if (Op.getValueType().bitsLT(VT)) {
3904 Op = DAG.getNode(ISD::ANY_EXTEND, N->getDebugLoc(), VT, Op);
3905 } else if (Op.getValueType().bitsGT(VT)) {
3906 Op = DAG.getNode(ISD::TRUNCATE, N->getDebugLoc(), VT, Op);
3908 return DAG.getZeroExtendInReg(Op, N->getDebugLoc(),
3909 N0.getValueType().getScalarType());
3912 // Fold (zext (and (trunc x), cst)) -> (and x, cst),
3913 // if either of the casts is not free.
3914 if (N0.getOpcode() == ISD::AND &&
3915 N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
3916 N0.getOperand(1).getOpcode() == ISD::Constant &&
3917 (!TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(),
3918 N0.getValueType()) ||
3919 !TLI.isZExtFree(N0.getValueType(), VT))) {
3920 SDValue X = N0.getOperand(0).getOperand(0);
3921 if (X.getValueType().bitsLT(VT)) {
3922 X = DAG.getNode(ISD::ANY_EXTEND, X.getDebugLoc(), VT, X);
3923 } else if (X.getValueType().bitsGT(VT)) {
3924 X = DAG.getNode(ISD::TRUNCATE, X.getDebugLoc(), VT, X);
3926 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
3927 Mask = Mask.zext(VT.getSizeInBits());
3928 return DAG.getNode(ISD::AND, N->getDebugLoc(), VT,
3929 X, DAG.getConstant(Mask, VT));
3932 // fold (zext (load x)) -> (zext (truncate (zextload x)))
3933 // None of the supported targets knows how to perform load and vector_zext
3934 // on vectors in one instruction. We only perform this transformation on
3936 if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() &&
3937 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
3938 TLI.isLoadExtLegal(ISD::ZEXTLOAD, N0.getValueType()))) {
3939 bool DoXform = true;
3940 SmallVector<SDNode*, 4> SetCCs;
3941 if (!N0.hasOneUse())
3942 DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ZERO_EXTEND, SetCCs, TLI);
3944 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
3945 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, N->getDebugLoc(), VT,
3947 LN0->getBasePtr(), LN0->getPointerInfo(),
3949 LN0->isVolatile(), LN0->isNonTemporal(),
3950 LN0->getAlignment());
3951 CombineTo(N, ExtLoad);
3952 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, N0.getDebugLoc(),
3953 N0.getValueType(), ExtLoad);
3954 CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
3956 // Extend SetCC uses if necessary.
3957 for (unsigned i = 0, e = SetCCs.size(); i != e; ++i) {
3958 SDNode *SetCC = SetCCs[i];
3959 SmallVector<SDValue, 4> Ops;
3961 for (unsigned j = 0; j != 2; ++j) {
3962 SDValue SOp = SetCC->getOperand(j);
3964 Ops.push_back(ExtLoad);
3966 Ops.push_back(DAG.getNode(ISD::ZERO_EXTEND,
3967 N->getDebugLoc(), VT, SOp));
3970 Ops.push_back(SetCC->getOperand(2));
3971 CombineTo(SetCC, DAG.getNode(ISD::SETCC, N->getDebugLoc(),
3972 SetCC->getValueType(0),
3973 &Ops[0], Ops.size()));
3976 return SDValue(N, 0); // Return N so it doesn't get rechecked!
3980 // fold (zext (zextload x)) -> (zext (truncate (zextload x)))
3981 // fold (zext ( extload x)) -> (zext (truncate (zextload x)))
3982 if ((ISD::isZEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) &&
3983 ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) {
3984 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
3985 EVT MemVT = LN0->getMemoryVT();
3986 if ((!LegalOperations && !LN0->isVolatile()) ||
3987 TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT)) {
3988 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, N->getDebugLoc(), VT,
3990 LN0->getBasePtr(), LN0->getPointerInfo(),
3992 LN0->isVolatile(), LN0->isNonTemporal(),
3993 LN0->getAlignment());
3994 CombineTo(N, ExtLoad);
3995 CombineTo(N0.getNode(),
3996 DAG.getNode(ISD::TRUNCATE, N0.getDebugLoc(), N0.getValueType(),
3998 ExtLoad.getValue(1));
3999 return SDValue(N, 0); // Return N so it doesn't get rechecked!
4003 if (N0.getOpcode() == ISD::SETCC) {
4004 if (!LegalOperations && VT.isVector()) {
4005 // zext(setcc) -> (and (vsetcc), (1, 1, ...) for vectors.
4006 // Only do this before legalize for now.
4007 EVT N0VT = N0.getOperand(0).getValueType();
4008 EVT EltVT = VT.getVectorElementType();
4009 SmallVector<SDValue,8> OneOps(VT.getVectorNumElements(),
4010 DAG.getConstant(1, EltVT));
4011 if (VT.getSizeInBits() == N0VT.getSizeInBits()) {
4012 // We know that the # elements of the results is the same as the
4013 // # elements of the compare (and the # elements of the compare result
4014 // for that matter). Check to see that they are the same size. If so,
4015 // we know that the element size of the sext'd result matches the
4016 // element size of the compare operands.
4017 return DAG.getNode(ISD::AND, N->getDebugLoc(), VT,
4018 DAG.getVSetCC(N->getDebugLoc(), VT, N0.getOperand(0),
4020 cast<CondCodeSDNode>(N0.getOperand(2))->get()),
4021 DAG.getNode(ISD::BUILD_VECTOR, N->getDebugLoc(), VT,
4022 &OneOps[0], OneOps.size()));
4024 // If the desired elements are smaller or larger than the source
4025 // elements we can use a matching integer vector type and then
4026 // truncate/sign extend
4027 EVT MatchingElementType =
4028 EVT::getIntegerVT(*DAG.getContext(),
4029 N0VT.getScalarType().getSizeInBits());
4030 EVT MatchingVectorType =
4031 EVT::getVectorVT(*DAG.getContext(), MatchingElementType,
4032 N0VT.getVectorNumElements());
4034 DAG.getVSetCC(N->getDebugLoc(), MatchingVectorType, N0.getOperand(0),
4036 cast<CondCodeSDNode>(N0.getOperand(2))->get());
4037 return DAG.getNode(ISD::AND, N->getDebugLoc(), VT,
4038 DAG.getSExtOrTrunc(VsetCC, N->getDebugLoc(), VT),
4039 DAG.getNode(ISD::BUILD_VECTOR, N->getDebugLoc(), VT,
4040 &OneOps[0], OneOps.size()));
4044 // zext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
4046 SimplifySelectCC(N->getDebugLoc(), N0.getOperand(0), N0.getOperand(1),
4047 DAG.getConstant(1, VT), DAG.getConstant(0, VT),
4048 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
4049 if (SCC.getNode()) return SCC;
4052 // (zext (shl (zext x), cst)) -> (shl (zext x), cst)
4053 if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL) &&
4054 isa<ConstantSDNode>(N0.getOperand(1)) &&
4055 N0.getOperand(0).getOpcode() == ISD::ZERO_EXTEND &&
4057 SDValue ShAmt = N0.getOperand(1);
4058 unsigned ShAmtVal = cast<ConstantSDNode>(ShAmt)->getZExtValue();
4059 if (N0.getOpcode() == ISD::SHL) {
4060 SDValue InnerZExt = N0.getOperand(0);
4061 // If the original shl may be shifting out bits, do not perform this
4063 unsigned KnownZeroBits = InnerZExt.getValueType().getSizeInBits() -
4064 InnerZExt.getOperand(0).getValueType().getSizeInBits();
4065 if (ShAmtVal > KnownZeroBits)
4069 DebugLoc DL = N->getDebugLoc();
4071 // Ensure that the shift amount is wide enough for the shifted value.
4072 if (VT.getSizeInBits() >= 256)
4073 ShAmt = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, ShAmt);
4075 return DAG.getNode(N0.getOpcode(), DL, VT,
4076 DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0)),
4083 SDValue DAGCombiner::visitANY_EXTEND(SDNode *N) {
4084 SDValue N0 = N->getOperand(0);
4085 EVT VT = N->getValueType(0);
4087 // fold (aext c1) -> c1
4088 if (isa<ConstantSDNode>(N0))
4089 return DAG.getNode(ISD::ANY_EXTEND, N->getDebugLoc(), VT, N0);
4090 // fold (aext (aext x)) -> (aext x)
4091 // fold (aext (zext x)) -> (zext x)
4092 // fold (aext (sext x)) -> (sext x)
4093 if (N0.getOpcode() == ISD::ANY_EXTEND ||
4094 N0.getOpcode() == ISD::ZERO_EXTEND ||
4095 N0.getOpcode() == ISD::SIGN_EXTEND)
4096 return DAG.getNode(N0.getOpcode(), N->getDebugLoc(), VT, N0.getOperand(0));
4098 // fold (aext (truncate (load x))) -> (aext (smaller load x))
4099 // fold (aext (truncate (srl (load x), c))) -> (aext (small load (x+c/n)))
4100 if (N0.getOpcode() == ISD::TRUNCATE) {
4101 SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
4102 if (NarrowLoad.getNode()) {
4103 SDNode* oye = N0.getNode()->getOperand(0).getNode();
4104 if (NarrowLoad.getNode() != N0.getNode()) {
4105 CombineTo(N0.getNode(), NarrowLoad);
4106 // CombineTo deleted the truncate, if needed, but not what's under it.
4109 return DAG.getNode(ISD::ANY_EXTEND, N->getDebugLoc(), VT, NarrowLoad);
4113 // fold (aext (truncate x))
4114 if (N0.getOpcode() == ISD::TRUNCATE) {
4115 SDValue TruncOp = N0.getOperand(0);
4116 if (TruncOp.getValueType() == VT)
4117 return TruncOp; // x iff x size == zext size.
4118 if (TruncOp.getValueType().bitsGT(VT))
4119 return DAG.getNode(ISD::TRUNCATE, N->getDebugLoc(), VT, TruncOp);
4120 return DAG.getNode(ISD::ANY_EXTEND, N->getDebugLoc(), VT, TruncOp);
4123 // Fold (aext (and (trunc x), cst)) -> (and x, cst)
4124 // if the trunc is not free.
4125 if (N0.getOpcode() == ISD::AND &&
4126 N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
4127 N0.getOperand(1).getOpcode() == ISD::Constant &&
4128 !TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(),
4129 N0.getValueType())) {
4130 SDValue X = N0.getOperand(0).getOperand(0);
4131 if (X.getValueType().bitsLT(VT)) {
4132 X = DAG.getNode(ISD::ANY_EXTEND, N->getDebugLoc(), VT, X);
4133 } else if (X.getValueType().bitsGT(VT)) {
4134 X = DAG.getNode(ISD::TRUNCATE, N->getDebugLoc(), VT, X);
4136 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
4137 Mask = Mask.zext(VT.getSizeInBits());
4138 return DAG.getNode(ISD::AND, N->getDebugLoc(), VT,
4139 X, DAG.getConstant(Mask, VT));
4142 // fold (aext (load x)) -> (aext (truncate (extload x)))
4143 // None of the supported targets knows how to perform load and any_ext
4144 // on vectors in one instruction. We only perform this transformation on
4146 if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() &&
4147 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
4148 TLI.isLoadExtLegal(ISD::EXTLOAD, N0.getValueType()))) {
4149 bool DoXform = true;
4150 SmallVector<SDNode*, 4> SetCCs;
4151 if (!N0.hasOneUse())
4152 DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ANY_EXTEND, SetCCs, TLI);
4154 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
4155 SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, N->getDebugLoc(), VT,
4157 LN0->getBasePtr(), LN0->getPointerInfo(),
4159 LN0->isVolatile(), LN0->isNonTemporal(),
4160 LN0->getAlignment());
4161 CombineTo(N, ExtLoad);
4162 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, N0.getDebugLoc(),
4163 N0.getValueType(), ExtLoad);
4164 CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
4166 // Extend SetCC uses if necessary.
4167 for (unsigned i = 0, e = SetCCs.size(); i != e; ++i) {
4168 SDNode *SetCC = SetCCs[i];
4169 SmallVector<SDValue, 4> Ops;
4171 for (unsigned j = 0; j != 2; ++j) {
4172 SDValue SOp = SetCC->getOperand(j);
4174 Ops.push_back(ExtLoad);
4176 Ops.push_back(DAG.getNode(ISD::ANY_EXTEND,
4177 N->getDebugLoc(), VT, SOp));
4180 Ops.push_back(SetCC->getOperand(2));
4181 CombineTo(SetCC, DAG.getNode(ISD::SETCC, N->getDebugLoc(),
4182 SetCC->getValueType(0),
4183 &Ops[0], Ops.size()));
4186 return SDValue(N, 0); // Return N so it doesn't get rechecked!
4190 // fold (aext (zextload x)) -> (aext (truncate (zextload x)))
4191 // fold (aext (sextload x)) -> (aext (truncate (sextload x)))
4192 // fold (aext ( extload x)) -> (aext (truncate (extload x)))
4193 if (N0.getOpcode() == ISD::LOAD &&
4194 !ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
4196 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
4197 EVT MemVT = LN0->getMemoryVT();
4198 SDValue ExtLoad = DAG.getExtLoad(LN0->getExtensionType(), N->getDebugLoc(),
4199 VT, LN0->getChain(), LN0->getBasePtr(),
4200 LN0->getPointerInfo(), MemVT,
4201 LN0->isVolatile(), LN0->isNonTemporal(),
4202 LN0->getAlignment());
4203 CombineTo(N, ExtLoad);
4204 CombineTo(N0.getNode(),
4205 DAG.getNode(ISD::TRUNCATE, N0.getDebugLoc(),
4206 N0.getValueType(), ExtLoad),
4207 ExtLoad.getValue(1));
4208 return SDValue(N, 0); // Return N so it doesn't get rechecked!
4211 if (N0.getOpcode() == ISD::SETCC) {
4212 // aext(setcc) -> sext_in_reg(vsetcc) for vectors.
4213 // Only do this before legalize for now.
4214 if (VT.isVector() && !LegalOperations) {
4215 EVT N0VT = N0.getOperand(0).getValueType();
4216 // We know that the # elements of the results is the same as the
4217 // # elements of the compare (and the # elements of the compare result
4218 // for that matter). Check to see that they are the same size. If so,
4219 // we know that the element size of the sext'd result matches the
4220 // element size of the compare operands.
4221 if (VT.getSizeInBits() == N0VT.getSizeInBits())
4222 return DAG.getVSetCC(N->getDebugLoc(), VT, N0.getOperand(0),
4224 cast<CondCodeSDNode>(N0.getOperand(2))->get());
4225 // If the desired elements are smaller or larger than the source
4226 // elements we can use a matching integer vector type and then
4227 // truncate/sign extend
4229 EVT MatchingElementType =
4230 EVT::getIntegerVT(*DAG.getContext(),
4231 N0VT.getScalarType().getSizeInBits());
4232 EVT MatchingVectorType =
4233 EVT::getVectorVT(*DAG.getContext(), MatchingElementType,
4234 N0VT.getVectorNumElements());
4236 DAG.getVSetCC(N->getDebugLoc(), MatchingVectorType, N0.getOperand(0),
4238 cast<CondCodeSDNode>(N0.getOperand(2))->get());
4239 return DAG.getSExtOrTrunc(VsetCC, N->getDebugLoc(), VT);
4243 // aext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
4245 SimplifySelectCC(N->getDebugLoc(), N0.getOperand(0), N0.getOperand(1),
4246 DAG.getConstant(1, VT), DAG.getConstant(0, VT),
4247 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
4255 /// GetDemandedBits - See if the specified operand can be simplified with the
4256 /// knowledge that only the bits specified by Mask are used. If so, return the
4257 /// simpler operand, otherwise return a null SDValue.
4258 SDValue DAGCombiner::GetDemandedBits(SDValue V, const APInt &Mask) {
4259 switch (V.getOpcode()) {
4263 // If the LHS or RHS don't contribute bits to the or, drop them.
4264 if (DAG.MaskedValueIsZero(V.getOperand(0), Mask))
4265 return V.getOperand(1);
4266 if (DAG.MaskedValueIsZero(V.getOperand(1), Mask))
4267 return V.getOperand(0);
4270 // Only look at single-use SRLs.
4271 if (!V.getNode()->hasOneUse())
4273 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(V.getOperand(1))) {
4274 // See if we can recursively simplify the LHS.
4275 unsigned Amt = RHSC->getZExtValue();
4277 // Watch out for shift count overflow though.
4278 if (Amt >= Mask.getBitWidth()) break;
4279 APInt NewMask = Mask << Amt;
4280 SDValue SimplifyLHS = GetDemandedBits(V.getOperand(0), NewMask);
4281 if (SimplifyLHS.getNode())
4282 return DAG.getNode(ISD::SRL, V.getDebugLoc(), V.getValueType(),
4283 SimplifyLHS, V.getOperand(1));
4289 /// ReduceLoadWidth - If the result of a wider load is shifted to right of N
4290 /// bits and then truncated to a narrower type and where N is a multiple
4291 /// of number of bits of the narrower type, transform it to a narrower load
4292 /// from address + N / num of bits of new type. If the result is to be
4293 /// extended, also fold the extension to form a extending load.
4294 SDValue DAGCombiner::ReduceLoadWidth(SDNode *N) {
4295 unsigned Opc = N->getOpcode();
4297 ISD::LoadExtType ExtType = ISD::NON_EXTLOAD;
4298 SDValue N0 = N->getOperand(0);
4299 EVT VT = N->getValueType(0);
4302 // This transformation isn't valid for vector loads.
4306 // Special case: SIGN_EXTEND_INREG is basically truncating to ExtVT then
4308 if (Opc == ISD::SIGN_EXTEND_INREG) {
4309 ExtType = ISD::SEXTLOAD;
4310 ExtVT = cast<VTSDNode>(N->getOperand(1))->getVT();
4311 } else if (Opc == ISD::SRL) {
4312 // Another special-case: SRL is basically zero-extending a narrower value.
4313 ExtType = ISD::ZEXTLOAD;
4315 ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1));
4316 if (!N01) return SDValue();
4317 ExtVT = EVT::getIntegerVT(*DAG.getContext(),
4318 VT.getSizeInBits() - N01->getZExtValue());
4320 if (LegalOperations && !TLI.isLoadExtLegal(ExtType, ExtVT))
4323 unsigned EVTBits = ExtVT.getSizeInBits();
4325 // Do not generate loads of non-round integer types since these can
4326 // be expensive (and would be wrong if the type is not byte sized).
4327 if (!ExtVT.isRound())
4331 if (N0.getOpcode() == ISD::SRL && N0.hasOneUse()) {
4332 if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
4333 ShAmt = N01->getZExtValue();
4334 // Is the shift amount a multiple of size of VT?
4335 if ((ShAmt & (EVTBits-1)) == 0) {
4336 N0 = N0.getOperand(0);
4337 // Is the load width a multiple of size of VT?
4338 if ((N0.getValueType().getSizeInBits() & (EVTBits-1)) != 0)
4342 // At this point, we must have a load or else we can't do the transform.
4343 if (!isa<LoadSDNode>(N0)) return SDValue();
4345 // If the shift amount is larger than the input type then we're not
4346 // accessing any of the loaded bytes. If the load was a zextload/extload
4347 // then the result of the shift+trunc is zero/undef (handled elsewhere).
4348 // If the load was a sextload then the result is a splat of the sign bit
4349 // of the extended byte. This is not worth optimizing for.
4350 if (ShAmt >= cast<LoadSDNode>(N0)->getMemoryVT().getSizeInBits())
4355 // If the load is shifted left (and the result isn't shifted back right),
4356 // we can fold the truncate through the shift.
4357 unsigned ShLeftAmt = 0;
4358 if (ShAmt == 0 && N0.getOpcode() == ISD::SHL && N0.hasOneUse() &&
4359 ExtVT == VT && TLI.isNarrowingProfitable(N0.getValueType(), VT)) {
4360 if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
4361 ShLeftAmt = N01->getZExtValue();
4362 N0 = N0.getOperand(0);
4366 // If we haven't found a load, we can't narrow it. Don't transform one with
4367 // multiple uses, this would require adding a new load.
4368 if (!isa<LoadSDNode>(N0) || !N0.hasOneUse() ||
4369 // Don't change the width of a volatile load.
4370 cast<LoadSDNode>(N0)->isVolatile())
4373 // Verify that we are actually reducing a load width here.
4374 if (cast<LoadSDNode>(N0)->getMemoryVT().getSizeInBits() < EVTBits)
4377 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
4378 EVT PtrType = N0.getOperand(1).getValueType();
4380 // For big endian targets, we need to adjust the offset to the pointer to
4381 // load the correct bytes.
4382 if (TLI.isBigEndian()) {
4383 unsigned LVTStoreBits = LN0->getMemoryVT().getStoreSizeInBits();
4384 unsigned EVTStoreBits = ExtVT.getStoreSizeInBits();
4385 ShAmt = LVTStoreBits - EVTStoreBits - ShAmt;
4388 uint64_t PtrOff = ShAmt / 8;
4389 unsigned NewAlign = MinAlign(LN0->getAlignment(), PtrOff);
4390 SDValue NewPtr = DAG.getNode(ISD::ADD, LN0->getDebugLoc(),
4391 PtrType, LN0->getBasePtr(),
4392 DAG.getConstant(PtrOff, PtrType));
4393 AddToWorkList(NewPtr.getNode());
4396 if (ExtType == ISD::NON_EXTLOAD)
4397 Load = DAG.getLoad(VT, N0.getDebugLoc(), LN0->getChain(), NewPtr,
4398 LN0->getPointerInfo().getWithOffset(PtrOff),
4399 LN0->isVolatile(), LN0->isNonTemporal(), NewAlign);
4401 Load = DAG.getExtLoad(ExtType, N0.getDebugLoc(), VT, LN0->getChain(),NewPtr,
4402 LN0->getPointerInfo().getWithOffset(PtrOff),
4403 ExtVT, LN0->isVolatile(), LN0->isNonTemporal(),
4406 // Replace the old load's chain with the new load's chain.
4407 WorkListRemover DeadNodes(*this);
4408 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1),
4411 // Shift the result left, if we've swallowed a left shift.
4412 SDValue Result = Load;
4413 if (ShLeftAmt != 0) {
4414 EVT ShImmTy = getShiftAmountTy(Result.getValueType());
4415 if (!isUIntN(ShImmTy.getSizeInBits(), ShLeftAmt))
4417 Result = DAG.getNode(ISD::SHL, N0.getDebugLoc(), VT,
4418 Result, DAG.getConstant(ShLeftAmt, ShImmTy));
4421 // Return the new loaded value.
4425 SDValue DAGCombiner::visitSIGN_EXTEND_INREG(SDNode *N) {
4426 SDValue N0 = N->getOperand(0);
4427 SDValue N1 = N->getOperand(1);
4428 EVT VT = N->getValueType(0);
4429 EVT EVT = cast<VTSDNode>(N1)->getVT();
4430 unsigned VTBits = VT.getScalarType().getSizeInBits();
4431 unsigned EVTBits = EVT.getScalarType().getSizeInBits();
4433 // fold (sext_in_reg c1) -> c1
4434 if (isa<ConstantSDNode>(N0) || N0.getOpcode() == ISD::UNDEF)
4435 return DAG.getNode(ISD::SIGN_EXTEND_INREG, N->getDebugLoc(), VT, N0, N1);
4437 // If the input is already sign extended, just drop the extension.
4438 if (DAG.ComputeNumSignBits(N0) >= VTBits-EVTBits+1)
4441 // fold (sext_in_reg (sext_in_reg x, VT2), VT1) -> (sext_in_reg x, minVT) pt2
4442 if (N0.getOpcode() == ISD::SIGN_EXTEND_INREG &&
4443 EVT.bitsLT(cast<VTSDNode>(N0.getOperand(1))->getVT())) {
4444 return DAG.getNode(ISD::SIGN_EXTEND_INREG, N->getDebugLoc(), VT,
4445 N0.getOperand(0), N1);
4448 // fold (sext_in_reg (sext x)) -> (sext x)
4449 // fold (sext_in_reg (aext x)) -> (sext x)
4450 // if x is small enough.
4451 if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND) {
4452 SDValue N00 = N0.getOperand(0);
4453 if (N00.getValueType().getScalarType().getSizeInBits() <= EVTBits &&
4454 (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND, VT)))
4455 return DAG.getNode(ISD::SIGN_EXTEND, N->getDebugLoc(), VT, N00, N1);
4458 // fold (sext_in_reg x) -> (zext_in_reg x) if the sign bit is known zero.
4459 if (DAG.MaskedValueIsZero(N0, APInt::getBitsSet(VTBits, EVTBits-1, EVTBits)))
4460 return DAG.getZeroExtendInReg(N0, N->getDebugLoc(), EVT);
4462 // fold operands of sext_in_reg based on knowledge that the top bits are not
4464 if (SimplifyDemandedBits(SDValue(N, 0)))
4465 return SDValue(N, 0);
4467 // fold (sext_in_reg (load x)) -> (smaller sextload x)
4468 // fold (sext_in_reg (srl (load x), c)) -> (smaller sextload (x+c/evtbits))
4469 SDValue NarrowLoad = ReduceLoadWidth(N);
4470 if (NarrowLoad.getNode())
4473 // fold (sext_in_reg (srl X, 24), i8) -> (sra X, 24)
4474 // fold (sext_in_reg (srl X, 23), i8) -> (sra X, 23) iff possible.
4475 // We already fold "(sext_in_reg (srl X, 25), i8) -> srl X, 25" above.
4476 if (N0.getOpcode() == ISD::SRL) {
4477 if (ConstantSDNode *ShAmt = dyn_cast<ConstantSDNode>(N0.getOperand(1)))
4478 if (ShAmt->getZExtValue()+EVTBits <= VTBits) {
4479 // We can turn this into an SRA iff the input to the SRL is already sign
4481 unsigned InSignBits = DAG.ComputeNumSignBits(N0.getOperand(0));
4482 if (VTBits-(ShAmt->getZExtValue()+EVTBits) < InSignBits)
4483 return DAG.getNode(ISD::SRA, N->getDebugLoc(), VT,
4484 N0.getOperand(0), N0.getOperand(1));
4488 // fold (sext_inreg (extload x)) -> (sextload x)
4489 if (ISD::isEXTLoad(N0.getNode()) &&
4490 ISD::isUNINDEXEDLoad(N0.getNode()) &&
4491 EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
4492 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
4493 TLI.isLoadExtLegal(ISD::SEXTLOAD, EVT))) {
4494 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
4495 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, N->getDebugLoc(), VT,
4497 LN0->getBasePtr(), LN0->getPointerInfo(),
4499 LN0->isVolatile(), LN0->isNonTemporal(),
4500 LN0->getAlignment());
4501 CombineTo(N, ExtLoad);
4502 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
4503 return SDValue(N, 0); // Return N so it doesn't get rechecked!
4505 // fold (sext_inreg (zextload x)) -> (sextload x) iff load has one use
4506 if (ISD::isZEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
4508 EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
4509 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
4510 TLI.isLoadExtLegal(ISD::SEXTLOAD, EVT))) {
4511 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
4512 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, N->getDebugLoc(), VT,
4514 LN0->getBasePtr(), LN0->getPointerInfo(),
4516 LN0->isVolatile(), LN0->isNonTemporal(),
4517 LN0->getAlignment());
4518 CombineTo(N, ExtLoad);
4519 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
4520 return SDValue(N, 0); // Return N so it doesn't get rechecked!
4525 SDValue DAGCombiner::visitTRUNCATE(SDNode *N) {
4526 SDValue N0 = N->getOperand(0);
4527 EVT VT = N->getValueType(0);
4530 if (N0.getValueType() == N->getValueType(0))
4532 // fold (truncate c1) -> c1
4533 if (isa<ConstantSDNode>(N0))
4534 return DAG.getNode(ISD::TRUNCATE, N->getDebugLoc(), VT, N0);
4535 // fold (truncate (truncate x)) -> (truncate x)
4536 if (N0.getOpcode() == ISD::TRUNCATE)
4537 return DAG.getNode(ISD::TRUNCATE, N->getDebugLoc(), VT, N0.getOperand(0));
4538 // fold (truncate (ext x)) -> (ext x) or (truncate x) or x
4539 if (N0.getOpcode() == ISD::ZERO_EXTEND ||
4540 N0.getOpcode() == ISD::SIGN_EXTEND ||
4541 N0.getOpcode() == ISD::ANY_EXTEND) {
4542 if (N0.getOperand(0).getValueType().bitsLT(VT))
4543 // if the source is smaller than the dest, we still need an extend
4544 return DAG.getNode(N0.getOpcode(), N->getDebugLoc(), VT,
4546 else if (N0.getOperand(0).getValueType().bitsGT(VT))
4547 // if the source is larger than the dest, than we just need the truncate
4548 return DAG.getNode(ISD::TRUNCATE, N->getDebugLoc(), VT, N0.getOperand(0));
4550 // if the source and dest are the same type, we can drop both the extend
4551 // and the truncate.
4552 return N0.getOperand(0);
4555 // See if we can simplify the input to this truncate through knowledge that
4556 // only the low bits are being used.
4557 // For example "trunc (or (shl x, 8), y)" // -> trunc y
4558 // Currently we only perform this optimization on scalars because vectors
4559 // may have different active low bits.
4560 if (!VT.isVector()) {
4562 GetDemandedBits(N0, APInt::getLowBitsSet(N0.getValueSizeInBits(),
4563 VT.getSizeInBits()));
4564 if (Shorter.getNode())
4565 return DAG.getNode(ISD::TRUNCATE, N->getDebugLoc(), VT, Shorter);
4567 // fold (truncate (load x)) -> (smaller load x)
4568 // fold (truncate (srl (load x), c)) -> (smaller load (x+c/evtbits))
4569 if (!LegalTypes || TLI.isTypeDesirableForOp(N0.getOpcode(), VT)) {
4570 SDValue Reduced = ReduceLoadWidth(N);
4571 if (Reduced.getNode())
4575 // Simplify the operands using demanded-bits information.
4576 if (!VT.isVector() &&
4577 SimplifyDemandedBits(SDValue(N, 0)))
4578 return SDValue(N, 0);
4583 static SDNode *getBuildPairElt(SDNode *N, unsigned i) {
4584 SDValue Elt = N->getOperand(i);
4585 if (Elt.getOpcode() != ISD::MERGE_VALUES)
4586 return Elt.getNode();
4587 return Elt.getOperand(Elt.getResNo()).getNode();
4590 /// CombineConsecutiveLoads - build_pair (load, load) -> load
4591 /// if load locations are consecutive.
4592 SDValue DAGCombiner::CombineConsecutiveLoads(SDNode *N, EVT VT) {
4593 assert(N->getOpcode() == ISD::BUILD_PAIR);
4595 LoadSDNode *LD1 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 0));
4596 LoadSDNode *LD2 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 1));
4597 if (!LD1 || !LD2 || !ISD::isNON_EXTLoad(LD1) || !LD1->hasOneUse() ||
4598 LD1->getPointerInfo().getAddrSpace() !=
4599 LD2->getPointerInfo().getAddrSpace())
4601 EVT LD1VT = LD1->getValueType(0);
4603 if (ISD::isNON_EXTLoad(LD2) &&
4605 // If both are volatile this would reduce the number of volatile loads.
4606 // If one is volatile it might be ok, but play conservative and bail out.
4607 !LD1->isVolatile() &&
4608 !LD2->isVolatile() &&
4609 DAG.isConsecutiveLoad(LD2, LD1, LD1VT.getSizeInBits()/8, 1)) {
4610 unsigned Align = LD1->getAlignment();
4611 unsigned NewAlign = TLI.getTargetData()->
4612 getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
4614 if (NewAlign <= Align &&
4615 (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT)))
4616 return DAG.getLoad(VT, N->getDebugLoc(), LD1->getChain(),
4617 LD1->getBasePtr(), LD1->getPointerInfo(),
4618 false, false, Align);
4624 SDValue DAGCombiner::visitBITCAST(SDNode *N) {
4625 SDValue N0 = N->getOperand(0);
4626 EVT VT = N->getValueType(0);
4628 // If the input is a BUILD_VECTOR with all constant elements, fold this now.
4629 // Only do this before legalize, since afterward the target may be depending
4630 // on the bitconvert.
4631 // First check to see if this is all constant.
4633 N0.getOpcode() == ISD::BUILD_VECTOR && N0.getNode()->hasOneUse() &&
4635 bool isSimple = true;
4636 for (unsigned i = 0, e = N0.getNumOperands(); i != e; ++i)
4637 if (N0.getOperand(i).getOpcode() != ISD::UNDEF &&
4638 N0.getOperand(i).getOpcode() != ISD::Constant &&
4639 N0.getOperand(i).getOpcode() != ISD::ConstantFP) {
4644 EVT DestEltVT = N->getValueType(0).getVectorElementType();
4645 assert(!DestEltVT.isVector() &&
4646 "Element type of vector ValueType must not be vector!");
4648 return ConstantFoldBITCASTofBUILD_VECTOR(N0.getNode(), DestEltVT);
4651 // If the input is a constant, let getNode fold it.
4652 if (isa<ConstantSDNode>(N0) || isa<ConstantFPSDNode>(N0)) {
4653 SDValue Res = DAG.getNode(ISD::BITCAST, N->getDebugLoc(), VT, N0);
4654 if (Res.getNode() != N) {
4655 if (!LegalOperations ||
4656 TLI.isOperationLegal(Res.getNode()->getOpcode(), VT))
4659 // Folding it resulted in an illegal node, and it's too late to
4660 // do that. Clean up the old node and forego the transformation.
4661 // Ideally this won't happen very often, because instcombine
4662 // and the earlier dagcombine runs (where illegal nodes are
4663 // permitted) should have folded most of them already.
4664 DAG.DeleteNode(Res.getNode());
4668 // (conv (conv x, t1), t2) -> (conv x, t2)
4669 if (N0.getOpcode() == ISD::BITCAST)
4670 return DAG.getNode(ISD::BITCAST, N->getDebugLoc(), VT,
4673 // fold (conv (load x)) -> (load (conv*)x)
4674 // If the resultant load doesn't need a higher alignment than the original!
4675 if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
4676 // Do not change the width of a volatile load.
4677 !cast<LoadSDNode>(N0)->isVolatile() &&
4678 (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT))) {
4679 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
4680 unsigned Align = TLI.getTargetData()->
4681 getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
4682 unsigned OrigAlign = LN0->getAlignment();
4684 if (Align <= OrigAlign) {
4685 SDValue Load = DAG.getLoad(VT, N->getDebugLoc(), LN0->getChain(),
4686 LN0->getBasePtr(), LN0->getPointerInfo(),
4687 LN0->isVolatile(), LN0->isNonTemporal(),
4690 CombineTo(N0.getNode(),
4691 DAG.getNode(ISD::BITCAST, N0.getDebugLoc(),
4692 N0.getValueType(), Load),
4698 // fold (bitconvert (fneg x)) -> (xor (bitconvert x), signbit)
4699 // fold (bitconvert (fabs x)) -> (and (bitconvert x), (not signbit))
4700 // This often reduces constant pool loads.
4701 if ((N0.getOpcode() == ISD::FNEG || N0.getOpcode() == ISD::FABS) &&
4702 N0.getNode()->hasOneUse() && VT.isInteger() && !VT.isVector()) {
4703 SDValue NewConv = DAG.getNode(ISD::BITCAST, N0.getDebugLoc(), VT,
4705 AddToWorkList(NewConv.getNode());
4707 APInt SignBit = APInt::getSignBit(VT.getSizeInBits());
4708 if (N0.getOpcode() == ISD::FNEG)
4709 return DAG.getNode(ISD::XOR, N->getDebugLoc(), VT,
4710 NewConv, DAG.getConstant(SignBit, VT));
4711 assert(N0.getOpcode() == ISD::FABS);
4712 return DAG.getNode(ISD::AND, N->getDebugLoc(), VT,
4713 NewConv, DAG.getConstant(~SignBit, VT));
4716 // fold (bitconvert (fcopysign cst, x)) ->
4717 // (or (and (bitconvert x), sign), (and cst, (not sign)))
4718 // Note that we don't handle (copysign x, cst) because this can always be
4719 // folded to an fneg or fabs.
4720 if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse() &&
4721 isa<ConstantFPSDNode>(N0.getOperand(0)) &&
4722 VT.isInteger() && !VT.isVector()) {
4723 unsigned OrigXWidth = N0.getOperand(1).getValueType().getSizeInBits();
4724 EVT IntXVT = EVT::getIntegerVT(*DAG.getContext(), OrigXWidth);
4725 if (isTypeLegal(IntXVT)) {
4726 SDValue X = DAG.getNode(ISD::BITCAST, N0.getDebugLoc(),
4727 IntXVT, N0.getOperand(1));
4728 AddToWorkList(X.getNode());
4730 // If X has a different width than the result/lhs, sext it or truncate it.
4731 unsigned VTWidth = VT.getSizeInBits();
4732 if (OrigXWidth < VTWidth) {
4733 X = DAG.getNode(ISD::SIGN_EXTEND, N->getDebugLoc(), VT, X);
4734 AddToWorkList(X.getNode());
4735 } else if (OrigXWidth > VTWidth) {
4736 // To get the sign bit in the right place, we have to shift it right
4737 // before truncating.
4738 X = DAG.getNode(ISD::SRL, X.getDebugLoc(),
4739 X.getValueType(), X,
4740 DAG.getConstant(OrigXWidth-VTWidth, X.getValueType()));
4741 AddToWorkList(X.getNode());
4742 X = DAG.getNode(ISD::TRUNCATE, X.getDebugLoc(), VT, X);
4743 AddToWorkList(X.getNode());
4746 APInt SignBit = APInt::getSignBit(VT.getSizeInBits());
4747 X = DAG.getNode(ISD::AND, X.getDebugLoc(), VT,
4748 X, DAG.getConstant(SignBit, VT));
4749 AddToWorkList(X.getNode());
4751 SDValue Cst = DAG.getNode(ISD::BITCAST, N0.getDebugLoc(),
4752 VT, N0.getOperand(0));
4753 Cst = DAG.getNode(ISD::AND, Cst.getDebugLoc(), VT,
4754 Cst, DAG.getConstant(~SignBit, VT));
4755 AddToWorkList(Cst.getNode());
4757 return DAG.getNode(ISD::OR, N->getDebugLoc(), VT, X, Cst);
4761 // bitconvert(build_pair(ld, ld)) -> ld iff load locations are consecutive.
4762 if (N0.getOpcode() == ISD::BUILD_PAIR) {
4763 SDValue CombineLD = CombineConsecutiveLoads(N0.getNode(), VT);
4764 if (CombineLD.getNode())
4771 SDValue DAGCombiner::visitBUILD_PAIR(SDNode *N) {
4772 EVT VT = N->getValueType(0);
4773 return CombineConsecutiveLoads(N, VT);
4776 /// ConstantFoldBITCASTofBUILD_VECTOR - We know that BV is a build_vector
4777 /// node with Constant, ConstantFP or Undef operands. DstEltVT indicates the
4778 /// destination element value type.
4779 SDValue DAGCombiner::
4780 ConstantFoldBITCASTofBUILD_VECTOR(SDNode *BV, EVT DstEltVT) {
4781 EVT SrcEltVT = BV->getValueType(0).getVectorElementType();
4783 // If this is already the right type, we're done.
4784 if (SrcEltVT == DstEltVT) return SDValue(BV, 0);
4786 unsigned SrcBitSize = SrcEltVT.getSizeInBits();
4787 unsigned DstBitSize = DstEltVT.getSizeInBits();
4789 // If this is a conversion of N elements of one type to N elements of another
4790 // type, convert each element. This handles FP<->INT cases.
4791 if (SrcBitSize == DstBitSize) {
4792 EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT,
4793 BV->getValueType(0).getVectorNumElements());
4795 // Due to the FP element handling below calling this routine recursively,
4796 // we can end up with a scalar-to-vector node here.
4797 if (BV->getOpcode() == ISD::SCALAR_TO_VECTOR)
4798 return DAG.getNode(ISD::SCALAR_TO_VECTOR, BV->getDebugLoc(), VT,
4799 DAG.getNode(ISD::BITCAST, BV->getDebugLoc(),
4800 DstEltVT, BV->getOperand(0)));
4802 SmallVector<SDValue, 8> Ops;
4803 for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) {
4804 SDValue Op = BV->getOperand(i);
4805 // If the vector element type is not legal, the BUILD_VECTOR operands
4806 // are promoted and implicitly truncated. Make that explicit here.
4807 if (Op.getValueType() != SrcEltVT)
4808 Op = DAG.getNode(ISD::TRUNCATE, BV->getDebugLoc(), SrcEltVT, Op);
4809 Ops.push_back(DAG.getNode(ISD::BITCAST, BV->getDebugLoc(),
4811 AddToWorkList(Ops.back().getNode());
4813 return DAG.getNode(ISD::BUILD_VECTOR, BV->getDebugLoc(), VT,
4814 &Ops[0], Ops.size());
4817 // Otherwise, we're growing or shrinking the elements. To avoid having to
4818 // handle annoying details of growing/shrinking FP values, we convert them to
4820 if (SrcEltVT.isFloatingPoint()) {
4821 // Convert the input float vector to a int vector where the elements are the
4823 assert((SrcEltVT == MVT::f32 || SrcEltVT == MVT::f64) && "Unknown FP VT!");
4824 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), SrcEltVT.getSizeInBits());
4825 BV = ConstantFoldBITCASTofBUILD_VECTOR(BV, IntVT).getNode();
4829 // Now we know the input is an integer vector. If the output is a FP type,
4830 // convert to integer first, then to FP of the right size.
4831 if (DstEltVT.isFloatingPoint()) {
4832 assert((DstEltVT == MVT::f32 || DstEltVT == MVT::f64) && "Unknown FP VT!");
4833 EVT TmpVT = EVT::getIntegerVT(*DAG.getContext(), DstEltVT.getSizeInBits());
4834 SDNode *Tmp = ConstantFoldBITCASTofBUILD_VECTOR(BV, TmpVT).getNode();
4836 // Next, convert to FP elements of the same size.
4837 return ConstantFoldBITCASTofBUILD_VECTOR(Tmp, DstEltVT);
4840 // Okay, we know the src/dst types are both integers of differing types.
4841 // Handling growing first.
4842 assert(SrcEltVT.isInteger() && DstEltVT.isInteger());
4843 if (SrcBitSize < DstBitSize) {
4844 unsigned NumInputsPerOutput = DstBitSize/SrcBitSize;
4846 SmallVector<SDValue, 8> Ops;
4847 for (unsigned i = 0, e = BV->getNumOperands(); i != e;
4848 i += NumInputsPerOutput) {
4849 bool isLE = TLI.isLittleEndian();
4850 APInt NewBits = APInt(DstBitSize, 0);
4851 bool EltIsUndef = true;
4852 for (unsigned j = 0; j != NumInputsPerOutput; ++j) {
4853 // Shift the previously computed bits over.
4854 NewBits <<= SrcBitSize;
4855 SDValue Op = BV->getOperand(i+ (isLE ? (NumInputsPerOutput-j-1) : j));
4856 if (Op.getOpcode() == ISD::UNDEF) continue;
4859 NewBits |= cast<ConstantSDNode>(Op)->getAPIntValue().
4860 zextOrTrunc(SrcBitSize).zext(DstBitSize);
4864 Ops.push_back(DAG.getUNDEF(DstEltVT));
4866 Ops.push_back(DAG.getConstant(NewBits, DstEltVT));
4869 EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT, Ops.size());
4870 return DAG.getNode(ISD::BUILD_VECTOR, BV->getDebugLoc(), VT,
4871 &Ops[0], Ops.size());
4874 // Finally, this must be the case where we are shrinking elements: each input
4875 // turns into multiple outputs.
4876 bool isS2V = ISD::isScalarToVector(BV);
4877 unsigned NumOutputsPerInput = SrcBitSize/DstBitSize;
4878 EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT,
4879 NumOutputsPerInput*BV->getNumOperands());
4880 SmallVector<SDValue, 8> Ops;
4882 for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) {
4883 if (BV->getOperand(i).getOpcode() == ISD::UNDEF) {
4884 for (unsigned j = 0; j != NumOutputsPerInput; ++j)
4885 Ops.push_back(DAG.getUNDEF(DstEltVT));
4889 APInt OpVal = cast<ConstantSDNode>(BV->getOperand(i))->
4890 getAPIntValue().zextOrTrunc(SrcBitSize);
4892 for (unsigned j = 0; j != NumOutputsPerInput; ++j) {
4893 APInt ThisVal = OpVal.trunc(DstBitSize);
4894 Ops.push_back(DAG.getConstant(ThisVal, DstEltVT));
4895 if (isS2V && i == 0 && j == 0 && ThisVal.zext(SrcBitSize) == OpVal)
4896 // Simply turn this into a SCALAR_TO_VECTOR of the new type.
4897 return DAG.getNode(ISD::SCALAR_TO_VECTOR, BV->getDebugLoc(), VT,
4899 OpVal = OpVal.lshr(DstBitSize);
4902 // For big endian targets, swap the order of the pieces of each element.
4903 if (TLI.isBigEndian())
4904 std::reverse(Ops.end()-NumOutputsPerInput, Ops.end());
4907 return DAG.getNode(ISD::BUILD_VECTOR, BV->getDebugLoc(), VT,
4908 &Ops[0], Ops.size());
4911 SDValue DAGCombiner::visitFADD(SDNode *N) {
4912 SDValue N0 = N->getOperand(0);
4913 SDValue N1 = N->getOperand(1);
4914 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
4915 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
4916 EVT VT = N->getValueType(0);
4919 if (VT.isVector()) {
4920 SDValue FoldedVOp = SimplifyVBinOp(N);
4921 if (FoldedVOp.getNode()) return FoldedVOp;
4924 // fold (fadd c1, c2) -> (fadd c1, c2)
4925 if (N0CFP && N1CFP && VT != MVT::ppcf128)
4926 return DAG.getNode(ISD::FADD, N->getDebugLoc(), VT, N0, N1);
4927 // canonicalize constant to RHS
4928 if (N0CFP && !N1CFP)
4929 return DAG.getNode(ISD::FADD, N->getDebugLoc(), VT, N1, N0);
4930 // fold (fadd A, 0) -> A
4931 if (UnsafeFPMath && N1CFP && N1CFP->getValueAPF().isZero())
4933 // fold (fadd A, (fneg B)) -> (fsub A, B)
4934 if (isNegatibleForFree(N1, LegalOperations) == 2)
4935 return DAG.getNode(ISD::FSUB, N->getDebugLoc(), VT, N0,
4936 GetNegatedExpression(N1, DAG, LegalOperations));
4937 // fold (fadd (fneg A), B) -> (fsub B, A)
4938 if (isNegatibleForFree(N0, LegalOperations) == 2)
4939 return DAG.getNode(ISD::FSUB, N->getDebugLoc(), VT, N1,
4940 GetNegatedExpression(N0, DAG, LegalOperations));
4942 // If allowed, fold (fadd (fadd x, c1), c2) -> (fadd x, (fadd c1, c2))
4943 if (UnsafeFPMath && N1CFP && N0.getOpcode() == ISD::FADD &&
4944 N0.getNode()->hasOneUse() && isa<ConstantFPSDNode>(N0.getOperand(1)))
4945 return DAG.getNode(ISD::FADD, N->getDebugLoc(), VT, N0.getOperand(0),
4946 DAG.getNode(ISD::FADD, N->getDebugLoc(), VT,
4947 N0.getOperand(1), N1));
4952 SDValue DAGCombiner::visitFSUB(SDNode *N) {
4953 SDValue N0 = N->getOperand(0);
4954 SDValue N1 = N->getOperand(1);
4955 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
4956 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
4957 EVT VT = N->getValueType(0);
4960 if (VT.isVector()) {
4961 SDValue FoldedVOp = SimplifyVBinOp(N);
4962 if (FoldedVOp.getNode()) return FoldedVOp;
4965 // fold (fsub c1, c2) -> c1-c2
4966 if (N0CFP && N1CFP && VT != MVT::ppcf128)
4967 return DAG.getNode(ISD::FSUB, N->getDebugLoc(), VT, N0, N1);
4968 // fold (fsub A, 0) -> A
4969 if (UnsafeFPMath && N1CFP && N1CFP->getValueAPF().isZero())
4971 // fold (fsub 0, B) -> -B
4972 if (UnsafeFPMath && N0CFP && N0CFP->getValueAPF().isZero()) {
4973 if (isNegatibleForFree(N1, LegalOperations))
4974 return GetNegatedExpression(N1, DAG, LegalOperations);
4975 if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
4976 return DAG.getNode(ISD::FNEG, N->getDebugLoc(), VT, N1);
4978 // fold (fsub A, (fneg B)) -> (fadd A, B)
4979 if (isNegatibleForFree(N1, LegalOperations))
4980 return DAG.getNode(ISD::FADD, N->getDebugLoc(), VT, N0,
4981 GetNegatedExpression(N1, DAG, LegalOperations));
4986 SDValue DAGCombiner::visitFMUL(SDNode *N) {
4987 SDValue N0 = N->getOperand(0);
4988 SDValue N1 = N->getOperand(1);
4989 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
4990 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
4991 EVT VT = N->getValueType(0);
4994 if (VT.isVector()) {
4995 SDValue FoldedVOp = SimplifyVBinOp(N);
4996 if (FoldedVOp.getNode()) return FoldedVOp;
4999 // fold (fmul c1, c2) -> c1*c2
5000 if (N0CFP && N1CFP && VT != MVT::ppcf128)
5001 return DAG.getNode(ISD::FMUL, N->getDebugLoc(), VT, N0, N1);
5002 // canonicalize constant to RHS
5003 if (N0CFP && !N1CFP)
5004 return DAG.getNode(ISD::FMUL, N->getDebugLoc(), VT, N1, N0);
5005 // fold (fmul A, 0) -> 0
5006 if (UnsafeFPMath && N1CFP && N1CFP->getValueAPF().isZero())
5008 // fold (fmul A, 0) -> 0, vector edition.
5009 if (UnsafeFPMath && ISD::isBuildVectorAllZeros(N1.getNode()))
5011 // fold (fmul X, 2.0) -> (fadd X, X)
5012 if (N1CFP && N1CFP->isExactlyValue(+2.0))
5013 return DAG.getNode(ISD::FADD, N->getDebugLoc(), VT, N0, N0);
5014 // fold (fmul X, -1.0) -> (fneg X)
5015 if (N1CFP && N1CFP->isExactlyValue(-1.0))
5016 if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
5017 return DAG.getNode(ISD::FNEG, N->getDebugLoc(), VT, N0);
5019 // fold (fmul (fneg X), (fneg Y)) -> (fmul X, Y)
5020 if (char LHSNeg = isNegatibleForFree(N0, LegalOperations)) {
5021 if (char RHSNeg = isNegatibleForFree(N1, LegalOperations)) {
5022 // Both can be negated for free, check to see if at least one is cheaper
5024 if (LHSNeg == 2 || RHSNeg == 2)
5025 return DAG.getNode(ISD::FMUL, N->getDebugLoc(), VT,
5026 GetNegatedExpression(N0, DAG, LegalOperations),
5027 GetNegatedExpression(N1, DAG, LegalOperations));
5031 // If allowed, fold (fmul (fmul x, c1), c2) -> (fmul x, (fmul c1, c2))
5032 if (UnsafeFPMath && N1CFP && N0.getOpcode() == ISD::FMUL &&
5033 N0.getNode()->hasOneUse() && isa<ConstantFPSDNode>(N0.getOperand(1)))
5034 return DAG.getNode(ISD::FMUL, N->getDebugLoc(), VT, N0.getOperand(0),
5035 DAG.getNode(ISD::FMUL, N->getDebugLoc(), VT,
5036 N0.getOperand(1), N1));
5041 SDValue DAGCombiner::visitFDIV(SDNode *N) {
5042 SDValue N0 = N->getOperand(0);
5043 SDValue N1 = N->getOperand(1);
5044 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
5045 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
5046 EVT VT = N->getValueType(0);
5049 if (VT.isVector()) {
5050 SDValue FoldedVOp = SimplifyVBinOp(N);
5051 if (FoldedVOp.getNode()) return FoldedVOp;
5054 // fold (fdiv c1, c2) -> c1/c2
5055 if (N0CFP && N1CFP && VT != MVT::ppcf128)
5056 return DAG.getNode(ISD::FDIV, N->getDebugLoc(), VT, N0, N1);
5059 // (fdiv (fneg X), (fneg Y)) -> (fdiv X, Y)
5060 if (char LHSNeg = isNegatibleForFree(N0, LegalOperations)) {
5061 if (char RHSNeg = isNegatibleForFree(N1, LegalOperations)) {
5062 // Both can be negated for free, check to see if at least one is cheaper
5064 if (LHSNeg == 2 || RHSNeg == 2)
5065 return DAG.getNode(ISD::FDIV, N->getDebugLoc(), VT,
5066 GetNegatedExpression(N0, DAG, LegalOperations),
5067 GetNegatedExpression(N1, DAG, LegalOperations));
5074 SDValue DAGCombiner::visitFREM(SDNode *N) {
5075 SDValue N0 = N->getOperand(0);
5076 SDValue N1 = N->getOperand(1);
5077 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
5078 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
5079 EVT VT = N->getValueType(0);
5081 // fold (frem c1, c2) -> fmod(c1,c2)
5082 if (N0CFP && N1CFP && VT != MVT::ppcf128)
5083 return DAG.getNode(ISD::FREM, N->getDebugLoc(), VT, N0, N1);
5088 SDValue DAGCombiner::visitFCOPYSIGN(SDNode *N) {
5089 SDValue N0 = N->getOperand(0);
5090 SDValue N1 = N->getOperand(1);
5091 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
5092 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
5093 EVT VT = N->getValueType(0);
5095 if (N0CFP && N1CFP && VT != MVT::ppcf128) // Constant fold
5096 return DAG.getNode(ISD::FCOPYSIGN, N->getDebugLoc(), VT, N0, N1);
5099 const APFloat& V = N1CFP->getValueAPF();
5100 // copysign(x, c1) -> fabs(x) iff ispos(c1)
5101 // copysign(x, c1) -> fneg(fabs(x)) iff isneg(c1)
5102 if (!V.isNegative()) {
5103 if (!LegalOperations || TLI.isOperationLegal(ISD::FABS, VT))
5104 return DAG.getNode(ISD::FABS, N->getDebugLoc(), VT, N0);
5106 if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
5107 return DAG.getNode(ISD::FNEG, N->getDebugLoc(), VT,
5108 DAG.getNode(ISD::FABS, N0.getDebugLoc(), VT, N0));
5112 // copysign(fabs(x), y) -> copysign(x, y)
5113 // copysign(fneg(x), y) -> copysign(x, y)
5114 // copysign(copysign(x,z), y) -> copysign(x, y)
5115 if (N0.getOpcode() == ISD::FABS || N0.getOpcode() == ISD::FNEG ||
5116 N0.getOpcode() == ISD::FCOPYSIGN)
5117 return DAG.getNode(ISD::FCOPYSIGN, N->getDebugLoc(), VT,
5118 N0.getOperand(0), N1);
5120 // copysign(x, abs(y)) -> abs(x)
5121 if (N1.getOpcode() == ISD::FABS)
5122 return DAG.getNode(ISD::FABS, N->getDebugLoc(), VT, N0);
5124 // copysign(x, copysign(y,z)) -> copysign(x, z)
5125 if (N1.getOpcode() == ISD::FCOPYSIGN)
5126 return DAG.getNode(ISD::FCOPYSIGN, N->getDebugLoc(), VT,
5127 N0, N1.getOperand(1));
5129 // copysign(x, fp_extend(y)) -> copysign(x, y)
5130 // copysign(x, fp_round(y)) -> copysign(x, y)
5131 if (N1.getOpcode() == ISD::FP_EXTEND || N1.getOpcode() == ISD::FP_ROUND)
5132 return DAG.getNode(ISD::FCOPYSIGN, N->getDebugLoc(), VT,
5133 N0, N1.getOperand(0));
5138 SDValue DAGCombiner::visitSINT_TO_FP(SDNode *N) {
5139 SDValue N0 = N->getOperand(0);
5140 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
5141 EVT VT = N->getValueType(0);
5142 EVT OpVT = N0.getValueType();
5144 // fold (sint_to_fp c1) -> c1fp
5145 if (N0C && OpVT != MVT::ppcf128 &&
5146 // ...but only if the target supports immediate floating-point values
5147 (Level == llvm::Unrestricted || TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT)))
5148 return DAG.getNode(ISD::SINT_TO_FP, N->getDebugLoc(), VT, N0);
5150 // If the input is a legal type, and SINT_TO_FP is not legal on this target,
5151 // but UINT_TO_FP is legal on this target, try to convert.
5152 if (!TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT) &&
5153 TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT)) {
5154 // If the sign bit is known to be zero, we can change this to UINT_TO_FP.
5155 if (DAG.SignBitIsZero(N0))
5156 return DAG.getNode(ISD::UINT_TO_FP, N->getDebugLoc(), VT, N0);
5162 SDValue DAGCombiner::visitUINT_TO_FP(SDNode *N) {
5163 SDValue N0 = N->getOperand(0);
5164 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
5165 EVT VT = N->getValueType(0);
5166 EVT OpVT = N0.getValueType();
5168 // fold (uint_to_fp c1) -> c1fp
5169 if (N0C && OpVT != MVT::ppcf128 &&
5170 // ...but only if the target supports immediate floating-point values
5171 (Level == llvm::Unrestricted || TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT)))
5172 return DAG.getNode(ISD::UINT_TO_FP, N->getDebugLoc(), VT, N0);
5174 // If the input is a legal type, and UINT_TO_FP is not legal on this target,
5175 // but SINT_TO_FP is legal on this target, try to convert.
5176 if (!TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT) &&
5177 TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT)) {
5178 // If the sign bit is known to be zero, we can change this to SINT_TO_FP.
5179 if (DAG.SignBitIsZero(N0))
5180 return DAG.getNode(ISD::SINT_TO_FP, N->getDebugLoc(), VT, N0);
5186 SDValue DAGCombiner::visitFP_TO_SINT(SDNode *N) {
5187 SDValue N0 = N->getOperand(0);
5188 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
5189 EVT VT = N->getValueType(0);
5191 // fold (fp_to_sint c1fp) -> c1
5193 return DAG.getNode(ISD::FP_TO_SINT, N->getDebugLoc(), VT, N0);
5198 SDValue DAGCombiner::visitFP_TO_UINT(SDNode *N) {
5199 SDValue N0 = N->getOperand(0);
5200 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
5201 EVT VT = N->getValueType(0);
5203 // fold (fp_to_uint c1fp) -> c1
5204 if (N0CFP && VT != MVT::ppcf128)
5205 return DAG.getNode(ISD::FP_TO_UINT, N->getDebugLoc(), VT, N0);
5210 SDValue DAGCombiner::visitFP_ROUND(SDNode *N) {
5211 SDValue N0 = N->getOperand(0);
5212 SDValue N1 = N->getOperand(1);
5213 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
5214 EVT VT = N->getValueType(0);
5216 // fold (fp_round c1fp) -> c1fp
5217 if (N0CFP && N0.getValueType() != MVT::ppcf128)
5218 return DAG.getNode(ISD::FP_ROUND, N->getDebugLoc(), VT, N0, N1);
5220 // fold (fp_round (fp_extend x)) -> x
5221 if (N0.getOpcode() == ISD::FP_EXTEND && VT == N0.getOperand(0).getValueType())
5222 return N0.getOperand(0);
5224 // fold (fp_round (fp_round x)) -> (fp_round x)
5225 if (N0.getOpcode() == ISD::FP_ROUND) {
5226 // This is a value preserving truncation if both round's are.
5227 bool IsTrunc = N->getConstantOperandVal(1) == 1 &&
5228 N0.getNode()->getConstantOperandVal(1) == 1;
5229 return DAG.getNode(ISD::FP_ROUND, N->getDebugLoc(), VT, N0.getOperand(0),
5230 DAG.getIntPtrConstant(IsTrunc));
5233 // fold (fp_round (copysign X, Y)) -> (copysign (fp_round X), Y)
5234 if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse()) {
5235 SDValue Tmp = DAG.getNode(ISD::FP_ROUND, N0.getDebugLoc(), VT,
5236 N0.getOperand(0), N1);
5237 AddToWorkList(Tmp.getNode());
5238 return DAG.getNode(ISD::FCOPYSIGN, N->getDebugLoc(), VT,
5239 Tmp, N0.getOperand(1));
5245 SDValue DAGCombiner::visitFP_ROUND_INREG(SDNode *N) {
5246 SDValue N0 = N->getOperand(0);
5247 EVT VT = N->getValueType(0);
5248 EVT EVT = cast<VTSDNode>(N->getOperand(1))->getVT();
5249 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
5251 // fold (fp_round_inreg c1fp) -> c1fp
5252 if (N0CFP && isTypeLegal(EVT)) {
5253 SDValue Round = DAG.getConstantFP(*N0CFP->getConstantFPValue(), EVT);
5254 return DAG.getNode(ISD::FP_EXTEND, N->getDebugLoc(), VT, Round);
5260 SDValue DAGCombiner::visitFP_EXTEND(SDNode *N) {
5261 SDValue N0 = N->getOperand(0);
5262 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
5263 EVT VT = N->getValueType(0);
5265 // If this is fp_round(fpextend), don't fold it, allow ourselves to be folded.
5266 if (N->hasOneUse() &&
5267 N->use_begin()->getOpcode() == ISD::FP_ROUND)
5270 // fold (fp_extend c1fp) -> c1fp
5271 if (N0CFP && VT != MVT::ppcf128)
5272 return DAG.getNode(ISD::FP_EXTEND, N->getDebugLoc(), VT, N0);
5274 // Turn fp_extend(fp_round(X, 1)) -> x since the fp_round doesn't affect the
5276 if (N0.getOpcode() == ISD::FP_ROUND
5277 && N0.getNode()->getConstantOperandVal(1) == 1) {
5278 SDValue In = N0.getOperand(0);
5279 if (In.getValueType() == VT) return In;
5280 if (VT.bitsLT(In.getValueType()))
5281 return DAG.getNode(ISD::FP_ROUND, N->getDebugLoc(), VT,
5282 In, N0.getOperand(1));
5283 return DAG.getNode(ISD::FP_EXTEND, N->getDebugLoc(), VT, In);
5286 // fold (fpext (load x)) -> (fpext (fptrunc (extload x)))
5287 if (ISD::isNON_EXTLoad(N0.getNode()) && N0.hasOneUse() &&
5288 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
5289 TLI.isLoadExtLegal(ISD::EXTLOAD, N0.getValueType()))) {
5290 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5291 SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, N->getDebugLoc(), VT,
5293 LN0->getBasePtr(), LN0->getPointerInfo(),
5295 LN0->isVolatile(), LN0->isNonTemporal(),
5296 LN0->getAlignment());
5297 CombineTo(N, ExtLoad);
5298 CombineTo(N0.getNode(),
5299 DAG.getNode(ISD::FP_ROUND, N0.getDebugLoc(),
5300 N0.getValueType(), ExtLoad, DAG.getIntPtrConstant(1)),
5301 ExtLoad.getValue(1));
5302 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5308 SDValue DAGCombiner::visitFNEG(SDNode *N) {
5309 SDValue N0 = N->getOperand(0);
5310 EVT VT = N->getValueType(0);
5312 if (isNegatibleForFree(N0, LegalOperations))
5313 return GetNegatedExpression(N0, DAG, LegalOperations);
5315 // Transform fneg(bitconvert(x)) -> bitconvert(x^sign) to avoid loading
5316 // constant pool values.
5317 if (N0.getOpcode() == ISD::BITCAST &&
5319 N0.getNode()->hasOneUse() &&
5320 N0.getOperand(0).getValueType().isInteger()) {
5321 SDValue Int = N0.getOperand(0);
5322 EVT IntVT = Int.getValueType();
5323 if (IntVT.isInteger() && !IntVT.isVector()) {
5324 Int = DAG.getNode(ISD::XOR, N0.getDebugLoc(), IntVT, Int,
5325 DAG.getConstant(APInt::getSignBit(IntVT.getSizeInBits()), IntVT));
5326 AddToWorkList(Int.getNode());
5327 return DAG.getNode(ISD::BITCAST, N->getDebugLoc(),
5335 SDValue DAGCombiner::visitFABS(SDNode *N) {
5336 SDValue N0 = N->getOperand(0);
5337 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
5338 EVT VT = N->getValueType(0);
5340 // fold (fabs c1) -> fabs(c1)
5341 if (N0CFP && VT != MVT::ppcf128)
5342 return DAG.getNode(ISD::FABS, N->getDebugLoc(), VT, N0);
5343 // fold (fabs (fabs x)) -> (fabs x)
5344 if (N0.getOpcode() == ISD::FABS)
5345 return N->getOperand(0);
5346 // fold (fabs (fneg x)) -> (fabs x)
5347 // fold (fabs (fcopysign x, y)) -> (fabs x)
5348 if (N0.getOpcode() == ISD::FNEG || N0.getOpcode() == ISD::FCOPYSIGN)
5349 return DAG.getNode(ISD::FABS, N->getDebugLoc(), VT, N0.getOperand(0));
5351 // Transform fabs(bitconvert(x)) -> bitconvert(x&~sign) to avoid loading
5352 // constant pool values.
5353 if (N0.getOpcode() == ISD::BITCAST && N0.getNode()->hasOneUse() &&
5354 N0.getOperand(0).getValueType().isInteger() &&
5355 !N0.getOperand(0).getValueType().isVector()) {
5356 SDValue Int = N0.getOperand(0);
5357 EVT IntVT = Int.getValueType();
5358 if (IntVT.isInteger() && !IntVT.isVector()) {
5359 Int = DAG.getNode(ISD::AND, N0.getDebugLoc(), IntVT, Int,
5360 DAG.getConstant(~APInt::getSignBit(IntVT.getSizeInBits()), IntVT));
5361 AddToWorkList(Int.getNode());
5362 return DAG.getNode(ISD::BITCAST, N->getDebugLoc(),
5363 N->getValueType(0), Int);
5370 SDValue DAGCombiner::visitBRCOND(SDNode *N) {
5371 SDValue Chain = N->getOperand(0);
5372 SDValue N1 = N->getOperand(1);
5373 SDValue N2 = N->getOperand(2);
5375 // If N is a constant we could fold this into a fallthrough or unconditional
5376 // branch. However that doesn't happen very often in normal code, because
5377 // Instcombine/SimplifyCFG should have handled the available opportunities.
5378 // If we did this folding here, it would be necessary to update the
5379 // MachineBasicBlock CFG, which is awkward.
5381 // fold a brcond with a setcc condition into a BR_CC node if BR_CC is legal
5383 if (N1.getOpcode() == ISD::SETCC &&
5384 TLI.isOperationLegalOrCustom(ISD::BR_CC, MVT::Other)) {
5385 return DAG.getNode(ISD::BR_CC, N->getDebugLoc(), MVT::Other,
5386 Chain, N1.getOperand(2),
5387 N1.getOperand(0), N1.getOperand(1), N2);
5390 if ((N1.hasOneUse() && N1.getOpcode() == ISD::SRL) ||
5391 ((N1.getOpcode() == ISD::TRUNCATE && N1.hasOneUse()) &&
5392 (N1.getOperand(0).hasOneUse() &&
5393 N1.getOperand(0).getOpcode() == ISD::SRL))) {
5395 if (N1.getOpcode() == ISD::TRUNCATE) {
5396 // Look pass the truncate.
5397 Trunc = N1.getNode();
5398 N1 = N1.getOperand(0);
5401 // Match this pattern so that we can generate simpler code:
5404 // %b = and i32 %a, 2
5405 // %c = srl i32 %b, 1
5406 // brcond i32 %c ...
5411 // %b = and i32 %a, 2
5412 // %c = setcc eq %b, 0
5415 // This applies only when the AND constant value has one bit set and the
5416 // SRL constant is equal to the log2 of the AND constant. The back-end is
5417 // smart enough to convert the result into a TEST/JMP sequence.
5418 SDValue Op0 = N1.getOperand(0);
5419 SDValue Op1 = N1.getOperand(1);
5421 if (Op0.getOpcode() == ISD::AND &&
5422 Op1.getOpcode() == ISD::Constant) {
5423 SDValue AndOp1 = Op0.getOperand(1);
5425 if (AndOp1.getOpcode() == ISD::Constant) {
5426 const APInt &AndConst = cast<ConstantSDNode>(AndOp1)->getAPIntValue();
5428 if (AndConst.isPowerOf2() &&
5429 cast<ConstantSDNode>(Op1)->getAPIntValue()==AndConst.logBase2()) {
5431 DAG.getSetCC(N->getDebugLoc(),
5432 TLI.getSetCCResultType(Op0.getValueType()),
5433 Op0, DAG.getConstant(0, Op0.getValueType()),
5436 SDValue NewBRCond = DAG.getNode(ISD::BRCOND, N->getDebugLoc(),
5437 MVT::Other, Chain, SetCC, N2);
5438 // Don't add the new BRCond into the worklist or else SimplifySelectCC
5439 // will convert it back to (X & C1) >> C2.
5440 CombineTo(N, NewBRCond, false);
5441 // Truncate is dead.
5443 removeFromWorkList(Trunc);
5444 DAG.DeleteNode(Trunc);
5446 // Replace the uses of SRL with SETCC
5447 WorkListRemover DeadNodes(*this);
5448 DAG.ReplaceAllUsesOfValueWith(N1, SetCC, &DeadNodes);
5449 removeFromWorkList(N1.getNode());
5450 DAG.DeleteNode(N1.getNode());
5451 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5457 // Restore N1 if the above transformation doesn't match.
5458 N1 = N->getOperand(1);
5461 // Transform br(xor(x, y)) -> br(x != y)
5462 // Transform br(xor(xor(x,y), 1)) -> br (x == y)
5463 if (N1.hasOneUse() && N1.getOpcode() == ISD::XOR) {
5464 SDNode *TheXor = N1.getNode();
5465 SDValue Op0 = TheXor->getOperand(0);
5466 SDValue Op1 = TheXor->getOperand(1);
5467 if (Op0.getOpcode() == Op1.getOpcode()) {
5468 // Avoid missing important xor optimizations.
5469 SDValue Tmp = visitXOR(TheXor);
5470 if (Tmp.getNode() && Tmp.getNode() != TheXor) {
5471 DEBUG(dbgs() << "\nReplacing.8 ";
5473 dbgs() << "\nWith: ";
5474 Tmp.getNode()->dump(&DAG);
5476 WorkListRemover DeadNodes(*this);
5477 DAG.ReplaceAllUsesOfValueWith(N1, Tmp, &DeadNodes);
5478 removeFromWorkList(TheXor);
5479 DAG.DeleteNode(TheXor);
5480 return DAG.getNode(ISD::BRCOND, N->getDebugLoc(),
5481 MVT::Other, Chain, Tmp, N2);
5485 if (Op0.getOpcode() != ISD::SETCC && Op1.getOpcode() != ISD::SETCC) {
5487 if (ConstantSDNode *RHSCI = dyn_cast<ConstantSDNode>(Op0))
5488 if (RHSCI->getAPIntValue() == 1 && Op0.hasOneUse() &&
5489 Op0.getOpcode() == ISD::XOR) {
5490 TheXor = Op0.getNode();
5494 EVT SetCCVT = N1.getValueType();
5496 SetCCVT = TLI.getSetCCResultType(SetCCVT);
5497 SDValue SetCC = DAG.getSetCC(TheXor->getDebugLoc(),
5500 Equal ? ISD::SETEQ : ISD::SETNE);
5501 // Replace the uses of XOR with SETCC
5502 WorkListRemover DeadNodes(*this);
5503 DAG.ReplaceAllUsesOfValueWith(N1, SetCC, &DeadNodes);
5504 removeFromWorkList(N1.getNode());
5505 DAG.DeleteNode(N1.getNode());
5506 return DAG.getNode(ISD::BRCOND, N->getDebugLoc(),
5507 MVT::Other, Chain, SetCC, N2);
5514 // Operand List for BR_CC: Chain, CondCC, CondLHS, CondRHS, DestBB.
5516 SDValue DAGCombiner::visitBR_CC(SDNode *N) {
5517 CondCodeSDNode *CC = cast<CondCodeSDNode>(N->getOperand(1));
5518 SDValue CondLHS = N->getOperand(2), CondRHS = N->getOperand(3);
5520 // If N is a constant we could fold this into a fallthrough or unconditional
5521 // branch. However that doesn't happen very often in normal code, because
5522 // Instcombine/SimplifyCFG should have handled the available opportunities.
5523 // If we did this folding here, it would be necessary to update the
5524 // MachineBasicBlock CFG, which is awkward.
5526 // Use SimplifySetCC to simplify SETCC's.
5527 SDValue Simp = SimplifySetCC(TLI.getSetCCResultType(CondLHS.getValueType()),
5528 CondLHS, CondRHS, CC->get(), N->getDebugLoc(),
5530 if (Simp.getNode()) AddToWorkList(Simp.getNode());
5532 // fold to a simpler setcc
5533 if (Simp.getNode() && Simp.getOpcode() == ISD::SETCC)
5534 return DAG.getNode(ISD::BR_CC, N->getDebugLoc(), MVT::Other,
5535 N->getOperand(0), Simp.getOperand(2),
5536 Simp.getOperand(0), Simp.getOperand(1),
5542 /// CombineToPreIndexedLoadStore - Try turning a load / store into a
5543 /// pre-indexed load / store when the base pointer is an add or subtract
5544 /// and it has other uses besides the load / store. After the
5545 /// transformation, the new indexed load / store has effectively folded
5546 /// the add / subtract in and all of its other uses are redirected to the
5547 /// new load / store.
5548 bool DAGCombiner::CombineToPreIndexedLoadStore(SDNode *N) {
5549 if (!LegalOperations)
5555 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
5556 if (LD->isIndexed())
5558 VT = LD->getMemoryVT();
5559 if (!TLI.isIndexedLoadLegal(ISD::PRE_INC, VT) &&
5560 !TLI.isIndexedLoadLegal(ISD::PRE_DEC, VT))
5562 Ptr = LD->getBasePtr();
5563 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
5564 if (ST->isIndexed())
5566 VT = ST->getMemoryVT();
5567 if (!TLI.isIndexedStoreLegal(ISD::PRE_INC, VT) &&
5568 !TLI.isIndexedStoreLegal(ISD::PRE_DEC, VT))
5570 Ptr = ST->getBasePtr();
5576 // If the pointer is not an add/sub, or if it doesn't have multiple uses, bail
5577 // out. There is no reason to make this a preinc/predec.
5578 if ((Ptr.getOpcode() != ISD::ADD && Ptr.getOpcode() != ISD::SUB) ||
5579 Ptr.getNode()->hasOneUse())
5582 // Ask the target to do addressing mode selection.
5585 ISD::MemIndexedMode AM = ISD::UNINDEXED;
5586 if (!TLI.getPreIndexedAddressParts(N, BasePtr, Offset, AM, DAG))
5588 // Don't create a indexed load / store with zero offset.
5589 if (isa<ConstantSDNode>(Offset) &&
5590 cast<ConstantSDNode>(Offset)->isNullValue())
5593 // Try turning it into a pre-indexed load / store except when:
5594 // 1) The new base ptr is a frame index.
5595 // 2) If N is a store and the new base ptr is either the same as or is a
5596 // predecessor of the value being stored.
5597 // 3) Another use of old base ptr is a predecessor of N. If ptr is folded
5598 // that would create a cycle.
5599 // 4) All uses are load / store ops that use it as old base ptr.
5601 // Check #1. Preinc'ing a frame index would require copying the stack pointer
5602 // (plus the implicit offset) to a register to preinc anyway.
5603 if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr))
5608 SDValue Val = cast<StoreSDNode>(N)->getValue();
5609 if (Val == BasePtr || BasePtr.getNode()->isPredecessorOf(Val.getNode()))
5613 // Now check for #3 and #4.
5614 bool RealUse = false;
5615 for (SDNode::use_iterator I = Ptr.getNode()->use_begin(),
5616 E = Ptr.getNode()->use_end(); I != E; ++I) {
5620 if (Use->isPredecessorOf(N))
5623 if (!((Use->getOpcode() == ISD::LOAD &&
5624 cast<LoadSDNode>(Use)->getBasePtr() == Ptr) ||
5625 (Use->getOpcode() == ISD::STORE &&
5626 cast<StoreSDNode>(Use)->getBasePtr() == Ptr)))
5635 Result = DAG.getIndexedLoad(SDValue(N,0), N->getDebugLoc(),
5636 BasePtr, Offset, AM);
5638 Result = DAG.getIndexedStore(SDValue(N,0), N->getDebugLoc(),
5639 BasePtr, Offset, AM);
5642 DEBUG(dbgs() << "\nReplacing.4 ";
5644 dbgs() << "\nWith: ";
5645 Result.getNode()->dump(&DAG);
5647 WorkListRemover DeadNodes(*this);
5649 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0),
5651 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2),
5654 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1),
5658 // Finally, since the node is now dead, remove it from the graph.
5661 // Replace the uses of Ptr with uses of the updated base value.
5662 DAG.ReplaceAllUsesOfValueWith(Ptr, Result.getValue(isLoad ? 1 : 0),
5664 removeFromWorkList(Ptr.getNode());
5665 DAG.DeleteNode(Ptr.getNode());
5670 /// CombineToPostIndexedLoadStore - Try to combine a load / store with a
5671 /// add / sub of the base pointer node into a post-indexed load / store.
5672 /// The transformation folded the add / subtract into the new indexed
5673 /// load / store effectively and all of its uses are redirected to the
5674 /// new load / store.
5675 bool DAGCombiner::CombineToPostIndexedLoadStore(SDNode *N) {
5676 if (!LegalOperations)
5682 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
5683 if (LD->isIndexed())
5685 VT = LD->getMemoryVT();
5686 if (!TLI.isIndexedLoadLegal(ISD::POST_INC, VT) &&
5687 !TLI.isIndexedLoadLegal(ISD::POST_DEC, VT))
5689 Ptr = LD->getBasePtr();
5690 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
5691 if (ST->isIndexed())
5693 VT = ST->getMemoryVT();
5694 if (!TLI.isIndexedStoreLegal(ISD::POST_INC, VT) &&
5695 !TLI.isIndexedStoreLegal(ISD::POST_DEC, VT))
5697 Ptr = ST->getBasePtr();
5703 if (Ptr.getNode()->hasOneUse())
5706 for (SDNode::use_iterator I = Ptr.getNode()->use_begin(),
5707 E = Ptr.getNode()->use_end(); I != E; ++I) {
5710 (Op->getOpcode() != ISD::ADD && Op->getOpcode() != ISD::SUB))
5715 ISD::MemIndexedMode AM = ISD::UNINDEXED;
5716 if (TLI.getPostIndexedAddressParts(N, Op, BasePtr, Offset, AM, DAG)) {
5717 // Don't create a indexed load / store with zero offset.
5718 if (isa<ConstantSDNode>(Offset) &&
5719 cast<ConstantSDNode>(Offset)->isNullValue())
5722 // Try turning it into a post-indexed load / store except when
5723 // 1) All uses are load / store ops that use it as base ptr.
5724 // 2) Op must be independent of N, i.e. Op is neither a predecessor
5725 // nor a successor of N. Otherwise, if Op is folded that would
5728 if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr))
5732 bool TryNext = false;
5733 for (SDNode::use_iterator II = BasePtr.getNode()->use_begin(),
5734 EE = BasePtr.getNode()->use_end(); II != EE; ++II) {
5736 if (Use == Ptr.getNode())
5739 // If all the uses are load / store addresses, then don't do the
5741 if (Use->getOpcode() == ISD::ADD || Use->getOpcode() == ISD::SUB){
5742 bool RealUse = false;
5743 for (SDNode::use_iterator III = Use->use_begin(),
5744 EEE = Use->use_end(); III != EEE; ++III) {
5745 SDNode *UseUse = *III;
5746 if (!((UseUse->getOpcode() == ISD::LOAD &&
5747 cast<LoadSDNode>(UseUse)->getBasePtr().getNode() == Use) ||
5748 (UseUse->getOpcode() == ISD::STORE &&
5749 cast<StoreSDNode>(UseUse)->getBasePtr().getNode() == Use)))
5764 if (!Op->isPredecessorOf(N) && !N->isPredecessorOf(Op)) {
5765 SDValue Result = isLoad
5766 ? DAG.getIndexedLoad(SDValue(N,0), N->getDebugLoc(),
5767 BasePtr, Offset, AM)
5768 : DAG.getIndexedStore(SDValue(N,0), N->getDebugLoc(),
5769 BasePtr, Offset, AM);
5772 DEBUG(dbgs() << "\nReplacing.5 ";
5774 dbgs() << "\nWith: ";
5775 Result.getNode()->dump(&DAG);
5777 WorkListRemover DeadNodes(*this);
5779 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0),
5781 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2),
5784 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1),
5788 // Finally, since the node is now dead, remove it from the graph.
5791 // Replace the uses of Use with uses of the updated base value.
5792 DAG.ReplaceAllUsesOfValueWith(SDValue(Op, 0),
5793 Result.getValue(isLoad ? 1 : 0),
5795 removeFromWorkList(Op);
5805 SDValue DAGCombiner::visitLOAD(SDNode *N) {
5806 LoadSDNode *LD = cast<LoadSDNode>(N);
5807 SDValue Chain = LD->getChain();
5808 SDValue Ptr = LD->getBasePtr();
5810 // If load is not volatile and there are no uses of the loaded value (and
5811 // the updated indexed value in case of indexed loads), change uses of the
5812 // chain value into uses of the chain input (i.e. delete the dead load).
5813 if (!LD->isVolatile()) {
5814 if (N->getValueType(1) == MVT::Other) {
5816 if (N->hasNUsesOfValue(0, 0)) {
5817 // It's not safe to use the two value CombineTo variant here. e.g.
5818 // v1, chain2 = load chain1, loc
5819 // v2, chain3 = load chain2, loc
5821 // Now we replace use of chain2 with chain1. This makes the second load
5822 // isomorphic to the one we are deleting, and thus makes this load live.
5823 DEBUG(dbgs() << "\nReplacing.6 ";
5825 dbgs() << "\nWith chain: ";
5826 Chain.getNode()->dump(&DAG);
5828 WorkListRemover DeadNodes(*this);
5829 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain, &DeadNodes);
5831 if (N->use_empty()) {
5832 removeFromWorkList(N);
5836 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5840 assert(N->getValueType(2) == MVT::Other && "Malformed indexed loads?");
5841 if (N->hasNUsesOfValue(0, 0) && N->hasNUsesOfValue(0, 1)) {
5842 SDValue Undef = DAG.getUNDEF(N->getValueType(0));
5843 DEBUG(dbgs() << "\nReplacing.7 ";
5845 dbgs() << "\nWith: ";
5846 Undef.getNode()->dump(&DAG);
5847 dbgs() << " and 2 other values\n");
5848 WorkListRemover DeadNodes(*this);
5849 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Undef, &DeadNodes);
5850 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1),
5851 DAG.getUNDEF(N->getValueType(1)),
5853 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 2), Chain, &DeadNodes);
5854 removeFromWorkList(N);
5856 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5861 // If this load is directly stored, replace the load value with the stored
5863 // TODO: Handle store large -> read small portion.
5864 // TODO: Handle TRUNCSTORE/LOADEXT
5865 if (ISD::isNormalLoad(N) && !LD->isVolatile()) {
5866 if (ISD::isNON_TRUNCStore(Chain.getNode())) {
5867 StoreSDNode *PrevST = cast<StoreSDNode>(Chain);
5868 if (PrevST->getBasePtr() == Ptr &&
5869 PrevST->getValue().getValueType() == N->getValueType(0))
5870 return CombineTo(N, Chain.getOperand(1), Chain);
5874 // Try to infer better alignment information than the load already has.
5875 if (OptLevel != CodeGenOpt::None && LD->isUnindexed()) {
5876 if (unsigned Align = DAG.InferPtrAlignment(Ptr)) {
5877 if (Align > LD->getAlignment())
5878 return DAG.getExtLoad(LD->getExtensionType(), N->getDebugLoc(),
5879 LD->getValueType(0),
5880 Chain, Ptr, LD->getPointerInfo(),
5882 LD->isVolatile(), LD->isNonTemporal(), Align);
5887 // Walk up chain skipping non-aliasing memory nodes.
5888 SDValue BetterChain = FindBetterChain(N, Chain);
5890 // If there is a better chain.
5891 if (Chain != BetterChain) {
5894 // Replace the chain to void dependency.
5895 if (LD->getExtensionType() == ISD::NON_EXTLOAD) {
5896 ReplLoad = DAG.getLoad(N->getValueType(0), LD->getDebugLoc(),
5897 BetterChain, Ptr, LD->getPointerInfo(),
5898 LD->isVolatile(), LD->isNonTemporal(),
5899 LD->getAlignment());
5901 ReplLoad = DAG.getExtLoad(LD->getExtensionType(), LD->getDebugLoc(),
5902 LD->getValueType(0),
5903 BetterChain, Ptr, LD->getPointerInfo(),
5906 LD->isNonTemporal(),
5907 LD->getAlignment());
5910 // Create token factor to keep old chain connected.
5911 SDValue Token = DAG.getNode(ISD::TokenFactor, N->getDebugLoc(),
5912 MVT::Other, Chain, ReplLoad.getValue(1));
5914 // Make sure the new and old chains are cleaned up.
5915 AddToWorkList(Token.getNode());
5917 // Replace uses with load result and token factor. Don't add users
5919 return CombineTo(N, ReplLoad.getValue(0), Token, false);
5923 // Try transforming N to an indexed load.
5924 if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
5925 return SDValue(N, 0);
5930 /// CheckForMaskedLoad - Check to see if V is (and load (ptr), imm), where the
5931 /// load is having specific bytes cleared out. If so, return the byte size
5932 /// being masked out and the shift amount.
5933 static std::pair<unsigned, unsigned>
5934 CheckForMaskedLoad(SDValue V, SDValue Ptr, SDValue Chain) {
5935 std::pair<unsigned, unsigned> Result(0, 0);
5937 // Check for the structure we're looking for.
5938 if (V->getOpcode() != ISD::AND ||
5939 !isa<ConstantSDNode>(V->getOperand(1)) ||
5940 !ISD::isNormalLoad(V->getOperand(0).getNode()))
5943 // Check the chain and pointer.
5944 LoadSDNode *LD = cast<LoadSDNode>(V->getOperand(0));
5945 if (LD->getBasePtr() != Ptr) return Result; // Not from same pointer.
5947 // The store should be chained directly to the load or be an operand of a
5949 if (LD == Chain.getNode())
5951 else if (Chain->getOpcode() != ISD::TokenFactor)
5952 return Result; // Fail.
5955 for (unsigned i = 0, e = Chain->getNumOperands(); i != e; ++i)
5956 if (Chain->getOperand(i).getNode() == LD) {
5960 if (!isOk) return Result;
5963 // This only handles simple types.
5964 if (V.getValueType() != MVT::i16 &&
5965 V.getValueType() != MVT::i32 &&
5966 V.getValueType() != MVT::i64)
5969 // Check the constant mask. Invert it so that the bits being masked out are
5970 // 0 and the bits being kept are 1. Use getSExtValue so that leading bits
5971 // follow the sign bit for uniformity.
5972 uint64_t NotMask = ~cast<ConstantSDNode>(V->getOperand(1))->getSExtValue();
5973 unsigned NotMaskLZ = CountLeadingZeros_64(NotMask);
5974 if (NotMaskLZ & 7) return Result; // Must be multiple of a byte.
5975 unsigned NotMaskTZ = CountTrailingZeros_64(NotMask);
5976 if (NotMaskTZ & 7) return Result; // Must be multiple of a byte.
5977 if (NotMaskLZ == 64) return Result; // All zero mask.
5979 // See if we have a continuous run of bits. If so, we have 0*1+0*
5980 if (CountTrailingOnes_64(NotMask >> NotMaskTZ)+NotMaskTZ+NotMaskLZ != 64)
5983 // Adjust NotMaskLZ down to be from the actual size of the int instead of i64.
5984 if (V.getValueType() != MVT::i64 && NotMaskLZ)
5985 NotMaskLZ -= 64-V.getValueSizeInBits();
5987 unsigned MaskedBytes = (V.getValueSizeInBits()-NotMaskLZ-NotMaskTZ)/8;
5988 switch (MaskedBytes) {
5992 default: return Result; // All one mask, or 5-byte mask.
5995 // Verify that the first bit starts at a multiple of mask so that the access
5996 // is aligned the same as the access width.
5997 if (NotMaskTZ && NotMaskTZ/8 % MaskedBytes) return Result;
5999 Result.first = MaskedBytes;
6000 Result.second = NotMaskTZ/8;
6005 /// ShrinkLoadReplaceStoreWithStore - Check to see if IVal is something that
6006 /// provides a value as specified by MaskInfo. If so, replace the specified
6007 /// store with a narrower store of truncated IVal.
6009 ShrinkLoadReplaceStoreWithStore(const std::pair<unsigned, unsigned> &MaskInfo,
6010 SDValue IVal, StoreSDNode *St,
6012 unsigned NumBytes = MaskInfo.first;
6013 unsigned ByteShift = MaskInfo.second;
6014 SelectionDAG &DAG = DC->getDAG();
6016 // Check to see if IVal is all zeros in the part being masked in by the 'or'
6017 // that uses this. If not, this is not a replacement.
6018 APInt Mask = ~APInt::getBitsSet(IVal.getValueSizeInBits(),
6019 ByteShift*8, (ByteShift+NumBytes)*8);
6020 if (!DAG.MaskedValueIsZero(IVal, Mask)) return 0;
6022 // Check that it is legal on the target to do this. It is legal if the new
6023 // VT we're shrinking to (i8/i16/i32) is legal or we're still before type
6025 MVT VT = MVT::getIntegerVT(NumBytes*8);
6026 if (!DC->isTypeLegal(VT))
6029 // Okay, we can do this! Replace the 'St' store with a store of IVal that is
6030 // shifted by ByteShift and truncated down to NumBytes.
6032 IVal = DAG.getNode(ISD::SRL, IVal->getDebugLoc(), IVal.getValueType(), IVal,
6033 DAG.getConstant(ByteShift*8,
6034 DC->getShiftAmountTy(IVal.getValueType())));
6036 // Figure out the offset for the store and the alignment of the access.
6038 unsigned NewAlign = St->getAlignment();
6040 if (DAG.getTargetLoweringInfo().isLittleEndian())
6041 StOffset = ByteShift;
6043 StOffset = IVal.getValueType().getStoreSize() - ByteShift - NumBytes;
6045 SDValue Ptr = St->getBasePtr();
6047 Ptr = DAG.getNode(ISD::ADD, IVal->getDebugLoc(), Ptr.getValueType(),
6048 Ptr, DAG.getConstant(StOffset, Ptr.getValueType()));
6049 NewAlign = MinAlign(NewAlign, StOffset);
6052 // Truncate down to the new size.
6053 IVal = DAG.getNode(ISD::TRUNCATE, IVal->getDebugLoc(), VT, IVal);
6056 return DAG.getStore(St->getChain(), St->getDebugLoc(), IVal, Ptr,
6057 St->getPointerInfo().getWithOffset(StOffset),
6058 false, false, NewAlign).getNode();
6062 /// ReduceLoadOpStoreWidth - Look for sequence of load / op / store where op is
6063 /// one of 'or', 'xor', and 'and' of immediates. If 'op' is only touching some
6064 /// of the loaded bits, try narrowing the load and store if it would end up
6065 /// being a win for performance or code size.
6066 SDValue DAGCombiner::ReduceLoadOpStoreWidth(SDNode *N) {
6067 StoreSDNode *ST = cast<StoreSDNode>(N);
6068 if (ST->isVolatile())
6071 SDValue Chain = ST->getChain();
6072 SDValue Value = ST->getValue();
6073 SDValue Ptr = ST->getBasePtr();
6074 EVT VT = Value.getValueType();
6076 if (ST->isTruncatingStore() || VT.isVector() || !Value.hasOneUse())
6079 unsigned Opc = Value.getOpcode();
6081 // If this is "store (or X, Y), P" and X is "(and (load P), cst)", where cst
6082 // is a byte mask indicating a consecutive number of bytes, check to see if
6083 // Y is known to provide just those bytes. If so, we try to replace the
6084 // load + replace + store sequence with a single (narrower) store, which makes
6086 if (Opc == ISD::OR) {
6087 std::pair<unsigned, unsigned> MaskedLoad;
6088 MaskedLoad = CheckForMaskedLoad(Value.getOperand(0), Ptr, Chain);
6089 if (MaskedLoad.first)
6090 if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad,
6091 Value.getOperand(1), ST,this))
6092 return SDValue(NewST, 0);
6094 // Or is commutative, so try swapping X and Y.
6095 MaskedLoad = CheckForMaskedLoad(Value.getOperand(1), Ptr, Chain);
6096 if (MaskedLoad.first)
6097 if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad,
6098 Value.getOperand(0), ST,this))
6099 return SDValue(NewST, 0);
6102 if ((Opc != ISD::OR && Opc != ISD::XOR && Opc != ISD::AND) ||
6103 Value.getOperand(1).getOpcode() != ISD::Constant)
6106 SDValue N0 = Value.getOperand(0);
6107 if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
6108 Chain == SDValue(N0.getNode(), 1)) {
6109 LoadSDNode *LD = cast<LoadSDNode>(N0);
6110 if (LD->getBasePtr() != Ptr ||
6111 LD->getPointerInfo().getAddrSpace() !=
6112 ST->getPointerInfo().getAddrSpace())
6115 // Find the type to narrow it the load / op / store to.
6116 SDValue N1 = Value.getOperand(1);
6117 unsigned BitWidth = N1.getValueSizeInBits();
6118 APInt Imm = cast<ConstantSDNode>(N1)->getAPIntValue();
6119 if (Opc == ISD::AND)
6120 Imm ^= APInt::getAllOnesValue(BitWidth);
6121 if (Imm == 0 || Imm.isAllOnesValue())
6123 unsigned ShAmt = Imm.countTrailingZeros();
6124 unsigned MSB = BitWidth - Imm.countLeadingZeros() - 1;
6125 unsigned NewBW = NextPowerOf2(MSB - ShAmt);
6126 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW);
6127 while (NewBW < BitWidth &&
6128 !(TLI.isOperationLegalOrCustom(Opc, NewVT) &&
6129 TLI.isNarrowingProfitable(VT, NewVT))) {
6130 NewBW = NextPowerOf2(NewBW);
6131 NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW);
6133 if (NewBW >= BitWidth)
6136 // If the lsb changed does not start at the type bitwidth boundary,
6137 // start at the previous one.
6139 ShAmt = (((ShAmt + NewBW - 1) / NewBW) * NewBW) - NewBW;
6140 APInt Mask = APInt::getBitsSet(BitWidth, ShAmt, ShAmt + NewBW);
6141 if ((Imm & Mask) == Imm) {
6142 APInt NewImm = (Imm & Mask).lshr(ShAmt).trunc(NewBW);
6143 if (Opc == ISD::AND)
6144 NewImm ^= APInt::getAllOnesValue(NewBW);
6145 uint64_t PtrOff = ShAmt / 8;
6146 // For big endian targets, we need to adjust the offset to the pointer to
6147 // load the correct bytes.
6148 if (TLI.isBigEndian())
6149 PtrOff = (BitWidth + 7 - NewBW) / 8 - PtrOff;
6151 unsigned NewAlign = MinAlign(LD->getAlignment(), PtrOff);
6152 const Type *NewVTTy = NewVT.getTypeForEVT(*DAG.getContext());
6153 if (NewAlign < TLI.getTargetData()->getABITypeAlignment(NewVTTy))
6156 SDValue NewPtr = DAG.getNode(ISD::ADD, LD->getDebugLoc(),
6157 Ptr.getValueType(), Ptr,
6158 DAG.getConstant(PtrOff, Ptr.getValueType()));
6159 SDValue NewLD = DAG.getLoad(NewVT, N0.getDebugLoc(),
6160 LD->getChain(), NewPtr,
6161 LD->getPointerInfo().getWithOffset(PtrOff),
6162 LD->isVolatile(), LD->isNonTemporal(),
6164 SDValue NewVal = DAG.getNode(Opc, Value.getDebugLoc(), NewVT, NewLD,
6165 DAG.getConstant(NewImm, NewVT));
6166 SDValue NewST = DAG.getStore(Chain, N->getDebugLoc(),
6168 ST->getPointerInfo().getWithOffset(PtrOff),
6169 false, false, NewAlign);
6171 AddToWorkList(NewPtr.getNode());
6172 AddToWorkList(NewLD.getNode());
6173 AddToWorkList(NewVal.getNode());
6174 WorkListRemover DeadNodes(*this);
6175 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLD.getValue(1),
6185 /// TransformFPLoadStorePair - For a given floating point load / store pair,
6186 /// if the load value isn't used by any other operations, then consider
6187 /// transforming the pair to integer load / store operations if the target
6188 /// deems the transformation profitable.
6189 SDValue DAGCombiner::TransformFPLoadStorePair(SDNode *N) {
6190 StoreSDNode *ST = cast<StoreSDNode>(N);
6191 SDValue Chain = ST->getChain();
6192 SDValue Value = ST->getValue();
6193 if (ISD::isNormalStore(ST) && ISD::isNormalLoad(Value.getNode()) &&
6194 Value.hasOneUse() &&
6195 Chain == SDValue(Value.getNode(), 1)) {
6196 LoadSDNode *LD = cast<LoadSDNode>(Value);
6197 EVT VT = LD->getMemoryVT();
6198 if (!VT.isFloatingPoint() ||
6199 VT != ST->getMemoryVT() ||
6200 LD->isNonTemporal() ||
6201 ST->isNonTemporal() ||
6202 LD->getPointerInfo().getAddrSpace() != 0 ||
6203 ST->getPointerInfo().getAddrSpace() != 0)
6206 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), VT.getSizeInBits());
6207 if (!TLI.isOperationLegal(ISD::LOAD, IntVT) ||
6208 !TLI.isOperationLegal(ISD::STORE, IntVT) ||
6209 !TLI.isDesirableToTransformToIntegerOp(ISD::LOAD, VT) ||
6210 !TLI.isDesirableToTransformToIntegerOp(ISD::STORE, VT))
6213 unsigned LDAlign = LD->getAlignment();
6214 unsigned STAlign = ST->getAlignment();
6215 const Type *IntVTTy = IntVT.getTypeForEVT(*DAG.getContext());
6216 unsigned ABIAlign = TLI.getTargetData()->getABITypeAlignment(IntVTTy);
6217 if (LDAlign < ABIAlign || STAlign < ABIAlign)
6220 SDValue NewLD = DAG.getLoad(IntVT, Value.getDebugLoc(),
6221 LD->getChain(), LD->getBasePtr(),
6222 LD->getPointerInfo(),
6223 false, false, LDAlign);
6225 SDValue NewST = DAG.getStore(NewLD.getValue(1), N->getDebugLoc(),
6226 NewLD, ST->getBasePtr(),
6227 ST->getPointerInfo(),
6228 false, false, STAlign);
6230 AddToWorkList(NewLD.getNode());
6231 AddToWorkList(NewST.getNode());
6232 WorkListRemover DeadNodes(*this);
6233 DAG.ReplaceAllUsesOfValueWith(Value.getValue(1), NewLD.getValue(1),
6242 SDValue DAGCombiner::visitSTORE(SDNode *N) {
6243 StoreSDNode *ST = cast<StoreSDNode>(N);
6244 SDValue Chain = ST->getChain();
6245 SDValue Value = ST->getValue();
6246 SDValue Ptr = ST->getBasePtr();
6248 // If this is a store of a bit convert, store the input value if the
6249 // resultant store does not need a higher alignment than the original.
6250 if (Value.getOpcode() == ISD::BITCAST && !ST->isTruncatingStore() &&
6251 ST->isUnindexed()) {
6252 unsigned OrigAlign = ST->getAlignment();
6253 EVT SVT = Value.getOperand(0).getValueType();
6254 unsigned Align = TLI.getTargetData()->
6255 getABITypeAlignment(SVT.getTypeForEVT(*DAG.getContext()));
6256 if (Align <= OrigAlign &&
6257 ((!LegalOperations && !ST->isVolatile()) ||
6258 TLI.isOperationLegalOrCustom(ISD::STORE, SVT)))
6259 return DAG.getStore(Chain, N->getDebugLoc(), Value.getOperand(0),
6260 Ptr, ST->getPointerInfo(), ST->isVolatile(),
6261 ST->isNonTemporal(), OrigAlign);
6264 // Turn 'store float 1.0, Ptr' -> 'store int 0x12345678, Ptr'
6265 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Value)) {
6266 // NOTE: If the original store is volatile, this transform must not increase
6267 // the number of stores. For example, on x86-32 an f64 can be stored in one
6268 // processor operation but an i64 (which is not legal) requires two. So the
6269 // transform should not be done in this case.
6270 if (Value.getOpcode() != ISD::TargetConstantFP) {
6272 switch (CFP->getValueType(0).getSimpleVT().SimpleTy) {
6273 default: llvm_unreachable("Unknown FP type");
6274 case MVT::f80: // We don't do this for these yet.
6279 if ((isTypeLegal(MVT::i32) && !LegalOperations && !ST->isVolatile()) ||
6280 TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) {
6281 Tmp = DAG.getConstant((uint32_t)CFP->getValueAPF().
6282 bitcastToAPInt().getZExtValue(), MVT::i32);
6283 return DAG.getStore(Chain, N->getDebugLoc(), Tmp,
6284 Ptr, ST->getPointerInfo(), ST->isVolatile(),
6285 ST->isNonTemporal(), ST->getAlignment());
6289 if ((TLI.isTypeLegal(MVT::i64) && !LegalOperations &&
6290 !ST->isVolatile()) ||
6291 TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i64)) {
6292 Tmp = DAG.getConstant(CFP->getValueAPF().bitcastToAPInt().
6293 getZExtValue(), MVT::i64);
6294 return DAG.getStore(Chain, N->getDebugLoc(), Tmp,
6295 Ptr, ST->getPointerInfo(), ST->isVolatile(),
6296 ST->isNonTemporal(), ST->getAlignment());
6297 } else if (!ST->isVolatile() &&
6298 TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) {
6299 // Many FP stores are not made apparent until after legalize, e.g. for
6300 // argument passing. Since this is so common, custom legalize the
6301 // 64-bit integer store into two 32-bit stores.
6302 uint64_t Val = CFP->getValueAPF().bitcastToAPInt().getZExtValue();
6303 SDValue Lo = DAG.getConstant(Val & 0xFFFFFFFF, MVT::i32);
6304 SDValue Hi = DAG.getConstant(Val >> 32, MVT::i32);
6305 if (TLI.isBigEndian()) std::swap(Lo, Hi);
6307 unsigned Alignment = ST->getAlignment();
6308 bool isVolatile = ST->isVolatile();
6309 bool isNonTemporal = ST->isNonTemporal();
6311 SDValue St0 = DAG.getStore(Chain, ST->getDebugLoc(), Lo,
6312 Ptr, ST->getPointerInfo(),
6313 isVolatile, isNonTemporal,
6314 ST->getAlignment());
6315 Ptr = DAG.getNode(ISD::ADD, N->getDebugLoc(), Ptr.getValueType(), Ptr,
6316 DAG.getConstant(4, Ptr.getValueType()));
6317 Alignment = MinAlign(Alignment, 4U);
6318 SDValue St1 = DAG.getStore(Chain, ST->getDebugLoc(), Hi,
6319 Ptr, ST->getPointerInfo().getWithOffset(4),
6320 isVolatile, isNonTemporal,
6322 return DAG.getNode(ISD::TokenFactor, N->getDebugLoc(), MVT::Other,
6331 // Try to infer better alignment information than the store already has.
6332 if (OptLevel != CodeGenOpt::None && ST->isUnindexed()) {
6333 if (unsigned Align = DAG.InferPtrAlignment(Ptr)) {
6334 if (Align > ST->getAlignment())
6335 return DAG.getTruncStore(Chain, N->getDebugLoc(), Value,
6336 Ptr, ST->getPointerInfo(), ST->getMemoryVT(),
6337 ST->isVolatile(), ST->isNonTemporal(), Align);
6341 // Try transforming a pair floating point load / store ops to integer
6342 // load / store ops.
6343 SDValue NewST = TransformFPLoadStorePair(N);
6344 if (NewST.getNode())
6348 // Walk up chain skipping non-aliasing memory nodes.
6349 SDValue BetterChain = FindBetterChain(N, Chain);
6351 // If there is a better chain.
6352 if (Chain != BetterChain) {
6355 // Replace the chain to avoid dependency.
6356 if (ST->isTruncatingStore()) {
6357 ReplStore = DAG.getTruncStore(BetterChain, N->getDebugLoc(), Value, Ptr,
6358 ST->getPointerInfo(),
6359 ST->getMemoryVT(), ST->isVolatile(),
6360 ST->isNonTemporal(), ST->getAlignment());
6362 ReplStore = DAG.getStore(BetterChain, N->getDebugLoc(), Value, Ptr,
6363 ST->getPointerInfo(),
6364 ST->isVolatile(), ST->isNonTemporal(),
6365 ST->getAlignment());
6368 // Create token to keep both nodes around.
6369 SDValue Token = DAG.getNode(ISD::TokenFactor, N->getDebugLoc(),
6370 MVT::Other, Chain, ReplStore);
6372 // Make sure the new and old chains are cleaned up.
6373 AddToWorkList(Token.getNode());
6375 // Don't add users to work list.
6376 return CombineTo(N, Token, false);
6380 // Try transforming N to an indexed store.
6381 if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
6382 return SDValue(N, 0);
6384 // FIXME: is there such a thing as a truncating indexed store?
6385 if (ST->isTruncatingStore() && ST->isUnindexed() &&
6386 Value.getValueType().isInteger()) {
6387 // See if we can simplify the input to this truncstore with knowledge that
6388 // only the low bits are being used. For example:
6389 // "truncstore (or (shl x, 8), y), i8" -> "truncstore y, i8"
6391 GetDemandedBits(Value,
6392 APInt::getLowBitsSet(Value.getValueSizeInBits(),
6393 ST->getMemoryVT().getSizeInBits()));
6394 AddToWorkList(Value.getNode());
6395 if (Shorter.getNode())
6396 return DAG.getTruncStore(Chain, N->getDebugLoc(), Shorter,
6397 Ptr, ST->getPointerInfo(), ST->getMemoryVT(),
6398 ST->isVolatile(), ST->isNonTemporal(),
6399 ST->getAlignment());
6401 // Otherwise, see if we can simplify the operation with
6402 // SimplifyDemandedBits, which only works if the value has a single use.
6403 if (SimplifyDemandedBits(Value,
6404 APInt::getLowBitsSet(
6405 Value.getValueType().getScalarType().getSizeInBits(),
6406 ST->getMemoryVT().getScalarType().getSizeInBits())))
6407 return SDValue(N, 0);
6410 // If this is a load followed by a store to the same location, then the store
6412 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Value)) {
6413 if (Ld->getBasePtr() == Ptr && ST->getMemoryVT() == Ld->getMemoryVT() &&
6414 ST->isUnindexed() && !ST->isVolatile() &&
6415 // There can't be any side effects between the load and store, such as
6417 Chain.reachesChainWithoutSideEffects(SDValue(Ld, 1))) {
6418 // The store is dead, remove it.
6423 // If this is an FP_ROUND or TRUNC followed by a store, fold this into a
6424 // truncating store. We can do this even if this is already a truncstore.
6425 if ((Value.getOpcode() == ISD::FP_ROUND || Value.getOpcode() == ISD::TRUNCATE)
6426 && Value.getNode()->hasOneUse() && ST->isUnindexed() &&
6427 TLI.isTruncStoreLegal(Value.getOperand(0).getValueType(),
6428 ST->getMemoryVT())) {
6429 return DAG.getTruncStore(Chain, N->getDebugLoc(), Value.getOperand(0),
6430 Ptr, ST->getPointerInfo(), ST->getMemoryVT(),
6431 ST->isVolatile(), ST->isNonTemporal(),
6432 ST->getAlignment());
6435 return ReduceLoadOpStoreWidth(N);
6438 SDValue DAGCombiner::visitINSERT_VECTOR_ELT(SDNode *N) {
6439 SDValue InVec = N->getOperand(0);
6440 SDValue InVal = N->getOperand(1);
6441 SDValue EltNo = N->getOperand(2);
6443 // If the inserted element is an UNDEF, just use the input vector.
6444 if (InVal.getOpcode() == ISD::UNDEF)
6447 EVT VT = InVec.getValueType();
6449 // If we can't generate a legal BUILD_VECTOR, exit
6450 if (LegalOperations && !TLI.isOperationLegal(ISD::BUILD_VECTOR, VT))
6453 // If the invec is a BUILD_VECTOR and if EltNo is a constant, build a new
6454 // vector with the inserted element.
6455 if (InVec.getOpcode() == ISD::BUILD_VECTOR && isa<ConstantSDNode>(EltNo)) {
6456 unsigned Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
6457 SmallVector<SDValue, 8> Ops(InVec.getNode()->op_begin(),
6458 InVec.getNode()->op_end());
6459 if (Elt < Ops.size())
6461 return DAG.getNode(ISD::BUILD_VECTOR, N->getDebugLoc(),
6462 VT, &Ops[0], Ops.size());
6464 // If the invec is an UNDEF and if EltNo is a constant, create a new
6465 // BUILD_VECTOR with undef elements and the inserted element.
6466 if (InVec.getOpcode() == ISD::UNDEF &&
6467 isa<ConstantSDNode>(EltNo)) {
6468 EVT EltVT = VT.getVectorElementType();
6469 unsigned NElts = VT.getVectorNumElements();
6470 SmallVector<SDValue, 8> Ops(NElts, DAG.getUNDEF(EltVT));
6472 unsigned Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
6473 if (Elt < Ops.size())
6475 return DAG.getNode(ISD::BUILD_VECTOR, N->getDebugLoc(),
6476 VT, &Ops[0], Ops.size());
6481 SDValue DAGCombiner::visitEXTRACT_VECTOR_ELT(SDNode *N) {
6482 // (vextract (scalar_to_vector val, 0) -> val
6483 SDValue InVec = N->getOperand(0);
6485 if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR) {
6486 // Check if the result type doesn't match the inserted element type. A
6487 // SCALAR_TO_VECTOR may truncate the inserted element and the
6488 // EXTRACT_VECTOR_ELT may widen the extracted vector.
6489 SDValue InOp = InVec.getOperand(0);
6490 EVT NVT = N->getValueType(0);
6491 if (InOp.getValueType() != NVT) {
6492 assert(InOp.getValueType().isInteger() && NVT.isInteger());
6493 return DAG.getSExtOrTrunc(InOp, InVec.getDebugLoc(), NVT);
6498 // Perform only after legalization to ensure build_vector / vector_shuffle
6499 // optimizations have already been done.
6500 if (!LegalOperations) return SDValue();
6502 // (vextract (v4f32 load $addr), c) -> (f32 load $addr+c*size)
6503 // (vextract (v4f32 s2v (f32 load $addr)), c) -> (f32 load $addr+c*size)
6504 // (vextract (v4f32 shuffle (load $addr), <1,u,u,u>), 0) -> (f32 load $addr)
6505 SDValue EltNo = N->getOperand(1);
6507 if (isa<ConstantSDNode>(EltNo)) {
6508 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
6509 bool NewLoad = false;
6510 bool BCNumEltsChanged = false;
6511 EVT VT = InVec.getValueType();
6512 EVT ExtVT = VT.getVectorElementType();
6515 if (InVec.getOpcode() == ISD::BITCAST) {
6516 EVT BCVT = InVec.getOperand(0).getValueType();
6517 if (!BCVT.isVector() || ExtVT.bitsGT(BCVT.getVectorElementType()))
6519 if (VT.getVectorNumElements() != BCVT.getVectorNumElements())
6520 BCNumEltsChanged = true;
6521 InVec = InVec.getOperand(0);
6522 ExtVT = BCVT.getVectorElementType();
6526 LoadSDNode *LN0 = NULL;
6527 const ShuffleVectorSDNode *SVN = NULL;
6528 if (ISD::isNormalLoad(InVec.getNode())) {
6529 LN0 = cast<LoadSDNode>(InVec);
6530 } else if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR &&
6531 InVec.getOperand(0).getValueType() == ExtVT &&
6532 ISD::isNormalLoad(InVec.getOperand(0).getNode())) {
6533 LN0 = cast<LoadSDNode>(InVec.getOperand(0));
6534 } else if ((SVN = dyn_cast<ShuffleVectorSDNode>(InVec))) {
6535 // (vextract (vector_shuffle (load $addr), v2, <1, u, u, u>), 1)
6537 // (load $addr+1*size)
6539 // If the bit convert changed the number of elements, it is unsafe
6540 // to examine the mask.
6541 if (BCNumEltsChanged)
6544 // Select the input vector, guarding against out of range extract vector.
6545 unsigned NumElems = VT.getVectorNumElements();
6546 int Idx = (Elt > (int)NumElems) ? -1 : SVN->getMaskElt(Elt);
6547 InVec = (Idx < (int)NumElems) ? InVec.getOperand(0) : InVec.getOperand(1);
6549 if (InVec.getOpcode() == ISD::BITCAST)
6550 InVec = InVec.getOperand(0);
6551 if (ISD::isNormalLoad(InVec.getNode())) {
6552 LN0 = cast<LoadSDNode>(InVec);
6553 Elt = (Idx < (int)NumElems) ? Idx : Idx - (int)NumElems;
6557 if (!LN0 || !LN0->hasOneUse() || LN0->isVolatile())
6560 // If Idx was -1 above, Elt is going to be -1, so just return undef.
6562 return DAG.getUNDEF(LN0->getBasePtr().getValueType());
6564 unsigned Align = LN0->getAlignment();
6566 // Check the resultant load doesn't need a higher alignment than the
6570 ->getABITypeAlignment(LVT.getTypeForEVT(*DAG.getContext()));
6572 if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, LVT))
6578 SDValue NewPtr = LN0->getBasePtr();
6579 unsigned PtrOff = 0;
6582 PtrOff = LVT.getSizeInBits() * Elt / 8;
6583 EVT PtrType = NewPtr.getValueType();
6584 if (TLI.isBigEndian())
6585 PtrOff = VT.getSizeInBits() / 8 - PtrOff;
6586 NewPtr = DAG.getNode(ISD::ADD, N->getDebugLoc(), PtrType, NewPtr,
6587 DAG.getConstant(PtrOff, PtrType));
6590 return DAG.getLoad(LVT, N->getDebugLoc(), LN0->getChain(), NewPtr,
6591 LN0->getPointerInfo().getWithOffset(PtrOff),
6592 LN0->isVolatile(), LN0->isNonTemporal(), Align);
6598 SDValue DAGCombiner::visitBUILD_VECTOR(SDNode *N) {
6599 unsigned NumInScalars = N->getNumOperands();
6600 EVT VT = N->getValueType(0);
6602 // Check to see if this is a BUILD_VECTOR of a bunch of EXTRACT_VECTOR_ELT
6603 // operations. If so, and if the EXTRACT_VECTOR_ELT vector inputs come from
6604 // at most two distinct vectors, turn this into a shuffle node.
6605 SDValue VecIn1, VecIn2;
6606 for (unsigned i = 0; i != NumInScalars; ++i) {
6607 // Ignore undef inputs.
6608 if (N->getOperand(i).getOpcode() == ISD::UNDEF) continue;
6610 // If this input is something other than a EXTRACT_VECTOR_ELT with a
6611 // constant index, bail out.
6612 if (N->getOperand(i).getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
6613 !isa<ConstantSDNode>(N->getOperand(i).getOperand(1))) {
6614 VecIn1 = VecIn2 = SDValue(0, 0);
6618 // If the input vector type disagrees with the result of the build_vector,
6619 // we can't make a shuffle.
6620 SDValue ExtractedFromVec = N->getOperand(i).getOperand(0);
6621 if (ExtractedFromVec.getValueType() != VT) {
6622 VecIn1 = VecIn2 = SDValue(0, 0);
6626 // Otherwise, remember this. We allow up to two distinct input vectors.
6627 if (ExtractedFromVec == VecIn1 || ExtractedFromVec == VecIn2)
6630 if (VecIn1.getNode() == 0) {
6631 VecIn1 = ExtractedFromVec;
6632 } else if (VecIn2.getNode() == 0) {
6633 VecIn2 = ExtractedFromVec;
6636 VecIn1 = VecIn2 = SDValue(0, 0);
6641 // If everything is good, we can make a shuffle operation.
6642 if (VecIn1.getNode()) {
6643 SmallVector<int, 8> Mask;
6644 for (unsigned i = 0; i != NumInScalars; ++i) {
6645 if (N->getOperand(i).getOpcode() == ISD::UNDEF) {
6650 // If extracting from the first vector, just use the index directly.
6651 SDValue Extract = N->getOperand(i);
6652 SDValue ExtVal = Extract.getOperand(1);
6653 if (Extract.getOperand(0) == VecIn1) {
6654 unsigned ExtIndex = cast<ConstantSDNode>(ExtVal)->getZExtValue();
6655 if (ExtIndex > VT.getVectorNumElements())
6658 Mask.push_back(ExtIndex);
6662 // Otherwise, use InIdx + VecSize
6663 unsigned Idx = cast<ConstantSDNode>(ExtVal)->getZExtValue();
6664 Mask.push_back(Idx+NumInScalars);
6667 // Add count and size info.
6668 if (!isTypeLegal(VT))
6671 // Return the new VECTOR_SHUFFLE node.
6674 Ops[1] = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(VT);
6675 return DAG.getVectorShuffle(VT, N->getDebugLoc(), Ops[0], Ops[1], &Mask[0]);
6681 SDValue DAGCombiner::visitCONCAT_VECTORS(SDNode *N) {
6682 // TODO: Check to see if this is a CONCAT_VECTORS of a bunch of
6683 // EXTRACT_SUBVECTOR operations. If so, and if the EXTRACT_SUBVECTOR vector
6684 // inputs come from at most two distinct vectors, turn this into a shuffle
6687 // If we only have one input vector, we don't need to do any concatenation.
6688 if (N->getNumOperands() == 1)
6689 return N->getOperand(0);
6694 SDValue DAGCombiner::visitVECTOR_SHUFFLE(SDNode *N) {
6695 EVT VT = N->getValueType(0);
6696 unsigned NumElts = VT.getVectorNumElements();
6698 SDValue N0 = N->getOperand(0);
6700 assert(N0.getValueType().getVectorNumElements() == NumElts &&
6701 "Vector shuffle must be normalized in DAG");
6703 // FIXME: implement canonicalizations from DAG.getVectorShuffle()
6705 // If it is a splat, check if the argument vector is another splat or a
6706 // build_vector with all scalar elements the same.
6707 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
6708 if (SVN->isSplat() && SVN->getSplatIndex() < (int)NumElts) {
6709 SDNode *V = N0.getNode();
6711 // If this is a bit convert that changes the element type of the vector but
6712 // not the number of vector elements, look through it. Be careful not to
6713 // look though conversions that change things like v4f32 to v2f64.
6714 if (V->getOpcode() == ISD::BITCAST) {
6715 SDValue ConvInput = V->getOperand(0);
6716 if (ConvInput.getValueType().isVector() &&
6717 ConvInput.getValueType().getVectorNumElements() == NumElts)
6718 V = ConvInput.getNode();
6721 if (V->getOpcode() == ISD::BUILD_VECTOR) {
6722 assert(V->getNumOperands() == NumElts &&
6723 "BUILD_VECTOR has wrong number of operands");
6725 bool AllSame = true;
6726 for (unsigned i = 0; i != NumElts; ++i) {
6727 if (V->getOperand(i).getOpcode() != ISD::UNDEF) {
6728 Base = V->getOperand(i);
6732 // Splat of <u, u, u, u>, return <u, u, u, u>
6733 if (!Base.getNode())
6735 for (unsigned i = 0; i != NumElts; ++i) {
6736 if (V->getOperand(i) != Base) {
6741 // Splat of <x, x, x, x>, return <x, x, x, x>
6749 SDValue DAGCombiner::visitMEMBARRIER(SDNode* N) {
6750 if (!TLI.getShouldFoldAtomicFences())
6753 SDValue atomic = N->getOperand(0);
6754 switch (atomic.getOpcode()) {
6755 case ISD::ATOMIC_CMP_SWAP:
6756 case ISD::ATOMIC_SWAP:
6757 case ISD::ATOMIC_LOAD_ADD:
6758 case ISD::ATOMIC_LOAD_SUB:
6759 case ISD::ATOMIC_LOAD_AND:
6760 case ISD::ATOMIC_LOAD_OR:
6761 case ISD::ATOMIC_LOAD_XOR:
6762 case ISD::ATOMIC_LOAD_NAND:
6763 case ISD::ATOMIC_LOAD_MIN:
6764 case ISD::ATOMIC_LOAD_MAX:
6765 case ISD::ATOMIC_LOAD_UMIN:
6766 case ISD::ATOMIC_LOAD_UMAX:
6772 SDValue fence = atomic.getOperand(0);
6773 if (fence.getOpcode() != ISD::MEMBARRIER)
6776 switch (atomic.getOpcode()) {
6777 case ISD::ATOMIC_CMP_SWAP:
6778 return SDValue(DAG.UpdateNodeOperands(atomic.getNode(),
6779 fence.getOperand(0),
6780 atomic.getOperand(1), atomic.getOperand(2),
6781 atomic.getOperand(3)), atomic.getResNo());
6782 case ISD::ATOMIC_SWAP:
6783 case ISD::ATOMIC_LOAD_ADD:
6784 case ISD::ATOMIC_LOAD_SUB:
6785 case ISD::ATOMIC_LOAD_AND:
6786 case ISD::ATOMIC_LOAD_OR:
6787 case ISD::ATOMIC_LOAD_XOR:
6788 case ISD::ATOMIC_LOAD_NAND:
6789 case ISD::ATOMIC_LOAD_MIN:
6790 case ISD::ATOMIC_LOAD_MAX:
6791 case ISD::ATOMIC_LOAD_UMIN:
6792 case ISD::ATOMIC_LOAD_UMAX:
6793 return SDValue(DAG.UpdateNodeOperands(atomic.getNode(),
6794 fence.getOperand(0),
6795 atomic.getOperand(1), atomic.getOperand(2)),
6802 /// XformToShuffleWithZero - Returns a vector_shuffle if it able to transform
6803 /// an AND to a vector_shuffle with the destination vector and a zero vector.
6804 /// e.g. AND V, <0xffffffff, 0, 0xffffffff, 0>. ==>
6805 /// vector_shuffle V, Zero, <0, 4, 2, 4>
6806 SDValue DAGCombiner::XformToShuffleWithZero(SDNode *N) {
6807 EVT VT = N->getValueType(0);
6808 DebugLoc dl = N->getDebugLoc();
6809 SDValue LHS = N->getOperand(0);
6810 SDValue RHS = N->getOperand(1);
6811 if (N->getOpcode() == ISD::AND) {
6812 if (RHS.getOpcode() == ISD::BITCAST)
6813 RHS = RHS.getOperand(0);
6814 if (RHS.getOpcode() == ISD::BUILD_VECTOR) {
6815 SmallVector<int, 8> Indices;
6816 unsigned NumElts = RHS.getNumOperands();
6817 for (unsigned i = 0; i != NumElts; ++i) {
6818 SDValue Elt = RHS.getOperand(i);
6819 if (!isa<ConstantSDNode>(Elt))
6821 else if (cast<ConstantSDNode>(Elt)->isAllOnesValue())
6822 Indices.push_back(i);
6823 else if (cast<ConstantSDNode>(Elt)->isNullValue())
6824 Indices.push_back(NumElts);
6829 // Let's see if the target supports this vector_shuffle.
6830 EVT RVT = RHS.getValueType();
6831 if (!TLI.isVectorClearMaskLegal(Indices, RVT))
6834 // Return the new VECTOR_SHUFFLE node.
6835 EVT EltVT = RVT.getVectorElementType();
6836 SmallVector<SDValue,8> ZeroOps(RVT.getVectorNumElements(),
6837 DAG.getConstant(0, EltVT));
6838 SDValue Zero = DAG.getNode(ISD::BUILD_VECTOR, N->getDebugLoc(),
6839 RVT, &ZeroOps[0], ZeroOps.size());
6840 LHS = DAG.getNode(ISD::BITCAST, dl, RVT, LHS);
6841 SDValue Shuf = DAG.getVectorShuffle(RVT, dl, LHS, Zero, &Indices[0]);
6842 return DAG.getNode(ISD::BITCAST, dl, VT, Shuf);
6849 /// SimplifyVBinOp - Visit a binary vector operation, like ADD.
6850 SDValue DAGCombiner::SimplifyVBinOp(SDNode *N) {
6851 // After legalize, the target may be depending on adds and other
6852 // binary ops to provide legal ways to construct constants or other
6853 // things. Simplifying them may result in a loss of legality.
6854 if (LegalOperations) return SDValue();
6856 assert(N->getValueType(0).isVector() &&
6857 "SimplifyVBinOp only works on vectors!");
6859 SDValue LHS = N->getOperand(0);
6860 SDValue RHS = N->getOperand(1);
6861 SDValue Shuffle = XformToShuffleWithZero(N);
6862 if (Shuffle.getNode()) return Shuffle;
6864 // If the LHS and RHS are BUILD_VECTOR nodes, see if we can constant fold
6866 if (LHS.getOpcode() == ISD::BUILD_VECTOR &&
6867 RHS.getOpcode() == ISD::BUILD_VECTOR) {
6868 SmallVector<SDValue, 8> Ops;
6869 for (unsigned i = 0, e = LHS.getNumOperands(); i != e; ++i) {
6870 SDValue LHSOp = LHS.getOperand(i);
6871 SDValue RHSOp = RHS.getOperand(i);
6872 // If these two elements can't be folded, bail out.
6873 if ((LHSOp.getOpcode() != ISD::UNDEF &&
6874 LHSOp.getOpcode() != ISD::Constant &&
6875 LHSOp.getOpcode() != ISD::ConstantFP) ||
6876 (RHSOp.getOpcode() != ISD::UNDEF &&
6877 RHSOp.getOpcode() != ISD::Constant &&
6878 RHSOp.getOpcode() != ISD::ConstantFP))
6881 // Can't fold divide by zero.
6882 if (N->getOpcode() == ISD::SDIV || N->getOpcode() == ISD::UDIV ||
6883 N->getOpcode() == ISD::FDIV) {
6884 if ((RHSOp.getOpcode() == ISD::Constant &&
6885 cast<ConstantSDNode>(RHSOp.getNode())->isNullValue()) ||
6886 (RHSOp.getOpcode() == ISD::ConstantFP &&
6887 cast<ConstantFPSDNode>(RHSOp.getNode())->getValueAPF().isZero()))
6891 EVT VT = LHSOp.getValueType();
6892 assert(RHSOp.getValueType() == VT &&
6893 "SimplifyVBinOp with different BUILD_VECTOR element types");
6894 SDValue FoldOp = DAG.getNode(N->getOpcode(), LHS.getDebugLoc(), VT,
6896 if (FoldOp.getOpcode() != ISD::UNDEF &&
6897 FoldOp.getOpcode() != ISD::Constant &&
6898 FoldOp.getOpcode() != ISD::ConstantFP)
6900 Ops.push_back(FoldOp);
6901 AddToWorkList(FoldOp.getNode());
6904 if (Ops.size() == LHS.getNumOperands())
6905 return DAG.getNode(ISD::BUILD_VECTOR, N->getDebugLoc(),
6906 LHS.getValueType(), &Ops[0], Ops.size());
6912 SDValue DAGCombiner::SimplifySelect(DebugLoc DL, SDValue N0,
6913 SDValue N1, SDValue N2){
6914 assert(N0.getOpcode() ==ISD::SETCC && "First argument must be a SetCC node!");
6916 SDValue SCC = SimplifySelectCC(DL, N0.getOperand(0), N0.getOperand(1), N1, N2,
6917 cast<CondCodeSDNode>(N0.getOperand(2))->get());
6919 // If we got a simplified select_cc node back from SimplifySelectCC, then
6920 // break it down into a new SETCC node, and a new SELECT node, and then return
6921 // the SELECT node, since we were called with a SELECT node.
6922 if (SCC.getNode()) {
6923 // Check to see if we got a select_cc back (to turn into setcc/select).
6924 // Otherwise, just return whatever node we got back, like fabs.
6925 if (SCC.getOpcode() == ISD::SELECT_CC) {
6926 SDValue SETCC = DAG.getNode(ISD::SETCC, N0.getDebugLoc(),
6928 SCC.getOperand(0), SCC.getOperand(1),
6930 AddToWorkList(SETCC.getNode());
6931 return DAG.getNode(ISD::SELECT, SCC.getDebugLoc(), SCC.getValueType(),
6932 SCC.getOperand(2), SCC.getOperand(3), SETCC);
6940 /// SimplifySelectOps - Given a SELECT or a SELECT_CC node, where LHS and RHS
6941 /// are the two values being selected between, see if we can simplify the
6942 /// select. Callers of this should assume that TheSelect is deleted if this
6943 /// returns true. As such, they should return the appropriate thing (e.g. the
6944 /// node) back to the top-level of the DAG combiner loop to avoid it being
6946 bool DAGCombiner::SimplifySelectOps(SDNode *TheSelect, SDValue LHS,
6949 // Cannot simplify select with vector condition
6950 if (TheSelect->getOperand(0).getValueType().isVector()) return false;
6952 // If this is a select from two identical things, try to pull the operation
6953 // through the select.
6954 if (LHS.getOpcode() != RHS.getOpcode() ||
6955 !LHS.hasOneUse() || !RHS.hasOneUse())
6958 // If this is a load and the token chain is identical, replace the select
6959 // of two loads with a load through a select of the address to load from.
6960 // This triggers in things like "select bool X, 10.0, 123.0" after the FP
6961 // constants have been dropped into the constant pool.
6962 if (LHS.getOpcode() == ISD::LOAD) {
6963 LoadSDNode *LLD = cast<LoadSDNode>(LHS);
6964 LoadSDNode *RLD = cast<LoadSDNode>(RHS);
6966 // Token chains must be identical.
6967 if (LHS.getOperand(0) != RHS.getOperand(0) ||
6968 // Do not let this transformation reduce the number of volatile loads.
6969 LLD->isVolatile() || RLD->isVolatile() ||
6970 // If this is an EXTLOAD, the VT's must match.
6971 LLD->getMemoryVT() != RLD->getMemoryVT() ||
6972 // If this is an EXTLOAD, the kind of extension must match.
6973 (LLD->getExtensionType() != RLD->getExtensionType() &&
6974 // The only exception is if one of the extensions is anyext.
6975 LLD->getExtensionType() != ISD::EXTLOAD &&
6976 RLD->getExtensionType() != ISD::EXTLOAD) ||
6977 // FIXME: this discards src value information. This is
6978 // over-conservative. It would be beneficial to be able to remember
6979 // both potential memory locations. Since we are discarding
6980 // src value info, don't do the transformation if the memory
6981 // locations are not in the default address space.
6982 LLD->getPointerInfo().getAddrSpace() != 0 ||
6983 RLD->getPointerInfo().getAddrSpace() != 0)
6986 // Check that the select condition doesn't reach either load. If so,
6987 // folding this will induce a cycle into the DAG. If not, this is safe to
6988 // xform, so create a select of the addresses.
6990 if (TheSelect->getOpcode() == ISD::SELECT) {
6991 SDNode *CondNode = TheSelect->getOperand(0).getNode();
6992 if ((LLD->hasAnyUseOfValue(1) && LLD->isPredecessorOf(CondNode)) ||
6993 (RLD->hasAnyUseOfValue(1) && RLD->isPredecessorOf(CondNode)))
6995 Addr = DAG.getNode(ISD::SELECT, TheSelect->getDebugLoc(),
6996 LLD->getBasePtr().getValueType(),
6997 TheSelect->getOperand(0), LLD->getBasePtr(),
6999 } else { // Otherwise SELECT_CC
7000 SDNode *CondLHS = TheSelect->getOperand(0).getNode();
7001 SDNode *CondRHS = TheSelect->getOperand(1).getNode();
7003 if ((LLD->hasAnyUseOfValue(1) &&
7004 (LLD->isPredecessorOf(CondLHS) || LLD->isPredecessorOf(CondRHS))) ||
7005 (LLD->hasAnyUseOfValue(1) &&
7006 (LLD->isPredecessorOf(CondLHS) || LLD->isPredecessorOf(CondRHS))))
7009 Addr = DAG.getNode(ISD::SELECT_CC, TheSelect->getDebugLoc(),
7010 LLD->getBasePtr().getValueType(),
7011 TheSelect->getOperand(0),
7012 TheSelect->getOperand(1),
7013 LLD->getBasePtr(), RLD->getBasePtr(),
7014 TheSelect->getOperand(4));
7018 if (LLD->getExtensionType() == ISD::NON_EXTLOAD) {
7019 Load = DAG.getLoad(TheSelect->getValueType(0),
7020 TheSelect->getDebugLoc(),
7021 // FIXME: Discards pointer info.
7022 LLD->getChain(), Addr, MachinePointerInfo(),
7023 LLD->isVolatile(), LLD->isNonTemporal(),
7024 LLD->getAlignment());
7026 Load = DAG.getExtLoad(LLD->getExtensionType() == ISD::EXTLOAD ?
7027 RLD->getExtensionType() : LLD->getExtensionType(),
7028 TheSelect->getDebugLoc(),
7029 TheSelect->getValueType(0),
7030 // FIXME: Discards pointer info.
7031 LLD->getChain(), Addr, MachinePointerInfo(),
7032 LLD->getMemoryVT(), LLD->isVolatile(),
7033 LLD->isNonTemporal(), LLD->getAlignment());
7036 // Users of the select now use the result of the load.
7037 CombineTo(TheSelect, Load);
7039 // Users of the old loads now use the new load's chain. We know the
7040 // old-load value is dead now.
7041 CombineTo(LHS.getNode(), Load.getValue(0), Load.getValue(1));
7042 CombineTo(RHS.getNode(), Load.getValue(0), Load.getValue(1));
7049 /// SimplifySelectCC - Simplify an expression of the form (N0 cond N1) ? N2 : N3
7050 /// where 'cond' is the comparison specified by CC.
7051 SDValue DAGCombiner::SimplifySelectCC(DebugLoc DL, SDValue N0, SDValue N1,
7052 SDValue N2, SDValue N3,
7053 ISD::CondCode CC, bool NotExtCompare) {
7054 // (x ? y : y) -> y.
7055 if (N2 == N3) return N2;
7057 EVT VT = N2.getValueType();
7058 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
7059 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2.getNode());
7060 ConstantSDNode *N3C = dyn_cast<ConstantSDNode>(N3.getNode());
7062 // Determine if the condition we're dealing with is constant
7063 SDValue SCC = SimplifySetCC(TLI.getSetCCResultType(N0.getValueType()),
7064 N0, N1, CC, DL, false);
7065 if (SCC.getNode()) AddToWorkList(SCC.getNode());
7066 ConstantSDNode *SCCC = dyn_cast_or_null<ConstantSDNode>(SCC.getNode());
7068 // fold select_cc true, x, y -> x
7069 if (SCCC && !SCCC->isNullValue())
7071 // fold select_cc false, x, y -> y
7072 if (SCCC && SCCC->isNullValue())
7075 // Check to see if we can simplify the select into an fabs node
7076 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N1)) {
7077 // Allow either -0.0 or 0.0
7078 if (CFP->getValueAPF().isZero()) {
7079 // select (setg[te] X, +/-0.0), X, fneg(X) -> fabs
7080 if ((CC == ISD::SETGE || CC == ISD::SETGT) &&
7081 N0 == N2 && N3.getOpcode() == ISD::FNEG &&
7082 N2 == N3.getOperand(0))
7083 return DAG.getNode(ISD::FABS, DL, VT, N0);
7085 // select (setl[te] X, +/-0.0), fneg(X), X -> fabs
7086 if ((CC == ISD::SETLT || CC == ISD::SETLE) &&
7087 N0 == N3 && N2.getOpcode() == ISD::FNEG &&
7088 N2.getOperand(0) == N3)
7089 return DAG.getNode(ISD::FABS, DL, VT, N3);
7093 // Turn "(a cond b) ? 1.0f : 2.0f" into "load (tmp + ((a cond b) ? 0 : 4)"
7094 // where "tmp" is a constant pool entry containing an array with 1.0 and 2.0
7095 // in it. This is a win when the constant is not otherwise available because
7096 // it replaces two constant pool loads with one. We only do this if the FP
7097 // type is known to be legal, because if it isn't, then we are before legalize
7098 // types an we want the other legalization to happen first (e.g. to avoid
7099 // messing with soft float) and if the ConstantFP is not legal, because if
7100 // it is legal, we may not need to store the FP constant in a constant pool.
7101 if (ConstantFPSDNode *TV = dyn_cast<ConstantFPSDNode>(N2))
7102 if (ConstantFPSDNode *FV = dyn_cast<ConstantFPSDNode>(N3)) {
7103 if (TLI.isTypeLegal(N2.getValueType()) &&
7104 (TLI.getOperationAction(ISD::ConstantFP, N2.getValueType()) !=
7105 TargetLowering::Legal) &&
7106 // If both constants have multiple uses, then we won't need to do an
7107 // extra load, they are likely around in registers for other users.
7108 (TV->hasOneUse() || FV->hasOneUse())) {
7109 Constant *Elts[] = {
7110 const_cast<ConstantFP*>(FV->getConstantFPValue()),
7111 const_cast<ConstantFP*>(TV->getConstantFPValue())
7113 const Type *FPTy = Elts[0]->getType();
7114 const TargetData &TD = *TLI.getTargetData();
7116 // Create a ConstantArray of the two constants.
7117 Constant *CA = ConstantArray::get(ArrayType::get(FPTy, 2), Elts, 2);
7118 SDValue CPIdx = DAG.getConstantPool(CA, TLI.getPointerTy(),
7119 TD.getPrefTypeAlignment(FPTy));
7120 unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
7122 // Get the offsets to the 0 and 1 element of the array so that we can
7123 // select between them.
7124 SDValue Zero = DAG.getIntPtrConstant(0);
7125 unsigned EltSize = (unsigned)TD.getTypeAllocSize(Elts[0]->getType());
7126 SDValue One = DAG.getIntPtrConstant(EltSize);
7128 SDValue Cond = DAG.getSetCC(DL,
7129 TLI.getSetCCResultType(N0.getValueType()),
7131 SDValue CstOffset = DAG.getNode(ISD::SELECT, DL, Zero.getValueType(),
7133 CPIdx = DAG.getNode(ISD::ADD, DL, TLI.getPointerTy(), CPIdx,
7135 return DAG.getLoad(TV->getValueType(0), DL, DAG.getEntryNode(), CPIdx,
7136 MachinePointerInfo::getConstantPool(), false,
7142 // Check to see if we can perform the "gzip trick", transforming
7143 // (select_cc setlt X, 0, A, 0) -> (and (sra X, (sub size(X), 1), A)
7144 if (N1C && N3C && N3C->isNullValue() && CC == ISD::SETLT &&
7145 N0.getValueType().isInteger() &&
7146 N2.getValueType().isInteger() &&
7147 (N1C->isNullValue() || // (a < 0) ? b : 0
7148 (N1C->getAPIntValue() == 1 && N0 == N2))) { // (a < 1) ? a : 0
7149 EVT XType = N0.getValueType();
7150 EVT AType = N2.getValueType();
7151 if (XType.bitsGE(AType)) {
7152 // and (sra X, size(X)-1, A) -> "and (srl X, C2), A" iff A is a
7153 // single-bit constant.
7154 if (N2C && ((N2C->getAPIntValue() & (N2C->getAPIntValue()-1)) == 0)) {
7155 unsigned ShCtV = N2C->getAPIntValue().logBase2();
7156 ShCtV = XType.getSizeInBits()-ShCtV-1;
7157 SDValue ShCt = DAG.getConstant(ShCtV,
7158 getShiftAmountTy(N0.getValueType()));
7159 SDValue Shift = DAG.getNode(ISD::SRL, N0.getDebugLoc(),
7161 AddToWorkList(Shift.getNode());
7163 if (XType.bitsGT(AType)) {
7164 Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift);
7165 AddToWorkList(Shift.getNode());
7168 return DAG.getNode(ISD::AND, DL, AType, Shift, N2);
7171 SDValue Shift = DAG.getNode(ISD::SRA, N0.getDebugLoc(),
7173 DAG.getConstant(XType.getSizeInBits()-1,
7174 getShiftAmountTy(N0.getValueType())));
7175 AddToWorkList(Shift.getNode());
7177 if (XType.bitsGT(AType)) {
7178 Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift);
7179 AddToWorkList(Shift.getNode());
7182 return DAG.getNode(ISD::AND, DL, AType, Shift, N2);
7186 // fold (select_cc seteq (and x, y), 0, 0, A) -> (and (shr (shl x)) A)
7187 // where y is has a single bit set.
7188 // A plaintext description would be, we can turn the SELECT_CC into an AND
7189 // when the condition can be materialized as an all-ones register. Any
7190 // single bit-test can be materialized as an all-ones register with
7191 // shift-left and shift-right-arith.
7192 if (CC == ISD::SETEQ && N0->getOpcode() == ISD::AND &&
7193 N0->getValueType(0) == VT &&
7194 N1C && N1C->isNullValue() &&
7195 N2C && N2C->isNullValue()) {
7196 SDValue AndLHS = N0->getOperand(0);
7197 ConstantSDNode *ConstAndRHS = dyn_cast<ConstantSDNode>(N0->getOperand(1));
7198 if (ConstAndRHS && ConstAndRHS->getAPIntValue().countPopulation() == 1) {
7199 // Shift the tested bit over the sign bit.
7200 APInt AndMask = ConstAndRHS->getAPIntValue();
7202 DAG.getConstant(AndMask.countLeadingZeros(),
7203 getShiftAmountTy(AndLHS.getValueType()));
7204 SDValue Shl = DAG.getNode(ISD::SHL, N0.getDebugLoc(), VT, AndLHS, ShlAmt);
7206 // Now arithmetic right shift it all the way over, so the result is either
7207 // all-ones, or zero.
7209 DAG.getConstant(AndMask.getBitWidth()-1,
7210 getShiftAmountTy(Shl.getValueType()));
7211 SDValue Shr = DAG.getNode(ISD::SRA, N0.getDebugLoc(), VT, Shl, ShrAmt);
7213 return DAG.getNode(ISD::AND, DL, VT, Shr, N3);
7217 // fold select C, 16, 0 -> shl C, 4
7218 if (N2C && N3C && N3C->isNullValue() && N2C->getAPIntValue().isPowerOf2() &&
7219 TLI.getBooleanContents() == TargetLowering::ZeroOrOneBooleanContent) {
7221 // If the caller doesn't want us to simplify this into a zext of a compare,
7223 if (NotExtCompare && N2C->getAPIntValue() == 1)
7226 // Get a SetCC of the condition
7227 // FIXME: Should probably make sure that setcc is legal if we ever have a
7228 // target where it isn't.
7230 // cast from setcc result type to select result type
7232 SCC = DAG.getSetCC(DL, TLI.getSetCCResultType(N0.getValueType()),
7234 if (N2.getValueType().bitsLT(SCC.getValueType()))
7235 Temp = DAG.getZeroExtendInReg(SCC, N2.getDebugLoc(), N2.getValueType());
7237 Temp = DAG.getNode(ISD::ZERO_EXTEND, N2.getDebugLoc(),
7238 N2.getValueType(), SCC);
7240 SCC = DAG.getSetCC(N0.getDebugLoc(), MVT::i1, N0, N1, CC);
7241 Temp = DAG.getNode(ISD::ZERO_EXTEND, N2.getDebugLoc(),
7242 N2.getValueType(), SCC);
7245 AddToWorkList(SCC.getNode());
7246 AddToWorkList(Temp.getNode());
7248 if (N2C->getAPIntValue() == 1)
7251 // shl setcc result by log2 n2c
7252 return DAG.getNode(ISD::SHL, DL, N2.getValueType(), Temp,
7253 DAG.getConstant(N2C->getAPIntValue().logBase2(),
7254 getShiftAmountTy(Temp.getValueType())));
7257 // Check to see if this is the equivalent of setcc
7258 // FIXME: Turn all of these into setcc if setcc if setcc is legal
7259 // otherwise, go ahead with the folds.
7260 if (0 && N3C && N3C->isNullValue() && N2C && (N2C->getAPIntValue() == 1ULL)) {
7261 EVT XType = N0.getValueType();
7262 if (!LegalOperations ||
7263 TLI.isOperationLegal(ISD::SETCC, TLI.getSetCCResultType(XType))) {
7264 SDValue Res = DAG.getSetCC(DL, TLI.getSetCCResultType(XType), N0, N1, CC);
7265 if (Res.getValueType() != VT)
7266 Res = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, Res);
7270 // fold (seteq X, 0) -> (srl (ctlz X, log2(size(X))))
7271 if (N1C && N1C->isNullValue() && CC == ISD::SETEQ &&
7272 (!LegalOperations ||
7273 TLI.isOperationLegal(ISD::CTLZ, XType))) {
7274 SDValue Ctlz = DAG.getNode(ISD::CTLZ, N0.getDebugLoc(), XType, N0);
7275 return DAG.getNode(ISD::SRL, DL, XType, Ctlz,
7276 DAG.getConstant(Log2_32(XType.getSizeInBits()),
7277 getShiftAmountTy(Ctlz.getValueType())));
7279 // fold (setgt X, 0) -> (srl (and (-X, ~X), size(X)-1))
7280 if (N1C && N1C->isNullValue() && CC == ISD::SETGT) {
7281 SDValue NegN0 = DAG.getNode(ISD::SUB, N0.getDebugLoc(),
7282 XType, DAG.getConstant(0, XType), N0);
7283 SDValue NotN0 = DAG.getNOT(N0.getDebugLoc(), N0, XType);
7284 return DAG.getNode(ISD::SRL, DL, XType,
7285 DAG.getNode(ISD::AND, DL, XType, NegN0, NotN0),
7286 DAG.getConstant(XType.getSizeInBits()-1,
7287 getShiftAmountTy(XType)));
7289 // fold (setgt X, -1) -> (xor (srl (X, size(X)-1), 1))
7290 if (N1C && N1C->isAllOnesValue() && CC == ISD::SETGT) {
7291 SDValue Sign = DAG.getNode(ISD::SRL, N0.getDebugLoc(), XType, N0,
7292 DAG.getConstant(XType.getSizeInBits()-1,
7293 getShiftAmountTy(N0.getValueType())));
7294 return DAG.getNode(ISD::XOR, DL, XType, Sign, DAG.getConstant(1, XType));
7298 // Check to see if this is an integer abs.
7299 // select_cc setg[te] X, 0, X, -X ->
7300 // select_cc setgt X, -1, X, -X ->
7301 // select_cc setl[te] X, 0, -X, X ->
7302 // select_cc setlt X, 1, -X, X ->
7303 // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
7305 ConstantSDNode *SubC = NULL;
7306 if (((N1C->isNullValue() && (CC == ISD::SETGT || CC == ISD::SETGE)) ||
7307 (N1C->isAllOnesValue() && CC == ISD::SETGT)) &&
7308 N0 == N2 && N3.getOpcode() == ISD::SUB && N0 == N3.getOperand(1))
7309 SubC = dyn_cast<ConstantSDNode>(N3.getOperand(0));
7310 else if (((N1C->isNullValue() && (CC == ISD::SETLT || CC == ISD::SETLE)) ||
7311 (N1C->isOne() && CC == ISD::SETLT)) &&
7312 N0 == N3 && N2.getOpcode() == ISD::SUB && N0 == N2.getOperand(1))
7313 SubC = dyn_cast<ConstantSDNode>(N2.getOperand(0));
7315 EVT XType = N0.getValueType();
7316 if (SubC && SubC->isNullValue() && XType.isInteger()) {
7317 SDValue Shift = DAG.getNode(ISD::SRA, N0.getDebugLoc(), XType,
7319 DAG.getConstant(XType.getSizeInBits()-1,
7320 getShiftAmountTy(N0.getValueType())));
7321 SDValue Add = DAG.getNode(ISD::ADD, N0.getDebugLoc(),
7323 AddToWorkList(Shift.getNode());
7324 AddToWorkList(Add.getNode());
7325 return DAG.getNode(ISD::XOR, DL, XType, Add, Shift);
7332 /// SimplifySetCC - This is a stub for TargetLowering::SimplifySetCC.
7333 SDValue DAGCombiner::SimplifySetCC(EVT VT, SDValue N0,
7334 SDValue N1, ISD::CondCode Cond,
7335 DebugLoc DL, bool foldBooleans) {
7336 TargetLowering::DAGCombinerInfo
7337 DagCombineInfo(DAG, !LegalTypes, !LegalOperations, false, this);
7338 return TLI.SimplifySetCC(VT, N0, N1, Cond, foldBooleans, DagCombineInfo, DL);
7341 /// BuildSDIVSequence - Given an ISD::SDIV node expressing a divide by constant,
7342 /// return a DAG expression to select that will generate the same value by
7343 /// multiplying by a magic number. See:
7344 /// <http://the.wall.riscom.net/books/proc/ppc/cwg/code2.html>
7345 SDValue DAGCombiner::BuildSDIV(SDNode *N) {
7346 std::vector<SDNode*> Built;
7347 SDValue S = TLI.BuildSDIV(N, DAG, &Built);
7349 for (std::vector<SDNode*>::iterator ii = Built.begin(), ee = Built.end();
7355 /// BuildUDIVSequence - Given an ISD::UDIV node expressing a divide by constant,
7356 /// return a DAG expression to select that will generate the same value by
7357 /// multiplying by a magic number. See:
7358 /// <http://the.wall.riscom.net/books/proc/ppc/cwg/code2.html>
7359 SDValue DAGCombiner::BuildUDIV(SDNode *N) {
7360 std::vector<SDNode*> Built;
7361 SDValue S = TLI.BuildUDIV(N, DAG, &Built);
7363 for (std::vector<SDNode*>::iterator ii = Built.begin(), ee = Built.end();
7369 /// FindBaseOffset - Return true if base is a frame index, which is known not
7370 // to alias with anything but itself. Provides base object and offset as
7372 static bool FindBaseOffset(SDValue Ptr, SDValue &Base, int64_t &Offset,
7373 const GlobalValue *&GV, void *&CV) {
7374 // Assume it is a primitive operation.
7375 Base = Ptr; Offset = 0; GV = 0; CV = 0;
7377 // If it's an adding a simple constant then integrate the offset.
7378 if (Base.getOpcode() == ISD::ADD) {
7379 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Base.getOperand(1))) {
7380 Base = Base.getOperand(0);
7381 Offset += C->getZExtValue();
7385 // Return the underlying GlobalValue, and update the Offset. Return false
7386 // for GlobalAddressSDNode since the same GlobalAddress may be represented
7387 // by multiple nodes with different offsets.
7388 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Base)) {
7389 GV = G->getGlobal();
7390 Offset += G->getOffset();
7394 // Return the underlying Constant value, and update the Offset. Return false
7395 // for ConstantSDNodes since the same constant pool entry may be represented
7396 // by multiple nodes with different offsets.
7397 if (ConstantPoolSDNode *C = dyn_cast<ConstantPoolSDNode>(Base)) {
7398 CV = C->isMachineConstantPoolEntry() ? (void *)C->getMachineCPVal()
7399 : (void *)C->getConstVal();
7400 Offset += C->getOffset();
7403 // If it's any of the following then it can't alias with anything but itself.
7404 return isa<FrameIndexSDNode>(Base);
7407 /// isAlias - Return true if there is any possibility that the two addresses
7409 bool DAGCombiner::isAlias(SDValue Ptr1, int64_t Size1,
7410 const Value *SrcValue1, int SrcValueOffset1,
7411 unsigned SrcValueAlign1,
7412 const MDNode *TBAAInfo1,
7413 SDValue Ptr2, int64_t Size2,
7414 const Value *SrcValue2, int SrcValueOffset2,
7415 unsigned SrcValueAlign2,
7416 const MDNode *TBAAInfo2) const {
7417 // If they are the same then they must be aliases.
7418 if (Ptr1 == Ptr2) return true;
7420 // Gather base node and offset information.
7421 SDValue Base1, Base2;
7422 int64_t Offset1, Offset2;
7423 const GlobalValue *GV1, *GV2;
7425 bool isFrameIndex1 = FindBaseOffset(Ptr1, Base1, Offset1, GV1, CV1);
7426 bool isFrameIndex2 = FindBaseOffset(Ptr2, Base2, Offset2, GV2, CV2);
7428 // If they have a same base address then check to see if they overlap.
7429 if (Base1 == Base2 || (GV1 && (GV1 == GV2)) || (CV1 && (CV1 == CV2)))
7430 return !((Offset1 + Size1) <= Offset2 || (Offset2 + Size2) <= Offset1);
7432 // It is possible for different frame indices to alias each other, mostly
7433 // when tail call optimization reuses return address slots for arguments.
7434 // To catch this case, look up the actual index of frame indices to compute
7435 // the real alias relationship.
7436 if (isFrameIndex1 && isFrameIndex2) {
7437 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
7438 Offset1 += MFI->getObjectOffset(cast<FrameIndexSDNode>(Base1)->getIndex());
7439 Offset2 += MFI->getObjectOffset(cast<FrameIndexSDNode>(Base2)->getIndex());
7440 return !((Offset1 + Size1) <= Offset2 || (Offset2 + Size2) <= Offset1);
7443 // Otherwise, if we know what the bases are, and they aren't identical, then
7444 // we know they cannot alias.
7445 if ((isFrameIndex1 || CV1 || GV1) && (isFrameIndex2 || CV2 || GV2))
7448 // If we know required SrcValue1 and SrcValue2 have relatively large alignment
7449 // compared to the size and offset of the access, we may be able to prove they
7450 // do not alias. This check is conservative for now to catch cases created by
7451 // splitting vector types.
7452 if ((SrcValueAlign1 == SrcValueAlign2) &&
7453 (SrcValueOffset1 != SrcValueOffset2) &&
7454 (Size1 == Size2) && (SrcValueAlign1 > Size1)) {
7455 int64_t OffAlign1 = SrcValueOffset1 % SrcValueAlign1;
7456 int64_t OffAlign2 = SrcValueOffset2 % SrcValueAlign1;
7458 // There is no overlap between these relatively aligned accesses of similar
7459 // size, return no alias.
7460 if ((OffAlign1 + Size1) <= OffAlign2 || (OffAlign2 + Size2) <= OffAlign1)
7464 if (CombinerGlobalAA) {
7465 // Use alias analysis information.
7466 int64_t MinOffset = std::min(SrcValueOffset1, SrcValueOffset2);
7467 int64_t Overlap1 = Size1 + SrcValueOffset1 - MinOffset;
7468 int64_t Overlap2 = Size2 + SrcValueOffset2 - MinOffset;
7469 AliasAnalysis::AliasResult AAResult =
7470 AA.alias(AliasAnalysis::Location(SrcValue1, Overlap1, TBAAInfo1),
7471 AliasAnalysis::Location(SrcValue2, Overlap2, TBAAInfo2));
7472 if (AAResult == AliasAnalysis::NoAlias)
7476 // Otherwise we have to assume they alias.
7480 /// FindAliasInfo - Extracts the relevant alias information from the memory
7481 /// node. Returns true if the operand was a load.
7482 bool DAGCombiner::FindAliasInfo(SDNode *N,
7483 SDValue &Ptr, int64_t &Size,
7484 const Value *&SrcValue,
7485 int &SrcValueOffset,
7486 unsigned &SrcValueAlign,
7487 const MDNode *&TBAAInfo) const {
7488 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
7489 Ptr = LD->getBasePtr();
7490 Size = LD->getMemoryVT().getSizeInBits() >> 3;
7491 SrcValue = LD->getSrcValue();
7492 SrcValueOffset = LD->getSrcValueOffset();
7493 SrcValueAlign = LD->getOriginalAlignment();
7494 TBAAInfo = LD->getTBAAInfo();
7496 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
7497 Ptr = ST->getBasePtr();
7498 Size = ST->getMemoryVT().getSizeInBits() >> 3;
7499 SrcValue = ST->getSrcValue();
7500 SrcValueOffset = ST->getSrcValueOffset();
7501 SrcValueAlign = ST->getOriginalAlignment();
7502 TBAAInfo = ST->getTBAAInfo();
7504 llvm_unreachable("FindAliasInfo expected a memory operand");
7510 /// GatherAllAliases - Walk up chain skipping non-aliasing memory nodes,
7511 /// looking for aliasing nodes and adding them to the Aliases vector.
7512 void DAGCombiner::GatherAllAliases(SDNode *N, SDValue OriginalChain,
7513 SmallVector<SDValue, 8> &Aliases) {
7514 SmallVector<SDValue, 8> Chains; // List of chains to visit.
7515 SmallPtrSet<SDNode *, 16> Visited; // Visited node set.
7517 // Get alias information for node.
7520 const Value *SrcValue;
7522 unsigned SrcValueAlign;
7523 const MDNode *SrcTBAAInfo;
7524 bool IsLoad = FindAliasInfo(N, Ptr, Size, SrcValue, SrcValueOffset,
7525 SrcValueAlign, SrcTBAAInfo);
7528 Chains.push_back(OriginalChain);
7531 // Look at each chain and determine if it is an alias. If so, add it to the
7532 // aliases list. If not, then continue up the chain looking for the next
7534 while (!Chains.empty()) {
7535 SDValue Chain = Chains.back();
7538 // For TokenFactor nodes, look at each operand and only continue up the
7539 // chain until we find two aliases. If we've seen two aliases, assume we'll
7540 // find more and revert to original chain since the xform is unlikely to be
7543 // FIXME: The depth check could be made to return the last non-aliasing
7544 // chain we found before we hit a tokenfactor rather than the original
7546 if (Depth > 6 || Aliases.size() == 2) {
7548 Aliases.push_back(OriginalChain);
7552 // Don't bother if we've been before.
7553 if (!Visited.insert(Chain.getNode()))
7556 switch (Chain.getOpcode()) {
7557 case ISD::EntryToken:
7558 // Entry token is ideal chain operand, but handled in FindBetterChain.
7563 // Get alias information for Chain.
7566 const Value *OpSrcValue;
7567 int OpSrcValueOffset;
7568 unsigned OpSrcValueAlign;
7569 const MDNode *OpSrcTBAAInfo;
7570 bool IsOpLoad = FindAliasInfo(Chain.getNode(), OpPtr, OpSize,
7571 OpSrcValue, OpSrcValueOffset,
7575 // If chain is alias then stop here.
7576 if (!(IsLoad && IsOpLoad) &&
7577 isAlias(Ptr, Size, SrcValue, SrcValueOffset, SrcValueAlign,
7579 OpPtr, OpSize, OpSrcValue, OpSrcValueOffset,
7580 OpSrcValueAlign, OpSrcTBAAInfo)) {
7581 Aliases.push_back(Chain);
7583 // Look further up the chain.
7584 Chains.push_back(Chain.getOperand(0));
7590 case ISD::TokenFactor:
7591 // We have to check each of the operands of the token factor for "small"
7592 // token factors, so we queue them up. Adding the operands to the queue
7593 // (stack) in reverse order maintains the original order and increases the
7594 // likelihood that getNode will find a matching token factor (CSE.)
7595 if (Chain.getNumOperands() > 16) {
7596 Aliases.push_back(Chain);
7599 for (unsigned n = Chain.getNumOperands(); n;)
7600 Chains.push_back(Chain.getOperand(--n));
7605 // For all other instructions we will just have to take what we can get.
7606 Aliases.push_back(Chain);
7612 /// FindBetterChain - Walk up chain skipping non-aliasing memory nodes, looking
7613 /// for a better chain (aliasing node.)
7614 SDValue DAGCombiner::FindBetterChain(SDNode *N, SDValue OldChain) {
7615 SmallVector<SDValue, 8> Aliases; // Ops for replacing token factor.
7617 // Accumulate all the aliases to this node.
7618 GatherAllAliases(N, OldChain, Aliases);
7620 if (Aliases.size() == 0) {
7621 // If no operands then chain to entry token.
7622 return DAG.getEntryNode();
7623 } else if (Aliases.size() == 1) {
7624 // If a single operand then chain to it. We don't need to revisit it.
7628 // Construct a custom tailored token factor.
7629 return DAG.getNode(ISD::TokenFactor, N->getDebugLoc(), MVT::Other,
7630 &Aliases[0], Aliases.size());
7633 // SelectionDAG::Combine - This is the entry point for the file.
7635 void SelectionDAG::Combine(CombineLevel Level, AliasAnalysis &AA,
7636 CodeGenOpt::Level OptLevel) {
7637 /// run - This is the main entry point to this class.
7639 DAGCombiner(*this, AA, OptLevel).Run(Level);