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 #include "llvm/CodeGen/SelectionDAG.h"
20 #include "llvm/ADT/SmallPtrSet.h"
21 #include "llvm/ADT/SetVector.h"
22 #include "llvm/ADT/Statistic.h"
23 #include "llvm/Analysis/AliasAnalysis.h"
24 #include "llvm/CodeGen/MachineFrameInfo.h"
25 #include "llvm/CodeGen/MachineFunction.h"
26 #include "llvm/IR/DataLayout.h"
27 #include "llvm/IR/DerivedTypes.h"
28 #include "llvm/IR/Function.h"
29 #include "llvm/IR/LLVMContext.h"
30 #include "llvm/Support/CommandLine.h"
31 #include "llvm/Support/Debug.h"
32 #include "llvm/Support/ErrorHandling.h"
33 #include "llvm/Support/MathExtras.h"
34 #include "llvm/Support/raw_ostream.h"
35 #include "llvm/Target/TargetLowering.h"
36 #include "llvm/Target/TargetMachine.h"
37 #include "llvm/Target/TargetOptions.h"
38 #include "llvm/Target/TargetRegisterInfo.h"
39 #include "llvm/Target/TargetSubtargetInfo.h"
43 #define DEBUG_TYPE "dagcombine"
45 STATISTIC(NodesCombined , "Number of dag nodes combined");
46 STATISTIC(PreIndexedNodes , "Number of pre-indexed nodes created");
47 STATISTIC(PostIndexedNodes, "Number of post-indexed nodes created");
48 STATISTIC(OpsNarrowed , "Number of load/op/store narrowed");
49 STATISTIC(LdStFP2Int , "Number of fp load/store pairs transformed to int");
50 STATISTIC(SlicedLoads, "Number of load sliced");
54 CombinerAA("combiner-alias-analysis", cl::Hidden,
55 cl::desc("Enable DAG combiner alias-analysis heuristics"));
58 CombinerGlobalAA("combiner-global-alias-analysis", cl::Hidden,
59 cl::desc("Enable DAG combiner's use of IR alias analysis"));
62 UseTBAA("combiner-use-tbaa", cl::Hidden, cl::init(true),
63 cl::desc("Enable DAG combiner's use of TBAA"));
66 static cl::opt<std::string>
67 CombinerAAOnlyFunc("combiner-aa-only-func", cl::Hidden,
68 cl::desc("Only use DAG-combiner alias analysis in this"
72 /// Hidden option to stress test load slicing, i.e., when this option
73 /// is enabled, load slicing bypasses most of its profitability guards.
75 StressLoadSlicing("combiner-stress-load-slicing", cl::Hidden,
76 cl::desc("Bypass the profitability model of load "
80 //------------------------------ DAGCombiner ---------------------------------//
84 const TargetLowering &TLI;
86 CodeGenOpt::Level OptLevel;
91 /// \brief Worklist of all of the nodes that need to be simplified.
93 /// This must behave as a stack -- new nodes to process are pushed onto the
94 /// back and when processing we pop off of the back.
96 /// The worklist will not contain duplicates but may contain null entries
97 /// due to nodes being deleted from the underlying DAG.
98 SmallVector<SDNode *, 64> Worklist;
100 /// \brief Mapping from an SDNode to its position on the worklist.
102 /// This is used to find and remove nodes from the worklist (by nulling
103 /// them) when they are deleted from the underlying DAG. It relies on
104 /// stable indices of nodes within the worklist.
105 DenseMap<SDNode *, unsigned> WorklistMap;
107 /// \brief Set of nodes which have been combined (at least once).
109 /// This is used to allow us to reliably add any operands of a DAG node
110 /// which have not yet been combined to the worklist.
111 SmallPtrSet<SDNode *, 64> CombinedNodes;
113 // AA - Used for DAG load/store alias analysis.
116 /// AddUsersToWorklist - When an instruction is simplified, add all users of
117 /// the instruction to the work lists because they might get more simplified
120 void AddUsersToWorklist(SDNode *N) {
121 for (SDNode *Node : N->uses())
125 /// visit - call the node-specific routine that knows how to fold each
126 /// particular type of node.
127 SDValue visit(SDNode *N);
130 /// AddToWorklist - Add to the work list making sure its instance is at the
131 /// back (next to be processed.)
132 void AddToWorklist(SDNode *N) {
133 // Skip handle nodes as they can't usefully be combined and confuse the
134 // zero-use deletion strategy.
135 if (N->getOpcode() == ISD::HANDLENODE)
138 if (WorklistMap.insert(std::make_pair(N, Worklist.size())).second)
139 Worklist.push_back(N);
142 /// removeFromWorklist - remove all instances of N from the worklist.
144 void removeFromWorklist(SDNode *N) {
145 CombinedNodes.erase(N);
147 auto It = WorklistMap.find(N);
148 if (It == WorklistMap.end())
149 return; // Not in the worklist.
151 // Null out the entry rather than erasing it to avoid a linear operation.
152 Worklist[It->second] = nullptr;
153 WorklistMap.erase(It);
156 void deleteAndRecombine(SDNode *N);
157 bool recursivelyDeleteUnusedNodes(SDNode *N);
159 SDValue CombineTo(SDNode *N, const SDValue *To, unsigned NumTo,
162 SDValue CombineTo(SDNode *N, SDValue Res, bool AddTo = true) {
163 return CombineTo(N, &Res, 1, AddTo);
166 SDValue CombineTo(SDNode *N, SDValue Res0, SDValue Res1,
168 SDValue To[] = { Res0, Res1 };
169 return CombineTo(N, To, 2, AddTo);
172 void CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO);
176 /// SimplifyDemandedBits - Check the specified integer node value to see if
177 /// it can be simplified or if things it uses can be simplified by bit
178 /// propagation. If so, return true.
179 bool SimplifyDemandedBits(SDValue Op) {
180 unsigned BitWidth = Op.getValueType().getScalarType().getSizeInBits();
181 APInt Demanded = APInt::getAllOnesValue(BitWidth);
182 return SimplifyDemandedBits(Op, Demanded);
185 bool SimplifyDemandedBits(SDValue Op, const APInt &Demanded);
187 bool CombineToPreIndexedLoadStore(SDNode *N);
188 bool CombineToPostIndexedLoadStore(SDNode *N);
189 bool SliceUpLoad(SDNode *N);
191 /// \brief Replace an ISD::EXTRACT_VECTOR_ELT of a load with a narrowed
194 /// \param EVE ISD::EXTRACT_VECTOR_ELT to be replaced.
195 /// \param InVecVT type of the input vector to EVE with bitcasts resolved.
196 /// \param EltNo index of the vector element to load.
197 /// \param OriginalLoad load that EVE came from to be replaced.
198 /// \returns EVE on success SDValue() on failure.
199 SDValue ReplaceExtractVectorEltOfLoadWithNarrowedLoad(
200 SDNode *EVE, EVT InVecVT, SDValue EltNo, LoadSDNode *OriginalLoad);
201 void ReplaceLoadWithPromotedLoad(SDNode *Load, SDNode *ExtLoad);
202 SDValue PromoteOperand(SDValue Op, EVT PVT, bool &Replace);
203 SDValue SExtPromoteOperand(SDValue Op, EVT PVT);
204 SDValue ZExtPromoteOperand(SDValue Op, EVT PVT);
205 SDValue PromoteIntBinOp(SDValue Op);
206 SDValue PromoteIntShiftOp(SDValue Op);
207 SDValue PromoteExtend(SDValue Op);
208 bool PromoteLoad(SDValue Op);
210 void ExtendSetCCUses(const SmallVectorImpl<SDNode *> &SetCCs,
211 SDValue Trunc, SDValue ExtLoad, SDLoc DL,
212 ISD::NodeType ExtType);
214 /// combine - call the node-specific routine that knows how to fold each
215 /// particular type of node. If that doesn't do anything, try the
216 /// target-specific DAG combines.
217 SDValue combine(SDNode *N);
219 // Visitation implementation - Implement dag node combining for different
220 // node types. The semantics are as follows:
222 // SDValue.getNode() == 0 - No change was made
223 // SDValue.getNode() == N - N was replaced, is dead and has been handled.
224 // otherwise - N should be replaced by the returned Operand.
226 SDValue visitTokenFactor(SDNode *N);
227 SDValue visitMERGE_VALUES(SDNode *N);
228 SDValue visitADD(SDNode *N);
229 SDValue visitSUB(SDNode *N);
230 SDValue visitADDC(SDNode *N);
231 SDValue visitSUBC(SDNode *N);
232 SDValue visitADDE(SDNode *N);
233 SDValue visitSUBE(SDNode *N);
234 SDValue visitMUL(SDNode *N);
235 SDValue visitSDIV(SDNode *N);
236 SDValue visitUDIV(SDNode *N);
237 SDValue visitSREM(SDNode *N);
238 SDValue visitUREM(SDNode *N);
239 SDValue visitMULHU(SDNode *N);
240 SDValue visitMULHS(SDNode *N);
241 SDValue visitSMUL_LOHI(SDNode *N);
242 SDValue visitUMUL_LOHI(SDNode *N);
243 SDValue visitSMULO(SDNode *N);
244 SDValue visitUMULO(SDNode *N);
245 SDValue visitSDIVREM(SDNode *N);
246 SDValue visitUDIVREM(SDNode *N);
247 SDValue visitAND(SDNode *N);
248 SDValue visitOR(SDNode *N);
249 SDValue visitXOR(SDNode *N);
250 SDValue SimplifyVBinOp(SDNode *N);
251 SDValue SimplifyVUnaryOp(SDNode *N);
252 SDValue visitSHL(SDNode *N);
253 SDValue visitSRA(SDNode *N);
254 SDValue visitSRL(SDNode *N);
255 SDValue visitRotate(SDNode *N);
256 SDValue visitCTLZ(SDNode *N);
257 SDValue visitCTLZ_ZERO_UNDEF(SDNode *N);
258 SDValue visitCTTZ(SDNode *N);
259 SDValue visitCTTZ_ZERO_UNDEF(SDNode *N);
260 SDValue visitCTPOP(SDNode *N);
261 SDValue visitSELECT(SDNode *N);
262 SDValue visitVSELECT(SDNode *N);
263 SDValue visitSELECT_CC(SDNode *N);
264 SDValue visitSETCC(SDNode *N);
265 SDValue visitSIGN_EXTEND(SDNode *N);
266 SDValue visitZERO_EXTEND(SDNode *N);
267 SDValue visitANY_EXTEND(SDNode *N);
268 SDValue visitSIGN_EXTEND_INREG(SDNode *N);
269 SDValue visitTRUNCATE(SDNode *N);
270 SDValue visitBITCAST(SDNode *N);
271 SDValue visitBUILD_PAIR(SDNode *N);
272 SDValue visitFADD(SDNode *N);
273 SDValue visitFSUB(SDNode *N);
274 SDValue visitFMUL(SDNode *N);
275 SDValue visitFMA(SDNode *N);
276 SDValue visitFDIV(SDNode *N);
277 SDValue visitFREM(SDNode *N);
278 SDValue visitFCOPYSIGN(SDNode *N);
279 SDValue visitSINT_TO_FP(SDNode *N);
280 SDValue visitUINT_TO_FP(SDNode *N);
281 SDValue visitFP_TO_SINT(SDNode *N);
282 SDValue visitFP_TO_UINT(SDNode *N);
283 SDValue visitFP_ROUND(SDNode *N);
284 SDValue visitFP_ROUND_INREG(SDNode *N);
285 SDValue visitFP_EXTEND(SDNode *N);
286 SDValue visitFNEG(SDNode *N);
287 SDValue visitFABS(SDNode *N);
288 SDValue visitFCEIL(SDNode *N);
289 SDValue visitFTRUNC(SDNode *N);
290 SDValue visitFFLOOR(SDNode *N);
291 SDValue visitBRCOND(SDNode *N);
292 SDValue visitBR_CC(SDNode *N);
293 SDValue visitLOAD(SDNode *N);
294 SDValue visitSTORE(SDNode *N);
295 SDValue visitINSERT_VECTOR_ELT(SDNode *N);
296 SDValue visitEXTRACT_VECTOR_ELT(SDNode *N);
297 SDValue visitBUILD_VECTOR(SDNode *N);
298 SDValue visitCONCAT_VECTORS(SDNode *N);
299 SDValue visitEXTRACT_SUBVECTOR(SDNode *N);
300 SDValue visitVECTOR_SHUFFLE(SDNode *N);
301 SDValue visitINSERT_SUBVECTOR(SDNode *N);
303 SDValue XformToShuffleWithZero(SDNode *N);
304 SDValue ReassociateOps(unsigned Opc, SDLoc DL, SDValue LHS, SDValue RHS);
306 SDValue visitShiftByConstant(SDNode *N, ConstantSDNode *Amt);
308 bool SimplifySelectOps(SDNode *SELECT, SDValue LHS, SDValue RHS);
309 SDValue SimplifyBinOpWithSameOpcodeHands(SDNode *N);
310 SDValue SimplifySelect(SDLoc DL, SDValue N0, SDValue N1, SDValue N2);
311 SDValue SimplifySelectCC(SDLoc DL, SDValue N0, SDValue N1, SDValue N2,
312 SDValue N3, ISD::CondCode CC,
313 bool NotExtCompare = false);
314 SDValue SimplifySetCC(EVT VT, SDValue N0, SDValue N1, ISD::CondCode Cond,
315 SDLoc DL, bool foldBooleans = true);
317 bool isSetCCEquivalent(SDValue N, SDValue &LHS, SDValue &RHS,
319 bool isOneUseSetCC(SDValue N) const;
321 SDValue SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp,
323 SDValue CombineConsecutiveLoads(SDNode *N, EVT VT);
324 SDValue ConstantFoldBITCASTofBUILD_VECTOR(SDNode *, EVT);
325 SDValue BuildSDIV(SDNode *N);
326 SDValue BuildSDIVPow2(SDNode *N);
327 SDValue BuildUDIV(SDNode *N);
328 SDValue MatchBSwapHWordLow(SDNode *N, SDValue N0, SDValue N1,
329 bool DemandHighBits = true);
330 SDValue MatchBSwapHWord(SDNode *N, SDValue N0, SDValue N1);
331 SDNode *MatchRotatePosNeg(SDValue Shifted, SDValue Pos, SDValue Neg,
332 SDValue InnerPos, SDValue InnerNeg,
333 unsigned PosOpcode, unsigned NegOpcode,
335 SDNode *MatchRotate(SDValue LHS, SDValue RHS, SDLoc DL);
336 SDValue ReduceLoadWidth(SDNode *N);
337 SDValue ReduceLoadOpStoreWidth(SDNode *N);
338 SDValue TransformFPLoadStorePair(SDNode *N);
339 SDValue reduceBuildVecExtToExtBuildVec(SDNode *N);
340 SDValue reduceBuildVecConvertToConvertBuildVec(SDNode *N);
342 SDValue GetDemandedBits(SDValue V, const APInt &Mask);
344 /// GatherAllAliases - Walk up chain skipping non-aliasing memory nodes,
345 /// looking for aliasing nodes and adding them to the Aliases vector.
346 void GatherAllAliases(SDNode *N, SDValue OriginalChain,
347 SmallVectorImpl<SDValue> &Aliases);
349 /// isAlias - Return true if there is any possibility that the two addresses
351 bool isAlias(LSBaseSDNode *Op0, LSBaseSDNode *Op1) const;
353 /// FindBetterChain - Walk up chain skipping non-aliasing memory nodes,
354 /// looking for a better chain (aliasing node.)
355 SDValue FindBetterChain(SDNode *N, SDValue Chain);
357 /// Merge consecutive store operations into a wide store.
358 /// This optimization uses wide integers or vectors when possible.
359 /// \return True if some memory operations were changed.
360 bool MergeConsecutiveStores(StoreSDNode *N);
362 /// \brief Try to transform a truncation where C is a constant:
363 /// (trunc (and X, C)) -> (and (trunc X), (trunc C))
365 /// \p N needs to be a truncation and its first operand an AND. Other
366 /// requirements are checked by the function (e.g. that trunc is
367 /// single-use) and if missed an empty SDValue is returned.
368 SDValue distributeTruncateThroughAnd(SDNode *N);
371 DAGCombiner(SelectionDAG &D, AliasAnalysis &A, CodeGenOpt::Level OL)
372 : DAG(D), TLI(D.getTargetLoweringInfo()), Level(BeforeLegalizeTypes),
373 OptLevel(OL), LegalOperations(false), LegalTypes(false), AA(A) {
374 AttributeSet FnAttrs =
375 DAG.getMachineFunction().getFunction()->getAttributes();
377 FnAttrs.hasAttribute(AttributeSet::FunctionIndex,
378 Attribute::OptimizeForSize) ||
379 FnAttrs.hasAttribute(AttributeSet::FunctionIndex, Attribute::MinSize);
382 /// Run - runs the dag combiner on all nodes in the work list
383 void Run(CombineLevel AtLevel);
385 SelectionDAG &getDAG() const { return DAG; }
387 /// getShiftAmountTy - Returns a type large enough to hold any valid
388 /// shift amount - before type legalization these can be huge.
389 EVT getShiftAmountTy(EVT LHSTy) {
390 assert(LHSTy.isInteger() && "Shift amount is not an integer type!");
391 if (LHSTy.isVector())
393 return LegalTypes ? TLI.getScalarShiftAmountTy(LHSTy)
394 : TLI.getPointerTy();
397 /// isTypeLegal - This method returns true if we are running before type
398 /// legalization or if the specified VT is legal.
399 bool isTypeLegal(const EVT &VT) {
400 if (!LegalTypes) return true;
401 return TLI.isTypeLegal(VT);
404 /// getSetCCResultType - Convenience wrapper around
405 /// TargetLowering::getSetCCResultType
406 EVT getSetCCResultType(EVT VT) const {
407 return TLI.getSetCCResultType(*DAG.getContext(), VT);
414 /// WorklistRemover - This class is a DAGUpdateListener that removes any deleted
415 /// nodes from the worklist.
416 class WorklistRemover : public SelectionDAG::DAGUpdateListener {
419 explicit WorklistRemover(DAGCombiner &dc)
420 : SelectionDAG::DAGUpdateListener(dc.getDAG()), DC(dc) {}
422 void NodeDeleted(SDNode *N, SDNode *E) override {
423 DC.removeFromWorklist(N);
428 //===----------------------------------------------------------------------===//
429 // TargetLowering::DAGCombinerInfo implementation
430 //===----------------------------------------------------------------------===//
432 void TargetLowering::DAGCombinerInfo::AddToWorklist(SDNode *N) {
433 ((DAGCombiner*)DC)->AddToWorklist(N);
436 void TargetLowering::DAGCombinerInfo::RemoveFromWorklist(SDNode *N) {
437 ((DAGCombiner*)DC)->removeFromWorklist(N);
440 SDValue TargetLowering::DAGCombinerInfo::
441 CombineTo(SDNode *N, const std::vector<SDValue> &To, bool AddTo) {
442 return ((DAGCombiner*)DC)->CombineTo(N, &To[0], To.size(), AddTo);
445 SDValue TargetLowering::DAGCombinerInfo::
446 CombineTo(SDNode *N, SDValue Res, bool AddTo) {
447 return ((DAGCombiner*)DC)->CombineTo(N, Res, AddTo);
451 SDValue TargetLowering::DAGCombinerInfo::
452 CombineTo(SDNode *N, SDValue Res0, SDValue Res1, bool AddTo) {
453 return ((DAGCombiner*)DC)->CombineTo(N, Res0, Res1, AddTo);
456 void TargetLowering::DAGCombinerInfo::
457 CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) {
458 return ((DAGCombiner*)DC)->CommitTargetLoweringOpt(TLO);
461 //===----------------------------------------------------------------------===//
463 //===----------------------------------------------------------------------===//
465 void DAGCombiner::deleteAndRecombine(SDNode *N) {
466 removeFromWorklist(N);
468 // If the operands of this node are only used by the node, they will now be
469 // dead. Make sure to re-visit them and recursively delete dead nodes.
470 for (const SDValue &Op : N->ops())
472 AddToWorklist(Op.getNode());
477 /// isNegatibleForFree - Return 1 if we can compute the negated form of the
478 /// specified expression for the same cost as the expression itself, or 2 if we
479 /// can compute the negated form more cheaply than the expression itself.
480 static char isNegatibleForFree(SDValue Op, bool LegalOperations,
481 const TargetLowering &TLI,
482 const TargetOptions *Options,
483 unsigned Depth = 0) {
484 // fneg is removable even if it has multiple uses.
485 if (Op.getOpcode() == ISD::FNEG) return 2;
487 // Don't allow anything with multiple uses.
488 if (!Op.hasOneUse()) return 0;
490 // Don't recurse exponentially.
491 if (Depth > 6) return 0;
493 switch (Op.getOpcode()) {
494 default: return false;
495 case ISD::ConstantFP:
496 // Don't invert constant FP values after legalize. The negated constant
497 // isn't necessarily legal.
498 return LegalOperations ? 0 : 1;
500 // FIXME: determine better conditions for this xform.
501 if (!Options->UnsafeFPMath) return 0;
503 // After operation legalization, it might not be legal to create new FSUBs.
504 if (LegalOperations &&
505 !TLI.isOperationLegalOrCustom(ISD::FSUB, Op.getValueType()))
508 // fold (fneg (fadd A, B)) -> (fsub (fneg A), B)
509 if (char V = isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI,
512 // fold (fneg (fadd A, B)) -> (fsub (fneg B), A)
513 return isNegatibleForFree(Op.getOperand(1), LegalOperations, TLI, Options,
516 // We can't turn -(A-B) into B-A when we honor signed zeros.
517 if (!Options->UnsafeFPMath) return 0;
519 // fold (fneg (fsub A, B)) -> (fsub B, A)
524 if (Options->HonorSignDependentRoundingFPMath()) return 0;
526 // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y) or (fmul X, (fneg Y))
527 if (char V = isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI,
531 return isNegatibleForFree(Op.getOperand(1), LegalOperations, TLI, Options,
537 return isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI, Options,
542 /// GetNegatedExpression - If isNegatibleForFree returns true, this function
543 /// returns the newly negated expression.
544 static SDValue GetNegatedExpression(SDValue Op, SelectionDAG &DAG,
545 bool LegalOperations, unsigned Depth = 0) {
546 // fneg is removable even if it has multiple uses.
547 if (Op.getOpcode() == ISD::FNEG) return Op.getOperand(0);
549 // Don't allow anything with multiple uses.
550 assert(Op.hasOneUse() && "Unknown reuse!");
552 assert(Depth <= 6 && "GetNegatedExpression doesn't match isNegatibleForFree");
553 switch (Op.getOpcode()) {
554 default: llvm_unreachable("Unknown code");
555 case ISD::ConstantFP: {
556 APFloat V = cast<ConstantFPSDNode>(Op)->getValueAPF();
558 return DAG.getConstantFP(V, Op.getValueType());
561 // FIXME: determine better conditions for this xform.
562 assert(DAG.getTarget().Options.UnsafeFPMath);
564 // fold (fneg (fadd A, B)) -> (fsub (fneg A), B)
565 if (isNegatibleForFree(Op.getOperand(0), LegalOperations,
566 DAG.getTargetLoweringInfo(),
567 &DAG.getTarget().Options, Depth+1))
568 return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
569 GetNegatedExpression(Op.getOperand(0), DAG,
570 LegalOperations, Depth+1),
572 // fold (fneg (fadd A, B)) -> (fsub (fneg B), A)
573 return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
574 GetNegatedExpression(Op.getOperand(1), DAG,
575 LegalOperations, Depth+1),
578 // We can't turn -(A-B) into B-A when we honor signed zeros.
579 assert(DAG.getTarget().Options.UnsafeFPMath);
581 // fold (fneg (fsub 0, B)) -> B
582 if (ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(Op.getOperand(0)))
583 if (N0CFP->getValueAPF().isZero())
584 return Op.getOperand(1);
586 // fold (fneg (fsub A, B)) -> (fsub B, A)
587 return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
588 Op.getOperand(1), Op.getOperand(0));
592 assert(!DAG.getTarget().Options.HonorSignDependentRoundingFPMath());
594 // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y)
595 if (isNegatibleForFree(Op.getOperand(0), LegalOperations,
596 DAG.getTargetLoweringInfo(),
597 &DAG.getTarget().Options, Depth+1))
598 return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
599 GetNegatedExpression(Op.getOperand(0), DAG,
600 LegalOperations, Depth+1),
603 // fold (fneg (fmul X, Y)) -> (fmul X, (fneg Y))
604 return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
606 GetNegatedExpression(Op.getOperand(1), DAG,
607 LegalOperations, Depth+1));
611 return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
612 GetNegatedExpression(Op.getOperand(0), DAG,
613 LegalOperations, Depth+1));
615 return DAG.getNode(ISD::FP_ROUND, SDLoc(Op), Op.getValueType(),
616 GetNegatedExpression(Op.getOperand(0), DAG,
617 LegalOperations, Depth+1),
622 // isSetCCEquivalent - Return true if this node is a setcc, or is a select_cc
623 // that selects between the target values used for true and false, making it
624 // equivalent to a setcc. Also, set the incoming LHS, RHS, and CC references to
625 // the appropriate nodes based on the type of node we are checking. This
626 // simplifies life a bit for the callers.
627 bool DAGCombiner::isSetCCEquivalent(SDValue N, SDValue &LHS, SDValue &RHS,
629 if (N.getOpcode() == ISD::SETCC) {
630 LHS = N.getOperand(0);
631 RHS = N.getOperand(1);
632 CC = N.getOperand(2);
636 if (N.getOpcode() != ISD::SELECT_CC ||
637 !TLI.isConstTrueVal(N.getOperand(2).getNode()) ||
638 !TLI.isConstFalseVal(N.getOperand(3).getNode()))
641 LHS = N.getOperand(0);
642 RHS = N.getOperand(1);
643 CC = N.getOperand(4);
647 // isOneUseSetCC - Return true if this is a SetCC-equivalent operation with only
648 // one use. If this is true, it allows the users to invert the operation for
649 // free when it is profitable to do so.
650 bool DAGCombiner::isOneUseSetCC(SDValue N) const {
652 if (isSetCCEquivalent(N, N0, N1, N2) && N.getNode()->hasOneUse())
657 /// isConstantSplatVector - Returns true if N is a BUILD_VECTOR node whose
658 /// elements are all the same constant or undefined.
659 static bool isConstantSplatVector(SDNode *N, APInt& SplatValue) {
660 BuildVectorSDNode *C = dyn_cast<BuildVectorSDNode>(N);
665 unsigned SplatBitSize;
667 EVT EltVT = N->getValueType(0).getVectorElementType();
668 return (C->isConstantSplat(SplatValue, SplatUndef, SplatBitSize,
670 EltVT.getSizeInBits() >= SplatBitSize);
673 // \brief Returns the SDNode if it is a constant BuildVector or constant.
674 static SDNode *isConstantBuildVectorOrConstantInt(SDValue N) {
675 if (isa<ConstantSDNode>(N))
677 BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N);
678 if(BV && BV->isConstant())
683 // \brief Returns the SDNode if it is a constant splat BuildVector or constant
685 static ConstantSDNode *isConstOrConstSplat(SDValue N) {
686 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N))
689 if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) {
690 BitVector UndefElements;
691 ConstantSDNode *CN = BV->getConstantSplatNode(&UndefElements);
693 // BuildVectors can truncate their operands. Ignore that case here.
694 // FIXME: We blindly ignore splats which include undef which is overly
696 if (CN && UndefElements.none() &&
697 CN->getValueType(0) == N.getValueType().getScalarType())
704 SDValue DAGCombiner::ReassociateOps(unsigned Opc, SDLoc DL,
705 SDValue N0, SDValue N1) {
706 EVT VT = N0.getValueType();
707 if (N0.getOpcode() == Opc) {
708 if (SDNode *L = isConstantBuildVectorOrConstantInt(N0.getOperand(1))) {
709 if (SDNode *R = isConstantBuildVectorOrConstantInt(N1)) {
710 // reassoc. (op (op x, c1), c2) -> (op x, (op c1, c2))
711 SDValue OpNode = DAG.FoldConstantArithmetic(Opc, VT, L, R);
712 if (!OpNode.getNode())
714 return DAG.getNode(Opc, DL, VT, N0.getOperand(0), OpNode);
716 if (N0.hasOneUse()) {
717 // reassoc. (op (op x, c1), y) -> (op (op x, y), c1) iff x+c1 has one
719 SDValue OpNode = DAG.getNode(Opc, SDLoc(N0), VT, N0.getOperand(0), N1);
720 if (!OpNode.getNode())
722 AddToWorklist(OpNode.getNode());
723 return DAG.getNode(Opc, DL, VT, OpNode, N0.getOperand(1));
728 if (N1.getOpcode() == Opc) {
729 if (SDNode *R = isConstantBuildVectorOrConstantInt(N1.getOperand(1))) {
730 if (SDNode *L = isConstantBuildVectorOrConstantInt(N0)) {
731 // reassoc. (op c2, (op x, c1)) -> (op x, (op c1, c2))
732 SDValue OpNode = DAG.FoldConstantArithmetic(Opc, VT, R, L);
733 if (!OpNode.getNode())
735 return DAG.getNode(Opc, DL, VT, N1.getOperand(0), OpNode);
737 if (N1.hasOneUse()) {
738 // reassoc. (op y, (op x, c1)) -> (op (op x, y), c1) iff x+c1 has one
740 SDValue OpNode = DAG.getNode(Opc, SDLoc(N0), VT, N1.getOperand(0), N0);
741 if (!OpNode.getNode())
743 AddToWorklist(OpNode.getNode());
744 return DAG.getNode(Opc, DL, VT, OpNode, N1.getOperand(1));
752 SDValue DAGCombiner::CombineTo(SDNode *N, const SDValue *To, unsigned NumTo,
754 assert(N->getNumValues() == NumTo && "Broken CombineTo call!");
756 DEBUG(dbgs() << "\nReplacing.1 ";
758 dbgs() << "\nWith: ";
759 To[0].getNode()->dump(&DAG);
760 dbgs() << " and " << NumTo-1 << " other values\n";
761 for (unsigned i = 0, e = NumTo; i != e; ++i)
762 assert((!To[i].getNode() ||
763 N->getValueType(i) == To[i].getValueType()) &&
764 "Cannot combine value to value of different type!"));
765 WorklistRemover DeadNodes(*this);
766 DAG.ReplaceAllUsesWith(N, To);
768 // Push the new nodes and any users onto the worklist
769 for (unsigned i = 0, e = NumTo; i != e; ++i) {
770 if (To[i].getNode()) {
771 AddToWorklist(To[i].getNode());
772 AddUsersToWorklist(To[i].getNode());
777 // Finally, if the node is now dead, remove it from the graph. The node
778 // may not be dead if the replacement process recursively simplified to
779 // something else needing this node.
781 deleteAndRecombine(N);
782 return SDValue(N, 0);
786 CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) {
787 // Replace all uses. If any nodes become isomorphic to other nodes and
788 // are deleted, make sure to remove them from our worklist.
789 WorklistRemover DeadNodes(*this);
790 DAG.ReplaceAllUsesOfValueWith(TLO.Old, TLO.New);
792 // Push the new node and any (possibly new) users onto the worklist.
793 AddToWorklist(TLO.New.getNode());
794 AddUsersToWorklist(TLO.New.getNode());
796 // Finally, if the node is now dead, remove it from the graph. The node
797 // may not be dead if the replacement process recursively simplified to
798 // something else needing this node.
799 if (TLO.Old.getNode()->use_empty())
800 deleteAndRecombine(TLO.Old.getNode());
803 /// SimplifyDemandedBits - Check the specified integer node value to see if
804 /// it can be simplified or if things it uses can be simplified by bit
805 /// propagation. If so, return true.
806 bool DAGCombiner::SimplifyDemandedBits(SDValue Op, const APInt &Demanded) {
807 TargetLowering::TargetLoweringOpt TLO(DAG, LegalTypes, LegalOperations);
808 APInt KnownZero, KnownOne;
809 if (!TLI.SimplifyDemandedBits(Op, Demanded, KnownZero, KnownOne, TLO))
813 AddToWorklist(Op.getNode());
815 // Replace the old value with the new one.
817 DEBUG(dbgs() << "\nReplacing.2 ";
818 TLO.Old.getNode()->dump(&DAG);
819 dbgs() << "\nWith: ";
820 TLO.New.getNode()->dump(&DAG);
823 CommitTargetLoweringOpt(TLO);
827 void DAGCombiner::ReplaceLoadWithPromotedLoad(SDNode *Load, SDNode *ExtLoad) {
829 EVT VT = Load->getValueType(0);
830 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, dl, VT, SDValue(ExtLoad, 0));
832 DEBUG(dbgs() << "\nReplacing.9 ";
834 dbgs() << "\nWith: ";
835 Trunc.getNode()->dump(&DAG);
837 WorklistRemover DeadNodes(*this);
838 DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 0), Trunc);
839 DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 1), SDValue(ExtLoad, 1));
840 deleteAndRecombine(Load);
841 AddToWorklist(Trunc.getNode());
844 SDValue DAGCombiner::PromoteOperand(SDValue Op, EVT PVT, bool &Replace) {
847 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Op)) {
848 EVT MemVT = LD->getMemoryVT();
849 ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD)
850 ? (TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT) ? ISD::ZEXTLOAD
852 : LD->getExtensionType();
854 return DAG.getExtLoad(ExtType, dl, PVT,
855 LD->getChain(), LD->getBasePtr(),
856 MemVT, LD->getMemOperand());
859 unsigned Opc = Op.getOpcode();
862 case ISD::AssertSext:
863 return DAG.getNode(ISD::AssertSext, dl, PVT,
864 SExtPromoteOperand(Op.getOperand(0), PVT),
866 case ISD::AssertZext:
867 return DAG.getNode(ISD::AssertZext, dl, PVT,
868 ZExtPromoteOperand(Op.getOperand(0), PVT),
870 case ISD::Constant: {
872 Op.getValueType().isByteSized() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
873 return DAG.getNode(ExtOpc, dl, PVT, Op);
877 if (!TLI.isOperationLegal(ISD::ANY_EXTEND, PVT))
879 return DAG.getNode(ISD::ANY_EXTEND, dl, PVT, Op);
882 SDValue DAGCombiner::SExtPromoteOperand(SDValue Op, EVT PVT) {
883 if (!TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, PVT))
885 EVT OldVT = Op.getValueType();
887 bool Replace = false;
888 SDValue NewOp = PromoteOperand(Op, PVT, Replace);
889 if (!NewOp.getNode())
891 AddToWorklist(NewOp.getNode());
894 ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode());
895 return DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, NewOp.getValueType(), NewOp,
896 DAG.getValueType(OldVT));
899 SDValue DAGCombiner::ZExtPromoteOperand(SDValue Op, EVT PVT) {
900 EVT OldVT = Op.getValueType();
902 bool Replace = false;
903 SDValue NewOp = PromoteOperand(Op, PVT, Replace);
904 if (!NewOp.getNode())
906 AddToWorklist(NewOp.getNode());
909 ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode());
910 return DAG.getZeroExtendInReg(NewOp, dl, OldVT);
913 /// PromoteIntBinOp - Promote the specified integer binary operation if the
914 /// target indicates it is beneficial. e.g. On x86, it's usually better to
915 /// promote i16 operations to i32 since i16 instructions are longer.
916 SDValue DAGCombiner::PromoteIntBinOp(SDValue Op) {
917 if (!LegalOperations)
920 EVT VT = Op.getValueType();
921 if (VT.isVector() || !VT.isInteger())
924 // If operation type is 'undesirable', e.g. i16 on x86, consider
926 unsigned Opc = Op.getOpcode();
927 if (TLI.isTypeDesirableForOp(Opc, VT))
931 // Consult target whether it is a good idea to promote this operation and
932 // what's the right type to promote it to.
933 if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
934 assert(PVT != VT && "Don't know what type to promote to!");
936 bool Replace0 = false;
937 SDValue N0 = Op.getOperand(0);
938 SDValue NN0 = PromoteOperand(N0, PVT, Replace0);
942 bool Replace1 = false;
943 SDValue N1 = Op.getOperand(1);
948 NN1 = PromoteOperand(N1, PVT, Replace1);
953 AddToWorklist(NN0.getNode());
955 AddToWorklist(NN1.getNode());
958 ReplaceLoadWithPromotedLoad(N0.getNode(), NN0.getNode());
960 ReplaceLoadWithPromotedLoad(N1.getNode(), NN1.getNode());
962 DEBUG(dbgs() << "\nPromoting ";
963 Op.getNode()->dump(&DAG));
965 return DAG.getNode(ISD::TRUNCATE, dl, VT,
966 DAG.getNode(Opc, dl, PVT, NN0, NN1));
971 /// PromoteIntShiftOp - Promote the specified integer shift operation if the
972 /// target indicates it is beneficial. e.g. On x86, it's usually better to
973 /// promote i16 operations to i32 since i16 instructions are longer.
974 SDValue DAGCombiner::PromoteIntShiftOp(SDValue Op) {
975 if (!LegalOperations)
978 EVT VT = Op.getValueType();
979 if (VT.isVector() || !VT.isInteger())
982 // If operation type is 'undesirable', e.g. i16 on x86, consider
984 unsigned Opc = Op.getOpcode();
985 if (TLI.isTypeDesirableForOp(Opc, VT))
989 // Consult target whether it is a good idea to promote this operation and
990 // what's the right type to promote it to.
991 if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
992 assert(PVT != VT && "Don't know what type to promote to!");
994 bool Replace = false;
995 SDValue N0 = Op.getOperand(0);
997 N0 = SExtPromoteOperand(Op.getOperand(0), PVT);
998 else if (Opc == ISD::SRL)
999 N0 = ZExtPromoteOperand(Op.getOperand(0), PVT);
1001 N0 = PromoteOperand(N0, PVT, Replace);
1005 AddToWorklist(N0.getNode());
1007 ReplaceLoadWithPromotedLoad(Op.getOperand(0).getNode(), N0.getNode());
1009 DEBUG(dbgs() << "\nPromoting ";
1010 Op.getNode()->dump(&DAG));
1012 return DAG.getNode(ISD::TRUNCATE, dl, VT,
1013 DAG.getNode(Opc, dl, PVT, N0, Op.getOperand(1)));
1018 SDValue DAGCombiner::PromoteExtend(SDValue Op) {
1019 if (!LegalOperations)
1022 EVT VT = Op.getValueType();
1023 if (VT.isVector() || !VT.isInteger())
1026 // If operation type is 'undesirable', e.g. i16 on x86, consider
1028 unsigned Opc = Op.getOpcode();
1029 if (TLI.isTypeDesirableForOp(Opc, VT))
1033 // Consult target whether it is a good idea to promote this operation and
1034 // what's the right type to promote it to.
1035 if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1036 assert(PVT != VT && "Don't know what type to promote to!");
1037 // fold (aext (aext x)) -> (aext x)
1038 // fold (aext (zext x)) -> (zext x)
1039 // fold (aext (sext x)) -> (sext x)
1040 DEBUG(dbgs() << "\nPromoting ";
1041 Op.getNode()->dump(&DAG));
1042 return DAG.getNode(Op.getOpcode(), SDLoc(Op), VT, Op.getOperand(0));
1047 bool DAGCombiner::PromoteLoad(SDValue Op) {
1048 if (!LegalOperations)
1051 EVT VT = Op.getValueType();
1052 if (VT.isVector() || !VT.isInteger())
1055 // If operation type is 'undesirable', e.g. i16 on x86, consider
1057 unsigned Opc = Op.getOpcode();
1058 if (TLI.isTypeDesirableForOp(Opc, VT))
1062 // Consult target whether it is a good idea to promote this operation and
1063 // what's the right type to promote it to.
1064 if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1065 assert(PVT != VT && "Don't know what type to promote to!");
1068 SDNode *N = Op.getNode();
1069 LoadSDNode *LD = cast<LoadSDNode>(N);
1070 EVT MemVT = LD->getMemoryVT();
1071 ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD)
1072 ? (TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT) ? ISD::ZEXTLOAD
1074 : LD->getExtensionType();
1075 SDValue NewLD = DAG.getExtLoad(ExtType, dl, PVT,
1076 LD->getChain(), LD->getBasePtr(),
1077 MemVT, LD->getMemOperand());
1078 SDValue Result = DAG.getNode(ISD::TRUNCATE, dl, VT, NewLD);
1080 DEBUG(dbgs() << "\nPromoting ";
1083 Result.getNode()->dump(&DAG);
1085 WorklistRemover DeadNodes(*this);
1086 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result);
1087 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), NewLD.getValue(1));
1088 deleteAndRecombine(N);
1089 AddToWorklist(Result.getNode());
1095 /// \brief Recursively delete a node which has no uses and any operands for
1096 /// which it is the only use.
1098 /// Note that this both deletes the nodes and removes them from the worklist.
1099 /// It also adds any nodes who have had a user deleted to the worklist as they
1100 /// may now have only one use and subject to other combines.
1101 bool DAGCombiner::recursivelyDeleteUnusedNodes(SDNode *N) {
1102 if (!N->use_empty())
1105 SmallSetVector<SDNode *, 16> Nodes;
1108 N = Nodes.pop_back_val();
1112 if (N->use_empty()) {
1113 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1114 Nodes.insert(N->getOperand(i).getNode());
1116 removeFromWorklist(N);
1121 } while (!Nodes.empty());
1125 //===----------------------------------------------------------------------===//
1126 // Main DAG Combiner implementation
1127 //===----------------------------------------------------------------------===//
1129 void DAGCombiner::Run(CombineLevel AtLevel) {
1130 // set the instance variables, so that the various visit routines may use it.
1132 LegalOperations = Level >= AfterLegalizeVectorOps;
1133 LegalTypes = Level >= AfterLegalizeTypes;
1135 // Add all the dag nodes to the worklist.
1136 for (SelectionDAG::allnodes_iterator I = DAG.allnodes_begin(),
1137 E = DAG.allnodes_end(); I != E; ++I)
1140 // Create a dummy node (which is not added to allnodes), that adds a reference
1141 // to the root node, preventing it from being deleted, and tracking any
1142 // changes of the root.
1143 HandleSDNode Dummy(DAG.getRoot());
1145 // while the worklist isn't empty, find a node and
1146 // try and combine it.
1147 while (!WorklistMap.empty()) {
1149 // The Worklist holds the SDNodes in order, but it may contain null entries.
1151 N = Worklist.pop_back_val();
1154 bool GoodWorklistEntry = WorklistMap.erase(N);
1155 (void)GoodWorklistEntry;
1156 assert(GoodWorklistEntry &&
1157 "Found a worklist entry without a corresponding map entry!");
1159 // If N has no uses, it is dead. Make sure to revisit all N's operands once
1160 // N is deleted from the DAG, since they too may now be dead or may have a
1161 // reduced number of uses, allowing other xforms.
1162 if (recursivelyDeleteUnusedNodes(N))
1165 WorklistRemover DeadNodes(*this);
1167 // If this combine is running after legalizing the DAG, re-legalize any
1168 // nodes pulled off the worklist.
1169 if (Level == AfterLegalizeDAG) {
1170 SmallSetVector<SDNode *, 16> UpdatedNodes;
1171 bool NIsValid = DAG.LegalizeOp(N, UpdatedNodes);
1173 for (SDNode *LN : UpdatedNodes) {
1175 AddUsersToWorklist(LN);
1181 DEBUG(dbgs() << "\nCombining: "; N->dump(&DAG));
1183 // Add any operands of the new node which have not yet been combined to the
1184 // worklist as well. Because the worklist uniques things already, this
1185 // won't repeatedly process the same operand.
1186 CombinedNodes.insert(N);
1187 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1188 if (!CombinedNodes.count(N->getOperand(i).getNode()))
1189 AddToWorklist(N->getOperand(i).getNode());
1191 SDValue RV = combine(N);
1198 // If we get back the same node we passed in, rather than a new node or
1199 // zero, we know that the node must have defined multiple values and
1200 // CombineTo was used. Since CombineTo takes care of the worklist
1201 // mechanics for us, we have no work to do in this case.
1202 if (RV.getNode() == N)
1205 assert(N->getOpcode() != ISD::DELETED_NODE &&
1206 RV.getNode()->getOpcode() != ISD::DELETED_NODE &&
1207 "Node was deleted but visit returned new node!");
1209 DEBUG(dbgs() << " ... into: ";
1210 RV.getNode()->dump(&DAG));
1212 // Transfer debug value.
1213 DAG.TransferDbgValues(SDValue(N, 0), RV);
1214 if (N->getNumValues() == RV.getNode()->getNumValues())
1215 DAG.ReplaceAllUsesWith(N, RV.getNode());
1217 assert(N->getValueType(0) == RV.getValueType() &&
1218 N->getNumValues() == 1 && "Type mismatch");
1220 DAG.ReplaceAllUsesWith(N, &OpV);
1223 // Push the new node and any users onto the worklist
1224 AddToWorklist(RV.getNode());
1225 AddUsersToWorklist(RV.getNode());
1227 // Finally, if the node is now dead, remove it from the graph. The node
1228 // may not be dead if the replacement process recursively simplified to
1229 // something else needing this node. This will also take care of adding any
1230 // operands which have lost a user to the worklist.
1231 recursivelyDeleteUnusedNodes(N);
1234 // If the root changed (e.g. it was a dead load, update the root).
1235 DAG.setRoot(Dummy.getValue());
1236 DAG.RemoveDeadNodes();
1239 SDValue DAGCombiner::visit(SDNode *N) {
1240 switch (N->getOpcode()) {
1242 case ISD::TokenFactor: return visitTokenFactor(N);
1243 case ISD::MERGE_VALUES: return visitMERGE_VALUES(N);
1244 case ISD::ADD: return visitADD(N);
1245 case ISD::SUB: return visitSUB(N);
1246 case ISD::ADDC: return visitADDC(N);
1247 case ISD::SUBC: return visitSUBC(N);
1248 case ISD::ADDE: return visitADDE(N);
1249 case ISD::SUBE: return visitSUBE(N);
1250 case ISD::MUL: return visitMUL(N);
1251 case ISD::SDIV: return visitSDIV(N);
1252 case ISD::UDIV: return visitUDIV(N);
1253 case ISD::SREM: return visitSREM(N);
1254 case ISD::UREM: return visitUREM(N);
1255 case ISD::MULHU: return visitMULHU(N);
1256 case ISD::MULHS: return visitMULHS(N);
1257 case ISD::SMUL_LOHI: return visitSMUL_LOHI(N);
1258 case ISD::UMUL_LOHI: return visitUMUL_LOHI(N);
1259 case ISD::SMULO: return visitSMULO(N);
1260 case ISD::UMULO: return visitUMULO(N);
1261 case ISD::SDIVREM: return visitSDIVREM(N);
1262 case ISD::UDIVREM: return visitUDIVREM(N);
1263 case ISD::AND: return visitAND(N);
1264 case ISD::OR: return visitOR(N);
1265 case ISD::XOR: return visitXOR(N);
1266 case ISD::SHL: return visitSHL(N);
1267 case ISD::SRA: return visitSRA(N);
1268 case ISD::SRL: return visitSRL(N);
1270 case ISD::ROTL: return visitRotate(N);
1271 case ISD::CTLZ: return visitCTLZ(N);
1272 case ISD::CTLZ_ZERO_UNDEF: return visitCTLZ_ZERO_UNDEF(N);
1273 case ISD::CTTZ: return visitCTTZ(N);
1274 case ISD::CTTZ_ZERO_UNDEF: return visitCTTZ_ZERO_UNDEF(N);
1275 case ISD::CTPOP: return visitCTPOP(N);
1276 case ISD::SELECT: return visitSELECT(N);
1277 case ISD::VSELECT: return visitVSELECT(N);
1278 case ISD::SELECT_CC: return visitSELECT_CC(N);
1279 case ISD::SETCC: return visitSETCC(N);
1280 case ISD::SIGN_EXTEND: return visitSIGN_EXTEND(N);
1281 case ISD::ZERO_EXTEND: return visitZERO_EXTEND(N);
1282 case ISD::ANY_EXTEND: return visitANY_EXTEND(N);
1283 case ISD::SIGN_EXTEND_INREG: return visitSIGN_EXTEND_INREG(N);
1284 case ISD::TRUNCATE: return visitTRUNCATE(N);
1285 case ISD::BITCAST: return visitBITCAST(N);
1286 case ISD::BUILD_PAIR: return visitBUILD_PAIR(N);
1287 case ISD::FADD: return visitFADD(N);
1288 case ISD::FSUB: return visitFSUB(N);
1289 case ISD::FMUL: return visitFMUL(N);
1290 case ISD::FMA: return visitFMA(N);
1291 case ISD::FDIV: return visitFDIV(N);
1292 case ISD::FREM: return visitFREM(N);
1293 case ISD::FCOPYSIGN: return visitFCOPYSIGN(N);
1294 case ISD::SINT_TO_FP: return visitSINT_TO_FP(N);
1295 case ISD::UINT_TO_FP: return visitUINT_TO_FP(N);
1296 case ISD::FP_TO_SINT: return visitFP_TO_SINT(N);
1297 case ISD::FP_TO_UINT: return visitFP_TO_UINT(N);
1298 case ISD::FP_ROUND: return visitFP_ROUND(N);
1299 case ISD::FP_ROUND_INREG: return visitFP_ROUND_INREG(N);
1300 case ISD::FP_EXTEND: return visitFP_EXTEND(N);
1301 case ISD::FNEG: return visitFNEG(N);
1302 case ISD::FABS: return visitFABS(N);
1303 case ISD::FFLOOR: return visitFFLOOR(N);
1304 case ISD::FCEIL: return visitFCEIL(N);
1305 case ISD::FTRUNC: return visitFTRUNC(N);
1306 case ISD::BRCOND: return visitBRCOND(N);
1307 case ISD::BR_CC: return visitBR_CC(N);
1308 case ISD::LOAD: return visitLOAD(N);
1309 case ISD::STORE: return visitSTORE(N);
1310 case ISD::INSERT_VECTOR_ELT: return visitINSERT_VECTOR_ELT(N);
1311 case ISD::EXTRACT_VECTOR_ELT: return visitEXTRACT_VECTOR_ELT(N);
1312 case ISD::BUILD_VECTOR: return visitBUILD_VECTOR(N);
1313 case ISD::CONCAT_VECTORS: return visitCONCAT_VECTORS(N);
1314 case ISD::EXTRACT_SUBVECTOR: return visitEXTRACT_SUBVECTOR(N);
1315 case ISD::VECTOR_SHUFFLE: return visitVECTOR_SHUFFLE(N);
1316 case ISD::INSERT_SUBVECTOR: return visitINSERT_SUBVECTOR(N);
1321 SDValue DAGCombiner::combine(SDNode *N) {
1322 SDValue RV = visit(N);
1324 // If nothing happened, try a target-specific DAG combine.
1325 if (!RV.getNode()) {
1326 assert(N->getOpcode() != ISD::DELETED_NODE &&
1327 "Node was deleted but visit returned NULL!");
1329 if (N->getOpcode() >= ISD::BUILTIN_OP_END ||
1330 TLI.hasTargetDAGCombine((ISD::NodeType)N->getOpcode())) {
1332 // Expose the DAG combiner to the target combiner impls.
1333 TargetLowering::DAGCombinerInfo
1334 DagCombineInfo(DAG, Level, false, this);
1336 RV = TLI.PerformDAGCombine(N, DagCombineInfo);
1340 // If nothing happened still, try promoting the operation.
1341 if (!RV.getNode()) {
1342 switch (N->getOpcode()) {
1350 RV = PromoteIntBinOp(SDValue(N, 0));
1355 RV = PromoteIntShiftOp(SDValue(N, 0));
1357 case ISD::SIGN_EXTEND:
1358 case ISD::ZERO_EXTEND:
1359 case ISD::ANY_EXTEND:
1360 RV = PromoteExtend(SDValue(N, 0));
1363 if (PromoteLoad(SDValue(N, 0)))
1369 // If N is a commutative binary node, try commuting it to enable more
1371 if (!RV.getNode() && SelectionDAG::isCommutativeBinOp(N->getOpcode()) &&
1372 N->getNumValues() == 1) {
1373 SDValue N0 = N->getOperand(0);
1374 SDValue N1 = N->getOperand(1);
1376 // Constant operands are canonicalized to RHS.
1377 if (isa<ConstantSDNode>(N0) || !isa<ConstantSDNode>(N1)) {
1378 SDValue Ops[] = {N1, N0};
1380 if (const BinaryWithFlagsSDNode *BinNode =
1381 dyn_cast<BinaryWithFlagsSDNode>(N)) {
1382 CSENode = DAG.getNodeIfExists(
1383 N->getOpcode(), N->getVTList(), Ops, BinNode->hasNoUnsignedWrap(),
1384 BinNode->hasNoSignedWrap(), BinNode->isExact());
1386 CSENode = DAG.getNodeIfExists(N->getOpcode(), N->getVTList(), Ops);
1389 return SDValue(CSENode, 0);
1396 /// getInputChainForNode - Given a node, return its input chain if it has one,
1397 /// otherwise return a null sd operand.
1398 static SDValue getInputChainForNode(SDNode *N) {
1399 if (unsigned NumOps = N->getNumOperands()) {
1400 if (N->getOperand(0).getValueType() == MVT::Other)
1401 return N->getOperand(0);
1402 if (N->getOperand(NumOps-1).getValueType() == MVT::Other)
1403 return N->getOperand(NumOps-1);
1404 for (unsigned i = 1; i < NumOps-1; ++i)
1405 if (N->getOperand(i).getValueType() == MVT::Other)
1406 return N->getOperand(i);
1411 SDValue DAGCombiner::visitTokenFactor(SDNode *N) {
1412 // If N has two operands, where one has an input chain equal to the other,
1413 // the 'other' chain is redundant.
1414 if (N->getNumOperands() == 2) {
1415 if (getInputChainForNode(N->getOperand(0).getNode()) == N->getOperand(1))
1416 return N->getOperand(0);
1417 if (getInputChainForNode(N->getOperand(1).getNode()) == N->getOperand(0))
1418 return N->getOperand(1);
1421 SmallVector<SDNode *, 8> TFs; // List of token factors to visit.
1422 SmallVector<SDValue, 8> Ops; // Ops for replacing token factor.
1423 SmallPtrSet<SDNode*, 16> SeenOps;
1424 bool Changed = false; // If we should replace this token factor.
1426 // Start out with this token factor.
1429 // Iterate through token factors. The TFs grows when new token factors are
1431 for (unsigned i = 0; i < TFs.size(); ++i) {
1432 SDNode *TF = TFs[i];
1434 // Check each of the operands.
1435 for (unsigned i = 0, ie = TF->getNumOperands(); i != ie; ++i) {
1436 SDValue Op = TF->getOperand(i);
1438 switch (Op.getOpcode()) {
1439 case ISD::EntryToken:
1440 // Entry tokens don't need to be added to the list. They are
1445 case ISD::TokenFactor:
1446 if (Op.hasOneUse() &&
1447 std::find(TFs.begin(), TFs.end(), Op.getNode()) == TFs.end()) {
1448 // Queue up for processing.
1449 TFs.push_back(Op.getNode());
1450 // Clean up in case the token factor is removed.
1451 AddToWorklist(Op.getNode());
1458 // Only add if it isn't already in the list.
1459 if (SeenOps.insert(Op.getNode()))
1470 // If we've change things around then replace token factor.
1473 // The entry token is the only possible outcome.
1474 Result = DAG.getEntryNode();
1476 // New and improved token factor.
1477 Result = DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other, Ops);
1480 // Don't add users to work list.
1481 return CombineTo(N, Result, false);
1487 /// MERGE_VALUES can always be eliminated.
1488 SDValue DAGCombiner::visitMERGE_VALUES(SDNode *N) {
1489 WorklistRemover DeadNodes(*this);
1490 // Replacing results may cause a different MERGE_VALUES to suddenly
1491 // be CSE'd with N, and carry its uses with it. Iterate until no
1492 // uses remain, to ensure that the node can be safely deleted.
1493 // First add the users of this node to the work list so that they
1494 // can be tried again once they have new operands.
1495 AddUsersToWorklist(N);
1497 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1498 DAG.ReplaceAllUsesOfValueWith(SDValue(N, i), N->getOperand(i));
1499 } while (!N->use_empty());
1500 deleteAndRecombine(N);
1501 return SDValue(N, 0); // Return N so it doesn't get rechecked!
1505 SDValue combineShlAddConstant(SDLoc DL, SDValue N0, SDValue N1,
1506 SelectionDAG &DAG) {
1507 EVT VT = N0.getValueType();
1508 SDValue N00 = N0.getOperand(0);
1509 SDValue N01 = N0.getOperand(1);
1510 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N01);
1512 if (N01C && N00.getOpcode() == ISD::ADD && N00.getNode()->hasOneUse() &&
1513 isa<ConstantSDNode>(N00.getOperand(1))) {
1514 // fold (add (shl (add x, c1), c2), ) -> (add (add (shl x, c2), c1<<c2), )
1515 N0 = DAG.getNode(ISD::ADD, SDLoc(N0), VT,
1516 DAG.getNode(ISD::SHL, SDLoc(N00), VT,
1517 N00.getOperand(0), N01),
1518 DAG.getNode(ISD::SHL, SDLoc(N01), VT,
1519 N00.getOperand(1), N01));
1520 return DAG.getNode(ISD::ADD, DL, VT, N0, N1);
1526 SDValue DAGCombiner::visitADD(SDNode *N) {
1527 SDValue N0 = N->getOperand(0);
1528 SDValue N1 = N->getOperand(1);
1529 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1530 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1531 EVT VT = N0.getValueType();
1534 if (VT.isVector()) {
1535 SDValue FoldedVOp = SimplifyVBinOp(N);
1536 if (FoldedVOp.getNode()) return FoldedVOp;
1538 // fold (add x, 0) -> x, vector edition
1539 if (ISD::isBuildVectorAllZeros(N1.getNode()))
1541 if (ISD::isBuildVectorAllZeros(N0.getNode()))
1545 // fold (add x, undef) -> undef
1546 if (N0.getOpcode() == ISD::UNDEF)
1548 if (N1.getOpcode() == ISD::UNDEF)
1550 // fold (add c1, c2) -> c1+c2
1552 return DAG.FoldConstantArithmetic(ISD::ADD, VT, N0C, N1C);
1553 // canonicalize constant to RHS
1555 return DAG.getNode(ISD::ADD, SDLoc(N), VT, N1, N0);
1556 // fold (add x, 0) -> x
1557 if (N1C && N1C->isNullValue())
1559 // fold (add Sym, c) -> Sym+c
1560 if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N0))
1561 if (!LegalOperations && TLI.isOffsetFoldingLegal(GA) && N1C &&
1562 GA->getOpcode() == ISD::GlobalAddress)
1563 return DAG.getGlobalAddress(GA->getGlobal(), SDLoc(N1C), VT,
1565 (uint64_t)N1C->getSExtValue());
1566 // fold ((c1-A)+c2) -> (c1+c2)-A
1567 if (N1C && N0.getOpcode() == ISD::SUB)
1568 if (ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getOperand(0)))
1569 return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1570 DAG.getConstant(N1C->getAPIntValue()+
1571 N0C->getAPIntValue(), VT),
1574 SDValue RADD = ReassociateOps(ISD::ADD, SDLoc(N), N0, N1);
1577 // fold ((0-A) + B) -> B-A
1578 if (N0.getOpcode() == ISD::SUB && isa<ConstantSDNode>(N0.getOperand(0)) &&
1579 cast<ConstantSDNode>(N0.getOperand(0))->isNullValue())
1580 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1, N0.getOperand(1));
1581 // fold (A + (0-B)) -> A-B
1582 if (N1.getOpcode() == ISD::SUB && isa<ConstantSDNode>(N1.getOperand(0)) &&
1583 cast<ConstantSDNode>(N1.getOperand(0))->isNullValue())
1584 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, N1.getOperand(1));
1585 // fold (A+(B-A)) -> B
1586 if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(1))
1587 return N1.getOperand(0);
1588 // fold ((B-A)+A) -> B
1589 if (N0.getOpcode() == ISD::SUB && N1 == N0.getOperand(1))
1590 return N0.getOperand(0);
1591 // fold (A+(B-(A+C))) to (B-C)
1592 if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD &&
1593 N0 == N1.getOperand(1).getOperand(0))
1594 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1.getOperand(0),
1595 N1.getOperand(1).getOperand(1));
1596 // fold (A+(B-(C+A))) to (B-C)
1597 if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD &&
1598 N0 == N1.getOperand(1).getOperand(1))
1599 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1.getOperand(0),
1600 N1.getOperand(1).getOperand(0));
1601 // fold (A+((B-A)+or-C)) to (B+or-C)
1602 if ((N1.getOpcode() == ISD::SUB || N1.getOpcode() == ISD::ADD) &&
1603 N1.getOperand(0).getOpcode() == ISD::SUB &&
1604 N0 == N1.getOperand(0).getOperand(1))
1605 return DAG.getNode(N1.getOpcode(), SDLoc(N), VT,
1606 N1.getOperand(0).getOperand(0), N1.getOperand(1));
1608 // fold (A-B)+(C-D) to (A+C)-(B+D) when A or C is constant
1609 if (N0.getOpcode() == ISD::SUB && N1.getOpcode() == ISD::SUB) {
1610 SDValue N00 = N0.getOperand(0);
1611 SDValue N01 = N0.getOperand(1);
1612 SDValue N10 = N1.getOperand(0);
1613 SDValue N11 = N1.getOperand(1);
1615 if (isa<ConstantSDNode>(N00) || isa<ConstantSDNode>(N10))
1616 return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1617 DAG.getNode(ISD::ADD, SDLoc(N0), VT, N00, N10),
1618 DAG.getNode(ISD::ADD, SDLoc(N1), VT, N01, N11));
1621 if (!VT.isVector() && SimplifyDemandedBits(SDValue(N, 0)))
1622 return SDValue(N, 0);
1624 // fold (a+b) -> (a|b) iff a and b share no bits.
1625 if (VT.isInteger() && !VT.isVector()) {
1626 APInt LHSZero, LHSOne;
1627 APInt RHSZero, RHSOne;
1628 DAG.computeKnownBits(N0, LHSZero, LHSOne);
1630 if (LHSZero.getBoolValue()) {
1631 DAG.computeKnownBits(N1, RHSZero, RHSOne);
1633 // If all possibly-set bits on the LHS are clear on the RHS, return an OR.
1634 // If all possibly-set bits on the RHS are clear on the LHS, return an OR.
1635 if ((RHSZero & ~LHSZero) == ~LHSZero || (LHSZero & ~RHSZero) == ~RHSZero){
1636 if (!LegalOperations || TLI.isOperationLegal(ISD::OR, VT))
1637 return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N1);
1642 // fold (add (shl (add x, c1), c2), ) -> (add (add (shl x, c2), c1<<c2), )
1643 if (N0.getOpcode() == ISD::SHL && N0.getNode()->hasOneUse()) {
1644 SDValue Result = combineShlAddConstant(SDLoc(N), N0, N1, DAG);
1645 if (Result.getNode()) return Result;
1647 if (N1.getOpcode() == ISD::SHL && N1.getNode()->hasOneUse()) {
1648 SDValue Result = combineShlAddConstant(SDLoc(N), N1, N0, DAG);
1649 if (Result.getNode()) return Result;
1652 // fold (add x, shl(0 - y, n)) -> sub(x, shl(y, n))
1653 if (N1.getOpcode() == ISD::SHL &&
1654 N1.getOperand(0).getOpcode() == ISD::SUB)
1655 if (ConstantSDNode *C =
1656 dyn_cast<ConstantSDNode>(N1.getOperand(0).getOperand(0)))
1657 if (C->getAPIntValue() == 0)
1658 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N0,
1659 DAG.getNode(ISD::SHL, SDLoc(N), VT,
1660 N1.getOperand(0).getOperand(1),
1662 if (N0.getOpcode() == ISD::SHL &&
1663 N0.getOperand(0).getOpcode() == ISD::SUB)
1664 if (ConstantSDNode *C =
1665 dyn_cast<ConstantSDNode>(N0.getOperand(0).getOperand(0)))
1666 if (C->getAPIntValue() == 0)
1667 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1,
1668 DAG.getNode(ISD::SHL, SDLoc(N), VT,
1669 N0.getOperand(0).getOperand(1),
1672 if (N1.getOpcode() == ISD::AND) {
1673 SDValue AndOp0 = N1.getOperand(0);
1674 ConstantSDNode *AndOp1 = dyn_cast<ConstantSDNode>(N1->getOperand(1));
1675 unsigned NumSignBits = DAG.ComputeNumSignBits(AndOp0);
1676 unsigned DestBits = VT.getScalarType().getSizeInBits();
1678 // (add z, (and (sbbl x, x), 1)) -> (sub z, (sbbl x, x))
1679 // and similar xforms where the inner op is either ~0 or 0.
1680 if (NumSignBits == DestBits && AndOp1 && AndOp1->isOne()) {
1682 return DAG.getNode(ISD::SUB, DL, VT, N->getOperand(0), AndOp0);
1686 // add (sext i1), X -> sub X, (zext i1)
1687 if (N0.getOpcode() == ISD::SIGN_EXTEND &&
1688 N0.getOperand(0).getValueType() == MVT::i1 &&
1689 !TLI.isOperationLegal(ISD::SIGN_EXTEND, MVT::i1)) {
1691 SDValue ZExt = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0));
1692 return DAG.getNode(ISD::SUB, DL, VT, N1, ZExt);
1698 SDValue DAGCombiner::visitADDC(SDNode *N) {
1699 SDValue N0 = N->getOperand(0);
1700 SDValue N1 = N->getOperand(1);
1701 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1702 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1703 EVT VT = N0.getValueType();
1705 // If the flag result is dead, turn this into an ADD.
1706 if (!N->hasAnyUseOfValue(1))
1707 return CombineTo(N, DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, N1),
1708 DAG.getNode(ISD::CARRY_FALSE,
1709 SDLoc(N), MVT::Glue));
1711 // canonicalize constant to RHS.
1713 return DAG.getNode(ISD::ADDC, SDLoc(N), N->getVTList(), N1, N0);
1715 // fold (addc x, 0) -> x + no carry out
1716 if (N1C && N1C->isNullValue())
1717 return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE,
1718 SDLoc(N), MVT::Glue));
1720 // fold (addc a, b) -> (or a, b), CARRY_FALSE iff a and b share no bits.
1721 APInt LHSZero, LHSOne;
1722 APInt RHSZero, RHSOne;
1723 DAG.computeKnownBits(N0, LHSZero, LHSOne);
1725 if (LHSZero.getBoolValue()) {
1726 DAG.computeKnownBits(N1, RHSZero, RHSOne);
1728 // If all possibly-set bits on the LHS are clear on the RHS, return an OR.
1729 // If all possibly-set bits on the RHS are clear on the LHS, return an OR.
1730 if ((RHSZero & ~LHSZero) == ~LHSZero || (LHSZero & ~RHSZero) == ~RHSZero)
1731 return CombineTo(N, DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N1),
1732 DAG.getNode(ISD::CARRY_FALSE,
1733 SDLoc(N), MVT::Glue));
1739 SDValue DAGCombiner::visitADDE(SDNode *N) {
1740 SDValue N0 = N->getOperand(0);
1741 SDValue N1 = N->getOperand(1);
1742 SDValue CarryIn = N->getOperand(2);
1743 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1744 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1746 // canonicalize constant to RHS
1748 return DAG.getNode(ISD::ADDE, SDLoc(N), N->getVTList(),
1751 // fold (adde x, y, false) -> (addc x, y)
1752 if (CarryIn.getOpcode() == ISD::CARRY_FALSE)
1753 return DAG.getNode(ISD::ADDC, SDLoc(N), N->getVTList(), N0, N1);
1758 // Since it may not be valid to emit a fold to zero for vector initializers
1759 // check if we can before folding.
1760 static SDValue tryFoldToZero(SDLoc DL, const TargetLowering &TLI, EVT VT,
1762 bool LegalOperations, bool LegalTypes) {
1764 return DAG.getConstant(0, VT);
1765 if (!LegalOperations || TLI.isOperationLegal(ISD::BUILD_VECTOR, VT))
1766 return DAG.getConstant(0, VT);
1770 SDValue DAGCombiner::visitSUB(SDNode *N) {
1771 SDValue N0 = N->getOperand(0);
1772 SDValue N1 = N->getOperand(1);
1773 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getNode());
1774 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
1775 ConstantSDNode *N1C1 = N1.getOpcode() != ISD::ADD ? nullptr :
1776 dyn_cast<ConstantSDNode>(N1.getOperand(1).getNode());
1777 EVT VT = N0.getValueType();
1780 if (VT.isVector()) {
1781 SDValue FoldedVOp = SimplifyVBinOp(N);
1782 if (FoldedVOp.getNode()) return FoldedVOp;
1784 // fold (sub x, 0) -> x, vector edition
1785 if (ISD::isBuildVectorAllZeros(N1.getNode()))
1789 // fold (sub x, x) -> 0
1790 // FIXME: Refactor this and xor and other similar operations together.
1792 return tryFoldToZero(SDLoc(N), TLI, VT, DAG, LegalOperations, LegalTypes);
1793 // fold (sub c1, c2) -> c1-c2
1795 return DAG.FoldConstantArithmetic(ISD::SUB, VT, N0C, N1C);
1796 // fold (sub x, c) -> (add x, -c)
1798 return DAG.getNode(ISD::ADD, SDLoc(N), VT, N0,
1799 DAG.getConstant(-N1C->getAPIntValue(), VT));
1800 // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1)
1801 if (N0C && N0C->isAllOnesValue())
1802 return DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0);
1803 // fold A-(A-B) -> B
1804 if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(0))
1805 return N1.getOperand(1);
1806 // fold (A+B)-A -> B
1807 if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1)
1808 return N0.getOperand(1);
1809 // fold (A+B)-B -> A
1810 if (N0.getOpcode() == ISD::ADD && N0.getOperand(1) == N1)
1811 return N0.getOperand(0);
1812 // fold C2-(A+C1) -> (C2-C1)-A
1813 if (N1.getOpcode() == ISD::ADD && N0C && N1C1) {
1814 SDValue NewC = DAG.getConstant(N0C->getAPIntValue() - N1C1->getAPIntValue(),
1816 return DAG.getNode(ISD::SUB, SDLoc(N), VT, NewC,
1819 // fold ((A+(B+or-C))-B) -> A+or-C
1820 if (N0.getOpcode() == ISD::ADD &&
1821 (N0.getOperand(1).getOpcode() == ISD::SUB ||
1822 N0.getOperand(1).getOpcode() == ISD::ADD) &&
1823 N0.getOperand(1).getOperand(0) == N1)
1824 return DAG.getNode(N0.getOperand(1).getOpcode(), SDLoc(N), VT,
1825 N0.getOperand(0), N0.getOperand(1).getOperand(1));
1826 // fold ((A+(C+B))-B) -> A+C
1827 if (N0.getOpcode() == ISD::ADD &&
1828 N0.getOperand(1).getOpcode() == ISD::ADD &&
1829 N0.getOperand(1).getOperand(1) == N1)
1830 return DAG.getNode(ISD::ADD, SDLoc(N), VT,
1831 N0.getOperand(0), N0.getOperand(1).getOperand(0));
1832 // fold ((A-(B-C))-C) -> A-B
1833 if (N0.getOpcode() == ISD::SUB &&
1834 N0.getOperand(1).getOpcode() == ISD::SUB &&
1835 N0.getOperand(1).getOperand(1) == N1)
1836 return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1837 N0.getOperand(0), N0.getOperand(1).getOperand(0));
1839 // If either operand of a sub is undef, the result is undef
1840 if (N0.getOpcode() == ISD::UNDEF)
1842 if (N1.getOpcode() == ISD::UNDEF)
1845 // If the relocation model supports it, consider symbol offsets.
1846 if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N0))
1847 if (!LegalOperations && TLI.isOffsetFoldingLegal(GA)) {
1848 // fold (sub Sym, c) -> Sym-c
1849 if (N1C && GA->getOpcode() == ISD::GlobalAddress)
1850 return DAG.getGlobalAddress(GA->getGlobal(), SDLoc(N1C), VT,
1852 (uint64_t)N1C->getSExtValue());
1853 // fold (sub Sym+c1, Sym+c2) -> c1-c2
1854 if (GlobalAddressSDNode *GB = dyn_cast<GlobalAddressSDNode>(N1))
1855 if (GA->getGlobal() == GB->getGlobal())
1856 return DAG.getConstant((uint64_t)GA->getOffset() - GB->getOffset(),
1863 SDValue DAGCombiner::visitSUBC(SDNode *N) {
1864 SDValue N0 = N->getOperand(0);
1865 SDValue N1 = N->getOperand(1);
1866 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1867 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1868 EVT VT = N0.getValueType();
1870 // If the flag result is dead, turn this into an SUB.
1871 if (!N->hasAnyUseOfValue(1))
1872 return CombineTo(N, DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, N1),
1873 DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
1876 // fold (subc x, x) -> 0 + no borrow
1878 return CombineTo(N, DAG.getConstant(0, VT),
1879 DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
1882 // fold (subc x, 0) -> x + no borrow
1883 if (N1C && N1C->isNullValue())
1884 return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
1887 // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1) + no borrow
1888 if (N0C && N0C->isAllOnesValue())
1889 return CombineTo(N, DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0),
1890 DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
1896 SDValue DAGCombiner::visitSUBE(SDNode *N) {
1897 SDValue N0 = N->getOperand(0);
1898 SDValue N1 = N->getOperand(1);
1899 SDValue CarryIn = N->getOperand(2);
1901 // fold (sube x, y, false) -> (subc x, y)
1902 if (CarryIn.getOpcode() == ISD::CARRY_FALSE)
1903 return DAG.getNode(ISD::SUBC, SDLoc(N), N->getVTList(), N0, N1);
1908 SDValue DAGCombiner::visitMUL(SDNode *N) {
1909 SDValue N0 = N->getOperand(0);
1910 SDValue N1 = N->getOperand(1);
1911 EVT VT = N0.getValueType();
1913 // fold (mul x, undef) -> 0
1914 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
1915 return DAG.getConstant(0, VT);
1917 bool N0IsConst = false;
1918 bool N1IsConst = false;
1919 APInt ConstValue0, ConstValue1;
1921 if (VT.isVector()) {
1922 SDValue FoldedVOp = SimplifyVBinOp(N);
1923 if (FoldedVOp.getNode()) return FoldedVOp;
1925 N0IsConst = isConstantSplatVector(N0.getNode(), ConstValue0);
1926 N1IsConst = isConstantSplatVector(N1.getNode(), ConstValue1);
1928 N0IsConst = dyn_cast<ConstantSDNode>(N0) != nullptr;
1929 ConstValue0 = N0IsConst ? (dyn_cast<ConstantSDNode>(N0))->getAPIntValue()
1931 N1IsConst = dyn_cast<ConstantSDNode>(N1) != nullptr;
1932 ConstValue1 = N1IsConst ? (dyn_cast<ConstantSDNode>(N1))->getAPIntValue()
1936 // fold (mul c1, c2) -> c1*c2
1937 if (N0IsConst && N1IsConst)
1938 return DAG.FoldConstantArithmetic(ISD::MUL, VT, N0.getNode(), N1.getNode());
1940 // canonicalize constant to RHS
1941 if (N0IsConst && !N1IsConst)
1942 return DAG.getNode(ISD::MUL, SDLoc(N), VT, N1, N0);
1943 // fold (mul x, 0) -> 0
1944 if (N1IsConst && ConstValue1 == 0)
1946 // We require a splat of the entire scalar bit width for non-contiguous
1949 ConstValue1.getBitWidth() == VT.getScalarType().getSizeInBits();
1950 // fold (mul x, 1) -> x
1951 if (N1IsConst && ConstValue1 == 1 && IsFullSplat)
1953 // fold (mul x, -1) -> 0-x
1954 if (N1IsConst && ConstValue1.isAllOnesValue())
1955 return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1956 DAG.getConstant(0, VT), N0);
1957 // fold (mul x, (1 << c)) -> x << c
1958 if (N1IsConst && ConstValue1.isPowerOf2() && IsFullSplat)
1959 return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0,
1960 DAG.getConstant(ConstValue1.logBase2(),
1961 getShiftAmountTy(N0.getValueType())));
1962 // fold (mul x, -(1 << c)) -> -(x << c) or (-x) << c
1963 if (N1IsConst && (-ConstValue1).isPowerOf2() && IsFullSplat) {
1964 unsigned Log2Val = (-ConstValue1).logBase2();
1965 // FIXME: If the input is something that is easily negated (e.g. a
1966 // single-use add), we should put the negate there.
1967 return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1968 DAG.getConstant(0, VT),
1969 DAG.getNode(ISD::SHL, SDLoc(N), VT, N0,
1970 DAG.getConstant(Log2Val,
1971 getShiftAmountTy(N0.getValueType()))));
1975 // (mul (shl X, c1), c2) -> (mul X, c2 << c1)
1976 if (N1IsConst && N0.getOpcode() == ISD::SHL &&
1977 (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
1978 isa<ConstantSDNode>(N0.getOperand(1)))) {
1979 SDValue C3 = DAG.getNode(ISD::SHL, SDLoc(N), VT,
1980 N1, N0.getOperand(1));
1981 AddToWorklist(C3.getNode());
1982 return DAG.getNode(ISD::MUL, SDLoc(N), VT,
1983 N0.getOperand(0), C3);
1986 // Change (mul (shl X, C), Y) -> (shl (mul X, Y), C) when the shift has one
1989 SDValue Sh(nullptr,0), Y(nullptr,0);
1990 // Check for both (mul (shl X, C), Y) and (mul Y, (shl X, C)).
1991 if (N0.getOpcode() == ISD::SHL &&
1992 (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
1993 isa<ConstantSDNode>(N0.getOperand(1))) &&
1994 N0.getNode()->hasOneUse()) {
1996 } else if (N1.getOpcode() == ISD::SHL &&
1997 isa<ConstantSDNode>(N1.getOperand(1)) &&
1998 N1.getNode()->hasOneUse()) {
2003 SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT,
2004 Sh.getOperand(0), Y);
2005 return DAG.getNode(ISD::SHL, SDLoc(N), VT,
2006 Mul, Sh.getOperand(1));
2010 // fold (mul (add x, c1), c2) -> (add (mul x, c2), c1*c2)
2011 if (N1IsConst && N0.getOpcode() == ISD::ADD && N0.getNode()->hasOneUse() &&
2012 (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
2013 isa<ConstantSDNode>(N0.getOperand(1))))
2014 return DAG.getNode(ISD::ADD, SDLoc(N), VT,
2015 DAG.getNode(ISD::MUL, SDLoc(N0), VT,
2016 N0.getOperand(0), N1),
2017 DAG.getNode(ISD::MUL, SDLoc(N1), VT,
2018 N0.getOperand(1), N1));
2021 SDValue RMUL = ReassociateOps(ISD::MUL, SDLoc(N), N0, N1);
2028 SDValue DAGCombiner::visitSDIV(SDNode *N) {
2029 SDValue N0 = N->getOperand(0);
2030 SDValue N1 = N->getOperand(1);
2031 ConstantSDNode *N0C = isConstOrConstSplat(N0);
2032 ConstantSDNode *N1C = isConstOrConstSplat(N1);
2033 EVT VT = N->getValueType(0);
2036 if (VT.isVector()) {
2037 SDValue FoldedVOp = SimplifyVBinOp(N);
2038 if (FoldedVOp.getNode()) return FoldedVOp;
2041 // fold (sdiv c1, c2) -> c1/c2
2042 if (N0C && N1C && !N1C->isNullValue())
2043 return DAG.FoldConstantArithmetic(ISD::SDIV, VT, N0C, N1C);
2044 // fold (sdiv X, 1) -> X
2045 if (N1C && N1C->getAPIntValue() == 1LL)
2047 // fold (sdiv X, -1) -> 0-X
2048 if (N1C && N1C->isAllOnesValue())
2049 return DAG.getNode(ISD::SUB, SDLoc(N), VT,
2050 DAG.getConstant(0, VT), N0);
2051 // If we know the sign bits of both operands are zero, strength reduce to a
2052 // udiv instead. Handles (X&15) /s 4 -> X&15 >> 2
2053 if (!VT.isVector()) {
2054 if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
2055 return DAG.getNode(ISD::UDIV, SDLoc(N), N1.getValueType(),
2059 // fold (sdiv X, pow2) -> simple ops after legalize
2060 if (N1C && !N1C->isNullValue() && (N1C->getAPIntValue().isPowerOf2() ||
2061 (-N1C->getAPIntValue()).isPowerOf2())) {
2062 // If dividing by powers of two is cheap, then don't perform the following
2064 if (TLI.isPow2DivCheap())
2067 // Target-specific implementation of sdiv x, pow2.
2068 SDValue Res = BuildSDIVPow2(N);
2072 unsigned lg2 = N1C->getAPIntValue().countTrailingZeros();
2074 // Splat the sign bit into the register
2076 DAG.getNode(ISD::SRA, SDLoc(N), VT, N0,
2077 DAG.getConstant(VT.getScalarSizeInBits() - 1,
2078 getShiftAmountTy(N0.getValueType())));
2079 AddToWorklist(SGN.getNode());
2081 // Add (N0 < 0) ? abs2 - 1 : 0;
2083 DAG.getNode(ISD::SRL, SDLoc(N), VT, SGN,
2084 DAG.getConstant(VT.getScalarSizeInBits() - lg2,
2085 getShiftAmountTy(SGN.getValueType())));
2086 SDValue ADD = DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, SRL);
2087 AddToWorklist(SRL.getNode());
2088 AddToWorklist(ADD.getNode()); // Divide by pow2
2089 SDValue SRA = DAG.getNode(ISD::SRA, SDLoc(N), VT, ADD,
2090 DAG.getConstant(lg2, getShiftAmountTy(ADD.getValueType())));
2092 // If we're dividing by a positive value, we're done. Otherwise, we must
2093 // negate the result.
2094 if (N1C->getAPIntValue().isNonNegative())
2097 AddToWorklist(SRA.getNode());
2098 return DAG.getNode(ISD::SUB, SDLoc(N), VT, DAG.getConstant(0, VT), SRA);
2101 // if integer divide is expensive and we satisfy the requirements, emit an
2102 // alternate sequence.
2103 if (N1C && !TLI.isIntDivCheap()) {
2104 SDValue Op = BuildSDIV(N);
2105 if (Op.getNode()) return Op;
2109 if (N0.getOpcode() == ISD::UNDEF)
2110 return DAG.getConstant(0, VT);
2111 // X / undef -> undef
2112 if (N1.getOpcode() == ISD::UNDEF)
2118 SDValue DAGCombiner::visitUDIV(SDNode *N) {
2119 SDValue N0 = N->getOperand(0);
2120 SDValue N1 = N->getOperand(1);
2121 ConstantSDNode *N0C = isConstOrConstSplat(N0);
2122 ConstantSDNode *N1C = isConstOrConstSplat(N1);
2123 EVT VT = N->getValueType(0);
2126 if (VT.isVector()) {
2127 SDValue FoldedVOp = SimplifyVBinOp(N);
2128 if (FoldedVOp.getNode()) return FoldedVOp;
2131 // fold (udiv c1, c2) -> c1/c2
2132 if (N0C && N1C && !N1C->isNullValue())
2133 return DAG.FoldConstantArithmetic(ISD::UDIV, VT, N0C, N1C);
2134 // fold (udiv x, (1 << c)) -> x >>u c
2135 if (N1C && N1C->getAPIntValue().isPowerOf2())
2136 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0,
2137 DAG.getConstant(N1C->getAPIntValue().logBase2(),
2138 getShiftAmountTy(N0.getValueType())));
2139 // fold (udiv x, (shl c, y)) -> x >>u (log2(c)+y) iff c is power of 2
2140 if (N1.getOpcode() == ISD::SHL) {
2141 if (ConstantSDNode *SHC = dyn_cast<ConstantSDNode>(N1.getOperand(0))) {
2142 if (SHC->getAPIntValue().isPowerOf2()) {
2143 EVT ADDVT = N1.getOperand(1).getValueType();
2144 SDValue Add = DAG.getNode(ISD::ADD, SDLoc(N), ADDVT,
2146 DAG.getConstant(SHC->getAPIntValue()
2149 AddToWorklist(Add.getNode());
2150 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, Add);
2154 // fold (udiv x, c) -> alternate
2155 if (N1C && !TLI.isIntDivCheap()) {
2156 SDValue Op = BuildUDIV(N);
2157 if (Op.getNode()) return Op;
2161 if (N0.getOpcode() == ISD::UNDEF)
2162 return DAG.getConstant(0, VT);
2163 // X / undef -> undef
2164 if (N1.getOpcode() == ISD::UNDEF)
2170 SDValue DAGCombiner::visitSREM(SDNode *N) {
2171 SDValue N0 = N->getOperand(0);
2172 SDValue N1 = N->getOperand(1);
2173 ConstantSDNode *N0C = isConstOrConstSplat(N0);
2174 ConstantSDNode *N1C = isConstOrConstSplat(N1);
2175 EVT VT = N->getValueType(0);
2177 // fold (srem c1, c2) -> c1%c2
2178 if (N0C && N1C && !N1C->isNullValue())
2179 return DAG.FoldConstantArithmetic(ISD::SREM, VT, N0C, N1C);
2180 // If we know the sign bits of both operands are zero, strength reduce to a
2181 // urem instead. Handles (X & 0x0FFFFFFF) %s 16 -> X&15
2182 if (!VT.isVector()) {
2183 if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
2184 return DAG.getNode(ISD::UREM, SDLoc(N), VT, N0, N1);
2187 // If X/C can be simplified by the division-by-constant logic, lower
2188 // X%C to the equivalent of X-X/C*C.
2189 if (N1C && !N1C->isNullValue()) {
2190 SDValue Div = DAG.getNode(ISD::SDIV, SDLoc(N), VT, N0, N1);
2191 AddToWorklist(Div.getNode());
2192 SDValue OptimizedDiv = combine(Div.getNode());
2193 if (OptimizedDiv.getNode() && OptimizedDiv.getNode() != Div.getNode()) {
2194 SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT,
2196 SDValue Sub = DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, Mul);
2197 AddToWorklist(Mul.getNode());
2203 if (N0.getOpcode() == ISD::UNDEF)
2204 return DAG.getConstant(0, VT);
2205 // X % undef -> undef
2206 if (N1.getOpcode() == ISD::UNDEF)
2212 SDValue DAGCombiner::visitUREM(SDNode *N) {
2213 SDValue N0 = N->getOperand(0);
2214 SDValue N1 = N->getOperand(1);
2215 ConstantSDNode *N0C = isConstOrConstSplat(N0);
2216 ConstantSDNode *N1C = isConstOrConstSplat(N1);
2217 EVT VT = N->getValueType(0);
2219 // fold (urem c1, c2) -> c1%c2
2220 if (N0C && N1C && !N1C->isNullValue())
2221 return DAG.FoldConstantArithmetic(ISD::UREM, VT, N0C, N1C);
2222 // fold (urem x, pow2) -> (and x, pow2-1)
2223 if (N1C && !N1C->isNullValue() && N1C->getAPIntValue().isPowerOf2())
2224 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0,
2225 DAG.getConstant(N1C->getAPIntValue()-1,VT));
2226 // fold (urem x, (shl pow2, y)) -> (and x, (add (shl pow2, y), -1))
2227 if (N1.getOpcode() == ISD::SHL) {
2228 if (ConstantSDNode *SHC = dyn_cast<ConstantSDNode>(N1.getOperand(0))) {
2229 if (SHC->getAPIntValue().isPowerOf2()) {
2231 DAG.getNode(ISD::ADD, SDLoc(N), VT, N1,
2232 DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()),
2234 AddToWorklist(Add.getNode());
2235 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, Add);
2240 // If X/C can be simplified by the division-by-constant logic, lower
2241 // X%C to the equivalent of X-X/C*C.
2242 if (N1C && !N1C->isNullValue()) {
2243 SDValue Div = DAG.getNode(ISD::UDIV, SDLoc(N), VT, N0, N1);
2244 AddToWorklist(Div.getNode());
2245 SDValue OptimizedDiv = combine(Div.getNode());
2246 if (OptimizedDiv.getNode() && OptimizedDiv.getNode() != Div.getNode()) {
2247 SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT,
2249 SDValue Sub = DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, Mul);
2250 AddToWorklist(Mul.getNode());
2256 if (N0.getOpcode() == ISD::UNDEF)
2257 return DAG.getConstant(0, VT);
2258 // X % undef -> undef
2259 if (N1.getOpcode() == ISD::UNDEF)
2265 SDValue DAGCombiner::visitMULHS(SDNode *N) {
2266 SDValue N0 = N->getOperand(0);
2267 SDValue N1 = N->getOperand(1);
2268 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2269 EVT VT = N->getValueType(0);
2272 // fold (mulhs x, 0) -> 0
2273 if (N1C && N1C->isNullValue())
2275 // fold (mulhs x, 1) -> (sra x, size(x)-1)
2276 if (N1C && N1C->getAPIntValue() == 1)
2277 return DAG.getNode(ISD::SRA, SDLoc(N), N0.getValueType(), N0,
2278 DAG.getConstant(N0.getValueType().getSizeInBits() - 1,
2279 getShiftAmountTy(N0.getValueType())));
2280 // fold (mulhs x, undef) -> 0
2281 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2282 return DAG.getConstant(0, VT);
2284 // If the type twice as wide is legal, transform the mulhs to a wider multiply
2286 if (VT.isSimple() && !VT.isVector()) {
2287 MVT Simple = VT.getSimpleVT();
2288 unsigned SimpleSize = Simple.getSizeInBits();
2289 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2290 if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2291 N0 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N0);
2292 N1 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N1);
2293 N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1);
2294 N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1,
2295 DAG.getConstant(SimpleSize, getShiftAmountTy(N1.getValueType())));
2296 return DAG.getNode(ISD::TRUNCATE, DL, VT, N1);
2303 SDValue DAGCombiner::visitMULHU(SDNode *N) {
2304 SDValue N0 = N->getOperand(0);
2305 SDValue N1 = N->getOperand(1);
2306 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2307 EVT VT = N->getValueType(0);
2310 // fold (mulhu x, 0) -> 0
2311 if (N1C && N1C->isNullValue())
2313 // fold (mulhu x, 1) -> 0
2314 if (N1C && N1C->getAPIntValue() == 1)
2315 return DAG.getConstant(0, N0.getValueType());
2316 // fold (mulhu x, undef) -> 0
2317 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2318 return DAG.getConstant(0, VT);
2320 // If the type twice as wide is legal, transform the mulhu to a wider multiply
2322 if (VT.isSimple() && !VT.isVector()) {
2323 MVT Simple = VT.getSimpleVT();
2324 unsigned SimpleSize = Simple.getSizeInBits();
2325 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2326 if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2327 N0 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N0);
2328 N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N1);
2329 N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1);
2330 N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1,
2331 DAG.getConstant(SimpleSize, getShiftAmountTy(N1.getValueType())));
2332 return DAG.getNode(ISD::TRUNCATE, DL, VT, N1);
2339 /// SimplifyNodeWithTwoResults - Perform optimizations common to nodes that
2340 /// compute two values. LoOp and HiOp give the opcodes for the two computations
2341 /// that are being performed. Return true if a simplification was made.
2343 SDValue DAGCombiner::SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp,
2345 // If the high half is not needed, just compute the low half.
2346 bool HiExists = N->hasAnyUseOfValue(1);
2348 (!LegalOperations ||
2349 TLI.isOperationLegalOrCustom(LoOp, N->getValueType(0)))) {
2350 SDValue Res = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0),
2351 ArrayRef<SDUse>(N->op_begin(), N->op_end()));
2352 return CombineTo(N, Res, Res);
2355 // If the low half is not needed, just compute the high half.
2356 bool LoExists = N->hasAnyUseOfValue(0);
2358 (!LegalOperations ||
2359 TLI.isOperationLegal(HiOp, N->getValueType(1)))) {
2360 SDValue Res = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1),
2361 ArrayRef<SDUse>(N->op_begin(), N->op_end()));
2362 return CombineTo(N, Res, Res);
2365 // If both halves are used, return as it is.
2366 if (LoExists && HiExists)
2369 // If the two computed results can be simplified separately, separate them.
2371 SDValue Lo = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0),
2372 ArrayRef<SDUse>(N->op_begin(), N->op_end()));
2373 AddToWorklist(Lo.getNode());
2374 SDValue LoOpt = combine(Lo.getNode());
2375 if (LoOpt.getNode() && LoOpt.getNode() != Lo.getNode() &&
2376 (!LegalOperations ||
2377 TLI.isOperationLegal(LoOpt.getOpcode(), LoOpt.getValueType())))
2378 return CombineTo(N, LoOpt, LoOpt);
2382 SDValue Hi = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1),
2383 ArrayRef<SDUse>(N->op_begin(), N->op_end()));
2384 AddToWorklist(Hi.getNode());
2385 SDValue HiOpt = combine(Hi.getNode());
2386 if (HiOpt.getNode() && HiOpt != Hi &&
2387 (!LegalOperations ||
2388 TLI.isOperationLegal(HiOpt.getOpcode(), HiOpt.getValueType())))
2389 return CombineTo(N, HiOpt, HiOpt);
2395 SDValue DAGCombiner::visitSMUL_LOHI(SDNode *N) {
2396 SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHS);
2397 if (Res.getNode()) return Res;
2399 EVT VT = N->getValueType(0);
2402 // If the type twice as wide is legal, transform the mulhu to a wider multiply
2404 if (VT.isSimple() && !VT.isVector()) {
2405 MVT Simple = VT.getSimpleVT();
2406 unsigned SimpleSize = Simple.getSizeInBits();
2407 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2408 if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2409 SDValue Lo = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(0));
2410 SDValue Hi = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(1));
2411 Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi);
2412 // Compute the high part as N1.
2413 Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo,
2414 DAG.getConstant(SimpleSize, getShiftAmountTy(Lo.getValueType())));
2415 Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi);
2416 // Compute the low part as N0.
2417 Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo);
2418 return CombineTo(N, Lo, Hi);
2425 SDValue DAGCombiner::visitUMUL_LOHI(SDNode *N) {
2426 SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHU);
2427 if (Res.getNode()) return Res;
2429 EVT VT = N->getValueType(0);
2432 // If the type twice as wide is legal, transform the mulhu to a wider multiply
2434 if (VT.isSimple() && !VT.isVector()) {
2435 MVT Simple = VT.getSimpleVT();
2436 unsigned SimpleSize = Simple.getSizeInBits();
2437 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2438 if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2439 SDValue Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(0));
2440 SDValue Hi = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(1));
2441 Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi);
2442 // Compute the high part as N1.
2443 Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo,
2444 DAG.getConstant(SimpleSize, getShiftAmountTy(Lo.getValueType())));
2445 Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi);
2446 // Compute the low part as N0.
2447 Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo);
2448 return CombineTo(N, Lo, Hi);
2455 SDValue DAGCombiner::visitSMULO(SDNode *N) {
2456 // (smulo x, 2) -> (saddo x, x)
2457 if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1)))
2458 if (C2->getAPIntValue() == 2)
2459 return DAG.getNode(ISD::SADDO, SDLoc(N), N->getVTList(),
2460 N->getOperand(0), N->getOperand(0));
2465 SDValue DAGCombiner::visitUMULO(SDNode *N) {
2466 // (umulo x, 2) -> (uaddo x, x)
2467 if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1)))
2468 if (C2->getAPIntValue() == 2)
2469 return DAG.getNode(ISD::UADDO, SDLoc(N), N->getVTList(),
2470 N->getOperand(0), N->getOperand(0));
2475 SDValue DAGCombiner::visitSDIVREM(SDNode *N) {
2476 SDValue Res = SimplifyNodeWithTwoResults(N, ISD::SDIV, ISD::SREM);
2477 if (Res.getNode()) return Res;
2482 SDValue DAGCombiner::visitUDIVREM(SDNode *N) {
2483 SDValue Res = SimplifyNodeWithTwoResults(N, ISD::UDIV, ISD::UREM);
2484 if (Res.getNode()) return Res;
2489 /// SimplifyBinOpWithSameOpcodeHands - If this is a binary operator with
2490 /// two operands of the same opcode, try to simplify it.
2491 SDValue DAGCombiner::SimplifyBinOpWithSameOpcodeHands(SDNode *N) {
2492 SDValue N0 = N->getOperand(0), N1 = N->getOperand(1);
2493 EVT VT = N0.getValueType();
2494 assert(N0.getOpcode() == N1.getOpcode() && "Bad input!");
2496 // Bail early if none of these transforms apply.
2497 if (N0.getNode()->getNumOperands() == 0) return SDValue();
2499 // For each of OP in AND/OR/XOR:
2500 // fold (OP (zext x), (zext y)) -> (zext (OP x, y))
2501 // fold (OP (sext x), (sext y)) -> (sext (OP x, y))
2502 // fold (OP (aext x), (aext y)) -> (aext (OP x, y))
2503 // fold (OP (trunc x), (trunc y)) -> (trunc (OP x, y)) (if trunc isn't free)
2505 // do not sink logical op inside of a vector extend, since it may combine
2507 EVT Op0VT = N0.getOperand(0).getValueType();
2508 if ((N0.getOpcode() == ISD::ZERO_EXTEND ||
2509 N0.getOpcode() == ISD::SIGN_EXTEND ||
2510 // Avoid infinite looping with PromoteIntBinOp.
2511 (N0.getOpcode() == ISD::ANY_EXTEND &&
2512 (!LegalTypes || TLI.isTypeDesirableForOp(N->getOpcode(), Op0VT))) ||
2513 (N0.getOpcode() == ISD::TRUNCATE &&
2514 (!TLI.isZExtFree(VT, Op0VT) ||
2515 !TLI.isTruncateFree(Op0VT, VT)) &&
2516 TLI.isTypeLegal(Op0VT))) &&
2518 Op0VT == N1.getOperand(0).getValueType() &&
2519 (!LegalOperations || TLI.isOperationLegal(N->getOpcode(), Op0VT))) {
2520 SDValue ORNode = DAG.getNode(N->getOpcode(), SDLoc(N0),
2521 N0.getOperand(0).getValueType(),
2522 N0.getOperand(0), N1.getOperand(0));
2523 AddToWorklist(ORNode.getNode());
2524 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, ORNode);
2527 // For each of OP in SHL/SRL/SRA/AND...
2528 // fold (and (OP x, z), (OP y, z)) -> (OP (and x, y), z)
2529 // fold (or (OP x, z), (OP y, z)) -> (OP (or x, y), z)
2530 // fold (xor (OP x, z), (OP y, z)) -> (OP (xor x, y), z)
2531 if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL ||
2532 N0.getOpcode() == ISD::SRA || N0.getOpcode() == ISD::AND) &&
2533 N0.getOperand(1) == N1.getOperand(1)) {
2534 SDValue ORNode = DAG.getNode(N->getOpcode(), SDLoc(N0),
2535 N0.getOperand(0).getValueType(),
2536 N0.getOperand(0), N1.getOperand(0));
2537 AddToWorklist(ORNode.getNode());
2538 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
2539 ORNode, N0.getOperand(1));
2542 // Simplify xor/and/or (bitcast(A), bitcast(B)) -> bitcast(op (A,B))
2543 // Only perform this optimization after type legalization and before
2544 // LegalizeVectorOprs. LegalizeVectorOprs promotes vector operations by
2545 // adding bitcasts. For example (xor v4i32) is promoted to (v2i64), and
2546 // we don't want to undo this promotion.
2547 // We also handle SCALAR_TO_VECTOR because xor/or/and operations are cheaper
2549 if ((N0.getOpcode() == ISD::BITCAST ||
2550 N0.getOpcode() == ISD::SCALAR_TO_VECTOR) &&
2551 Level == AfterLegalizeTypes) {
2552 SDValue In0 = N0.getOperand(0);
2553 SDValue In1 = N1.getOperand(0);
2554 EVT In0Ty = In0.getValueType();
2555 EVT In1Ty = In1.getValueType();
2557 // If both incoming values are integers, and the original types are the
2559 if (In0Ty.isInteger() && In1Ty.isInteger() && In0Ty == In1Ty) {
2560 SDValue Op = DAG.getNode(N->getOpcode(), DL, In0Ty, In0, In1);
2561 SDValue BC = DAG.getNode(N0.getOpcode(), DL, VT, Op);
2562 AddToWorklist(Op.getNode());
2567 // Xor/and/or are indifferent to the swizzle operation (shuffle of one value).
2568 // Simplify xor/and/or (shuff(A), shuff(B)) -> shuff(op (A,B))
2569 // If both shuffles use the same mask, and both shuffle within a single
2570 // vector, then it is worthwhile to move the swizzle after the operation.
2571 // The type-legalizer generates this pattern when loading illegal
2572 // vector types from memory. In many cases this allows additional shuffle
2574 // There are other cases where moving the shuffle after the xor/and/or
2575 // is profitable even if shuffles don't perform a swizzle.
2576 // If both shuffles use the same mask, and both shuffles have the same first
2577 // or second operand, then it might still be profitable to move the shuffle
2578 // after the xor/and/or operation.
2579 if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG) {
2580 ShuffleVectorSDNode *SVN0 = cast<ShuffleVectorSDNode>(N0);
2581 ShuffleVectorSDNode *SVN1 = cast<ShuffleVectorSDNode>(N1);
2583 assert(N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType() &&
2584 "Inputs to shuffles are not the same type");
2586 // Check that both shuffles use the same mask. The masks are known to be of
2587 // the same length because the result vector type is the same.
2588 // Check also that shuffles have only one use to avoid introducing extra
2590 if (SVN0->hasOneUse() && SVN1->hasOneUse() &&
2591 SVN0->getMask().equals(SVN1->getMask())) {
2592 SDValue ShOp = N0->getOperand(1);
2594 // Don't try to fold this node if it requires introducing a
2595 // build vector of all zeros that might be illegal at this stage.
2596 if (N->getOpcode() == ISD::XOR && ShOp.getOpcode() != ISD::UNDEF) {
2598 ShOp = DAG.getConstant(0, VT);
2603 // (AND (shuf (A, C), shuf (B, C)) -> shuf (AND (A, B), C)
2604 // (OR (shuf (A, C), shuf (B, C)) -> shuf (OR (A, B), C)
2605 // (XOR (shuf (A, C), shuf (B, C)) -> shuf (XOR (A, B), V_0)
2606 if (N0.getOperand(1) == N1.getOperand(1) && ShOp.getNode()) {
2607 SDValue NewNode = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
2608 N0->getOperand(0), N1->getOperand(0));
2609 AddToWorklist(NewNode.getNode());
2610 return DAG.getVectorShuffle(VT, SDLoc(N), NewNode, ShOp,
2611 &SVN0->getMask()[0]);
2614 // Don't try to fold this node if it requires introducing a
2615 // build vector of all zeros that might be illegal at this stage.
2616 ShOp = N0->getOperand(0);
2617 if (N->getOpcode() == ISD::XOR && ShOp.getOpcode() != ISD::UNDEF) {
2619 ShOp = DAG.getConstant(0, VT);
2624 // (AND (shuf (C, A), shuf (C, B)) -> shuf (C, AND (A, B))
2625 // (OR (shuf (C, A), shuf (C, B)) -> shuf (C, OR (A, B))
2626 // (XOR (shuf (C, A), shuf (C, B)) -> shuf (V_0, XOR (A, B))
2627 if (N0->getOperand(0) == N1->getOperand(0) && ShOp.getNode()) {
2628 SDValue NewNode = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
2629 N0->getOperand(1), N1->getOperand(1));
2630 AddToWorklist(NewNode.getNode());
2631 return DAG.getVectorShuffle(VT, SDLoc(N), ShOp, NewNode,
2632 &SVN0->getMask()[0]);
2640 SDValue DAGCombiner::visitAND(SDNode *N) {
2641 SDValue N0 = N->getOperand(0);
2642 SDValue N1 = N->getOperand(1);
2643 SDValue LL, LR, RL, RR, CC0, CC1;
2644 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
2645 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2646 EVT VT = N1.getValueType();
2647 unsigned BitWidth = VT.getScalarType().getSizeInBits();
2650 if (VT.isVector()) {
2651 SDValue FoldedVOp = SimplifyVBinOp(N);
2652 if (FoldedVOp.getNode()) return FoldedVOp;
2654 // fold (and x, 0) -> 0, vector edition
2655 if (ISD::isBuildVectorAllZeros(N0.getNode()))
2657 if (ISD::isBuildVectorAllZeros(N1.getNode()))
2660 // fold (and x, -1) -> x, vector edition
2661 if (ISD::isBuildVectorAllOnes(N0.getNode()))
2663 if (ISD::isBuildVectorAllOnes(N1.getNode()))
2667 // fold (and x, undef) -> 0
2668 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2669 return DAG.getConstant(0, VT);
2670 // fold (and c1, c2) -> c1&c2
2672 return DAG.FoldConstantArithmetic(ISD::AND, VT, N0C, N1C);
2673 // canonicalize constant to RHS
2675 return DAG.getNode(ISD::AND, SDLoc(N), VT, N1, N0);
2676 // fold (and x, -1) -> x
2677 if (N1C && N1C->isAllOnesValue())
2679 // if (and x, c) is known to be zero, return 0
2680 if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0),
2681 APInt::getAllOnesValue(BitWidth)))
2682 return DAG.getConstant(0, VT);
2684 SDValue RAND = ReassociateOps(ISD::AND, SDLoc(N), N0, N1);
2687 // fold (and (or x, C), D) -> D if (C & D) == D
2688 if (N1C && N0.getOpcode() == ISD::OR)
2689 if (ConstantSDNode *ORI = dyn_cast<ConstantSDNode>(N0.getOperand(1)))
2690 if ((ORI->getAPIntValue() & N1C->getAPIntValue()) == N1C->getAPIntValue())
2692 // fold (and (any_ext V), c) -> (zero_ext V) if 'and' only clears top bits.
2693 if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
2694 SDValue N0Op0 = N0.getOperand(0);
2695 APInt Mask = ~N1C->getAPIntValue();
2696 Mask = Mask.trunc(N0Op0.getValueSizeInBits());
2697 if (DAG.MaskedValueIsZero(N0Op0, Mask)) {
2698 SDValue Zext = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N),
2699 N0.getValueType(), N0Op0);
2701 // Replace uses of the AND with uses of the Zero extend node.
2704 // We actually want to replace all uses of the any_extend with the
2705 // zero_extend, to avoid duplicating things. This will later cause this
2706 // AND to be folded.
2707 CombineTo(N0.getNode(), Zext);
2708 return SDValue(N, 0); // Return N so it doesn't get rechecked!
2711 // similarly fold (and (X (load ([non_ext|any_ext|zero_ext] V))), c) ->
2712 // (X (load ([non_ext|zero_ext] V))) if 'and' only clears top bits which must
2713 // already be zero by virtue of the width of the base type of the load.
2715 // the 'X' node here can either be nothing or an extract_vector_elt to catch
2717 if ((N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
2718 N0.getOperand(0).getOpcode() == ISD::LOAD) ||
2719 N0.getOpcode() == ISD::LOAD) {
2720 LoadSDNode *Load = cast<LoadSDNode>( (N0.getOpcode() == ISD::LOAD) ?
2721 N0 : N0.getOperand(0) );
2723 // Get the constant (if applicable) the zero'th operand is being ANDed with.
2724 // This can be a pure constant or a vector splat, in which case we treat the
2725 // vector as a scalar and use the splat value.
2726 APInt Constant = APInt::getNullValue(1);
2727 if (const ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
2728 Constant = C->getAPIntValue();
2729 } else if (BuildVectorSDNode *Vector = dyn_cast<BuildVectorSDNode>(N1)) {
2730 APInt SplatValue, SplatUndef;
2731 unsigned SplatBitSize;
2733 bool IsSplat = Vector->isConstantSplat(SplatValue, SplatUndef,
2734 SplatBitSize, HasAnyUndefs);
2736 // Undef bits can contribute to a possible optimisation if set, so
2738 SplatValue |= SplatUndef;
2740 // The splat value may be something like "0x00FFFFFF", which means 0 for
2741 // the first vector value and FF for the rest, repeating. We need a mask
2742 // that will apply equally to all members of the vector, so AND all the
2743 // lanes of the constant together.
2744 EVT VT = Vector->getValueType(0);
2745 unsigned BitWidth = VT.getVectorElementType().getSizeInBits();
2747 // If the splat value has been compressed to a bitlength lower
2748 // than the size of the vector lane, we need to re-expand it to
2750 if (BitWidth > SplatBitSize)
2751 for (SplatValue = SplatValue.zextOrTrunc(BitWidth);
2752 SplatBitSize < BitWidth;
2753 SplatBitSize = SplatBitSize * 2)
2754 SplatValue |= SplatValue.shl(SplatBitSize);
2756 Constant = APInt::getAllOnesValue(BitWidth);
2757 for (unsigned i = 0, n = SplatBitSize/BitWidth; i < n; ++i)
2758 Constant &= SplatValue.lshr(i*BitWidth).zextOrTrunc(BitWidth);
2762 // If we want to change an EXTLOAD to a ZEXTLOAD, ensure a ZEXTLOAD is
2763 // actually legal and isn't going to get expanded, else this is a false
2765 bool CanZextLoadProfitably = TLI.isLoadExtLegal(ISD::ZEXTLOAD,
2766 Load->getMemoryVT());
2768 // Resize the constant to the same size as the original memory access before
2769 // extension. If it is still the AllOnesValue then this AND is completely
2772 Constant.zextOrTrunc(Load->getMemoryVT().getScalarType().getSizeInBits());
2775 switch (Load->getExtensionType()) {
2776 default: B = false; break;
2777 case ISD::EXTLOAD: B = CanZextLoadProfitably; break;
2779 case ISD::NON_EXTLOAD: B = true; break;
2782 if (B && Constant.isAllOnesValue()) {
2783 // If the load type was an EXTLOAD, convert to ZEXTLOAD in order to
2784 // preserve semantics once we get rid of the AND.
2785 SDValue NewLoad(Load, 0);
2786 if (Load->getExtensionType() == ISD::EXTLOAD) {
2787 NewLoad = DAG.getLoad(Load->getAddressingMode(), ISD::ZEXTLOAD,
2788 Load->getValueType(0), SDLoc(Load),
2789 Load->getChain(), Load->getBasePtr(),
2790 Load->getOffset(), Load->getMemoryVT(),
2791 Load->getMemOperand());
2792 // Replace uses of the EXTLOAD with the new ZEXTLOAD.
2793 if (Load->getNumValues() == 3) {
2794 // PRE/POST_INC loads have 3 values.
2795 SDValue To[] = { NewLoad.getValue(0), NewLoad.getValue(1),
2796 NewLoad.getValue(2) };
2797 CombineTo(Load, To, 3, true);
2799 CombineTo(Load, NewLoad.getValue(0), NewLoad.getValue(1));
2803 // Fold the AND away, taking care not to fold to the old load node if we
2805 CombineTo(N, (N0.getNode() == Load) ? NewLoad : N0);
2807 return SDValue(N, 0); // Return N so it doesn't get rechecked!
2810 // fold (and (setcc x), (setcc y)) -> (setcc (and x, y))
2811 if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){
2812 ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get();
2813 ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get();
2815 if (LR == RR && isa<ConstantSDNode>(LR) && Op0 == Op1 &&
2816 LL.getValueType().isInteger()) {
2817 // fold (and (seteq X, 0), (seteq Y, 0)) -> (seteq (or X, Y), 0)
2818 if (cast<ConstantSDNode>(LR)->isNullValue() && Op1 == ISD::SETEQ) {
2819 SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(N0),
2820 LR.getValueType(), LL, RL);
2821 AddToWorklist(ORNode.getNode());
2822 return DAG.getSetCC(SDLoc(N), VT, ORNode, LR, Op1);
2824 // fold (and (seteq X, -1), (seteq Y, -1)) -> (seteq (and X, Y), -1)
2825 if (cast<ConstantSDNode>(LR)->isAllOnesValue() && Op1 == ISD::SETEQ) {
2826 SDValue ANDNode = DAG.getNode(ISD::AND, SDLoc(N0),
2827 LR.getValueType(), LL, RL);
2828 AddToWorklist(ANDNode.getNode());
2829 return DAG.getSetCC(SDLoc(N), VT, ANDNode, LR, Op1);
2831 // fold (and (setgt X, -1), (setgt Y, -1)) -> (setgt (or X, Y), -1)
2832 if (cast<ConstantSDNode>(LR)->isAllOnesValue() && Op1 == ISD::SETGT) {
2833 SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(N0),
2834 LR.getValueType(), LL, RL);
2835 AddToWorklist(ORNode.getNode());
2836 return DAG.getSetCC(SDLoc(N), VT, ORNode, LR, Op1);
2839 // Simplify (and (setne X, 0), (setne X, -1)) -> (setuge (add X, 1), 2)
2840 if (LL == RL && isa<ConstantSDNode>(LR) && isa<ConstantSDNode>(RR) &&
2841 Op0 == Op1 && LL.getValueType().isInteger() &&
2842 Op0 == ISD::SETNE && ((cast<ConstantSDNode>(LR)->isNullValue() &&
2843 cast<ConstantSDNode>(RR)->isAllOnesValue()) ||
2844 (cast<ConstantSDNode>(LR)->isAllOnesValue() &&
2845 cast<ConstantSDNode>(RR)->isNullValue()))) {
2846 SDValue ADDNode = DAG.getNode(ISD::ADD, SDLoc(N0), LL.getValueType(),
2847 LL, DAG.getConstant(1, LL.getValueType()));
2848 AddToWorklist(ADDNode.getNode());
2849 return DAG.getSetCC(SDLoc(N), VT, ADDNode,
2850 DAG.getConstant(2, LL.getValueType()), ISD::SETUGE);
2852 // canonicalize equivalent to ll == rl
2853 if (LL == RR && LR == RL) {
2854 Op1 = ISD::getSetCCSwappedOperands(Op1);
2857 if (LL == RL && LR == RR) {
2858 bool isInteger = LL.getValueType().isInteger();
2859 ISD::CondCode Result = ISD::getSetCCAndOperation(Op0, Op1, isInteger);
2860 if (Result != ISD::SETCC_INVALID &&
2861 (!LegalOperations ||
2862 (TLI.isCondCodeLegal(Result, LL.getSimpleValueType()) &&
2863 TLI.isOperationLegal(ISD::SETCC,
2864 getSetCCResultType(N0.getSimpleValueType())))))
2865 return DAG.getSetCC(SDLoc(N), N0.getValueType(),
2870 // Simplify: (and (op x...), (op y...)) -> (op (and x, y))
2871 if (N0.getOpcode() == N1.getOpcode()) {
2872 SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
2873 if (Tmp.getNode()) return Tmp;
2876 // fold (and (sign_extend_inreg x, i16 to i32), 1) -> (and x, 1)
2877 // fold (and (sra)) -> (and (srl)) when possible.
2878 if (!VT.isVector() &&
2879 SimplifyDemandedBits(SDValue(N, 0)))
2880 return SDValue(N, 0);
2882 // fold (zext_inreg (extload x)) -> (zextload x)
2883 if (ISD::isEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode())) {
2884 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
2885 EVT MemVT = LN0->getMemoryVT();
2886 // If we zero all the possible extended bits, then we can turn this into
2887 // a zextload if we are running before legalize or the operation is legal.
2888 unsigned BitWidth = N1.getValueType().getScalarType().getSizeInBits();
2889 if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth,
2890 BitWidth - MemVT.getScalarType().getSizeInBits())) &&
2891 ((!LegalOperations && !LN0->isVolatile()) ||
2892 TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT))) {
2893 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N0), VT,
2894 LN0->getChain(), LN0->getBasePtr(),
2895 MemVT, LN0->getMemOperand());
2897 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
2898 return SDValue(N, 0); // Return N so it doesn't get rechecked!
2901 // fold (zext_inreg (sextload x)) -> (zextload x) iff load has one use
2902 if (ISD::isSEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
2904 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
2905 EVT MemVT = LN0->getMemoryVT();
2906 // If we zero all the possible extended bits, then we can turn this into
2907 // a zextload if we are running before legalize or the operation is legal.
2908 unsigned BitWidth = N1.getValueType().getScalarType().getSizeInBits();
2909 if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth,
2910 BitWidth - MemVT.getScalarType().getSizeInBits())) &&
2911 ((!LegalOperations && !LN0->isVolatile()) ||
2912 TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT))) {
2913 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N0), VT,
2914 LN0->getChain(), LN0->getBasePtr(),
2915 MemVT, LN0->getMemOperand());
2917 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
2918 return SDValue(N, 0); // Return N so it doesn't get rechecked!
2922 // fold (and (load x), 255) -> (zextload x, i8)
2923 // fold (and (extload x, i16), 255) -> (zextload x, i8)
2924 // fold (and (any_ext (extload x, i16)), 255) -> (zextload x, i8)
2925 if (N1C && (N0.getOpcode() == ISD::LOAD ||
2926 (N0.getOpcode() == ISD::ANY_EXTEND &&
2927 N0.getOperand(0).getOpcode() == ISD::LOAD))) {
2928 bool HasAnyExt = N0.getOpcode() == ISD::ANY_EXTEND;
2929 LoadSDNode *LN0 = HasAnyExt
2930 ? cast<LoadSDNode>(N0.getOperand(0))
2931 : cast<LoadSDNode>(N0);
2932 if (LN0->getExtensionType() != ISD::SEXTLOAD &&
2933 LN0->isUnindexed() && N0.hasOneUse() && SDValue(LN0, 0).hasOneUse()) {
2934 uint32_t ActiveBits = N1C->getAPIntValue().getActiveBits();
2935 if (ActiveBits > 0 && APIntOps::isMask(ActiveBits, N1C->getAPIntValue())){
2936 EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), ActiveBits);
2937 EVT LoadedVT = LN0->getMemoryVT();
2939 if (ExtVT == LoadedVT &&
2940 (!LegalOperations || TLI.isLoadExtLegal(ISD::ZEXTLOAD, ExtVT))) {
2941 EVT LoadResultTy = HasAnyExt ? LN0->getValueType(0) : VT;
2944 DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), LoadResultTy,
2945 LN0->getChain(), LN0->getBasePtr(), ExtVT,
2946 LN0->getMemOperand());
2948 CombineTo(LN0, NewLoad, NewLoad.getValue(1));
2949 return SDValue(N, 0); // Return N so it doesn't get rechecked!
2952 // Do not change the width of a volatile load.
2953 // Do not generate loads of non-round integer types since these can
2954 // be expensive (and would be wrong if the type is not byte sized).
2955 if (!LN0->isVolatile() && LoadedVT.bitsGT(ExtVT) && ExtVT.isRound() &&
2956 (!LegalOperations || TLI.isLoadExtLegal(ISD::ZEXTLOAD, ExtVT))) {
2957 EVT PtrType = LN0->getOperand(1).getValueType();
2959 unsigned Alignment = LN0->getAlignment();
2960 SDValue NewPtr = LN0->getBasePtr();
2962 // For big endian targets, we need to add an offset to the pointer
2963 // to load the correct bytes. For little endian systems, we merely
2964 // need to read fewer bytes from the same pointer.
2965 if (TLI.isBigEndian()) {
2966 unsigned LVTStoreBytes = LoadedVT.getStoreSize();
2967 unsigned EVTStoreBytes = ExtVT.getStoreSize();
2968 unsigned PtrOff = LVTStoreBytes - EVTStoreBytes;
2969 NewPtr = DAG.getNode(ISD::ADD, SDLoc(LN0), PtrType,
2970 NewPtr, DAG.getConstant(PtrOff, PtrType));
2971 Alignment = MinAlign(Alignment, PtrOff);
2974 AddToWorklist(NewPtr.getNode());
2976 EVT LoadResultTy = HasAnyExt ? LN0->getValueType(0) : VT;
2978 DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), LoadResultTy,
2979 LN0->getChain(), NewPtr,
2980 LN0->getPointerInfo(),
2981 ExtVT, LN0->isVolatile(), LN0->isNonTemporal(),
2982 LN0->isInvariant(), Alignment, LN0->getAAInfo());
2984 CombineTo(LN0, Load, Load.getValue(1));
2985 return SDValue(N, 0); // Return N so it doesn't get rechecked!
2991 if (N0.getOpcode() == ISD::ADD && N1.getOpcode() == ISD::SRL &&
2992 VT.getSizeInBits() <= 64) {
2993 if (ConstantSDNode *ADDI = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
2994 APInt ADDC = ADDI->getAPIntValue();
2995 if (!TLI.isLegalAddImmediate(ADDC.getSExtValue())) {
2996 // Look for (and (add x, c1), (lshr y, c2)). If C1 wasn't a legal
2997 // immediate for an add, but it is legal if its top c2 bits are set,
2998 // transform the ADD so the immediate doesn't need to be materialized
3000 if (ConstantSDNode *SRLI = dyn_cast<ConstantSDNode>(N1.getOperand(1))) {
3001 APInt Mask = APInt::getHighBitsSet(VT.getSizeInBits(),
3002 SRLI->getZExtValue());
3003 if (DAG.MaskedValueIsZero(N0.getOperand(1), Mask)) {
3005 if (TLI.isLegalAddImmediate(ADDC.getSExtValue())) {
3007 DAG.getNode(ISD::ADD, SDLoc(N0), VT,
3008 N0.getOperand(0), DAG.getConstant(ADDC, VT));
3009 CombineTo(N0.getNode(), NewAdd);
3010 return SDValue(N, 0); // Return N so it doesn't get rechecked!
3018 // fold (and (or (srl N, 8), (shl N, 8)), 0xffff) -> (srl (bswap N), const)
3019 if (N1C && N1C->getAPIntValue() == 0xffff && N0.getOpcode() == ISD::OR) {
3020 SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0),
3021 N0.getOperand(1), false);
3022 if (BSwap.getNode())
3029 /// MatchBSwapHWord - Match (a >> 8) | (a << 8) as (bswap a) >> 16
3031 SDValue DAGCombiner::MatchBSwapHWordLow(SDNode *N, SDValue N0, SDValue N1,
3032 bool DemandHighBits) {
3033 if (!LegalOperations)
3036 EVT VT = N->getValueType(0);
3037 if (VT != MVT::i64 && VT != MVT::i32 && VT != MVT::i16)
3039 if (!TLI.isOperationLegal(ISD::BSWAP, VT))
3042 // Recognize (and (shl a, 8), 0xff), (and (srl a, 8), 0xff00)
3043 bool LookPassAnd0 = false;
3044 bool LookPassAnd1 = false;
3045 if (N0.getOpcode() == ISD::AND && N0.getOperand(0).getOpcode() == ISD::SRL)
3047 if (N1.getOpcode() == ISD::AND && N1.getOperand(0).getOpcode() == ISD::SHL)
3049 if (N0.getOpcode() == ISD::AND) {
3050 if (!N0.getNode()->hasOneUse())
3052 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3053 if (!N01C || N01C->getZExtValue() != 0xFF00)
3055 N0 = N0.getOperand(0);
3056 LookPassAnd0 = true;
3059 if (N1.getOpcode() == ISD::AND) {
3060 if (!N1.getNode()->hasOneUse())
3062 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
3063 if (!N11C || N11C->getZExtValue() != 0xFF)
3065 N1 = N1.getOperand(0);
3066 LookPassAnd1 = true;
3069 if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
3071 if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
3073 if (!N0.getNode()->hasOneUse() ||
3074 !N1.getNode()->hasOneUse())
3077 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3078 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
3081 if (N01C->getZExtValue() != 8 || N11C->getZExtValue() != 8)
3084 // Look for (shl (and a, 0xff), 8), (srl (and a, 0xff00), 8)
3085 SDValue N00 = N0->getOperand(0);
3086 if (!LookPassAnd0 && N00.getOpcode() == ISD::AND) {
3087 if (!N00.getNode()->hasOneUse())
3089 ConstantSDNode *N001C = dyn_cast<ConstantSDNode>(N00.getOperand(1));
3090 if (!N001C || N001C->getZExtValue() != 0xFF)
3092 N00 = N00.getOperand(0);
3093 LookPassAnd0 = true;
3096 SDValue N10 = N1->getOperand(0);
3097 if (!LookPassAnd1 && N10.getOpcode() == ISD::AND) {
3098 if (!N10.getNode()->hasOneUse())
3100 ConstantSDNode *N101C = dyn_cast<ConstantSDNode>(N10.getOperand(1));
3101 if (!N101C || N101C->getZExtValue() != 0xFF00)
3103 N10 = N10.getOperand(0);
3104 LookPassAnd1 = true;
3110 // Make sure everything beyond the low halfword gets set to zero since the SRL
3111 // 16 will clear the top bits.
3112 unsigned OpSizeInBits = VT.getSizeInBits();
3113 if (DemandHighBits && OpSizeInBits > 16) {
3114 // If the left-shift isn't masked out then the only way this is a bswap is
3115 // if all bits beyond the low 8 are 0. In that case the entire pattern
3116 // reduces to a left shift anyway: leave it for other parts of the combiner.
3120 // However, if the right shift isn't masked out then it might be because
3121 // it's not needed. See if we can spot that too.
3122 if (!LookPassAnd1 &&
3123 !DAG.MaskedValueIsZero(
3124 N10, APInt::getHighBitsSet(OpSizeInBits, OpSizeInBits - 16)))
3128 SDValue Res = DAG.getNode(ISD::BSWAP, SDLoc(N), VT, N00);
3129 if (OpSizeInBits > 16)
3130 Res = DAG.getNode(ISD::SRL, SDLoc(N), VT, Res,
3131 DAG.getConstant(OpSizeInBits-16, getShiftAmountTy(VT)));
3135 /// isBSwapHWordElement - Return true if the specified node is an element
3136 /// that makes up a 32-bit packed halfword byteswap. i.e.
3137 /// ((x&0xff)<<8)|((x&0xff00)>>8)|((x&0x00ff0000)<<8)|((x&0xff000000)>>8)
3138 static bool isBSwapHWordElement(SDValue N, SmallVectorImpl<SDNode *> &Parts) {
3139 if (!N.getNode()->hasOneUse())
3142 unsigned Opc = N.getOpcode();
3143 if (Opc != ISD::AND && Opc != ISD::SHL && Opc != ISD::SRL)
3146 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3151 switch (N1C->getZExtValue()) {
3154 case 0xFF: Num = 0; break;
3155 case 0xFF00: Num = 1; break;
3156 case 0xFF0000: Num = 2; break;
3157 case 0xFF000000: Num = 3; break;
3160 // Look for (x & 0xff) << 8 as well as ((x << 8) & 0xff00).
3161 SDValue N0 = N.getOperand(0);
3162 if (Opc == ISD::AND) {
3163 if (Num == 0 || Num == 2) {
3165 // (x >> 8) & 0xff0000
3166 if (N0.getOpcode() != ISD::SRL)
3168 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3169 if (!C || C->getZExtValue() != 8)
3172 // (x << 8) & 0xff00
3173 // (x << 8) & 0xff000000
3174 if (N0.getOpcode() != ISD::SHL)
3176 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3177 if (!C || C->getZExtValue() != 8)
3180 } else if (Opc == ISD::SHL) {
3182 // (x & 0xff0000) << 8
3183 if (Num != 0 && Num != 2)
3185 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3186 if (!C || C->getZExtValue() != 8)
3188 } else { // Opc == ISD::SRL
3189 // (x & 0xff00) >> 8
3190 // (x & 0xff000000) >> 8
3191 if (Num != 1 && Num != 3)
3193 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3194 if (!C || C->getZExtValue() != 8)
3201 Parts[Num] = N0.getOperand(0).getNode();
3205 /// MatchBSwapHWord - Match a 32-bit packed halfword bswap. That is
3206 /// ((x&0xff)<<8)|((x&0xff00)>>8)|((x&0x00ff0000)<<8)|((x&0xff000000)>>8)
3207 /// => (rotl (bswap x), 16)
3208 SDValue DAGCombiner::MatchBSwapHWord(SDNode *N, SDValue N0, SDValue N1) {
3209 if (!LegalOperations)
3212 EVT VT = N->getValueType(0);
3215 if (!TLI.isOperationLegal(ISD::BSWAP, VT))
3218 SmallVector<SDNode*,4> Parts(4, (SDNode*)nullptr);
3220 // (or (or (and), (and)), (or (and), (and)))
3221 // (or (or (or (and), (and)), (and)), (and))
3222 if (N0.getOpcode() != ISD::OR)
3224 SDValue N00 = N0.getOperand(0);
3225 SDValue N01 = N0.getOperand(1);
3227 if (N1.getOpcode() == ISD::OR &&
3228 N00.getNumOperands() == 2 && N01.getNumOperands() == 2) {
3229 // (or (or (and), (and)), (or (and), (and)))
3230 SDValue N000 = N00.getOperand(0);
3231 if (!isBSwapHWordElement(N000, Parts))
3234 SDValue N001 = N00.getOperand(1);
3235 if (!isBSwapHWordElement(N001, Parts))
3237 SDValue N010 = N01.getOperand(0);
3238 if (!isBSwapHWordElement(N010, Parts))
3240 SDValue N011 = N01.getOperand(1);
3241 if (!isBSwapHWordElement(N011, Parts))
3244 // (or (or (or (and), (and)), (and)), (and))
3245 if (!isBSwapHWordElement(N1, Parts))
3247 if (!isBSwapHWordElement(N01, Parts))
3249 if (N00.getOpcode() != ISD::OR)
3251 SDValue N000 = N00.getOperand(0);
3252 if (!isBSwapHWordElement(N000, Parts))
3254 SDValue N001 = N00.getOperand(1);
3255 if (!isBSwapHWordElement(N001, Parts))
3259 // Make sure the parts are all coming from the same node.
3260 if (Parts[0] != Parts[1] || Parts[0] != Parts[2] || Parts[0] != Parts[3])
3263 SDValue BSwap = DAG.getNode(ISD::BSWAP, SDLoc(N), VT,
3264 SDValue(Parts[0],0));
3266 // Result of the bswap should be rotated by 16. If it's not legal, then
3267 // do (x << 16) | (x >> 16).
3268 SDValue ShAmt = DAG.getConstant(16, getShiftAmountTy(VT));
3269 if (TLI.isOperationLegalOrCustom(ISD::ROTL, VT))
3270 return DAG.getNode(ISD::ROTL, SDLoc(N), VT, BSwap, ShAmt);
3271 if (TLI.isOperationLegalOrCustom(ISD::ROTR, VT))
3272 return DAG.getNode(ISD::ROTR, SDLoc(N), VT, BSwap, ShAmt);
3273 return DAG.getNode(ISD::OR, SDLoc(N), VT,
3274 DAG.getNode(ISD::SHL, SDLoc(N), VT, BSwap, ShAmt),
3275 DAG.getNode(ISD::SRL, SDLoc(N), VT, BSwap, ShAmt));
3278 SDValue DAGCombiner::visitOR(SDNode *N) {
3279 SDValue N0 = N->getOperand(0);
3280 SDValue N1 = N->getOperand(1);
3281 SDValue LL, LR, RL, RR, CC0, CC1;
3282 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
3283 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
3284 EVT VT = N1.getValueType();
3287 if (VT.isVector()) {
3288 SDValue FoldedVOp = SimplifyVBinOp(N);
3289 if (FoldedVOp.getNode()) return FoldedVOp;
3291 // fold (or x, 0) -> x, vector edition
3292 if (ISD::isBuildVectorAllZeros(N0.getNode()))
3294 if (ISD::isBuildVectorAllZeros(N1.getNode()))
3297 // fold (or x, -1) -> -1, vector edition
3298 if (ISD::isBuildVectorAllOnes(N0.getNode()))
3300 if (ISD::isBuildVectorAllOnes(N1.getNode()))
3303 // fold (or (shuf A, V_0, MA), (shuf B, V_0, MB)) -> (shuf A, B, Mask1)
3304 // fold (or (shuf A, V_0, MA), (shuf B, V_0, MB)) -> (shuf B, A, Mask2)
3305 // Do this only if the resulting shuffle is legal.
3306 if (isa<ShuffleVectorSDNode>(N0) &&
3307 isa<ShuffleVectorSDNode>(N1) &&
3308 // Avoid folding a node with illegal type.
3309 TLI.isTypeLegal(VT) &&
3310 N0->getOperand(1) == N1->getOperand(1) &&
3311 ISD::isBuildVectorAllZeros(N0.getOperand(1).getNode())) {
3312 bool CanFold = true;
3313 unsigned NumElts = VT.getVectorNumElements();
3314 const ShuffleVectorSDNode *SV0 = cast<ShuffleVectorSDNode>(N0);
3315 const ShuffleVectorSDNode *SV1 = cast<ShuffleVectorSDNode>(N1);
3316 // We construct two shuffle masks:
3317 // - Mask1 is a shuffle mask for a shuffle with N0 as the first operand
3318 // and N1 as the second operand.
3319 // - Mask2 is a shuffle mask for a shuffle with N1 as the first operand
3320 // and N0 as the second operand.
3321 // We do this because OR is commutable and therefore there might be
3322 // two ways to fold this node into a shuffle.
3323 SmallVector<int,4> Mask1;
3324 SmallVector<int,4> Mask2;
3326 for (unsigned i = 0; i != NumElts && CanFold; ++i) {
3327 int M0 = SV0->getMaskElt(i);
3328 int M1 = SV1->getMaskElt(i);
3330 // Both shuffle indexes are undef. Propagate Undef.
3331 if (M0 < 0 && M1 < 0) {
3332 Mask1.push_back(M0);
3333 Mask2.push_back(M0);
3337 if (M0 < 0 || M1 < 0 ||
3338 (M0 < (int)NumElts && M1 < (int)NumElts) ||
3339 (M0 >= (int)NumElts && M1 >= (int)NumElts)) {
3344 Mask1.push_back(M0 < (int)NumElts ? M0 : M1 + NumElts);
3345 Mask2.push_back(M1 < (int)NumElts ? M1 : M0 + NumElts);
3349 // Fold this sequence only if the resulting shuffle is 'legal'.
3350 if (TLI.isShuffleMaskLegal(Mask1, VT))
3351 return DAG.getVectorShuffle(VT, SDLoc(N), N0->getOperand(0),
3352 N1->getOperand(0), &Mask1[0]);
3353 if (TLI.isShuffleMaskLegal(Mask2, VT))
3354 return DAG.getVectorShuffle(VT, SDLoc(N), N1->getOperand(0),
3355 N0->getOperand(0), &Mask2[0]);
3360 // fold (or x, undef) -> -1
3361 if (!LegalOperations &&
3362 (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)) {
3363 EVT EltVT = VT.isVector() ? VT.getVectorElementType() : VT;
3364 return DAG.getConstant(APInt::getAllOnesValue(EltVT.getSizeInBits()), VT);
3366 // fold (or c1, c2) -> c1|c2
3368 return DAG.FoldConstantArithmetic(ISD::OR, VT, N0C, N1C);
3369 // canonicalize constant to RHS
3371 return DAG.getNode(ISD::OR, SDLoc(N), VT, N1, N0);
3372 // fold (or x, 0) -> x
3373 if (N1C && N1C->isNullValue())
3375 // fold (or x, -1) -> -1
3376 if (N1C && N1C->isAllOnesValue())
3378 // fold (or x, c) -> c iff (x & ~c) == 0
3379 if (N1C && DAG.MaskedValueIsZero(N0, ~N1C->getAPIntValue()))
3382 // Recognize halfword bswaps as (bswap + rotl 16) or (bswap + shl 16)
3383 SDValue BSwap = MatchBSwapHWord(N, N0, N1);
3384 if (BSwap.getNode())
3386 BSwap = MatchBSwapHWordLow(N, N0, N1);
3387 if (BSwap.getNode())
3391 SDValue ROR = ReassociateOps(ISD::OR, SDLoc(N), N0, N1);
3394 // Canonicalize (or (and X, c1), c2) -> (and (or X, c2), c1|c2)
3395 // iff (c1 & c2) == 0.
3396 if (N1C && N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() &&
3397 isa<ConstantSDNode>(N0.getOperand(1))) {
3398 ConstantSDNode *C1 = cast<ConstantSDNode>(N0.getOperand(1));
3399 if ((C1->getAPIntValue() & N1C->getAPIntValue()) != 0) {
3400 SDValue COR = DAG.FoldConstantArithmetic(ISD::OR, VT, N1C, C1);
3403 return DAG.getNode(ISD::AND, SDLoc(N), VT,
3404 DAG.getNode(ISD::OR, SDLoc(N0), VT,
3405 N0.getOperand(0), N1), COR);
3408 // fold (or (setcc x), (setcc y)) -> (setcc (or x, y))
3409 if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){
3410 ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get();
3411 ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get();
3413 if (LR == RR && isa<ConstantSDNode>(LR) && Op0 == Op1 &&
3414 LL.getValueType().isInteger()) {
3415 // fold (or (setne X, 0), (setne Y, 0)) -> (setne (or X, Y), 0)
3416 // fold (or (setlt X, 0), (setlt Y, 0)) -> (setne (or X, Y), 0)
3417 if (cast<ConstantSDNode>(LR)->isNullValue() &&
3418 (Op1 == ISD::SETNE || Op1 == ISD::SETLT)) {
3419 SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(LR),
3420 LR.getValueType(), LL, RL);
3421 AddToWorklist(ORNode.getNode());
3422 return DAG.getSetCC(SDLoc(N), VT, ORNode, LR, Op1);
3424 // fold (or (setne X, -1), (setne Y, -1)) -> (setne (and X, Y), -1)
3425 // fold (or (setgt X, -1), (setgt Y -1)) -> (setgt (and X, Y), -1)
3426 if (cast<ConstantSDNode>(LR)->isAllOnesValue() &&
3427 (Op1 == ISD::SETNE || Op1 == ISD::SETGT)) {
3428 SDValue ANDNode = DAG.getNode(ISD::AND, SDLoc(LR),
3429 LR.getValueType(), LL, RL);
3430 AddToWorklist(ANDNode.getNode());
3431 return DAG.getSetCC(SDLoc(N), VT, ANDNode, LR, Op1);
3434 // canonicalize equivalent to ll == rl
3435 if (LL == RR && LR == RL) {
3436 Op1 = ISD::getSetCCSwappedOperands(Op1);
3439 if (LL == RL && LR == RR) {
3440 bool isInteger = LL.getValueType().isInteger();
3441 ISD::CondCode Result = ISD::getSetCCOrOperation(Op0, Op1, isInteger);
3442 if (Result != ISD::SETCC_INVALID &&
3443 (!LegalOperations ||
3444 (TLI.isCondCodeLegal(Result, LL.getSimpleValueType()) &&
3445 TLI.isOperationLegal(ISD::SETCC,
3446 getSetCCResultType(N0.getValueType())))))
3447 return DAG.getSetCC(SDLoc(N), N0.getValueType(),
3452 // Simplify: (or (op x...), (op y...)) -> (op (or x, y))
3453 if (N0.getOpcode() == N1.getOpcode()) {
3454 SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
3455 if (Tmp.getNode()) return Tmp;
3458 // (or (and X, C1), (and Y, C2)) -> (and (or X, Y), C3) if possible.
3459 if (N0.getOpcode() == ISD::AND &&
3460 N1.getOpcode() == ISD::AND &&
3461 N0.getOperand(1).getOpcode() == ISD::Constant &&
3462 N1.getOperand(1).getOpcode() == ISD::Constant &&
3463 // Don't increase # computations.
3464 (N0.getNode()->hasOneUse() || N1.getNode()->hasOneUse())) {
3465 // We can only do this xform if we know that bits from X that are set in C2
3466 // but not in C1 are already zero. Likewise for Y.
3467 const APInt &LHSMask =
3468 cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
3469 const APInt &RHSMask =
3470 cast<ConstantSDNode>(N1.getOperand(1))->getAPIntValue();
3472 if (DAG.MaskedValueIsZero(N0.getOperand(0), RHSMask&~LHSMask) &&
3473 DAG.MaskedValueIsZero(N1.getOperand(0), LHSMask&~RHSMask)) {
3474 SDValue X = DAG.getNode(ISD::OR, SDLoc(N0), VT,
3475 N0.getOperand(0), N1.getOperand(0));
3476 return DAG.getNode(ISD::AND, SDLoc(N), VT, X,
3477 DAG.getConstant(LHSMask | RHSMask, VT));
3481 // See if this is some rotate idiom.
3482 if (SDNode *Rot = MatchRotate(N0, N1, SDLoc(N)))
3483 return SDValue(Rot, 0);
3485 // Simplify the operands using demanded-bits information.
3486 if (!VT.isVector() &&
3487 SimplifyDemandedBits(SDValue(N, 0)))
3488 return SDValue(N, 0);
3493 /// MatchRotateHalf - Match "(X shl/srl V1) & V2" where V2 may not be present.
3494 static bool MatchRotateHalf(SDValue Op, SDValue &Shift, SDValue &Mask) {
3495 if (Op.getOpcode() == ISD::AND) {
3496 if (isa<ConstantSDNode>(Op.getOperand(1))) {
3497 Mask = Op.getOperand(1);
3498 Op = Op.getOperand(0);
3504 if (Op.getOpcode() == ISD::SRL || Op.getOpcode() == ISD::SHL) {
3512 // Return true if we can prove that, whenever Neg and Pos are both in the
3513 // range [0, OpSize), Neg == (Pos == 0 ? 0 : OpSize - Pos). This means that
3514 // for two opposing shifts shift1 and shift2 and a value X with OpBits bits:
3516 // (or (shift1 X, Neg), (shift2 X, Pos))
3518 // reduces to a rotate in direction shift2 by Pos or (equivalently) a rotate
3519 // in direction shift1 by Neg. The range [0, OpSize) means that we only need
3520 // to consider shift amounts with defined behavior.
3521 static bool matchRotateSub(SDValue Pos, SDValue Neg, unsigned OpSize) {
3522 // If OpSize is a power of 2 then:
3524 // (a) (Pos == 0 ? 0 : OpSize - Pos) == (OpSize - Pos) & (OpSize - 1)
3525 // (b) Neg == Neg & (OpSize - 1) whenever Neg is in [0, OpSize).
3527 // So if OpSize is a power of 2 and Neg is (and Neg', OpSize-1), we check
3528 // for the stronger condition:
3530 // Neg & (OpSize - 1) == (OpSize - Pos) & (OpSize - 1) [A]
3532 // for all Neg and Pos. Since Neg & (OpSize - 1) == Neg' & (OpSize - 1)
3533 // we can just replace Neg with Neg' for the rest of the function.
3535 // In other cases we check for the even stronger condition:
3537 // Neg == OpSize - Pos [B]
3539 // for all Neg and Pos. Note that the (or ...) then invokes undefined
3540 // behavior if Pos == 0 (and consequently Neg == OpSize).
3542 // We could actually use [A] whenever OpSize is a power of 2, but the
3543 // only extra cases that it would match are those uninteresting ones
3544 // where Neg and Pos are never in range at the same time. E.g. for
3545 // OpSize == 32, using [A] would allow a Neg of the form (sub 64, Pos)
3546 // as well as (sub 32, Pos), but:
3548 // (or (shift1 X, (sub 64, Pos)), (shift2 X, Pos))
3550 // always invokes undefined behavior for 32-bit X.
3552 // Below, Mask == OpSize - 1 when using [A] and is all-ones otherwise.
3553 unsigned MaskLoBits = 0;
3554 if (Neg.getOpcode() == ISD::AND &&
3555 isPowerOf2_64(OpSize) &&
3556 Neg.getOperand(1).getOpcode() == ISD::Constant &&
3557 cast<ConstantSDNode>(Neg.getOperand(1))->getAPIntValue() == OpSize - 1) {
3558 Neg = Neg.getOperand(0);
3559 MaskLoBits = Log2_64(OpSize);
3562 // Check whether Neg has the form (sub NegC, NegOp1) for some NegC and NegOp1.
3563 if (Neg.getOpcode() != ISD::SUB)
3565 ConstantSDNode *NegC = dyn_cast<ConstantSDNode>(Neg.getOperand(0));
3568 SDValue NegOp1 = Neg.getOperand(1);
3570 // On the RHS of [A], if Pos is Pos' & (OpSize - 1), just replace Pos with
3571 // Pos'. The truncation is redundant for the purpose of the equality.
3573 Pos.getOpcode() == ISD::AND &&
3574 Pos.getOperand(1).getOpcode() == ISD::Constant &&
3575 cast<ConstantSDNode>(Pos.getOperand(1))->getAPIntValue() == OpSize - 1)
3576 Pos = Pos.getOperand(0);
3578 // The condition we need is now:
3580 // (NegC - NegOp1) & Mask == (OpSize - Pos) & Mask
3582 // If NegOp1 == Pos then we need:
3584 // OpSize & Mask == NegC & Mask
3586 // (because "x & Mask" is a truncation and distributes through subtraction).
3589 Width = NegC->getAPIntValue();
3590 // Check for cases where Pos has the form (add NegOp1, PosC) for some PosC.
3591 // Then the condition we want to prove becomes:
3593 // (NegC - NegOp1) & Mask == (OpSize - (NegOp1 + PosC)) & Mask
3595 // which, again because "x & Mask" is a truncation, becomes:
3597 // NegC & Mask == (OpSize - PosC) & Mask
3598 // OpSize & Mask == (NegC + PosC) & Mask
3599 else if (Pos.getOpcode() == ISD::ADD &&
3600 Pos.getOperand(0) == NegOp1 &&
3601 Pos.getOperand(1).getOpcode() == ISD::Constant)
3602 Width = (cast<ConstantSDNode>(Pos.getOperand(1))->getAPIntValue() +
3603 NegC->getAPIntValue());
3607 // Now we just need to check that OpSize & Mask == Width & Mask.
3609 // Opsize & Mask is 0 since Mask is Opsize - 1.
3610 return Width.getLoBits(MaskLoBits) == 0;
3611 return Width == OpSize;
3614 // A subroutine of MatchRotate used once we have found an OR of two opposite
3615 // shifts of Shifted. If Neg == <operand size> - Pos then the OR reduces
3616 // to both (PosOpcode Shifted, Pos) and (NegOpcode Shifted, Neg), with the
3617 // former being preferred if supported. InnerPos and InnerNeg are Pos and
3618 // Neg with outer conversions stripped away.
3619 SDNode *DAGCombiner::MatchRotatePosNeg(SDValue Shifted, SDValue Pos,
3620 SDValue Neg, SDValue InnerPos,
3621 SDValue InnerNeg, unsigned PosOpcode,
3622 unsigned NegOpcode, SDLoc DL) {
3623 // fold (or (shl x, (*ext y)),
3624 // (srl x, (*ext (sub 32, y)))) ->
3625 // (rotl x, y) or (rotr x, (sub 32, y))
3627 // fold (or (shl x, (*ext (sub 32, y))),
3628 // (srl x, (*ext y))) ->
3629 // (rotr x, y) or (rotl x, (sub 32, y))
3630 EVT VT = Shifted.getValueType();
3631 if (matchRotateSub(InnerPos, InnerNeg, VT.getSizeInBits())) {
3632 bool HasPos = TLI.isOperationLegalOrCustom(PosOpcode, VT);
3633 return DAG.getNode(HasPos ? PosOpcode : NegOpcode, DL, VT, Shifted,
3634 HasPos ? Pos : Neg).getNode();
3640 // MatchRotate - Handle an 'or' of two operands. If this is one of the many
3641 // idioms for rotate, and if the target supports rotation instructions, generate
3643 SDNode *DAGCombiner::MatchRotate(SDValue LHS, SDValue RHS, SDLoc DL) {
3644 // Must be a legal type. Expanded 'n promoted things won't work with rotates.
3645 EVT VT = LHS.getValueType();
3646 if (!TLI.isTypeLegal(VT)) return nullptr;
3648 // The target must have at least one rotate flavor.
3649 bool HasROTL = TLI.isOperationLegalOrCustom(ISD::ROTL, VT);
3650 bool HasROTR = TLI.isOperationLegalOrCustom(ISD::ROTR, VT);
3651 if (!HasROTL && !HasROTR) return nullptr;
3653 // Match "(X shl/srl V1) & V2" where V2 may not be present.
3654 SDValue LHSShift; // The shift.
3655 SDValue LHSMask; // AND value if any.
3656 if (!MatchRotateHalf(LHS, LHSShift, LHSMask))
3657 return nullptr; // Not part of a rotate.
3659 SDValue RHSShift; // The shift.
3660 SDValue RHSMask; // AND value if any.
3661 if (!MatchRotateHalf(RHS, RHSShift, RHSMask))
3662 return nullptr; // Not part of a rotate.
3664 if (LHSShift.getOperand(0) != RHSShift.getOperand(0))
3665 return nullptr; // Not shifting the same value.
3667 if (LHSShift.getOpcode() == RHSShift.getOpcode())
3668 return nullptr; // Shifts must disagree.
3670 // Canonicalize shl to left side in a shl/srl pair.
3671 if (RHSShift.getOpcode() == ISD::SHL) {
3672 std::swap(LHS, RHS);
3673 std::swap(LHSShift, RHSShift);
3674 std::swap(LHSMask , RHSMask );
3677 unsigned OpSizeInBits = VT.getSizeInBits();
3678 SDValue LHSShiftArg = LHSShift.getOperand(0);
3679 SDValue LHSShiftAmt = LHSShift.getOperand(1);
3680 SDValue RHSShiftArg = RHSShift.getOperand(0);
3681 SDValue RHSShiftAmt = RHSShift.getOperand(1);
3683 // fold (or (shl x, C1), (srl x, C2)) -> (rotl x, C1)
3684 // fold (or (shl x, C1), (srl x, C2)) -> (rotr x, C2)
3685 if (LHSShiftAmt.getOpcode() == ISD::Constant &&
3686 RHSShiftAmt.getOpcode() == ISD::Constant) {
3687 uint64_t LShVal = cast<ConstantSDNode>(LHSShiftAmt)->getZExtValue();
3688 uint64_t RShVal = cast<ConstantSDNode>(RHSShiftAmt)->getZExtValue();
3689 if ((LShVal + RShVal) != OpSizeInBits)
3692 SDValue Rot = DAG.getNode(HasROTL ? ISD::ROTL : ISD::ROTR, DL, VT,
3693 LHSShiftArg, HasROTL ? LHSShiftAmt : RHSShiftAmt);
3695 // If there is an AND of either shifted operand, apply it to the result.
3696 if (LHSMask.getNode() || RHSMask.getNode()) {
3697 APInt Mask = APInt::getAllOnesValue(OpSizeInBits);
3699 if (LHSMask.getNode()) {
3700 APInt RHSBits = APInt::getLowBitsSet(OpSizeInBits, LShVal);
3701 Mask &= cast<ConstantSDNode>(LHSMask)->getAPIntValue() | RHSBits;
3703 if (RHSMask.getNode()) {
3704 APInt LHSBits = APInt::getHighBitsSet(OpSizeInBits, RShVal);
3705 Mask &= cast<ConstantSDNode>(RHSMask)->getAPIntValue() | LHSBits;
3708 Rot = DAG.getNode(ISD::AND, DL, VT, Rot, DAG.getConstant(Mask, VT));
3711 return Rot.getNode();
3714 // If there is a mask here, and we have a variable shift, we can't be sure
3715 // that we're masking out the right stuff.
3716 if (LHSMask.getNode() || RHSMask.getNode())
3719 // If the shift amount is sign/zext/any-extended just peel it off.
3720 SDValue LExtOp0 = LHSShiftAmt;
3721 SDValue RExtOp0 = RHSShiftAmt;
3722 if ((LHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND ||
3723 LHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND ||
3724 LHSShiftAmt.getOpcode() == ISD::ANY_EXTEND ||
3725 LHSShiftAmt.getOpcode() == ISD::TRUNCATE) &&
3726 (RHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND ||
3727 RHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND ||
3728 RHSShiftAmt.getOpcode() == ISD::ANY_EXTEND ||
3729 RHSShiftAmt.getOpcode() == ISD::TRUNCATE)) {
3730 LExtOp0 = LHSShiftAmt.getOperand(0);
3731 RExtOp0 = RHSShiftAmt.getOperand(0);
3734 SDNode *TryL = MatchRotatePosNeg(LHSShiftArg, LHSShiftAmt, RHSShiftAmt,
3735 LExtOp0, RExtOp0, ISD::ROTL, ISD::ROTR, DL);
3739 SDNode *TryR = MatchRotatePosNeg(RHSShiftArg, RHSShiftAmt, LHSShiftAmt,
3740 RExtOp0, LExtOp0, ISD::ROTR, ISD::ROTL, DL);
3747 SDValue DAGCombiner::visitXOR(SDNode *N) {
3748 SDValue N0 = N->getOperand(0);
3749 SDValue N1 = N->getOperand(1);
3750 SDValue LHS, RHS, CC;
3751 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
3752 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
3753 EVT VT = N0.getValueType();
3756 if (VT.isVector()) {
3757 SDValue FoldedVOp = SimplifyVBinOp(N);
3758 if (FoldedVOp.getNode()) return FoldedVOp;
3760 // fold (xor x, 0) -> x, vector edition
3761 if (ISD::isBuildVectorAllZeros(N0.getNode()))
3763 if (ISD::isBuildVectorAllZeros(N1.getNode()))
3767 // fold (xor undef, undef) -> 0. This is a common idiom (misuse).
3768 if (N0.getOpcode() == ISD::UNDEF && N1.getOpcode() == ISD::UNDEF)
3769 return DAG.getConstant(0, VT);
3770 // fold (xor x, undef) -> undef
3771 if (N0.getOpcode() == ISD::UNDEF)
3773 if (N1.getOpcode() == ISD::UNDEF)
3775 // fold (xor c1, c2) -> c1^c2
3777 return DAG.FoldConstantArithmetic(ISD::XOR, VT, N0C, N1C);
3778 // canonicalize constant to RHS
3780 return DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0);
3781 // fold (xor x, 0) -> x
3782 if (N1C && N1C->isNullValue())
3785 SDValue RXOR = ReassociateOps(ISD::XOR, SDLoc(N), N0, N1);
3789 // fold !(x cc y) -> (x !cc y)
3790 if (N1C && N1C->getAPIntValue() == 1 && isSetCCEquivalent(N0, LHS, RHS, CC)) {
3791 bool isInt = LHS.getValueType().isInteger();
3792 ISD::CondCode NotCC = ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(),
3795 if (!LegalOperations ||
3796 TLI.isCondCodeLegal(NotCC, LHS.getSimpleValueType())) {
3797 switch (N0.getOpcode()) {
3799 llvm_unreachable("Unhandled SetCC Equivalent!");
3801 return DAG.getSetCC(SDLoc(N), VT, LHS, RHS, NotCC);
3802 case ISD::SELECT_CC:
3803 return DAG.getSelectCC(SDLoc(N), LHS, RHS, N0.getOperand(2),
3804 N0.getOperand(3), NotCC);
3809 // fold (not (zext (setcc x, y))) -> (zext (not (setcc x, y)))
3810 if (N1C && N1C->getAPIntValue() == 1 && N0.getOpcode() == ISD::ZERO_EXTEND &&
3811 N0.getNode()->hasOneUse() &&
3812 isSetCCEquivalent(N0.getOperand(0), LHS, RHS, CC)){
3813 SDValue V = N0.getOperand(0);
3814 V = DAG.getNode(ISD::XOR, SDLoc(N0), V.getValueType(), V,
3815 DAG.getConstant(1, V.getValueType()));
3816 AddToWorklist(V.getNode());
3817 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, V);
3820 // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are setcc
3821 if (N1C && N1C->getAPIntValue() == 1 && VT == MVT::i1 &&
3822 (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
3823 SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
3824 if (isOneUseSetCC(RHS) || isOneUseSetCC(LHS)) {
3825 unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
3826 LHS = DAG.getNode(ISD::XOR, SDLoc(LHS), VT, LHS, N1); // LHS = ~LHS
3827 RHS = DAG.getNode(ISD::XOR, SDLoc(RHS), VT, RHS, N1); // RHS = ~RHS
3828 AddToWorklist(LHS.getNode()); AddToWorklist(RHS.getNode());
3829 return DAG.getNode(NewOpcode, SDLoc(N), VT, LHS, RHS);
3832 // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are constants
3833 if (N1C && N1C->isAllOnesValue() &&
3834 (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
3835 SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
3836 if (isa<ConstantSDNode>(RHS) || isa<ConstantSDNode>(LHS)) {
3837 unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
3838 LHS = DAG.getNode(ISD::XOR, SDLoc(LHS), VT, LHS, N1); // LHS = ~LHS
3839 RHS = DAG.getNode(ISD::XOR, SDLoc(RHS), VT, RHS, N1); // RHS = ~RHS
3840 AddToWorklist(LHS.getNode()); AddToWorklist(RHS.getNode());
3841 return DAG.getNode(NewOpcode, SDLoc(N), VT, LHS, RHS);
3844 // fold (xor (and x, y), y) -> (and (not x), y)
3845 if (N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() &&
3846 N0->getOperand(1) == N1) {
3847 SDValue X = N0->getOperand(0);
3848 SDValue NotX = DAG.getNOT(SDLoc(X), X, VT);
3849 AddToWorklist(NotX.getNode());
3850 return DAG.getNode(ISD::AND, SDLoc(N), VT, NotX, N1);
3852 // fold (xor (xor x, c1), c2) -> (xor x, (xor c1, c2))
3853 if (N1C && N0.getOpcode() == ISD::XOR) {
3854 ConstantSDNode *N00C = dyn_cast<ConstantSDNode>(N0.getOperand(0));
3855 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3857 return DAG.getNode(ISD::XOR, SDLoc(N), VT, N0.getOperand(1),
3858 DAG.getConstant(N1C->getAPIntValue() ^
3859 N00C->getAPIntValue(), VT));
3861 return DAG.getNode(ISD::XOR, SDLoc(N), VT, N0.getOperand(0),
3862 DAG.getConstant(N1C->getAPIntValue() ^
3863 N01C->getAPIntValue(), VT));
3865 // fold (xor x, x) -> 0
3867 return tryFoldToZero(SDLoc(N), TLI, VT, DAG, LegalOperations, LegalTypes);
3869 // Simplify: xor (op x...), (op y...) -> (op (xor x, y))
3870 if (N0.getOpcode() == N1.getOpcode()) {
3871 SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
3872 if (Tmp.getNode()) return Tmp;
3875 // Simplify the expression using non-local knowledge.
3876 if (!VT.isVector() &&
3877 SimplifyDemandedBits(SDValue(N, 0)))
3878 return SDValue(N, 0);
3883 /// visitShiftByConstant - Handle transforms common to the three shifts, when
3884 /// the shift amount is a constant.
3885 SDValue DAGCombiner::visitShiftByConstant(SDNode *N, ConstantSDNode *Amt) {
3886 // We can't and shouldn't fold opaque constants.
3887 if (Amt->isOpaque())
3890 SDNode *LHS = N->getOperand(0).getNode();
3891 if (!LHS->hasOneUse()) return SDValue();
3893 // We want to pull some binops through shifts, so that we have (and (shift))
3894 // instead of (shift (and)), likewise for add, or, xor, etc. This sort of
3895 // thing happens with address calculations, so it's important to canonicalize
3897 bool HighBitSet = false; // Can we transform this if the high bit is set?
3899 switch (LHS->getOpcode()) {
3900 default: return SDValue();
3903 HighBitSet = false; // We can only transform sra if the high bit is clear.
3906 HighBitSet = true; // We can only transform sra if the high bit is set.
3909 if (N->getOpcode() != ISD::SHL)
3910 return SDValue(); // only shl(add) not sr[al](add).
3911 HighBitSet = false; // We can only transform sra if the high bit is clear.
3915 // We require the RHS of the binop to be a constant and not opaque as well.
3916 ConstantSDNode *BinOpCst = dyn_cast<ConstantSDNode>(LHS->getOperand(1));
3917 if (!BinOpCst || BinOpCst->isOpaque()) return SDValue();
3919 // FIXME: disable this unless the input to the binop is a shift by a constant.
3920 // If it is not a shift, it pessimizes some common cases like:
3922 // void foo(int *X, int i) { X[i & 1235] = 1; }
3923 // int bar(int *X, int i) { return X[i & 255]; }
3924 SDNode *BinOpLHSVal = LHS->getOperand(0).getNode();
3925 if ((BinOpLHSVal->getOpcode() != ISD::SHL &&
3926 BinOpLHSVal->getOpcode() != ISD::SRA &&
3927 BinOpLHSVal->getOpcode() != ISD::SRL) ||
3928 !isa<ConstantSDNode>(BinOpLHSVal->getOperand(1)))
3931 EVT VT = N->getValueType(0);
3933 // If this is a signed shift right, and the high bit is modified by the
3934 // logical operation, do not perform the transformation. The highBitSet
3935 // boolean indicates the value of the high bit of the constant which would
3936 // cause it to be modified for this operation.
3937 if (N->getOpcode() == ISD::SRA) {
3938 bool BinOpRHSSignSet = BinOpCst->getAPIntValue().isNegative();
3939 if (BinOpRHSSignSet != HighBitSet)
3943 if (!TLI.isDesirableToCommuteWithShift(LHS))
3946 // Fold the constants, shifting the binop RHS by the shift amount.
3947 SDValue NewRHS = DAG.getNode(N->getOpcode(), SDLoc(LHS->getOperand(1)),
3949 LHS->getOperand(1), N->getOperand(1));
3950 assert(isa<ConstantSDNode>(NewRHS) && "Folding was not successful!");
3952 // Create the new shift.
3953 SDValue NewShift = DAG.getNode(N->getOpcode(),
3954 SDLoc(LHS->getOperand(0)),
3955 VT, LHS->getOperand(0), N->getOperand(1));
3957 // Create the new binop.
3958 return DAG.getNode(LHS->getOpcode(), SDLoc(N), VT, NewShift, NewRHS);
3961 SDValue DAGCombiner::distributeTruncateThroughAnd(SDNode *N) {
3962 assert(N->getOpcode() == ISD::TRUNCATE);
3963 assert(N->getOperand(0).getOpcode() == ISD::AND);
3965 // (truncate:TruncVT (and N00, N01C)) -> (and (truncate:TruncVT N00), TruncC)
3966 if (N->hasOneUse() && N->getOperand(0).hasOneUse()) {
3967 SDValue N01 = N->getOperand(0).getOperand(1);
3969 if (ConstantSDNode *N01C = isConstOrConstSplat(N01)) {
3970 EVT TruncVT = N->getValueType(0);
3971 SDValue N00 = N->getOperand(0).getOperand(0);
3972 APInt TruncC = N01C->getAPIntValue();
3973 TruncC = TruncC.trunc(TruncVT.getScalarSizeInBits());
3975 return DAG.getNode(ISD::AND, SDLoc(N), TruncVT,
3976 DAG.getNode(ISD::TRUNCATE, SDLoc(N), TruncVT, N00),
3977 DAG.getConstant(TruncC, TruncVT));
3984 SDValue DAGCombiner::visitRotate(SDNode *N) {
3985 // fold (rot* x, (trunc (and y, c))) -> (rot* x, (and (trunc y), (trunc c))).
3986 if (N->getOperand(1).getOpcode() == ISD::TRUNCATE &&
3987 N->getOperand(1).getOperand(0).getOpcode() == ISD::AND) {
3988 SDValue NewOp1 = distributeTruncateThroughAnd(N->getOperand(1).getNode());
3989 if (NewOp1.getNode())
3990 return DAG.getNode(N->getOpcode(), SDLoc(N), N->getValueType(0),
3991 N->getOperand(0), NewOp1);
3996 SDValue DAGCombiner::visitSHL(SDNode *N) {
3997 SDValue N0 = N->getOperand(0);
3998 SDValue N1 = N->getOperand(1);
3999 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
4000 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4001 EVT VT = N0.getValueType();
4002 unsigned OpSizeInBits = VT.getScalarSizeInBits();
4005 if (VT.isVector()) {
4006 SDValue FoldedVOp = SimplifyVBinOp(N);
4007 if (FoldedVOp.getNode()) return FoldedVOp;
4009 BuildVectorSDNode *N1CV = dyn_cast<BuildVectorSDNode>(N1);
4010 // If setcc produces all-one true value then:
4011 // (shl (and (setcc) N01CV) N1CV) -> (and (setcc) N01CV<<N1CV)
4012 if (N1CV && N1CV->isConstant()) {
4013 if (N0.getOpcode() == ISD::AND) {
4014 SDValue N00 = N0->getOperand(0);
4015 SDValue N01 = N0->getOperand(1);
4016 BuildVectorSDNode *N01CV = dyn_cast<BuildVectorSDNode>(N01);
4018 if (N01CV && N01CV->isConstant() && N00.getOpcode() == ISD::SETCC &&
4019 TLI.getBooleanContents(N00.getOperand(0).getValueType()) ==
4020 TargetLowering::ZeroOrNegativeOneBooleanContent) {
4021 SDValue C = DAG.FoldConstantArithmetic(ISD::SHL, VT, N01CV, N1CV);
4023 return DAG.getNode(ISD::AND, SDLoc(N), VT, N00, C);
4026 N1C = isConstOrConstSplat(N1);
4031 // fold (shl c1, c2) -> c1<<c2
4033 return DAG.FoldConstantArithmetic(ISD::SHL, VT, N0C, N1C);
4034 // fold (shl 0, x) -> 0
4035 if (N0C && N0C->isNullValue())
4037 // fold (shl x, c >= size(x)) -> undef
4038 if (N1C && N1C->getZExtValue() >= OpSizeInBits)
4039 return DAG.getUNDEF(VT);
4040 // fold (shl x, 0) -> x
4041 if (N1C && N1C->isNullValue())
4043 // fold (shl undef, x) -> 0
4044 if (N0.getOpcode() == ISD::UNDEF)
4045 return DAG.getConstant(0, VT);
4046 // if (shl x, c) is known to be zero, return 0
4047 if (DAG.MaskedValueIsZero(SDValue(N, 0),
4048 APInt::getAllOnesValue(OpSizeInBits)))
4049 return DAG.getConstant(0, VT);
4050 // fold (shl x, (trunc (and y, c))) -> (shl x, (and (trunc y), (trunc c))).
4051 if (N1.getOpcode() == ISD::TRUNCATE &&
4052 N1.getOperand(0).getOpcode() == ISD::AND) {
4053 SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode());
4054 if (NewOp1.getNode())
4055 return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0, NewOp1);
4058 if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
4059 return SDValue(N, 0);
4061 // fold (shl (shl x, c1), c2) -> 0 or (shl x, (add c1, c2))
4062 if (N1C && N0.getOpcode() == ISD::SHL) {
4063 if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) {
4064 uint64_t c1 = N0C1->getZExtValue();
4065 uint64_t c2 = N1C->getZExtValue();
4066 if (c1 + c2 >= OpSizeInBits)
4067 return DAG.getConstant(0, VT);
4068 return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0.getOperand(0),
4069 DAG.getConstant(c1 + c2, N1.getValueType()));
4073 // fold (shl (ext (shl x, c1)), c2) -> (ext (shl x, (add c1, c2)))
4074 // For this to be valid, the second form must not preserve any of the bits
4075 // that are shifted out by the inner shift in the first form. This means
4076 // the outer shift size must be >= the number of bits added by the ext.
4077 // As a corollary, we don't care what kind of ext it is.
4078 if (N1C && (N0.getOpcode() == ISD::ZERO_EXTEND ||
4079 N0.getOpcode() == ISD::ANY_EXTEND ||
4080 N0.getOpcode() == ISD::SIGN_EXTEND) &&
4081 N0.getOperand(0).getOpcode() == ISD::SHL) {
4082 SDValue N0Op0 = N0.getOperand(0);
4083 if (ConstantSDNode *N0Op0C1 = isConstOrConstSplat(N0Op0.getOperand(1))) {
4084 uint64_t c1 = N0Op0C1->getZExtValue();
4085 uint64_t c2 = N1C->getZExtValue();
4086 EVT InnerShiftVT = N0Op0.getValueType();
4087 uint64_t InnerShiftSize = InnerShiftVT.getScalarSizeInBits();
4088 if (c2 >= OpSizeInBits - InnerShiftSize) {
4089 if (c1 + c2 >= OpSizeInBits)
4090 return DAG.getConstant(0, VT);
4091 return DAG.getNode(ISD::SHL, SDLoc(N0), VT,
4092 DAG.getNode(N0.getOpcode(), SDLoc(N0), VT,
4093 N0Op0->getOperand(0)),
4094 DAG.getConstant(c1 + c2, N1.getValueType()));
4099 // fold (shl (zext (srl x, C)), C) -> (zext (shl (srl x, C), C))
4100 // Only fold this if the inner zext has no other uses to avoid increasing
4101 // the total number of instructions.
4102 if (N1C && N0.getOpcode() == ISD::ZERO_EXTEND && N0.hasOneUse() &&
4103 N0.getOperand(0).getOpcode() == ISD::SRL) {
4104 SDValue N0Op0 = N0.getOperand(0);
4105 if (ConstantSDNode *N0Op0C1 = isConstOrConstSplat(N0Op0.getOperand(1))) {
4106 uint64_t c1 = N0Op0C1->getZExtValue();
4107 if (c1 < VT.getScalarSizeInBits()) {
4108 uint64_t c2 = N1C->getZExtValue();
4110 SDValue NewOp0 = N0.getOperand(0);
4111 EVT CountVT = NewOp0.getOperand(1).getValueType();
4112 SDValue NewSHL = DAG.getNode(ISD::SHL, SDLoc(N), NewOp0.getValueType(),
4113 NewOp0, DAG.getConstant(c2, CountVT));
4114 AddToWorklist(NewSHL.getNode());
4115 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N0), VT, NewSHL);
4121 // fold (shl (srl x, c1), c2) -> (and (shl x, (sub c2, c1), MASK) or
4122 // (and (srl x, (sub c1, c2), MASK)
4123 // Only fold this if the inner shift has no other uses -- if it does, folding
4124 // this will increase the total number of instructions.
4125 if (N1C && N0.getOpcode() == ISD::SRL && N0.hasOneUse()) {
4126 if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) {
4127 uint64_t c1 = N0C1->getZExtValue();
4128 if (c1 < OpSizeInBits) {
4129 uint64_t c2 = N1C->getZExtValue();
4130 APInt Mask = APInt::getHighBitsSet(OpSizeInBits, OpSizeInBits - c1);
4133 Mask = Mask.shl(c2 - c1);
4134 Shift = DAG.getNode(ISD::SHL, SDLoc(N), VT, N0.getOperand(0),
4135 DAG.getConstant(c2 - c1, N1.getValueType()));
4137 Mask = Mask.lshr(c1 - c2);
4138 Shift = DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0),
4139 DAG.getConstant(c1 - c2, N1.getValueType()));
4141 return DAG.getNode(ISD::AND, SDLoc(N0), VT, Shift,
4142 DAG.getConstant(Mask, VT));
4146 // fold (shl (sra x, c1), c1) -> (and x, (shl -1, c1))
4147 if (N1C && N0.getOpcode() == ISD::SRA && N1 == N0.getOperand(1)) {
4148 unsigned BitSize = VT.getScalarSizeInBits();
4149 SDValue HiBitsMask =
4150 DAG.getConstant(APInt::getHighBitsSet(BitSize,
4151 BitSize - N1C->getZExtValue()), VT);
4152 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0.getOperand(0),
4157 SDValue NewSHL = visitShiftByConstant(N, N1C);
4158 if (NewSHL.getNode())
4165 SDValue DAGCombiner::visitSRA(SDNode *N) {
4166 SDValue N0 = N->getOperand(0);
4167 SDValue N1 = N->getOperand(1);
4168 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
4169 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4170 EVT VT = N0.getValueType();
4171 unsigned OpSizeInBits = VT.getScalarType().getSizeInBits();
4174 if (VT.isVector()) {
4175 SDValue FoldedVOp = SimplifyVBinOp(N);
4176 if (FoldedVOp.getNode()) return FoldedVOp;
4178 N1C = isConstOrConstSplat(N1);
4181 // fold (sra c1, c2) -> (sra c1, c2)
4183 return DAG.FoldConstantArithmetic(ISD::SRA, VT, N0C, N1C);
4184 // fold (sra 0, x) -> 0
4185 if (N0C && N0C->isNullValue())
4187 // fold (sra -1, x) -> -1
4188 if (N0C && N0C->isAllOnesValue())
4190 // fold (sra x, (setge c, size(x))) -> undef
4191 if (N1C && N1C->getZExtValue() >= OpSizeInBits)
4192 return DAG.getUNDEF(VT);
4193 // fold (sra x, 0) -> x
4194 if (N1C && N1C->isNullValue())
4196 // fold (sra (shl x, c1), c1) -> sext_inreg for some c1 and target supports
4198 if (N1C && N0.getOpcode() == ISD::SHL && N1 == N0.getOperand(1)) {
4199 unsigned LowBits = OpSizeInBits - (unsigned)N1C->getZExtValue();
4200 EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), LowBits);
4202 ExtVT = EVT::getVectorVT(*DAG.getContext(),
4203 ExtVT, VT.getVectorNumElements());
4204 if ((!LegalOperations ||
4205 TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, ExtVT)))
4206 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
4207 N0.getOperand(0), DAG.getValueType(ExtVT));
4210 // fold (sra (sra x, c1), c2) -> (sra x, (add c1, c2))
4211 if (N1C && N0.getOpcode() == ISD::SRA) {
4212 if (ConstantSDNode *C1 = isConstOrConstSplat(N0.getOperand(1))) {
4213 unsigned Sum = N1C->getZExtValue() + C1->getZExtValue();
4214 if (Sum >= OpSizeInBits)
4215 Sum = OpSizeInBits - 1;
4216 return DAG.getNode(ISD::SRA, SDLoc(N), VT, N0.getOperand(0),
4217 DAG.getConstant(Sum, N1.getValueType()));
4221 // fold (sra (shl X, m), (sub result_size, n))
4222 // -> (sign_extend (trunc (shl X, (sub (sub result_size, n), m)))) for
4223 // result_size - n != m.
4224 // If truncate is free for the target sext(shl) is likely to result in better
4226 if (N0.getOpcode() == ISD::SHL && N1C) {
4227 // Get the two constanst of the shifts, CN0 = m, CN = n.
4228 const ConstantSDNode *N01C = isConstOrConstSplat(N0.getOperand(1));
4230 LLVMContext &Ctx = *DAG.getContext();
4231 // Determine what the truncate's result bitsize and type would be.
4232 EVT TruncVT = EVT::getIntegerVT(Ctx, OpSizeInBits - N1C->getZExtValue());
4235 TruncVT = EVT::getVectorVT(Ctx, TruncVT, VT.getVectorNumElements());
4237 // Determine the residual right-shift amount.
4238 signed ShiftAmt = N1C->getZExtValue() - N01C->getZExtValue();
4240 // If the shift is not a no-op (in which case this should be just a sign
4241 // extend already), the truncated to type is legal, sign_extend is legal
4242 // on that type, and the truncate to that type is both legal and free,
4243 // perform the transform.
4244 if ((ShiftAmt > 0) &&
4245 TLI.isOperationLegalOrCustom(ISD::SIGN_EXTEND, TruncVT) &&
4246 TLI.isOperationLegalOrCustom(ISD::TRUNCATE, VT) &&
4247 TLI.isTruncateFree(VT, TruncVT)) {
4249 SDValue Amt = DAG.getConstant(ShiftAmt,
4250 getShiftAmountTy(N0.getOperand(0).getValueType()));
4251 SDValue Shift = DAG.getNode(ISD::SRL, SDLoc(N0), VT,
4252 N0.getOperand(0), Amt);
4253 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0), TruncVT,
4255 return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N),
4256 N->getValueType(0), Trunc);
4261 // fold (sra x, (trunc (and y, c))) -> (sra x, (and (trunc y), (trunc c))).
4262 if (N1.getOpcode() == ISD::TRUNCATE &&
4263 N1.getOperand(0).getOpcode() == ISD::AND) {
4264 SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode());
4265 if (NewOp1.getNode())
4266 return DAG.getNode(ISD::SRA, SDLoc(N), VT, N0, NewOp1);
4269 // fold (sra (trunc (srl x, c1)), c2) -> (trunc (sra x, c1 + c2))
4270 // if c1 is equal to the number of bits the trunc removes
4271 if (N0.getOpcode() == ISD::TRUNCATE &&
4272 (N0.getOperand(0).getOpcode() == ISD::SRL ||
4273 N0.getOperand(0).getOpcode() == ISD::SRA) &&
4274 N0.getOperand(0).hasOneUse() &&
4275 N0.getOperand(0).getOperand(1).hasOneUse() &&
4277 SDValue N0Op0 = N0.getOperand(0);
4278 if (ConstantSDNode *LargeShift = isConstOrConstSplat(N0Op0.getOperand(1))) {
4279 unsigned LargeShiftVal = LargeShift->getZExtValue();
4280 EVT LargeVT = N0Op0.getValueType();
4282 if (LargeVT.getScalarSizeInBits() - OpSizeInBits == LargeShiftVal) {
4284 DAG.getConstant(LargeShiftVal + N1C->getZExtValue(),
4285 getShiftAmountTy(N0Op0.getOperand(0).getValueType()));
4286 SDValue SRA = DAG.getNode(ISD::SRA, SDLoc(N), LargeVT,
4287 N0Op0.getOperand(0), Amt);
4288 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, SRA);
4293 // Simplify, based on bits shifted out of the LHS.
4294 if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
4295 return SDValue(N, 0);
4298 // If the sign bit is known to be zero, switch this to a SRL.
4299 if (DAG.SignBitIsZero(N0))
4300 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, N1);
4303 SDValue NewSRA = visitShiftByConstant(N, N1C);
4304 if (NewSRA.getNode())
4311 SDValue DAGCombiner::visitSRL(SDNode *N) {
4312 SDValue N0 = N->getOperand(0);
4313 SDValue N1 = N->getOperand(1);
4314 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
4315 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4316 EVT VT = N0.getValueType();
4317 unsigned OpSizeInBits = VT.getScalarType().getSizeInBits();
4320 if (VT.isVector()) {
4321 SDValue FoldedVOp = SimplifyVBinOp(N);
4322 if (FoldedVOp.getNode()) return FoldedVOp;
4324 N1C = isConstOrConstSplat(N1);
4327 // fold (srl c1, c2) -> c1 >>u c2
4329 return DAG.FoldConstantArithmetic(ISD::SRL, VT, N0C, N1C);
4330 // fold (srl 0, x) -> 0
4331 if (N0C && N0C->isNullValue())
4333 // fold (srl x, c >= size(x)) -> undef
4334 if (N1C && N1C->getZExtValue() >= OpSizeInBits)
4335 return DAG.getUNDEF(VT);
4336 // fold (srl x, 0) -> x
4337 if (N1C && N1C->isNullValue())
4339 // if (srl x, c) is known to be zero, return 0
4340 if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0),
4341 APInt::getAllOnesValue(OpSizeInBits)))
4342 return DAG.getConstant(0, VT);
4344 // fold (srl (srl x, c1), c2) -> 0 or (srl x, (add c1, c2))
4345 if (N1C && N0.getOpcode() == ISD::SRL) {
4346 if (ConstantSDNode *N01C = isConstOrConstSplat(N0.getOperand(1))) {
4347 uint64_t c1 = N01C->getZExtValue();
4348 uint64_t c2 = N1C->getZExtValue();
4349 if (c1 + c2 >= OpSizeInBits)
4350 return DAG.getConstant(0, VT);
4351 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0),
4352 DAG.getConstant(c1 + c2, N1.getValueType()));
4356 // fold (srl (trunc (srl x, c1)), c2) -> 0 or (trunc (srl x, (add c1, c2)))
4357 if (N1C && N0.getOpcode() == ISD::TRUNCATE &&
4358 N0.getOperand(0).getOpcode() == ISD::SRL &&
4359 isa<ConstantSDNode>(N0.getOperand(0)->getOperand(1))) {
4361 cast<ConstantSDNode>(N0.getOperand(0)->getOperand(1))->getZExtValue();
4362 uint64_t c2 = N1C->getZExtValue();
4363 EVT InnerShiftVT = N0.getOperand(0).getValueType();
4364 EVT ShiftCountVT = N0.getOperand(0)->getOperand(1).getValueType();
4365 uint64_t InnerShiftSize = InnerShiftVT.getScalarType().getSizeInBits();
4366 // This is only valid if the OpSizeInBits + c1 = size of inner shift.
4367 if (c1 + OpSizeInBits == InnerShiftSize) {
4368 if (c1 + c2 >= InnerShiftSize)
4369 return DAG.getConstant(0, VT);
4370 return DAG.getNode(ISD::TRUNCATE, SDLoc(N0), VT,
4371 DAG.getNode(ISD::SRL, SDLoc(N0), InnerShiftVT,
4372 N0.getOperand(0)->getOperand(0),
4373 DAG.getConstant(c1 + c2, ShiftCountVT)));
4377 // fold (srl (shl x, c), c) -> (and x, cst2)
4378 if (N1C && N0.getOpcode() == ISD::SHL && N0.getOperand(1) == N1) {
4379 unsigned BitSize = N0.getScalarValueSizeInBits();
4380 if (BitSize <= 64) {
4381 uint64_t ShAmt = N1C->getZExtValue() + 64 - BitSize;
4382 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0.getOperand(0),
4383 DAG.getConstant(~0ULL >> ShAmt, VT));
4387 // fold (srl (anyextend x), c) -> (and (anyextend (srl x, c)), mask)
4388 if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
4389 // Shifting in all undef bits?
4390 EVT SmallVT = N0.getOperand(0).getValueType();
4391 unsigned BitSize = SmallVT.getScalarSizeInBits();
4392 if (N1C->getZExtValue() >= BitSize)
4393 return DAG.getUNDEF(VT);
4395 if (!LegalTypes || TLI.isTypeDesirableForOp(ISD::SRL, SmallVT)) {
4396 uint64_t ShiftAmt = N1C->getZExtValue();
4397 SDValue SmallShift = DAG.getNode(ISD::SRL, SDLoc(N0), SmallVT,
4399 DAG.getConstant(ShiftAmt, getShiftAmountTy(SmallVT)));
4400 AddToWorklist(SmallShift.getNode());
4401 APInt Mask = APInt::getAllOnesValue(OpSizeInBits).lshr(ShiftAmt);
4402 return DAG.getNode(ISD::AND, SDLoc(N), VT,
4403 DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, SmallShift),
4404 DAG.getConstant(Mask, VT));
4408 // fold (srl (sra X, Y), 31) -> (srl X, 31). This srl only looks at the sign
4409 // bit, which is unmodified by sra.
4410 if (N1C && N1C->getZExtValue() + 1 == OpSizeInBits) {
4411 if (N0.getOpcode() == ISD::SRA)
4412 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0), N1);
4415 // fold (srl (ctlz x), "5") -> x iff x has one bit set (the low bit).
4416 if (N1C && N0.getOpcode() == ISD::CTLZ &&
4417 N1C->getAPIntValue() == Log2_32(OpSizeInBits)) {
4418 APInt KnownZero, KnownOne;
4419 DAG.computeKnownBits(N0.getOperand(0), KnownZero, KnownOne);
4421 // If any of the input bits are KnownOne, then the input couldn't be all
4422 // zeros, thus the result of the srl will always be zero.
4423 if (KnownOne.getBoolValue()) return DAG.getConstant(0, VT);
4425 // If all of the bits input the to ctlz node are known to be zero, then
4426 // the result of the ctlz is "32" and the result of the shift is one.
4427 APInt UnknownBits = ~KnownZero;
4428 if (UnknownBits == 0) return DAG.getConstant(1, VT);
4430 // Otherwise, check to see if there is exactly one bit input to the ctlz.
4431 if ((UnknownBits & (UnknownBits - 1)) == 0) {
4432 // Okay, we know that only that the single bit specified by UnknownBits
4433 // could be set on input to the CTLZ node. If this bit is set, the SRL
4434 // will return 0, if it is clear, it returns 1. Change the CTLZ/SRL pair
4435 // to an SRL/XOR pair, which is likely to simplify more.
4436 unsigned ShAmt = UnknownBits.countTrailingZeros();
4437 SDValue Op = N0.getOperand(0);
4440 Op = DAG.getNode(ISD::SRL, SDLoc(N0), VT, Op,
4441 DAG.getConstant(ShAmt, getShiftAmountTy(Op.getValueType())));
4442 AddToWorklist(Op.getNode());
4445 return DAG.getNode(ISD::XOR, SDLoc(N), VT,
4446 Op, DAG.getConstant(1, VT));
4450 // fold (srl x, (trunc (and y, c))) -> (srl x, (and (trunc y), (trunc c))).
4451 if (N1.getOpcode() == ISD::TRUNCATE &&
4452 N1.getOperand(0).getOpcode() == ISD::AND) {
4453 SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode());
4454 if (NewOp1.getNode())
4455 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, NewOp1);
4458 // fold operands of srl based on knowledge that the low bits are not
4460 if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
4461 return SDValue(N, 0);
4464 SDValue NewSRL = visitShiftByConstant(N, N1C);
4465 if (NewSRL.getNode())
4469 // Attempt to convert a srl of a load into a narrower zero-extending load.
4470 SDValue NarrowLoad = ReduceLoadWidth(N);
4471 if (NarrowLoad.getNode())
4474 // Here is a common situation. We want to optimize:
4477 // %b = and i32 %a, 2
4478 // %c = srl i32 %b, 1
4479 // brcond i32 %c ...
4485 // %c = setcc eq %b, 0
4488 // However when after the source operand of SRL is optimized into AND, the SRL
4489 // itself may not be optimized further. Look for it and add the BRCOND into
4491 if (N->hasOneUse()) {
4492 SDNode *Use = *N->use_begin();
4493 if (Use->getOpcode() == ISD::BRCOND)
4495 else if (Use->getOpcode() == ISD::TRUNCATE && Use->hasOneUse()) {
4496 // Also look pass the truncate.
4497 Use = *Use->use_begin();
4498 if (Use->getOpcode() == ISD::BRCOND)
4506 SDValue DAGCombiner::visitCTLZ(SDNode *N) {
4507 SDValue N0 = N->getOperand(0);
4508 EVT VT = N->getValueType(0);
4510 // fold (ctlz c1) -> c2
4511 if (isa<ConstantSDNode>(N0))
4512 return DAG.getNode(ISD::CTLZ, SDLoc(N), VT, N0);
4516 SDValue DAGCombiner::visitCTLZ_ZERO_UNDEF(SDNode *N) {
4517 SDValue N0 = N->getOperand(0);
4518 EVT VT = N->getValueType(0);
4520 // fold (ctlz_zero_undef c1) -> c2
4521 if (isa<ConstantSDNode>(N0))
4522 return DAG.getNode(ISD::CTLZ_ZERO_UNDEF, SDLoc(N), VT, N0);
4526 SDValue DAGCombiner::visitCTTZ(SDNode *N) {
4527 SDValue N0 = N->getOperand(0);
4528 EVT VT = N->getValueType(0);
4530 // fold (cttz c1) -> c2
4531 if (isa<ConstantSDNode>(N0))
4532 return DAG.getNode(ISD::CTTZ, SDLoc(N), VT, N0);
4536 SDValue DAGCombiner::visitCTTZ_ZERO_UNDEF(SDNode *N) {
4537 SDValue N0 = N->getOperand(0);
4538 EVT VT = N->getValueType(0);
4540 // fold (cttz_zero_undef c1) -> c2
4541 if (isa<ConstantSDNode>(N0))
4542 return DAG.getNode(ISD::CTTZ_ZERO_UNDEF, SDLoc(N), VT, N0);
4546 SDValue DAGCombiner::visitCTPOP(SDNode *N) {
4547 SDValue N0 = N->getOperand(0);
4548 EVT VT = N->getValueType(0);
4550 // fold (ctpop c1) -> c2
4551 if (isa<ConstantSDNode>(N0))
4552 return DAG.getNode(ISD::CTPOP, SDLoc(N), VT, N0);
4556 SDValue DAGCombiner::visitSELECT(SDNode *N) {
4557 SDValue N0 = N->getOperand(0);
4558 SDValue N1 = N->getOperand(1);
4559 SDValue N2 = N->getOperand(2);
4560 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
4561 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4562 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2);
4563 EVT VT = N->getValueType(0);
4564 EVT VT0 = N0.getValueType();
4566 // fold (select C, X, X) -> X
4569 // fold (select true, X, Y) -> X
4570 if (N0C && !N0C->isNullValue())
4572 // fold (select false, X, Y) -> Y
4573 if (N0C && N0C->isNullValue())
4575 // fold (select C, 1, X) -> (or C, X)
4576 if (VT == MVT::i1 && N1C && N1C->getAPIntValue() == 1)
4577 return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N2);
4578 // fold (select C, 0, 1) -> (xor C, 1)
4579 // We can't do this reliably if integer based booleans have different contents
4580 // to floating point based booleans. This is because we can't tell whether we
4581 // have an integer-based boolean or a floating-point-based boolean unless we
4582 // can find the SETCC that produced it and inspect its operands. This is
4583 // fairly easy if C is the SETCC node, but it can potentially be
4584 // undiscoverable (or not reasonably discoverable). For example, it could be
4585 // in another basic block or it could require searching a complicated
4587 if (VT.isInteger() &&
4588 (VT0 == MVT::i1 || (VT0.isInteger() &&
4589 TLI.getBooleanContents(false, false) ==
4590 TLI.getBooleanContents(false, true) &&
4591 TLI.getBooleanContents(false, false) ==
4592 TargetLowering::ZeroOrOneBooleanContent)) &&
4593 N1C && N2C && N1C->isNullValue() && N2C->getAPIntValue() == 1) {
4596 return DAG.getNode(ISD::XOR, SDLoc(N), VT0,
4597 N0, DAG.getConstant(1, VT0));
4598 XORNode = DAG.getNode(ISD::XOR, SDLoc(N0), VT0,
4599 N0, DAG.getConstant(1, VT0));
4600 AddToWorklist(XORNode.getNode());
4602 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, XORNode);
4603 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, XORNode);
4605 // fold (select C, 0, X) -> (and (not C), X)
4606 if (VT == VT0 && VT == MVT::i1 && N1C && N1C->isNullValue()) {
4607 SDValue NOTNode = DAG.getNOT(SDLoc(N0), N0, VT);
4608 AddToWorklist(NOTNode.getNode());
4609 return DAG.getNode(ISD::AND, SDLoc(N), VT, NOTNode, N2);
4611 // fold (select C, X, 1) -> (or (not C), X)
4612 if (VT == VT0 && VT == MVT::i1 && N2C && N2C->getAPIntValue() == 1) {
4613 SDValue NOTNode = DAG.getNOT(SDLoc(N0), N0, VT);
4614 AddToWorklist(NOTNode.getNode());
4615 return DAG.getNode(ISD::OR, SDLoc(N), VT, NOTNode, N1);
4617 // fold (select C, X, 0) -> (and C, X)
4618 if (VT == MVT::i1 && N2C && N2C->isNullValue())
4619 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, N1);
4620 // fold (select X, X, Y) -> (or X, Y)
4621 // fold (select X, 1, Y) -> (or X, Y)
4622 if (VT == MVT::i1 && (N0 == N1 || (N1C && N1C->getAPIntValue() == 1)))
4623 return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N2);
4624 // fold (select X, Y, X) -> (and X, Y)
4625 // fold (select X, Y, 0) -> (and X, Y)
4626 if (VT == MVT::i1 && (N0 == N2 || (N2C && N2C->getAPIntValue() == 0)))
4627 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, N1);
4629 // If we can fold this based on the true/false value, do so.
4630 if (SimplifySelectOps(N, N1, N2))
4631 return SDValue(N, 0); // Don't revisit N.
4633 // fold selects based on a setcc into other things, such as min/max/abs
4634 if (N0.getOpcode() == ISD::SETCC) {
4635 if ((!LegalOperations &&
4636 TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT)) ||
4637 TLI.isOperationLegal(ISD::SELECT_CC, VT))
4638 return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT,
4639 N0.getOperand(0), N0.getOperand(1),
4640 N1, N2, N0.getOperand(2));
4641 return SimplifySelect(SDLoc(N), N0, N1, N2);
4648 std::pair<SDValue, SDValue> SplitVSETCC(const SDNode *N, SelectionDAG &DAG) {
4651 std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(N->getValueType(0));
4653 // Split the inputs.
4654 SDValue Lo, Hi, LL, LH, RL, RH;
4655 std::tie(LL, LH) = DAG.SplitVectorOperand(N, 0);
4656 std::tie(RL, RH) = DAG.SplitVectorOperand(N, 1);
4658 Lo = DAG.getNode(N->getOpcode(), DL, LoVT, LL, RL, N->getOperand(2));
4659 Hi = DAG.getNode(N->getOpcode(), DL, HiVT, LH, RH, N->getOperand(2));
4661 return std::make_pair(Lo, Hi);
4664 // This function assumes all the vselect's arguments are CONCAT_VECTOR
4665 // nodes and that the condition is a BV of ConstantSDNodes (or undefs).
4666 static SDValue ConvertSelectToConcatVector(SDNode *N, SelectionDAG &DAG) {
4668 SDValue Cond = N->getOperand(0);
4669 SDValue LHS = N->getOperand(1);
4670 SDValue RHS = N->getOperand(2);
4671 MVT VT = N->getSimpleValueType(0);
4672 int NumElems = VT.getVectorNumElements();
4673 assert(LHS.getOpcode() == ISD::CONCAT_VECTORS &&
4674 RHS.getOpcode() == ISD::CONCAT_VECTORS &&
4675 Cond.getOpcode() == ISD::BUILD_VECTOR);
4677 // We're sure we have an even number of elements due to the
4678 // concat_vectors we have as arguments to vselect.
4679 // Skip BV elements until we find one that's not an UNDEF
4680 // After we find an UNDEF element, keep looping until we get to half the
4681 // length of the BV and see if all the non-undef nodes are the same.
4682 ConstantSDNode *BottomHalf = nullptr;
4683 for (int i = 0; i < NumElems / 2; ++i) {
4684 if (Cond->getOperand(i)->getOpcode() == ISD::UNDEF)
4687 if (BottomHalf == nullptr)
4688 BottomHalf = cast<ConstantSDNode>(Cond.getOperand(i));
4689 else if (Cond->getOperand(i).getNode() != BottomHalf)
4693 // Do the same for the second half of the BuildVector
4694 ConstantSDNode *TopHalf = nullptr;
4695 for (int i = NumElems / 2; i < NumElems; ++i) {
4696 if (Cond->getOperand(i)->getOpcode() == ISD::UNDEF)
4699 if (TopHalf == nullptr)
4700 TopHalf = cast<ConstantSDNode>(Cond.getOperand(i));
4701 else if (Cond->getOperand(i).getNode() != TopHalf)
4705 assert(TopHalf && BottomHalf &&
4706 "One half of the selector was all UNDEFs and the other was all the "
4707 "same value. This should have been addressed before this function.");
4709 ISD::CONCAT_VECTORS, dl, VT,
4710 BottomHalf->isNullValue() ? RHS->getOperand(0) : LHS->getOperand(0),
4711 TopHalf->isNullValue() ? RHS->getOperand(1) : LHS->getOperand(1));
4714 SDValue DAGCombiner::visitVSELECT(SDNode *N) {
4715 SDValue N0 = N->getOperand(0);
4716 SDValue N1 = N->getOperand(1);
4717 SDValue N2 = N->getOperand(2);
4720 // Canonicalize integer abs.
4721 // vselect (setg[te] X, 0), X, -X ->
4722 // vselect (setgt X, -1), X, -X ->
4723 // vselect (setl[te] X, 0), -X, X ->
4724 // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
4725 if (N0.getOpcode() == ISD::SETCC) {
4726 SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
4727 ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
4729 bool RHSIsAllZeros = ISD::isBuildVectorAllZeros(RHS.getNode());
4731 if (((RHSIsAllZeros && (CC == ISD::SETGT || CC == ISD::SETGE)) ||
4732 (ISD::isBuildVectorAllOnes(RHS.getNode()) && CC == ISD::SETGT)) &&
4733 N1 == LHS && N2.getOpcode() == ISD::SUB && N1 == N2.getOperand(1))
4734 isAbs = ISD::isBuildVectorAllZeros(N2.getOperand(0).getNode());
4735 else if ((RHSIsAllZeros && (CC == ISD::SETLT || CC == ISD::SETLE)) &&
4736 N2 == LHS && N1.getOpcode() == ISD::SUB && N2 == N1.getOperand(1))
4737 isAbs = ISD::isBuildVectorAllZeros(N1.getOperand(0).getNode());
4740 EVT VT = LHS.getValueType();
4741 SDValue Shift = DAG.getNode(
4742 ISD::SRA, DL, VT, LHS,
4743 DAG.getConstant(VT.getScalarType().getSizeInBits() - 1, VT));
4744 SDValue Add = DAG.getNode(ISD::ADD, DL, VT, LHS, Shift);
4745 AddToWorklist(Shift.getNode());
4746 AddToWorklist(Add.getNode());
4747 return DAG.getNode(ISD::XOR, DL, VT, Add, Shift);
4751 // If the VSELECT result requires splitting and the mask is provided by a
4752 // SETCC, then split both nodes and its operands before legalization. This
4753 // prevents the type legalizer from unrolling SETCC into scalar comparisons
4754 // and enables future optimizations (e.g. min/max pattern matching on X86).
4755 if (N0.getOpcode() == ISD::SETCC) {
4756 EVT VT = N->getValueType(0);
4758 // Check if any splitting is required.
4759 if (TLI.getTypeAction(*DAG.getContext(), VT) !=
4760 TargetLowering::TypeSplitVector)
4763 SDValue Lo, Hi, CCLo, CCHi, LL, LH, RL, RH;
4764 std::tie(CCLo, CCHi) = SplitVSETCC(N0.getNode(), DAG);
4765 std::tie(LL, LH) = DAG.SplitVectorOperand(N, 1);
4766 std::tie(RL, RH) = DAG.SplitVectorOperand(N, 2);
4768 Lo = DAG.getNode(N->getOpcode(), DL, LL.getValueType(), CCLo, LL, RL);
4769 Hi = DAG.getNode(N->getOpcode(), DL, LH.getValueType(), CCHi, LH, RH);
4771 // Add the new VSELECT nodes to the work list in case they need to be split
4773 AddToWorklist(Lo.getNode());
4774 AddToWorklist(Hi.getNode());
4776 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
4779 // Fold (vselect (build_vector all_ones), N1, N2) -> N1
4780 if (ISD::isBuildVectorAllOnes(N0.getNode()))
4782 // Fold (vselect (build_vector all_zeros), N1, N2) -> N2
4783 if (ISD::isBuildVectorAllZeros(N0.getNode()))
4786 // The ConvertSelectToConcatVector function is assuming both the above
4787 // checks for (vselect (build_vector all{ones,zeros) ...) have been made
4789 if (N1.getOpcode() == ISD::CONCAT_VECTORS &&
4790 N2.getOpcode() == ISD::CONCAT_VECTORS &&
4791 ISD::isBuildVectorOfConstantSDNodes(N0.getNode())) {
4792 SDValue CV = ConvertSelectToConcatVector(N, DAG);
4800 SDValue DAGCombiner::visitSELECT_CC(SDNode *N) {
4801 SDValue N0 = N->getOperand(0);
4802 SDValue N1 = N->getOperand(1);
4803 SDValue N2 = N->getOperand(2);
4804 SDValue N3 = N->getOperand(3);
4805 SDValue N4 = N->getOperand(4);
4806 ISD::CondCode CC = cast<CondCodeSDNode>(N4)->get();
4808 // fold select_cc lhs, rhs, x, x, cc -> x
4812 // Determine if the condition we're dealing with is constant
4813 SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()),
4814 N0, N1, CC, SDLoc(N), false);
4815 if (SCC.getNode()) {
4816 AddToWorklist(SCC.getNode());
4818 if (ConstantSDNode *SCCC = dyn_cast<ConstantSDNode>(SCC.getNode())) {
4819 if (!SCCC->isNullValue())
4820 return N2; // cond always true -> true val
4822 return N3; // cond always false -> false val
4825 // Fold to a simpler select_cc
4826 if (SCC.getOpcode() == ISD::SETCC)
4827 return DAG.getNode(ISD::SELECT_CC, SDLoc(N), N2.getValueType(),
4828 SCC.getOperand(0), SCC.getOperand(1), N2, N3,
4832 // If we can fold this based on the true/false value, do so.
4833 if (SimplifySelectOps(N, N2, N3))
4834 return SDValue(N, 0); // Don't revisit N.
4836 // fold select_cc into other things, such as min/max/abs
4837 return SimplifySelectCC(SDLoc(N), N0, N1, N2, N3, CC);
4840 SDValue DAGCombiner::visitSETCC(SDNode *N) {
4841 return SimplifySetCC(N->getValueType(0), N->getOperand(0), N->getOperand(1),
4842 cast<CondCodeSDNode>(N->getOperand(2))->get(),
4846 // tryToFoldExtendOfConstant - Try to fold a sext/zext/aext
4847 // dag node into a ConstantSDNode or a build_vector of constants.
4848 // This function is called by the DAGCombiner when visiting sext/zext/aext
4849 // dag nodes (see for example method DAGCombiner::visitSIGN_EXTEND).
4850 // Vector extends are not folded if operations are legal; this is to
4851 // avoid introducing illegal build_vector dag nodes.
4852 static SDNode *tryToFoldExtendOfConstant(SDNode *N, const TargetLowering &TLI,
4853 SelectionDAG &DAG, bool LegalTypes,
4854 bool LegalOperations) {
4855 unsigned Opcode = N->getOpcode();
4856 SDValue N0 = N->getOperand(0);
4857 EVT VT = N->getValueType(0);
4859 assert((Opcode == ISD::SIGN_EXTEND || Opcode == ISD::ZERO_EXTEND ||
4860 Opcode == ISD::ANY_EXTEND) && "Expected EXTEND dag node in input!");
4862 // fold (sext c1) -> c1
4863 // fold (zext c1) -> c1
4864 // fold (aext c1) -> c1
4865 if (isa<ConstantSDNode>(N0))
4866 return DAG.getNode(Opcode, SDLoc(N), VT, N0).getNode();
4868 // fold (sext (build_vector AllConstants) -> (build_vector AllConstants)
4869 // fold (zext (build_vector AllConstants) -> (build_vector AllConstants)
4870 // fold (aext (build_vector AllConstants) -> (build_vector AllConstants)
4871 EVT SVT = VT.getScalarType();
4872 if (!(VT.isVector() &&
4873 (!LegalTypes || (!LegalOperations && TLI.isTypeLegal(SVT))) &&
4874 ISD::isBuildVectorOfConstantSDNodes(N0.getNode())))
4877 // We can fold this node into a build_vector.
4878 unsigned VTBits = SVT.getSizeInBits();
4879 unsigned EVTBits = N0->getValueType(0).getScalarType().getSizeInBits();
4880 unsigned ShAmt = VTBits - EVTBits;
4881 SmallVector<SDValue, 8> Elts;
4882 unsigned NumElts = N0->getNumOperands();
4885 for (unsigned i=0; i != NumElts; ++i) {
4886 SDValue Op = N0->getOperand(i);
4887 if (Op->getOpcode() == ISD::UNDEF) {
4888 Elts.push_back(DAG.getUNDEF(SVT));
4892 ConstantSDNode *CurrentND = cast<ConstantSDNode>(Op);
4893 const APInt &C = APInt(VTBits, CurrentND->getAPIntValue().getZExtValue());
4894 if (Opcode == ISD::SIGN_EXTEND)
4895 Elts.push_back(DAG.getConstant(C.shl(ShAmt).ashr(ShAmt).getZExtValue(),
4898 Elts.push_back(DAG.getConstant(C.shl(ShAmt).lshr(ShAmt).getZExtValue(),
4902 return DAG.getNode(ISD::BUILD_VECTOR, DL, VT, Elts).getNode();
4905 // ExtendUsesToFormExtLoad - Trying to extend uses of a load to enable this:
4906 // "fold ({s|z|a}ext (load x)) -> ({s|z|a}ext (truncate ({s|z|a}extload x)))"
4907 // transformation. Returns true if extension are possible and the above
4908 // mentioned transformation is profitable.
4909 static bool ExtendUsesToFormExtLoad(SDNode *N, SDValue N0,
4911 SmallVectorImpl<SDNode *> &ExtendNodes,
4912 const TargetLowering &TLI) {
4913 bool HasCopyToRegUses = false;
4914 bool isTruncFree = TLI.isTruncateFree(N->getValueType(0), N0.getValueType());
4915 for (SDNode::use_iterator UI = N0.getNode()->use_begin(),
4916 UE = N0.getNode()->use_end();
4921 if (UI.getUse().getResNo() != N0.getResNo())
4923 // FIXME: Only extend SETCC N, N and SETCC N, c for now.
4924 if (ExtOpc != ISD::ANY_EXTEND && User->getOpcode() == ISD::SETCC) {
4925 ISD::CondCode CC = cast<CondCodeSDNode>(User->getOperand(2))->get();
4926 if (ExtOpc == ISD::ZERO_EXTEND && ISD::isSignedIntSetCC(CC))
4927 // Sign bits will be lost after a zext.
4930 for (unsigned i = 0; i != 2; ++i) {
4931 SDValue UseOp = User->getOperand(i);
4934 if (!isa<ConstantSDNode>(UseOp))
4939 ExtendNodes.push_back(User);
4942 // If truncates aren't free and there are users we can't
4943 // extend, it isn't worthwhile.
4946 // Remember if this value is live-out.
4947 if (User->getOpcode() == ISD::CopyToReg)
4948 HasCopyToRegUses = true;
4951 if (HasCopyToRegUses) {
4952 bool BothLiveOut = false;
4953 for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
4955 SDUse &Use = UI.getUse();
4956 if (Use.getResNo() == 0 && Use.getUser()->getOpcode() == ISD::CopyToReg) {
4962 // Both unextended and extended values are live out. There had better be
4963 // a good reason for the transformation.
4964 return ExtendNodes.size();
4969 void DAGCombiner::ExtendSetCCUses(const SmallVectorImpl<SDNode *> &SetCCs,
4970 SDValue Trunc, SDValue ExtLoad, SDLoc DL,
4971 ISD::NodeType ExtType) {
4972 // Extend SetCC uses if necessary.
4973 for (unsigned i = 0, e = SetCCs.size(); i != e; ++i) {
4974 SDNode *SetCC = SetCCs[i];
4975 SmallVector<SDValue, 4> Ops;
4977 for (unsigned j = 0; j != 2; ++j) {
4978 SDValue SOp = SetCC->getOperand(j);
4980 Ops.push_back(ExtLoad);
4982 Ops.push_back(DAG.getNode(ExtType, DL, ExtLoad->getValueType(0), SOp));
4985 Ops.push_back(SetCC->getOperand(2));
4986 CombineTo(SetCC, DAG.getNode(ISD::SETCC, DL, SetCC->getValueType(0), Ops));
4990 SDValue DAGCombiner::visitSIGN_EXTEND(SDNode *N) {
4991 SDValue N0 = N->getOperand(0);
4992 EVT VT = N->getValueType(0);
4994 if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
4996 return SDValue(Res, 0);
4998 // fold (sext (sext x)) -> (sext x)
4999 // fold (sext (aext x)) -> (sext x)
5000 if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
5001 return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT,
5004 if (N0.getOpcode() == ISD::TRUNCATE) {
5005 // fold (sext (truncate (load x))) -> (sext (smaller load x))
5006 // fold (sext (truncate (srl (load x), c))) -> (sext (smaller load (x+c/n)))
5007 SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
5008 if (NarrowLoad.getNode()) {
5009 SDNode* oye = N0.getNode()->getOperand(0).getNode();
5010 if (NarrowLoad.getNode() != N0.getNode()) {
5011 CombineTo(N0.getNode(), NarrowLoad);
5012 // CombineTo deleted the truncate, if needed, but not what's under it.
5015 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5018 // See if the value being truncated is already sign extended. If so, just
5019 // eliminate the trunc/sext pair.
5020 SDValue Op = N0.getOperand(0);
5021 unsigned OpBits = Op.getValueType().getScalarType().getSizeInBits();
5022 unsigned MidBits = N0.getValueType().getScalarType().getSizeInBits();
5023 unsigned DestBits = VT.getScalarType().getSizeInBits();
5024 unsigned NumSignBits = DAG.ComputeNumSignBits(Op);
5026 if (OpBits == DestBits) {
5027 // Op is i32, Mid is i8, and Dest is i32. If Op has more than 24 sign
5028 // bits, it is already ready.
5029 if (NumSignBits > DestBits-MidBits)
5031 } else if (OpBits < DestBits) {
5032 // Op is i32, Mid is i8, and Dest is i64. If Op has more than 24 sign
5033 // bits, just sext from i32.
5034 if (NumSignBits > OpBits-MidBits)
5035 return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, Op);
5037 // Op is i64, Mid is i8, and Dest is i32. If Op has more than 56 sign
5038 // bits, just truncate to i32.
5039 if (NumSignBits > OpBits-MidBits)
5040 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
5043 // fold (sext (truncate x)) -> (sextinreg x).
5044 if (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG,
5045 N0.getValueType())) {
5046 if (OpBits < DestBits)
5047 Op = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N0), VT, Op);
5048 else if (OpBits > DestBits)
5049 Op = DAG.getNode(ISD::TRUNCATE, SDLoc(N0), VT, Op);
5050 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, Op,
5051 DAG.getValueType(N0.getValueType()));
5055 // fold (sext (load x)) -> (sext (truncate (sextload x)))
5056 // None of the supported targets knows how to perform load and sign extend
5057 // on vectors in one instruction. We only perform this transformation on
5059 if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() &&
5060 ISD::isUNINDEXEDLoad(N0.getNode()) &&
5061 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
5062 TLI.isLoadExtLegal(ISD::SEXTLOAD, N0.getValueType()))) {
5063 bool DoXform = true;
5064 SmallVector<SDNode*, 4> SetCCs;
5065 if (!N0.hasOneUse())
5066 DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::SIGN_EXTEND, SetCCs, TLI);
5068 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5069 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
5071 LN0->getBasePtr(), N0.getValueType(),
5072 LN0->getMemOperand());
5073 CombineTo(N, ExtLoad);
5074 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
5075 N0.getValueType(), ExtLoad);
5076 CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
5077 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
5079 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5083 // fold (sext (sextload x)) -> (sext (truncate (sextload x)))
5084 // fold (sext ( extload x)) -> (sext (truncate (sextload x)))
5085 if ((ISD::isSEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) &&
5086 ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) {
5087 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5088 EVT MemVT = LN0->getMemoryVT();
5089 if ((!LegalOperations && !LN0->isVolatile()) ||
5090 TLI.isLoadExtLegal(ISD::SEXTLOAD, MemVT)) {
5091 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
5093 LN0->getBasePtr(), MemVT,
5094 LN0->getMemOperand());
5095 CombineTo(N, ExtLoad);
5096 CombineTo(N0.getNode(),
5097 DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
5098 N0.getValueType(), ExtLoad),
5099 ExtLoad.getValue(1));
5100 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5104 // fold (sext (and/or/xor (load x), cst)) ->
5105 // (and/or/xor (sextload x), (sext cst))
5106 if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR ||
5107 N0.getOpcode() == ISD::XOR) &&
5108 isa<LoadSDNode>(N0.getOperand(0)) &&
5109 N0.getOperand(1).getOpcode() == ISD::Constant &&
5110 TLI.isLoadExtLegal(ISD::SEXTLOAD, N0.getValueType()) &&
5111 (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) {
5112 LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0));
5113 if (LN0->getExtensionType() != ISD::ZEXTLOAD && LN0->isUnindexed()) {
5114 bool DoXform = true;
5115 SmallVector<SDNode*, 4> SetCCs;
5116 if (!N0.hasOneUse())
5117 DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0), ISD::SIGN_EXTEND,
5120 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(LN0), VT,
5121 LN0->getChain(), LN0->getBasePtr(),
5123 LN0->getMemOperand());
5124 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
5125 Mask = Mask.sext(VT.getSizeInBits());
5126 SDValue And = DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
5127 ExtLoad, DAG.getConstant(Mask, VT));
5128 SDValue Trunc = DAG.getNode(ISD::TRUNCATE,
5129 SDLoc(N0.getOperand(0)),
5130 N0.getOperand(0).getValueType(), ExtLoad);
5132 CombineTo(N0.getOperand(0).getNode(), Trunc, ExtLoad.getValue(1));
5133 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
5135 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5140 if (N0.getOpcode() == ISD::SETCC) {
5141 EVT N0VT = N0.getOperand(0).getValueType();
5142 // sext(setcc) -> sext_in_reg(vsetcc) for vectors.
5143 // Only do this before legalize for now.
5144 if (VT.isVector() && !LegalOperations &&
5145 TLI.getBooleanContents(N0VT) ==
5146 TargetLowering::ZeroOrNegativeOneBooleanContent) {
5147 // On some architectures (such as SSE/NEON/etc) the SETCC result type is
5148 // of the same size as the compared operands. Only optimize sext(setcc())
5149 // if this is the case.
5150 EVT SVT = getSetCCResultType(N0VT);
5152 // We know that the # elements of the results is the same as the
5153 // # elements of the compare (and the # elements of the compare result
5154 // for that matter). Check to see that they are the same size. If so,
5155 // we know that the element size of the sext'd result matches the
5156 // element size of the compare operands.
5157 if (VT.getSizeInBits() == SVT.getSizeInBits())
5158 return DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
5160 cast<CondCodeSDNode>(N0.getOperand(2))->get());
5162 // If the desired elements are smaller or larger than the source
5163 // elements we can use a matching integer vector type and then
5164 // truncate/sign extend
5165 EVT MatchingVectorType = N0VT.changeVectorElementTypeToInteger();
5166 if (SVT == MatchingVectorType) {
5167 SDValue VsetCC = DAG.getSetCC(SDLoc(N), MatchingVectorType,
5168 N0.getOperand(0), N0.getOperand(1),
5169 cast<CondCodeSDNode>(N0.getOperand(2))->get());
5170 return DAG.getSExtOrTrunc(VsetCC, SDLoc(N), VT);
5174 // sext(setcc x, y, cc) -> (select (setcc x, y, cc), -1, 0)
5175 unsigned ElementWidth = VT.getScalarType().getSizeInBits();
5177 DAG.getConstant(APInt::getAllOnesValue(ElementWidth), VT);
5179 SimplifySelectCC(SDLoc(N), N0.getOperand(0), N0.getOperand(1),
5180 NegOne, DAG.getConstant(0, VT),
5181 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
5182 if (SCC.getNode()) return SCC;
5184 if (!VT.isVector()) {
5185 EVT SetCCVT = getSetCCResultType(N0.getOperand(0).getValueType());
5186 if (!LegalOperations || TLI.isOperationLegal(ISD::SETCC, SetCCVT)) {
5188 ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
5189 SDValue SetCC = DAG.getSetCC(DL,
5191 N0.getOperand(0), N0.getOperand(1), CC);
5192 EVT SelectVT = getSetCCResultType(VT);
5193 return DAG.getSelect(DL, VT,
5194 DAG.getSExtOrTrunc(SetCC, DL, SelectVT),
5195 NegOne, DAG.getConstant(0, VT));
5201 // fold (sext x) -> (zext x) if the sign bit is known zero.
5202 if ((!LegalOperations || TLI.isOperationLegal(ISD::ZERO_EXTEND, VT)) &&
5203 DAG.SignBitIsZero(N0))
5204 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, N0);
5209 // isTruncateOf - If N is a truncate of some other value, return true, record
5210 // the value being truncated in Op and which of Op's bits are zero in KnownZero.
5211 // This function computes KnownZero to avoid a duplicated call to
5212 // computeKnownBits in the caller.
5213 static bool isTruncateOf(SelectionDAG &DAG, SDValue N, SDValue &Op,
5216 if (N->getOpcode() == ISD::TRUNCATE) {
5217 Op = N->getOperand(0);
5218 DAG.computeKnownBits(Op, KnownZero, KnownOne);
5222 if (N->getOpcode() != ISD::SETCC || N->getValueType(0) != MVT::i1 ||
5223 cast<CondCodeSDNode>(N->getOperand(2))->get() != ISD::SETNE)
5226 SDValue Op0 = N->getOperand(0);
5227 SDValue Op1 = N->getOperand(1);
5228 assert(Op0.getValueType() == Op1.getValueType());
5230 ConstantSDNode *COp0 = dyn_cast<ConstantSDNode>(Op0);
5231 ConstantSDNode *COp1 = dyn_cast<ConstantSDNode>(Op1);
5232 if (COp0 && COp0->isNullValue())
5234 else if (COp1 && COp1->isNullValue())
5239 DAG.computeKnownBits(Op, KnownZero, KnownOne);
5241 if (!(KnownZero | APInt(Op.getValueSizeInBits(), 1)).isAllOnesValue())
5247 SDValue DAGCombiner::visitZERO_EXTEND(SDNode *N) {
5248 SDValue N0 = N->getOperand(0);
5249 EVT VT = N->getValueType(0);
5251 if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
5253 return SDValue(Res, 0);
5255 // fold (zext (zext x)) -> (zext x)
5256 // fold (zext (aext x)) -> (zext x)
5257 if (N0.getOpcode() == ISD::ZERO_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
5258 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT,
5261 // fold (zext (truncate x)) -> (zext x) or
5262 // (zext (truncate x)) -> (truncate x)
5263 // This is valid when the truncated bits of x are already zero.
5264 // FIXME: We should extend this to work for vectors too.
5267 if (!VT.isVector() && isTruncateOf(DAG, N0, Op, KnownZero)) {
5268 APInt TruncatedBits =
5269 (Op.getValueSizeInBits() == N0.getValueSizeInBits()) ?
5270 APInt(Op.getValueSizeInBits(), 0) :
5271 APInt::getBitsSet(Op.getValueSizeInBits(),
5272 N0.getValueSizeInBits(),
5273 std::min(Op.getValueSizeInBits(),
5274 VT.getSizeInBits()));
5275 if (TruncatedBits == (KnownZero & TruncatedBits)) {
5276 if (VT.bitsGT(Op.getValueType()))
5277 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, Op);
5278 if (VT.bitsLT(Op.getValueType()))
5279 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
5285 // fold (zext (truncate (load x))) -> (zext (smaller load x))
5286 // fold (zext (truncate (srl (load x), c))) -> (zext (small load (x+c/n)))
5287 if (N0.getOpcode() == ISD::TRUNCATE) {
5288 SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
5289 if (NarrowLoad.getNode()) {
5290 SDNode* oye = N0.getNode()->getOperand(0).getNode();
5291 if (NarrowLoad.getNode() != N0.getNode()) {
5292 CombineTo(N0.getNode(), NarrowLoad);
5293 // CombineTo deleted the truncate, if needed, but not what's under it.
5296 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5300 // fold (zext (truncate x)) -> (and x, mask)
5301 if (N0.getOpcode() == ISD::TRUNCATE &&
5302 (!LegalOperations || TLI.isOperationLegal(ISD::AND, VT))) {
5304 // fold (zext (truncate (load x))) -> (zext (smaller load x))
5305 // fold (zext (truncate (srl (load x), c))) -> (zext (smaller load (x+c/n)))
5306 SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
5307 if (NarrowLoad.getNode()) {
5308 SDNode* oye = N0.getNode()->getOperand(0).getNode();
5309 if (NarrowLoad.getNode() != N0.getNode()) {
5310 CombineTo(N0.getNode(), NarrowLoad);
5311 // CombineTo deleted the truncate, if needed, but not what's under it.
5314 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5317 SDValue Op = N0.getOperand(0);
5318 if (Op.getValueType().bitsLT(VT)) {
5319 Op = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, Op);
5320 AddToWorklist(Op.getNode());
5321 } else if (Op.getValueType().bitsGT(VT)) {
5322 Op = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
5323 AddToWorklist(Op.getNode());
5325 return DAG.getZeroExtendInReg(Op, SDLoc(N),
5326 N0.getValueType().getScalarType());
5329 // Fold (zext (and (trunc x), cst)) -> (and x, cst),
5330 // if either of the casts is not free.
5331 if (N0.getOpcode() == ISD::AND &&
5332 N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
5333 N0.getOperand(1).getOpcode() == ISD::Constant &&
5334 (!TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(),
5335 N0.getValueType()) ||
5336 !TLI.isZExtFree(N0.getValueType(), VT))) {
5337 SDValue X = N0.getOperand(0).getOperand(0);
5338 if (X.getValueType().bitsLT(VT)) {
5339 X = DAG.getNode(ISD::ANY_EXTEND, SDLoc(X), VT, X);
5340 } else if (X.getValueType().bitsGT(VT)) {
5341 X = DAG.getNode(ISD::TRUNCATE, SDLoc(X), VT, X);
5343 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
5344 Mask = Mask.zext(VT.getSizeInBits());
5345 return DAG.getNode(ISD::AND, SDLoc(N), VT,
5346 X, DAG.getConstant(Mask, VT));
5349 // fold (zext (load x)) -> (zext (truncate (zextload x)))
5350 // None of the supported targets knows how to perform load and vector_zext
5351 // on vectors in one instruction. We only perform this transformation on
5353 if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() &&
5354 ISD::isUNINDEXEDLoad(N0.getNode()) &&
5355 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
5356 TLI.isLoadExtLegal(ISD::ZEXTLOAD, N0.getValueType()))) {
5357 bool DoXform = true;
5358 SmallVector<SDNode*, 4> SetCCs;
5359 if (!N0.hasOneUse())
5360 DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ZERO_EXTEND, SetCCs, TLI);
5362 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5363 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT,
5365 LN0->getBasePtr(), N0.getValueType(),
5366 LN0->getMemOperand());
5367 CombineTo(N, ExtLoad);
5368 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
5369 N0.getValueType(), ExtLoad);
5370 CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
5372 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
5374 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5378 // fold (zext (and/or/xor (load x), cst)) ->
5379 // (and/or/xor (zextload x), (zext cst))
5380 if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR ||
5381 N0.getOpcode() == ISD::XOR) &&
5382 isa<LoadSDNode>(N0.getOperand(0)) &&
5383 N0.getOperand(1).getOpcode() == ISD::Constant &&
5384 TLI.isLoadExtLegal(ISD::ZEXTLOAD, N0.getValueType()) &&
5385 (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) {
5386 LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0));
5387 if (LN0->getExtensionType() != ISD::SEXTLOAD && LN0->isUnindexed()) {
5388 bool DoXform = true;
5389 SmallVector<SDNode*, 4> SetCCs;
5390 if (!N0.hasOneUse())
5391 DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0), ISD::ZERO_EXTEND,
5394 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), VT,
5395 LN0->getChain(), LN0->getBasePtr(),
5397 LN0->getMemOperand());
5398 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
5399 Mask = Mask.zext(VT.getSizeInBits());
5400 SDValue And = DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
5401 ExtLoad, DAG.getConstant(Mask, VT));
5402 SDValue Trunc = DAG.getNode(ISD::TRUNCATE,
5403 SDLoc(N0.getOperand(0)),
5404 N0.getOperand(0).getValueType(), ExtLoad);
5406 CombineTo(N0.getOperand(0).getNode(), Trunc, ExtLoad.getValue(1));
5407 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
5409 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5414 // fold (zext (zextload x)) -> (zext (truncate (zextload x)))
5415 // fold (zext ( extload x)) -> (zext (truncate (zextload x)))
5416 if ((ISD::isZEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) &&
5417 ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) {
5418 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5419 EVT MemVT = LN0->getMemoryVT();
5420 if ((!LegalOperations && !LN0->isVolatile()) ||
5421 TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT)) {
5422 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT,
5424 LN0->getBasePtr(), MemVT,
5425 LN0->getMemOperand());
5426 CombineTo(N, ExtLoad);
5427 CombineTo(N0.getNode(),
5428 DAG.getNode(ISD::TRUNCATE, SDLoc(N0), N0.getValueType(),
5430 ExtLoad.getValue(1));
5431 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5435 if (N0.getOpcode() == ISD::SETCC) {
5436 if (!LegalOperations && VT.isVector() &&
5437 N0.getValueType().getVectorElementType() == MVT::i1) {
5438 EVT N0VT = N0.getOperand(0).getValueType();
5439 if (getSetCCResultType(N0VT) == N0.getValueType())
5442 // zext(setcc) -> (and (vsetcc), (1, 1, ...) for vectors.
5443 // Only do this before legalize for now.
5444 EVT EltVT = VT.getVectorElementType();
5445 SmallVector<SDValue,8> OneOps(VT.getVectorNumElements(),
5446 DAG.getConstant(1, EltVT));
5447 if (VT.getSizeInBits() == N0VT.getSizeInBits())
5448 // We know that the # elements of the results is the same as the
5449 // # elements of the compare (and the # elements of the compare result
5450 // for that matter). Check to see that they are the same size. If so,
5451 // we know that the element size of the sext'd result matches the
5452 // element size of the compare operands.
5453 return DAG.getNode(ISD::AND, SDLoc(N), VT,
5454 DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
5456 cast<CondCodeSDNode>(N0.getOperand(2))->get()),
5457 DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT,
5460 // If the desired elements are smaller or larger than the source
5461 // elements we can use a matching integer vector type and then
5462 // truncate/sign extend
5463 EVT MatchingElementType =
5464 EVT::getIntegerVT(*DAG.getContext(),
5465 N0VT.getScalarType().getSizeInBits());
5466 EVT MatchingVectorType =
5467 EVT::getVectorVT(*DAG.getContext(), MatchingElementType,
5468 N0VT.getVectorNumElements());
5470 DAG.getSetCC(SDLoc(N), MatchingVectorType, N0.getOperand(0),
5472 cast<CondCodeSDNode>(N0.getOperand(2))->get());
5473 return DAG.getNode(ISD::AND, SDLoc(N), VT,
5474 DAG.getSExtOrTrunc(VsetCC, SDLoc(N), VT),
5475 DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, OneOps));
5478 // zext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
5480 SimplifySelectCC(SDLoc(N), N0.getOperand(0), N0.getOperand(1),
5481 DAG.getConstant(1, VT), DAG.getConstant(0, VT),
5482 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
5483 if (SCC.getNode()) return SCC;
5486 // (zext (shl (zext x), cst)) -> (shl (zext x), cst)
5487 if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL) &&
5488 isa<ConstantSDNode>(N0.getOperand(1)) &&
5489 N0.getOperand(0).getOpcode() == ISD::ZERO_EXTEND &&
5491 SDValue ShAmt = N0.getOperand(1);
5492 unsigned ShAmtVal = cast<ConstantSDNode>(ShAmt)->getZExtValue();
5493 if (N0.getOpcode() == ISD::SHL) {
5494 SDValue InnerZExt = N0.getOperand(0);
5495 // If the original shl may be shifting out bits, do not perform this
5497 unsigned KnownZeroBits = InnerZExt.getValueType().getSizeInBits() -
5498 InnerZExt.getOperand(0).getValueType().getSizeInBits();
5499 if (ShAmtVal > KnownZeroBits)
5505 // Ensure that the shift amount is wide enough for the shifted value.
5506 if (VT.getSizeInBits() >= 256)
5507 ShAmt = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, ShAmt);
5509 return DAG.getNode(N0.getOpcode(), DL, VT,
5510 DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0)),
5517 SDValue DAGCombiner::visitANY_EXTEND(SDNode *N) {
5518 SDValue N0 = N->getOperand(0);
5519 EVT VT = N->getValueType(0);
5521 if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
5523 return SDValue(Res, 0);
5525 // fold (aext (aext x)) -> (aext x)
5526 // fold (aext (zext x)) -> (zext x)
5527 // fold (aext (sext x)) -> (sext x)
5528 if (N0.getOpcode() == ISD::ANY_EXTEND ||
5529 N0.getOpcode() == ISD::ZERO_EXTEND ||
5530 N0.getOpcode() == ISD::SIGN_EXTEND)
5531 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, N0.getOperand(0));
5533 // fold (aext (truncate (load x))) -> (aext (smaller load x))
5534 // fold (aext (truncate (srl (load x), c))) -> (aext (small load (x+c/n)))
5535 if (N0.getOpcode() == ISD::TRUNCATE) {
5536 SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
5537 if (NarrowLoad.getNode()) {
5538 SDNode* oye = N0.getNode()->getOperand(0).getNode();
5539 if (NarrowLoad.getNode() != N0.getNode()) {
5540 CombineTo(N0.getNode(), NarrowLoad);
5541 // CombineTo deleted the truncate, if needed, but not what's under it.
5544 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5548 // fold (aext (truncate x))
5549 if (N0.getOpcode() == ISD::TRUNCATE) {
5550 SDValue TruncOp = N0.getOperand(0);
5551 if (TruncOp.getValueType() == VT)
5552 return TruncOp; // x iff x size == zext size.
5553 if (TruncOp.getValueType().bitsGT(VT))
5554 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, TruncOp);
5555 return DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, TruncOp);
5558 // Fold (aext (and (trunc x), cst)) -> (and x, cst)
5559 // if the trunc is not free.
5560 if (N0.getOpcode() == ISD::AND &&
5561 N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
5562 N0.getOperand(1).getOpcode() == ISD::Constant &&
5563 !TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(),
5564 N0.getValueType())) {
5565 SDValue X = N0.getOperand(0).getOperand(0);
5566 if (X.getValueType().bitsLT(VT)) {
5567 X = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, X);
5568 } else if (X.getValueType().bitsGT(VT)) {
5569 X = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, X);
5571 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
5572 Mask = Mask.zext(VT.getSizeInBits());
5573 return DAG.getNode(ISD::AND, SDLoc(N), VT,
5574 X, DAG.getConstant(Mask, VT));
5577 // fold (aext (load x)) -> (aext (truncate (extload x)))
5578 // None of the supported targets knows how to perform load and any_ext
5579 // on vectors in one instruction. We only perform this transformation on
5581 if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() &&
5582 ISD::isUNINDEXEDLoad(N0.getNode()) &&
5583 TLI.isLoadExtLegal(ISD::EXTLOAD, N0.getValueType())) {
5584 bool DoXform = true;
5585 SmallVector<SDNode*, 4> SetCCs;
5586 if (!N0.hasOneUse())
5587 DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ANY_EXTEND, SetCCs, TLI);
5589 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5590 SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT,
5592 LN0->getBasePtr(), N0.getValueType(),
5593 LN0->getMemOperand());
5594 CombineTo(N, ExtLoad);
5595 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
5596 N0.getValueType(), ExtLoad);
5597 CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
5598 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
5600 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5604 // fold (aext (zextload x)) -> (aext (truncate (zextload x)))
5605 // fold (aext (sextload x)) -> (aext (truncate (sextload x)))
5606 // fold (aext ( extload x)) -> (aext (truncate (extload x)))
5607 if (N0.getOpcode() == ISD::LOAD &&
5608 !ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
5610 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5611 ISD::LoadExtType ExtType = LN0->getExtensionType();
5612 EVT MemVT = LN0->getMemoryVT();
5613 if (!LegalOperations || TLI.isLoadExtLegal(ExtType, MemVT)) {
5614 SDValue ExtLoad = DAG.getExtLoad(ExtType, SDLoc(N),
5615 VT, LN0->getChain(), LN0->getBasePtr(),
5616 MemVT, LN0->getMemOperand());
5617 CombineTo(N, ExtLoad);
5618 CombineTo(N0.getNode(),
5619 DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
5620 N0.getValueType(), ExtLoad),
5621 ExtLoad.getValue(1));
5622 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5626 if (N0.getOpcode() == ISD::SETCC) {
5628 // aext(setcc) -> vsetcc
5629 // aext(setcc) -> truncate(vsetcc)
5630 // aext(setcc) -> aext(vsetcc)
5631 // Only do this before legalize for now.
5632 if (VT.isVector() && !LegalOperations) {
5633 EVT N0VT = N0.getOperand(0).getValueType();
5634 // We know that the # elements of the results is the same as the
5635 // # elements of the compare (and the # elements of the compare result
5636 // for that matter). Check to see that they are the same size. If so,
5637 // we know that the element size of the sext'd result matches the
5638 // element size of the compare operands.
5639 if (VT.getSizeInBits() == N0VT.getSizeInBits())
5640 return DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
5642 cast<CondCodeSDNode>(N0.getOperand(2))->get());
5643 // If the desired elements are smaller or larger than the source
5644 // elements we can use a matching integer vector type and then
5645 // truncate/any extend
5647 EVT MatchingVectorType = N0VT.changeVectorElementTypeToInteger();
5649 DAG.getSetCC(SDLoc(N), MatchingVectorType, N0.getOperand(0),
5651 cast<CondCodeSDNode>(N0.getOperand(2))->get());
5652 return DAG.getAnyExtOrTrunc(VsetCC, SDLoc(N), VT);
5656 // aext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
5658 SimplifySelectCC(SDLoc(N), N0.getOperand(0), N0.getOperand(1),
5659 DAG.getConstant(1, VT), DAG.getConstant(0, VT),
5660 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
5668 /// GetDemandedBits - See if the specified operand can be simplified with the
5669 /// knowledge that only the bits specified by Mask are used. If so, return the
5670 /// simpler operand, otherwise return a null SDValue.
5671 SDValue DAGCombiner::GetDemandedBits(SDValue V, const APInt &Mask) {
5672 switch (V.getOpcode()) {
5674 case ISD::Constant: {
5675 const ConstantSDNode *CV = cast<ConstantSDNode>(V.getNode());
5676 assert(CV && "Const value should be ConstSDNode.");
5677 const APInt &CVal = CV->getAPIntValue();
5678 APInt NewVal = CVal & Mask;
5680 return DAG.getConstant(NewVal, V.getValueType());
5685 // If the LHS or RHS don't contribute bits to the or, drop them.
5686 if (DAG.MaskedValueIsZero(V.getOperand(0), Mask))
5687 return V.getOperand(1);
5688 if (DAG.MaskedValueIsZero(V.getOperand(1), Mask))
5689 return V.getOperand(0);
5692 // Only look at single-use SRLs.
5693 if (!V.getNode()->hasOneUse())
5695 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(V.getOperand(1))) {
5696 // See if we can recursively simplify the LHS.
5697 unsigned Amt = RHSC->getZExtValue();
5699 // Watch out for shift count overflow though.
5700 if (Amt >= Mask.getBitWidth()) break;
5701 APInt NewMask = Mask << Amt;
5702 SDValue SimplifyLHS = GetDemandedBits(V.getOperand(0), NewMask);
5703 if (SimplifyLHS.getNode())
5704 return DAG.getNode(ISD::SRL, SDLoc(V), V.getValueType(),
5705 SimplifyLHS, V.getOperand(1));
5711 /// ReduceLoadWidth - If the result of a wider load is shifted to right of N
5712 /// bits and then truncated to a narrower type and where N is a multiple
5713 /// of number of bits of the narrower type, transform it to a narrower load
5714 /// from address + N / num of bits of new type. If the result is to be
5715 /// extended, also fold the extension to form a extending load.
5716 SDValue DAGCombiner::ReduceLoadWidth(SDNode *N) {
5717 unsigned Opc = N->getOpcode();
5719 ISD::LoadExtType ExtType = ISD::NON_EXTLOAD;
5720 SDValue N0 = N->getOperand(0);
5721 EVT VT = N->getValueType(0);
5724 // This transformation isn't valid for vector loads.
5728 // Special case: SIGN_EXTEND_INREG is basically truncating to ExtVT then
5730 if (Opc == ISD::SIGN_EXTEND_INREG) {
5731 ExtType = ISD::SEXTLOAD;
5732 ExtVT = cast<VTSDNode>(N->getOperand(1))->getVT();
5733 } else if (Opc == ISD::SRL) {
5734 // Another special-case: SRL is basically zero-extending a narrower value.
5735 ExtType = ISD::ZEXTLOAD;
5737 ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1));
5738 if (!N01) return SDValue();
5739 ExtVT = EVT::getIntegerVT(*DAG.getContext(),
5740 VT.getSizeInBits() - N01->getZExtValue());
5742 if (LegalOperations && !TLI.isLoadExtLegal(ExtType, ExtVT))
5745 unsigned EVTBits = ExtVT.getSizeInBits();
5747 // Do not generate loads of non-round integer types since these can
5748 // be expensive (and would be wrong if the type is not byte sized).
5749 if (!ExtVT.isRound())
5753 if (N0.getOpcode() == ISD::SRL && N0.hasOneUse()) {
5754 if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
5755 ShAmt = N01->getZExtValue();
5756 // Is the shift amount a multiple of size of VT?
5757 if ((ShAmt & (EVTBits-1)) == 0) {
5758 N0 = N0.getOperand(0);
5759 // Is the load width a multiple of size of VT?
5760 if ((N0.getValueType().getSizeInBits() & (EVTBits-1)) != 0)
5764 // At this point, we must have a load or else we can't do the transform.
5765 if (!isa<LoadSDNode>(N0)) return SDValue();
5767 // Because a SRL must be assumed to *need* to zero-extend the high bits
5768 // (as opposed to anyext the high bits), we can't combine the zextload
5769 // lowering of SRL and an sextload.
5770 if (cast<LoadSDNode>(N0)->getExtensionType() == ISD::SEXTLOAD)
5773 // If the shift amount is larger than the input type then we're not
5774 // accessing any of the loaded bytes. If the load was a zextload/extload
5775 // then the result of the shift+trunc is zero/undef (handled elsewhere).
5776 if (ShAmt >= cast<LoadSDNode>(N0)->getMemoryVT().getSizeInBits())
5781 // If the load is shifted left (and the result isn't shifted back right),
5782 // we can fold the truncate through the shift.
5783 unsigned ShLeftAmt = 0;
5784 if (ShAmt == 0 && N0.getOpcode() == ISD::SHL && N0.hasOneUse() &&
5785 ExtVT == VT && TLI.isNarrowingProfitable(N0.getValueType(), VT)) {
5786 if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
5787 ShLeftAmt = N01->getZExtValue();
5788 N0 = N0.getOperand(0);
5792 // If we haven't found a load, we can't narrow it. Don't transform one with
5793 // multiple uses, this would require adding a new load.
5794 if (!isa<LoadSDNode>(N0) || !N0.hasOneUse())
5797 // Don't change the width of a volatile load.
5798 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5799 if (LN0->isVolatile())
5802 // Verify that we are actually reducing a load width here.
5803 if (LN0->getMemoryVT().getSizeInBits() < EVTBits)
5806 // For the transform to be legal, the load must produce only two values
5807 // (the value loaded and the chain). Don't transform a pre-increment
5808 // load, for example, which produces an extra value. Otherwise the
5809 // transformation is not equivalent, and the downstream logic to replace
5810 // uses gets things wrong.
5811 if (LN0->getNumValues() > 2)
5814 // If the load that we're shrinking is an extload and we're not just
5815 // discarding the extension we can't simply shrink the load. Bail.
5816 // TODO: It would be possible to merge the extensions in some cases.
5817 if (LN0->getExtensionType() != ISD::NON_EXTLOAD &&
5818 LN0->getMemoryVT().getSizeInBits() < ExtVT.getSizeInBits() + ShAmt)
5821 EVT PtrType = N0.getOperand(1).getValueType();
5823 if (PtrType == MVT::Untyped || PtrType.isExtended())
5824 // It's not possible to generate a constant of extended or untyped type.
5827 // For big endian targets, we need to adjust the offset to the pointer to
5828 // load the correct bytes.
5829 if (TLI.isBigEndian()) {
5830 unsigned LVTStoreBits = LN0->getMemoryVT().getStoreSizeInBits();
5831 unsigned EVTStoreBits = ExtVT.getStoreSizeInBits();
5832 ShAmt = LVTStoreBits - EVTStoreBits - ShAmt;
5835 uint64_t PtrOff = ShAmt / 8;
5836 unsigned NewAlign = MinAlign(LN0->getAlignment(), PtrOff);
5837 SDValue NewPtr = DAG.getNode(ISD::ADD, SDLoc(LN0),
5838 PtrType, LN0->getBasePtr(),
5839 DAG.getConstant(PtrOff, PtrType));
5840 AddToWorklist(NewPtr.getNode());
5843 if (ExtType == ISD::NON_EXTLOAD)
5844 Load = DAG.getLoad(VT, SDLoc(N0), LN0->getChain(), NewPtr,
5845 LN0->getPointerInfo().getWithOffset(PtrOff),
5846 LN0->isVolatile(), LN0->isNonTemporal(),
5847 LN0->isInvariant(), NewAlign, LN0->getAAInfo());
5849 Load = DAG.getExtLoad(ExtType, SDLoc(N0), VT, LN0->getChain(),NewPtr,
5850 LN0->getPointerInfo().getWithOffset(PtrOff),
5851 ExtVT, LN0->isVolatile(), LN0->isNonTemporal(),
5852 LN0->isInvariant(), NewAlign, LN0->getAAInfo());
5854 // Replace the old load's chain with the new load's chain.
5855 WorklistRemover DeadNodes(*this);
5856 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1));
5858 // Shift the result left, if we've swallowed a left shift.
5859 SDValue Result = Load;
5860 if (ShLeftAmt != 0) {
5861 EVT ShImmTy = getShiftAmountTy(Result.getValueType());
5862 if (!isUIntN(ShImmTy.getSizeInBits(), ShLeftAmt))
5864 // If the shift amount is as large as the result size (but, presumably,
5865 // no larger than the source) then the useful bits of the result are
5866 // zero; we can't simply return the shortened shift, because the result
5867 // of that operation is undefined.
5868 if (ShLeftAmt >= VT.getSizeInBits())
5869 Result = DAG.getConstant(0, VT);
5871 Result = DAG.getNode(ISD::SHL, SDLoc(N0), VT,
5872 Result, DAG.getConstant(ShLeftAmt, ShImmTy));
5875 // Return the new loaded value.
5879 SDValue DAGCombiner::visitSIGN_EXTEND_INREG(SDNode *N) {
5880 SDValue N0 = N->getOperand(0);
5881 SDValue N1 = N->getOperand(1);
5882 EVT VT = N->getValueType(0);
5883 EVT EVT = cast<VTSDNode>(N1)->getVT();
5884 unsigned VTBits = VT.getScalarType().getSizeInBits();
5885 unsigned EVTBits = EVT.getScalarType().getSizeInBits();
5887 // fold (sext_in_reg c1) -> c1
5888 if (isa<ConstantSDNode>(N0) || N0.getOpcode() == ISD::UNDEF)
5889 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, N0, N1);
5891 // If the input is already sign extended, just drop the extension.
5892 if (DAG.ComputeNumSignBits(N0) >= VTBits-EVTBits+1)
5895 // fold (sext_in_reg (sext_in_reg x, VT2), VT1) -> (sext_in_reg x, minVT) pt2
5896 if (N0.getOpcode() == ISD::SIGN_EXTEND_INREG &&
5897 EVT.bitsLT(cast<VTSDNode>(N0.getOperand(1))->getVT()))
5898 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
5899 N0.getOperand(0), N1);
5901 // fold (sext_in_reg (sext x)) -> (sext x)
5902 // fold (sext_in_reg (aext x)) -> (sext x)
5903 // if x is small enough.
5904 if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND) {
5905 SDValue N00 = N0.getOperand(0);
5906 if (N00.getValueType().getScalarType().getSizeInBits() <= EVTBits &&
5907 (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND, VT)))
5908 return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, N00, N1);
5911 // fold (sext_in_reg x) -> (zext_in_reg x) if the sign bit is known zero.
5912 if (DAG.MaskedValueIsZero(N0, APInt::getBitsSet(VTBits, EVTBits-1, EVTBits)))
5913 return DAG.getZeroExtendInReg(N0, SDLoc(N), EVT);
5915 // fold operands of sext_in_reg based on knowledge that the top bits are not
5917 if (SimplifyDemandedBits(SDValue(N, 0)))
5918 return SDValue(N, 0);
5920 // fold (sext_in_reg (load x)) -> (smaller sextload x)
5921 // fold (sext_in_reg (srl (load x), c)) -> (smaller sextload (x+c/evtbits))
5922 SDValue NarrowLoad = ReduceLoadWidth(N);
5923 if (NarrowLoad.getNode())
5926 // fold (sext_in_reg (srl X, 24), i8) -> (sra X, 24)
5927 // fold (sext_in_reg (srl X, 23), i8) -> (sra X, 23) iff possible.
5928 // We already fold "(sext_in_reg (srl X, 25), i8) -> srl X, 25" above.
5929 if (N0.getOpcode() == ISD::SRL) {
5930 if (ConstantSDNode *ShAmt = dyn_cast<ConstantSDNode>(N0.getOperand(1)))
5931 if (ShAmt->getZExtValue()+EVTBits <= VTBits) {
5932 // We can turn this into an SRA iff the input to the SRL is already sign
5934 unsigned InSignBits = DAG.ComputeNumSignBits(N0.getOperand(0));
5935 if (VTBits-(ShAmt->getZExtValue()+EVTBits) < InSignBits)
5936 return DAG.getNode(ISD::SRA, SDLoc(N), VT,
5937 N0.getOperand(0), N0.getOperand(1));
5941 // fold (sext_inreg (extload x)) -> (sextload x)
5942 if (ISD::isEXTLoad(N0.getNode()) &&
5943 ISD::isUNINDEXEDLoad(N0.getNode()) &&
5944 EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
5945 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
5946 TLI.isLoadExtLegal(ISD::SEXTLOAD, EVT))) {
5947 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5948 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
5950 LN0->getBasePtr(), EVT,
5951 LN0->getMemOperand());
5952 CombineTo(N, ExtLoad);
5953 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
5954 AddToWorklist(ExtLoad.getNode());
5955 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5957 // fold (sext_inreg (zextload x)) -> (sextload x) iff load has one use
5958 if (ISD::isZEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
5960 EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
5961 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
5962 TLI.isLoadExtLegal(ISD::SEXTLOAD, EVT))) {
5963 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5964 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
5966 LN0->getBasePtr(), EVT,
5967 LN0->getMemOperand());
5968 CombineTo(N, ExtLoad);
5969 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
5970 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5973 // Form (sext_inreg (bswap >> 16)) or (sext_inreg (rotl (bswap) 16))
5974 if (EVTBits <= 16 && N0.getOpcode() == ISD::OR) {
5975 SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0),
5976 N0.getOperand(1), false);
5977 if (BSwap.getNode())
5978 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
5982 // Fold a sext_inreg of a build_vector of ConstantSDNodes or undefs
5983 // into a build_vector.
5984 if (ISD::isBuildVectorOfConstantSDNodes(N0.getNode())) {
5985 SmallVector<SDValue, 8> Elts;
5986 unsigned NumElts = N0->getNumOperands();
5987 unsigned ShAmt = VTBits - EVTBits;
5989 for (unsigned i = 0; i != NumElts; ++i) {
5990 SDValue Op = N0->getOperand(i);
5991 if (Op->getOpcode() == ISD::UNDEF) {
5996 ConstantSDNode *CurrentND = cast<ConstantSDNode>(Op);
5997 const APInt &C = APInt(VTBits, CurrentND->getAPIntValue().getZExtValue());
5998 Elts.push_back(DAG.getConstant(C.shl(ShAmt).ashr(ShAmt).getZExtValue(),
5999 Op.getValueType()));
6002 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, Elts);
6008 SDValue DAGCombiner::visitTRUNCATE(SDNode *N) {
6009 SDValue N0 = N->getOperand(0);
6010 EVT VT = N->getValueType(0);
6011 bool isLE = TLI.isLittleEndian();
6014 if (N0.getValueType() == N->getValueType(0))
6016 // fold (truncate c1) -> c1
6017 if (isa<ConstantSDNode>(N0))
6018 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0);
6019 // fold (truncate (truncate x)) -> (truncate x)
6020 if (N0.getOpcode() == ISD::TRUNCATE)
6021 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0));
6022 // fold (truncate (ext x)) -> (ext x) or (truncate x) or x
6023 if (N0.getOpcode() == ISD::ZERO_EXTEND ||
6024 N0.getOpcode() == ISD::SIGN_EXTEND ||
6025 N0.getOpcode() == ISD::ANY_EXTEND) {
6026 if (N0.getOperand(0).getValueType().bitsLT(VT))
6027 // if the source is smaller than the dest, we still need an extend
6028 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
6030 if (N0.getOperand(0).getValueType().bitsGT(VT))
6031 // if the source is larger than the dest, than we just need the truncate
6032 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0));
6033 // if the source and dest are the same type, we can drop both the extend
6034 // and the truncate.
6035 return N0.getOperand(0);
6038 // Fold extract-and-trunc into a narrow extract. For example:
6039 // i64 x = EXTRACT_VECTOR_ELT(v2i64 val, i32 1)
6040 // i32 y = TRUNCATE(i64 x)
6042 // v16i8 b = BITCAST (v2i64 val)
6043 // i8 x = EXTRACT_VECTOR_ELT(v16i8 b, i32 8)
6045 // Note: We only run this optimization after type legalization (which often
6046 // creates this pattern) and before operation legalization after which
6047 // we need to be more careful about the vector instructions that we generate.
6048 if (N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
6049 LegalTypes && !LegalOperations && N0->hasOneUse() && VT != MVT::i1) {
6051 EVT VecTy = N0.getOperand(0).getValueType();
6052 EVT ExTy = N0.getValueType();
6053 EVT TrTy = N->getValueType(0);
6055 unsigned NumElem = VecTy.getVectorNumElements();
6056 unsigned SizeRatio = ExTy.getSizeInBits()/TrTy.getSizeInBits();
6058 EVT NVT = EVT::getVectorVT(*DAG.getContext(), TrTy, SizeRatio * NumElem);
6059 assert(NVT.getSizeInBits() == VecTy.getSizeInBits() && "Invalid Size");
6061 SDValue EltNo = N0->getOperand(1);
6062 if (isa<ConstantSDNode>(EltNo) && isTypeLegal(NVT)) {
6063 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
6064 EVT IndexTy = TLI.getVectorIdxTy();
6065 int Index = isLE ? (Elt*SizeRatio) : (Elt*SizeRatio + (SizeRatio-1));
6067 SDValue V = DAG.getNode(ISD::BITCAST, SDLoc(N),
6068 NVT, N0.getOperand(0));
6070 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT,
6072 DAG.getConstant(Index, IndexTy));
6076 // trunc (select c, a, b) -> select c, (trunc a), (trunc b)
6077 if (N0.getOpcode() == ISD::SELECT) {
6078 EVT SrcVT = N0.getValueType();
6079 if ((!LegalOperations || TLI.isOperationLegal(ISD::SELECT, SrcVT)) &&
6080 TLI.isTruncateFree(SrcVT, VT)) {
6082 SDValue Cond = N0.getOperand(0);
6083 SDValue TruncOp0 = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(1));
6084 SDValue TruncOp1 = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(2));
6085 return DAG.getNode(ISD::SELECT, SDLoc(N), VT, Cond, TruncOp0, TruncOp1);
6089 // Fold a series of buildvector, bitcast, and truncate if possible.
6091 // (2xi32 trunc (bitcast ((4xi32)buildvector x, x, y, y) 2xi64)) to
6092 // (2xi32 (buildvector x, y)).
6093 if (Level == AfterLegalizeVectorOps && VT.isVector() &&
6094 N0.getOpcode() == ISD::BITCAST && N0.hasOneUse() &&
6095 N0.getOperand(0).getOpcode() == ISD::BUILD_VECTOR &&
6096 N0.getOperand(0).hasOneUse()) {
6098 SDValue BuildVect = N0.getOperand(0);
6099 EVT BuildVectEltTy = BuildVect.getValueType().getVectorElementType();
6100 EVT TruncVecEltTy = VT.getVectorElementType();
6102 // Check that the element types match.
6103 if (BuildVectEltTy == TruncVecEltTy) {
6104 // Now we only need to compute the offset of the truncated elements.
6105 unsigned BuildVecNumElts = BuildVect.getNumOperands();
6106 unsigned TruncVecNumElts = VT.getVectorNumElements();
6107 unsigned TruncEltOffset = BuildVecNumElts / TruncVecNumElts;
6109 assert((BuildVecNumElts % TruncVecNumElts) == 0 &&
6110 "Invalid number of elements");
6112 SmallVector<SDValue, 8> Opnds;
6113 for (unsigned i = 0, e = BuildVecNumElts; i != e; i += TruncEltOffset)
6114 Opnds.push_back(BuildVect.getOperand(i));
6116 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, Opnds);
6120 // See if we can simplify the input to this truncate through knowledge that
6121 // only the low bits are being used.
6122 // For example "trunc (or (shl x, 8), y)" // -> trunc y
6123 // Currently we only perform this optimization on scalars because vectors
6124 // may have different active low bits.
6125 if (!VT.isVector()) {
6127 GetDemandedBits(N0, APInt::getLowBitsSet(N0.getValueSizeInBits(),
6128 VT.getSizeInBits()));
6129 if (Shorter.getNode())
6130 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Shorter);
6132 // fold (truncate (load x)) -> (smaller load x)
6133 // fold (truncate (srl (load x), c)) -> (smaller load (x+c/evtbits))
6134 if (!LegalTypes || TLI.isTypeDesirableForOp(N0.getOpcode(), VT)) {
6135 SDValue Reduced = ReduceLoadWidth(N);
6136 if (Reduced.getNode())
6138 // Handle the case where the load remains an extending load even
6139 // after truncation.
6140 if (N0.hasOneUse() && ISD::isUNINDEXEDLoad(N0.getNode())) {
6141 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6142 if (!LN0->isVolatile() &&
6143 LN0->getMemoryVT().getStoreSizeInBits() < VT.getSizeInBits()) {
6144 SDValue NewLoad = DAG.getExtLoad(LN0->getExtensionType(), SDLoc(LN0),
6145 VT, LN0->getChain(), LN0->getBasePtr(),
6147 LN0->getMemOperand());
6148 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLoad.getValue(1));
6153 // fold (trunc (concat ... x ...)) -> (concat ..., (trunc x), ...)),
6154 // where ... are all 'undef'.
6155 if (N0.getOpcode() == ISD::CONCAT_VECTORS && !LegalTypes) {
6156 SmallVector<EVT, 8> VTs;
6159 unsigned NumDefs = 0;
6161 for (unsigned i = 0, e = N0.getNumOperands(); i != e; ++i) {
6162 SDValue X = N0.getOperand(i);
6163 if (X.getOpcode() != ISD::UNDEF) {
6168 // Stop if more than one members are non-undef.
6171 VTs.push_back(EVT::getVectorVT(*DAG.getContext(),
6172 VT.getVectorElementType(),
6173 X.getValueType().getVectorNumElements()));
6177 return DAG.getUNDEF(VT);
6180 assert(V.getNode() && "The single defined operand is empty!");
6181 SmallVector<SDValue, 8> Opnds;
6182 for (unsigned i = 0, e = VTs.size(); i != e; ++i) {
6184 Opnds.push_back(DAG.getUNDEF(VTs[i]));
6187 SDValue NV = DAG.getNode(ISD::TRUNCATE, SDLoc(V), VTs[i], V);
6188 AddToWorklist(NV.getNode());
6189 Opnds.push_back(NV);
6191 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Opnds);
6195 // Simplify the operands using demanded-bits information.
6196 if (!VT.isVector() &&
6197 SimplifyDemandedBits(SDValue(N, 0)))
6198 return SDValue(N, 0);
6203 static SDNode *getBuildPairElt(SDNode *N, unsigned i) {
6204 SDValue Elt = N->getOperand(i);
6205 if (Elt.getOpcode() != ISD::MERGE_VALUES)
6206 return Elt.getNode();
6207 return Elt.getOperand(Elt.getResNo()).getNode();
6210 /// CombineConsecutiveLoads - build_pair (load, load) -> load
6211 /// if load locations are consecutive.
6212 SDValue DAGCombiner::CombineConsecutiveLoads(SDNode *N, EVT VT) {
6213 assert(N->getOpcode() == ISD::BUILD_PAIR);
6215 LoadSDNode *LD1 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 0));
6216 LoadSDNode *LD2 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 1));
6217 if (!LD1 || !LD2 || !ISD::isNON_EXTLoad(LD1) || !LD1->hasOneUse() ||
6218 LD1->getAddressSpace() != LD2->getAddressSpace())
6220 EVT LD1VT = LD1->getValueType(0);
6222 if (ISD::isNON_EXTLoad(LD2) &&
6224 // If both are volatile this would reduce the number of volatile loads.
6225 // If one is volatile it might be ok, but play conservative and bail out.
6226 !LD1->isVolatile() &&
6227 !LD2->isVolatile() &&
6228 DAG.isConsecutiveLoad(LD2, LD1, LD1VT.getSizeInBits()/8, 1)) {
6229 unsigned Align = LD1->getAlignment();
6230 unsigned NewAlign = TLI.getDataLayout()->
6231 getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
6233 if (NewAlign <= Align &&
6234 (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT)))
6235 return DAG.getLoad(VT, SDLoc(N), LD1->getChain(),
6236 LD1->getBasePtr(), LD1->getPointerInfo(),
6237 false, false, false, Align);
6243 SDValue DAGCombiner::visitBITCAST(SDNode *N) {
6244 SDValue N0 = N->getOperand(0);
6245 EVT VT = N->getValueType(0);
6247 // If the input is a BUILD_VECTOR with all constant elements, fold this now.
6248 // Only do this before legalize, since afterward the target may be depending
6249 // on the bitconvert.
6250 // First check to see if this is all constant.
6252 N0.getOpcode() == ISD::BUILD_VECTOR && N0.getNode()->hasOneUse() &&
6254 bool isSimple = cast<BuildVectorSDNode>(N0)->isConstant();
6256 EVT DestEltVT = N->getValueType(0).getVectorElementType();
6257 assert(!DestEltVT.isVector() &&
6258 "Element type of vector ValueType must not be vector!");
6260 return ConstantFoldBITCASTofBUILD_VECTOR(N0.getNode(), DestEltVT);
6263 // If the input is a constant, let getNode fold it.
6264 if (isa<ConstantSDNode>(N0) || isa<ConstantFPSDNode>(N0)) {
6265 SDValue Res = DAG.getNode(ISD::BITCAST, SDLoc(N), VT, N0);
6266 if (Res.getNode() != N) {
6267 if (!LegalOperations ||
6268 TLI.isOperationLegal(Res.getNode()->getOpcode(), VT))
6271 // Folding it resulted in an illegal node, and it's too late to
6272 // do that. Clean up the old node and forego the transformation.
6273 // Ideally this won't happen very often, because instcombine
6274 // and the earlier dagcombine runs (where illegal nodes are
6275 // permitted) should have folded most of them already.
6276 deleteAndRecombine(Res.getNode());
6280 // (conv (conv x, t1), t2) -> (conv x, t2)
6281 if (N0.getOpcode() == ISD::BITCAST)
6282 return DAG.getNode(ISD::BITCAST, SDLoc(N), VT,
6285 // fold (conv (load x)) -> (load (conv*)x)
6286 // If the resultant load doesn't need a higher alignment than the original!
6287 if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
6288 // Do not change the width of a volatile load.
6289 !cast<LoadSDNode>(N0)->isVolatile() &&
6290 // Do not remove the cast if the types differ in endian layout.
6291 TLI.hasBigEndianPartOrdering(N0.getValueType()) ==
6292 TLI.hasBigEndianPartOrdering(VT) &&
6293 (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT)) &&
6294 TLI.isLoadBitCastBeneficial(N0.getValueType(), VT)) {
6295 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6296 unsigned Align = TLI.getDataLayout()->
6297 getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
6298 unsigned OrigAlign = LN0->getAlignment();
6300 if (Align <= OrigAlign) {
6301 SDValue Load = DAG.getLoad(VT, SDLoc(N), LN0->getChain(),
6302 LN0->getBasePtr(), LN0->getPointerInfo(),
6303 LN0->isVolatile(), LN0->isNonTemporal(),
6304 LN0->isInvariant(), OrigAlign,
6306 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1));
6311 // fold (bitconvert (fneg x)) -> (xor (bitconvert x), signbit)
6312 // fold (bitconvert (fabs x)) -> (and (bitconvert x), (not signbit))
6313 // This often reduces constant pool loads.
6314 if (((N0.getOpcode() == ISD::FNEG && !TLI.isFNegFree(N0.getValueType())) ||
6315 (N0.getOpcode() == ISD::FABS && !TLI.isFAbsFree(N0.getValueType()))) &&
6316 N0.getNode()->hasOneUse() && VT.isInteger() &&
6317 !VT.isVector() && !N0.getValueType().isVector()) {
6318 SDValue NewConv = DAG.getNode(ISD::BITCAST, SDLoc(N0), VT,
6320 AddToWorklist(NewConv.getNode());
6322 APInt SignBit = APInt::getSignBit(VT.getSizeInBits());
6323 if (N0.getOpcode() == ISD::FNEG)
6324 return DAG.getNode(ISD::XOR, SDLoc(N), VT,
6325 NewConv, DAG.getConstant(SignBit, VT));
6326 assert(N0.getOpcode() == ISD::FABS);
6327 return DAG.getNode(ISD::AND, SDLoc(N), VT,
6328 NewConv, DAG.getConstant(~SignBit, VT));
6331 // fold (bitconvert (fcopysign cst, x)) ->
6332 // (or (and (bitconvert x), sign), (and cst, (not sign)))
6333 // Note that we don't handle (copysign x, cst) because this can always be
6334 // folded to an fneg or fabs.
6335 if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse() &&
6336 isa<ConstantFPSDNode>(N0.getOperand(0)) &&
6337 VT.isInteger() && !VT.isVector()) {
6338 unsigned OrigXWidth = N0.getOperand(1).getValueType().getSizeInBits();
6339 EVT IntXVT = EVT::getIntegerVT(*DAG.getContext(), OrigXWidth);
6340 if (isTypeLegal(IntXVT)) {
6341 SDValue X = DAG.getNode(ISD::BITCAST, SDLoc(N0),
6342 IntXVT, N0.getOperand(1));
6343 AddToWorklist(X.getNode());
6345 // If X has a different width than the result/lhs, sext it or truncate it.
6346 unsigned VTWidth = VT.getSizeInBits();
6347 if (OrigXWidth < VTWidth) {
6348 X = DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, X);
6349 AddToWorklist(X.getNode());
6350 } else if (OrigXWidth > VTWidth) {
6351 // To get the sign bit in the right place, we have to shift it right
6352 // before truncating.
6353 X = DAG.getNode(ISD::SRL, SDLoc(X),
6354 X.getValueType(), X,
6355 DAG.getConstant(OrigXWidth-VTWidth, X.getValueType()));
6356 AddToWorklist(X.getNode());
6357 X = DAG.getNode(ISD::TRUNCATE, SDLoc(X), VT, X);
6358 AddToWorklist(X.getNode());
6361 APInt SignBit = APInt::getSignBit(VT.getSizeInBits());
6362 X = DAG.getNode(ISD::AND, SDLoc(X), VT,
6363 X, DAG.getConstant(SignBit, VT));
6364 AddToWorklist(X.getNode());
6366 SDValue Cst = DAG.getNode(ISD::BITCAST, SDLoc(N0),
6367 VT, N0.getOperand(0));
6368 Cst = DAG.getNode(ISD::AND, SDLoc(Cst), VT,
6369 Cst, DAG.getConstant(~SignBit, VT));
6370 AddToWorklist(Cst.getNode());
6372 return DAG.getNode(ISD::OR, SDLoc(N), VT, X, Cst);
6376 // bitconvert(build_pair(ld, ld)) -> ld iff load locations are consecutive.
6377 if (N0.getOpcode() == ISD::BUILD_PAIR) {
6378 SDValue CombineLD = CombineConsecutiveLoads(N0.getNode(), VT);
6379 if (CombineLD.getNode())
6386 SDValue DAGCombiner::visitBUILD_PAIR(SDNode *N) {
6387 EVT VT = N->getValueType(0);
6388 return CombineConsecutiveLoads(N, VT);
6391 /// ConstantFoldBITCASTofBUILD_VECTOR - We know that BV is a build_vector
6392 /// node with Constant, ConstantFP or Undef operands. DstEltVT indicates the
6393 /// destination element value type.
6394 SDValue DAGCombiner::
6395 ConstantFoldBITCASTofBUILD_VECTOR(SDNode *BV, EVT DstEltVT) {
6396 EVT SrcEltVT = BV->getValueType(0).getVectorElementType();
6398 // If this is already the right type, we're done.
6399 if (SrcEltVT == DstEltVT) return SDValue(BV, 0);
6401 unsigned SrcBitSize = SrcEltVT.getSizeInBits();
6402 unsigned DstBitSize = DstEltVT.getSizeInBits();
6404 // If this is a conversion of N elements of one type to N elements of another
6405 // type, convert each element. This handles FP<->INT cases.
6406 if (SrcBitSize == DstBitSize) {
6407 EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT,
6408 BV->getValueType(0).getVectorNumElements());
6410 // Due to the FP element handling below calling this routine recursively,
6411 // we can end up with a scalar-to-vector node here.
6412 if (BV->getOpcode() == ISD::SCALAR_TO_VECTOR)
6413 return DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(BV), VT,
6414 DAG.getNode(ISD::BITCAST, SDLoc(BV),
6415 DstEltVT, BV->getOperand(0)));
6417 SmallVector<SDValue, 8> Ops;
6418 for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) {
6419 SDValue Op = BV->getOperand(i);
6420 // If the vector element type is not legal, the BUILD_VECTOR operands
6421 // are promoted and implicitly truncated. Make that explicit here.
6422 if (Op.getValueType() != SrcEltVT)
6423 Op = DAG.getNode(ISD::TRUNCATE, SDLoc(BV), SrcEltVT, Op);
6424 Ops.push_back(DAG.getNode(ISD::BITCAST, SDLoc(BV),
6426 AddToWorklist(Ops.back().getNode());
6428 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(BV), VT, Ops);
6431 // Otherwise, we're growing or shrinking the elements. To avoid having to
6432 // handle annoying details of growing/shrinking FP values, we convert them to
6434 if (SrcEltVT.isFloatingPoint()) {
6435 // Convert the input float vector to a int vector where the elements are the
6437 assert((SrcEltVT == MVT::f32 || SrcEltVT == MVT::f64) && "Unknown FP VT!");
6438 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), SrcEltVT.getSizeInBits());
6439 BV = ConstantFoldBITCASTofBUILD_VECTOR(BV, IntVT).getNode();
6443 // Now we know the input is an integer vector. If the output is a FP type,
6444 // convert to integer first, then to FP of the right size.
6445 if (DstEltVT.isFloatingPoint()) {
6446 assert((DstEltVT == MVT::f32 || DstEltVT == MVT::f64) && "Unknown FP VT!");
6447 EVT TmpVT = EVT::getIntegerVT(*DAG.getContext(), DstEltVT.getSizeInBits());
6448 SDNode *Tmp = ConstantFoldBITCASTofBUILD_VECTOR(BV, TmpVT).getNode();
6450 // Next, convert to FP elements of the same size.
6451 return ConstantFoldBITCASTofBUILD_VECTOR(Tmp, DstEltVT);
6454 // Okay, we know the src/dst types are both integers of differing types.
6455 // Handling growing first.
6456 assert(SrcEltVT.isInteger() && DstEltVT.isInteger());
6457 if (SrcBitSize < DstBitSize) {
6458 unsigned NumInputsPerOutput = DstBitSize/SrcBitSize;
6460 SmallVector<SDValue, 8> Ops;
6461 for (unsigned i = 0, e = BV->getNumOperands(); i != e;
6462 i += NumInputsPerOutput) {
6463 bool isLE = TLI.isLittleEndian();
6464 APInt NewBits = APInt(DstBitSize, 0);
6465 bool EltIsUndef = true;
6466 for (unsigned j = 0; j != NumInputsPerOutput; ++j) {
6467 // Shift the previously computed bits over.
6468 NewBits <<= SrcBitSize;
6469 SDValue Op = BV->getOperand(i+ (isLE ? (NumInputsPerOutput-j-1) : j));
6470 if (Op.getOpcode() == ISD::UNDEF) continue;
6473 NewBits |= cast<ConstantSDNode>(Op)->getAPIntValue().
6474 zextOrTrunc(SrcBitSize).zext(DstBitSize);
6478 Ops.push_back(DAG.getUNDEF(DstEltVT));
6480 Ops.push_back(DAG.getConstant(NewBits, DstEltVT));
6483 EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT, Ops.size());
6484 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(BV), VT, Ops);
6487 // Finally, this must be the case where we are shrinking elements: each input
6488 // turns into multiple outputs.
6489 bool isS2V = ISD::isScalarToVector(BV);
6490 unsigned NumOutputsPerInput = SrcBitSize/DstBitSize;
6491 EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT,
6492 NumOutputsPerInput*BV->getNumOperands());
6493 SmallVector<SDValue, 8> Ops;
6495 for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) {
6496 if (BV->getOperand(i).getOpcode() == ISD::UNDEF) {
6497 for (unsigned j = 0; j != NumOutputsPerInput; ++j)
6498 Ops.push_back(DAG.getUNDEF(DstEltVT));
6502 APInt OpVal = cast<ConstantSDNode>(BV->getOperand(i))->
6503 getAPIntValue().zextOrTrunc(SrcBitSize);
6505 for (unsigned j = 0; j != NumOutputsPerInput; ++j) {
6506 APInt ThisVal = OpVal.trunc(DstBitSize);
6507 Ops.push_back(DAG.getConstant(ThisVal, DstEltVT));
6508 if (isS2V && i == 0 && j == 0 && ThisVal.zext(SrcBitSize) == OpVal)
6509 // Simply turn this into a SCALAR_TO_VECTOR of the new type.
6510 return DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(BV), VT,
6512 OpVal = OpVal.lshr(DstBitSize);
6515 // For big endian targets, swap the order of the pieces of each element.
6516 if (TLI.isBigEndian())
6517 std::reverse(Ops.end()-NumOutputsPerInput, Ops.end());
6520 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(BV), VT, Ops);
6523 SDValue DAGCombiner::visitFADD(SDNode *N) {
6524 SDValue N0 = N->getOperand(0);
6525 SDValue N1 = N->getOperand(1);
6526 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6527 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6528 EVT VT = N->getValueType(0);
6531 if (VT.isVector()) {
6532 SDValue FoldedVOp = SimplifyVBinOp(N);
6533 if (FoldedVOp.getNode()) return FoldedVOp;
6536 // fold (fadd c1, c2) -> c1 + c2
6538 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N1);
6539 // canonicalize constant to RHS
6540 if (N0CFP && !N1CFP)
6541 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N1, N0);
6542 // fold (fadd A, 0) -> A
6543 if (DAG.getTarget().Options.UnsafeFPMath && N1CFP &&
6544 N1CFP->getValueAPF().isZero())
6546 // fold (fadd A, (fneg B)) -> (fsub A, B)
6547 if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) &&
6548 isNegatibleForFree(N1, LegalOperations, TLI, &DAG.getTarget().Options) == 2)
6549 return DAG.getNode(ISD::FSUB, SDLoc(N), VT, N0,
6550 GetNegatedExpression(N1, DAG, LegalOperations));
6551 // fold (fadd (fneg A), B) -> (fsub B, A)
6552 if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) &&
6553 isNegatibleForFree(N0, LegalOperations, TLI, &DAG.getTarget().Options) == 2)
6554 return DAG.getNode(ISD::FSUB, SDLoc(N), VT, N1,
6555 GetNegatedExpression(N0, DAG, LegalOperations));
6557 // If allowed, fold (fadd (fadd x, c1), c2) -> (fadd x, (fadd c1, c2))
6558 if (DAG.getTarget().Options.UnsafeFPMath && N1CFP &&
6559 N0.getOpcode() == ISD::FADD && N0.getNode()->hasOneUse() &&
6560 isa<ConstantFPSDNode>(N0.getOperand(1)))
6561 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0.getOperand(0),
6562 DAG.getNode(ISD::FADD, SDLoc(N), VT,
6563 N0.getOperand(1), N1));
6565 // No FP constant should be created after legalization as Instruction
6566 // Selection pass has hard time in dealing with FP constant.
6568 // We don't need test this condition for transformation like following, as
6569 // the DAG being transformed implies it is legal to take FP constant as
6572 // (fadd (fmul c, x), x) -> (fmul c+1, x)
6574 bool AllowNewFpConst = (Level < AfterLegalizeDAG);
6576 // If allow, fold (fadd (fneg x), x) -> 0.0
6577 if (AllowNewFpConst && DAG.getTarget().Options.UnsafeFPMath &&
6578 N0.getOpcode() == ISD::FNEG && N0.getOperand(0) == N1)
6579 return DAG.getConstantFP(0.0, VT);
6581 // If allow, fold (fadd x, (fneg x)) -> 0.0
6582 if (AllowNewFpConst && DAG.getTarget().Options.UnsafeFPMath &&
6583 N1.getOpcode() == ISD::FNEG && N1.getOperand(0) == N0)
6584 return DAG.getConstantFP(0.0, VT);
6586 // In unsafe math mode, we can fold chains of FADD's of the same value
6587 // into multiplications. This transform is not safe in general because
6588 // we are reducing the number of rounding steps.
6589 if (DAG.getTarget().Options.UnsafeFPMath &&
6590 TLI.isOperationLegalOrCustom(ISD::FMUL, VT) &&
6592 if (N0.getOpcode() == ISD::FMUL) {
6593 ConstantFPSDNode *CFP00 = dyn_cast<ConstantFPSDNode>(N0.getOperand(0));
6594 ConstantFPSDNode *CFP01 = dyn_cast<ConstantFPSDNode>(N0.getOperand(1));
6596 // (fadd (fmul c, x), x) -> (fmul x, c+1)
6597 if (CFP00 && !CFP01 && N0.getOperand(1) == N1) {
6598 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6600 DAG.getConstantFP(1.0, VT));
6601 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6605 // (fadd (fmul x, c), x) -> (fmul x, c+1)
6606 if (CFP01 && !CFP00 && N0.getOperand(0) == N1) {
6607 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6609 DAG.getConstantFP(1.0, VT));
6610 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6614 // (fadd (fmul c, x), (fadd x, x)) -> (fmul x, c+2)
6615 if (CFP00 && !CFP01 && N1.getOpcode() == ISD::FADD &&
6616 N1.getOperand(0) == N1.getOperand(1) &&
6617 N0.getOperand(1) == N1.getOperand(0)) {
6618 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6620 DAG.getConstantFP(2.0, VT));
6621 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6622 N0.getOperand(1), NewCFP);
6625 // (fadd (fmul x, c), (fadd x, x)) -> (fmul x, c+2)
6626 if (CFP01 && !CFP00 && N1.getOpcode() == ISD::FADD &&
6627 N1.getOperand(0) == N1.getOperand(1) &&
6628 N0.getOperand(0) == N1.getOperand(0)) {
6629 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6631 DAG.getConstantFP(2.0, VT));
6632 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6633 N0.getOperand(0), NewCFP);
6637 if (N1.getOpcode() == ISD::FMUL) {
6638 ConstantFPSDNode *CFP10 = dyn_cast<ConstantFPSDNode>(N1.getOperand(0));
6639 ConstantFPSDNode *CFP11 = dyn_cast<ConstantFPSDNode>(N1.getOperand(1));
6641 // (fadd x, (fmul c, x)) -> (fmul x, c+1)
6642 if (CFP10 && !CFP11 && N1.getOperand(1) == N0) {
6643 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6645 DAG.getConstantFP(1.0, VT));
6646 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6650 // (fadd x, (fmul x, c)) -> (fmul x, c+1)
6651 if (CFP11 && !CFP10 && N1.getOperand(0) == N0) {
6652 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6654 DAG.getConstantFP(1.0, VT));
6655 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6660 // (fadd (fadd x, x), (fmul c, x)) -> (fmul x, c+2)
6661 if (CFP10 && !CFP11 && N0.getOpcode() == ISD::FADD &&
6662 N0.getOperand(0) == N0.getOperand(1) &&
6663 N1.getOperand(1) == N0.getOperand(0)) {
6664 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6666 DAG.getConstantFP(2.0, VT));
6667 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6668 N1.getOperand(1), NewCFP);
6671 // (fadd (fadd x, x), (fmul x, c)) -> (fmul x, c+2)
6672 if (CFP11 && !CFP10 && N0.getOpcode() == ISD::FADD &&
6673 N0.getOperand(0) == N0.getOperand(1) &&
6674 N1.getOperand(0) == N0.getOperand(0)) {
6675 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6677 DAG.getConstantFP(2.0, VT));
6678 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6679 N1.getOperand(0), NewCFP);
6683 if (N0.getOpcode() == ISD::FADD && AllowNewFpConst) {
6684 ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N0.getOperand(0));
6685 // (fadd (fadd x, x), x) -> (fmul x, 3.0)
6686 if (!CFP && N0.getOperand(0) == N0.getOperand(1) &&
6687 (N0.getOperand(0) == N1))
6688 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6689 N1, DAG.getConstantFP(3.0, VT));
6692 if (N1.getOpcode() == ISD::FADD && AllowNewFpConst) {
6693 ConstantFPSDNode *CFP10 = dyn_cast<ConstantFPSDNode>(N1.getOperand(0));
6694 // (fadd x, (fadd x, x)) -> (fmul x, 3.0)
6695 if (!CFP10 && N1.getOperand(0) == N1.getOperand(1) &&
6696 N1.getOperand(0) == N0)
6697 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6698 N0, DAG.getConstantFP(3.0, VT));
6701 // (fadd (fadd x, x), (fadd x, x)) -> (fmul x, 4.0)
6702 if (AllowNewFpConst &&
6703 N0.getOpcode() == ISD::FADD && N1.getOpcode() == ISD::FADD &&
6704 N0.getOperand(0) == N0.getOperand(1) &&
6705 N1.getOperand(0) == N1.getOperand(1) &&
6706 N0.getOperand(0) == N1.getOperand(0))
6707 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6709 DAG.getConstantFP(4.0, VT));
6712 // FADD -> FMA combines:
6713 if ((DAG.getTarget().Options.AllowFPOpFusion == FPOpFusion::Fast ||
6714 DAG.getTarget().Options.UnsafeFPMath) &&
6717 ->getTargetLowering()
6718 ->isFMAFasterThanFMulAndFAdd(VT) &&
6719 (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT))) {
6721 // fold (fadd (fmul x, y), z) -> (fma x, y, z)
6722 if (N0.getOpcode() == ISD::FMUL && N0->hasOneUse())
6723 return DAG.getNode(ISD::FMA, SDLoc(N), VT,
6724 N0.getOperand(0), N0.getOperand(1), N1);
6726 // fold (fadd x, (fmul y, z)) -> (fma y, z, x)
6727 // Note: Commutes FADD operands.
6728 if (N1.getOpcode() == ISD::FMUL && N1->hasOneUse())
6729 return DAG.getNode(ISD::FMA, SDLoc(N), VT,
6730 N1.getOperand(0), N1.getOperand(1), N0);
6736 SDValue DAGCombiner::visitFSUB(SDNode *N) {
6737 SDValue N0 = N->getOperand(0);
6738 SDValue N1 = N->getOperand(1);
6739 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6740 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6741 EVT VT = N->getValueType(0);
6745 if (VT.isVector()) {
6746 SDValue FoldedVOp = SimplifyVBinOp(N);
6747 if (FoldedVOp.getNode()) return FoldedVOp;
6750 // fold (fsub c1, c2) -> c1-c2
6752 return DAG.getNode(ISD::FSUB, SDLoc(N), VT, N0, N1);
6753 // fold (fsub A, 0) -> A
6754 if (DAG.getTarget().Options.UnsafeFPMath &&
6755 N1CFP && N1CFP->getValueAPF().isZero())
6757 // fold (fsub 0, B) -> -B
6758 if (DAG.getTarget().Options.UnsafeFPMath &&
6759 N0CFP && N0CFP->getValueAPF().isZero()) {
6760 if (isNegatibleForFree(N1, LegalOperations, TLI, &DAG.getTarget().Options))
6761 return GetNegatedExpression(N1, DAG, LegalOperations);
6762 if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
6763 return DAG.getNode(ISD::FNEG, dl, VT, N1);
6765 // fold (fsub A, (fneg B)) -> (fadd A, B)
6766 if (isNegatibleForFree(N1, LegalOperations, TLI, &DAG.getTarget().Options))
6767 return DAG.getNode(ISD::FADD, dl, VT, N0,
6768 GetNegatedExpression(N1, DAG, LegalOperations));
6770 // If 'unsafe math' is enabled, fold
6771 // (fsub x, x) -> 0.0 &
6772 // (fsub x, (fadd x, y)) -> (fneg y) &
6773 // (fsub x, (fadd y, x)) -> (fneg y)
6774 if (DAG.getTarget().Options.UnsafeFPMath) {
6776 return DAG.getConstantFP(0.0f, VT);
6778 if (N1.getOpcode() == ISD::FADD) {
6779 SDValue N10 = N1->getOperand(0);
6780 SDValue N11 = N1->getOperand(1);
6782 if (N10 == N0 && isNegatibleForFree(N11, LegalOperations, TLI,
6783 &DAG.getTarget().Options))
6784 return GetNegatedExpression(N11, DAG, LegalOperations);
6786 if (N11 == N0 && isNegatibleForFree(N10, LegalOperations, TLI,
6787 &DAG.getTarget().Options))
6788 return GetNegatedExpression(N10, DAG, LegalOperations);
6792 // FSUB -> FMA combines:
6793 if ((DAG.getTarget().Options.AllowFPOpFusion == FPOpFusion::Fast ||
6794 DAG.getTarget().Options.UnsafeFPMath) &&
6797 ->getTargetLowering()
6798 ->isFMAFasterThanFMulAndFAdd(VT) &&
6799 (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT))) {
6801 // fold (fsub (fmul x, y), z) -> (fma x, y, (fneg z))
6802 if (N0.getOpcode() == ISD::FMUL && N0->hasOneUse())
6803 return DAG.getNode(ISD::FMA, dl, VT,
6804 N0.getOperand(0), N0.getOperand(1),
6805 DAG.getNode(ISD::FNEG, dl, VT, N1));
6807 // fold (fsub x, (fmul y, z)) -> (fma (fneg y), z, x)
6808 // Note: Commutes FSUB operands.
6809 if (N1.getOpcode() == ISD::FMUL && N1->hasOneUse())
6810 return DAG.getNode(ISD::FMA, dl, VT,
6811 DAG.getNode(ISD::FNEG, dl, VT,
6813 N1.getOperand(1), N0);
6815 // fold (fsub (fneg (fmul, x, y)), z) -> (fma (fneg x), y, (fneg z))
6816 if (N0.getOpcode() == ISD::FNEG &&
6817 N0.getOperand(0).getOpcode() == ISD::FMUL &&
6818 N0->hasOneUse() && N0.getOperand(0).hasOneUse()) {
6819 SDValue N00 = N0.getOperand(0).getOperand(0);
6820 SDValue N01 = N0.getOperand(0).getOperand(1);
6821 return DAG.getNode(ISD::FMA, dl, VT,
6822 DAG.getNode(ISD::FNEG, dl, VT, N00), N01,
6823 DAG.getNode(ISD::FNEG, dl, VT, N1));
6830 SDValue DAGCombiner::visitFMUL(SDNode *N) {
6831 SDValue N0 = N->getOperand(0);
6832 SDValue N1 = N->getOperand(1);
6833 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6834 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6835 EVT VT = N->getValueType(0);
6836 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6839 if (VT.isVector()) {
6840 SDValue FoldedVOp = SimplifyVBinOp(N);
6841 if (FoldedVOp.getNode()) return FoldedVOp;
6844 // fold (fmul c1, c2) -> c1*c2
6846 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0, N1);
6847 // canonicalize constant to RHS
6848 if (N0CFP && !N1CFP)
6849 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N1, N0);
6850 // fold (fmul A, 0) -> 0
6851 if (DAG.getTarget().Options.UnsafeFPMath &&
6852 N1CFP && N1CFP->getValueAPF().isZero())
6854 // fold (fmul A, 0) -> 0, vector edition.
6855 if (DAG.getTarget().Options.UnsafeFPMath &&
6856 ISD::isBuildVectorAllZeros(N1.getNode()))
6858 // fold (fmul A, 1.0) -> A
6859 if (N1CFP && N1CFP->isExactlyValue(1.0))
6861 // fold (fmul X, 2.0) -> (fadd X, X)
6862 if (N1CFP && N1CFP->isExactlyValue(+2.0))
6863 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N0);
6864 // fold (fmul X, -1.0) -> (fneg X)
6865 if (N1CFP && N1CFP->isExactlyValue(-1.0))
6866 if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
6867 return DAG.getNode(ISD::FNEG, SDLoc(N), VT, N0);
6869 // fold (fmul (fneg X), (fneg Y)) -> (fmul X, Y)
6870 if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI,
6871 &DAG.getTarget().Options)) {
6872 if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI,
6873 &DAG.getTarget().Options)) {
6874 // Both can be negated for free, check to see if at least one is cheaper
6876 if (LHSNeg == 2 || RHSNeg == 2)
6877 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6878 GetNegatedExpression(N0, DAG, LegalOperations),
6879 GetNegatedExpression(N1, DAG, LegalOperations));
6883 // If allowed, fold (fmul (fmul x, c1), c2) -> (fmul x, (fmul c1, c2))
6884 if (DAG.getTarget().Options.UnsafeFPMath &&
6885 N1CFP && N0.getOpcode() == ISD::FMUL &&
6886 N0.getNode()->hasOneUse() && isa<ConstantFPSDNode>(N0.getOperand(1)))
6887 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0.getOperand(0),
6888 DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6889 N0.getOperand(1), N1));
6894 SDValue DAGCombiner::visitFMA(SDNode *N) {
6895 SDValue N0 = N->getOperand(0);
6896 SDValue N1 = N->getOperand(1);
6897 SDValue N2 = N->getOperand(2);
6898 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6899 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6900 EVT VT = N->getValueType(0);
6904 // Constant fold FMA.
6905 if (isa<ConstantFPSDNode>(N0) &&
6906 isa<ConstantFPSDNode>(N1) &&
6907 isa<ConstantFPSDNode>(N2)) {
6908 return DAG.getNode(ISD::FMA, dl, VT, N0, N1, N2);
6911 if (DAG.getTarget().Options.UnsafeFPMath) {
6912 if (N0CFP && N0CFP->isZero())
6914 if (N1CFP && N1CFP->isZero())
6917 if (N0CFP && N0CFP->isExactlyValue(1.0))
6918 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N1, N2);
6919 if (N1CFP && N1CFP->isExactlyValue(1.0))
6920 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N2);
6922 // Canonicalize (fma c, x, y) -> (fma x, c, y)
6923 if (N0CFP && !N1CFP)
6924 return DAG.getNode(ISD::FMA, SDLoc(N), VT, N1, N0, N2);
6926 // (fma x, c1, (fmul x, c2)) -> (fmul x, c1+c2)
6927 if (DAG.getTarget().Options.UnsafeFPMath && N1CFP &&
6928 N2.getOpcode() == ISD::FMUL &&
6929 N0 == N2.getOperand(0) &&
6930 N2.getOperand(1).getOpcode() == ISD::ConstantFP) {
6931 return DAG.getNode(ISD::FMUL, dl, VT, N0,
6932 DAG.getNode(ISD::FADD, dl, VT, N1, N2.getOperand(1)));
6936 // (fma (fmul x, c1), c2, y) -> (fma x, c1*c2, y)
6937 if (DAG.getTarget().Options.UnsafeFPMath &&
6938 N0.getOpcode() == ISD::FMUL && N1CFP &&
6939 N0.getOperand(1).getOpcode() == ISD::ConstantFP) {
6940 return DAG.getNode(ISD::FMA, dl, VT,
6942 DAG.getNode(ISD::FMUL, dl, VT, N1, N0.getOperand(1)),
6946 // (fma x, 1, y) -> (fadd x, y)
6947 // (fma x, -1, y) -> (fadd (fneg x), y)
6949 if (N1CFP->isExactlyValue(1.0))
6950 return DAG.getNode(ISD::FADD, dl, VT, N0, N2);
6952 if (N1CFP->isExactlyValue(-1.0) &&
6953 (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))) {
6954 SDValue RHSNeg = DAG.getNode(ISD::FNEG, dl, VT, N0);
6955 AddToWorklist(RHSNeg.getNode());
6956 return DAG.getNode(ISD::FADD, dl, VT, N2, RHSNeg);
6960 // (fma x, c, x) -> (fmul x, (c+1))
6961 if (DAG.getTarget().Options.UnsafeFPMath && N1CFP && N0 == N2)
6962 return DAG.getNode(ISD::FMUL, dl, VT, N0,
6963 DAG.getNode(ISD::FADD, dl, VT,
6964 N1, DAG.getConstantFP(1.0, VT)));
6966 // (fma x, c, (fneg x)) -> (fmul x, (c-1))
6967 if (DAG.getTarget().Options.UnsafeFPMath && N1CFP &&
6968 N2.getOpcode() == ISD::FNEG && N2.getOperand(0) == N0)
6969 return DAG.getNode(ISD::FMUL, dl, VT, N0,
6970 DAG.getNode(ISD::FADD, dl, VT,
6971 N1, DAG.getConstantFP(-1.0, VT)));
6977 SDValue DAGCombiner::visitFDIV(SDNode *N) {
6978 SDValue N0 = N->getOperand(0);
6979 SDValue N1 = N->getOperand(1);
6980 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6981 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6982 EVT VT = N->getValueType(0);
6983 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6986 if (VT.isVector()) {
6987 SDValue FoldedVOp = SimplifyVBinOp(N);
6988 if (FoldedVOp.getNode()) return FoldedVOp;
6991 // fold (fdiv c1, c2) -> c1/c2
6993 return DAG.getNode(ISD::FDIV, SDLoc(N), VT, N0, N1);
6995 // fold (fdiv X, c2) -> fmul X, 1/c2 if losing precision is acceptable.
6996 if (N1CFP && DAG.getTarget().Options.UnsafeFPMath) {
6997 // Compute the reciprocal 1.0 / c2.
6998 APFloat N1APF = N1CFP->getValueAPF();
6999 APFloat Recip(N1APF.getSemantics(), 1); // 1.0
7000 APFloat::opStatus st = Recip.divide(N1APF, APFloat::rmNearestTiesToEven);
7001 // Only do the transform if the reciprocal is a legal fp immediate that
7002 // isn't too nasty (eg NaN, denormal, ...).
7003 if ((st == APFloat::opOK || st == APFloat::opInexact) && // Not too nasty
7004 (!LegalOperations ||
7005 // FIXME: custom lowering of ConstantFP might fail (see e.g. ARM
7006 // backend)... we should handle this gracefully after Legalize.
7007 // TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT) ||
7008 TLI.isOperationLegal(llvm::ISD::ConstantFP, VT) ||
7009 TLI.isFPImmLegal(Recip, VT)))
7010 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0,
7011 DAG.getConstantFP(Recip, VT));
7014 // (fdiv (fneg X), (fneg Y)) -> (fdiv X, Y)
7015 if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI,
7016 &DAG.getTarget().Options)) {
7017 if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI,
7018 &DAG.getTarget().Options)) {
7019 // Both can be negated for free, check to see if at least one is cheaper
7021 if (LHSNeg == 2 || RHSNeg == 2)
7022 return DAG.getNode(ISD::FDIV, SDLoc(N), VT,
7023 GetNegatedExpression(N0, DAG, LegalOperations),
7024 GetNegatedExpression(N1, DAG, LegalOperations));
7031 SDValue DAGCombiner::visitFREM(SDNode *N) {
7032 SDValue N0 = N->getOperand(0);
7033 SDValue N1 = N->getOperand(1);
7034 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7035 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
7036 EVT VT = N->getValueType(0);
7038 // fold (frem c1, c2) -> fmod(c1,c2)
7040 return DAG.getNode(ISD::FREM, SDLoc(N), VT, N0, N1);
7045 SDValue DAGCombiner::visitFCOPYSIGN(SDNode *N) {
7046 SDValue N0 = N->getOperand(0);
7047 SDValue N1 = N->getOperand(1);
7048 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7049 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
7050 EVT VT = N->getValueType(0);
7052 if (N0CFP && N1CFP) // Constant fold
7053 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, N0, N1);
7056 const APFloat& V = N1CFP->getValueAPF();
7057 // copysign(x, c1) -> fabs(x) iff ispos(c1)
7058 // copysign(x, c1) -> fneg(fabs(x)) iff isneg(c1)
7059 if (!V.isNegative()) {
7060 if (!LegalOperations || TLI.isOperationLegal(ISD::FABS, VT))
7061 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
7063 if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
7064 return DAG.getNode(ISD::FNEG, SDLoc(N), VT,
7065 DAG.getNode(ISD::FABS, SDLoc(N0), VT, N0));
7069 // copysign(fabs(x), y) -> copysign(x, y)
7070 // copysign(fneg(x), y) -> copysign(x, y)
7071 // copysign(copysign(x,z), y) -> copysign(x, y)
7072 if (N0.getOpcode() == ISD::FABS || N0.getOpcode() == ISD::FNEG ||
7073 N0.getOpcode() == ISD::FCOPYSIGN)
7074 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
7075 N0.getOperand(0), N1);
7077 // copysign(x, abs(y)) -> abs(x)
7078 if (N1.getOpcode() == ISD::FABS)
7079 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
7081 // copysign(x, copysign(y,z)) -> copysign(x, z)
7082 if (N1.getOpcode() == ISD::FCOPYSIGN)
7083 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
7084 N0, N1.getOperand(1));
7086 // copysign(x, fp_extend(y)) -> copysign(x, y)
7087 // copysign(x, fp_round(y)) -> copysign(x, y)
7088 if (N1.getOpcode() == ISD::FP_EXTEND || N1.getOpcode() == ISD::FP_ROUND)
7089 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
7090 N0, N1.getOperand(0));
7095 SDValue DAGCombiner::visitSINT_TO_FP(SDNode *N) {
7096 SDValue N0 = N->getOperand(0);
7097 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
7098 EVT VT = N->getValueType(0);
7099 EVT OpVT = N0.getValueType();
7101 // fold (sint_to_fp c1) -> c1fp
7103 // ...but only if the target supports immediate floating-point values
7104 (!LegalOperations ||
7105 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT)))
7106 return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0);
7108 // If the input is a legal type, and SINT_TO_FP is not legal on this target,
7109 // but UINT_TO_FP is legal on this target, try to convert.
7110 if (!TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT) &&
7111 TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT)) {
7112 // If the sign bit is known to be zero, we can change this to UINT_TO_FP.
7113 if (DAG.SignBitIsZero(N0))
7114 return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0);
7117 // The next optimizations are desirable only if SELECT_CC can be lowered.
7118 if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT) || !LegalOperations) {
7119 // fold (sint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc)
7120 if (N0.getOpcode() == ISD::SETCC && N0.getValueType() == MVT::i1 &&
7122 (!LegalOperations ||
7123 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
7125 { N0.getOperand(0), N0.getOperand(1),
7126 DAG.getConstantFP(-1.0, VT) , DAG.getConstantFP(0.0, VT),
7128 return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT, Ops);
7131 // fold (sint_to_fp (zext (setcc x, y, cc))) ->
7132 // (select_cc x, y, 1.0, 0.0,, cc)
7133 if (N0.getOpcode() == ISD::ZERO_EXTEND &&
7134 N0.getOperand(0).getOpcode() == ISD::SETCC &&!VT.isVector() &&
7135 (!LegalOperations ||
7136 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
7138 { N0.getOperand(0).getOperand(0), N0.getOperand(0).getOperand(1),
7139 DAG.getConstantFP(1.0, VT) , DAG.getConstantFP(0.0, VT),
7140 N0.getOperand(0).getOperand(2) };
7141 return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT, Ops);
7148 SDValue DAGCombiner::visitUINT_TO_FP(SDNode *N) {
7149 SDValue N0 = N->getOperand(0);
7150 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
7151 EVT VT = N->getValueType(0);
7152 EVT OpVT = N0.getValueType();
7154 // fold (uint_to_fp c1) -> c1fp
7156 // ...but only if the target supports immediate floating-point values
7157 (!LegalOperations ||
7158 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT)))
7159 return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0);
7161 // If the input is a legal type, and UINT_TO_FP is not legal on this target,
7162 // but SINT_TO_FP is legal on this target, try to convert.
7163 if (!TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT) &&
7164 TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT)) {
7165 // If the sign bit is known to be zero, we can change this to SINT_TO_FP.
7166 if (DAG.SignBitIsZero(N0))
7167 return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0);
7170 // The next optimizations are desirable only if SELECT_CC can be lowered.
7171 if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT) || !LegalOperations) {
7172 // fold (uint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc)
7174 if (N0.getOpcode() == ISD::SETCC && !VT.isVector() &&
7175 (!LegalOperations ||
7176 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
7178 { N0.getOperand(0), N0.getOperand(1),
7179 DAG.getConstantFP(1.0, VT), DAG.getConstantFP(0.0, VT),
7181 return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT, Ops);
7188 SDValue DAGCombiner::visitFP_TO_SINT(SDNode *N) {
7189 SDValue N0 = N->getOperand(0);
7190 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7191 EVT VT = N->getValueType(0);
7193 // fold (fp_to_sint c1fp) -> c1
7195 return DAG.getNode(ISD::FP_TO_SINT, SDLoc(N), VT, N0);
7200 SDValue DAGCombiner::visitFP_TO_UINT(SDNode *N) {
7201 SDValue N0 = N->getOperand(0);
7202 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7203 EVT VT = N->getValueType(0);
7205 // fold (fp_to_uint c1fp) -> c1
7207 return DAG.getNode(ISD::FP_TO_UINT, SDLoc(N), VT, N0);
7212 SDValue DAGCombiner::visitFP_ROUND(SDNode *N) {
7213 SDValue N0 = N->getOperand(0);
7214 SDValue N1 = N->getOperand(1);
7215 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7216 EVT VT = N->getValueType(0);
7218 // fold (fp_round c1fp) -> c1fp
7220 return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT, N0, N1);
7222 // fold (fp_round (fp_extend x)) -> x
7223 if (N0.getOpcode() == ISD::FP_EXTEND && VT == N0.getOperand(0).getValueType())
7224 return N0.getOperand(0);
7226 // fold (fp_round (fp_round x)) -> (fp_round x)
7227 if (N0.getOpcode() == ISD::FP_ROUND) {
7228 // This is a value preserving truncation if both round's are.
7229 bool IsTrunc = N->getConstantOperandVal(1) == 1 &&
7230 N0.getNode()->getConstantOperandVal(1) == 1;
7231 return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT, N0.getOperand(0),
7232 DAG.getIntPtrConstant(IsTrunc));
7235 // fold (fp_round (copysign X, Y)) -> (copysign (fp_round X), Y)
7236 if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse()) {
7237 SDValue Tmp = DAG.getNode(ISD::FP_ROUND, SDLoc(N0), VT,
7238 N0.getOperand(0), N1);
7239 AddToWorklist(Tmp.getNode());
7240 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
7241 Tmp, N0.getOperand(1));
7247 SDValue DAGCombiner::visitFP_ROUND_INREG(SDNode *N) {
7248 SDValue N0 = N->getOperand(0);
7249 EVT VT = N->getValueType(0);
7250 EVT EVT = cast<VTSDNode>(N->getOperand(1))->getVT();
7251 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7253 // fold (fp_round_inreg c1fp) -> c1fp
7254 if (N0CFP && isTypeLegal(EVT)) {
7255 SDValue Round = DAG.getConstantFP(*N0CFP->getConstantFPValue(), EVT);
7256 return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, Round);
7262 SDValue DAGCombiner::visitFP_EXTEND(SDNode *N) {
7263 SDValue N0 = N->getOperand(0);
7264 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7265 EVT VT = N->getValueType(0);
7267 // If this is fp_round(fpextend), don't fold it, allow ourselves to be folded.
7268 if (N->hasOneUse() &&
7269 N->use_begin()->getOpcode() == ISD::FP_ROUND)
7272 // fold (fp_extend c1fp) -> c1fp
7274 return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, N0);
7276 // Turn fp_extend(fp_round(X, 1)) -> x since the fp_round doesn't affect the
7278 if (N0.getOpcode() == ISD::FP_ROUND
7279 && N0.getNode()->getConstantOperandVal(1) == 1) {
7280 SDValue In = N0.getOperand(0);
7281 if (In.getValueType() == VT) return In;
7282 if (VT.bitsLT(In.getValueType()))
7283 return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT,
7284 In, N0.getOperand(1));
7285 return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, In);
7288 // fold (fpext (load x)) -> (fpext (fptrunc (extload x)))
7289 if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
7290 TLI.isLoadExtLegal(ISD::EXTLOAD, N0.getValueType())) {
7291 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
7292 SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT,
7294 LN0->getBasePtr(), N0.getValueType(),
7295 LN0->getMemOperand());
7296 CombineTo(N, ExtLoad);
7297 CombineTo(N0.getNode(),
7298 DAG.getNode(ISD::FP_ROUND, SDLoc(N0),
7299 N0.getValueType(), ExtLoad, DAG.getIntPtrConstant(1)),
7300 ExtLoad.getValue(1));
7301 return SDValue(N, 0); // Return N so it doesn't get rechecked!
7307 SDValue DAGCombiner::visitFNEG(SDNode *N) {
7308 SDValue N0 = N->getOperand(0);
7309 EVT VT = N->getValueType(0);
7311 // Constant fold FNEG.
7312 if (isa<ConstantFPSDNode>(N0))
7313 return DAG.getNode(ISD::FNEG, SDLoc(N), VT, N->getOperand(0));
7315 if (VT.isVector()) {
7316 SDValue FoldedVOp = SimplifyVUnaryOp(N);
7317 if (FoldedVOp.getNode()) return FoldedVOp;
7320 if (isNegatibleForFree(N0, LegalOperations, DAG.getTargetLoweringInfo(),
7321 &DAG.getTarget().Options))
7322 return GetNegatedExpression(N0, DAG, LegalOperations);
7324 // Transform fneg(bitconvert(x)) -> bitconvert(x ^ sign) to avoid loading
7325 // constant pool values.
7326 if (!TLI.isFNegFree(VT) && N0.getOpcode() == ISD::BITCAST &&
7327 N0.getNode()->hasOneUse()) {
7328 SDValue Int = N0.getOperand(0);
7329 EVT IntVT = Int.getValueType();
7330 if (IntVT.isInteger() && !IntVT.isVector()) {
7332 if (N0.getValueType().isVector()) {
7333 // For a vector, get a mask such as 0x80... per scalar element
7335 SignMask = APInt::getSignBit(N0.getValueType().getScalarSizeInBits());
7336 SignMask = APInt::getSplat(IntVT.getSizeInBits(), SignMask);
7338 // For a scalar, just generate 0x80...
7339 SignMask = APInt::getSignBit(IntVT.getSizeInBits());
7341 Int = DAG.getNode(ISD::XOR, SDLoc(N0), IntVT, Int,
7342 DAG.getConstant(SignMask, IntVT));
7343 AddToWorklist(Int.getNode());
7344 return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Int);
7348 // (fneg (fmul c, x)) -> (fmul -c, x)
7349 if (N0.getOpcode() == ISD::FMUL) {
7350 ConstantFPSDNode *CFP1 = dyn_cast<ConstantFPSDNode>(N0.getOperand(1));
7352 APFloat CVal = CFP1->getValueAPF();
7354 if (Level >= AfterLegalizeDAG &&
7355 (TLI.isFPImmLegal(CVal, N->getValueType(0)) ||
7356 TLI.isOperationLegal(ISD::ConstantFP, N->getValueType(0))))
7358 ISD::FMUL, SDLoc(N), VT, N0.getOperand(0),
7359 DAG.getNode(ISD::FNEG, SDLoc(N), VT, N0.getOperand(1)));
7366 SDValue DAGCombiner::visitFCEIL(SDNode *N) {
7367 SDValue N0 = N->getOperand(0);
7368 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7369 EVT VT = N->getValueType(0);
7371 // fold (fceil c1) -> fceil(c1)
7373 return DAG.getNode(ISD::FCEIL, SDLoc(N), VT, N0);
7378 SDValue DAGCombiner::visitFTRUNC(SDNode *N) {
7379 SDValue N0 = N->getOperand(0);
7380 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7381 EVT VT = N->getValueType(0);
7383 // fold (ftrunc c1) -> ftrunc(c1)
7385 return DAG.getNode(ISD::FTRUNC, SDLoc(N), VT, N0);
7390 SDValue DAGCombiner::visitFFLOOR(SDNode *N) {
7391 SDValue N0 = N->getOperand(0);
7392 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7393 EVT VT = N->getValueType(0);
7395 // fold (ffloor c1) -> ffloor(c1)
7397 return DAG.getNode(ISD::FFLOOR, SDLoc(N), VT, N0);
7402 SDValue DAGCombiner::visitFABS(SDNode *N) {
7403 SDValue N0 = N->getOperand(0);
7404 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7405 EVT VT = N->getValueType(0);
7407 if (VT.isVector()) {
7408 SDValue FoldedVOp = SimplifyVUnaryOp(N);
7409 if (FoldedVOp.getNode()) return FoldedVOp;
7412 // fold (fabs c1) -> fabs(c1)
7414 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
7415 // fold (fabs (fabs x)) -> (fabs x)
7416 if (N0.getOpcode() == ISD::FABS)
7417 return N->getOperand(0);
7418 // fold (fabs (fneg x)) -> (fabs x)
7419 // fold (fabs (fcopysign x, y)) -> (fabs x)
7420 if (N0.getOpcode() == ISD::FNEG || N0.getOpcode() == ISD::FCOPYSIGN)
7421 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0.getOperand(0));
7423 // Transform fabs(bitconvert(x)) -> bitconvert(x & ~sign) to avoid loading
7424 // constant pool values.
7425 if (!TLI.isFAbsFree(VT) &&
7426 N0.getOpcode() == ISD::BITCAST &&
7427 N0.getNode()->hasOneUse()) {
7428 SDValue Int = N0.getOperand(0);
7429 EVT IntVT = Int.getValueType();
7430 if (IntVT.isInteger() && !IntVT.isVector()) {
7432 if (N0.getValueType().isVector()) {
7433 // For a vector, get a mask such as 0x7f... per scalar element
7435 SignMask = ~APInt::getSignBit(N0.getValueType().getScalarSizeInBits());
7436 SignMask = APInt::getSplat(IntVT.getSizeInBits(), SignMask);
7438 // For a scalar, just generate 0x7f...
7439 SignMask = ~APInt::getSignBit(IntVT.getSizeInBits());
7441 Int = DAG.getNode(ISD::AND, SDLoc(N0), IntVT, Int,
7442 DAG.getConstant(SignMask, IntVT));
7443 AddToWorklist(Int.getNode());
7444 return DAG.getNode(ISD::BITCAST, SDLoc(N), N->getValueType(0), Int);
7451 SDValue DAGCombiner::visitBRCOND(SDNode *N) {
7452 SDValue Chain = N->getOperand(0);
7453 SDValue N1 = N->getOperand(1);
7454 SDValue N2 = N->getOperand(2);
7456 // If N is a constant we could fold this into a fallthrough or unconditional
7457 // branch. However that doesn't happen very often in normal code, because
7458 // Instcombine/SimplifyCFG should have handled the available opportunities.
7459 // If we did this folding here, it would be necessary to update the
7460 // MachineBasicBlock CFG, which is awkward.
7462 // fold a brcond with a setcc condition into a BR_CC node if BR_CC is legal
7464 if (N1.getOpcode() == ISD::SETCC &&
7465 TLI.isOperationLegalOrCustom(ISD::BR_CC,
7466 N1.getOperand(0).getValueType())) {
7467 return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other,
7468 Chain, N1.getOperand(2),
7469 N1.getOperand(0), N1.getOperand(1), N2);
7472 if ((N1.hasOneUse() && N1.getOpcode() == ISD::SRL) ||
7473 ((N1.getOpcode() == ISD::TRUNCATE && N1.hasOneUse()) &&
7474 (N1.getOperand(0).hasOneUse() &&
7475 N1.getOperand(0).getOpcode() == ISD::SRL))) {
7476 SDNode *Trunc = nullptr;
7477 if (N1.getOpcode() == ISD::TRUNCATE) {
7478 // Look pass the truncate.
7479 Trunc = N1.getNode();
7480 N1 = N1.getOperand(0);
7483 // Match this pattern so that we can generate simpler code:
7486 // %b = and i32 %a, 2
7487 // %c = srl i32 %b, 1
7488 // brcond i32 %c ...
7493 // %b = and i32 %a, 2
7494 // %c = setcc eq %b, 0
7497 // This applies only when the AND constant value has one bit set and the
7498 // SRL constant is equal to the log2 of the AND constant. The back-end is
7499 // smart enough to convert the result into a TEST/JMP sequence.
7500 SDValue Op0 = N1.getOperand(0);
7501 SDValue Op1 = N1.getOperand(1);
7503 if (Op0.getOpcode() == ISD::AND &&
7504 Op1.getOpcode() == ISD::Constant) {
7505 SDValue AndOp1 = Op0.getOperand(1);
7507 if (AndOp1.getOpcode() == ISD::Constant) {
7508 const APInt &AndConst = cast<ConstantSDNode>(AndOp1)->getAPIntValue();
7510 if (AndConst.isPowerOf2() &&
7511 cast<ConstantSDNode>(Op1)->getAPIntValue()==AndConst.logBase2()) {
7513 DAG.getSetCC(SDLoc(N),
7514 getSetCCResultType(Op0.getValueType()),
7515 Op0, DAG.getConstant(0, Op0.getValueType()),
7518 SDValue NewBRCond = DAG.getNode(ISD::BRCOND, SDLoc(N),
7519 MVT::Other, Chain, SetCC, N2);
7520 // Don't add the new BRCond into the worklist or else SimplifySelectCC
7521 // will convert it back to (X & C1) >> C2.
7522 CombineTo(N, NewBRCond, false);
7523 // Truncate is dead.
7525 deleteAndRecombine(Trunc);
7526 // Replace the uses of SRL with SETCC
7527 WorklistRemover DeadNodes(*this);
7528 DAG.ReplaceAllUsesOfValueWith(N1, SetCC);
7529 deleteAndRecombine(N1.getNode());
7530 return SDValue(N, 0); // Return N so it doesn't get rechecked!
7536 // Restore N1 if the above transformation doesn't match.
7537 N1 = N->getOperand(1);
7540 // Transform br(xor(x, y)) -> br(x != y)
7541 // Transform br(xor(xor(x,y), 1)) -> br (x == y)
7542 if (N1.hasOneUse() && N1.getOpcode() == ISD::XOR) {
7543 SDNode *TheXor = N1.getNode();
7544 SDValue Op0 = TheXor->getOperand(0);
7545 SDValue Op1 = TheXor->getOperand(1);
7546 if (Op0.getOpcode() == Op1.getOpcode()) {
7547 // Avoid missing important xor optimizations.
7548 SDValue Tmp = visitXOR(TheXor);
7549 if (Tmp.getNode()) {
7550 if (Tmp.getNode() != TheXor) {
7551 DEBUG(dbgs() << "\nReplacing.8 ";
7553 dbgs() << "\nWith: ";
7554 Tmp.getNode()->dump(&DAG);
7556 WorklistRemover DeadNodes(*this);
7557 DAG.ReplaceAllUsesOfValueWith(N1, Tmp);
7558 deleteAndRecombine(TheXor);
7559 return DAG.getNode(ISD::BRCOND, SDLoc(N),
7560 MVT::Other, Chain, Tmp, N2);
7563 // visitXOR has changed XOR's operands or replaced the XOR completely,
7565 return SDValue(N, 0);
7569 if (Op0.getOpcode() != ISD::SETCC && Op1.getOpcode() != ISD::SETCC) {
7571 if (ConstantSDNode *RHSCI = dyn_cast<ConstantSDNode>(Op0))
7572 if (RHSCI->getAPIntValue() == 1 && Op0.hasOneUse() &&
7573 Op0.getOpcode() == ISD::XOR) {
7574 TheXor = Op0.getNode();
7578 EVT SetCCVT = N1.getValueType();
7580 SetCCVT = getSetCCResultType(SetCCVT);
7581 SDValue SetCC = DAG.getSetCC(SDLoc(TheXor),
7584 Equal ? ISD::SETEQ : ISD::SETNE);
7585 // Replace the uses of XOR with SETCC
7586 WorklistRemover DeadNodes(*this);
7587 DAG.ReplaceAllUsesOfValueWith(N1, SetCC);
7588 deleteAndRecombine(N1.getNode());
7589 return DAG.getNode(ISD::BRCOND, SDLoc(N),
7590 MVT::Other, Chain, SetCC, N2);
7597 // Operand List for BR_CC: Chain, CondCC, CondLHS, CondRHS, DestBB.
7599 SDValue DAGCombiner::visitBR_CC(SDNode *N) {
7600 CondCodeSDNode *CC = cast<CondCodeSDNode>(N->getOperand(1));
7601 SDValue CondLHS = N->getOperand(2), CondRHS = N->getOperand(3);
7603 // If N is a constant we could fold this into a fallthrough or unconditional
7604 // branch. However that doesn't happen very often in normal code, because
7605 // Instcombine/SimplifyCFG should have handled the available opportunities.
7606 // If we did this folding here, it would be necessary to update the
7607 // MachineBasicBlock CFG, which is awkward.
7609 // Use SimplifySetCC to simplify SETCC's.
7610 SDValue Simp = SimplifySetCC(getSetCCResultType(CondLHS.getValueType()),
7611 CondLHS, CondRHS, CC->get(), SDLoc(N),
7613 if (Simp.getNode()) AddToWorklist(Simp.getNode());
7615 // fold to a simpler setcc
7616 if (Simp.getNode() && Simp.getOpcode() == ISD::SETCC)
7617 return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other,
7618 N->getOperand(0), Simp.getOperand(2),
7619 Simp.getOperand(0), Simp.getOperand(1),
7625 /// canFoldInAddressingMode - Return true if 'Use' is a load or a store that
7626 /// uses N as its base pointer and that N may be folded in the load / store
7627 /// addressing mode.
7628 static bool canFoldInAddressingMode(SDNode *N, SDNode *Use,
7630 const TargetLowering &TLI) {
7632 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Use)) {
7633 if (LD->isIndexed() || LD->getBasePtr().getNode() != N)
7635 VT = Use->getValueType(0);
7636 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(Use)) {
7637 if (ST->isIndexed() || ST->getBasePtr().getNode() != N)
7639 VT = ST->getValue().getValueType();
7643 TargetLowering::AddrMode AM;
7644 if (N->getOpcode() == ISD::ADD) {
7645 ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1));
7648 AM.BaseOffs = Offset->getSExtValue();
7652 } else if (N->getOpcode() == ISD::SUB) {
7653 ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1));
7656 AM.BaseOffs = -Offset->getSExtValue();
7663 return TLI.isLegalAddressingMode(AM, VT.getTypeForEVT(*DAG.getContext()));
7666 /// CombineToPreIndexedLoadStore - Try turning a load / store into a
7667 /// pre-indexed load / store when the base pointer is an add or subtract
7668 /// and it has other uses besides the load / store. After the
7669 /// transformation, the new indexed load / store has effectively folded
7670 /// the add / subtract in and all of its other uses are redirected to the
7671 /// new load / store.
7672 bool DAGCombiner::CombineToPreIndexedLoadStore(SDNode *N) {
7673 if (Level < AfterLegalizeDAG)
7679 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
7680 if (LD->isIndexed())
7682 VT = LD->getMemoryVT();
7683 if (!TLI.isIndexedLoadLegal(ISD::PRE_INC, VT) &&
7684 !TLI.isIndexedLoadLegal(ISD::PRE_DEC, VT))
7686 Ptr = LD->getBasePtr();
7687 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
7688 if (ST->isIndexed())
7690 VT = ST->getMemoryVT();
7691 if (!TLI.isIndexedStoreLegal(ISD::PRE_INC, VT) &&
7692 !TLI.isIndexedStoreLegal(ISD::PRE_DEC, VT))
7694 Ptr = ST->getBasePtr();
7700 // If the pointer is not an add/sub, or if it doesn't have multiple uses, bail
7701 // out. There is no reason to make this a preinc/predec.
7702 if ((Ptr.getOpcode() != ISD::ADD && Ptr.getOpcode() != ISD::SUB) ||
7703 Ptr.getNode()->hasOneUse())
7706 // Ask the target to do addressing mode selection.
7709 ISD::MemIndexedMode AM = ISD::UNINDEXED;
7710 if (!TLI.getPreIndexedAddressParts(N, BasePtr, Offset, AM, DAG))
7713 // Backends without true r+i pre-indexed forms may need to pass a
7714 // constant base with a variable offset so that constant coercion
7715 // will work with the patterns in canonical form.
7716 bool Swapped = false;
7717 if (isa<ConstantSDNode>(BasePtr)) {
7718 std::swap(BasePtr, Offset);
7722 // Don't create a indexed load / store with zero offset.
7723 if (isa<ConstantSDNode>(Offset) &&
7724 cast<ConstantSDNode>(Offset)->isNullValue())
7727 // Try turning it into a pre-indexed load / store except when:
7728 // 1) The new base ptr is a frame index.
7729 // 2) If N is a store and the new base ptr is either the same as or is a
7730 // predecessor of the value being stored.
7731 // 3) Another use of old base ptr is a predecessor of N. If ptr is folded
7732 // that would create a cycle.
7733 // 4) All uses are load / store ops that use it as old base ptr.
7735 // Check #1. Preinc'ing a frame index would require copying the stack pointer
7736 // (plus the implicit offset) to a register to preinc anyway.
7737 if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr))
7742 SDValue Val = cast<StoreSDNode>(N)->getValue();
7743 if (Val == BasePtr || BasePtr.getNode()->isPredecessorOf(Val.getNode()))
7747 // If the offset is a constant, there may be other adds of constants that
7748 // can be folded with this one. We should do this to avoid having to keep
7749 // a copy of the original base pointer.
7750 SmallVector<SDNode *, 16> OtherUses;
7751 if (isa<ConstantSDNode>(Offset))
7752 for (SDNode *Use : BasePtr.getNode()->uses()) {
7753 if (Use == Ptr.getNode())
7756 if (Use->isPredecessorOf(N))
7759 if (Use->getOpcode() != ISD::ADD && Use->getOpcode() != ISD::SUB) {
7764 SDValue Op0 = Use->getOperand(0), Op1 = Use->getOperand(1);
7765 if (Op1.getNode() == BasePtr.getNode())
7766 std::swap(Op0, Op1);
7767 assert(Op0.getNode() == BasePtr.getNode() &&
7768 "Use of ADD/SUB but not an operand");
7770 if (!isa<ConstantSDNode>(Op1)) {
7775 // FIXME: In some cases, we can be smarter about this.
7776 if (Op1.getValueType() != Offset.getValueType()) {
7781 OtherUses.push_back(Use);
7785 std::swap(BasePtr, Offset);
7787 // Now check for #3 and #4.
7788 bool RealUse = false;
7790 // Caches for hasPredecessorHelper
7791 SmallPtrSet<const SDNode *, 32> Visited;
7792 SmallVector<const SDNode *, 16> Worklist;
7794 for (SDNode *Use : Ptr.getNode()->uses()) {
7797 if (N->hasPredecessorHelper(Use, Visited, Worklist))
7800 // If Ptr may be folded in addressing mode of other use, then it's
7801 // not profitable to do this transformation.
7802 if (!canFoldInAddressingMode(Ptr.getNode(), Use, DAG, TLI))
7811 Result = DAG.getIndexedLoad(SDValue(N,0), SDLoc(N),
7812 BasePtr, Offset, AM);
7814 Result = DAG.getIndexedStore(SDValue(N,0), SDLoc(N),
7815 BasePtr, Offset, AM);
7818 DEBUG(dbgs() << "\nReplacing.4 ";
7820 dbgs() << "\nWith: ";
7821 Result.getNode()->dump(&DAG);
7823 WorklistRemover DeadNodes(*this);
7825 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0));
7826 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2));
7828 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1));
7831 // Finally, since the node is now dead, remove it from the graph.
7832 deleteAndRecombine(N);
7835 std::swap(BasePtr, Offset);
7837 // Replace other uses of BasePtr that can be updated to use Ptr
7838 for (unsigned i = 0, e = OtherUses.size(); i != e; ++i) {
7839 unsigned OffsetIdx = 1;
7840 if (OtherUses[i]->getOperand(OffsetIdx).getNode() == BasePtr.getNode())
7842 assert(OtherUses[i]->getOperand(!OffsetIdx).getNode() ==
7843 BasePtr.getNode() && "Expected BasePtr operand");
7845 // We need to replace ptr0 in the following expression:
7846 // x0 * offset0 + y0 * ptr0 = t0
7848 // x1 * offset1 + y1 * ptr0 = t1 (the indexed load/store)
7850 // where x0, x1, y0 and y1 in {-1, 1} are given by the types of the
7851 // indexed load/store and the expresion that needs to be re-written.
7853 // Therefore, we have:
7854 // t0 = (x0 * offset0 - x1 * y0 * y1 *offset1) + (y0 * y1) * t1
7856 ConstantSDNode *CN =
7857 cast<ConstantSDNode>(OtherUses[i]->getOperand(OffsetIdx));
7859 APInt Offset0 = CN->getAPIntValue();
7860 APInt Offset1 = cast<ConstantSDNode>(Offset)->getAPIntValue();
7862 X0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 1) ? -1 : 1;
7863 Y0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 0) ? -1 : 1;
7864 X1 = (AM == ISD::PRE_DEC && !Swapped) ? -1 : 1;
7865 Y1 = (AM == ISD::PRE_DEC && Swapped) ? -1 : 1;
7867 unsigned Opcode = (Y0 * Y1 < 0) ? ISD::SUB : ISD::ADD;
7869 APInt CNV = Offset0;
7870 if (X0 < 0) CNV = -CNV;
7871 if (X1 * Y0 * Y1 < 0) CNV = CNV + Offset1;
7872 else CNV = CNV - Offset1;
7874 // We can now generate the new expression.
7875 SDValue NewOp1 = DAG.getConstant(CNV, CN->getValueType(0));
7876 SDValue NewOp2 = Result.getValue(isLoad ? 1 : 0);
7878 SDValue NewUse = DAG.getNode(Opcode,
7879 SDLoc(OtherUses[i]),
7880 OtherUses[i]->getValueType(0), NewOp1, NewOp2);
7881 DAG.ReplaceAllUsesOfValueWith(SDValue(OtherUses[i], 0), NewUse);
7882 deleteAndRecombine(OtherUses[i]);
7885 // Replace the uses of Ptr with uses of the updated base value.
7886 DAG.ReplaceAllUsesOfValueWith(Ptr, Result.getValue(isLoad ? 1 : 0));
7887 deleteAndRecombine(Ptr.getNode());
7892 /// CombineToPostIndexedLoadStore - Try to combine a load / store with a
7893 /// add / sub of the base pointer node into a post-indexed load / store.
7894 /// The transformation folded the add / subtract into the new indexed
7895 /// load / store effectively and all of its uses are redirected to the
7896 /// new load / store.
7897 bool DAGCombiner::CombineToPostIndexedLoadStore(SDNode *N) {
7898 if (Level < AfterLegalizeDAG)
7904 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
7905 if (LD->isIndexed())
7907 VT = LD->getMemoryVT();
7908 if (!TLI.isIndexedLoadLegal(ISD::POST_INC, VT) &&
7909 !TLI.isIndexedLoadLegal(ISD::POST_DEC, VT))
7911 Ptr = LD->getBasePtr();
7912 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
7913 if (ST->isIndexed())
7915 VT = ST->getMemoryVT();
7916 if (!TLI.isIndexedStoreLegal(ISD::POST_INC, VT) &&
7917 !TLI.isIndexedStoreLegal(ISD::POST_DEC, VT))
7919 Ptr = ST->getBasePtr();
7925 if (Ptr.getNode()->hasOneUse())
7928 for (SDNode *Op : Ptr.getNode()->uses()) {
7930 (Op->getOpcode() != ISD::ADD && Op->getOpcode() != ISD::SUB))
7935 ISD::MemIndexedMode AM = ISD::UNINDEXED;
7936 if (TLI.getPostIndexedAddressParts(N, Op, BasePtr, Offset, AM, DAG)) {
7937 // Don't create a indexed load / store with zero offset.
7938 if (isa<ConstantSDNode>(Offset) &&
7939 cast<ConstantSDNode>(Offset)->isNullValue())
7942 // Try turning it into a post-indexed load / store except when
7943 // 1) All uses are load / store ops that use it as base ptr (and
7944 // it may be folded as addressing mmode).
7945 // 2) Op must be independent of N, i.e. Op is neither a predecessor
7946 // nor a successor of N. Otherwise, if Op is folded that would
7949 if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr))
7953 bool TryNext = false;
7954 for (SDNode *Use : BasePtr.getNode()->uses()) {
7955 if (Use == Ptr.getNode())
7958 // If all the uses are load / store addresses, then don't do the
7960 if (Use->getOpcode() == ISD::ADD || Use->getOpcode() == ISD::SUB){
7961 bool RealUse = false;
7962 for (SDNode *UseUse : Use->uses()) {
7963 if (!canFoldInAddressingMode(Use, UseUse, DAG, TLI))
7978 if (!Op->isPredecessorOf(N) && !N->isPredecessorOf(Op)) {
7979 SDValue Result = isLoad
7980 ? DAG.getIndexedLoad(SDValue(N,0), SDLoc(N),
7981 BasePtr, Offset, AM)
7982 : DAG.getIndexedStore(SDValue(N,0), SDLoc(N),
7983 BasePtr, Offset, AM);
7986 DEBUG(dbgs() << "\nReplacing.5 ";
7988 dbgs() << "\nWith: ";
7989 Result.getNode()->dump(&DAG);
7991 WorklistRemover DeadNodes(*this);
7993 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0));
7994 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2));
7996 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1));
7999 // Finally, since the node is now dead, remove it from the graph.
8000 deleteAndRecombine(N);
8002 // Replace the uses of Use with uses of the updated base value.
8003 DAG.ReplaceAllUsesOfValueWith(SDValue(Op, 0),
8004 Result.getValue(isLoad ? 1 : 0));
8005 deleteAndRecombine(Op);
8014 SDValue DAGCombiner::visitLOAD(SDNode *N) {
8015 LoadSDNode *LD = cast<LoadSDNode>(N);
8016 SDValue Chain = LD->getChain();
8017 SDValue Ptr = LD->getBasePtr();
8019 // If load is not volatile and there are no uses of the loaded value (and
8020 // the updated indexed value in case of indexed loads), change uses of the
8021 // chain value into uses of the chain input (i.e. delete the dead load).
8022 if (!LD->isVolatile()) {
8023 if (N->getValueType(1) == MVT::Other) {
8025 if (!N->hasAnyUseOfValue(0)) {
8026 // It's not safe to use the two value CombineTo variant here. e.g.
8027 // v1, chain2 = load chain1, loc
8028 // v2, chain3 = load chain2, loc
8030 // Now we replace use of chain2 with chain1. This makes the second load
8031 // isomorphic to the one we are deleting, and thus makes this load live.
8032 DEBUG(dbgs() << "\nReplacing.6 ";
8034 dbgs() << "\nWith chain: ";
8035 Chain.getNode()->dump(&DAG);
8037 WorklistRemover DeadNodes(*this);
8038 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain);
8041 deleteAndRecombine(N);
8043 return SDValue(N, 0); // Return N so it doesn't get rechecked!
8047 assert(N->getValueType(2) == MVT::Other && "Malformed indexed loads?");
8048 if (!N->hasAnyUseOfValue(0) && !N->hasAnyUseOfValue(1)) {
8049 SDValue Undef = DAG.getUNDEF(N->getValueType(0));
8050 DEBUG(dbgs() << "\nReplacing.7 ";
8052 dbgs() << "\nWith: ";
8053 Undef.getNode()->dump(&DAG);
8054 dbgs() << " and 2 other values\n");
8055 WorklistRemover DeadNodes(*this);
8056 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Undef);
8057 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1),
8058 DAG.getUNDEF(N->getValueType(1)));
8059 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 2), Chain);
8060 deleteAndRecombine(N);
8061 return SDValue(N, 0); // Return N so it doesn't get rechecked!
8066 // If this load is directly stored, replace the load value with the stored
8068 // TODO: Handle store large -> read small portion.
8069 // TODO: Handle TRUNCSTORE/LOADEXT
8070 if (ISD::isNormalLoad(N) && !LD->isVolatile()) {
8071 if (ISD::isNON_TRUNCStore(Chain.getNode())) {
8072 StoreSDNode *PrevST = cast<StoreSDNode>(Chain);
8073 if (PrevST->getBasePtr() == Ptr &&
8074 PrevST->getValue().getValueType() == N->getValueType(0))
8075 return CombineTo(N, Chain.getOperand(1), Chain);
8079 // Try to infer better alignment information than the load already has.
8080 if (OptLevel != CodeGenOpt::None && LD->isUnindexed()) {
8081 if (unsigned Align = DAG.InferPtrAlignment(Ptr)) {
8082 if (Align > LD->getMemOperand()->getBaseAlignment()) {
8084 DAG.getExtLoad(LD->getExtensionType(), SDLoc(N),
8085 LD->getValueType(0),
8086 Chain, Ptr, LD->getPointerInfo(),
8088 LD->isVolatile(), LD->isNonTemporal(),
8089 LD->isInvariant(), Align, LD->getAAInfo());
8090 return CombineTo(N, NewLoad, SDValue(NewLoad.getNode(), 1), true);
8095 bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA :
8096 TLI.getTargetMachine().getSubtarget<TargetSubtargetInfo>().useAA();
8098 if (CombinerAAOnlyFunc.getNumOccurrences() &&
8099 CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
8102 if (UseAA && LD->isUnindexed()) {
8103 // Walk up chain skipping non-aliasing memory nodes.
8104 SDValue BetterChain = FindBetterChain(N, Chain);
8106 // If there is a better chain.
8107 if (Chain != BetterChain) {
8110 // Replace the chain to void dependency.
8111 if (LD->getExtensionType() == ISD::NON_EXTLOAD) {
8112 ReplLoad = DAG.getLoad(N->getValueType(0), SDLoc(LD),
8113 BetterChain, Ptr, LD->getMemOperand());
8115 ReplLoad = DAG.getExtLoad(LD->getExtensionType(), SDLoc(LD),
8116 LD->getValueType(0),
8117 BetterChain, Ptr, LD->getMemoryVT(),
8118 LD->getMemOperand());
8121 // Create token factor to keep old chain connected.
8122 SDValue Token = DAG.getNode(ISD::TokenFactor, SDLoc(N),
8123 MVT::Other, Chain, ReplLoad.getValue(1));
8125 // Make sure the new and old chains are cleaned up.
8126 AddToWorklist(Token.getNode());
8128 // Replace uses with load result and token factor. Don't add users
8130 return CombineTo(N, ReplLoad.getValue(0), Token, false);
8134 // Try transforming N to an indexed load.
8135 if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
8136 return SDValue(N, 0);
8138 // Try to slice up N to more direct loads if the slices are mapped to
8139 // different register banks or pairing can take place.
8141 return SDValue(N, 0);
8147 /// \brief Helper structure used to slice a load in smaller loads.
8148 /// Basically a slice is obtained from the following sequence:
8149 /// Origin = load Ty1, Base
8150 /// Shift = srl Ty1 Origin, CstTy Amount
8151 /// Inst = trunc Shift to Ty2
8153 /// Then, it will be rewriten into:
8154 /// Slice = load SliceTy, Base + SliceOffset
8155 /// [Inst = zext Slice to Ty2], only if SliceTy <> Ty2
8157 /// SliceTy is deduced from the number of bits that are actually used to
8159 struct LoadedSlice {
8160 /// \brief Helper structure used to compute the cost of a slice.
8162 /// Are we optimizing for code size.
8167 unsigned CrossRegisterBanksCopies;
8171 Cost(bool ForCodeSize = false)
8172 : ForCodeSize(ForCodeSize), Loads(0), Truncates(0),
8173 CrossRegisterBanksCopies(0), ZExts(0), Shift(0) {}
8175 /// \brief Get the cost of one isolated slice.
8176 Cost(const LoadedSlice &LS, bool ForCodeSize = false)
8177 : ForCodeSize(ForCodeSize), Loads(1), Truncates(0),
8178 CrossRegisterBanksCopies(0), ZExts(0), Shift(0) {
8179 EVT TruncType = LS.Inst->getValueType(0);
8180 EVT LoadedType = LS.getLoadedType();
8181 if (TruncType != LoadedType &&
8182 !LS.DAG->getTargetLoweringInfo().isZExtFree(LoadedType, TruncType))
8186 /// \brief Account for slicing gain in the current cost.
8187 /// Slicing provide a few gains like removing a shift or a
8188 /// truncate. This method allows to grow the cost of the original
8189 /// load with the gain from this slice.
8190 void addSliceGain(const LoadedSlice &LS) {
8191 // Each slice saves a truncate.
8192 const TargetLowering &TLI = LS.DAG->getTargetLoweringInfo();
8193 if (!TLI.isTruncateFree(LS.Inst->getValueType(0),
8194 LS.Inst->getOperand(0).getValueType()))
8196 // If there is a shift amount, this slice gets rid of it.
8199 // If this slice can merge a cross register bank copy, account for it.
8200 if (LS.canMergeExpensiveCrossRegisterBankCopy())
8201 ++CrossRegisterBanksCopies;
8204 Cost &operator+=(const Cost &RHS) {
8206 Truncates += RHS.Truncates;
8207 CrossRegisterBanksCopies += RHS.CrossRegisterBanksCopies;
8213 bool operator==(const Cost &RHS) const {
8214 return Loads == RHS.Loads && Truncates == RHS.Truncates &&
8215 CrossRegisterBanksCopies == RHS.CrossRegisterBanksCopies &&
8216 ZExts == RHS.ZExts && Shift == RHS.Shift;
8219 bool operator!=(const Cost &RHS) const { return !(*this == RHS); }
8221 bool operator<(const Cost &RHS) const {
8222 // Assume cross register banks copies are as expensive as loads.
8223 // FIXME: Do we want some more target hooks?
8224 unsigned ExpensiveOpsLHS = Loads + CrossRegisterBanksCopies;
8225 unsigned ExpensiveOpsRHS = RHS.Loads + RHS.CrossRegisterBanksCopies;
8226 // Unless we are optimizing for code size, consider the
8227 // expensive operation first.
8228 if (!ForCodeSize && ExpensiveOpsLHS != ExpensiveOpsRHS)
8229 return ExpensiveOpsLHS < ExpensiveOpsRHS;
8230 return (Truncates + ZExts + Shift + ExpensiveOpsLHS) <
8231 (RHS.Truncates + RHS.ZExts + RHS.Shift + ExpensiveOpsRHS);
8234 bool operator>(const Cost &RHS) const { return RHS < *this; }
8236 bool operator<=(const Cost &RHS) const { return !(RHS < *this); }
8238 bool operator>=(const Cost &RHS) const { return !(*this < RHS); }
8240 // The last instruction that represent the slice. This should be a
8241 // truncate instruction.
8243 // The original load instruction.
8245 // The right shift amount in bits from the original load.
8247 // The DAG from which Origin came from.
8248 // This is used to get some contextual information about legal types, etc.
8251 LoadedSlice(SDNode *Inst = nullptr, LoadSDNode *Origin = nullptr,
8252 unsigned Shift = 0, SelectionDAG *DAG = nullptr)
8253 : Inst(Inst), Origin(Origin), Shift(Shift), DAG(DAG) {}
8255 LoadedSlice(const LoadedSlice &LS)
8256 : Inst(LS.Inst), Origin(LS.Origin), Shift(LS.Shift), DAG(LS.DAG) {}
8258 /// \brief Get the bits used in a chunk of bits \p BitWidth large.
8259 /// \return Result is \p BitWidth and has used bits set to 1 and
8260 /// not used bits set to 0.
8261 APInt getUsedBits() const {
8262 // Reproduce the trunc(lshr) sequence:
8263 // - Start from the truncated value.
8264 // - Zero extend to the desired bit width.
8266 assert(Origin && "No original load to compare against.");
8267 unsigned BitWidth = Origin->getValueSizeInBits(0);
8268 assert(Inst && "This slice is not bound to an instruction");
8269 assert(Inst->getValueSizeInBits(0) <= BitWidth &&
8270 "Extracted slice is bigger than the whole type!");
8271 APInt UsedBits(Inst->getValueSizeInBits(0), 0);
8272 UsedBits.setAllBits();
8273 UsedBits = UsedBits.zext(BitWidth);
8278 /// \brief Get the size of the slice to be loaded in bytes.
8279 unsigned getLoadedSize() const {
8280 unsigned SliceSize = getUsedBits().countPopulation();
8281 assert(!(SliceSize & 0x7) && "Size is not a multiple of a byte.");
8282 return SliceSize / 8;
8285 /// \brief Get the type that will be loaded for this slice.
8286 /// Note: This may not be the final type for the slice.
8287 EVT getLoadedType() const {
8288 assert(DAG && "Missing context");
8289 LLVMContext &Ctxt = *DAG->getContext();
8290 return EVT::getIntegerVT(Ctxt, getLoadedSize() * 8);
8293 /// \brief Get the alignment of the load used for this slice.
8294 unsigned getAlignment() const {
8295 unsigned Alignment = Origin->getAlignment();
8296 unsigned Offset = getOffsetFromBase();
8298 Alignment = MinAlign(Alignment, Alignment + Offset);
8302 /// \brief Check if this slice can be rewritten with legal operations.
8303 bool isLegal() const {
8304 // An invalid slice is not legal.
8305 if (!Origin || !Inst || !DAG)
8308 // Offsets are for indexed load only, we do not handle that.
8309 if (Origin->getOffset().getOpcode() != ISD::UNDEF)
8312 const TargetLowering &TLI = DAG->getTargetLoweringInfo();
8314 // Check that the type is legal.
8315 EVT SliceType = getLoadedType();
8316 if (!TLI.isTypeLegal(SliceType))
8319 // Check that the load is legal for this type.
8320 if (!TLI.isOperationLegal(ISD::LOAD, SliceType))
8323 // Check that the offset can be computed.
8324 // 1. Check its type.
8325 EVT PtrType = Origin->getBasePtr().getValueType();
8326 if (PtrType == MVT::Untyped || PtrType.isExtended())
8329 // 2. Check that it fits in the immediate.
8330 if (!TLI.isLegalAddImmediate(getOffsetFromBase()))
8333 // 3. Check that the computation is legal.
8334 if (!TLI.isOperationLegal(ISD::ADD, PtrType))
8337 // Check that the zext is legal if it needs one.
8338 EVT TruncateType = Inst->getValueType(0);
8339 if (TruncateType != SliceType &&
8340 !TLI.isOperationLegal(ISD::ZERO_EXTEND, TruncateType))
8346 /// \brief Get the offset in bytes of this slice in the original chunk of
8348 /// \pre DAG != nullptr.
8349 uint64_t getOffsetFromBase() const {
8350 assert(DAG && "Missing context.");
8352 DAG->getTargetLoweringInfo().getDataLayout()->isBigEndian();
8353 assert(!(Shift & 0x7) && "Shifts not aligned on Bytes are not supported.");
8354 uint64_t Offset = Shift / 8;
8355 unsigned TySizeInBytes = Origin->getValueSizeInBits(0) / 8;
8356 assert(!(Origin->getValueSizeInBits(0) & 0x7) &&
8357 "The size of the original loaded type is not a multiple of a"
8359 // If Offset is bigger than TySizeInBytes, it means we are loading all
8360 // zeros. This should have been optimized before in the process.
8361 assert(TySizeInBytes > Offset &&
8362 "Invalid shift amount for given loaded size");
8364 Offset = TySizeInBytes - Offset - getLoadedSize();
8368 /// \brief Generate the sequence of instructions to load the slice
8369 /// represented by this object and redirect the uses of this slice to
8370 /// this new sequence of instructions.
8371 /// \pre this->Inst && this->Origin are valid Instructions and this
8372 /// object passed the legal check: LoadedSlice::isLegal returned true.
8373 /// \return The last instruction of the sequence used to load the slice.
8374 SDValue loadSlice() const {
8375 assert(Inst && Origin && "Unable to replace a non-existing slice.");
8376 const SDValue &OldBaseAddr = Origin->getBasePtr();
8377 SDValue BaseAddr = OldBaseAddr;
8378 // Get the offset in that chunk of bytes w.r.t. the endianess.
8379 int64_t Offset = static_cast<int64_t>(getOffsetFromBase());
8380 assert(Offset >= 0 && "Offset too big to fit in int64_t!");
8382 // BaseAddr = BaseAddr + Offset.
8383 EVT ArithType = BaseAddr.getValueType();
8384 BaseAddr = DAG->getNode(ISD::ADD, SDLoc(Origin), ArithType, BaseAddr,
8385 DAG->getConstant(Offset, ArithType));
8388 // Create the type of the loaded slice according to its size.
8389 EVT SliceType = getLoadedType();
8391 // Create the load for the slice.
8392 SDValue LastInst = DAG->getLoad(
8393 SliceType, SDLoc(Origin), Origin->getChain(), BaseAddr,
8394 Origin->getPointerInfo().getWithOffset(Offset), Origin->isVolatile(),
8395 Origin->isNonTemporal(), Origin->isInvariant(), getAlignment());
8396 // If the final type is not the same as the loaded type, this means that
8397 // we have to pad with zero. Create a zero extend for that.
8398 EVT FinalType = Inst->getValueType(0);
8399 if (SliceType != FinalType)
8401 DAG->getNode(ISD::ZERO_EXTEND, SDLoc(LastInst), FinalType, LastInst);
8405 /// \brief Check if this slice can be merged with an expensive cross register
8406 /// bank copy. E.g.,
8408 /// f = bitcast i32 i to float
8409 bool canMergeExpensiveCrossRegisterBankCopy() const {
8410 if (!Inst || !Inst->hasOneUse())
8412 SDNode *Use = *Inst->use_begin();
8413 if (Use->getOpcode() != ISD::BITCAST)
8415 assert(DAG && "Missing context");
8416 const TargetLowering &TLI = DAG->getTargetLoweringInfo();
8417 EVT ResVT = Use->getValueType(0);
8418 const TargetRegisterClass *ResRC = TLI.getRegClassFor(ResVT.getSimpleVT());
8419 const TargetRegisterClass *ArgRC =
8420 TLI.getRegClassFor(Use->getOperand(0).getValueType().getSimpleVT());
8421 if (ArgRC == ResRC || !TLI.isOperationLegal(ISD::LOAD, ResVT))
8424 // At this point, we know that we perform a cross-register-bank copy.
8425 // Check if it is expensive.
8426 const TargetRegisterInfo *TRI =
8427 TLI.getTargetMachine().getSubtargetImpl()->getRegisterInfo();
8428 // Assume bitcasts are cheap, unless both register classes do not
8429 // explicitly share a common sub class.
8430 if (!TRI || TRI->getCommonSubClass(ArgRC, ResRC))
8433 // Check if it will be merged with the load.
8434 // 1. Check the alignment constraint.
8435 unsigned RequiredAlignment = TLI.getDataLayout()->getABITypeAlignment(
8436 ResVT.getTypeForEVT(*DAG->getContext()));
8438 if (RequiredAlignment > getAlignment())
8441 // 2. Check that the load is a legal operation for that type.
8442 if (!TLI.isOperationLegal(ISD::LOAD, ResVT))
8445 // 3. Check that we do not have a zext in the way.
8446 if (Inst->getValueType(0) != getLoadedType())
8454 /// \brief Check that all bits set in \p UsedBits form a dense region, i.e.,
8455 /// \p UsedBits looks like 0..0 1..1 0..0.
8456 static bool areUsedBitsDense(const APInt &UsedBits) {
8457 // If all the bits are one, this is dense!
8458 if (UsedBits.isAllOnesValue())
8461 // Get rid of the unused bits on the right.
8462 APInt NarrowedUsedBits = UsedBits.lshr(UsedBits.countTrailingZeros());
8463 // Get rid of the unused bits on the left.
8464 if (NarrowedUsedBits.countLeadingZeros())
8465 NarrowedUsedBits = NarrowedUsedBits.trunc(NarrowedUsedBits.getActiveBits());
8466 // Check that the chunk of bits is completely used.
8467 return NarrowedUsedBits.isAllOnesValue();
8470 /// \brief Check whether or not \p First and \p Second are next to each other
8471 /// in memory. This means that there is no hole between the bits loaded
8472 /// by \p First and the bits loaded by \p Second.
8473 static bool areSlicesNextToEachOther(const LoadedSlice &First,
8474 const LoadedSlice &Second) {
8475 assert(First.Origin == Second.Origin && First.Origin &&
8476 "Unable to match different memory origins.");
8477 APInt UsedBits = First.getUsedBits();
8478 assert((UsedBits & Second.getUsedBits()) == 0 &&
8479 "Slices are not supposed to overlap.");
8480 UsedBits |= Second.getUsedBits();
8481 return areUsedBitsDense(UsedBits);
8484 /// \brief Adjust the \p GlobalLSCost according to the target
8485 /// paring capabilities and the layout of the slices.
8486 /// \pre \p GlobalLSCost should account for at least as many loads as
8487 /// there is in the slices in \p LoadedSlices.
8488 static void adjustCostForPairing(SmallVectorImpl<LoadedSlice> &LoadedSlices,
8489 LoadedSlice::Cost &GlobalLSCost) {
8490 unsigned NumberOfSlices = LoadedSlices.size();
8491 // If there is less than 2 elements, no pairing is possible.
8492 if (NumberOfSlices < 2)
8495 // Sort the slices so that elements that are likely to be next to each
8496 // other in memory are next to each other in the list.
8497 std::sort(LoadedSlices.begin(), LoadedSlices.end(),
8498 [](const LoadedSlice &LHS, const LoadedSlice &RHS) {
8499 assert(LHS.Origin == RHS.Origin && "Different bases not implemented.");
8500 return LHS.getOffsetFromBase() < RHS.getOffsetFromBase();
8502 const TargetLowering &TLI = LoadedSlices[0].DAG->getTargetLoweringInfo();
8503 // First (resp. Second) is the first (resp. Second) potentially candidate
8504 // to be placed in a paired load.
8505 const LoadedSlice *First = nullptr;
8506 const LoadedSlice *Second = nullptr;
8507 for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice,
8508 // Set the beginning of the pair.
8511 Second = &LoadedSlices[CurrSlice];
8513 // If First is NULL, it means we start a new pair.
8514 // Get to the next slice.
8518 EVT LoadedType = First->getLoadedType();
8520 // If the types of the slices are different, we cannot pair them.
8521 if (LoadedType != Second->getLoadedType())
8524 // Check if the target supplies paired loads for this type.
8525 unsigned RequiredAlignment = 0;
8526 if (!TLI.hasPairedLoad(LoadedType, RequiredAlignment)) {
8527 // move to the next pair, this type is hopeless.
8531 // Check if we meet the alignment requirement.
8532 if (RequiredAlignment > First->getAlignment())
8535 // Check that both loads are next to each other in memory.
8536 if (!areSlicesNextToEachOther(*First, *Second))
8539 assert(GlobalLSCost.Loads > 0 && "We save more loads than we created!");
8540 --GlobalLSCost.Loads;
8541 // Move to the next pair.
8546 /// \brief Check the profitability of all involved LoadedSlice.
8547 /// Currently, it is considered profitable if there is exactly two
8548 /// involved slices (1) which are (2) next to each other in memory, and
8549 /// whose cost (\see LoadedSlice::Cost) is smaller than the original load (3).
8551 /// Note: The order of the elements in \p LoadedSlices may be modified, but not
8552 /// the elements themselves.
8554 /// FIXME: When the cost model will be mature enough, we can relax
8555 /// constraints (1) and (2).
8556 static bool isSlicingProfitable(SmallVectorImpl<LoadedSlice> &LoadedSlices,
8557 const APInt &UsedBits, bool ForCodeSize) {
8558 unsigned NumberOfSlices = LoadedSlices.size();
8559 if (StressLoadSlicing)
8560 return NumberOfSlices > 1;
8563 if (NumberOfSlices != 2)
8567 if (!areUsedBitsDense(UsedBits))
8571 LoadedSlice::Cost OrigCost(ForCodeSize), GlobalSlicingCost(ForCodeSize);
8572 // The original code has one big load.
8574 for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice) {
8575 const LoadedSlice &LS = LoadedSlices[CurrSlice];
8576 // Accumulate the cost of all the slices.
8577 LoadedSlice::Cost SliceCost(LS, ForCodeSize);
8578 GlobalSlicingCost += SliceCost;
8580 // Account as cost in the original configuration the gain obtained
8581 // with the current slices.
8582 OrigCost.addSliceGain(LS);
8585 // If the target supports paired load, adjust the cost accordingly.
8586 adjustCostForPairing(LoadedSlices, GlobalSlicingCost);
8587 return OrigCost > GlobalSlicingCost;
8590 /// \brief If the given load, \p LI, is used only by trunc or trunc(lshr)
8591 /// operations, split it in the various pieces being extracted.
8593 /// This sort of thing is introduced by SROA.
8594 /// This slicing takes care not to insert overlapping loads.
8595 /// \pre LI is a simple load (i.e., not an atomic or volatile load).
8596 bool DAGCombiner::SliceUpLoad(SDNode *N) {
8597 if (Level < AfterLegalizeDAG)
8600 LoadSDNode *LD = cast<LoadSDNode>(N);
8601 if (LD->isVolatile() || !ISD::isNormalLoad(LD) ||
8602 !LD->getValueType(0).isInteger())
8605 // Keep track of already used bits to detect overlapping values.
8606 // In that case, we will just abort the transformation.
8607 APInt UsedBits(LD->getValueSizeInBits(0), 0);
8609 SmallVector<LoadedSlice, 4> LoadedSlices;
8611 // Check if this load is used as several smaller chunks of bits.
8612 // Basically, look for uses in trunc or trunc(lshr) and record a new chain
8613 // of computation for each trunc.
8614 for (SDNode::use_iterator UI = LD->use_begin(), UIEnd = LD->use_end();
8615 UI != UIEnd; ++UI) {
8616 // Skip the uses of the chain.
8617 if (UI.getUse().getResNo() != 0)
8623 // Check if this is a trunc(lshr).
8624 if (User->getOpcode() == ISD::SRL && User->hasOneUse() &&
8625 isa<ConstantSDNode>(User->getOperand(1))) {
8626 Shift = cast<ConstantSDNode>(User->getOperand(1))->getZExtValue();
8627 User = *User->use_begin();
8630 // At this point, User is a Truncate, iff we encountered, trunc or
8632 if (User->getOpcode() != ISD::TRUNCATE)
8635 // The width of the type must be a power of 2 and greater than 8-bits.
8636 // Otherwise the load cannot be represented in LLVM IR.
8637 // Moreover, if we shifted with a non-8-bits multiple, the slice
8638 // will be across several bytes. We do not support that.
8639 unsigned Width = User->getValueSizeInBits(0);
8640 if (Width < 8 || !isPowerOf2_32(Width) || (Shift & 0x7))
8643 // Build the slice for this chain of computations.
8644 LoadedSlice LS(User, LD, Shift, &DAG);
8645 APInt CurrentUsedBits = LS.getUsedBits();
8647 // Check if this slice overlaps with another.
8648 if ((CurrentUsedBits & UsedBits) != 0)
8650 // Update the bits used globally.
8651 UsedBits |= CurrentUsedBits;
8653 // Check if the new slice would be legal.
8657 // Record the slice.
8658 LoadedSlices.push_back(LS);
8661 // Abort slicing if it does not seem to be profitable.
8662 if (!isSlicingProfitable(LoadedSlices, UsedBits, ForCodeSize))
8667 // Rewrite each chain to use an independent load.
8668 // By construction, each chain can be represented by a unique load.
8670 // Prepare the argument for the new token factor for all the slices.
8671 SmallVector<SDValue, 8> ArgChains;
8672 for (SmallVectorImpl<LoadedSlice>::const_iterator
8673 LSIt = LoadedSlices.begin(),
8674 LSItEnd = LoadedSlices.end();
8675 LSIt != LSItEnd; ++LSIt) {
8676 SDValue SliceInst = LSIt->loadSlice();
8677 CombineTo(LSIt->Inst, SliceInst, true);
8678 if (SliceInst.getNode()->getOpcode() != ISD::LOAD)
8679 SliceInst = SliceInst.getOperand(0);
8680 assert(SliceInst->getOpcode() == ISD::LOAD &&
8681 "It takes more than a zext to get to the loaded slice!!");
8682 ArgChains.push_back(SliceInst.getValue(1));
8685 SDValue Chain = DAG.getNode(ISD::TokenFactor, SDLoc(LD), MVT::Other,
8687 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain);
8691 /// CheckForMaskedLoad - Check to see if V is (and load (ptr), imm), where the
8692 /// load is having specific bytes cleared out. If so, return the byte size
8693 /// being masked out and the shift amount.
8694 static std::pair<unsigned, unsigned>
8695 CheckForMaskedLoad(SDValue V, SDValue Ptr, SDValue Chain) {
8696 std::pair<unsigned, unsigned> Result(0, 0);
8698 // Check for the structure we're looking for.
8699 if (V->getOpcode() != ISD::AND ||
8700 !isa<ConstantSDNode>(V->getOperand(1)) ||
8701 !ISD::isNormalLoad(V->getOperand(0).getNode()))
8704 // Check the chain and pointer.
8705 LoadSDNode *LD = cast<LoadSDNode>(V->getOperand(0));
8706 if (LD->getBasePtr() != Ptr) return Result; // Not from same pointer.
8708 // The store should be chained directly to the load or be an operand of a
8710 if (LD == Chain.getNode())
8712 else if (Chain->getOpcode() != ISD::TokenFactor)
8713 return Result; // Fail.
8716 for (unsigned i = 0, e = Chain->getNumOperands(); i != e; ++i)
8717 if (Chain->getOperand(i).getNode() == LD) {
8721 if (!isOk) return Result;
8724 // This only handles simple types.
8725 if (V.getValueType() != MVT::i16 &&
8726 V.getValueType() != MVT::i32 &&
8727 V.getValueType() != MVT::i64)
8730 // Check the constant mask. Invert it so that the bits being masked out are
8731 // 0 and the bits being kept are 1. Use getSExtValue so that leading bits
8732 // follow the sign bit for uniformity.
8733 uint64_t NotMask = ~cast<ConstantSDNode>(V->getOperand(1))->getSExtValue();
8734 unsigned NotMaskLZ = countLeadingZeros(NotMask);
8735 if (NotMaskLZ & 7) return Result; // Must be multiple of a byte.
8736 unsigned NotMaskTZ = countTrailingZeros(NotMask);
8737 if (NotMaskTZ & 7) return Result; // Must be multiple of a byte.
8738 if (NotMaskLZ == 64) return Result; // All zero mask.
8740 // See if we have a continuous run of bits. If so, we have 0*1+0*
8741 if (CountTrailingOnes_64(NotMask >> NotMaskTZ)+NotMaskTZ+NotMaskLZ != 64)
8744 // Adjust NotMaskLZ down to be from the actual size of the int instead of i64.
8745 if (V.getValueType() != MVT::i64 && NotMaskLZ)
8746 NotMaskLZ -= 64-V.getValueSizeInBits();
8748 unsigned MaskedBytes = (V.getValueSizeInBits()-NotMaskLZ-NotMaskTZ)/8;
8749 switch (MaskedBytes) {
8753 default: return Result; // All one mask, or 5-byte mask.
8756 // Verify that the first bit starts at a multiple of mask so that the access
8757 // is aligned the same as the access width.
8758 if (NotMaskTZ && NotMaskTZ/8 % MaskedBytes) return Result;
8760 Result.first = MaskedBytes;
8761 Result.second = NotMaskTZ/8;
8766 /// ShrinkLoadReplaceStoreWithStore - Check to see if IVal is something that
8767 /// provides a value as specified by MaskInfo. If so, replace the specified
8768 /// store with a narrower store of truncated IVal.
8770 ShrinkLoadReplaceStoreWithStore(const std::pair<unsigned, unsigned> &MaskInfo,
8771 SDValue IVal, StoreSDNode *St,
8773 unsigned NumBytes = MaskInfo.first;
8774 unsigned ByteShift = MaskInfo.second;
8775 SelectionDAG &DAG = DC->getDAG();
8777 // Check to see if IVal is all zeros in the part being masked in by the 'or'
8778 // that uses this. If not, this is not a replacement.
8779 APInt Mask = ~APInt::getBitsSet(IVal.getValueSizeInBits(),
8780 ByteShift*8, (ByteShift+NumBytes)*8);
8781 if (!DAG.MaskedValueIsZero(IVal, Mask)) return nullptr;
8783 // Check that it is legal on the target to do this. It is legal if the new
8784 // VT we're shrinking to (i8/i16/i32) is legal or we're still before type
8786 MVT VT = MVT::getIntegerVT(NumBytes*8);
8787 if (!DC->isTypeLegal(VT))
8790 // Okay, we can do this! Replace the 'St' store with a store of IVal that is
8791 // shifted by ByteShift and truncated down to NumBytes.
8793 IVal = DAG.getNode(ISD::SRL, SDLoc(IVal), IVal.getValueType(), IVal,
8794 DAG.getConstant(ByteShift*8,
8795 DC->getShiftAmountTy(IVal.getValueType())));
8797 // Figure out the offset for the store and the alignment of the access.
8799 unsigned NewAlign = St->getAlignment();
8801 if (DAG.getTargetLoweringInfo().isLittleEndian())
8802 StOffset = ByteShift;
8804 StOffset = IVal.getValueType().getStoreSize() - ByteShift - NumBytes;
8806 SDValue Ptr = St->getBasePtr();
8808 Ptr = DAG.getNode(ISD::ADD, SDLoc(IVal), Ptr.getValueType(),
8809 Ptr, DAG.getConstant(StOffset, Ptr.getValueType()));
8810 NewAlign = MinAlign(NewAlign, StOffset);
8813 // Truncate down to the new size.
8814 IVal = DAG.getNode(ISD::TRUNCATE, SDLoc(IVal), VT, IVal);
8817 return DAG.getStore(St->getChain(), SDLoc(St), IVal, Ptr,
8818 St->getPointerInfo().getWithOffset(StOffset),
8819 false, false, NewAlign).getNode();
8823 /// ReduceLoadOpStoreWidth - Look for sequence of load / op / store where op is
8824 /// one of 'or', 'xor', and 'and' of immediates. If 'op' is only touching some
8825 /// of the loaded bits, try narrowing the load and store if it would end up
8826 /// being a win for performance or code size.
8827 SDValue DAGCombiner::ReduceLoadOpStoreWidth(SDNode *N) {
8828 StoreSDNode *ST = cast<StoreSDNode>(N);
8829 if (ST->isVolatile())
8832 SDValue Chain = ST->getChain();
8833 SDValue Value = ST->getValue();
8834 SDValue Ptr = ST->getBasePtr();
8835 EVT VT = Value.getValueType();
8837 if (ST->isTruncatingStore() || VT.isVector() || !Value.hasOneUse())
8840 unsigned Opc = Value.getOpcode();
8842 // If this is "store (or X, Y), P" and X is "(and (load P), cst)", where cst
8843 // is a byte mask indicating a consecutive number of bytes, check to see if
8844 // Y is known to provide just those bytes. If so, we try to replace the
8845 // load + replace + store sequence with a single (narrower) store, which makes
8847 if (Opc == ISD::OR) {
8848 std::pair<unsigned, unsigned> MaskedLoad;
8849 MaskedLoad = CheckForMaskedLoad(Value.getOperand(0), Ptr, Chain);
8850 if (MaskedLoad.first)
8851 if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad,
8852 Value.getOperand(1), ST,this))
8853 return SDValue(NewST, 0);
8855 // Or is commutative, so try swapping X and Y.
8856 MaskedLoad = CheckForMaskedLoad(Value.getOperand(1), Ptr, Chain);
8857 if (MaskedLoad.first)
8858 if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad,
8859 Value.getOperand(0), ST,this))
8860 return SDValue(NewST, 0);
8863 if ((Opc != ISD::OR && Opc != ISD::XOR && Opc != ISD::AND) ||
8864 Value.getOperand(1).getOpcode() != ISD::Constant)
8867 SDValue N0 = Value.getOperand(0);
8868 if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
8869 Chain == SDValue(N0.getNode(), 1)) {
8870 LoadSDNode *LD = cast<LoadSDNode>(N0);
8871 if (LD->getBasePtr() != Ptr ||
8872 LD->getPointerInfo().getAddrSpace() !=
8873 ST->getPointerInfo().getAddrSpace())
8876 // Find the type to narrow it the load / op / store to.
8877 SDValue N1 = Value.getOperand(1);
8878 unsigned BitWidth = N1.getValueSizeInBits();
8879 APInt Imm = cast<ConstantSDNode>(N1)->getAPIntValue();
8880 if (Opc == ISD::AND)
8881 Imm ^= APInt::getAllOnesValue(BitWidth);
8882 if (Imm == 0 || Imm.isAllOnesValue())
8884 unsigned ShAmt = Imm.countTrailingZeros();
8885 unsigned MSB = BitWidth - Imm.countLeadingZeros() - 1;
8886 unsigned NewBW = NextPowerOf2(MSB - ShAmt);
8887 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW);
8888 while (NewBW < BitWidth &&
8889 !(TLI.isOperationLegalOrCustom(Opc, NewVT) &&
8890 TLI.isNarrowingProfitable(VT, NewVT))) {
8891 NewBW = NextPowerOf2(NewBW);
8892 NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW);
8894 if (NewBW >= BitWidth)
8897 // If the lsb changed does not start at the type bitwidth boundary,
8898 // start at the previous one.
8900 ShAmt = (((ShAmt + NewBW - 1) / NewBW) * NewBW) - NewBW;
8901 APInt Mask = APInt::getBitsSet(BitWidth, ShAmt,
8902 std::min(BitWidth, ShAmt + NewBW));
8903 if ((Imm & Mask) == Imm) {
8904 APInt NewImm = (Imm & Mask).lshr(ShAmt).trunc(NewBW);
8905 if (Opc == ISD::AND)
8906 NewImm ^= APInt::getAllOnesValue(NewBW);
8907 uint64_t PtrOff = ShAmt / 8;
8908 // For big endian targets, we need to adjust the offset to the pointer to
8909 // load the correct bytes.
8910 if (TLI.isBigEndian())
8911 PtrOff = (BitWidth + 7 - NewBW) / 8 - PtrOff;
8913 unsigned NewAlign = MinAlign(LD->getAlignment(), PtrOff);
8914 Type *NewVTTy = NewVT.getTypeForEVT(*DAG.getContext());
8915 if (NewAlign < TLI.getDataLayout()->getABITypeAlignment(NewVTTy))
8918 SDValue NewPtr = DAG.getNode(ISD::ADD, SDLoc(LD),
8919 Ptr.getValueType(), Ptr,
8920 DAG.getConstant(PtrOff, Ptr.getValueType()));
8921 SDValue NewLD = DAG.getLoad(NewVT, SDLoc(N0),
8922 LD->getChain(), NewPtr,
8923 LD->getPointerInfo().getWithOffset(PtrOff),
8924 LD->isVolatile(), LD->isNonTemporal(),
8925 LD->isInvariant(), NewAlign,
8927 SDValue NewVal = DAG.getNode(Opc, SDLoc(Value), NewVT, NewLD,
8928 DAG.getConstant(NewImm, NewVT));
8929 SDValue NewST = DAG.getStore(Chain, SDLoc(N),
8931 ST->getPointerInfo().getWithOffset(PtrOff),
8932 false, false, NewAlign);
8934 AddToWorklist(NewPtr.getNode());
8935 AddToWorklist(NewLD.getNode());
8936 AddToWorklist(NewVal.getNode());
8937 WorklistRemover DeadNodes(*this);
8938 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLD.getValue(1));
8947 /// TransformFPLoadStorePair - For a given floating point load / store pair,
8948 /// if the load value isn't used by any other operations, then consider
8949 /// transforming the pair to integer load / store operations if the target
8950 /// deems the transformation profitable.
8951 SDValue DAGCombiner::TransformFPLoadStorePair(SDNode *N) {
8952 StoreSDNode *ST = cast<StoreSDNode>(N);
8953 SDValue Chain = ST->getChain();
8954 SDValue Value = ST->getValue();
8955 if (ISD::isNormalStore(ST) && ISD::isNormalLoad(Value.getNode()) &&
8956 Value.hasOneUse() &&
8957 Chain == SDValue(Value.getNode(), 1)) {
8958 LoadSDNode *LD = cast<LoadSDNode>(Value);
8959 EVT VT = LD->getMemoryVT();
8960 if (!VT.isFloatingPoint() ||
8961 VT != ST->getMemoryVT() ||
8962 LD->isNonTemporal() ||
8963 ST->isNonTemporal() ||
8964 LD->getPointerInfo().getAddrSpace() != 0 ||
8965 ST->getPointerInfo().getAddrSpace() != 0)
8968 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), VT.getSizeInBits());
8969 if (!TLI.isOperationLegal(ISD::LOAD, IntVT) ||
8970 !TLI.isOperationLegal(ISD::STORE, IntVT) ||
8971 !TLI.isDesirableToTransformToIntegerOp(ISD::LOAD, VT) ||
8972 !TLI.isDesirableToTransformToIntegerOp(ISD::STORE, VT))
8975 unsigned LDAlign = LD->getAlignment();
8976 unsigned STAlign = ST->getAlignment();
8977 Type *IntVTTy = IntVT.getTypeForEVT(*DAG.getContext());
8978 unsigned ABIAlign = TLI.getDataLayout()->getABITypeAlignment(IntVTTy);
8979 if (LDAlign < ABIAlign || STAlign < ABIAlign)
8982 SDValue NewLD = DAG.getLoad(IntVT, SDLoc(Value),
8983 LD->getChain(), LD->getBasePtr(),
8984 LD->getPointerInfo(),
8985 false, false, false, LDAlign);
8987 SDValue NewST = DAG.getStore(NewLD.getValue(1), SDLoc(N),
8988 NewLD, ST->getBasePtr(),
8989 ST->getPointerInfo(),
8990 false, false, STAlign);
8992 AddToWorklist(NewLD.getNode());
8993 AddToWorklist(NewST.getNode());
8994 WorklistRemover DeadNodes(*this);
8995 DAG.ReplaceAllUsesOfValueWith(Value.getValue(1), NewLD.getValue(1));
9003 /// Helper struct to parse and store a memory address as base + index + offset.
9004 /// We ignore sign extensions when it is safe to do so.
9005 /// The following two expressions are not equivalent. To differentiate we need
9006 /// to store whether there was a sign extension involved in the index
9008 /// (load (i64 add (i64 copyfromreg %c)
9009 /// (i64 signextend (add (i8 load %index)
9013 /// (load (i64 add (i64 copyfromreg %c)
9014 /// (i64 signextend (i32 add (i32 signextend (i8 load %index))
9016 struct BaseIndexOffset {
9020 bool IsIndexSignExt;
9022 BaseIndexOffset() : Offset(0), IsIndexSignExt(false) {}
9024 BaseIndexOffset(SDValue Base, SDValue Index, int64_t Offset,
9025 bool IsIndexSignExt) :
9026 Base(Base), Index(Index), Offset(Offset), IsIndexSignExt(IsIndexSignExt) {}
9028 bool equalBaseIndex(const BaseIndexOffset &Other) {
9029 return Other.Base == Base && Other.Index == Index &&
9030 Other.IsIndexSignExt == IsIndexSignExt;
9033 /// Parses tree in Ptr for base, index, offset addresses.
9034 static BaseIndexOffset match(SDValue Ptr) {
9035 bool IsIndexSignExt = false;
9037 // We only can pattern match BASE + INDEX + OFFSET. If Ptr is not an ADD
9038 // instruction, then it could be just the BASE or everything else we don't
9039 // know how to handle. Just use Ptr as BASE and give up.
9040 if (Ptr->getOpcode() != ISD::ADD)
9041 return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
9043 // We know that we have at least an ADD instruction. Try to pattern match
9044 // the simple case of BASE + OFFSET.
9045 if (isa<ConstantSDNode>(Ptr->getOperand(1))) {
9046 int64_t Offset = cast<ConstantSDNode>(Ptr->getOperand(1))->getSExtValue();
9047 return BaseIndexOffset(Ptr->getOperand(0), SDValue(), Offset,
9051 // Inside a loop the current BASE pointer is calculated using an ADD and a
9052 // MUL instruction. In this case Ptr is the actual BASE pointer.
9053 // (i64 add (i64 %array_ptr)
9054 // (i64 mul (i64 %induction_var)
9055 // (i64 %element_size)))
9056 if (Ptr->getOperand(1)->getOpcode() == ISD::MUL)
9057 return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
9059 // Look at Base + Index + Offset cases.
9060 SDValue Base = Ptr->getOperand(0);
9061 SDValue IndexOffset = Ptr->getOperand(1);
9063 // Skip signextends.
9064 if (IndexOffset->getOpcode() == ISD::SIGN_EXTEND) {
9065 IndexOffset = IndexOffset->getOperand(0);
9066 IsIndexSignExt = true;
9069 // Either the case of Base + Index (no offset) or something else.
9070 if (IndexOffset->getOpcode() != ISD::ADD)
9071 return BaseIndexOffset(Base, IndexOffset, 0, IsIndexSignExt);
9073 // Now we have the case of Base + Index + offset.
9074 SDValue Index = IndexOffset->getOperand(0);
9075 SDValue Offset = IndexOffset->getOperand(1);
9077 if (!isa<ConstantSDNode>(Offset))
9078 return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
9080 // Ignore signextends.
9081 if (Index->getOpcode() == ISD::SIGN_EXTEND) {
9082 Index = Index->getOperand(0);
9083 IsIndexSignExt = true;
9084 } else IsIndexSignExt = false;
9086 int64_t Off = cast<ConstantSDNode>(Offset)->getSExtValue();
9087 return BaseIndexOffset(Base, Index, Off, IsIndexSignExt);
9091 /// Holds a pointer to an LSBaseSDNode as well as information on where it
9092 /// is located in a sequence of memory operations connected by a chain.
9094 MemOpLink (LSBaseSDNode *N, int64_t Offset, unsigned Seq):
9095 MemNode(N), OffsetFromBase(Offset), SequenceNum(Seq) { }
9096 // Ptr to the mem node.
9097 LSBaseSDNode *MemNode;
9098 // Offset from the base ptr.
9099 int64_t OffsetFromBase;
9100 // What is the sequence number of this mem node.
9101 // Lowest mem operand in the DAG starts at zero.
9102 unsigned SequenceNum;
9105 bool DAGCombiner::MergeConsecutiveStores(StoreSDNode* St) {
9106 EVT MemVT = St->getMemoryVT();
9107 int64_t ElementSizeBytes = MemVT.getSizeInBits()/8;
9108 bool NoVectors = DAG.getMachineFunction().getFunction()->getAttributes().
9109 hasAttribute(AttributeSet::FunctionIndex, Attribute::NoImplicitFloat);
9111 // Don't merge vectors into wider inputs.
9112 if (MemVT.isVector() || !MemVT.isSimple())
9115 // Perform an early exit check. Do not bother looking at stored values that
9116 // are not constants or loads.
9117 SDValue StoredVal = St->getValue();
9118 bool IsLoadSrc = isa<LoadSDNode>(StoredVal);
9119 if (!isa<ConstantSDNode>(StoredVal) && !isa<ConstantFPSDNode>(StoredVal) &&
9123 // Only look at ends of store sequences.
9124 SDValue Chain = SDValue(St, 0);
9125 if (Chain->hasOneUse() && Chain->use_begin()->getOpcode() == ISD::STORE)
9128 // This holds the base pointer, index, and the offset in bytes from the base
9130 BaseIndexOffset BasePtr = BaseIndexOffset::match(St->getBasePtr());
9132 // We must have a base and an offset.
9133 if (!BasePtr.Base.getNode())
9136 // Do not handle stores to undef base pointers.
9137 if (BasePtr.Base.getOpcode() == ISD::UNDEF)
9140 // Save the LoadSDNodes that we find in the chain.
9141 // We need to make sure that these nodes do not interfere with
9142 // any of the store nodes.
9143 SmallVector<LSBaseSDNode*, 8> AliasLoadNodes;
9145 // Save the StoreSDNodes that we find in the chain.
9146 SmallVector<MemOpLink, 8> StoreNodes;
9148 // Walk up the chain and look for nodes with offsets from the same
9149 // base pointer. Stop when reaching an instruction with a different kind
9150 // or instruction which has a different base pointer.
9152 StoreSDNode *Index = St;
9154 // If the chain has more than one use, then we can't reorder the mem ops.
9155 if (Index != St && !SDValue(Index, 0)->hasOneUse())
9158 // Find the base pointer and offset for this memory node.
9159 BaseIndexOffset Ptr = BaseIndexOffset::match(Index->getBasePtr());
9161 // Check that the base pointer is the same as the original one.
9162 if (!Ptr.equalBaseIndex(BasePtr))
9165 // Check that the alignment is the same.
9166 if (Index->getAlignment() != St->getAlignment())
9169 // The memory operands must not be volatile.
9170 if (Index->isVolatile() || Index->isIndexed())
9174 if (StoreSDNode *St = dyn_cast<StoreSDNode>(Index))
9175 if (St->isTruncatingStore())
9178 // The stored memory type must be the same.
9179 if (Index->getMemoryVT() != MemVT)
9182 // We do not allow unaligned stores because we want to prevent overriding
9184 if (Index->getAlignment()*8 != MemVT.getSizeInBits())
9187 // We found a potential memory operand to merge.
9188 StoreNodes.push_back(MemOpLink(Index, Ptr.Offset, Seq++));
9190 // Find the next memory operand in the chain. If the next operand in the
9191 // chain is a store then move up and continue the scan with the next
9192 // memory operand. If the next operand is a load save it and use alias
9193 // information to check if it interferes with anything.
9194 SDNode *NextInChain = Index->getChain().getNode();
9196 if (StoreSDNode *STn = dyn_cast<StoreSDNode>(NextInChain)) {
9197 // We found a store node. Use it for the next iteration.
9200 } else if (LoadSDNode *Ldn = dyn_cast<LoadSDNode>(NextInChain)) {
9201 if (Ldn->isVolatile()) {
9206 // Save the load node for later. Continue the scan.
9207 AliasLoadNodes.push_back(Ldn);
9208 NextInChain = Ldn->getChain().getNode();
9217 // Check if there is anything to merge.
9218 if (StoreNodes.size() < 2)
9221 // Sort the memory operands according to their distance from the base pointer.
9222 std::sort(StoreNodes.begin(), StoreNodes.end(),
9223 [](MemOpLink LHS, MemOpLink RHS) {
9224 return LHS.OffsetFromBase < RHS.OffsetFromBase ||
9225 (LHS.OffsetFromBase == RHS.OffsetFromBase &&
9226 LHS.SequenceNum > RHS.SequenceNum);
9229 // Scan the memory operations on the chain and find the first non-consecutive
9230 // store memory address.
9231 unsigned LastConsecutiveStore = 0;
9232 int64_t StartAddress = StoreNodes[0].OffsetFromBase;
9233 for (unsigned i = 0, e = StoreNodes.size(); i < e; ++i) {
9235 // Check that the addresses are consecutive starting from the second
9236 // element in the list of stores.
9238 int64_t CurrAddress = StoreNodes[i].OffsetFromBase;
9239 if (CurrAddress - StartAddress != (ElementSizeBytes * i))
9244 // Check if this store interferes with any of the loads that we found.
9245 for (unsigned ld = 0, lde = AliasLoadNodes.size(); ld < lde; ++ld)
9246 if (isAlias(AliasLoadNodes[ld], StoreNodes[i].MemNode)) {
9250 // We found a load that alias with this store. Stop the sequence.
9254 // Mark this node as useful.
9255 LastConsecutiveStore = i;
9258 // The node with the lowest store address.
9259 LSBaseSDNode *FirstInChain = StoreNodes[0].MemNode;
9261 // Store the constants into memory as one consecutive store.
9263 unsigned LastLegalType = 0;
9264 unsigned LastLegalVectorType = 0;
9265 bool NonZero = false;
9266 for (unsigned i=0; i<LastConsecutiveStore+1; ++i) {
9267 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
9268 SDValue StoredVal = St->getValue();
9270 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(StoredVal)) {
9271 NonZero |= !C->isNullValue();
9272 } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(StoredVal)) {
9273 NonZero |= !C->getConstantFPValue()->isNullValue();
9279 // Find a legal type for the constant store.
9280 unsigned StoreBW = (i+1) * ElementSizeBytes * 8;
9281 EVT StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
9282 if (TLI.isTypeLegal(StoreTy))
9283 LastLegalType = i+1;
9284 // Or check whether a truncstore is legal.
9285 else if (TLI.getTypeAction(*DAG.getContext(), StoreTy) ==
9286 TargetLowering::TypePromoteInteger) {
9287 EVT LegalizedStoredValueTy =
9288 TLI.getTypeToTransformTo(*DAG.getContext(), StoredVal.getValueType());
9289 if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy))
9290 LastLegalType = i+1;
9293 // Find a legal type for the vector store.
9294 EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT, i+1);
9295 if (TLI.isTypeLegal(Ty))
9296 LastLegalVectorType = i + 1;
9299 // We only use vectors if the constant is known to be zero and the
9300 // function is not marked with the noimplicitfloat attribute.
9301 if (NonZero || NoVectors)
9302 LastLegalVectorType = 0;
9304 // Check if we found a legal integer type to store.
9305 if (LastLegalType == 0 && LastLegalVectorType == 0)
9308 bool UseVector = (LastLegalVectorType > LastLegalType) && !NoVectors;
9309 unsigned NumElem = UseVector ? LastLegalVectorType : LastLegalType;
9311 // Make sure we have something to merge.
9315 unsigned EarliestNodeUsed = 0;
9316 for (unsigned i=0; i < NumElem; ++i) {
9317 // Find a chain for the new wide-store operand. Notice that some
9318 // of the store nodes that we found may not be selected for inclusion
9319 // in the wide store. The chain we use needs to be the chain of the
9320 // earliest store node which is *used* and replaced by the wide store.
9321 if (StoreNodes[i].SequenceNum > StoreNodes[EarliestNodeUsed].SequenceNum)
9322 EarliestNodeUsed = i;
9325 // The earliest Node in the DAG.
9326 LSBaseSDNode *EarliestOp = StoreNodes[EarliestNodeUsed].MemNode;
9327 SDLoc DL(StoreNodes[0].MemNode);
9331 // Find a legal type for the vector store.
9332 EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT, NumElem);
9333 assert(TLI.isTypeLegal(Ty) && "Illegal vector store");
9334 StoredVal = DAG.getConstant(0, Ty);
9336 unsigned StoreBW = NumElem * ElementSizeBytes * 8;
9337 APInt StoreInt(StoreBW, 0);
9339 // Construct a single integer constant which is made of the smaller
9341 bool IsLE = TLI.isLittleEndian();
9342 for (unsigned i = 0; i < NumElem ; ++i) {
9343 unsigned Idx = IsLE ?(NumElem - 1 - i) : i;
9344 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[Idx].MemNode);
9345 SDValue Val = St->getValue();
9346 StoreInt<<=ElementSizeBytes*8;
9347 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Val)) {
9348 StoreInt|=C->getAPIntValue().zext(StoreBW);
9349 } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Val)) {
9350 StoreInt|= C->getValueAPF().bitcastToAPInt().zext(StoreBW);
9352 assert(false && "Invalid constant element type");
9356 // Create the new Load and Store operations.
9357 EVT StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
9358 StoredVal = DAG.getConstant(StoreInt, StoreTy);
9361 SDValue NewStore = DAG.getStore(EarliestOp->getChain(), DL, StoredVal,
9362 FirstInChain->getBasePtr(),
9363 FirstInChain->getPointerInfo(),
9365 FirstInChain->getAlignment());
9367 // Replace the first store with the new store
9368 CombineTo(EarliestOp, NewStore);
9369 // Erase all other stores.
9370 for (unsigned i = 0; i < NumElem ; ++i) {
9371 if (StoreNodes[i].MemNode == EarliestOp)
9373 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
9374 // ReplaceAllUsesWith will replace all uses that existed when it was
9375 // called, but graph optimizations may cause new ones to appear. For
9376 // example, the case in pr14333 looks like
9378 // St's chain -> St -> another store -> X
9380 // And the only difference from St to the other store is the chain.
9381 // When we change it's chain to be St's chain they become identical,
9382 // get CSEed and the net result is that X is now a use of St.
9383 // Since we know that St is redundant, just iterate.
9384 while (!St->use_empty())
9385 DAG.ReplaceAllUsesWith(SDValue(St, 0), St->getChain());
9386 deleteAndRecombine(St);
9392 // Below we handle the case of multiple consecutive stores that
9393 // come from multiple consecutive loads. We merge them into a single
9394 // wide load and a single wide store.
9396 // Look for load nodes which are used by the stored values.
9397 SmallVector<MemOpLink, 8> LoadNodes;
9399 // Find acceptable loads. Loads need to have the same chain (token factor),
9400 // must not be zext, volatile, indexed, and they must be consecutive.
9401 BaseIndexOffset LdBasePtr;
9402 for (unsigned i=0; i<LastConsecutiveStore+1; ++i) {
9403 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
9404 LoadSDNode *Ld = dyn_cast<LoadSDNode>(St->getValue());
9407 // Loads must only have one use.
9408 if (!Ld->hasNUsesOfValue(1, 0))
9411 // Check that the alignment is the same as the stores.
9412 if (Ld->getAlignment() != St->getAlignment())
9415 // The memory operands must not be volatile.
9416 if (Ld->isVolatile() || Ld->isIndexed())
9419 // We do not accept ext loads.
9420 if (Ld->getExtensionType() != ISD::NON_EXTLOAD)
9423 // The stored memory type must be the same.
9424 if (Ld->getMemoryVT() != MemVT)
9427 BaseIndexOffset LdPtr = BaseIndexOffset::match(Ld->getBasePtr());
9428 // If this is not the first ptr that we check.
9429 if (LdBasePtr.Base.getNode()) {
9430 // The base ptr must be the same.
9431 if (!LdPtr.equalBaseIndex(LdBasePtr))
9434 // Check that all other base pointers are the same as this one.
9438 // We found a potential memory operand to merge.
9439 LoadNodes.push_back(MemOpLink(Ld, LdPtr.Offset, 0));
9442 if (LoadNodes.size() < 2)
9445 // If we have load/store pair instructions and we only have two values,
9447 unsigned RequiredAlignment;
9448 if (LoadNodes.size() == 2 && TLI.hasPairedLoad(MemVT, RequiredAlignment) &&
9449 St->getAlignment() >= RequiredAlignment)
9452 // Scan the memory operations on the chain and find the first non-consecutive
9453 // load memory address. These variables hold the index in the store node
9455 unsigned LastConsecutiveLoad = 0;
9456 // This variable refers to the size and not index in the array.
9457 unsigned LastLegalVectorType = 0;
9458 unsigned LastLegalIntegerType = 0;
9459 StartAddress = LoadNodes[0].OffsetFromBase;
9460 SDValue FirstChain = LoadNodes[0].MemNode->getChain();
9461 for (unsigned i = 1; i < LoadNodes.size(); ++i) {
9462 // All loads much share the same chain.
9463 if (LoadNodes[i].MemNode->getChain() != FirstChain)
9466 int64_t CurrAddress = LoadNodes[i].OffsetFromBase;
9467 if (CurrAddress - StartAddress != (ElementSizeBytes * i))
9469 LastConsecutiveLoad = i;
9471 // Find a legal type for the vector store.
9472 EVT StoreTy = EVT::getVectorVT(*DAG.getContext(), MemVT, i+1);
9473 if (TLI.isTypeLegal(StoreTy))
9474 LastLegalVectorType = i + 1;
9476 // Find a legal type for the integer store.
9477 unsigned StoreBW = (i+1) * ElementSizeBytes * 8;
9478 StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
9479 if (TLI.isTypeLegal(StoreTy))
9480 LastLegalIntegerType = i + 1;
9481 // Or check whether a truncstore and extload is legal.
9482 else if (TLI.getTypeAction(*DAG.getContext(), StoreTy) ==
9483 TargetLowering::TypePromoteInteger) {
9484 EVT LegalizedStoredValueTy =
9485 TLI.getTypeToTransformTo(*DAG.getContext(), StoreTy);
9486 if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy) &&
9487 TLI.isLoadExtLegal(ISD::ZEXTLOAD, StoreTy) &&
9488 TLI.isLoadExtLegal(ISD::SEXTLOAD, StoreTy) &&
9489 TLI.isLoadExtLegal(ISD::EXTLOAD, StoreTy))
9490 LastLegalIntegerType = i+1;
9494 // Only use vector types if the vector type is larger than the integer type.
9495 // If they are the same, use integers.
9496 bool UseVectorTy = LastLegalVectorType > LastLegalIntegerType && !NoVectors;
9497 unsigned LastLegalType = std::max(LastLegalVectorType, LastLegalIntegerType);
9499 // We add +1 here because the LastXXX variables refer to location while
9500 // the NumElem refers to array/index size.
9501 unsigned NumElem = std::min(LastConsecutiveStore, LastConsecutiveLoad) + 1;
9502 NumElem = std::min(LastLegalType, NumElem);
9507 // The earliest Node in the DAG.
9508 unsigned EarliestNodeUsed = 0;
9509 LSBaseSDNode *EarliestOp = StoreNodes[EarliestNodeUsed].MemNode;
9510 for (unsigned i=1; i<NumElem; ++i) {
9511 // Find a chain for the new wide-store operand. Notice that some
9512 // of the store nodes that we found may not be selected for inclusion
9513 // in the wide store. The chain we use needs to be the chain of the
9514 // earliest store node which is *used* and replaced by the wide store.
9515 if (StoreNodes[i].SequenceNum > StoreNodes[EarliestNodeUsed].SequenceNum)
9516 EarliestNodeUsed = i;
9519 // Find if it is better to use vectors or integers to load and store
9523 JointMemOpVT = EVT::getVectorVT(*DAG.getContext(), MemVT, NumElem);
9525 unsigned StoreBW = NumElem * ElementSizeBytes * 8;
9526 JointMemOpVT = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
9529 SDLoc LoadDL(LoadNodes[0].MemNode);
9530 SDLoc StoreDL(StoreNodes[0].MemNode);
9532 LoadSDNode *FirstLoad = cast<LoadSDNode>(LoadNodes[0].MemNode);
9533 SDValue NewLoad = DAG.getLoad(JointMemOpVT, LoadDL,
9534 FirstLoad->getChain(),
9535 FirstLoad->getBasePtr(),
9536 FirstLoad->getPointerInfo(),
9537 false, false, false,
9538 FirstLoad->getAlignment());
9540 SDValue NewStore = DAG.getStore(EarliestOp->getChain(), StoreDL, NewLoad,
9541 FirstInChain->getBasePtr(),
9542 FirstInChain->getPointerInfo(), false, false,
9543 FirstInChain->getAlignment());
9545 // Replace one of the loads with the new load.
9546 LoadSDNode *Ld = cast<LoadSDNode>(LoadNodes[0].MemNode);
9547 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1),
9548 SDValue(NewLoad.getNode(), 1));
9550 // Remove the rest of the load chains.
9551 for (unsigned i = 1; i < NumElem ; ++i) {
9552 // Replace all chain users of the old load nodes with the chain of the new
9554 LoadSDNode *Ld = cast<LoadSDNode>(LoadNodes[i].MemNode);
9555 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), Ld->getChain());
9558 // Replace the first store with the new store.
9559 CombineTo(EarliestOp, NewStore);
9560 // Erase all other stores.
9561 for (unsigned i = 0; i < NumElem ; ++i) {
9562 // Remove all Store nodes.
9563 if (StoreNodes[i].MemNode == EarliestOp)
9565 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
9566 DAG.ReplaceAllUsesOfValueWith(SDValue(St, 0), St->getChain());
9567 deleteAndRecombine(St);
9573 SDValue DAGCombiner::visitSTORE(SDNode *N) {
9574 StoreSDNode *ST = cast<StoreSDNode>(N);
9575 SDValue Chain = ST->getChain();
9576 SDValue Value = ST->getValue();
9577 SDValue Ptr = ST->getBasePtr();
9579 // If this is a store of a bit convert, store the input value if the
9580 // resultant store does not need a higher alignment than the original.
9581 if (Value.getOpcode() == ISD::BITCAST && !ST->isTruncatingStore() &&
9582 ST->isUnindexed()) {
9583 unsigned OrigAlign = ST->getAlignment();
9584 EVT SVT = Value.getOperand(0).getValueType();
9585 unsigned Align = TLI.getDataLayout()->
9586 getABITypeAlignment(SVT.getTypeForEVT(*DAG.getContext()));
9587 if (Align <= OrigAlign &&
9588 ((!LegalOperations && !ST->isVolatile()) ||
9589 TLI.isOperationLegalOrCustom(ISD::STORE, SVT)))
9590 return DAG.getStore(Chain, SDLoc(N), Value.getOperand(0),
9591 Ptr, ST->getPointerInfo(), ST->isVolatile(),
9592 ST->isNonTemporal(), OrigAlign,
9596 // Turn 'store undef, Ptr' -> nothing.
9597 if (Value.getOpcode() == ISD::UNDEF && ST->isUnindexed())
9600 // Turn 'store float 1.0, Ptr' -> 'store int 0x12345678, Ptr'
9601 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Value)) {
9602 // NOTE: If the original store is volatile, this transform must not increase
9603 // the number of stores. For example, on x86-32 an f64 can be stored in one
9604 // processor operation but an i64 (which is not legal) requires two. So the
9605 // transform should not be done in this case.
9606 if (Value.getOpcode() != ISD::TargetConstantFP) {
9608 switch (CFP->getSimpleValueType(0).SimpleTy) {
9609 default: llvm_unreachable("Unknown FP type");
9610 case MVT::f16: // We don't do this for these yet.
9616 if ((isTypeLegal(MVT::i32) && !LegalOperations && !ST->isVolatile()) ||
9617 TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) {
9618 Tmp = DAG.getConstant((uint32_t)CFP->getValueAPF().
9619 bitcastToAPInt().getZExtValue(), MVT::i32);
9620 return DAG.getStore(Chain, SDLoc(N), Tmp,
9621 Ptr, ST->getMemOperand());
9625 if ((TLI.isTypeLegal(MVT::i64) && !LegalOperations &&
9626 !ST->isVolatile()) ||
9627 TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i64)) {
9628 Tmp = DAG.getConstant(CFP->getValueAPF().bitcastToAPInt().
9629 getZExtValue(), MVT::i64);
9630 return DAG.getStore(Chain, SDLoc(N), Tmp,
9631 Ptr, ST->getMemOperand());
9634 if (!ST->isVolatile() &&
9635 TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) {
9636 // Many FP stores are not made apparent until after legalize, e.g. for
9637 // argument passing. Since this is so common, custom legalize the
9638 // 64-bit integer store into two 32-bit stores.
9639 uint64_t Val = CFP->getValueAPF().bitcastToAPInt().getZExtValue();
9640 SDValue Lo = DAG.getConstant(Val & 0xFFFFFFFF, MVT::i32);
9641 SDValue Hi = DAG.getConstant(Val >> 32, MVT::i32);
9642 if (TLI.isBigEndian()) std::swap(Lo, Hi);
9644 unsigned Alignment = ST->getAlignment();
9645 bool isVolatile = ST->isVolatile();
9646 bool isNonTemporal = ST->isNonTemporal();
9647 AAMDNodes AAInfo = ST->getAAInfo();
9649 SDValue St0 = DAG.getStore(Chain, SDLoc(ST), Lo,
9650 Ptr, ST->getPointerInfo(),
9651 isVolatile, isNonTemporal,
9652 ST->getAlignment(), AAInfo);
9653 Ptr = DAG.getNode(ISD::ADD, SDLoc(N), Ptr.getValueType(), Ptr,
9654 DAG.getConstant(4, Ptr.getValueType()));
9655 Alignment = MinAlign(Alignment, 4U);
9656 SDValue St1 = DAG.getStore(Chain, SDLoc(ST), Hi,
9657 Ptr, ST->getPointerInfo().getWithOffset(4),
9658 isVolatile, isNonTemporal,
9660 return DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other,
9669 // Try to infer better alignment information than the store already has.
9670 if (OptLevel != CodeGenOpt::None && ST->isUnindexed()) {
9671 if (unsigned Align = DAG.InferPtrAlignment(Ptr)) {
9672 if (Align > ST->getAlignment())
9673 return DAG.getTruncStore(Chain, SDLoc(N), Value,
9674 Ptr, ST->getPointerInfo(), ST->getMemoryVT(),
9675 ST->isVolatile(), ST->isNonTemporal(), Align,
9680 // Try transforming a pair floating point load / store ops to integer
9681 // load / store ops.
9682 SDValue NewST = TransformFPLoadStorePair(N);
9683 if (NewST.getNode())
9686 bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA :
9687 TLI.getTargetMachine().getSubtarget<TargetSubtargetInfo>().useAA();
9689 if (CombinerAAOnlyFunc.getNumOccurrences() &&
9690 CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
9693 if (UseAA && ST->isUnindexed()) {
9694 // Walk up chain skipping non-aliasing memory nodes.
9695 SDValue BetterChain = FindBetterChain(N, Chain);
9697 // If there is a better chain.
9698 if (Chain != BetterChain) {
9701 // Replace the chain to avoid dependency.
9702 if (ST->isTruncatingStore()) {
9703 ReplStore = DAG.getTruncStore(BetterChain, SDLoc(N), Value, Ptr,
9704 ST->getMemoryVT(), ST->getMemOperand());
9706 ReplStore = DAG.getStore(BetterChain, SDLoc(N), Value, Ptr,
9707 ST->getMemOperand());
9710 // Create token to keep both nodes around.
9711 SDValue Token = DAG.getNode(ISD::TokenFactor, SDLoc(N),
9712 MVT::Other, Chain, ReplStore);
9714 // Make sure the new and old chains are cleaned up.
9715 AddToWorklist(Token.getNode());
9717 // Don't add users to work list.
9718 return CombineTo(N, Token, false);
9722 // Try transforming N to an indexed store.
9723 if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
9724 return SDValue(N, 0);
9726 // FIXME: is there such a thing as a truncating indexed store?
9727 if (ST->isTruncatingStore() && ST->isUnindexed() &&
9728 Value.getValueType().isInteger()) {
9729 // See if we can simplify the input to this truncstore with knowledge that
9730 // only the low bits are being used. For example:
9731 // "truncstore (or (shl x, 8), y), i8" -> "truncstore y, i8"
9733 GetDemandedBits(Value,
9734 APInt::getLowBitsSet(
9735 Value.getValueType().getScalarType().getSizeInBits(),
9736 ST->getMemoryVT().getScalarType().getSizeInBits()));
9737 AddToWorklist(Value.getNode());
9738 if (Shorter.getNode())
9739 return DAG.getTruncStore(Chain, SDLoc(N), Shorter,
9740 Ptr, ST->getMemoryVT(), ST->getMemOperand());
9742 // Otherwise, see if we can simplify the operation with
9743 // SimplifyDemandedBits, which only works if the value has a single use.
9744 if (SimplifyDemandedBits(Value,
9745 APInt::getLowBitsSet(
9746 Value.getValueType().getScalarType().getSizeInBits(),
9747 ST->getMemoryVT().getScalarType().getSizeInBits())))
9748 return SDValue(N, 0);
9751 // If this is a load followed by a store to the same location, then the store
9753 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Value)) {
9754 if (Ld->getBasePtr() == Ptr && ST->getMemoryVT() == Ld->getMemoryVT() &&
9755 ST->isUnindexed() && !ST->isVolatile() &&
9756 // There can't be any side effects between the load and store, such as
9758 Chain.reachesChainWithoutSideEffects(SDValue(Ld, 1))) {
9759 // The store is dead, remove it.
9764 // If this is an FP_ROUND or TRUNC followed by a store, fold this into a
9765 // truncating store. We can do this even if this is already a truncstore.
9766 if ((Value.getOpcode() == ISD::FP_ROUND || Value.getOpcode() == ISD::TRUNCATE)
9767 && Value.getNode()->hasOneUse() && ST->isUnindexed() &&
9768 TLI.isTruncStoreLegal(Value.getOperand(0).getValueType(),
9769 ST->getMemoryVT())) {
9770 return DAG.getTruncStore(Chain, SDLoc(N), Value.getOperand(0),
9771 Ptr, ST->getMemoryVT(), ST->getMemOperand());
9774 // Only perform this optimization before the types are legal, because we
9775 // don't want to perform this optimization on every DAGCombine invocation.
9777 bool EverChanged = false;
9780 // There can be multiple store sequences on the same chain.
9781 // Keep trying to merge store sequences until we are unable to do so
9782 // or until we merge the last store on the chain.
9783 bool Changed = MergeConsecutiveStores(ST);
9784 EverChanged |= Changed;
9785 if (!Changed) break;
9786 } while (ST->getOpcode() != ISD::DELETED_NODE);
9789 return SDValue(N, 0);
9792 return ReduceLoadOpStoreWidth(N);
9795 SDValue DAGCombiner::visitINSERT_VECTOR_ELT(SDNode *N) {
9796 SDValue InVec = N->getOperand(0);
9797 SDValue InVal = N->getOperand(1);
9798 SDValue EltNo = N->getOperand(2);
9801 // If the inserted element is an UNDEF, just use the input vector.
9802 if (InVal.getOpcode() == ISD::UNDEF)
9805 EVT VT = InVec.getValueType();
9807 // If we can't generate a legal BUILD_VECTOR, exit
9808 if (LegalOperations && !TLI.isOperationLegal(ISD::BUILD_VECTOR, VT))
9811 // Check that we know which element is being inserted
9812 if (!isa<ConstantSDNode>(EltNo))
9814 unsigned Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
9816 // Canonicalize insert_vector_elt dag nodes.
9818 // (insert_vector_elt (insert_vector_elt A, Idx0), Idx1)
9819 // -> (insert_vector_elt (insert_vector_elt A, Idx1), Idx0)
9821 // Do this only if the child insert_vector node has one use; also
9822 // do this only if indices are both constants and Idx1 < Idx0.
9823 if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT && InVec.hasOneUse()
9824 && isa<ConstantSDNode>(InVec.getOperand(2))) {
9826 cast<ConstantSDNode>(InVec.getOperand(2))->getZExtValue();
9827 if (Elt < OtherElt) {
9829 SDValue NewOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, SDLoc(N), VT,
9830 InVec.getOperand(0), InVal, EltNo);
9831 AddToWorklist(NewOp.getNode());
9832 return DAG.getNode(ISD::INSERT_VECTOR_ELT, SDLoc(InVec.getNode()),
9833 VT, NewOp, InVec.getOperand(1), InVec.getOperand(2));
9837 // Check that the operand is a BUILD_VECTOR (or UNDEF, which can essentially
9838 // be converted to a BUILD_VECTOR). Fill in the Ops vector with the
9840 SmallVector<SDValue, 8> Ops;
9841 // Do not combine these two vectors if the output vector will not replace
9842 // the input vector.
9843 if (InVec.getOpcode() == ISD::BUILD_VECTOR && InVec.hasOneUse()) {
9844 Ops.append(InVec.getNode()->op_begin(),
9845 InVec.getNode()->op_end());
9846 } else if (InVec.getOpcode() == ISD::UNDEF) {
9847 unsigned NElts = VT.getVectorNumElements();
9848 Ops.append(NElts, DAG.getUNDEF(InVal.getValueType()));
9853 // Insert the element
9854 if (Elt < Ops.size()) {
9855 // All the operands of BUILD_VECTOR must have the same type;
9856 // we enforce that here.
9857 EVT OpVT = Ops[0].getValueType();
9858 if (InVal.getValueType() != OpVT)
9859 InVal = OpVT.bitsGT(InVal.getValueType()) ?
9860 DAG.getNode(ISD::ANY_EXTEND, dl, OpVT, InVal) :
9861 DAG.getNode(ISD::TRUNCATE, dl, OpVT, InVal);
9865 // Return the new vector
9866 return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
9869 SDValue DAGCombiner::ReplaceExtractVectorEltOfLoadWithNarrowedLoad(
9870 SDNode *EVE, EVT InVecVT, SDValue EltNo, LoadSDNode *OriginalLoad) {
9871 EVT ResultVT = EVE->getValueType(0);
9872 EVT VecEltVT = InVecVT.getVectorElementType();
9873 unsigned Align = OriginalLoad->getAlignment();
9874 unsigned NewAlign = TLI.getDataLayout()->getABITypeAlignment(
9875 VecEltVT.getTypeForEVT(*DAG.getContext()));
9877 if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, VecEltVT))
9882 SDValue NewPtr = OriginalLoad->getBasePtr();
9884 EVT PtrType = NewPtr.getValueType();
9885 MachinePointerInfo MPI;
9886 if (auto *ConstEltNo = dyn_cast<ConstantSDNode>(EltNo)) {
9887 int Elt = ConstEltNo->getZExtValue();
9888 unsigned PtrOff = VecEltVT.getSizeInBits() * Elt / 8;
9889 if (TLI.isBigEndian())
9890 PtrOff = InVecVT.getSizeInBits() / 8 - PtrOff;
9891 Offset = DAG.getConstant(PtrOff, PtrType);
9892 MPI = OriginalLoad->getPointerInfo().getWithOffset(PtrOff);
9894 Offset = DAG.getNode(
9895 ISD::MUL, SDLoc(EVE), EltNo.getValueType(), EltNo,
9896 DAG.getConstant(VecEltVT.getStoreSize(), EltNo.getValueType()));
9897 if (TLI.isBigEndian())
9898 Offset = DAG.getNode(
9899 ISD::SUB, SDLoc(EVE), EltNo.getValueType(),
9900 DAG.getConstant(InVecVT.getStoreSize(), EltNo.getValueType()), Offset);
9901 MPI = OriginalLoad->getPointerInfo();
9903 NewPtr = DAG.getNode(ISD::ADD, SDLoc(EVE), PtrType, NewPtr, Offset);
9905 // The replacement we need to do here is a little tricky: we need to
9906 // replace an extractelement of a load with a load.
9907 // Use ReplaceAllUsesOfValuesWith to do the replacement.
9908 // Note that this replacement assumes that the extractvalue is the only
9909 // use of the load; that's okay because we don't want to perform this
9910 // transformation in other cases anyway.
9913 if (ResultVT.bitsGT(VecEltVT)) {
9914 // If the result type of vextract is wider than the load, then issue an
9915 // extending load instead.
9916 ISD::LoadExtType ExtType = TLI.isLoadExtLegal(ISD::ZEXTLOAD, VecEltVT)
9919 Load = DAG.getExtLoad(
9920 ExtType, SDLoc(EVE), ResultVT, OriginalLoad->getChain(), NewPtr, MPI,
9921 VecEltVT, OriginalLoad->isVolatile(), OriginalLoad->isNonTemporal(),
9922 OriginalLoad->isInvariant(), Align, OriginalLoad->getAAInfo());
9923 Chain = Load.getValue(1);
9926 VecEltVT, SDLoc(EVE), OriginalLoad->getChain(), NewPtr, MPI,
9927 OriginalLoad->isVolatile(), OriginalLoad->isNonTemporal(),
9928 OriginalLoad->isInvariant(), Align, OriginalLoad->getAAInfo());
9929 Chain = Load.getValue(1);
9930 if (ResultVT.bitsLT(VecEltVT))
9931 Load = DAG.getNode(ISD::TRUNCATE, SDLoc(EVE), ResultVT, Load);
9933 Load = DAG.getNode(ISD::BITCAST, SDLoc(EVE), ResultVT, Load);
9935 WorklistRemover DeadNodes(*this);
9936 SDValue From[] = { SDValue(EVE, 0), SDValue(OriginalLoad, 1) };
9937 SDValue To[] = { Load, Chain };
9938 DAG.ReplaceAllUsesOfValuesWith(From, To, 2);
9939 // Since we're explicitly calling ReplaceAllUses, add the new node to the
9940 // worklist explicitly as well.
9941 AddToWorklist(Load.getNode());
9942 AddUsersToWorklist(Load.getNode()); // Add users too
9943 // Make sure to revisit this node to clean it up; it will usually be dead.
9946 return SDValue(EVE, 0);
9949 SDValue DAGCombiner::visitEXTRACT_VECTOR_ELT(SDNode *N) {
9950 // (vextract (scalar_to_vector val, 0) -> val
9951 SDValue InVec = N->getOperand(0);
9952 EVT VT = InVec.getValueType();
9953 EVT NVT = N->getValueType(0);
9955 if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR) {
9956 // Check if the result type doesn't match the inserted element type. A
9957 // SCALAR_TO_VECTOR may truncate the inserted element and the
9958 // EXTRACT_VECTOR_ELT may widen the extracted vector.
9959 SDValue InOp = InVec.getOperand(0);
9960 if (InOp.getValueType() != NVT) {
9961 assert(InOp.getValueType().isInteger() && NVT.isInteger());
9962 return DAG.getSExtOrTrunc(InOp, SDLoc(InVec), NVT);
9967 SDValue EltNo = N->getOperand(1);
9968 bool ConstEltNo = isa<ConstantSDNode>(EltNo);
9970 // Transform: (EXTRACT_VECTOR_ELT( VECTOR_SHUFFLE )) -> EXTRACT_VECTOR_ELT.
9971 // We only perform this optimization before the op legalization phase because
9972 // we may introduce new vector instructions which are not backed by TD
9973 // patterns. For example on AVX, extracting elements from a wide vector
9974 // without using extract_subvector. However, if we can find an underlying
9975 // scalar value, then we can always use that.
9976 if (InVec.getOpcode() == ISD::VECTOR_SHUFFLE
9978 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
9979 int NumElem = VT.getVectorNumElements();
9980 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(InVec);
9981 // Find the new index to extract from.
9982 int OrigElt = SVOp->getMaskElt(Elt);
9984 // Extracting an undef index is undef.
9986 return DAG.getUNDEF(NVT);
9988 // Select the right vector half to extract from.
9990 if (OrigElt < NumElem) {
9991 SVInVec = InVec->getOperand(0);
9993 SVInVec = InVec->getOperand(1);
9997 if (SVInVec.getOpcode() == ISD::BUILD_VECTOR) {
9998 SDValue InOp = SVInVec.getOperand(OrigElt);
9999 if (InOp.getValueType() != NVT) {
10000 assert(InOp.getValueType().isInteger() && NVT.isInteger());
10001 InOp = DAG.getSExtOrTrunc(InOp, SDLoc(SVInVec), NVT);
10007 // FIXME: We should handle recursing on other vector shuffles and
10008 // scalar_to_vector here as well.
10010 if (!LegalOperations) {
10011 EVT IndexTy = TLI.getVectorIdxTy();
10012 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SDLoc(N), NVT,
10013 SVInVec, DAG.getConstant(OrigElt, IndexTy));
10017 bool BCNumEltsChanged = false;
10018 EVT ExtVT = VT.getVectorElementType();
10021 // If the result of load has to be truncated, then it's not necessarily
10023 if (NVT.bitsLT(LVT) && !TLI.isTruncateFree(LVT, NVT))
10026 if (InVec.getOpcode() == ISD::BITCAST) {
10027 // Don't duplicate a load with other uses.
10028 if (!InVec.hasOneUse())
10031 EVT BCVT = InVec.getOperand(0).getValueType();
10032 if (!BCVT.isVector() || ExtVT.bitsGT(BCVT.getVectorElementType()))
10034 if (VT.getVectorNumElements() != BCVT.getVectorNumElements())
10035 BCNumEltsChanged = true;
10036 InVec = InVec.getOperand(0);
10037 ExtVT = BCVT.getVectorElementType();
10040 // (vextract (vN[if]M load $addr), i) -> ([if]M load $addr + i * size)
10041 if (!LegalOperations && !ConstEltNo && InVec.hasOneUse() &&
10042 ISD::isNormalLoad(InVec.getNode()) &&
10043 !N->getOperand(1)->hasPredecessor(InVec.getNode())) {
10044 SDValue Index = N->getOperand(1);
10045 if (LoadSDNode *OrigLoad = dyn_cast<LoadSDNode>(InVec))
10046 return ReplaceExtractVectorEltOfLoadWithNarrowedLoad(N, VT, Index,
10050 // Perform only after legalization to ensure build_vector / vector_shuffle
10051 // optimizations have already been done.
10052 if (!LegalOperations) return SDValue();
10054 // (vextract (v4f32 load $addr), c) -> (f32 load $addr+c*size)
10055 // (vextract (v4f32 s2v (f32 load $addr)), c) -> (f32 load $addr+c*size)
10056 // (vextract (v4f32 shuffle (load $addr), <1,u,u,u>), 0) -> (f32 load $addr)
10059 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
10061 LoadSDNode *LN0 = nullptr;
10062 const ShuffleVectorSDNode *SVN = nullptr;
10063 if (ISD::isNormalLoad(InVec.getNode())) {
10064 LN0 = cast<LoadSDNode>(InVec);
10065 } else if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR &&
10066 InVec.getOperand(0).getValueType() == ExtVT &&
10067 ISD::isNormalLoad(InVec.getOperand(0).getNode())) {
10068 // Don't duplicate a load with other uses.
10069 if (!InVec.hasOneUse())
10072 LN0 = cast<LoadSDNode>(InVec.getOperand(0));
10073 } else if ((SVN = dyn_cast<ShuffleVectorSDNode>(InVec))) {
10074 // (vextract (vector_shuffle (load $addr), v2, <1, u, u, u>), 1)
10076 // (load $addr+1*size)
10078 // Don't duplicate a load with other uses.
10079 if (!InVec.hasOneUse())
10082 // If the bit convert changed the number of elements, it is unsafe
10083 // to examine the mask.
10084 if (BCNumEltsChanged)
10087 // Select the input vector, guarding against out of range extract vector.
10088 unsigned NumElems = VT.getVectorNumElements();
10089 int Idx = (Elt > (int)NumElems) ? -1 : SVN->getMaskElt(Elt);
10090 InVec = (Idx < (int)NumElems) ? InVec.getOperand(0) : InVec.getOperand(1);
10092 if (InVec.getOpcode() == ISD::BITCAST) {
10093 // Don't duplicate a load with other uses.
10094 if (!InVec.hasOneUse())
10097 InVec = InVec.getOperand(0);
10099 if (ISD::isNormalLoad(InVec.getNode())) {
10100 LN0 = cast<LoadSDNode>(InVec);
10101 Elt = (Idx < (int)NumElems) ? Idx : Idx - (int)NumElems;
10102 EltNo = DAG.getConstant(Elt, EltNo.getValueType());
10106 // Make sure we found a non-volatile load and the extractelement is
10108 if (!LN0 || !LN0->hasNUsesOfValue(1,0) || LN0->isVolatile())
10111 // If Idx was -1 above, Elt is going to be -1, so just return undef.
10113 return DAG.getUNDEF(LVT);
10115 return ReplaceExtractVectorEltOfLoadWithNarrowedLoad(N, VT, EltNo, LN0);
10121 // Simplify (build_vec (ext )) to (bitcast (build_vec ))
10122 SDValue DAGCombiner::reduceBuildVecExtToExtBuildVec(SDNode *N) {
10123 // We perform this optimization post type-legalization because
10124 // the type-legalizer often scalarizes integer-promoted vectors.
10125 // Performing this optimization before may create bit-casts which
10126 // will be type-legalized to complex code sequences.
10127 // We perform this optimization only before the operation legalizer because we
10128 // may introduce illegal operations.
10129 if (Level != AfterLegalizeVectorOps && Level != AfterLegalizeTypes)
10132 unsigned NumInScalars = N->getNumOperands();
10134 EVT VT = N->getValueType(0);
10136 // Check to see if this is a BUILD_VECTOR of a bunch of values
10137 // which come from any_extend or zero_extend nodes. If so, we can create
10138 // a new BUILD_VECTOR using bit-casts which may enable other BUILD_VECTOR
10139 // optimizations. We do not handle sign-extend because we can't fill the sign
10141 EVT SourceType = MVT::Other;
10142 bool AllAnyExt = true;
10144 for (unsigned i = 0; i != NumInScalars; ++i) {
10145 SDValue In = N->getOperand(i);
10146 // Ignore undef inputs.
10147 if (In.getOpcode() == ISD::UNDEF) continue;
10149 bool AnyExt = In.getOpcode() == ISD::ANY_EXTEND;
10150 bool ZeroExt = In.getOpcode() == ISD::ZERO_EXTEND;
10152 // Abort if the element is not an extension.
10153 if (!ZeroExt && !AnyExt) {
10154 SourceType = MVT::Other;
10158 // The input is a ZeroExt or AnyExt. Check the original type.
10159 EVT InTy = In.getOperand(0).getValueType();
10161 // Check that all of the widened source types are the same.
10162 if (SourceType == MVT::Other)
10165 else if (InTy != SourceType) {
10166 // Multiple income types. Abort.
10167 SourceType = MVT::Other;
10171 // Check if all of the extends are ANY_EXTENDs.
10172 AllAnyExt &= AnyExt;
10175 // In order to have valid types, all of the inputs must be extended from the
10176 // same source type and all of the inputs must be any or zero extend.
10177 // Scalar sizes must be a power of two.
10178 EVT OutScalarTy = VT.getScalarType();
10179 bool ValidTypes = SourceType != MVT::Other &&
10180 isPowerOf2_32(OutScalarTy.getSizeInBits()) &&
10181 isPowerOf2_32(SourceType.getSizeInBits());
10183 // Create a new simpler BUILD_VECTOR sequence which other optimizations can
10184 // turn into a single shuffle instruction.
10188 bool isLE = TLI.isLittleEndian();
10189 unsigned ElemRatio = OutScalarTy.getSizeInBits()/SourceType.getSizeInBits();
10190 assert(ElemRatio > 1 && "Invalid element size ratio");
10191 SDValue Filler = AllAnyExt ? DAG.getUNDEF(SourceType):
10192 DAG.getConstant(0, SourceType);
10194 unsigned NewBVElems = ElemRatio * VT.getVectorNumElements();
10195 SmallVector<SDValue, 8> Ops(NewBVElems, Filler);
10197 // Populate the new build_vector
10198 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
10199 SDValue Cast = N->getOperand(i);
10200 assert((Cast.getOpcode() == ISD::ANY_EXTEND ||
10201 Cast.getOpcode() == ISD::ZERO_EXTEND ||
10202 Cast.getOpcode() == ISD::UNDEF) && "Invalid cast opcode");
10204 if (Cast.getOpcode() == ISD::UNDEF)
10205 In = DAG.getUNDEF(SourceType);
10207 In = Cast->getOperand(0);
10208 unsigned Index = isLE ? (i * ElemRatio) :
10209 (i * ElemRatio + (ElemRatio - 1));
10211 assert(Index < Ops.size() && "Invalid index");
10215 // The type of the new BUILD_VECTOR node.
10216 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), SourceType, NewBVElems);
10217 assert(VecVT.getSizeInBits() == VT.getSizeInBits() &&
10218 "Invalid vector size");
10219 // Check if the new vector type is legal.
10220 if (!isTypeLegal(VecVT)) return SDValue();
10222 // Make the new BUILD_VECTOR.
10223 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, VecVT, Ops);
10225 // The new BUILD_VECTOR node has the potential to be further optimized.
10226 AddToWorklist(BV.getNode());
10227 // Bitcast to the desired type.
10228 return DAG.getNode(ISD::BITCAST, dl, VT, BV);
10231 SDValue DAGCombiner::reduceBuildVecConvertToConvertBuildVec(SDNode *N) {
10232 EVT VT = N->getValueType(0);
10234 unsigned NumInScalars = N->getNumOperands();
10237 EVT SrcVT = MVT::Other;
10238 unsigned Opcode = ISD::DELETED_NODE;
10239 unsigned NumDefs = 0;
10241 for (unsigned i = 0; i != NumInScalars; ++i) {
10242 SDValue In = N->getOperand(i);
10243 unsigned Opc = In.getOpcode();
10245 if (Opc == ISD::UNDEF)
10248 // If all scalar values are floats and converted from integers.
10249 if (Opcode == ISD::DELETED_NODE &&
10250 (Opc == ISD::UINT_TO_FP || Opc == ISD::SINT_TO_FP)) {
10257 EVT InVT = In.getOperand(0).getValueType();
10259 // If all scalar values are typed differently, bail out. It's chosen to
10260 // simplify BUILD_VECTOR of integer types.
10261 if (SrcVT == MVT::Other)
10268 // If the vector has just one element defined, it's not worth to fold it into
10269 // a vectorized one.
10273 assert((Opcode == ISD::UINT_TO_FP || Opcode == ISD::SINT_TO_FP)
10274 && "Should only handle conversion from integer to float.");
10275 assert(SrcVT != MVT::Other && "Cannot determine source type!");
10277 EVT NVT = EVT::getVectorVT(*DAG.getContext(), SrcVT, NumInScalars);
10279 if (!TLI.isOperationLegalOrCustom(Opcode, NVT))
10282 SmallVector<SDValue, 8> Opnds;
10283 for (unsigned i = 0; i != NumInScalars; ++i) {
10284 SDValue In = N->getOperand(i);
10286 if (In.getOpcode() == ISD::UNDEF)
10287 Opnds.push_back(DAG.getUNDEF(SrcVT));
10289 Opnds.push_back(In.getOperand(0));
10291 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, NVT, Opnds);
10292 AddToWorklist(BV.getNode());
10294 return DAG.getNode(Opcode, dl, VT, BV);
10297 SDValue DAGCombiner::visitBUILD_VECTOR(SDNode *N) {
10298 unsigned NumInScalars = N->getNumOperands();
10300 EVT VT = N->getValueType(0);
10302 // A vector built entirely of undefs is undef.
10303 if (ISD::allOperandsUndef(N))
10304 return DAG.getUNDEF(VT);
10306 SDValue V = reduceBuildVecExtToExtBuildVec(N);
10310 V = reduceBuildVecConvertToConvertBuildVec(N);
10314 // Check to see if this is a BUILD_VECTOR of a bunch of EXTRACT_VECTOR_ELT
10315 // operations. If so, and if the EXTRACT_VECTOR_ELT vector inputs come from
10316 // at most two distinct vectors, turn this into a shuffle node.
10318 // May only combine to shuffle after legalize if shuffle is legal.
10319 if (LegalOperations &&
10320 !TLI.isOperationLegalOrCustom(ISD::VECTOR_SHUFFLE, VT))
10323 SDValue VecIn1, VecIn2;
10324 for (unsigned i = 0; i != NumInScalars; ++i) {
10325 // Ignore undef inputs.
10326 if (N->getOperand(i).getOpcode() == ISD::UNDEF) continue;
10328 // If this input is something other than a EXTRACT_VECTOR_ELT with a
10329 // constant index, bail out.
10330 if (N->getOperand(i).getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
10331 !isa<ConstantSDNode>(N->getOperand(i).getOperand(1))) {
10332 VecIn1 = VecIn2 = SDValue(nullptr, 0);
10336 // We allow up to two distinct input vectors.
10337 SDValue ExtractedFromVec = N->getOperand(i).getOperand(0);
10338 if (ExtractedFromVec == VecIn1 || ExtractedFromVec == VecIn2)
10341 if (!VecIn1.getNode()) {
10342 VecIn1 = ExtractedFromVec;
10343 } else if (!VecIn2.getNode()) {
10344 VecIn2 = ExtractedFromVec;
10346 // Too many inputs.
10347 VecIn1 = VecIn2 = SDValue(nullptr, 0);
10352 // If everything is good, we can make a shuffle operation.
10353 if (VecIn1.getNode()) {
10354 SmallVector<int, 8> Mask;
10355 for (unsigned i = 0; i != NumInScalars; ++i) {
10356 if (N->getOperand(i).getOpcode() == ISD::UNDEF) {
10357 Mask.push_back(-1);
10361 // If extracting from the first vector, just use the index directly.
10362 SDValue Extract = N->getOperand(i);
10363 SDValue ExtVal = Extract.getOperand(1);
10364 if (Extract.getOperand(0) == VecIn1) {
10365 unsigned ExtIndex = cast<ConstantSDNode>(ExtVal)->getZExtValue();
10366 if (ExtIndex > VT.getVectorNumElements())
10369 Mask.push_back(ExtIndex);
10373 // Otherwise, use InIdx + VecSize
10374 unsigned Idx = cast<ConstantSDNode>(ExtVal)->getZExtValue();
10375 Mask.push_back(Idx+NumInScalars);
10378 // We can't generate a shuffle node with mismatched input and output types.
10379 // Attempt to transform a single input vector to the correct type.
10380 if ((VT != VecIn1.getValueType())) {
10381 // We don't support shuffeling between TWO values of different types.
10382 if (VecIn2.getNode())
10385 // We only support widening of vectors which are half the size of the
10386 // output registers. For example XMM->YMM widening on X86 with AVX.
10387 if (VecIn1.getValueType().getSizeInBits()*2 != VT.getSizeInBits())
10390 // If the input vector type has a different base type to the output
10391 // vector type, bail out.
10392 if (VecIn1.getValueType().getVectorElementType() !=
10393 VT.getVectorElementType())
10396 // Widen the input vector by adding undef values.
10397 VecIn1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
10398 VecIn1, DAG.getUNDEF(VecIn1.getValueType()));
10401 // If VecIn2 is unused then change it to undef.
10402 VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(VT);
10404 // Check that we were able to transform all incoming values to the same
10406 if (VecIn2.getValueType() != VecIn1.getValueType() ||
10407 VecIn1.getValueType() != VT)
10410 // Only type-legal BUILD_VECTOR nodes are converted to shuffle nodes.
10411 if (!isTypeLegal(VT))
10414 // Return the new VECTOR_SHUFFLE node.
10418 return DAG.getVectorShuffle(VT, dl, Ops[0], Ops[1], &Mask[0]);
10424 SDValue DAGCombiner::visitCONCAT_VECTORS(SDNode *N) {
10425 // TODO: Check to see if this is a CONCAT_VECTORS of a bunch of
10426 // EXTRACT_SUBVECTOR operations. If so, and if the EXTRACT_SUBVECTOR vector
10427 // inputs come from at most two distinct vectors, turn this into a shuffle
10430 // If we only have one input vector, we don't need to do any concatenation.
10431 if (N->getNumOperands() == 1)
10432 return N->getOperand(0);
10434 // Check if all of the operands are undefs.
10435 EVT VT = N->getValueType(0);
10436 if (ISD::allOperandsUndef(N))
10437 return DAG.getUNDEF(VT);
10439 // Optimize concat_vectors where one of the vectors is undef.
10440 if (N->getNumOperands() == 2 &&
10441 N->getOperand(1)->getOpcode() == ISD::UNDEF) {
10442 SDValue In = N->getOperand(0);
10443 assert(In.getValueType().isVector() && "Must concat vectors");
10445 // Transform: concat_vectors(scalar, undef) -> scalar_to_vector(sclr).
10446 if (In->getOpcode() == ISD::BITCAST &&
10447 !In->getOperand(0)->getValueType(0).isVector()) {
10448 SDValue Scalar = In->getOperand(0);
10449 EVT SclTy = Scalar->getValueType(0);
10451 if (!SclTy.isFloatingPoint() && !SclTy.isInteger())
10454 EVT NVT = EVT::getVectorVT(*DAG.getContext(), SclTy,
10455 VT.getSizeInBits() / SclTy.getSizeInBits());
10456 if (!TLI.isTypeLegal(NVT) || !TLI.isTypeLegal(Scalar.getValueType()))
10459 SDLoc dl = SDLoc(N);
10460 SDValue Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, NVT, Scalar);
10461 return DAG.getNode(ISD::BITCAST, dl, VT, Res);
10465 // fold (concat_vectors (BUILD_VECTOR A, B, ...), (BUILD_VECTOR C, D, ...))
10466 // -> (BUILD_VECTOR A, B, ..., C, D, ...)
10467 if (N->getNumOperands() == 2 &&
10468 N->getOperand(0).getOpcode() == ISD::BUILD_VECTOR &&
10469 N->getOperand(1).getOpcode() == ISD::BUILD_VECTOR) {
10470 EVT VT = N->getValueType(0);
10471 SDValue N0 = N->getOperand(0);
10472 SDValue N1 = N->getOperand(1);
10473 SmallVector<SDValue, 8> Opnds;
10474 unsigned BuildVecNumElts = N0.getNumOperands();
10476 EVT SclTy0 = N0.getOperand(0)->getValueType(0);
10477 EVT SclTy1 = N1.getOperand(0)->getValueType(0);
10478 if (SclTy0.isFloatingPoint()) {
10479 for (unsigned i = 0; i != BuildVecNumElts; ++i)
10480 Opnds.push_back(N0.getOperand(i));
10481 for (unsigned i = 0; i != BuildVecNumElts; ++i)
10482 Opnds.push_back(N1.getOperand(i));
10484 // If BUILD_VECTOR are from built from integer, they may have different
10485 // operand types. Get the smaller type and truncate all operands to it.
10486 EVT MinTy = SclTy0.bitsLE(SclTy1) ? SclTy0 : SclTy1;
10487 for (unsigned i = 0; i != BuildVecNumElts; ++i)
10488 Opnds.push_back(DAG.getNode(ISD::TRUNCATE, SDLoc(N), MinTy,
10489 N0.getOperand(i)));
10490 for (unsigned i = 0; i != BuildVecNumElts; ++i)
10491 Opnds.push_back(DAG.getNode(ISD::TRUNCATE, SDLoc(N), MinTy,
10492 N1.getOperand(i)));
10495 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, Opnds);
10498 // Type legalization of vectors and DAG canonicalization of SHUFFLE_VECTOR
10499 // nodes often generate nop CONCAT_VECTOR nodes.
10500 // Scan the CONCAT_VECTOR operands and look for a CONCAT operations that
10501 // place the incoming vectors at the exact same location.
10502 SDValue SingleSource = SDValue();
10503 unsigned PartNumElem = N->getOperand(0).getValueType().getVectorNumElements();
10505 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
10506 SDValue Op = N->getOperand(i);
10508 if (Op.getOpcode() == ISD::UNDEF)
10511 // Check if this is the identity extract:
10512 if (Op.getOpcode() != ISD::EXTRACT_SUBVECTOR)
10515 // Find the single incoming vector for the extract_subvector.
10516 if (SingleSource.getNode()) {
10517 if (Op.getOperand(0) != SingleSource)
10520 SingleSource = Op.getOperand(0);
10522 // Check the source type is the same as the type of the result.
10523 // If not, this concat may extend the vector, so we can not
10524 // optimize it away.
10525 if (SingleSource.getValueType() != N->getValueType(0))
10529 unsigned IdentityIndex = i * PartNumElem;
10530 ConstantSDNode *CS = dyn_cast<ConstantSDNode>(Op.getOperand(1));
10531 // The extract index must be constant.
10535 // Check that we are reading from the identity index.
10536 if (CS->getZExtValue() != IdentityIndex)
10540 if (SingleSource.getNode())
10541 return SingleSource;
10546 SDValue DAGCombiner::visitEXTRACT_SUBVECTOR(SDNode* N) {
10547 EVT NVT = N->getValueType(0);
10548 SDValue V = N->getOperand(0);
10550 if (V->getOpcode() == ISD::CONCAT_VECTORS) {
10552 // (extract_subvec (concat V1, V2, ...), i)
10555 // Only operand 0 is checked as 'concat' assumes all inputs of the same
10557 if (V->getOperand(0).getValueType() != NVT)
10559 unsigned Idx = dyn_cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
10560 unsigned NumElems = NVT.getVectorNumElements();
10561 assert((Idx % NumElems) == 0 &&
10562 "IDX in concat is not a multiple of the result vector length.");
10563 return V->getOperand(Idx / NumElems);
10567 if (V->getOpcode() == ISD::BITCAST)
10568 V = V.getOperand(0);
10570 if (V->getOpcode() == ISD::INSERT_SUBVECTOR) {
10572 // Handle only simple case where vector being inserted and vector
10573 // being extracted are of same type, and are half size of larger vectors.
10574 EVT BigVT = V->getOperand(0).getValueType();
10575 EVT SmallVT = V->getOperand(1).getValueType();
10576 if (!NVT.bitsEq(SmallVT) || NVT.getSizeInBits()*2 != BigVT.getSizeInBits())
10579 // Only handle cases where both indexes are constants with the same type.
10580 ConstantSDNode *ExtIdx = dyn_cast<ConstantSDNode>(N->getOperand(1));
10581 ConstantSDNode *InsIdx = dyn_cast<ConstantSDNode>(V->getOperand(2));
10583 if (InsIdx && ExtIdx &&
10584 InsIdx->getValueType(0).getSizeInBits() <= 64 &&
10585 ExtIdx->getValueType(0).getSizeInBits() <= 64) {
10587 // (extract_subvec (insert_subvec V1, V2, InsIdx), ExtIdx)
10589 // indices are equal or bit offsets are equal => V1
10590 // otherwise => (extract_subvec V1, ExtIdx)
10591 if (InsIdx->getZExtValue() * SmallVT.getScalarType().getSizeInBits() ==
10592 ExtIdx->getZExtValue() * NVT.getScalarType().getSizeInBits())
10593 return DAG.getNode(ISD::BITCAST, dl, NVT, V->getOperand(1));
10594 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, NVT,
10595 DAG.getNode(ISD::BITCAST, dl,
10596 N->getOperand(0).getValueType(),
10597 V->getOperand(0)), N->getOperand(1));
10604 // Tries to turn a shuffle of two CONCAT_VECTORS into a single concat.
10605 static SDValue partitionShuffleOfConcats(SDNode *N, SelectionDAG &DAG) {
10606 EVT VT = N->getValueType(0);
10607 unsigned NumElts = VT.getVectorNumElements();
10609 SDValue N0 = N->getOperand(0);
10610 SDValue N1 = N->getOperand(1);
10611 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
10613 SmallVector<SDValue, 4> Ops;
10614 EVT ConcatVT = N0.getOperand(0).getValueType();
10615 unsigned NumElemsPerConcat = ConcatVT.getVectorNumElements();
10616 unsigned NumConcats = NumElts / NumElemsPerConcat;
10618 // Look at every vector that's inserted. We're looking for exact
10619 // subvector-sized copies from a concatenated vector
10620 for (unsigned I = 0; I != NumConcats; ++I) {
10621 // Make sure we're dealing with a copy.
10622 unsigned Begin = I * NumElemsPerConcat;
10623 bool AllUndef = true, NoUndef = true;
10624 for (unsigned J = Begin; J != Begin + NumElemsPerConcat; ++J) {
10625 if (SVN->getMaskElt(J) >= 0)
10632 if (SVN->getMaskElt(Begin) % NumElemsPerConcat != 0)
10635 for (unsigned J = 1; J != NumElemsPerConcat; ++J)
10636 if (SVN->getMaskElt(Begin + J - 1) + 1 != SVN->getMaskElt(Begin + J))
10639 unsigned FirstElt = SVN->getMaskElt(Begin) / NumElemsPerConcat;
10640 if (FirstElt < N0.getNumOperands())
10641 Ops.push_back(N0.getOperand(FirstElt));
10643 Ops.push_back(N1.getOperand(FirstElt - N0.getNumOperands()));
10645 } else if (AllUndef) {
10646 Ops.push_back(DAG.getUNDEF(N0.getOperand(0).getValueType()));
10647 } else { // Mixed with general masks and undefs, can't do optimization.
10652 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Ops);
10655 SDValue DAGCombiner::visitVECTOR_SHUFFLE(SDNode *N) {
10656 EVT VT = N->getValueType(0);
10657 unsigned NumElts = VT.getVectorNumElements();
10659 SDValue N0 = N->getOperand(0);
10660 SDValue N1 = N->getOperand(1);
10662 assert(N0.getValueType() == VT && "Vector shuffle must be normalized in DAG");
10664 // Canonicalize shuffle undef, undef -> undef
10665 if (N0.getOpcode() == ISD::UNDEF && N1.getOpcode() == ISD::UNDEF)
10666 return DAG.getUNDEF(VT);
10668 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
10670 // Canonicalize shuffle v, v -> v, undef
10672 SmallVector<int, 8> NewMask;
10673 for (unsigned i = 0; i != NumElts; ++i) {
10674 int Idx = SVN->getMaskElt(i);
10675 if (Idx >= (int)NumElts) Idx -= NumElts;
10676 NewMask.push_back(Idx);
10678 return DAG.getVectorShuffle(VT, SDLoc(N), N0, DAG.getUNDEF(VT),
10682 // Canonicalize shuffle undef, v -> v, undef. Commute the shuffle mask.
10683 if (N0.getOpcode() == ISD::UNDEF) {
10684 SmallVector<int, 8> NewMask;
10685 for (unsigned i = 0; i != NumElts; ++i) {
10686 int Idx = SVN->getMaskElt(i);
10688 if (Idx >= (int)NumElts)
10691 Idx = -1; // remove reference to lhs
10693 NewMask.push_back(Idx);
10695 return DAG.getVectorShuffle(VT, SDLoc(N), N1, DAG.getUNDEF(VT),
10699 // Remove references to rhs if it is undef
10700 if (N1.getOpcode() == ISD::UNDEF) {
10701 bool Changed = false;
10702 SmallVector<int, 8> NewMask;
10703 for (unsigned i = 0; i != NumElts; ++i) {
10704 int Idx = SVN->getMaskElt(i);
10705 if (Idx >= (int)NumElts) {
10709 NewMask.push_back(Idx);
10712 return DAG.getVectorShuffle(VT, SDLoc(N), N0, N1, &NewMask[0]);
10715 // If it is a splat, check if the argument vector is another splat or a
10716 // build_vector with all scalar elements the same.
10717 if (SVN->isSplat() && SVN->getSplatIndex() < (int)NumElts) {
10718 SDNode *V = N0.getNode();
10720 // If this is a bit convert that changes the element type of the vector but
10721 // not the number of vector elements, look through it. Be careful not to
10722 // look though conversions that change things like v4f32 to v2f64.
10723 if (V->getOpcode() == ISD::BITCAST) {
10724 SDValue ConvInput = V->getOperand(0);
10725 if (ConvInput.getValueType().isVector() &&
10726 ConvInput.getValueType().getVectorNumElements() == NumElts)
10727 V = ConvInput.getNode();
10730 if (V->getOpcode() == ISD::BUILD_VECTOR) {
10731 assert(V->getNumOperands() == NumElts &&
10732 "BUILD_VECTOR has wrong number of operands");
10734 bool AllSame = true;
10735 for (unsigned i = 0; i != NumElts; ++i) {
10736 if (V->getOperand(i).getOpcode() != ISD::UNDEF) {
10737 Base = V->getOperand(i);
10741 // Splat of <u, u, u, u>, return <u, u, u, u>
10742 if (!Base.getNode())
10744 for (unsigned i = 0; i != NumElts; ++i) {
10745 if (V->getOperand(i) != Base) {
10750 // Splat of <x, x, x, x>, return <x, x, x, x>
10756 if (N0.getOpcode() == ISD::CONCAT_VECTORS &&
10757 Level < AfterLegalizeVectorOps &&
10758 (N1.getOpcode() == ISD::UNDEF ||
10759 (N1.getOpcode() == ISD::CONCAT_VECTORS &&
10760 N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType()))) {
10761 SDValue V = partitionShuffleOfConcats(N, DAG);
10767 // If this shuffle node is simply a swizzle of another shuffle node,
10768 // then try to simplify it.
10769 if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG &&
10770 N1.getOpcode() == ISD::UNDEF) {
10772 ShuffleVectorSDNode *OtherSV = cast<ShuffleVectorSDNode>(N0);
10774 // The incoming shuffle must be of the same type as the result of the
10775 // current shuffle.
10776 assert(OtherSV->getOperand(0).getValueType() == VT &&
10777 "Shuffle types don't match");
10779 SmallVector<int, 4> Mask;
10780 // Compute the combined shuffle mask.
10781 for (unsigned i = 0; i != NumElts; ++i) {
10782 int Idx = SVN->getMaskElt(i);
10783 assert(Idx < (int)NumElts && "Index references undef operand");
10784 // Next, this index comes from the first value, which is the incoming
10785 // shuffle. Adopt the incoming index.
10787 Idx = OtherSV->getMaskElt(Idx);
10788 Mask.push_back(Idx);
10791 bool CommuteOperands = false;
10792 if (N0.getOperand(1).getOpcode() != ISD::UNDEF) {
10793 // To be valid, the combine shuffle mask should only reference elements
10794 // from one of the two vectors in input to the inner shufflevector.
10795 bool IsValidMask = true;
10796 for (unsigned i = 0; i != NumElts && IsValidMask; ++i)
10797 // See if the combined mask only reference undefs or elements coming
10798 // from the first shufflevector operand.
10799 IsValidMask = Mask[i] < 0 || (unsigned)Mask[i] < NumElts;
10801 if (!IsValidMask) {
10802 IsValidMask = true;
10803 for (unsigned i = 0; i != NumElts && IsValidMask; ++i)
10804 // Check that all the elements come from the second shuffle operand.
10805 IsValidMask = Mask[i] < 0 || (unsigned)Mask[i] >= NumElts;
10806 CommuteOperands = IsValidMask;
10809 // Early exit if the combined shuffle mask is not valid.
10814 // See if this pair of shuffles can be safely folded according to either
10815 // of the following rules:
10816 // shuffle(shuffle(x, y), undef) -> x
10817 // shuffle(shuffle(x, undef), undef) -> x
10818 // shuffle(shuffle(x, y), undef) -> y
10819 bool IsIdentityMask = true;
10820 unsigned BaseMaskIndex = CommuteOperands ? NumElts : 0;
10821 for (unsigned i = 0; i != NumElts && IsIdentityMask; ++i) {
10826 // The combined shuffle must map each index to itself.
10827 IsIdentityMask = (unsigned)Mask[i] == i + BaseMaskIndex;
10830 if (IsIdentityMask) {
10831 if (CommuteOperands)
10832 // optimize shuffle(shuffle(x, y), undef) -> y.
10833 return OtherSV->getOperand(1);
10835 // optimize shuffle(shuffle(x, undef), undef) -> x
10836 // optimize shuffle(shuffle(x, y), undef) -> x
10837 return OtherSV->getOperand(0);
10840 // It may still be beneficial to combine the two shuffles if the
10841 // resulting shuffle is legal.
10842 if (TLI.isTypeLegal(VT)) {
10843 if (!CommuteOperands) {
10844 if (TLI.isShuffleMaskLegal(Mask, VT))
10845 // shuffle(shuffle(x, undef, M1), undef, M2) -> shuffle(x, undef, M3).
10846 // shuffle(shuffle(x, y, M1), undef, M2) -> shuffle(x, undef, M3)
10847 return DAG.getVectorShuffle(VT, SDLoc(N), N0->getOperand(0), N1,
10850 // Compute the commuted shuffle mask.
10851 for (unsigned i = 0; i != NumElts; ++i) {
10855 else if (idx < (int)NumElts)
10856 Mask[i] = idx + NumElts;
10858 Mask[i] = idx - NumElts;
10861 if (TLI.isShuffleMaskLegal(Mask, VT))
10862 // shuffle(shuffle(x, y, M1), undef, M2) -> shuffle(y, undef, M3)
10863 return DAG.getVectorShuffle(VT, SDLoc(N), N0->getOperand(1), N1,
10869 // Canonicalize shuffles according to rules:
10870 // shuffle(A, shuffle(A, B)) -> shuffle(shuffle(A,B), A)
10871 // shuffle(B, shuffle(A, B)) -> shuffle(shuffle(A,B), B)
10872 // shuffle(B, shuffle(A, Undef)) -> shuffle(shuffle(A, Undef), B)
10873 if (N1.getOpcode() == ISD::VECTOR_SHUFFLE && N0.getOpcode() != ISD::UNDEF &&
10874 N0.getOpcode() != ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG &&
10875 TLI.isTypeLegal(VT)) {
10876 // The incoming shuffle must be of the same type as the result of the
10877 // current shuffle.
10878 assert(N1->getOperand(0).getValueType() == VT &&
10879 "Shuffle types don't match");
10881 SDValue SV0 = N1->getOperand(0);
10882 SDValue SV1 = N1->getOperand(1);
10883 bool HasSameOp0 = N0 == SV0;
10884 bool IsSV1Undef = SV1.getOpcode() == ISD::UNDEF;
10885 if (HasSameOp0 || IsSV1Undef || N0 == SV1)
10886 // Commute the operands of this shuffle so that next rule
10888 return DAG.getCommutedVectorShuffle(*SVN);
10891 // Try to fold according to rules:
10892 // shuffle(shuffle(A, B, M0), B, M1) -> shuffle(A, B, M2)
10893 // shuffle(shuffle(A, B, M0), A, M1) -> shuffle(A, B, M2)
10894 // shuffle(shuffle(A, Undef, M0), B, M1) -> shuffle(A, B, M2)
10895 // shuffle(shuffle(A, Undef, M0), A, M1) -> shuffle(A, Undef, M2)
10896 // Don't try to fold shuffles with illegal type.
10897 if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG &&
10898 N1.getOpcode() != ISD::UNDEF && TLI.isTypeLegal(VT)) {
10899 ShuffleVectorSDNode *OtherSV = cast<ShuffleVectorSDNode>(N0);
10901 // The incoming shuffle must be of the same type as the result of the
10902 // current shuffle.
10903 assert(OtherSV->getOperand(0).getValueType() == VT &&
10904 "Shuffle types don't match");
10906 SDValue SV0 = OtherSV->getOperand(0);
10907 SDValue SV1 = OtherSV->getOperand(1);
10908 bool HasSameOp0 = N1 == SV0;
10909 bool IsSV1Undef = SV1.getOpcode() == ISD::UNDEF;
10910 if (!HasSameOp0 && !IsSV1Undef && N1 != SV1)
10914 SmallVector<int, 4> Mask;
10915 // Compute the combined shuffle mask for a shuffle with SV0 as the first
10916 // operand, and SV1 as the second operand.
10917 for (unsigned i = 0; i != NumElts; ++i) {
10918 int Idx = SVN->getMaskElt(i);
10920 // Propagate Undef.
10921 Mask.push_back(Idx);
10925 if (Idx < (int)NumElts) {
10926 Idx = OtherSV->getMaskElt(Idx);
10927 if (IsSV1Undef && Idx >= (int) NumElts)
10928 Idx = -1; // Propagate Undef.
10930 Idx = HasSameOp0 ? Idx - NumElts : Idx;
10932 Mask.push_back(Idx);
10935 // Avoid introducing shuffles with illegal mask.
10936 if (TLI.isShuffleMaskLegal(Mask, VT)) {
10938 // shuffle(shuffle(A, Undef, M0), B, M1) -> shuffle(A, B, M2)
10939 // shuffle(shuffle(A, Undef, M0), A, M1) -> shuffle(A, Undef, M2)
10940 return DAG.getVectorShuffle(VT, SDLoc(N), SV0, N1, &Mask[0]);
10941 return DAG.getVectorShuffle(VT, SDLoc(N), SV0, SV1, &Mask[0]);
10948 SDValue DAGCombiner::visitINSERT_SUBVECTOR(SDNode *N) {
10949 SDValue N0 = N->getOperand(0);
10950 SDValue N2 = N->getOperand(2);
10952 // If the input vector is a concatenation, and the insert replaces
10953 // one of the halves, we can optimize into a single concat_vectors.
10954 if (N0.getOpcode() == ISD::CONCAT_VECTORS &&
10955 N0->getNumOperands() == 2 && N2.getOpcode() == ISD::Constant) {
10956 APInt InsIdx = cast<ConstantSDNode>(N2)->getAPIntValue();
10957 EVT VT = N->getValueType(0);
10959 // Lower half: fold (insert_subvector (concat_vectors X, Y), Z) ->
10960 // (concat_vectors Z, Y)
10962 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
10963 N->getOperand(1), N0.getOperand(1));
10965 // Upper half: fold (insert_subvector (concat_vectors X, Y), Z) ->
10966 // (concat_vectors X, Z)
10967 if (InsIdx == VT.getVectorNumElements()/2)
10968 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
10969 N0.getOperand(0), N->getOperand(1));
10975 /// XformToShuffleWithZero - Returns a vector_shuffle if it able to transform
10976 /// an AND to a vector_shuffle with the destination vector and a zero vector.
10977 /// e.g. AND V, <0xffffffff, 0, 0xffffffff, 0>. ==>
10978 /// vector_shuffle V, Zero, <0, 4, 2, 4>
10979 SDValue DAGCombiner::XformToShuffleWithZero(SDNode *N) {
10980 EVT VT = N->getValueType(0);
10982 SDValue LHS = N->getOperand(0);
10983 SDValue RHS = N->getOperand(1);
10984 if (N->getOpcode() == ISD::AND) {
10985 if (RHS.getOpcode() == ISD::BITCAST)
10986 RHS = RHS.getOperand(0);
10987 if (RHS.getOpcode() == ISD::BUILD_VECTOR) {
10988 SmallVector<int, 8> Indices;
10989 unsigned NumElts = RHS.getNumOperands();
10990 for (unsigned i = 0; i != NumElts; ++i) {
10991 SDValue Elt = RHS.getOperand(i);
10992 if (!isa<ConstantSDNode>(Elt))
10995 if (cast<ConstantSDNode>(Elt)->isAllOnesValue())
10996 Indices.push_back(i);
10997 else if (cast<ConstantSDNode>(Elt)->isNullValue())
10998 Indices.push_back(NumElts);
11003 // Let's see if the target supports this vector_shuffle.
11004 EVT RVT = RHS.getValueType();
11005 if (!TLI.isVectorClearMaskLegal(Indices, RVT))
11008 // Return the new VECTOR_SHUFFLE node.
11009 EVT EltVT = RVT.getVectorElementType();
11010 SmallVector<SDValue,8> ZeroOps(RVT.getVectorNumElements(),
11011 DAG.getConstant(0, EltVT));
11012 SDValue Zero = DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), RVT, ZeroOps);
11013 LHS = DAG.getNode(ISD::BITCAST, dl, RVT, LHS);
11014 SDValue Shuf = DAG.getVectorShuffle(RVT, dl, LHS, Zero, &Indices[0]);
11015 return DAG.getNode(ISD::BITCAST, dl, VT, Shuf);
11022 /// SimplifyVBinOp - Visit a binary vector operation, like ADD.
11023 SDValue DAGCombiner::SimplifyVBinOp(SDNode *N) {
11024 assert(N->getValueType(0).isVector() &&
11025 "SimplifyVBinOp only works on vectors!");
11027 SDValue LHS = N->getOperand(0);
11028 SDValue RHS = N->getOperand(1);
11029 SDValue Shuffle = XformToShuffleWithZero(N);
11030 if (Shuffle.getNode()) return Shuffle;
11032 // If the LHS and RHS are BUILD_VECTOR nodes, see if we can constant fold
11034 if (LHS.getOpcode() == ISD::BUILD_VECTOR &&
11035 RHS.getOpcode() == ISD::BUILD_VECTOR) {
11036 // Check if both vectors are constants. If not bail out.
11037 if (!(cast<BuildVectorSDNode>(LHS)->isConstant() &&
11038 cast<BuildVectorSDNode>(RHS)->isConstant()))
11041 SmallVector<SDValue, 8> Ops;
11042 for (unsigned i = 0, e = LHS.getNumOperands(); i != e; ++i) {
11043 SDValue LHSOp = LHS.getOperand(i);
11044 SDValue RHSOp = RHS.getOperand(i);
11046 // Can't fold divide by zero.
11047 if (N->getOpcode() == ISD::SDIV || N->getOpcode() == ISD::UDIV ||
11048 N->getOpcode() == ISD::FDIV) {
11049 if ((RHSOp.getOpcode() == ISD::Constant &&
11050 cast<ConstantSDNode>(RHSOp.getNode())->isNullValue()) ||
11051 (RHSOp.getOpcode() == ISD::ConstantFP &&
11052 cast<ConstantFPSDNode>(RHSOp.getNode())->getValueAPF().isZero()))
11056 EVT VT = LHSOp.getValueType();
11057 EVT RVT = RHSOp.getValueType();
11059 // Integer BUILD_VECTOR operands may have types larger than the element
11060 // size (e.g., when the element type is not legal). Prior to type
11061 // legalization, the types may not match between the two BUILD_VECTORS.
11062 // Truncate one of the operands to make them match.
11063 if (RVT.getSizeInBits() > VT.getSizeInBits()) {
11064 RHSOp = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, RHSOp);
11066 LHSOp = DAG.getNode(ISD::TRUNCATE, SDLoc(N), RVT, LHSOp);
11070 SDValue FoldOp = DAG.getNode(N->getOpcode(), SDLoc(LHS), VT,
11072 if (FoldOp.getOpcode() != ISD::UNDEF &&
11073 FoldOp.getOpcode() != ISD::Constant &&
11074 FoldOp.getOpcode() != ISD::ConstantFP)
11076 Ops.push_back(FoldOp);
11077 AddToWorklist(FoldOp.getNode());
11080 if (Ops.size() == LHS.getNumOperands())
11081 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), LHS.getValueType(), Ops);
11084 // Type legalization might introduce new shuffles in the DAG.
11085 // Fold (VBinOp (shuffle (A, Undef, Mask)), (shuffle (B, Undef, Mask)))
11086 // -> (shuffle (VBinOp (A, B)), Undef, Mask).
11087 if (LegalTypes && isa<ShuffleVectorSDNode>(LHS) &&
11088 isa<ShuffleVectorSDNode>(RHS) && LHS.hasOneUse() && RHS.hasOneUse() &&
11089 LHS.getOperand(1).getOpcode() == ISD::UNDEF &&
11090 RHS.getOperand(1).getOpcode() == ISD::UNDEF) {
11091 ShuffleVectorSDNode *SVN0 = cast<ShuffleVectorSDNode>(LHS);
11092 ShuffleVectorSDNode *SVN1 = cast<ShuffleVectorSDNode>(RHS);
11094 if (SVN0->getMask().equals(SVN1->getMask())) {
11095 EVT VT = N->getValueType(0);
11096 SDValue UndefVector = LHS.getOperand(1);
11097 SDValue NewBinOp = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
11098 LHS.getOperand(0), RHS.getOperand(0));
11099 AddUsersToWorklist(N);
11100 return DAG.getVectorShuffle(VT, SDLoc(N), NewBinOp, UndefVector,
11101 &SVN0->getMask()[0]);
11108 /// SimplifyVUnaryOp - Visit a binary vector operation, like FABS/FNEG.
11109 SDValue DAGCombiner::SimplifyVUnaryOp(SDNode *N) {
11110 assert(N->getValueType(0).isVector() &&
11111 "SimplifyVUnaryOp only works on vectors!");
11113 SDValue N0 = N->getOperand(0);
11115 if (N0.getOpcode() != ISD::BUILD_VECTOR)
11118 // Operand is a BUILD_VECTOR node, see if we can constant fold it.
11119 SmallVector<SDValue, 8> Ops;
11120 for (unsigned i = 0, e = N0.getNumOperands(); i != e; ++i) {
11121 SDValue Op = N0.getOperand(i);
11122 if (Op.getOpcode() != ISD::UNDEF &&
11123 Op.getOpcode() != ISD::ConstantFP)
11125 EVT EltVT = Op.getValueType();
11126 SDValue FoldOp = DAG.getNode(N->getOpcode(), SDLoc(N0), EltVT, Op);
11127 if (FoldOp.getOpcode() != ISD::UNDEF &&
11128 FoldOp.getOpcode() != ISD::ConstantFP)
11130 Ops.push_back(FoldOp);
11131 AddToWorklist(FoldOp.getNode());
11134 if (Ops.size() != N0.getNumOperands())
11137 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), N0.getValueType(), Ops);
11140 SDValue DAGCombiner::SimplifySelect(SDLoc DL, SDValue N0,
11141 SDValue N1, SDValue N2){
11142 assert(N0.getOpcode() ==ISD::SETCC && "First argument must be a SetCC node!");
11144 SDValue SCC = SimplifySelectCC(DL, N0.getOperand(0), N0.getOperand(1), N1, N2,
11145 cast<CondCodeSDNode>(N0.getOperand(2))->get());
11147 // If we got a simplified select_cc node back from SimplifySelectCC, then
11148 // break it down into a new SETCC node, and a new SELECT node, and then return
11149 // the SELECT node, since we were called with a SELECT node.
11150 if (SCC.getNode()) {
11151 // Check to see if we got a select_cc back (to turn into setcc/select).
11152 // Otherwise, just return whatever node we got back, like fabs.
11153 if (SCC.getOpcode() == ISD::SELECT_CC) {
11154 SDValue SETCC = DAG.getNode(ISD::SETCC, SDLoc(N0),
11156 SCC.getOperand(0), SCC.getOperand(1),
11157 SCC.getOperand(4));
11158 AddToWorklist(SETCC.getNode());
11159 return DAG.getSelect(SDLoc(SCC), SCC.getValueType(), SETCC,
11160 SCC.getOperand(2), SCC.getOperand(3));
11168 /// SimplifySelectOps - Given a SELECT or a SELECT_CC node, where LHS and RHS
11169 /// are the two values being selected between, see if we can simplify the
11170 /// select. Callers of this should assume that TheSelect is deleted if this
11171 /// returns true. As such, they should return the appropriate thing (e.g. the
11172 /// node) back to the top-level of the DAG combiner loop to avoid it being
11174 bool DAGCombiner::SimplifySelectOps(SDNode *TheSelect, SDValue LHS,
11177 // Cannot simplify select with vector condition
11178 if (TheSelect->getOperand(0).getValueType().isVector()) return false;
11180 // If this is a select from two identical things, try to pull the operation
11181 // through the select.
11182 if (LHS.getOpcode() != RHS.getOpcode() ||
11183 !LHS.hasOneUse() || !RHS.hasOneUse())
11186 // If this is a load and the token chain is identical, replace the select
11187 // of two loads with a load through a select of the address to load from.
11188 // This triggers in things like "select bool X, 10.0, 123.0" after the FP
11189 // constants have been dropped into the constant pool.
11190 if (LHS.getOpcode() == ISD::LOAD) {
11191 LoadSDNode *LLD = cast<LoadSDNode>(LHS);
11192 LoadSDNode *RLD = cast<LoadSDNode>(RHS);
11194 // Token chains must be identical.
11195 if (LHS.getOperand(0) != RHS.getOperand(0) ||
11196 // Do not let this transformation reduce the number of volatile loads.
11197 LLD->isVolatile() || RLD->isVolatile() ||
11198 // If this is an EXTLOAD, the VT's must match.
11199 LLD->getMemoryVT() != RLD->getMemoryVT() ||
11200 // If this is an EXTLOAD, the kind of extension must match.
11201 (LLD->getExtensionType() != RLD->getExtensionType() &&
11202 // The only exception is if one of the extensions is anyext.
11203 LLD->getExtensionType() != ISD::EXTLOAD &&
11204 RLD->getExtensionType() != ISD::EXTLOAD) ||
11205 // FIXME: this discards src value information. This is
11206 // over-conservative. It would be beneficial to be able to remember
11207 // both potential memory locations. Since we are discarding
11208 // src value info, don't do the transformation if the memory
11209 // locations are not in the default address space.
11210 LLD->getPointerInfo().getAddrSpace() != 0 ||
11211 RLD->getPointerInfo().getAddrSpace() != 0 ||
11212 !TLI.isOperationLegalOrCustom(TheSelect->getOpcode(),
11213 LLD->getBasePtr().getValueType()))
11216 // Check that the select condition doesn't reach either load. If so,
11217 // folding this will induce a cycle into the DAG. If not, this is safe to
11218 // xform, so create a select of the addresses.
11220 if (TheSelect->getOpcode() == ISD::SELECT) {
11221 SDNode *CondNode = TheSelect->getOperand(0).getNode();
11222 if ((LLD->hasAnyUseOfValue(1) && LLD->isPredecessorOf(CondNode)) ||
11223 (RLD->hasAnyUseOfValue(1) && RLD->isPredecessorOf(CondNode)))
11225 // The loads must not depend on one another.
11226 if (LLD->isPredecessorOf(RLD) ||
11227 RLD->isPredecessorOf(LLD))
11229 Addr = DAG.getSelect(SDLoc(TheSelect),
11230 LLD->getBasePtr().getValueType(),
11231 TheSelect->getOperand(0), LLD->getBasePtr(),
11232 RLD->getBasePtr());
11233 } else { // Otherwise SELECT_CC
11234 SDNode *CondLHS = TheSelect->getOperand(0).getNode();
11235 SDNode *CondRHS = TheSelect->getOperand(1).getNode();
11237 if ((LLD->hasAnyUseOfValue(1) &&
11238 (LLD->isPredecessorOf(CondLHS) || LLD->isPredecessorOf(CondRHS))) ||
11239 (RLD->hasAnyUseOfValue(1) &&
11240 (RLD->isPredecessorOf(CondLHS) || RLD->isPredecessorOf(CondRHS))))
11243 Addr = DAG.getNode(ISD::SELECT_CC, SDLoc(TheSelect),
11244 LLD->getBasePtr().getValueType(),
11245 TheSelect->getOperand(0),
11246 TheSelect->getOperand(1),
11247 LLD->getBasePtr(), RLD->getBasePtr(),
11248 TheSelect->getOperand(4));
11252 // It is safe to replace the two loads if they have different alignments,
11253 // but the new load must be the minimum (most restrictive) alignment of the
11255 bool isInvariant = LLD->getAlignment() & RLD->getAlignment();
11256 unsigned Alignment = std::min(LLD->getAlignment(), RLD->getAlignment());
11257 if (LLD->getExtensionType() == ISD::NON_EXTLOAD) {
11258 Load = DAG.getLoad(TheSelect->getValueType(0),
11260 // FIXME: Discards pointer and AA info.
11261 LLD->getChain(), Addr, MachinePointerInfo(),
11262 LLD->isVolatile(), LLD->isNonTemporal(),
11263 isInvariant, Alignment);
11265 Load = DAG.getExtLoad(LLD->getExtensionType() == ISD::EXTLOAD ?
11266 RLD->getExtensionType() : LLD->getExtensionType(),
11268 TheSelect->getValueType(0),
11269 // FIXME: Discards pointer and AA info.
11270 LLD->getChain(), Addr, MachinePointerInfo(),
11271 LLD->getMemoryVT(), LLD->isVolatile(),
11272 LLD->isNonTemporal(), isInvariant, Alignment);
11275 // Users of the select now use the result of the load.
11276 CombineTo(TheSelect, Load);
11278 // Users of the old loads now use the new load's chain. We know the
11279 // old-load value is dead now.
11280 CombineTo(LHS.getNode(), Load.getValue(0), Load.getValue(1));
11281 CombineTo(RHS.getNode(), Load.getValue(0), Load.getValue(1));
11288 /// SimplifySelectCC - Simplify an expression of the form (N0 cond N1) ? N2 : N3
11289 /// where 'cond' is the comparison specified by CC.
11290 SDValue DAGCombiner::SimplifySelectCC(SDLoc DL, SDValue N0, SDValue N1,
11291 SDValue N2, SDValue N3,
11292 ISD::CondCode CC, bool NotExtCompare) {
11293 // (x ? y : y) -> y.
11294 if (N2 == N3) return N2;
11296 EVT VT = N2.getValueType();
11297 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
11298 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2.getNode());
11299 ConstantSDNode *N3C = dyn_cast<ConstantSDNode>(N3.getNode());
11301 // Determine if the condition we're dealing with is constant
11302 SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()),
11303 N0, N1, CC, DL, false);
11304 if (SCC.getNode()) AddToWorklist(SCC.getNode());
11305 ConstantSDNode *SCCC = dyn_cast_or_null<ConstantSDNode>(SCC.getNode());
11307 // fold select_cc true, x, y -> x
11308 if (SCCC && !SCCC->isNullValue())
11310 // fold select_cc false, x, y -> y
11311 if (SCCC && SCCC->isNullValue())
11314 // Check to see if we can simplify the select into an fabs node
11315 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N1)) {
11316 // Allow either -0.0 or 0.0
11317 if (CFP->getValueAPF().isZero()) {
11318 // select (setg[te] X, +/-0.0), X, fneg(X) -> fabs
11319 if ((CC == ISD::SETGE || CC == ISD::SETGT) &&
11320 N0 == N2 && N3.getOpcode() == ISD::FNEG &&
11321 N2 == N3.getOperand(0))
11322 return DAG.getNode(ISD::FABS, DL, VT, N0);
11324 // select (setl[te] X, +/-0.0), fneg(X), X -> fabs
11325 if ((CC == ISD::SETLT || CC == ISD::SETLE) &&
11326 N0 == N3 && N2.getOpcode() == ISD::FNEG &&
11327 N2.getOperand(0) == N3)
11328 return DAG.getNode(ISD::FABS, DL, VT, N3);
11332 // Turn "(a cond b) ? 1.0f : 2.0f" into "load (tmp + ((a cond b) ? 0 : 4)"
11333 // where "tmp" is a constant pool entry containing an array with 1.0 and 2.0
11334 // in it. This is a win when the constant is not otherwise available because
11335 // it replaces two constant pool loads with one. We only do this if the FP
11336 // type is known to be legal, because if it isn't, then we are before legalize
11337 // types an we want the other legalization to happen first (e.g. to avoid
11338 // messing with soft float) and if the ConstantFP is not legal, because if
11339 // it is legal, we may not need to store the FP constant in a constant pool.
11340 if (ConstantFPSDNode *TV = dyn_cast<ConstantFPSDNode>(N2))
11341 if (ConstantFPSDNode *FV = dyn_cast<ConstantFPSDNode>(N3)) {
11342 if (TLI.isTypeLegal(N2.getValueType()) &&
11343 (TLI.getOperationAction(ISD::ConstantFP, N2.getValueType()) !=
11344 TargetLowering::Legal &&
11345 !TLI.isFPImmLegal(TV->getValueAPF(), TV->getValueType(0)) &&
11346 !TLI.isFPImmLegal(FV->getValueAPF(), FV->getValueType(0))) &&
11347 // If both constants have multiple uses, then we won't need to do an
11348 // extra load, they are likely around in registers for other users.
11349 (TV->hasOneUse() || FV->hasOneUse())) {
11350 Constant *Elts[] = {
11351 const_cast<ConstantFP*>(FV->getConstantFPValue()),
11352 const_cast<ConstantFP*>(TV->getConstantFPValue())
11354 Type *FPTy = Elts[0]->getType();
11355 const DataLayout &TD = *TLI.getDataLayout();
11357 // Create a ConstantArray of the two constants.
11358 Constant *CA = ConstantArray::get(ArrayType::get(FPTy, 2), Elts);
11359 SDValue CPIdx = DAG.getConstantPool(CA, TLI.getPointerTy(),
11360 TD.getPrefTypeAlignment(FPTy));
11361 unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
11363 // Get the offsets to the 0 and 1 element of the array so that we can
11364 // select between them.
11365 SDValue Zero = DAG.getIntPtrConstant(0);
11366 unsigned EltSize = (unsigned)TD.getTypeAllocSize(Elts[0]->getType());
11367 SDValue One = DAG.getIntPtrConstant(EltSize);
11369 SDValue Cond = DAG.getSetCC(DL,
11370 getSetCCResultType(N0.getValueType()),
11372 AddToWorklist(Cond.getNode());
11373 SDValue CstOffset = DAG.getSelect(DL, Zero.getValueType(),
11375 AddToWorklist(CstOffset.getNode());
11376 CPIdx = DAG.getNode(ISD::ADD, DL, CPIdx.getValueType(), CPIdx,
11378 AddToWorklist(CPIdx.getNode());
11379 return DAG.getLoad(TV->getValueType(0), DL, DAG.getEntryNode(), CPIdx,
11380 MachinePointerInfo::getConstantPool(), false,
11381 false, false, Alignment);
11386 // Check to see if we can perform the "gzip trick", transforming
11387 // (select_cc setlt X, 0, A, 0) -> (and (sra X, (sub size(X), 1), A)
11388 if (N1C && N3C && N3C->isNullValue() && CC == ISD::SETLT &&
11389 (N1C->isNullValue() || // (a < 0) ? b : 0
11390 (N1C->getAPIntValue() == 1 && N0 == N2))) { // (a < 1) ? a : 0
11391 EVT XType = N0.getValueType();
11392 EVT AType = N2.getValueType();
11393 if (XType.bitsGE(AType)) {
11394 // and (sra X, size(X)-1, A) -> "and (srl X, C2), A" iff A is a
11395 // single-bit constant.
11396 if (N2C && ((N2C->getAPIntValue() & (N2C->getAPIntValue()-1)) == 0)) {
11397 unsigned ShCtV = N2C->getAPIntValue().logBase2();
11398 ShCtV = XType.getSizeInBits()-ShCtV-1;
11399 SDValue ShCt = DAG.getConstant(ShCtV,
11400 getShiftAmountTy(N0.getValueType()));
11401 SDValue Shift = DAG.getNode(ISD::SRL, SDLoc(N0),
11403 AddToWorklist(Shift.getNode());
11405 if (XType.bitsGT(AType)) {
11406 Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift);
11407 AddToWorklist(Shift.getNode());
11410 return DAG.getNode(ISD::AND, DL, AType, Shift, N2);
11413 SDValue Shift = DAG.getNode(ISD::SRA, SDLoc(N0),
11415 DAG.getConstant(XType.getSizeInBits()-1,
11416 getShiftAmountTy(N0.getValueType())));
11417 AddToWorklist(Shift.getNode());
11419 if (XType.bitsGT(AType)) {
11420 Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift);
11421 AddToWorklist(Shift.getNode());
11424 return DAG.getNode(ISD::AND, DL, AType, Shift, N2);
11428 // fold (select_cc seteq (and x, y), 0, 0, A) -> (and (shr (shl x)) A)
11429 // where y is has a single bit set.
11430 // A plaintext description would be, we can turn the SELECT_CC into an AND
11431 // when the condition can be materialized as an all-ones register. Any
11432 // single bit-test can be materialized as an all-ones register with
11433 // shift-left and shift-right-arith.
11434 if (CC == ISD::SETEQ && N0->getOpcode() == ISD::AND &&
11435 N0->getValueType(0) == VT &&
11436 N1C && N1C->isNullValue() &&
11437 N2C && N2C->isNullValue()) {
11438 SDValue AndLHS = N0->getOperand(0);
11439 ConstantSDNode *ConstAndRHS = dyn_cast<ConstantSDNode>(N0->getOperand(1));
11440 if (ConstAndRHS && ConstAndRHS->getAPIntValue().countPopulation() == 1) {
11441 // Shift the tested bit over the sign bit.
11442 APInt AndMask = ConstAndRHS->getAPIntValue();
11444 DAG.getConstant(AndMask.countLeadingZeros(),
11445 getShiftAmountTy(AndLHS.getValueType()));
11446 SDValue Shl = DAG.getNode(ISD::SHL, SDLoc(N0), VT, AndLHS, ShlAmt);
11448 // Now arithmetic right shift it all the way over, so the result is either
11449 // all-ones, or zero.
11451 DAG.getConstant(AndMask.getBitWidth()-1,
11452 getShiftAmountTy(Shl.getValueType()));
11453 SDValue Shr = DAG.getNode(ISD::SRA, SDLoc(N0), VT, Shl, ShrAmt);
11455 return DAG.getNode(ISD::AND, DL, VT, Shr, N3);
11459 // fold select C, 16, 0 -> shl C, 4
11460 if (N2C && N3C && N3C->isNullValue() && N2C->getAPIntValue().isPowerOf2() &&
11461 TLI.getBooleanContents(N0.getValueType()) ==
11462 TargetLowering::ZeroOrOneBooleanContent) {
11464 // If the caller doesn't want us to simplify this into a zext of a compare,
11466 if (NotExtCompare && N2C->getAPIntValue() == 1)
11469 // Get a SetCC of the condition
11470 // NOTE: Don't create a SETCC if it's not legal on this target.
11471 if (!LegalOperations ||
11472 TLI.isOperationLegal(ISD::SETCC,
11473 LegalTypes ? getSetCCResultType(N0.getValueType()) : MVT::i1)) {
11475 // cast from setcc result type to select result type
11477 SCC = DAG.getSetCC(DL, getSetCCResultType(N0.getValueType()),
11479 if (N2.getValueType().bitsLT(SCC.getValueType()))
11480 Temp = DAG.getZeroExtendInReg(SCC, SDLoc(N2),
11481 N2.getValueType());
11483 Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2),
11484 N2.getValueType(), SCC);
11486 SCC = DAG.getSetCC(SDLoc(N0), MVT::i1, N0, N1, CC);
11487 Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2),
11488 N2.getValueType(), SCC);
11491 AddToWorklist(SCC.getNode());
11492 AddToWorklist(Temp.getNode());
11494 if (N2C->getAPIntValue() == 1)
11497 // shl setcc result by log2 n2c
11498 return DAG.getNode(
11499 ISD::SHL, DL, N2.getValueType(), Temp,
11500 DAG.getConstant(N2C->getAPIntValue().logBase2(),
11501 getShiftAmountTy(Temp.getValueType())));
11505 // Check to see if this is the equivalent of setcc
11506 // FIXME: Turn all of these into setcc if setcc if setcc is legal
11507 // otherwise, go ahead with the folds.
11508 if (0 && N3C && N3C->isNullValue() && N2C && (N2C->getAPIntValue() == 1ULL)) {
11509 EVT XType = N0.getValueType();
11510 if (!LegalOperations ||
11511 TLI.isOperationLegal(ISD::SETCC, getSetCCResultType(XType))) {
11512 SDValue Res = DAG.getSetCC(DL, getSetCCResultType(XType), N0, N1, CC);
11513 if (Res.getValueType() != VT)
11514 Res = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, Res);
11518 // fold (seteq X, 0) -> (srl (ctlz X, log2(size(X))))
11519 if (N1C && N1C->isNullValue() && CC == ISD::SETEQ &&
11520 (!LegalOperations ||
11521 TLI.isOperationLegal(ISD::CTLZ, XType))) {
11522 SDValue Ctlz = DAG.getNode(ISD::CTLZ, SDLoc(N0), XType, N0);
11523 return DAG.getNode(ISD::SRL, DL, XType, Ctlz,
11524 DAG.getConstant(Log2_32(XType.getSizeInBits()),
11525 getShiftAmountTy(Ctlz.getValueType())));
11527 // fold (setgt X, 0) -> (srl (and (-X, ~X), size(X)-1))
11528 if (N1C && N1C->isNullValue() && CC == ISD::SETGT) {
11529 SDValue NegN0 = DAG.getNode(ISD::SUB, SDLoc(N0),
11530 XType, DAG.getConstant(0, XType), N0);
11531 SDValue NotN0 = DAG.getNOT(SDLoc(N0), N0, XType);
11532 return DAG.getNode(ISD::SRL, DL, XType,
11533 DAG.getNode(ISD::AND, DL, XType, NegN0, NotN0),
11534 DAG.getConstant(XType.getSizeInBits()-1,
11535 getShiftAmountTy(XType)));
11537 // fold (setgt X, -1) -> (xor (srl (X, size(X)-1), 1))
11538 if (N1C && N1C->isAllOnesValue() && CC == ISD::SETGT) {
11539 SDValue Sign = DAG.getNode(ISD::SRL, SDLoc(N0), XType, N0,
11540 DAG.getConstant(XType.getSizeInBits()-1,
11541 getShiftAmountTy(N0.getValueType())));
11542 return DAG.getNode(ISD::XOR, DL, XType, Sign, DAG.getConstant(1, XType));
11546 // Check to see if this is an integer abs.
11547 // select_cc setg[te] X, 0, X, -X ->
11548 // select_cc setgt X, -1, X, -X ->
11549 // select_cc setl[te] X, 0, -X, X ->
11550 // select_cc setlt X, 1, -X, X ->
11551 // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
11553 ConstantSDNode *SubC = nullptr;
11554 if (((N1C->isNullValue() && (CC == ISD::SETGT || CC == ISD::SETGE)) ||
11555 (N1C->isAllOnesValue() && CC == ISD::SETGT)) &&
11556 N0 == N2 && N3.getOpcode() == ISD::SUB && N0 == N3.getOperand(1))
11557 SubC = dyn_cast<ConstantSDNode>(N3.getOperand(0));
11558 else if (((N1C->isNullValue() && (CC == ISD::SETLT || CC == ISD::SETLE)) ||
11559 (N1C->isOne() && CC == ISD::SETLT)) &&
11560 N0 == N3 && N2.getOpcode() == ISD::SUB && N0 == N2.getOperand(1))
11561 SubC = dyn_cast<ConstantSDNode>(N2.getOperand(0));
11563 EVT XType = N0.getValueType();
11564 if (SubC && SubC->isNullValue() && XType.isInteger()) {
11565 SDValue Shift = DAG.getNode(ISD::SRA, SDLoc(N0), XType,
11567 DAG.getConstant(XType.getSizeInBits()-1,
11568 getShiftAmountTy(N0.getValueType())));
11569 SDValue Add = DAG.getNode(ISD::ADD, SDLoc(N0),
11571 AddToWorklist(Shift.getNode());
11572 AddToWorklist(Add.getNode());
11573 return DAG.getNode(ISD::XOR, DL, XType, Add, Shift);
11580 /// SimplifySetCC - This is a stub for TargetLowering::SimplifySetCC.
11581 SDValue DAGCombiner::SimplifySetCC(EVT VT, SDValue N0,
11582 SDValue N1, ISD::CondCode Cond,
11583 SDLoc DL, bool foldBooleans) {
11584 TargetLowering::DAGCombinerInfo
11585 DagCombineInfo(DAG, Level, false, this);
11586 return TLI.SimplifySetCC(VT, N0, N1, Cond, foldBooleans, DagCombineInfo, DL);
11589 /// BuildSDIV - Given an ISD::SDIV node expressing a divide by constant, return
11590 /// a DAG expression to select that will generate the same value by multiplying
11591 /// by a magic number. See:
11592 /// <http://the.wall.riscom.net/books/proc/ppc/cwg/code2.html>
11593 SDValue DAGCombiner::BuildSDIV(SDNode *N) {
11594 ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1));
11598 // Avoid division by zero.
11599 if (!C->getAPIntValue())
11602 std::vector<SDNode*> Built;
11604 TLI.BuildSDIV(N, C->getAPIntValue(), DAG, LegalOperations, &Built);
11606 for (SDNode *N : Built)
11611 /// BuildSDIVPow2 - Given an ISD::SDIV node expressing a divide by constant
11612 /// power of 2, return a DAG expression to select that will generate the same
11613 /// value by right shifting.
11614 SDValue DAGCombiner::BuildSDIVPow2(SDNode *N) {
11615 ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1));
11619 // Avoid division by zero.
11620 if (!C->getAPIntValue())
11623 std::vector<SDNode *> Built;
11624 SDValue S = TLI.BuildSDIVPow2(N, C->getAPIntValue(), DAG, &Built);
11626 for (SDNode *N : Built)
11631 /// BuildUDIV - Given an ISD::UDIV node expressing a divide by constant,
11632 /// return a DAG expression to select that will generate the same value by
11633 /// multiplying by a magic number. See:
11634 /// <http://the.wall.riscom.net/books/proc/ppc/cwg/code2.html>
11635 SDValue DAGCombiner::BuildUDIV(SDNode *N) {
11636 ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1));
11640 // Avoid division by zero.
11641 if (!C->getAPIntValue())
11644 std::vector<SDNode*> Built;
11646 TLI.BuildUDIV(N, C->getAPIntValue(), DAG, LegalOperations, &Built);
11648 for (SDNode *N : Built)
11653 /// FindBaseOffset - Return true if base is a frame index, which is known not
11654 // to alias with anything but itself. Provides base object and offset as
11656 static bool FindBaseOffset(SDValue Ptr, SDValue &Base, int64_t &Offset,
11657 const GlobalValue *&GV, const void *&CV) {
11658 // Assume it is a primitive operation.
11659 Base = Ptr; Offset = 0; GV = nullptr; CV = nullptr;
11661 // If it's an adding a simple constant then integrate the offset.
11662 if (Base.getOpcode() == ISD::ADD) {
11663 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Base.getOperand(1))) {
11664 Base = Base.getOperand(0);
11665 Offset += C->getZExtValue();
11669 // Return the underlying GlobalValue, and update the Offset. Return false
11670 // for GlobalAddressSDNode since the same GlobalAddress may be represented
11671 // by multiple nodes with different offsets.
11672 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Base)) {
11673 GV = G->getGlobal();
11674 Offset += G->getOffset();
11678 // Return the underlying Constant value, and update the Offset. Return false
11679 // for ConstantSDNodes since the same constant pool entry may be represented
11680 // by multiple nodes with different offsets.
11681 if (ConstantPoolSDNode *C = dyn_cast<ConstantPoolSDNode>(Base)) {
11682 CV = C->isMachineConstantPoolEntry() ? (const void *)C->getMachineCPVal()
11683 : (const void *)C->getConstVal();
11684 Offset += C->getOffset();
11687 // If it's any of the following then it can't alias with anything but itself.
11688 return isa<FrameIndexSDNode>(Base);
11691 /// isAlias - Return true if there is any possibility that the two addresses
11693 bool DAGCombiner::isAlias(LSBaseSDNode *Op0, LSBaseSDNode *Op1) const {
11694 // If they are the same then they must be aliases.
11695 if (Op0->getBasePtr() == Op1->getBasePtr()) return true;
11697 // If they are both volatile then they cannot be reordered.
11698 if (Op0->isVolatile() && Op1->isVolatile()) return true;
11700 // Gather base node and offset information.
11701 SDValue Base1, Base2;
11702 int64_t Offset1, Offset2;
11703 const GlobalValue *GV1, *GV2;
11704 const void *CV1, *CV2;
11705 bool isFrameIndex1 = FindBaseOffset(Op0->getBasePtr(),
11706 Base1, Offset1, GV1, CV1);
11707 bool isFrameIndex2 = FindBaseOffset(Op1->getBasePtr(),
11708 Base2, Offset2, GV2, CV2);
11710 // If they have a same base address then check to see if they overlap.
11711 if (Base1 == Base2 || (GV1 && (GV1 == GV2)) || (CV1 && (CV1 == CV2)))
11712 return !((Offset1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= Offset2 ||
11713 (Offset2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= Offset1);
11715 // It is possible for different frame indices to alias each other, mostly
11716 // when tail call optimization reuses return address slots for arguments.
11717 // To catch this case, look up the actual index of frame indices to compute
11718 // the real alias relationship.
11719 if (isFrameIndex1 && isFrameIndex2) {
11720 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
11721 Offset1 += MFI->getObjectOffset(cast<FrameIndexSDNode>(Base1)->getIndex());
11722 Offset2 += MFI->getObjectOffset(cast<FrameIndexSDNode>(Base2)->getIndex());
11723 return !((Offset1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= Offset2 ||
11724 (Offset2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= Offset1);
11727 // Otherwise, if we know what the bases are, and they aren't identical, then
11728 // we know they cannot alias.
11729 if ((isFrameIndex1 || CV1 || GV1) && (isFrameIndex2 || CV2 || GV2))
11732 // If we know required SrcValue1 and SrcValue2 have relatively large alignment
11733 // compared to the size and offset of the access, we may be able to prove they
11734 // do not alias. This check is conservative for now to catch cases created by
11735 // splitting vector types.
11736 if ((Op0->getOriginalAlignment() == Op1->getOriginalAlignment()) &&
11737 (Op0->getSrcValueOffset() != Op1->getSrcValueOffset()) &&
11738 (Op0->getMemoryVT().getSizeInBits() >> 3 ==
11739 Op1->getMemoryVT().getSizeInBits() >> 3) &&
11740 (Op0->getOriginalAlignment() > Op0->getMemoryVT().getSizeInBits()) >> 3) {
11741 int64_t OffAlign1 = Op0->getSrcValueOffset() % Op0->getOriginalAlignment();
11742 int64_t OffAlign2 = Op1->getSrcValueOffset() % Op1->getOriginalAlignment();
11744 // There is no overlap between these relatively aligned accesses of similar
11745 // size, return no alias.
11746 if ((OffAlign1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= OffAlign2 ||
11747 (OffAlign2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= OffAlign1)
11751 bool UseAA = CombinerGlobalAA.getNumOccurrences() > 0 ? CombinerGlobalAA :
11752 TLI.getTargetMachine().getSubtarget<TargetSubtargetInfo>().useAA();
11754 if (CombinerAAOnlyFunc.getNumOccurrences() &&
11755 CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
11759 Op0->getMemOperand()->getValue() && Op1->getMemOperand()->getValue()) {
11760 // Use alias analysis information.
11761 int64_t MinOffset = std::min(Op0->getSrcValueOffset(),
11762 Op1->getSrcValueOffset());
11763 int64_t Overlap1 = (Op0->getMemoryVT().getSizeInBits() >> 3) +
11764 Op0->getSrcValueOffset() - MinOffset;
11765 int64_t Overlap2 = (Op1->getMemoryVT().getSizeInBits() >> 3) +
11766 Op1->getSrcValueOffset() - MinOffset;
11767 AliasAnalysis::AliasResult AAResult =
11768 AA.alias(AliasAnalysis::Location(Op0->getMemOperand()->getValue(),
11770 UseTBAA ? Op0->getAAInfo() : AAMDNodes()),
11771 AliasAnalysis::Location(Op1->getMemOperand()->getValue(),
11773 UseTBAA ? Op1->getAAInfo() : AAMDNodes()));
11774 if (AAResult == AliasAnalysis::NoAlias)
11778 // Otherwise we have to assume they alias.
11782 /// GatherAllAliases - Walk up chain skipping non-aliasing memory nodes,
11783 /// looking for aliasing nodes and adding them to the Aliases vector.
11784 void DAGCombiner::GatherAllAliases(SDNode *N, SDValue OriginalChain,
11785 SmallVectorImpl<SDValue> &Aliases) {
11786 SmallVector<SDValue, 8> Chains; // List of chains to visit.
11787 SmallPtrSet<SDNode *, 16> Visited; // Visited node set.
11789 // Get alias information for node.
11790 bool IsLoad = isa<LoadSDNode>(N) && !cast<LSBaseSDNode>(N)->isVolatile();
11793 Chains.push_back(OriginalChain);
11794 unsigned Depth = 0;
11796 // Look at each chain and determine if it is an alias. If so, add it to the
11797 // aliases list. If not, then continue up the chain looking for the next
11799 while (!Chains.empty()) {
11800 SDValue Chain = Chains.back();
11803 // For TokenFactor nodes, look at each operand and only continue up the
11804 // chain until we find two aliases. If we've seen two aliases, assume we'll
11805 // find more and revert to original chain since the xform is unlikely to be
11808 // FIXME: The depth check could be made to return the last non-aliasing
11809 // chain we found before we hit a tokenfactor rather than the original
11811 if (Depth > 6 || Aliases.size() == 2) {
11813 Aliases.push_back(OriginalChain);
11817 // Don't bother if we've been before.
11818 if (!Visited.insert(Chain.getNode()))
11821 switch (Chain.getOpcode()) {
11822 case ISD::EntryToken:
11823 // Entry token is ideal chain operand, but handled in FindBetterChain.
11828 // Get alias information for Chain.
11829 bool IsOpLoad = isa<LoadSDNode>(Chain.getNode()) &&
11830 !cast<LSBaseSDNode>(Chain.getNode())->isVolatile();
11832 // If chain is alias then stop here.
11833 if (!(IsLoad && IsOpLoad) &&
11834 isAlias(cast<LSBaseSDNode>(N), cast<LSBaseSDNode>(Chain.getNode()))) {
11835 Aliases.push_back(Chain);
11837 // Look further up the chain.
11838 Chains.push_back(Chain.getOperand(0));
11844 case ISD::TokenFactor:
11845 // We have to check each of the operands of the token factor for "small"
11846 // token factors, so we queue them up. Adding the operands to the queue
11847 // (stack) in reverse order maintains the original order and increases the
11848 // likelihood that getNode will find a matching token factor (CSE.)
11849 if (Chain.getNumOperands() > 16) {
11850 Aliases.push_back(Chain);
11853 for (unsigned n = Chain.getNumOperands(); n;)
11854 Chains.push_back(Chain.getOperand(--n));
11859 // For all other instructions we will just have to take what we can get.
11860 Aliases.push_back(Chain);
11865 // We need to be careful here to also search for aliases through the
11866 // value operand of a store, etc. Consider the following situation:
11868 // L1 = load Token1, %52
11869 // S1 = store Token1, L1, %51
11870 // L2 = load Token1, %52+8
11871 // S2 = store Token1, L2, %51+8
11872 // Token2 = Token(S1, S2)
11873 // L3 = load Token2, %53
11874 // S3 = store Token2, L3, %52
11875 // L4 = load Token2, %53+8
11876 // S4 = store Token2, L4, %52+8
11877 // If we search for aliases of S3 (which loads address %52), and we look
11878 // only through the chain, then we'll miss the trivial dependence on L1
11879 // (which also loads from %52). We then might change all loads and
11880 // stores to use Token1 as their chain operand, which could result in
11881 // copying %53 into %52 before copying %52 into %51 (which should
11884 // The problem is, however, that searching for such data dependencies
11885 // can become expensive, and the cost is not directly related to the
11886 // chain depth. Instead, we'll rule out such configurations here by
11887 // insisting that we've visited all chain users (except for users
11888 // of the original chain, which is not necessary). When doing this,
11889 // we need to look through nodes we don't care about (otherwise, things
11890 // like register copies will interfere with trivial cases).
11892 SmallVector<const SDNode *, 16> Worklist;
11893 for (SmallPtrSet<SDNode *, 16>::iterator I = Visited.begin(),
11894 IE = Visited.end(); I != IE; ++I)
11895 if (*I != OriginalChain.getNode())
11896 Worklist.push_back(*I);
11898 while (!Worklist.empty()) {
11899 const SDNode *M = Worklist.pop_back_val();
11901 // We have already visited M, and want to make sure we've visited any uses
11902 // of M that we care about. For uses that we've not visisted, and don't
11903 // care about, queue them to the worklist.
11905 for (SDNode::use_iterator UI = M->use_begin(),
11906 UIE = M->use_end(); UI != UIE; ++UI)
11907 if (UI.getUse().getValueType() == MVT::Other && Visited.insert(*UI)) {
11908 if (isa<MemIntrinsicSDNode>(*UI) || isa<MemSDNode>(*UI)) {
11909 // We've not visited this use, and we care about it (it could have an
11910 // ordering dependency with the original node).
11912 Aliases.push_back(OriginalChain);
11916 // We've not visited this use, but we don't care about it. Mark it as
11917 // visited and enqueue it to the worklist.
11918 Worklist.push_back(*UI);
11923 /// FindBetterChain - Walk up chain skipping non-aliasing memory nodes, looking
11924 /// for a better chain (aliasing node.)
11925 SDValue DAGCombiner::FindBetterChain(SDNode *N, SDValue OldChain) {
11926 SmallVector<SDValue, 8> Aliases; // Ops for replacing token factor.
11928 // Accumulate all the aliases to this node.
11929 GatherAllAliases(N, OldChain, Aliases);
11931 // If no operands then chain to entry token.
11932 if (Aliases.size() == 0)
11933 return DAG.getEntryNode();
11935 // If a single operand then chain to it. We don't need to revisit it.
11936 if (Aliases.size() == 1)
11939 // Construct a custom tailored token factor.
11940 return DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other, Aliases);
11943 // SelectionDAG::Combine - This is the entry point for the file.
11945 void SelectionDAG::Combine(CombineLevel Level, AliasAnalysis &AA,
11946 CodeGenOpt::Level OptLevel) {
11947 /// run - This is the main entry point to this class.
11949 DAGCombiner(*this, AA, OptLevel).Run(Level);