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 "
81 MaySplitLoadIndex("combiner-split-load-index", cl::Hidden, cl::init(true),
82 cl::desc("DAG combiner may split indexing from loads"));
84 //------------------------------ DAGCombiner ---------------------------------//
88 const TargetLowering &TLI;
90 CodeGenOpt::Level OptLevel;
95 /// \brief Worklist of all of the nodes that need to be simplified.
97 /// This must behave as a stack -- new nodes to process are pushed onto the
98 /// back and when processing we pop off of the back.
100 /// The worklist will not contain duplicates but may contain null entries
101 /// due to nodes being deleted from the underlying DAG.
102 SmallVector<SDNode *, 64> Worklist;
104 /// \brief Mapping from an SDNode to its position on the worklist.
106 /// This is used to find and remove nodes from the worklist (by nulling
107 /// them) when they are deleted from the underlying DAG. It relies on
108 /// stable indices of nodes within the worklist.
109 DenseMap<SDNode *, unsigned> WorklistMap;
111 /// \brief Set of nodes which have been combined (at least once).
113 /// This is used to allow us to reliably add any operands of a DAG node
114 /// which have not yet been combined to the worklist.
115 SmallPtrSet<SDNode *, 64> CombinedNodes;
117 // AA - Used for DAG load/store alias analysis.
120 /// When an instruction is simplified, add all users of the instruction to
121 /// the work lists because they might get more simplified now.
122 void AddUsersToWorklist(SDNode *N) {
123 for (SDNode *Node : N->uses())
127 /// Call the node-specific routine that folds each particular type of node.
128 SDValue visit(SDNode *N);
131 /// Add to the worklist making sure its instance is at the back (next to be
133 void AddToWorklist(SDNode *N) {
134 // Skip handle nodes as they can't usefully be combined and confuse the
135 // zero-use deletion strategy.
136 if (N->getOpcode() == ISD::HANDLENODE)
139 if (WorklistMap.insert(std::make_pair(N, Worklist.size())).second)
140 Worklist.push_back(N);
143 /// 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 /// Check the specified integer node value to see if it can be simplified or
177 /// if things it uses can be simplified by bit propagation.
178 /// 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 SDValue SplitIndexingFromLoad(LoadSDNode *LD);
190 bool SliceUpLoad(SDNode *N);
192 /// \brief Replace an ISD::EXTRACT_VECTOR_ELT of a load with a narrowed
195 /// \param EVE ISD::EXTRACT_VECTOR_ELT to be replaced.
196 /// \param InVecVT type of the input vector to EVE with bitcasts resolved.
197 /// \param EltNo index of the vector element to load.
198 /// \param OriginalLoad load that EVE came from to be replaced.
199 /// \returns EVE on success SDValue() on failure.
200 SDValue ReplaceExtractVectorEltOfLoadWithNarrowedLoad(
201 SDNode *EVE, EVT InVecVT, SDValue EltNo, LoadSDNode *OriginalLoad);
202 void ReplaceLoadWithPromotedLoad(SDNode *Load, SDNode *ExtLoad);
203 SDValue PromoteOperand(SDValue Op, EVT PVT, bool &Replace);
204 SDValue SExtPromoteOperand(SDValue Op, EVT PVT);
205 SDValue ZExtPromoteOperand(SDValue Op, EVT PVT);
206 SDValue PromoteIntBinOp(SDValue Op);
207 SDValue PromoteIntShiftOp(SDValue Op);
208 SDValue PromoteExtend(SDValue Op);
209 bool PromoteLoad(SDValue Op);
211 void ExtendSetCCUses(const SmallVectorImpl<SDNode *> &SetCCs,
212 SDValue Trunc, SDValue ExtLoad, SDLoc DL,
213 ISD::NodeType ExtType);
215 /// Call the node-specific routine that knows how to fold each
216 /// particular type of node. If that doesn't do anything, try the
217 /// target-specific DAG combines.
218 SDValue combine(SDNode *N);
220 // Visitation implementation - Implement dag node combining for different
221 // node types. The semantics are as follows:
223 // SDValue.getNode() == 0 - No change was made
224 // SDValue.getNode() == N - N was replaced, is dead and has been handled.
225 // otherwise - N should be replaced by the returned Operand.
227 SDValue visitTokenFactor(SDNode *N);
228 SDValue visitMERGE_VALUES(SDNode *N);
229 SDValue visitADD(SDNode *N);
230 SDValue visitSUB(SDNode *N);
231 SDValue visitADDC(SDNode *N);
232 SDValue visitSUBC(SDNode *N);
233 SDValue visitADDE(SDNode *N);
234 SDValue visitSUBE(SDNode *N);
235 SDValue visitMUL(SDNode *N);
236 SDValue visitSDIV(SDNode *N);
237 SDValue visitUDIV(SDNode *N);
238 SDValue visitSREM(SDNode *N);
239 SDValue visitUREM(SDNode *N);
240 SDValue visitMULHU(SDNode *N);
241 SDValue visitMULHS(SDNode *N);
242 SDValue visitSMUL_LOHI(SDNode *N);
243 SDValue visitUMUL_LOHI(SDNode *N);
244 SDValue visitSMULO(SDNode *N);
245 SDValue visitUMULO(SDNode *N);
246 SDValue visitSDIVREM(SDNode *N);
247 SDValue visitUDIVREM(SDNode *N);
248 SDValue visitAND(SDNode *N);
249 SDValue visitOR(SDNode *N);
250 SDValue visitXOR(SDNode *N);
251 SDValue SimplifyVBinOp(SDNode *N);
252 SDValue SimplifyVUnaryOp(SDNode *N);
253 SDValue visitSHL(SDNode *N);
254 SDValue visitSRA(SDNode *N);
255 SDValue visitSRL(SDNode *N);
256 SDValue visitRotate(SDNode *N);
257 SDValue visitCTLZ(SDNode *N);
258 SDValue visitCTLZ_ZERO_UNDEF(SDNode *N);
259 SDValue visitCTTZ(SDNode *N);
260 SDValue visitCTTZ_ZERO_UNDEF(SDNode *N);
261 SDValue visitCTPOP(SDNode *N);
262 SDValue visitSELECT(SDNode *N);
263 SDValue visitVSELECT(SDNode *N);
264 SDValue visitSELECT_CC(SDNode *N);
265 SDValue visitSETCC(SDNode *N);
266 SDValue visitSIGN_EXTEND(SDNode *N);
267 SDValue visitZERO_EXTEND(SDNode *N);
268 SDValue visitANY_EXTEND(SDNode *N);
269 SDValue visitSIGN_EXTEND_INREG(SDNode *N);
270 SDValue visitTRUNCATE(SDNode *N);
271 SDValue visitBITCAST(SDNode *N);
272 SDValue visitBUILD_PAIR(SDNode *N);
273 SDValue visitFADD(SDNode *N);
274 SDValue visitFSUB(SDNode *N);
275 SDValue visitFMUL(SDNode *N);
276 SDValue visitFMA(SDNode *N);
277 SDValue visitFDIV(SDNode *N);
278 SDValue visitFREM(SDNode *N);
279 SDValue visitFCOPYSIGN(SDNode *N);
280 SDValue visitSINT_TO_FP(SDNode *N);
281 SDValue visitUINT_TO_FP(SDNode *N);
282 SDValue visitFP_TO_SINT(SDNode *N);
283 SDValue visitFP_TO_UINT(SDNode *N);
284 SDValue visitFP_ROUND(SDNode *N);
285 SDValue visitFP_ROUND_INREG(SDNode *N);
286 SDValue visitFP_EXTEND(SDNode *N);
287 SDValue visitFNEG(SDNode *N);
288 SDValue visitFABS(SDNode *N);
289 SDValue visitFCEIL(SDNode *N);
290 SDValue visitFTRUNC(SDNode *N);
291 SDValue visitFFLOOR(SDNode *N);
292 SDValue visitBRCOND(SDNode *N);
293 SDValue visitBR_CC(SDNode *N);
294 SDValue visitLOAD(SDNode *N);
295 SDValue visitSTORE(SDNode *N);
296 SDValue visitINSERT_VECTOR_ELT(SDNode *N);
297 SDValue visitEXTRACT_VECTOR_ELT(SDNode *N);
298 SDValue visitBUILD_VECTOR(SDNode *N);
299 SDValue visitCONCAT_VECTORS(SDNode *N);
300 SDValue visitEXTRACT_SUBVECTOR(SDNode *N);
301 SDValue visitVECTOR_SHUFFLE(SDNode *N);
302 SDValue visitINSERT_SUBVECTOR(SDNode *N);
304 SDValue XformToShuffleWithZero(SDNode *N);
305 SDValue ReassociateOps(unsigned Opc, SDLoc DL, SDValue LHS, SDValue RHS);
307 SDValue visitShiftByConstant(SDNode *N, ConstantSDNode *Amt);
309 bool SimplifySelectOps(SDNode *SELECT, SDValue LHS, SDValue RHS);
310 SDValue SimplifyBinOpWithSameOpcodeHands(SDNode *N);
311 SDValue SimplifySelect(SDLoc DL, SDValue N0, SDValue N1, SDValue N2);
312 SDValue SimplifySelectCC(SDLoc DL, SDValue N0, SDValue N1, SDValue N2,
313 SDValue N3, ISD::CondCode CC,
314 bool NotExtCompare = false);
315 SDValue SimplifySetCC(EVT VT, SDValue N0, SDValue N1, ISD::CondCode Cond,
316 SDLoc DL, bool foldBooleans = true);
318 bool isSetCCEquivalent(SDValue N, SDValue &LHS, SDValue &RHS,
320 bool isOneUseSetCC(SDValue N) const;
322 SDValue SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp,
324 SDValue CombineConsecutiveLoads(SDNode *N, EVT VT);
325 SDValue ConstantFoldBITCASTofBUILD_VECTOR(SDNode *, EVT);
326 SDValue BuildSDIV(SDNode *N);
327 SDValue BuildSDIVPow2(SDNode *N);
328 SDValue BuildUDIV(SDNode *N);
329 SDValue MatchBSwapHWordLow(SDNode *N, SDValue N0, SDValue N1,
330 bool DemandHighBits = true);
331 SDValue MatchBSwapHWord(SDNode *N, SDValue N0, SDValue N1);
332 SDNode *MatchRotatePosNeg(SDValue Shifted, SDValue Pos, SDValue Neg,
333 SDValue InnerPos, SDValue InnerNeg,
334 unsigned PosOpcode, unsigned NegOpcode,
336 SDNode *MatchRotate(SDValue LHS, SDValue RHS, SDLoc DL);
337 SDValue ReduceLoadWidth(SDNode *N);
338 SDValue ReduceLoadOpStoreWidth(SDNode *N);
339 SDValue TransformFPLoadStorePair(SDNode *N);
340 SDValue reduceBuildVecExtToExtBuildVec(SDNode *N);
341 SDValue reduceBuildVecConvertToConvertBuildVec(SDNode *N);
343 SDValue GetDemandedBits(SDValue V, const APInt &Mask);
345 /// Walk up chain skipping non-aliasing memory nodes,
346 /// looking for aliasing nodes and adding them to the Aliases vector.
347 void GatherAllAliases(SDNode *N, SDValue OriginalChain,
348 SmallVectorImpl<SDValue> &Aliases);
350 /// Return true if there is any possibility that the two addresses overlap.
351 bool isAlias(LSBaseSDNode *Op0, LSBaseSDNode *Op1) const;
353 /// Walk up chain skipping non-aliasing memory nodes, looking for a better
354 /// 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 /// Runs the dag combiner on all nodes in the work list
383 void Run(CombineLevel AtLevel);
385 SelectionDAG &getDAG() const { return DAG; }
387 /// Returns a type large enough to hold any valid shift amount - before type
388 /// 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 /// This method returns true if we are running before type legalization or
398 /// if the specified VT is legal.
399 bool isTypeLegal(const EVT &VT) {
400 if (!LegalTypes) return true;
401 return TLI.isTypeLegal(VT);
404 /// Convenience wrapper around TargetLowering::getSetCCResultType
405 EVT getSetCCResultType(EVT VT) const {
406 return TLI.getSetCCResultType(*DAG.getContext(), VT);
413 /// This class is a DAGUpdateListener that removes any deleted
414 /// nodes from the worklist.
415 class WorklistRemover : public SelectionDAG::DAGUpdateListener {
418 explicit WorklistRemover(DAGCombiner &dc)
419 : SelectionDAG::DAGUpdateListener(dc.getDAG()), DC(dc) {}
421 void NodeDeleted(SDNode *N, SDNode *E) override {
422 DC.removeFromWorklist(N);
427 //===----------------------------------------------------------------------===//
428 // TargetLowering::DAGCombinerInfo implementation
429 //===----------------------------------------------------------------------===//
431 void TargetLowering::DAGCombinerInfo::AddToWorklist(SDNode *N) {
432 ((DAGCombiner*)DC)->AddToWorklist(N);
435 void TargetLowering::DAGCombinerInfo::RemoveFromWorklist(SDNode *N) {
436 ((DAGCombiner*)DC)->removeFromWorklist(N);
439 SDValue TargetLowering::DAGCombinerInfo::
440 CombineTo(SDNode *N, const std::vector<SDValue> &To, bool AddTo) {
441 return ((DAGCombiner*)DC)->CombineTo(N, &To[0], To.size(), AddTo);
444 SDValue TargetLowering::DAGCombinerInfo::
445 CombineTo(SDNode *N, SDValue Res, bool AddTo) {
446 return ((DAGCombiner*)DC)->CombineTo(N, Res, AddTo);
450 SDValue TargetLowering::DAGCombinerInfo::
451 CombineTo(SDNode *N, SDValue Res0, SDValue Res1, bool AddTo) {
452 return ((DAGCombiner*)DC)->CombineTo(N, Res0, Res1, AddTo);
455 void TargetLowering::DAGCombinerInfo::
456 CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) {
457 return ((DAGCombiner*)DC)->CommitTargetLoweringOpt(TLO);
460 //===----------------------------------------------------------------------===//
462 //===----------------------------------------------------------------------===//
464 void DAGCombiner::deleteAndRecombine(SDNode *N) {
465 removeFromWorklist(N);
467 // If the operands of this node are only used by the node, they will now be
468 // dead. Make sure to re-visit them and recursively delete dead nodes.
469 for (const SDValue &Op : N->ops())
470 // For an operand generating multiple values, one of the values may
471 // become dead allowing further simplification (e.g. split index
472 // arithmetic from an indexed load).
473 if (Op->hasOneUse() || Op->getNumValues() > 1)
474 AddToWorklist(Op.getNode());
479 /// Return 1 if we can compute the negated form of the specified expression for
480 /// the same cost as the expression itself, or 2 if we can compute the negated
481 /// form more cheaply than the expression itself.
482 static char isNegatibleForFree(SDValue Op, bool LegalOperations,
483 const TargetLowering &TLI,
484 const TargetOptions *Options,
485 unsigned Depth = 0) {
486 // fneg is removable even if it has multiple uses.
487 if (Op.getOpcode() == ISD::FNEG) return 2;
489 // Don't allow anything with multiple uses.
490 if (!Op.hasOneUse()) return 0;
492 // Don't recurse exponentially.
493 if (Depth > 6) return 0;
495 switch (Op.getOpcode()) {
496 default: return false;
497 case ISD::ConstantFP:
498 // Don't invert constant FP values after legalize. The negated constant
499 // isn't necessarily legal.
500 return LegalOperations ? 0 : 1;
502 // FIXME: determine better conditions for this xform.
503 if (!Options->UnsafeFPMath) return 0;
505 // After operation legalization, it might not be legal to create new FSUBs.
506 if (LegalOperations &&
507 !TLI.isOperationLegalOrCustom(ISD::FSUB, Op.getValueType()))
510 // fold (fneg (fadd A, B)) -> (fsub (fneg A), B)
511 if (char V = isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI,
514 // fold (fneg (fadd A, B)) -> (fsub (fneg B), A)
515 return isNegatibleForFree(Op.getOperand(1), LegalOperations, TLI, Options,
518 // We can't turn -(A-B) into B-A when we honor signed zeros.
519 if (!Options->UnsafeFPMath) return 0;
521 // fold (fneg (fsub A, B)) -> (fsub B, A)
526 if (Options->HonorSignDependentRoundingFPMath()) return 0;
528 // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y) or (fmul X, (fneg Y))
529 if (char V = isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI,
533 return isNegatibleForFree(Op.getOperand(1), LegalOperations, TLI, Options,
539 return isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI, Options,
544 /// If isNegatibleForFree returns true, return the newly negated expression.
545 static SDValue GetNegatedExpression(SDValue Op, SelectionDAG &DAG,
546 bool LegalOperations, unsigned Depth = 0) {
547 const TargetOptions &Options = DAG.getTarget().Options;
548 // fneg is removable even if it has multiple uses.
549 if (Op.getOpcode() == ISD::FNEG) return Op.getOperand(0);
551 // Don't allow anything with multiple uses.
552 assert(Op.hasOneUse() && "Unknown reuse!");
554 assert(Depth <= 6 && "GetNegatedExpression doesn't match isNegatibleForFree");
555 switch (Op.getOpcode()) {
556 default: llvm_unreachable("Unknown code");
557 case ISD::ConstantFP: {
558 APFloat V = cast<ConstantFPSDNode>(Op)->getValueAPF();
560 return DAG.getConstantFP(V, Op.getValueType());
563 // FIXME: determine better conditions for this xform.
564 assert(Options.UnsafeFPMath);
566 // fold (fneg (fadd A, B)) -> (fsub (fneg A), B)
567 if (isNegatibleForFree(Op.getOperand(0), LegalOperations,
568 DAG.getTargetLoweringInfo(), &Options, Depth+1))
569 return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
570 GetNegatedExpression(Op.getOperand(0), DAG,
571 LegalOperations, Depth+1),
573 // fold (fneg (fadd A, B)) -> (fsub (fneg B), A)
574 return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
575 GetNegatedExpression(Op.getOperand(1), DAG,
576 LegalOperations, Depth+1),
579 // We can't turn -(A-B) into B-A when we honor signed zeros.
580 assert(Options.UnsafeFPMath);
582 // fold (fneg (fsub 0, B)) -> B
583 if (ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(Op.getOperand(0)))
584 if (N0CFP->getValueAPF().isZero())
585 return Op.getOperand(1);
587 // fold (fneg (fsub A, B)) -> (fsub B, A)
588 return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
589 Op.getOperand(1), Op.getOperand(0));
593 assert(!Options.HonorSignDependentRoundingFPMath());
595 // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y)
596 if (isNegatibleForFree(Op.getOperand(0), LegalOperations,
597 DAG.getTargetLoweringInfo(), &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 /// Return true if this is a SetCC-equivalent operation with only one use.
648 /// If this is true, it allows the users to invert the operation for free when
649 /// it is profitable to do so.
650 bool DAGCombiner::isOneUseSetCC(SDValue N) const {
652 if (isSetCCEquivalent(N, N0, N1, N2) && N.getNode()->hasOneUse())
657 /// 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 // \brief Returns the SDNode if it is a constant splat BuildVector or constant
706 static ConstantFPSDNode *isConstOrConstSplatFP(SDValue N) {
707 if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(N))
710 if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) {
711 BitVector UndefElements;
712 ConstantFPSDNode *CN = BV->getConstantFPSplatNode(&UndefElements);
714 // BuildVectors can truncate their operands. Ignore that case here.
715 // FIXME: We blindly ignore splats which include undef which is overly
717 if (CN && UndefElements.none() &&
718 CN->getValueType(0) == N.getValueType().getScalarType())
725 SDValue DAGCombiner::ReassociateOps(unsigned Opc, SDLoc DL,
726 SDValue N0, SDValue N1) {
727 EVT VT = N0.getValueType();
728 if (N0.getOpcode() == Opc) {
729 if (SDNode *L = isConstantBuildVectorOrConstantInt(N0.getOperand(1))) {
730 if (SDNode *R = isConstantBuildVectorOrConstantInt(N1)) {
731 // reassoc. (op (op x, c1), c2) -> (op x, (op c1, c2))
732 SDValue OpNode = DAG.FoldConstantArithmetic(Opc, VT, L, R);
733 if (!OpNode.getNode())
735 return DAG.getNode(Opc, DL, VT, N0.getOperand(0), OpNode);
737 if (N0.hasOneUse()) {
738 // reassoc. (op (op x, c1), y) -> (op (op x, y), c1) iff x+c1 has one
740 SDValue OpNode = DAG.getNode(Opc, SDLoc(N0), VT, N0.getOperand(0), N1);
741 if (!OpNode.getNode())
743 AddToWorklist(OpNode.getNode());
744 return DAG.getNode(Opc, DL, VT, OpNode, N0.getOperand(1));
749 if (N1.getOpcode() == Opc) {
750 if (SDNode *R = isConstantBuildVectorOrConstantInt(N1.getOperand(1))) {
751 if (SDNode *L = isConstantBuildVectorOrConstantInt(N0)) {
752 // reassoc. (op c2, (op x, c1)) -> (op x, (op c1, c2))
753 SDValue OpNode = DAG.FoldConstantArithmetic(Opc, VT, R, L);
754 if (!OpNode.getNode())
756 return DAG.getNode(Opc, DL, VT, N1.getOperand(0), OpNode);
758 if (N1.hasOneUse()) {
759 // reassoc. (op y, (op x, c1)) -> (op (op x, y), c1) iff x+c1 has one
761 SDValue OpNode = DAG.getNode(Opc, SDLoc(N0), VT, N1.getOperand(0), N0);
762 if (!OpNode.getNode())
764 AddToWorklist(OpNode.getNode());
765 return DAG.getNode(Opc, DL, VT, OpNode, N1.getOperand(1));
773 SDValue DAGCombiner::CombineTo(SDNode *N, const SDValue *To, unsigned NumTo,
775 assert(N->getNumValues() == NumTo && "Broken CombineTo call!");
777 DEBUG(dbgs() << "\nReplacing.1 ";
779 dbgs() << "\nWith: ";
780 To[0].getNode()->dump(&DAG);
781 dbgs() << " and " << NumTo-1 << " other values\n";
782 for (unsigned i = 0, e = NumTo; i != e; ++i)
783 assert((!To[i].getNode() ||
784 N->getValueType(i) == To[i].getValueType()) &&
785 "Cannot combine value to value of different type!"));
786 WorklistRemover DeadNodes(*this);
787 DAG.ReplaceAllUsesWith(N, To);
789 // Push the new nodes and any users onto the worklist
790 for (unsigned i = 0, e = NumTo; i != e; ++i) {
791 if (To[i].getNode()) {
792 AddToWorklist(To[i].getNode());
793 AddUsersToWorklist(To[i].getNode());
798 // Finally, if the node is now dead, remove it from the graph. The node
799 // may not be dead if the replacement process recursively simplified to
800 // something else needing this node.
802 deleteAndRecombine(N);
803 return SDValue(N, 0);
807 CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) {
808 // Replace all uses. If any nodes become isomorphic to other nodes and
809 // are deleted, make sure to remove them from our worklist.
810 WorklistRemover DeadNodes(*this);
811 DAG.ReplaceAllUsesOfValueWith(TLO.Old, TLO.New);
813 // Push the new node and any (possibly new) users onto the worklist.
814 AddToWorklist(TLO.New.getNode());
815 AddUsersToWorklist(TLO.New.getNode());
817 // Finally, if the node is now dead, remove it from the graph. The node
818 // may not be dead if the replacement process recursively simplified to
819 // something else needing this node.
820 if (TLO.Old.getNode()->use_empty())
821 deleteAndRecombine(TLO.Old.getNode());
824 /// Check the specified integer node value to see if it can be simplified or if
825 /// things it uses can be simplified by bit propagation. If so, return true.
826 bool DAGCombiner::SimplifyDemandedBits(SDValue Op, const APInt &Demanded) {
827 TargetLowering::TargetLoweringOpt TLO(DAG, LegalTypes, LegalOperations);
828 APInt KnownZero, KnownOne;
829 if (!TLI.SimplifyDemandedBits(Op, Demanded, KnownZero, KnownOne, TLO))
833 AddToWorklist(Op.getNode());
835 // Replace the old value with the new one.
837 DEBUG(dbgs() << "\nReplacing.2 ";
838 TLO.Old.getNode()->dump(&DAG);
839 dbgs() << "\nWith: ";
840 TLO.New.getNode()->dump(&DAG);
843 CommitTargetLoweringOpt(TLO);
847 void DAGCombiner::ReplaceLoadWithPromotedLoad(SDNode *Load, SDNode *ExtLoad) {
849 EVT VT = Load->getValueType(0);
850 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, dl, VT, SDValue(ExtLoad, 0));
852 DEBUG(dbgs() << "\nReplacing.9 ";
854 dbgs() << "\nWith: ";
855 Trunc.getNode()->dump(&DAG);
857 WorklistRemover DeadNodes(*this);
858 DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 0), Trunc);
859 DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 1), SDValue(ExtLoad, 1));
860 deleteAndRecombine(Load);
861 AddToWorklist(Trunc.getNode());
864 SDValue DAGCombiner::PromoteOperand(SDValue Op, EVT PVT, bool &Replace) {
867 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Op)) {
868 EVT MemVT = LD->getMemoryVT();
869 ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD)
870 ? (TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT) ? ISD::ZEXTLOAD
872 : LD->getExtensionType();
874 return DAG.getExtLoad(ExtType, dl, PVT,
875 LD->getChain(), LD->getBasePtr(),
876 MemVT, LD->getMemOperand());
879 unsigned Opc = Op.getOpcode();
882 case ISD::AssertSext:
883 return DAG.getNode(ISD::AssertSext, dl, PVT,
884 SExtPromoteOperand(Op.getOperand(0), PVT),
886 case ISD::AssertZext:
887 return DAG.getNode(ISD::AssertZext, dl, PVT,
888 ZExtPromoteOperand(Op.getOperand(0), PVT),
890 case ISD::Constant: {
892 Op.getValueType().isByteSized() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
893 return DAG.getNode(ExtOpc, dl, PVT, Op);
897 if (!TLI.isOperationLegal(ISD::ANY_EXTEND, PVT))
899 return DAG.getNode(ISD::ANY_EXTEND, dl, PVT, Op);
902 SDValue DAGCombiner::SExtPromoteOperand(SDValue Op, EVT PVT) {
903 if (!TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, PVT))
905 EVT OldVT = Op.getValueType();
907 bool Replace = false;
908 SDValue NewOp = PromoteOperand(Op, PVT, Replace);
909 if (!NewOp.getNode())
911 AddToWorklist(NewOp.getNode());
914 ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode());
915 return DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, NewOp.getValueType(), NewOp,
916 DAG.getValueType(OldVT));
919 SDValue DAGCombiner::ZExtPromoteOperand(SDValue Op, EVT PVT) {
920 EVT OldVT = Op.getValueType();
922 bool Replace = false;
923 SDValue NewOp = PromoteOperand(Op, PVT, Replace);
924 if (!NewOp.getNode())
926 AddToWorklist(NewOp.getNode());
929 ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode());
930 return DAG.getZeroExtendInReg(NewOp, dl, OldVT);
933 /// Promote the specified integer binary operation if the target indicates it is
934 /// beneficial. e.g. On x86, it's usually better to promote i16 operations to
935 /// i32 since i16 instructions are longer.
936 SDValue DAGCombiner::PromoteIntBinOp(SDValue Op) {
937 if (!LegalOperations)
940 EVT VT = Op.getValueType();
941 if (VT.isVector() || !VT.isInteger())
944 // If operation type is 'undesirable', e.g. i16 on x86, consider
946 unsigned Opc = Op.getOpcode();
947 if (TLI.isTypeDesirableForOp(Opc, VT))
951 // Consult target whether it is a good idea to promote this operation and
952 // what's the right type to promote it to.
953 if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
954 assert(PVT != VT && "Don't know what type to promote to!");
956 bool Replace0 = false;
957 SDValue N0 = Op.getOperand(0);
958 SDValue NN0 = PromoteOperand(N0, PVT, Replace0);
962 bool Replace1 = false;
963 SDValue N1 = Op.getOperand(1);
968 NN1 = PromoteOperand(N1, PVT, Replace1);
973 AddToWorklist(NN0.getNode());
975 AddToWorklist(NN1.getNode());
978 ReplaceLoadWithPromotedLoad(N0.getNode(), NN0.getNode());
980 ReplaceLoadWithPromotedLoad(N1.getNode(), NN1.getNode());
982 DEBUG(dbgs() << "\nPromoting ";
983 Op.getNode()->dump(&DAG));
985 return DAG.getNode(ISD::TRUNCATE, dl, VT,
986 DAG.getNode(Opc, dl, PVT, NN0, NN1));
991 /// Promote the specified integer shift operation if the target indicates it is
992 /// beneficial. e.g. On x86, it's usually better to promote i16 operations to
993 /// i32 since i16 instructions are longer.
994 SDValue DAGCombiner::PromoteIntShiftOp(SDValue Op) {
995 if (!LegalOperations)
998 EVT VT = Op.getValueType();
999 if (VT.isVector() || !VT.isInteger())
1002 // If operation type is 'undesirable', e.g. i16 on x86, consider
1004 unsigned Opc = Op.getOpcode();
1005 if (TLI.isTypeDesirableForOp(Opc, VT))
1009 // Consult target whether it is a good idea to promote this operation and
1010 // what's the right type to promote it to.
1011 if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1012 assert(PVT != VT && "Don't know what type to promote to!");
1014 bool Replace = false;
1015 SDValue N0 = Op.getOperand(0);
1016 if (Opc == ISD::SRA)
1017 N0 = SExtPromoteOperand(Op.getOperand(0), PVT);
1018 else if (Opc == ISD::SRL)
1019 N0 = ZExtPromoteOperand(Op.getOperand(0), PVT);
1021 N0 = PromoteOperand(N0, PVT, Replace);
1025 AddToWorklist(N0.getNode());
1027 ReplaceLoadWithPromotedLoad(Op.getOperand(0).getNode(), N0.getNode());
1029 DEBUG(dbgs() << "\nPromoting ";
1030 Op.getNode()->dump(&DAG));
1032 return DAG.getNode(ISD::TRUNCATE, dl, VT,
1033 DAG.getNode(Opc, dl, PVT, N0, Op.getOperand(1)));
1038 SDValue DAGCombiner::PromoteExtend(SDValue Op) {
1039 if (!LegalOperations)
1042 EVT VT = Op.getValueType();
1043 if (VT.isVector() || !VT.isInteger())
1046 // If operation type is 'undesirable', e.g. i16 on x86, consider
1048 unsigned Opc = Op.getOpcode();
1049 if (TLI.isTypeDesirableForOp(Opc, VT))
1053 // Consult target whether it is a good idea to promote this operation and
1054 // what's the right type to promote it to.
1055 if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1056 assert(PVT != VT && "Don't know what type to promote to!");
1057 // fold (aext (aext x)) -> (aext x)
1058 // fold (aext (zext x)) -> (zext x)
1059 // fold (aext (sext x)) -> (sext x)
1060 DEBUG(dbgs() << "\nPromoting ";
1061 Op.getNode()->dump(&DAG));
1062 return DAG.getNode(Op.getOpcode(), SDLoc(Op), VT, Op.getOperand(0));
1067 bool DAGCombiner::PromoteLoad(SDValue Op) {
1068 if (!LegalOperations)
1071 EVT VT = Op.getValueType();
1072 if (VT.isVector() || !VT.isInteger())
1075 // If operation type is 'undesirable', e.g. i16 on x86, consider
1077 unsigned Opc = Op.getOpcode();
1078 if (TLI.isTypeDesirableForOp(Opc, VT))
1082 // Consult target whether it is a good idea to promote this operation and
1083 // what's the right type to promote it to.
1084 if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1085 assert(PVT != VT && "Don't know what type to promote to!");
1088 SDNode *N = Op.getNode();
1089 LoadSDNode *LD = cast<LoadSDNode>(N);
1090 EVT MemVT = LD->getMemoryVT();
1091 ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD)
1092 ? (TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT) ? ISD::ZEXTLOAD
1094 : LD->getExtensionType();
1095 SDValue NewLD = DAG.getExtLoad(ExtType, dl, PVT,
1096 LD->getChain(), LD->getBasePtr(),
1097 MemVT, LD->getMemOperand());
1098 SDValue Result = DAG.getNode(ISD::TRUNCATE, dl, VT, NewLD);
1100 DEBUG(dbgs() << "\nPromoting ";
1103 Result.getNode()->dump(&DAG);
1105 WorklistRemover DeadNodes(*this);
1106 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result);
1107 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), NewLD.getValue(1));
1108 deleteAndRecombine(N);
1109 AddToWorklist(Result.getNode());
1115 /// \brief Recursively delete a node which has no uses and any operands for
1116 /// which it is the only use.
1118 /// Note that this both deletes the nodes and removes them from the worklist.
1119 /// It also adds any nodes who have had a user deleted to the worklist as they
1120 /// may now have only one use and subject to other combines.
1121 bool DAGCombiner::recursivelyDeleteUnusedNodes(SDNode *N) {
1122 if (!N->use_empty())
1125 SmallSetVector<SDNode *, 16> Nodes;
1128 N = Nodes.pop_back_val();
1132 if (N->use_empty()) {
1133 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1134 Nodes.insert(N->getOperand(i).getNode());
1136 removeFromWorklist(N);
1141 } while (!Nodes.empty());
1145 //===----------------------------------------------------------------------===//
1146 // Main DAG Combiner implementation
1147 //===----------------------------------------------------------------------===//
1149 void DAGCombiner::Run(CombineLevel AtLevel) {
1150 // set the instance variables, so that the various visit routines may use it.
1152 LegalOperations = Level >= AfterLegalizeVectorOps;
1153 LegalTypes = Level >= AfterLegalizeTypes;
1155 // Add all the dag nodes to the worklist.
1156 for (SelectionDAG::allnodes_iterator I = DAG.allnodes_begin(),
1157 E = DAG.allnodes_end(); I != E; ++I)
1160 // Create a dummy node (which is not added to allnodes), that adds a reference
1161 // to the root node, preventing it from being deleted, and tracking any
1162 // changes of the root.
1163 HandleSDNode Dummy(DAG.getRoot());
1165 // while the worklist isn't empty, find a node and
1166 // try and combine it.
1167 while (!WorklistMap.empty()) {
1169 // The Worklist holds the SDNodes in order, but it may contain null entries.
1171 N = Worklist.pop_back_val();
1174 bool GoodWorklistEntry = WorklistMap.erase(N);
1175 (void)GoodWorklistEntry;
1176 assert(GoodWorklistEntry &&
1177 "Found a worklist entry without a corresponding map entry!");
1179 // If N has no uses, it is dead. Make sure to revisit all N's operands once
1180 // N is deleted from the DAG, since they too may now be dead or may have a
1181 // reduced number of uses, allowing other xforms.
1182 if (recursivelyDeleteUnusedNodes(N))
1185 WorklistRemover DeadNodes(*this);
1187 // If this combine is running after legalizing the DAG, re-legalize any
1188 // nodes pulled off the worklist.
1189 if (Level == AfterLegalizeDAG) {
1190 SmallSetVector<SDNode *, 16> UpdatedNodes;
1191 bool NIsValid = DAG.LegalizeOp(N, UpdatedNodes);
1193 for (SDNode *LN : UpdatedNodes) {
1195 AddUsersToWorklist(LN);
1201 DEBUG(dbgs() << "\nCombining: "; N->dump(&DAG));
1203 // Add any operands of the new node which have not yet been combined to the
1204 // worklist as well. Because the worklist uniques things already, this
1205 // won't repeatedly process the same operand.
1206 CombinedNodes.insert(N);
1207 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1208 if (!CombinedNodes.count(N->getOperand(i).getNode()))
1209 AddToWorklist(N->getOperand(i).getNode());
1211 SDValue RV = combine(N);
1218 // If we get back the same node we passed in, rather than a new node or
1219 // zero, we know that the node must have defined multiple values and
1220 // CombineTo was used. Since CombineTo takes care of the worklist
1221 // mechanics for us, we have no work to do in this case.
1222 if (RV.getNode() == N)
1225 assert(N->getOpcode() != ISD::DELETED_NODE &&
1226 RV.getNode()->getOpcode() != ISD::DELETED_NODE &&
1227 "Node was deleted but visit returned new node!");
1229 DEBUG(dbgs() << " ... into: ";
1230 RV.getNode()->dump(&DAG));
1232 // Transfer debug value.
1233 DAG.TransferDbgValues(SDValue(N, 0), RV);
1234 if (N->getNumValues() == RV.getNode()->getNumValues())
1235 DAG.ReplaceAllUsesWith(N, RV.getNode());
1237 assert(N->getValueType(0) == RV.getValueType() &&
1238 N->getNumValues() == 1 && "Type mismatch");
1240 DAG.ReplaceAllUsesWith(N, &OpV);
1243 // Push the new node and any users onto the worklist
1244 AddToWorklist(RV.getNode());
1245 AddUsersToWorklist(RV.getNode());
1247 // Finally, if the node is now dead, remove it from the graph. The node
1248 // may not be dead if the replacement process recursively simplified to
1249 // something else needing this node. This will also take care of adding any
1250 // operands which have lost a user to the worklist.
1251 recursivelyDeleteUnusedNodes(N);
1254 // If the root changed (e.g. it was a dead load, update the root).
1255 DAG.setRoot(Dummy.getValue());
1256 DAG.RemoveDeadNodes();
1259 SDValue DAGCombiner::visit(SDNode *N) {
1260 switch (N->getOpcode()) {
1262 case ISD::TokenFactor: return visitTokenFactor(N);
1263 case ISD::MERGE_VALUES: return visitMERGE_VALUES(N);
1264 case ISD::ADD: return visitADD(N);
1265 case ISD::SUB: return visitSUB(N);
1266 case ISD::ADDC: return visitADDC(N);
1267 case ISD::SUBC: return visitSUBC(N);
1268 case ISD::ADDE: return visitADDE(N);
1269 case ISD::SUBE: return visitSUBE(N);
1270 case ISD::MUL: return visitMUL(N);
1271 case ISD::SDIV: return visitSDIV(N);
1272 case ISD::UDIV: return visitUDIV(N);
1273 case ISD::SREM: return visitSREM(N);
1274 case ISD::UREM: return visitUREM(N);
1275 case ISD::MULHU: return visitMULHU(N);
1276 case ISD::MULHS: return visitMULHS(N);
1277 case ISD::SMUL_LOHI: return visitSMUL_LOHI(N);
1278 case ISD::UMUL_LOHI: return visitUMUL_LOHI(N);
1279 case ISD::SMULO: return visitSMULO(N);
1280 case ISD::UMULO: return visitUMULO(N);
1281 case ISD::SDIVREM: return visitSDIVREM(N);
1282 case ISD::UDIVREM: return visitUDIVREM(N);
1283 case ISD::AND: return visitAND(N);
1284 case ISD::OR: return visitOR(N);
1285 case ISD::XOR: return visitXOR(N);
1286 case ISD::SHL: return visitSHL(N);
1287 case ISD::SRA: return visitSRA(N);
1288 case ISD::SRL: return visitSRL(N);
1290 case ISD::ROTL: return visitRotate(N);
1291 case ISD::CTLZ: return visitCTLZ(N);
1292 case ISD::CTLZ_ZERO_UNDEF: return visitCTLZ_ZERO_UNDEF(N);
1293 case ISD::CTTZ: return visitCTTZ(N);
1294 case ISD::CTTZ_ZERO_UNDEF: return visitCTTZ_ZERO_UNDEF(N);
1295 case ISD::CTPOP: return visitCTPOP(N);
1296 case ISD::SELECT: return visitSELECT(N);
1297 case ISD::VSELECT: return visitVSELECT(N);
1298 case ISD::SELECT_CC: return visitSELECT_CC(N);
1299 case ISD::SETCC: return visitSETCC(N);
1300 case ISD::SIGN_EXTEND: return visitSIGN_EXTEND(N);
1301 case ISD::ZERO_EXTEND: return visitZERO_EXTEND(N);
1302 case ISD::ANY_EXTEND: return visitANY_EXTEND(N);
1303 case ISD::SIGN_EXTEND_INREG: return visitSIGN_EXTEND_INREG(N);
1304 case ISD::TRUNCATE: return visitTRUNCATE(N);
1305 case ISD::BITCAST: return visitBITCAST(N);
1306 case ISD::BUILD_PAIR: return visitBUILD_PAIR(N);
1307 case ISD::FADD: return visitFADD(N);
1308 case ISD::FSUB: return visitFSUB(N);
1309 case ISD::FMUL: return visitFMUL(N);
1310 case ISD::FMA: return visitFMA(N);
1311 case ISD::FDIV: return visitFDIV(N);
1312 case ISD::FREM: return visitFREM(N);
1313 case ISD::FCOPYSIGN: return visitFCOPYSIGN(N);
1314 case ISD::SINT_TO_FP: return visitSINT_TO_FP(N);
1315 case ISD::UINT_TO_FP: return visitUINT_TO_FP(N);
1316 case ISD::FP_TO_SINT: return visitFP_TO_SINT(N);
1317 case ISD::FP_TO_UINT: return visitFP_TO_UINT(N);
1318 case ISD::FP_ROUND: return visitFP_ROUND(N);
1319 case ISD::FP_ROUND_INREG: return visitFP_ROUND_INREG(N);
1320 case ISD::FP_EXTEND: return visitFP_EXTEND(N);
1321 case ISD::FNEG: return visitFNEG(N);
1322 case ISD::FABS: return visitFABS(N);
1323 case ISD::FFLOOR: return visitFFLOOR(N);
1324 case ISD::FCEIL: return visitFCEIL(N);
1325 case ISD::FTRUNC: return visitFTRUNC(N);
1326 case ISD::BRCOND: return visitBRCOND(N);
1327 case ISD::BR_CC: return visitBR_CC(N);
1328 case ISD::LOAD: return visitLOAD(N);
1329 case ISD::STORE: return visitSTORE(N);
1330 case ISD::INSERT_VECTOR_ELT: return visitINSERT_VECTOR_ELT(N);
1331 case ISD::EXTRACT_VECTOR_ELT: return visitEXTRACT_VECTOR_ELT(N);
1332 case ISD::BUILD_VECTOR: return visitBUILD_VECTOR(N);
1333 case ISD::CONCAT_VECTORS: return visitCONCAT_VECTORS(N);
1334 case ISD::EXTRACT_SUBVECTOR: return visitEXTRACT_SUBVECTOR(N);
1335 case ISD::VECTOR_SHUFFLE: return visitVECTOR_SHUFFLE(N);
1336 case ISD::INSERT_SUBVECTOR: return visitINSERT_SUBVECTOR(N);
1341 SDValue DAGCombiner::combine(SDNode *N) {
1342 SDValue RV = visit(N);
1344 // If nothing happened, try a target-specific DAG combine.
1345 if (!RV.getNode()) {
1346 assert(N->getOpcode() != ISD::DELETED_NODE &&
1347 "Node was deleted but visit returned NULL!");
1349 if (N->getOpcode() >= ISD::BUILTIN_OP_END ||
1350 TLI.hasTargetDAGCombine((ISD::NodeType)N->getOpcode())) {
1352 // Expose the DAG combiner to the target combiner impls.
1353 TargetLowering::DAGCombinerInfo
1354 DagCombineInfo(DAG, Level, false, this);
1356 RV = TLI.PerformDAGCombine(N, DagCombineInfo);
1360 // If nothing happened still, try promoting the operation.
1361 if (!RV.getNode()) {
1362 switch (N->getOpcode()) {
1370 RV = PromoteIntBinOp(SDValue(N, 0));
1375 RV = PromoteIntShiftOp(SDValue(N, 0));
1377 case ISD::SIGN_EXTEND:
1378 case ISD::ZERO_EXTEND:
1379 case ISD::ANY_EXTEND:
1380 RV = PromoteExtend(SDValue(N, 0));
1383 if (PromoteLoad(SDValue(N, 0)))
1389 // If N is a commutative binary node, try commuting it to enable more
1391 if (!RV.getNode() && SelectionDAG::isCommutativeBinOp(N->getOpcode()) &&
1392 N->getNumValues() == 1) {
1393 SDValue N0 = N->getOperand(0);
1394 SDValue N1 = N->getOperand(1);
1396 // Constant operands are canonicalized to RHS.
1397 if (isa<ConstantSDNode>(N0) || !isa<ConstantSDNode>(N1)) {
1398 SDValue Ops[] = {N1, N0};
1400 if (const BinaryWithFlagsSDNode *BinNode =
1401 dyn_cast<BinaryWithFlagsSDNode>(N)) {
1402 CSENode = DAG.getNodeIfExists(
1403 N->getOpcode(), N->getVTList(), Ops, BinNode->hasNoUnsignedWrap(),
1404 BinNode->hasNoSignedWrap(), BinNode->isExact());
1406 CSENode = DAG.getNodeIfExists(N->getOpcode(), N->getVTList(), Ops);
1409 return SDValue(CSENode, 0);
1416 /// Given a node, return its input chain if it has one, otherwise return a null
1418 static SDValue getInputChainForNode(SDNode *N) {
1419 if (unsigned NumOps = N->getNumOperands()) {
1420 if (N->getOperand(0).getValueType() == MVT::Other)
1421 return N->getOperand(0);
1422 if (N->getOperand(NumOps-1).getValueType() == MVT::Other)
1423 return N->getOperand(NumOps-1);
1424 for (unsigned i = 1; i < NumOps-1; ++i)
1425 if (N->getOperand(i).getValueType() == MVT::Other)
1426 return N->getOperand(i);
1431 SDValue DAGCombiner::visitTokenFactor(SDNode *N) {
1432 // If N has two operands, where one has an input chain equal to the other,
1433 // the 'other' chain is redundant.
1434 if (N->getNumOperands() == 2) {
1435 if (getInputChainForNode(N->getOperand(0).getNode()) == N->getOperand(1))
1436 return N->getOperand(0);
1437 if (getInputChainForNode(N->getOperand(1).getNode()) == N->getOperand(0))
1438 return N->getOperand(1);
1441 SmallVector<SDNode *, 8> TFs; // List of token factors to visit.
1442 SmallVector<SDValue, 8> Ops; // Ops for replacing token factor.
1443 SmallPtrSet<SDNode*, 16> SeenOps;
1444 bool Changed = false; // If we should replace this token factor.
1446 // Start out with this token factor.
1449 // Iterate through token factors. The TFs grows when new token factors are
1451 for (unsigned i = 0; i < TFs.size(); ++i) {
1452 SDNode *TF = TFs[i];
1454 // Check each of the operands.
1455 for (unsigned i = 0, ie = TF->getNumOperands(); i != ie; ++i) {
1456 SDValue Op = TF->getOperand(i);
1458 switch (Op.getOpcode()) {
1459 case ISD::EntryToken:
1460 // Entry tokens don't need to be added to the list. They are
1465 case ISD::TokenFactor:
1466 if (Op.hasOneUse() &&
1467 std::find(TFs.begin(), TFs.end(), Op.getNode()) == TFs.end()) {
1468 // Queue up for processing.
1469 TFs.push_back(Op.getNode());
1470 // Clean up in case the token factor is removed.
1471 AddToWorklist(Op.getNode());
1478 // Only add if it isn't already in the list.
1479 if (SeenOps.insert(Op.getNode()))
1490 // If we've change things around then replace token factor.
1493 // The entry token is the only possible outcome.
1494 Result = DAG.getEntryNode();
1496 // New and improved token factor.
1497 Result = DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other, Ops);
1500 // Don't add users to work list.
1501 return CombineTo(N, Result, false);
1507 /// MERGE_VALUES can always be eliminated.
1508 SDValue DAGCombiner::visitMERGE_VALUES(SDNode *N) {
1509 WorklistRemover DeadNodes(*this);
1510 // Replacing results may cause a different MERGE_VALUES to suddenly
1511 // be CSE'd with N, and carry its uses with it. Iterate until no
1512 // uses remain, to ensure that the node can be safely deleted.
1513 // First add the users of this node to the work list so that they
1514 // can be tried again once they have new operands.
1515 AddUsersToWorklist(N);
1517 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1518 DAG.ReplaceAllUsesOfValueWith(SDValue(N, i), N->getOperand(i));
1519 } while (!N->use_empty());
1520 deleteAndRecombine(N);
1521 return SDValue(N, 0); // Return N so it doesn't get rechecked!
1525 SDValue combineShlAddConstant(SDLoc DL, SDValue N0, SDValue N1,
1526 SelectionDAG &DAG) {
1527 EVT VT = N0.getValueType();
1528 SDValue N00 = N0.getOperand(0);
1529 SDValue N01 = N0.getOperand(1);
1530 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N01);
1532 if (N01C && N00.getOpcode() == ISD::ADD && N00.getNode()->hasOneUse() &&
1533 isa<ConstantSDNode>(N00.getOperand(1))) {
1534 // fold (add (shl (add x, c1), c2), ) -> (add (add (shl x, c2), c1<<c2), )
1535 N0 = DAG.getNode(ISD::ADD, SDLoc(N0), VT,
1536 DAG.getNode(ISD::SHL, SDLoc(N00), VT,
1537 N00.getOperand(0), N01),
1538 DAG.getNode(ISD::SHL, SDLoc(N01), VT,
1539 N00.getOperand(1), N01));
1540 return DAG.getNode(ISD::ADD, DL, VT, N0, N1);
1546 SDValue DAGCombiner::visitADD(SDNode *N) {
1547 SDValue N0 = N->getOperand(0);
1548 SDValue N1 = N->getOperand(1);
1549 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1550 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1551 EVT VT = N0.getValueType();
1554 if (VT.isVector()) {
1555 SDValue FoldedVOp = SimplifyVBinOp(N);
1556 if (FoldedVOp.getNode()) return FoldedVOp;
1558 // fold (add x, 0) -> x, vector edition
1559 if (ISD::isBuildVectorAllZeros(N1.getNode()))
1561 if (ISD::isBuildVectorAllZeros(N0.getNode()))
1565 // fold (add x, undef) -> undef
1566 if (N0.getOpcode() == ISD::UNDEF)
1568 if (N1.getOpcode() == ISD::UNDEF)
1570 // fold (add c1, c2) -> c1+c2
1572 return DAG.FoldConstantArithmetic(ISD::ADD, VT, N0C, N1C);
1573 // canonicalize constant to RHS
1575 return DAG.getNode(ISD::ADD, SDLoc(N), VT, N1, N0);
1576 // fold (add x, 0) -> x
1577 if (N1C && N1C->isNullValue())
1579 // fold (add Sym, c) -> Sym+c
1580 if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N0))
1581 if (!LegalOperations && TLI.isOffsetFoldingLegal(GA) && N1C &&
1582 GA->getOpcode() == ISD::GlobalAddress)
1583 return DAG.getGlobalAddress(GA->getGlobal(), SDLoc(N1C), VT,
1585 (uint64_t)N1C->getSExtValue());
1586 // fold ((c1-A)+c2) -> (c1+c2)-A
1587 if (N1C && N0.getOpcode() == ISD::SUB)
1588 if (ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getOperand(0)))
1589 return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1590 DAG.getConstant(N1C->getAPIntValue()+
1591 N0C->getAPIntValue(), VT),
1594 SDValue RADD = ReassociateOps(ISD::ADD, SDLoc(N), N0, N1);
1597 // fold ((0-A) + B) -> B-A
1598 if (N0.getOpcode() == ISD::SUB && isa<ConstantSDNode>(N0.getOperand(0)) &&
1599 cast<ConstantSDNode>(N0.getOperand(0))->isNullValue())
1600 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1, N0.getOperand(1));
1601 // fold (A + (0-B)) -> A-B
1602 if (N1.getOpcode() == ISD::SUB && isa<ConstantSDNode>(N1.getOperand(0)) &&
1603 cast<ConstantSDNode>(N1.getOperand(0))->isNullValue())
1604 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, N1.getOperand(1));
1605 // fold (A+(B-A)) -> B
1606 if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(1))
1607 return N1.getOperand(0);
1608 // fold ((B-A)+A) -> B
1609 if (N0.getOpcode() == ISD::SUB && N1 == N0.getOperand(1))
1610 return N0.getOperand(0);
1611 // fold (A+(B-(A+C))) to (B-C)
1612 if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD &&
1613 N0 == N1.getOperand(1).getOperand(0))
1614 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1.getOperand(0),
1615 N1.getOperand(1).getOperand(1));
1616 // fold (A+(B-(C+A))) to (B-C)
1617 if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD &&
1618 N0 == N1.getOperand(1).getOperand(1))
1619 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1.getOperand(0),
1620 N1.getOperand(1).getOperand(0));
1621 // fold (A+((B-A)+or-C)) to (B+or-C)
1622 if ((N1.getOpcode() == ISD::SUB || N1.getOpcode() == ISD::ADD) &&
1623 N1.getOperand(0).getOpcode() == ISD::SUB &&
1624 N0 == N1.getOperand(0).getOperand(1))
1625 return DAG.getNode(N1.getOpcode(), SDLoc(N), VT,
1626 N1.getOperand(0).getOperand(0), N1.getOperand(1));
1628 // fold (A-B)+(C-D) to (A+C)-(B+D) when A or C is constant
1629 if (N0.getOpcode() == ISD::SUB && N1.getOpcode() == ISD::SUB) {
1630 SDValue N00 = N0.getOperand(0);
1631 SDValue N01 = N0.getOperand(1);
1632 SDValue N10 = N1.getOperand(0);
1633 SDValue N11 = N1.getOperand(1);
1635 if (isa<ConstantSDNode>(N00) || isa<ConstantSDNode>(N10))
1636 return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1637 DAG.getNode(ISD::ADD, SDLoc(N0), VT, N00, N10),
1638 DAG.getNode(ISD::ADD, SDLoc(N1), VT, N01, N11));
1641 if (!VT.isVector() && SimplifyDemandedBits(SDValue(N, 0)))
1642 return SDValue(N, 0);
1644 // fold (a+b) -> (a|b) iff a and b share no bits.
1645 if (VT.isInteger() && !VT.isVector()) {
1646 APInt LHSZero, LHSOne;
1647 APInt RHSZero, RHSOne;
1648 DAG.computeKnownBits(N0, LHSZero, LHSOne);
1650 if (LHSZero.getBoolValue()) {
1651 DAG.computeKnownBits(N1, RHSZero, RHSOne);
1653 // If all possibly-set bits on the LHS are clear on the RHS, return an OR.
1654 // If all possibly-set bits on the RHS are clear on the LHS, return an OR.
1655 if ((RHSZero & ~LHSZero) == ~LHSZero || (LHSZero & ~RHSZero) == ~RHSZero){
1656 if (!LegalOperations || TLI.isOperationLegal(ISD::OR, VT))
1657 return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N1);
1662 // fold (add (shl (add x, c1), c2), ) -> (add (add (shl x, c2), c1<<c2), )
1663 if (N0.getOpcode() == ISD::SHL && N0.getNode()->hasOneUse()) {
1664 SDValue Result = combineShlAddConstant(SDLoc(N), N0, N1, DAG);
1665 if (Result.getNode()) return Result;
1667 if (N1.getOpcode() == ISD::SHL && N1.getNode()->hasOneUse()) {
1668 SDValue Result = combineShlAddConstant(SDLoc(N), N1, N0, DAG);
1669 if (Result.getNode()) return Result;
1672 // fold (add x, shl(0 - y, n)) -> sub(x, shl(y, n))
1673 if (N1.getOpcode() == ISD::SHL &&
1674 N1.getOperand(0).getOpcode() == ISD::SUB)
1675 if (ConstantSDNode *C =
1676 dyn_cast<ConstantSDNode>(N1.getOperand(0).getOperand(0)))
1677 if (C->getAPIntValue() == 0)
1678 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N0,
1679 DAG.getNode(ISD::SHL, SDLoc(N), VT,
1680 N1.getOperand(0).getOperand(1),
1682 if (N0.getOpcode() == ISD::SHL &&
1683 N0.getOperand(0).getOpcode() == ISD::SUB)
1684 if (ConstantSDNode *C =
1685 dyn_cast<ConstantSDNode>(N0.getOperand(0).getOperand(0)))
1686 if (C->getAPIntValue() == 0)
1687 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1,
1688 DAG.getNode(ISD::SHL, SDLoc(N), VT,
1689 N0.getOperand(0).getOperand(1),
1692 if (N1.getOpcode() == ISD::AND) {
1693 SDValue AndOp0 = N1.getOperand(0);
1694 ConstantSDNode *AndOp1 = dyn_cast<ConstantSDNode>(N1->getOperand(1));
1695 unsigned NumSignBits = DAG.ComputeNumSignBits(AndOp0);
1696 unsigned DestBits = VT.getScalarType().getSizeInBits();
1698 // (add z, (and (sbbl x, x), 1)) -> (sub z, (sbbl x, x))
1699 // and similar xforms where the inner op is either ~0 or 0.
1700 if (NumSignBits == DestBits && AndOp1 && AndOp1->isOne()) {
1702 return DAG.getNode(ISD::SUB, DL, VT, N->getOperand(0), AndOp0);
1706 // add (sext i1), X -> sub X, (zext i1)
1707 if (N0.getOpcode() == ISD::SIGN_EXTEND &&
1708 N0.getOperand(0).getValueType() == MVT::i1 &&
1709 !TLI.isOperationLegal(ISD::SIGN_EXTEND, MVT::i1)) {
1711 SDValue ZExt = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0));
1712 return DAG.getNode(ISD::SUB, DL, VT, N1, ZExt);
1718 SDValue DAGCombiner::visitADDC(SDNode *N) {
1719 SDValue N0 = N->getOperand(0);
1720 SDValue N1 = N->getOperand(1);
1721 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1722 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1723 EVT VT = N0.getValueType();
1725 // If the flag result is dead, turn this into an ADD.
1726 if (!N->hasAnyUseOfValue(1))
1727 return CombineTo(N, DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, N1),
1728 DAG.getNode(ISD::CARRY_FALSE,
1729 SDLoc(N), MVT::Glue));
1731 // canonicalize constant to RHS.
1733 return DAG.getNode(ISD::ADDC, SDLoc(N), N->getVTList(), N1, N0);
1735 // fold (addc x, 0) -> x + no carry out
1736 if (N1C && N1C->isNullValue())
1737 return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE,
1738 SDLoc(N), MVT::Glue));
1740 // fold (addc a, b) -> (or a, b), CARRY_FALSE iff a and b share no bits.
1741 APInt LHSZero, LHSOne;
1742 APInt RHSZero, RHSOne;
1743 DAG.computeKnownBits(N0, LHSZero, LHSOne);
1745 if (LHSZero.getBoolValue()) {
1746 DAG.computeKnownBits(N1, RHSZero, RHSOne);
1748 // If all possibly-set bits on the LHS are clear on the RHS, return an OR.
1749 // If all possibly-set bits on the RHS are clear on the LHS, return an OR.
1750 if ((RHSZero & ~LHSZero) == ~LHSZero || (LHSZero & ~RHSZero) == ~RHSZero)
1751 return CombineTo(N, DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N1),
1752 DAG.getNode(ISD::CARRY_FALSE,
1753 SDLoc(N), MVT::Glue));
1759 SDValue DAGCombiner::visitADDE(SDNode *N) {
1760 SDValue N0 = N->getOperand(0);
1761 SDValue N1 = N->getOperand(1);
1762 SDValue CarryIn = N->getOperand(2);
1763 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1764 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1766 // canonicalize constant to RHS
1768 return DAG.getNode(ISD::ADDE, SDLoc(N), N->getVTList(),
1771 // fold (adde x, y, false) -> (addc x, y)
1772 if (CarryIn.getOpcode() == ISD::CARRY_FALSE)
1773 return DAG.getNode(ISD::ADDC, SDLoc(N), N->getVTList(), N0, N1);
1778 // Since it may not be valid to emit a fold to zero for vector initializers
1779 // check if we can before folding.
1780 static SDValue tryFoldToZero(SDLoc DL, const TargetLowering &TLI, EVT VT,
1782 bool LegalOperations, bool LegalTypes) {
1784 return DAG.getConstant(0, VT);
1785 if (!LegalOperations || TLI.isOperationLegal(ISD::BUILD_VECTOR, VT))
1786 return DAG.getConstant(0, VT);
1790 SDValue DAGCombiner::visitSUB(SDNode *N) {
1791 SDValue N0 = N->getOperand(0);
1792 SDValue N1 = N->getOperand(1);
1793 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getNode());
1794 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
1795 ConstantSDNode *N1C1 = N1.getOpcode() != ISD::ADD ? nullptr :
1796 dyn_cast<ConstantSDNode>(N1.getOperand(1).getNode());
1797 EVT VT = N0.getValueType();
1800 if (VT.isVector()) {
1801 SDValue FoldedVOp = SimplifyVBinOp(N);
1802 if (FoldedVOp.getNode()) return FoldedVOp;
1804 // fold (sub x, 0) -> x, vector edition
1805 if (ISD::isBuildVectorAllZeros(N1.getNode()))
1809 // fold (sub x, x) -> 0
1810 // FIXME: Refactor this and xor and other similar operations together.
1812 return tryFoldToZero(SDLoc(N), TLI, VT, DAG, LegalOperations, LegalTypes);
1813 // fold (sub c1, c2) -> c1-c2
1815 return DAG.FoldConstantArithmetic(ISD::SUB, VT, N0C, N1C);
1816 // fold (sub x, c) -> (add x, -c)
1818 return DAG.getNode(ISD::ADD, SDLoc(N), VT, N0,
1819 DAG.getConstant(-N1C->getAPIntValue(), VT));
1820 // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1)
1821 if (N0C && N0C->isAllOnesValue())
1822 return DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0);
1823 // fold A-(A-B) -> B
1824 if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(0))
1825 return N1.getOperand(1);
1826 // fold (A+B)-A -> B
1827 if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1)
1828 return N0.getOperand(1);
1829 // fold (A+B)-B -> A
1830 if (N0.getOpcode() == ISD::ADD && N0.getOperand(1) == N1)
1831 return N0.getOperand(0);
1832 // fold C2-(A+C1) -> (C2-C1)-A
1833 if (N1.getOpcode() == ISD::ADD && N0C && N1C1) {
1834 SDValue NewC = DAG.getConstant(N0C->getAPIntValue() - N1C1->getAPIntValue(),
1836 return DAG.getNode(ISD::SUB, SDLoc(N), VT, NewC,
1839 // fold ((A+(B+or-C))-B) -> A+or-C
1840 if (N0.getOpcode() == ISD::ADD &&
1841 (N0.getOperand(1).getOpcode() == ISD::SUB ||
1842 N0.getOperand(1).getOpcode() == ISD::ADD) &&
1843 N0.getOperand(1).getOperand(0) == N1)
1844 return DAG.getNode(N0.getOperand(1).getOpcode(), SDLoc(N), VT,
1845 N0.getOperand(0), N0.getOperand(1).getOperand(1));
1846 // fold ((A+(C+B))-B) -> A+C
1847 if (N0.getOpcode() == ISD::ADD &&
1848 N0.getOperand(1).getOpcode() == ISD::ADD &&
1849 N0.getOperand(1).getOperand(1) == N1)
1850 return DAG.getNode(ISD::ADD, SDLoc(N), VT,
1851 N0.getOperand(0), N0.getOperand(1).getOperand(0));
1852 // fold ((A-(B-C))-C) -> A-B
1853 if (N0.getOpcode() == ISD::SUB &&
1854 N0.getOperand(1).getOpcode() == ISD::SUB &&
1855 N0.getOperand(1).getOperand(1) == N1)
1856 return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1857 N0.getOperand(0), N0.getOperand(1).getOperand(0));
1859 // If either operand of a sub is undef, the result is undef
1860 if (N0.getOpcode() == ISD::UNDEF)
1862 if (N1.getOpcode() == ISD::UNDEF)
1865 // If the relocation model supports it, consider symbol offsets.
1866 if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N0))
1867 if (!LegalOperations && TLI.isOffsetFoldingLegal(GA)) {
1868 // fold (sub Sym, c) -> Sym-c
1869 if (N1C && GA->getOpcode() == ISD::GlobalAddress)
1870 return DAG.getGlobalAddress(GA->getGlobal(), SDLoc(N1C), VT,
1872 (uint64_t)N1C->getSExtValue());
1873 // fold (sub Sym+c1, Sym+c2) -> c1-c2
1874 if (GlobalAddressSDNode *GB = dyn_cast<GlobalAddressSDNode>(N1))
1875 if (GA->getGlobal() == GB->getGlobal())
1876 return DAG.getConstant((uint64_t)GA->getOffset() - GB->getOffset(),
1883 SDValue DAGCombiner::visitSUBC(SDNode *N) {
1884 SDValue N0 = N->getOperand(0);
1885 SDValue N1 = N->getOperand(1);
1886 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1887 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1888 EVT VT = N0.getValueType();
1890 // If the flag result is dead, turn this into an SUB.
1891 if (!N->hasAnyUseOfValue(1))
1892 return CombineTo(N, DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, N1),
1893 DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
1896 // fold (subc x, x) -> 0 + no borrow
1898 return CombineTo(N, DAG.getConstant(0, VT),
1899 DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
1902 // fold (subc x, 0) -> x + no borrow
1903 if (N1C && N1C->isNullValue())
1904 return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
1907 // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1) + no borrow
1908 if (N0C && N0C->isAllOnesValue())
1909 return CombineTo(N, DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0),
1910 DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
1916 SDValue DAGCombiner::visitSUBE(SDNode *N) {
1917 SDValue N0 = N->getOperand(0);
1918 SDValue N1 = N->getOperand(1);
1919 SDValue CarryIn = N->getOperand(2);
1921 // fold (sube x, y, false) -> (subc x, y)
1922 if (CarryIn.getOpcode() == ISD::CARRY_FALSE)
1923 return DAG.getNode(ISD::SUBC, SDLoc(N), N->getVTList(), N0, N1);
1928 SDValue DAGCombiner::visitMUL(SDNode *N) {
1929 SDValue N0 = N->getOperand(0);
1930 SDValue N1 = N->getOperand(1);
1931 EVT VT = N0.getValueType();
1933 // fold (mul x, undef) -> 0
1934 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
1935 return DAG.getConstant(0, VT);
1937 bool N0IsConst = false;
1938 bool N1IsConst = false;
1939 APInt ConstValue0, ConstValue1;
1941 if (VT.isVector()) {
1942 SDValue FoldedVOp = SimplifyVBinOp(N);
1943 if (FoldedVOp.getNode()) return FoldedVOp;
1945 N0IsConst = isConstantSplatVector(N0.getNode(), ConstValue0);
1946 N1IsConst = isConstantSplatVector(N1.getNode(), ConstValue1);
1948 N0IsConst = dyn_cast<ConstantSDNode>(N0) != nullptr;
1949 ConstValue0 = N0IsConst ? (dyn_cast<ConstantSDNode>(N0))->getAPIntValue()
1951 N1IsConst = dyn_cast<ConstantSDNode>(N1) != nullptr;
1952 ConstValue1 = N1IsConst ? (dyn_cast<ConstantSDNode>(N1))->getAPIntValue()
1956 // fold (mul c1, c2) -> c1*c2
1957 if (N0IsConst && N1IsConst)
1958 return DAG.FoldConstantArithmetic(ISD::MUL, VT, N0.getNode(), N1.getNode());
1960 // canonicalize constant to RHS
1961 if (N0IsConst && !N1IsConst)
1962 return DAG.getNode(ISD::MUL, SDLoc(N), VT, N1, N0);
1963 // fold (mul x, 0) -> 0
1964 if (N1IsConst && ConstValue1 == 0)
1966 // We require a splat of the entire scalar bit width for non-contiguous
1969 ConstValue1.getBitWidth() == VT.getScalarType().getSizeInBits();
1970 // fold (mul x, 1) -> x
1971 if (N1IsConst && ConstValue1 == 1 && IsFullSplat)
1973 // fold (mul x, -1) -> 0-x
1974 if (N1IsConst && ConstValue1.isAllOnesValue())
1975 return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1976 DAG.getConstant(0, VT), N0);
1977 // fold (mul x, (1 << c)) -> x << c
1978 if (N1IsConst && ConstValue1.isPowerOf2() && IsFullSplat)
1979 return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0,
1980 DAG.getConstant(ConstValue1.logBase2(),
1981 getShiftAmountTy(N0.getValueType())));
1982 // fold (mul x, -(1 << c)) -> -(x << c) or (-x) << c
1983 if (N1IsConst && (-ConstValue1).isPowerOf2() && IsFullSplat) {
1984 unsigned Log2Val = (-ConstValue1).logBase2();
1985 // FIXME: If the input is something that is easily negated (e.g. a
1986 // single-use add), we should put the negate there.
1987 return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1988 DAG.getConstant(0, VT),
1989 DAG.getNode(ISD::SHL, SDLoc(N), VT, N0,
1990 DAG.getConstant(Log2Val,
1991 getShiftAmountTy(N0.getValueType()))));
1995 // (mul (shl X, c1), c2) -> (mul X, c2 << c1)
1996 if (N1IsConst && N0.getOpcode() == ISD::SHL &&
1997 (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
1998 isa<ConstantSDNode>(N0.getOperand(1)))) {
1999 SDValue C3 = DAG.getNode(ISD::SHL, SDLoc(N), VT,
2000 N1, N0.getOperand(1));
2001 AddToWorklist(C3.getNode());
2002 return DAG.getNode(ISD::MUL, SDLoc(N), VT,
2003 N0.getOperand(0), C3);
2006 // Change (mul (shl X, C), Y) -> (shl (mul X, Y), C) when the shift has one
2009 SDValue Sh(nullptr,0), Y(nullptr,0);
2010 // Check for both (mul (shl X, C), Y) and (mul Y, (shl X, C)).
2011 if (N0.getOpcode() == ISD::SHL &&
2012 (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
2013 isa<ConstantSDNode>(N0.getOperand(1))) &&
2014 N0.getNode()->hasOneUse()) {
2016 } else if (N1.getOpcode() == ISD::SHL &&
2017 isa<ConstantSDNode>(N1.getOperand(1)) &&
2018 N1.getNode()->hasOneUse()) {
2023 SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT,
2024 Sh.getOperand(0), Y);
2025 return DAG.getNode(ISD::SHL, SDLoc(N), VT,
2026 Mul, Sh.getOperand(1));
2030 // fold (mul (add x, c1), c2) -> (add (mul x, c2), c1*c2)
2031 if (N1IsConst && N0.getOpcode() == ISD::ADD && N0.getNode()->hasOneUse() &&
2032 (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
2033 isa<ConstantSDNode>(N0.getOperand(1))))
2034 return DAG.getNode(ISD::ADD, SDLoc(N), VT,
2035 DAG.getNode(ISD::MUL, SDLoc(N0), VT,
2036 N0.getOperand(0), N1),
2037 DAG.getNode(ISD::MUL, SDLoc(N1), VT,
2038 N0.getOperand(1), N1));
2041 SDValue RMUL = ReassociateOps(ISD::MUL, SDLoc(N), N0, N1);
2048 SDValue DAGCombiner::visitSDIV(SDNode *N) {
2049 SDValue N0 = N->getOperand(0);
2050 SDValue N1 = N->getOperand(1);
2051 ConstantSDNode *N0C = isConstOrConstSplat(N0);
2052 ConstantSDNode *N1C = isConstOrConstSplat(N1);
2053 EVT VT = N->getValueType(0);
2056 if (VT.isVector()) {
2057 SDValue FoldedVOp = SimplifyVBinOp(N);
2058 if (FoldedVOp.getNode()) return FoldedVOp;
2061 // fold (sdiv c1, c2) -> c1/c2
2062 if (N0C && N1C && !N1C->isNullValue())
2063 return DAG.FoldConstantArithmetic(ISD::SDIV, VT, N0C, N1C);
2064 // fold (sdiv X, 1) -> X
2065 if (N1C && N1C->getAPIntValue() == 1LL)
2067 // fold (sdiv X, -1) -> 0-X
2068 if (N1C && N1C->isAllOnesValue())
2069 return DAG.getNode(ISD::SUB, SDLoc(N), VT,
2070 DAG.getConstant(0, VT), N0);
2071 // If we know the sign bits of both operands are zero, strength reduce to a
2072 // udiv instead. Handles (X&15) /s 4 -> X&15 >> 2
2073 if (!VT.isVector()) {
2074 if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
2075 return DAG.getNode(ISD::UDIV, SDLoc(N), N1.getValueType(),
2079 // fold (sdiv X, pow2) -> simple ops after legalize
2080 if (N1C && !N1C->isNullValue() && (N1C->getAPIntValue().isPowerOf2() ||
2081 (-N1C->getAPIntValue()).isPowerOf2())) {
2082 // If dividing by powers of two is cheap, then don't perform the following
2084 if (TLI.isPow2SDivCheap())
2087 // Target-specific implementation of sdiv x, pow2.
2088 SDValue Res = BuildSDIVPow2(N);
2092 unsigned lg2 = N1C->getAPIntValue().countTrailingZeros();
2094 // Splat the sign bit into the register
2096 DAG.getNode(ISD::SRA, SDLoc(N), VT, N0,
2097 DAG.getConstant(VT.getScalarSizeInBits() - 1,
2098 getShiftAmountTy(N0.getValueType())));
2099 AddToWorklist(SGN.getNode());
2101 // Add (N0 < 0) ? abs2 - 1 : 0;
2103 DAG.getNode(ISD::SRL, SDLoc(N), VT, SGN,
2104 DAG.getConstant(VT.getScalarSizeInBits() - lg2,
2105 getShiftAmountTy(SGN.getValueType())));
2106 SDValue ADD = DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, SRL);
2107 AddToWorklist(SRL.getNode());
2108 AddToWorklist(ADD.getNode()); // Divide by pow2
2109 SDValue SRA = DAG.getNode(ISD::SRA, SDLoc(N), VT, ADD,
2110 DAG.getConstant(lg2, getShiftAmountTy(ADD.getValueType())));
2112 // If we're dividing by a positive value, we're done. Otherwise, we must
2113 // negate the result.
2114 if (N1C->getAPIntValue().isNonNegative())
2117 AddToWorklist(SRA.getNode());
2118 return DAG.getNode(ISD::SUB, SDLoc(N), VT, DAG.getConstant(0, VT), SRA);
2121 // if integer divide is expensive and we satisfy the requirements, emit an
2122 // alternate sequence.
2123 if (N1C && !TLI.isIntDivCheap()) {
2124 SDValue Op = BuildSDIV(N);
2125 if (Op.getNode()) return Op;
2129 if (N0.getOpcode() == ISD::UNDEF)
2130 return DAG.getConstant(0, VT);
2131 // X / undef -> undef
2132 if (N1.getOpcode() == ISD::UNDEF)
2138 SDValue DAGCombiner::visitUDIV(SDNode *N) {
2139 SDValue N0 = N->getOperand(0);
2140 SDValue N1 = N->getOperand(1);
2141 ConstantSDNode *N0C = isConstOrConstSplat(N0);
2142 ConstantSDNode *N1C = isConstOrConstSplat(N1);
2143 EVT VT = N->getValueType(0);
2146 if (VT.isVector()) {
2147 SDValue FoldedVOp = SimplifyVBinOp(N);
2148 if (FoldedVOp.getNode()) return FoldedVOp;
2151 // fold (udiv c1, c2) -> c1/c2
2152 if (N0C && N1C && !N1C->isNullValue())
2153 return DAG.FoldConstantArithmetic(ISD::UDIV, VT, N0C, N1C);
2154 // fold (udiv x, (1 << c)) -> x >>u c
2155 if (N1C && N1C->getAPIntValue().isPowerOf2())
2156 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0,
2157 DAG.getConstant(N1C->getAPIntValue().logBase2(),
2158 getShiftAmountTy(N0.getValueType())));
2159 // fold (udiv x, (shl c, y)) -> x >>u (log2(c)+y) iff c is power of 2
2160 if (N1.getOpcode() == ISD::SHL) {
2161 if (ConstantSDNode *SHC = dyn_cast<ConstantSDNode>(N1.getOperand(0))) {
2162 if (SHC->getAPIntValue().isPowerOf2()) {
2163 EVT ADDVT = N1.getOperand(1).getValueType();
2164 SDValue Add = DAG.getNode(ISD::ADD, SDLoc(N), ADDVT,
2166 DAG.getConstant(SHC->getAPIntValue()
2169 AddToWorklist(Add.getNode());
2170 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, Add);
2174 // fold (udiv x, c) -> alternate
2175 if (N1C && !TLI.isIntDivCheap()) {
2176 SDValue Op = BuildUDIV(N);
2177 if (Op.getNode()) return Op;
2181 if (N0.getOpcode() == ISD::UNDEF)
2182 return DAG.getConstant(0, VT);
2183 // X / undef -> undef
2184 if (N1.getOpcode() == ISD::UNDEF)
2190 SDValue DAGCombiner::visitSREM(SDNode *N) {
2191 SDValue N0 = N->getOperand(0);
2192 SDValue N1 = N->getOperand(1);
2193 ConstantSDNode *N0C = isConstOrConstSplat(N0);
2194 ConstantSDNode *N1C = isConstOrConstSplat(N1);
2195 EVT VT = N->getValueType(0);
2197 // fold (srem c1, c2) -> c1%c2
2198 if (N0C && N1C && !N1C->isNullValue())
2199 return DAG.FoldConstantArithmetic(ISD::SREM, VT, N0C, N1C);
2200 // If we know the sign bits of both operands are zero, strength reduce to a
2201 // urem instead. Handles (X & 0x0FFFFFFF) %s 16 -> X&15
2202 if (!VT.isVector()) {
2203 if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
2204 return DAG.getNode(ISD::UREM, SDLoc(N), VT, N0, N1);
2207 // If X/C can be simplified by the division-by-constant logic, lower
2208 // X%C to the equivalent of X-X/C*C.
2209 if (N1C && !N1C->isNullValue()) {
2210 SDValue Div = DAG.getNode(ISD::SDIV, SDLoc(N), VT, N0, N1);
2211 AddToWorklist(Div.getNode());
2212 SDValue OptimizedDiv = combine(Div.getNode());
2213 if (OptimizedDiv.getNode() && OptimizedDiv.getNode() != Div.getNode()) {
2214 SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT,
2216 SDValue Sub = DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, Mul);
2217 AddToWorklist(Mul.getNode());
2223 if (N0.getOpcode() == ISD::UNDEF)
2224 return DAG.getConstant(0, VT);
2225 // X % undef -> undef
2226 if (N1.getOpcode() == ISD::UNDEF)
2232 SDValue DAGCombiner::visitUREM(SDNode *N) {
2233 SDValue N0 = N->getOperand(0);
2234 SDValue N1 = N->getOperand(1);
2235 ConstantSDNode *N0C = isConstOrConstSplat(N0);
2236 ConstantSDNode *N1C = isConstOrConstSplat(N1);
2237 EVT VT = N->getValueType(0);
2239 // fold (urem c1, c2) -> c1%c2
2240 if (N0C && N1C && !N1C->isNullValue())
2241 return DAG.FoldConstantArithmetic(ISD::UREM, VT, N0C, N1C);
2242 // fold (urem x, pow2) -> (and x, pow2-1)
2243 if (N1C && !N1C->isNullValue() && N1C->getAPIntValue().isPowerOf2())
2244 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0,
2245 DAG.getConstant(N1C->getAPIntValue()-1,VT));
2246 // fold (urem x, (shl pow2, y)) -> (and x, (add (shl pow2, y), -1))
2247 if (N1.getOpcode() == ISD::SHL) {
2248 if (ConstantSDNode *SHC = dyn_cast<ConstantSDNode>(N1.getOperand(0))) {
2249 if (SHC->getAPIntValue().isPowerOf2()) {
2251 DAG.getNode(ISD::ADD, SDLoc(N), VT, N1,
2252 DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()),
2254 AddToWorklist(Add.getNode());
2255 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, Add);
2260 // If X/C can be simplified by the division-by-constant logic, lower
2261 // X%C to the equivalent of X-X/C*C.
2262 if (N1C && !N1C->isNullValue()) {
2263 SDValue Div = DAG.getNode(ISD::UDIV, SDLoc(N), VT, N0, N1);
2264 AddToWorklist(Div.getNode());
2265 SDValue OptimizedDiv = combine(Div.getNode());
2266 if (OptimizedDiv.getNode() && OptimizedDiv.getNode() != Div.getNode()) {
2267 SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT,
2269 SDValue Sub = DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, Mul);
2270 AddToWorklist(Mul.getNode());
2276 if (N0.getOpcode() == ISD::UNDEF)
2277 return DAG.getConstant(0, VT);
2278 // X % undef -> undef
2279 if (N1.getOpcode() == ISD::UNDEF)
2285 SDValue DAGCombiner::visitMULHS(SDNode *N) {
2286 SDValue N0 = N->getOperand(0);
2287 SDValue N1 = N->getOperand(1);
2288 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2289 EVT VT = N->getValueType(0);
2292 // fold (mulhs x, 0) -> 0
2293 if (N1C && N1C->isNullValue())
2295 // fold (mulhs x, 1) -> (sra x, size(x)-1)
2296 if (N1C && N1C->getAPIntValue() == 1)
2297 return DAG.getNode(ISD::SRA, SDLoc(N), N0.getValueType(), N0,
2298 DAG.getConstant(N0.getValueType().getSizeInBits() - 1,
2299 getShiftAmountTy(N0.getValueType())));
2300 // fold (mulhs x, undef) -> 0
2301 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2302 return DAG.getConstant(0, VT);
2304 // If the type twice as wide is legal, transform the mulhs to a wider multiply
2306 if (VT.isSimple() && !VT.isVector()) {
2307 MVT Simple = VT.getSimpleVT();
2308 unsigned SimpleSize = Simple.getSizeInBits();
2309 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2310 if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2311 N0 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N0);
2312 N1 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N1);
2313 N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1);
2314 N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1,
2315 DAG.getConstant(SimpleSize, getShiftAmountTy(N1.getValueType())));
2316 return DAG.getNode(ISD::TRUNCATE, DL, VT, N1);
2323 SDValue DAGCombiner::visitMULHU(SDNode *N) {
2324 SDValue N0 = N->getOperand(0);
2325 SDValue N1 = N->getOperand(1);
2326 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2327 EVT VT = N->getValueType(0);
2330 // fold (mulhu x, 0) -> 0
2331 if (N1C && N1C->isNullValue())
2333 // fold (mulhu x, 1) -> 0
2334 if (N1C && N1C->getAPIntValue() == 1)
2335 return DAG.getConstant(0, N0.getValueType());
2336 // fold (mulhu x, undef) -> 0
2337 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2338 return DAG.getConstant(0, VT);
2340 // If the type twice as wide is legal, transform the mulhu to a wider multiply
2342 if (VT.isSimple() && !VT.isVector()) {
2343 MVT Simple = VT.getSimpleVT();
2344 unsigned SimpleSize = Simple.getSizeInBits();
2345 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2346 if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2347 N0 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N0);
2348 N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N1);
2349 N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1);
2350 N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1,
2351 DAG.getConstant(SimpleSize, getShiftAmountTy(N1.getValueType())));
2352 return DAG.getNode(ISD::TRUNCATE, DL, VT, N1);
2359 /// Perform optimizations common to nodes that compute two values. LoOp and HiOp
2360 /// give the opcodes for the two computations that are being performed. Return
2361 /// true if a simplification was made.
2362 SDValue DAGCombiner::SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp,
2364 // If the high half is not needed, just compute the low half.
2365 bool HiExists = N->hasAnyUseOfValue(1);
2367 (!LegalOperations ||
2368 TLI.isOperationLegalOrCustom(LoOp, N->getValueType(0)))) {
2369 SDValue Res = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0), N->ops());
2370 return CombineTo(N, Res, Res);
2373 // If the low half is not needed, just compute the high half.
2374 bool LoExists = N->hasAnyUseOfValue(0);
2376 (!LegalOperations ||
2377 TLI.isOperationLegal(HiOp, N->getValueType(1)))) {
2378 SDValue Res = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1), N->ops());
2379 return CombineTo(N, Res, Res);
2382 // If both halves are used, return as it is.
2383 if (LoExists && HiExists)
2386 // If the two computed results can be simplified separately, separate them.
2388 SDValue Lo = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0), N->ops());
2389 AddToWorklist(Lo.getNode());
2390 SDValue LoOpt = combine(Lo.getNode());
2391 if (LoOpt.getNode() && LoOpt.getNode() != Lo.getNode() &&
2392 (!LegalOperations ||
2393 TLI.isOperationLegal(LoOpt.getOpcode(), LoOpt.getValueType())))
2394 return CombineTo(N, LoOpt, LoOpt);
2398 SDValue Hi = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1), N->ops());
2399 AddToWorklist(Hi.getNode());
2400 SDValue HiOpt = combine(Hi.getNode());
2401 if (HiOpt.getNode() && HiOpt != Hi &&
2402 (!LegalOperations ||
2403 TLI.isOperationLegal(HiOpt.getOpcode(), HiOpt.getValueType())))
2404 return CombineTo(N, HiOpt, HiOpt);
2410 SDValue DAGCombiner::visitSMUL_LOHI(SDNode *N) {
2411 SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHS);
2412 if (Res.getNode()) return Res;
2414 EVT VT = N->getValueType(0);
2417 // If the type twice as wide is legal, transform the mulhu to a wider multiply
2419 if (VT.isSimple() && !VT.isVector()) {
2420 MVT Simple = VT.getSimpleVT();
2421 unsigned SimpleSize = Simple.getSizeInBits();
2422 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2423 if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2424 SDValue Lo = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(0));
2425 SDValue Hi = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(1));
2426 Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi);
2427 // Compute the high part as N1.
2428 Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo,
2429 DAG.getConstant(SimpleSize, getShiftAmountTy(Lo.getValueType())));
2430 Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi);
2431 // Compute the low part as N0.
2432 Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo);
2433 return CombineTo(N, Lo, Hi);
2440 SDValue DAGCombiner::visitUMUL_LOHI(SDNode *N) {
2441 SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHU);
2442 if (Res.getNode()) return Res;
2444 EVT VT = N->getValueType(0);
2447 // If the type twice as wide is legal, transform the mulhu to a wider multiply
2449 if (VT.isSimple() && !VT.isVector()) {
2450 MVT Simple = VT.getSimpleVT();
2451 unsigned SimpleSize = Simple.getSizeInBits();
2452 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2453 if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2454 SDValue Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(0));
2455 SDValue Hi = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(1));
2456 Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi);
2457 // Compute the high part as N1.
2458 Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo,
2459 DAG.getConstant(SimpleSize, getShiftAmountTy(Lo.getValueType())));
2460 Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi);
2461 // Compute the low part as N0.
2462 Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo);
2463 return CombineTo(N, Lo, Hi);
2470 SDValue DAGCombiner::visitSMULO(SDNode *N) {
2471 // (smulo x, 2) -> (saddo x, x)
2472 if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1)))
2473 if (C2->getAPIntValue() == 2)
2474 return DAG.getNode(ISD::SADDO, SDLoc(N), N->getVTList(),
2475 N->getOperand(0), N->getOperand(0));
2480 SDValue DAGCombiner::visitUMULO(SDNode *N) {
2481 // (umulo x, 2) -> (uaddo x, x)
2482 if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1)))
2483 if (C2->getAPIntValue() == 2)
2484 return DAG.getNode(ISD::UADDO, SDLoc(N), N->getVTList(),
2485 N->getOperand(0), N->getOperand(0));
2490 SDValue DAGCombiner::visitSDIVREM(SDNode *N) {
2491 SDValue Res = SimplifyNodeWithTwoResults(N, ISD::SDIV, ISD::SREM);
2492 if (Res.getNode()) return Res;
2497 SDValue DAGCombiner::visitUDIVREM(SDNode *N) {
2498 SDValue Res = SimplifyNodeWithTwoResults(N, ISD::UDIV, ISD::UREM);
2499 if (Res.getNode()) return Res;
2504 /// If this is a binary operator with two operands of the same opcode, try to
2506 SDValue DAGCombiner::SimplifyBinOpWithSameOpcodeHands(SDNode *N) {
2507 SDValue N0 = N->getOperand(0), N1 = N->getOperand(1);
2508 EVT VT = N0.getValueType();
2509 assert(N0.getOpcode() == N1.getOpcode() && "Bad input!");
2511 // Bail early if none of these transforms apply.
2512 if (N0.getNode()->getNumOperands() == 0) return SDValue();
2514 // For each of OP in AND/OR/XOR:
2515 // fold (OP (zext x), (zext y)) -> (zext (OP x, y))
2516 // fold (OP (sext x), (sext y)) -> (sext (OP x, y))
2517 // fold (OP (aext x), (aext y)) -> (aext (OP x, y))
2518 // fold (OP (trunc x), (trunc y)) -> (trunc (OP x, y)) (if trunc isn't free)
2520 // do not sink logical op inside of a vector extend, since it may combine
2522 EVT Op0VT = N0.getOperand(0).getValueType();
2523 if ((N0.getOpcode() == ISD::ZERO_EXTEND ||
2524 N0.getOpcode() == ISD::SIGN_EXTEND ||
2525 // Avoid infinite looping with PromoteIntBinOp.
2526 (N0.getOpcode() == ISD::ANY_EXTEND &&
2527 (!LegalTypes || TLI.isTypeDesirableForOp(N->getOpcode(), Op0VT))) ||
2528 (N0.getOpcode() == ISD::TRUNCATE &&
2529 (!TLI.isZExtFree(VT, Op0VT) ||
2530 !TLI.isTruncateFree(Op0VT, VT)) &&
2531 TLI.isTypeLegal(Op0VT))) &&
2533 Op0VT == N1.getOperand(0).getValueType() &&
2534 (!LegalOperations || TLI.isOperationLegal(N->getOpcode(), Op0VT))) {
2535 SDValue ORNode = DAG.getNode(N->getOpcode(), SDLoc(N0),
2536 N0.getOperand(0).getValueType(),
2537 N0.getOperand(0), N1.getOperand(0));
2538 AddToWorklist(ORNode.getNode());
2539 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, ORNode);
2542 // For each of OP in SHL/SRL/SRA/AND...
2543 // fold (and (OP x, z), (OP y, z)) -> (OP (and x, y), z)
2544 // fold (or (OP x, z), (OP y, z)) -> (OP (or x, y), z)
2545 // fold (xor (OP x, z), (OP y, z)) -> (OP (xor x, y), z)
2546 if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL ||
2547 N0.getOpcode() == ISD::SRA || N0.getOpcode() == ISD::AND) &&
2548 N0.getOperand(1) == N1.getOperand(1)) {
2549 SDValue ORNode = DAG.getNode(N->getOpcode(), SDLoc(N0),
2550 N0.getOperand(0).getValueType(),
2551 N0.getOperand(0), N1.getOperand(0));
2552 AddToWorklist(ORNode.getNode());
2553 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
2554 ORNode, N0.getOperand(1));
2557 // Simplify xor/and/or (bitcast(A), bitcast(B)) -> bitcast(op (A,B))
2558 // Only perform this optimization after type legalization and before
2559 // LegalizeVectorOprs. LegalizeVectorOprs promotes vector operations by
2560 // adding bitcasts. For example (xor v4i32) is promoted to (v2i64), and
2561 // we don't want to undo this promotion.
2562 // We also handle SCALAR_TO_VECTOR because xor/or/and operations are cheaper
2564 if ((N0.getOpcode() == ISD::BITCAST ||
2565 N0.getOpcode() == ISD::SCALAR_TO_VECTOR) &&
2566 Level == AfterLegalizeTypes) {
2567 SDValue In0 = N0.getOperand(0);
2568 SDValue In1 = N1.getOperand(0);
2569 EVT In0Ty = In0.getValueType();
2570 EVT In1Ty = In1.getValueType();
2572 // If both incoming values are integers, and the original types are the
2574 if (In0Ty.isInteger() && In1Ty.isInteger() && In0Ty == In1Ty) {
2575 SDValue Op = DAG.getNode(N->getOpcode(), DL, In0Ty, In0, In1);
2576 SDValue BC = DAG.getNode(N0.getOpcode(), DL, VT, Op);
2577 AddToWorklist(Op.getNode());
2582 // Xor/and/or are indifferent to the swizzle operation (shuffle of one value).
2583 // Simplify xor/and/or (shuff(A), shuff(B)) -> shuff(op (A,B))
2584 // If both shuffles use the same mask, and both shuffle within a single
2585 // vector, then it is worthwhile to move the swizzle after the operation.
2586 // The type-legalizer generates this pattern when loading illegal
2587 // vector types from memory. In many cases this allows additional shuffle
2589 // There are other cases where moving the shuffle after the xor/and/or
2590 // is profitable even if shuffles don't perform a swizzle.
2591 // If both shuffles use the same mask, and both shuffles have the same first
2592 // or second operand, then it might still be profitable to move the shuffle
2593 // after the xor/and/or operation.
2594 if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG) {
2595 ShuffleVectorSDNode *SVN0 = cast<ShuffleVectorSDNode>(N0);
2596 ShuffleVectorSDNode *SVN1 = cast<ShuffleVectorSDNode>(N1);
2598 assert(N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType() &&
2599 "Inputs to shuffles are not the same type");
2601 // Check that both shuffles use the same mask. The masks are known to be of
2602 // the same length because the result vector type is the same.
2603 // Check also that shuffles have only one use to avoid introducing extra
2605 if (SVN0->hasOneUse() && SVN1->hasOneUse() &&
2606 SVN0->getMask().equals(SVN1->getMask())) {
2607 SDValue ShOp = N0->getOperand(1);
2609 // Don't try to fold this node if it requires introducing a
2610 // build vector of all zeros that might be illegal at this stage.
2611 if (N->getOpcode() == ISD::XOR && ShOp.getOpcode() != ISD::UNDEF) {
2613 ShOp = DAG.getConstant(0, VT);
2618 // (AND (shuf (A, C), shuf (B, C)) -> shuf (AND (A, B), C)
2619 // (OR (shuf (A, C), shuf (B, C)) -> shuf (OR (A, B), C)
2620 // (XOR (shuf (A, C), shuf (B, C)) -> shuf (XOR (A, B), V_0)
2621 if (N0.getOperand(1) == N1.getOperand(1) && ShOp.getNode()) {
2622 SDValue NewNode = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
2623 N0->getOperand(0), N1->getOperand(0));
2624 AddToWorklist(NewNode.getNode());
2625 return DAG.getVectorShuffle(VT, SDLoc(N), NewNode, ShOp,
2626 &SVN0->getMask()[0]);
2629 // Don't try to fold this node if it requires introducing a
2630 // build vector of all zeros that might be illegal at this stage.
2631 ShOp = N0->getOperand(0);
2632 if (N->getOpcode() == ISD::XOR && ShOp.getOpcode() != ISD::UNDEF) {
2634 ShOp = DAG.getConstant(0, VT);
2639 // (AND (shuf (C, A), shuf (C, B)) -> shuf (C, AND (A, B))
2640 // (OR (shuf (C, A), shuf (C, B)) -> shuf (C, OR (A, B))
2641 // (XOR (shuf (C, A), shuf (C, B)) -> shuf (V_0, XOR (A, B))
2642 if (N0->getOperand(0) == N1->getOperand(0) && ShOp.getNode()) {
2643 SDValue NewNode = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
2644 N0->getOperand(1), N1->getOperand(1));
2645 AddToWorklist(NewNode.getNode());
2646 return DAG.getVectorShuffle(VT, SDLoc(N), ShOp, NewNode,
2647 &SVN0->getMask()[0]);
2655 SDValue DAGCombiner::visitAND(SDNode *N) {
2656 SDValue N0 = N->getOperand(0);
2657 SDValue N1 = N->getOperand(1);
2658 SDValue LL, LR, RL, RR, CC0, CC1;
2659 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
2660 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2661 EVT VT = N1.getValueType();
2662 unsigned BitWidth = VT.getScalarType().getSizeInBits();
2665 if (VT.isVector()) {
2666 SDValue FoldedVOp = SimplifyVBinOp(N);
2667 if (FoldedVOp.getNode()) return FoldedVOp;
2669 // fold (and x, 0) -> 0, vector edition
2670 if (ISD::isBuildVectorAllZeros(N0.getNode()))
2672 if (ISD::isBuildVectorAllZeros(N1.getNode()))
2675 // fold (and x, -1) -> x, vector edition
2676 if (ISD::isBuildVectorAllOnes(N0.getNode()))
2678 if (ISD::isBuildVectorAllOnes(N1.getNode()))
2682 // fold (and x, undef) -> 0
2683 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2684 return DAG.getConstant(0, VT);
2685 // fold (and c1, c2) -> c1&c2
2687 return DAG.FoldConstantArithmetic(ISD::AND, VT, N0C, N1C);
2688 // canonicalize constant to RHS
2690 return DAG.getNode(ISD::AND, SDLoc(N), VT, N1, N0);
2691 // fold (and x, -1) -> x
2692 if (N1C && N1C->isAllOnesValue())
2694 // if (and x, c) is known to be zero, return 0
2695 if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0),
2696 APInt::getAllOnesValue(BitWidth)))
2697 return DAG.getConstant(0, VT);
2699 SDValue RAND = ReassociateOps(ISD::AND, SDLoc(N), N0, N1);
2702 // fold (and (or x, C), D) -> D if (C & D) == D
2703 if (N1C && N0.getOpcode() == ISD::OR)
2704 if (ConstantSDNode *ORI = dyn_cast<ConstantSDNode>(N0.getOperand(1)))
2705 if ((ORI->getAPIntValue() & N1C->getAPIntValue()) == N1C->getAPIntValue())
2707 // fold (and (any_ext V), c) -> (zero_ext V) if 'and' only clears top bits.
2708 if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
2709 SDValue N0Op0 = N0.getOperand(0);
2710 APInt Mask = ~N1C->getAPIntValue();
2711 Mask = Mask.trunc(N0Op0.getValueSizeInBits());
2712 if (DAG.MaskedValueIsZero(N0Op0, Mask)) {
2713 SDValue Zext = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N),
2714 N0.getValueType(), N0Op0);
2716 // Replace uses of the AND with uses of the Zero extend node.
2719 // We actually want to replace all uses of the any_extend with the
2720 // zero_extend, to avoid duplicating things. This will later cause this
2721 // AND to be folded.
2722 CombineTo(N0.getNode(), Zext);
2723 return SDValue(N, 0); // Return N so it doesn't get rechecked!
2726 // similarly fold (and (X (load ([non_ext|any_ext|zero_ext] V))), c) ->
2727 // (X (load ([non_ext|zero_ext] V))) if 'and' only clears top bits which must
2728 // already be zero by virtue of the width of the base type of the load.
2730 // the 'X' node here can either be nothing or an extract_vector_elt to catch
2732 if ((N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
2733 N0.getOperand(0).getOpcode() == ISD::LOAD) ||
2734 N0.getOpcode() == ISD::LOAD) {
2735 LoadSDNode *Load = cast<LoadSDNode>( (N0.getOpcode() == ISD::LOAD) ?
2736 N0 : N0.getOperand(0) );
2738 // Get the constant (if applicable) the zero'th operand is being ANDed with.
2739 // This can be a pure constant or a vector splat, in which case we treat the
2740 // vector as a scalar and use the splat value.
2741 APInt Constant = APInt::getNullValue(1);
2742 if (const ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
2743 Constant = C->getAPIntValue();
2744 } else if (BuildVectorSDNode *Vector = dyn_cast<BuildVectorSDNode>(N1)) {
2745 APInt SplatValue, SplatUndef;
2746 unsigned SplatBitSize;
2748 bool IsSplat = Vector->isConstantSplat(SplatValue, SplatUndef,
2749 SplatBitSize, HasAnyUndefs);
2751 // Undef bits can contribute to a possible optimisation if set, so
2753 SplatValue |= SplatUndef;
2755 // The splat value may be something like "0x00FFFFFF", which means 0 for
2756 // the first vector value and FF for the rest, repeating. We need a mask
2757 // that will apply equally to all members of the vector, so AND all the
2758 // lanes of the constant together.
2759 EVT VT = Vector->getValueType(0);
2760 unsigned BitWidth = VT.getVectorElementType().getSizeInBits();
2762 // If the splat value has been compressed to a bitlength lower
2763 // than the size of the vector lane, we need to re-expand it to
2765 if (BitWidth > SplatBitSize)
2766 for (SplatValue = SplatValue.zextOrTrunc(BitWidth);
2767 SplatBitSize < BitWidth;
2768 SplatBitSize = SplatBitSize * 2)
2769 SplatValue |= SplatValue.shl(SplatBitSize);
2771 Constant = APInt::getAllOnesValue(BitWidth);
2772 for (unsigned i = 0, n = SplatBitSize/BitWidth; i < n; ++i)
2773 Constant &= SplatValue.lshr(i*BitWidth).zextOrTrunc(BitWidth);
2777 // If we want to change an EXTLOAD to a ZEXTLOAD, ensure a ZEXTLOAD is
2778 // actually legal and isn't going to get expanded, else this is a false
2780 bool CanZextLoadProfitably = TLI.isLoadExtLegal(ISD::ZEXTLOAD,
2781 Load->getMemoryVT());
2783 // Resize the constant to the same size as the original memory access before
2784 // extension. If it is still the AllOnesValue then this AND is completely
2787 Constant.zextOrTrunc(Load->getMemoryVT().getScalarType().getSizeInBits());
2790 switch (Load->getExtensionType()) {
2791 default: B = false; break;
2792 case ISD::EXTLOAD: B = CanZextLoadProfitably; break;
2794 case ISD::NON_EXTLOAD: B = true; break;
2797 if (B && Constant.isAllOnesValue()) {
2798 // If the load type was an EXTLOAD, convert to ZEXTLOAD in order to
2799 // preserve semantics once we get rid of the AND.
2800 SDValue NewLoad(Load, 0);
2801 if (Load->getExtensionType() == ISD::EXTLOAD) {
2802 NewLoad = DAG.getLoad(Load->getAddressingMode(), ISD::ZEXTLOAD,
2803 Load->getValueType(0), SDLoc(Load),
2804 Load->getChain(), Load->getBasePtr(),
2805 Load->getOffset(), Load->getMemoryVT(),
2806 Load->getMemOperand());
2807 // Replace uses of the EXTLOAD with the new ZEXTLOAD.
2808 if (Load->getNumValues() == 3) {
2809 // PRE/POST_INC loads have 3 values.
2810 SDValue To[] = { NewLoad.getValue(0), NewLoad.getValue(1),
2811 NewLoad.getValue(2) };
2812 CombineTo(Load, To, 3, true);
2814 CombineTo(Load, NewLoad.getValue(0), NewLoad.getValue(1));
2818 // Fold the AND away, taking care not to fold to the old load node if we
2820 CombineTo(N, (N0.getNode() == Load) ? NewLoad : N0);
2822 return SDValue(N, 0); // Return N so it doesn't get rechecked!
2825 // fold (and (setcc x), (setcc y)) -> (setcc (and x, y))
2826 if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){
2827 ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get();
2828 ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get();
2830 if (LR == RR && isa<ConstantSDNode>(LR) && Op0 == Op1 &&
2831 LL.getValueType().isInteger()) {
2832 // fold (and (seteq X, 0), (seteq Y, 0)) -> (seteq (or X, Y), 0)
2833 if (cast<ConstantSDNode>(LR)->isNullValue() && Op1 == ISD::SETEQ) {
2834 SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(N0),
2835 LR.getValueType(), LL, RL);
2836 AddToWorklist(ORNode.getNode());
2837 return DAG.getSetCC(SDLoc(N), VT, ORNode, LR, Op1);
2839 // fold (and (seteq X, -1), (seteq Y, -1)) -> (seteq (and X, Y), -1)
2840 if (cast<ConstantSDNode>(LR)->isAllOnesValue() && Op1 == ISD::SETEQ) {
2841 SDValue ANDNode = DAG.getNode(ISD::AND, SDLoc(N0),
2842 LR.getValueType(), LL, RL);
2843 AddToWorklist(ANDNode.getNode());
2844 return DAG.getSetCC(SDLoc(N), VT, ANDNode, LR, Op1);
2846 // fold (and (setgt X, -1), (setgt Y, -1)) -> (setgt (or X, Y), -1)
2847 if (cast<ConstantSDNode>(LR)->isAllOnesValue() && Op1 == ISD::SETGT) {
2848 SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(N0),
2849 LR.getValueType(), LL, RL);
2850 AddToWorklist(ORNode.getNode());
2851 return DAG.getSetCC(SDLoc(N), VT, ORNode, LR, Op1);
2854 // Simplify (and (setne X, 0), (setne X, -1)) -> (setuge (add X, 1), 2)
2855 if (LL == RL && isa<ConstantSDNode>(LR) && isa<ConstantSDNode>(RR) &&
2856 Op0 == Op1 && LL.getValueType().isInteger() &&
2857 Op0 == ISD::SETNE && ((cast<ConstantSDNode>(LR)->isNullValue() &&
2858 cast<ConstantSDNode>(RR)->isAllOnesValue()) ||
2859 (cast<ConstantSDNode>(LR)->isAllOnesValue() &&
2860 cast<ConstantSDNode>(RR)->isNullValue()))) {
2861 SDValue ADDNode = DAG.getNode(ISD::ADD, SDLoc(N0), LL.getValueType(),
2862 LL, DAG.getConstant(1, LL.getValueType()));
2863 AddToWorklist(ADDNode.getNode());
2864 return DAG.getSetCC(SDLoc(N), VT, ADDNode,
2865 DAG.getConstant(2, LL.getValueType()), ISD::SETUGE);
2867 // canonicalize equivalent to ll == rl
2868 if (LL == RR && LR == RL) {
2869 Op1 = ISD::getSetCCSwappedOperands(Op1);
2872 if (LL == RL && LR == RR) {
2873 bool isInteger = LL.getValueType().isInteger();
2874 ISD::CondCode Result = ISD::getSetCCAndOperation(Op0, Op1, isInteger);
2875 if (Result != ISD::SETCC_INVALID &&
2876 (!LegalOperations ||
2877 (TLI.isCondCodeLegal(Result, LL.getSimpleValueType()) &&
2878 TLI.isOperationLegal(ISD::SETCC,
2879 getSetCCResultType(N0.getSimpleValueType())))))
2880 return DAG.getSetCC(SDLoc(N), N0.getValueType(),
2885 // Simplify: (and (op x...), (op y...)) -> (op (and x, y))
2886 if (N0.getOpcode() == N1.getOpcode()) {
2887 SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
2888 if (Tmp.getNode()) return Tmp;
2891 // fold (and (sign_extend_inreg x, i16 to i32), 1) -> (and x, 1)
2892 // fold (and (sra)) -> (and (srl)) when possible.
2893 if (!VT.isVector() &&
2894 SimplifyDemandedBits(SDValue(N, 0)))
2895 return SDValue(N, 0);
2897 // fold (zext_inreg (extload x)) -> (zextload x)
2898 if (ISD::isEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode())) {
2899 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
2900 EVT MemVT = LN0->getMemoryVT();
2901 // If we zero all the possible extended bits, then we can turn this into
2902 // a zextload if we are running before legalize or the operation is legal.
2903 unsigned BitWidth = N1.getValueType().getScalarType().getSizeInBits();
2904 if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth,
2905 BitWidth - MemVT.getScalarType().getSizeInBits())) &&
2906 ((!LegalOperations && !LN0->isVolatile()) ||
2907 TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT))) {
2908 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N0), VT,
2909 LN0->getChain(), LN0->getBasePtr(),
2910 MemVT, LN0->getMemOperand());
2912 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
2913 return SDValue(N, 0); // Return N so it doesn't get rechecked!
2916 // fold (zext_inreg (sextload x)) -> (zextload x) iff load has one use
2917 if (ISD::isSEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
2919 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
2920 EVT MemVT = LN0->getMemoryVT();
2921 // If we zero all the possible extended bits, then we can turn this into
2922 // a zextload if we are running before legalize or the operation is legal.
2923 unsigned BitWidth = N1.getValueType().getScalarType().getSizeInBits();
2924 if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth,
2925 BitWidth - MemVT.getScalarType().getSizeInBits())) &&
2926 ((!LegalOperations && !LN0->isVolatile()) ||
2927 TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT))) {
2928 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N0), VT,
2929 LN0->getChain(), LN0->getBasePtr(),
2930 MemVT, LN0->getMemOperand());
2932 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
2933 return SDValue(N, 0); // Return N so it doesn't get rechecked!
2937 // fold (and (load x), 255) -> (zextload x, i8)
2938 // fold (and (extload x, i16), 255) -> (zextload x, i8)
2939 // fold (and (any_ext (extload x, i16)), 255) -> (zextload x, i8)
2940 if (N1C && (N0.getOpcode() == ISD::LOAD ||
2941 (N0.getOpcode() == ISD::ANY_EXTEND &&
2942 N0.getOperand(0).getOpcode() == ISD::LOAD))) {
2943 bool HasAnyExt = N0.getOpcode() == ISD::ANY_EXTEND;
2944 LoadSDNode *LN0 = HasAnyExt
2945 ? cast<LoadSDNode>(N0.getOperand(0))
2946 : cast<LoadSDNode>(N0);
2947 if (LN0->getExtensionType() != ISD::SEXTLOAD &&
2948 LN0->isUnindexed() && N0.hasOneUse() && SDValue(LN0, 0).hasOneUse()) {
2949 uint32_t ActiveBits = N1C->getAPIntValue().getActiveBits();
2950 if (ActiveBits > 0 && APIntOps::isMask(ActiveBits, N1C->getAPIntValue())){
2951 EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), ActiveBits);
2952 EVT LoadedVT = LN0->getMemoryVT();
2954 if (ExtVT == LoadedVT &&
2955 (!LegalOperations || TLI.isLoadExtLegal(ISD::ZEXTLOAD, ExtVT))) {
2956 EVT LoadResultTy = HasAnyExt ? LN0->getValueType(0) : VT;
2959 DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), LoadResultTy,
2960 LN0->getChain(), LN0->getBasePtr(), ExtVT,
2961 LN0->getMemOperand());
2963 CombineTo(LN0, NewLoad, NewLoad.getValue(1));
2964 return SDValue(N, 0); // Return N so it doesn't get rechecked!
2967 // Do not change the width of a volatile load.
2968 // Do not generate loads of non-round integer types since these can
2969 // be expensive (and would be wrong if the type is not byte sized).
2970 if (!LN0->isVolatile() && LoadedVT.bitsGT(ExtVT) && ExtVT.isRound() &&
2971 (!LegalOperations || TLI.isLoadExtLegal(ISD::ZEXTLOAD, ExtVT))) {
2972 EVT PtrType = LN0->getOperand(1).getValueType();
2974 unsigned Alignment = LN0->getAlignment();
2975 SDValue NewPtr = LN0->getBasePtr();
2977 // For big endian targets, we need to add an offset to the pointer
2978 // to load the correct bytes. For little endian systems, we merely
2979 // need to read fewer bytes from the same pointer.
2980 if (TLI.isBigEndian()) {
2981 unsigned LVTStoreBytes = LoadedVT.getStoreSize();
2982 unsigned EVTStoreBytes = ExtVT.getStoreSize();
2983 unsigned PtrOff = LVTStoreBytes - EVTStoreBytes;
2984 NewPtr = DAG.getNode(ISD::ADD, SDLoc(LN0), PtrType,
2985 NewPtr, DAG.getConstant(PtrOff, PtrType));
2986 Alignment = MinAlign(Alignment, PtrOff);
2989 AddToWorklist(NewPtr.getNode());
2991 EVT LoadResultTy = HasAnyExt ? LN0->getValueType(0) : VT;
2993 DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), LoadResultTy,
2994 LN0->getChain(), NewPtr,
2995 LN0->getPointerInfo(),
2996 ExtVT, LN0->isVolatile(), LN0->isNonTemporal(),
2997 LN0->isInvariant(), Alignment, LN0->getAAInfo());
2999 CombineTo(LN0, Load, Load.getValue(1));
3000 return SDValue(N, 0); // Return N so it doesn't get rechecked!
3006 if (N0.getOpcode() == ISD::ADD && N1.getOpcode() == ISD::SRL &&
3007 VT.getSizeInBits() <= 64) {
3008 if (ConstantSDNode *ADDI = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
3009 APInt ADDC = ADDI->getAPIntValue();
3010 if (!TLI.isLegalAddImmediate(ADDC.getSExtValue())) {
3011 // Look for (and (add x, c1), (lshr y, c2)). If C1 wasn't a legal
3012 // immediate for an add, but it is legal if its top c2 bits are set,
3013 // transform the ADD so the immediate doesn't need to be materialized
3015 if (ConstantSDNode *SRLI = dyn_cast<ConstantSDNode>(N1.getOperand(1))) {
3016 APInt Mask = APInt::getHighBitsSet(VT.getSizeInBits(),
3017 SRLI->getZExtValue());
3018 if (DAG.MaskedValueIsZero(N0.getOperand(1), Mask)) {
3020 if (TLI.isLegalAddImmediate(ADDC.getSExtValue())) {
3022 DAG.getNode(ISD::ADD, SDLoc(N0), VT,
3023 N0.getOperand(0), DAG.getConstant(ADDC, VT));
3024 CombineTo(N0.getNode(), NewAdd);
3025 return SDValue(N, 0); // Return N so it doesn't get rechecked!
3033 // fold (and (or (srl N, 8), (shl N, 8)), 0xffff) -> (srl (bswap N), const)
3034 if (N1C && N1C->getAPIntValue() == 0xffff && N0.getOpcode() == ISD::OR) {
3035 SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0),
3036 N0.getOperand(1), false);
3037 if (BSwap.getNode())
3044 /// Match (a >> 8) | (a << 8) as (bswap a) >> 16.
3045 SDValue DAGCombiner::MatchBSwapHWordLow(SDNode *N, SDValue N0, SDValue N1,
3046 bool DemandHighBits) {
3047 if (!LegalOperations)
3050 EVT VT = N->getValueType(0);
3051 if (VT != MVT::i64 && VT != MVT::i32 && VT != MVT::i16)
3053 if (!TLI.isOperationLegal(ISD::BSWAP, VT))
3056 // Recognize (and (shl a, 8), 0xff), (and (srl a, 8), 0xff00)
3057 bool LookPassAnd0 = false;
3058 bool LookPassAnd1 = false;
3059 if (N0.getOpcode() == ISD::AND && N0.getOperand(0).getOpcode() == ISD::SRL)
3061 if (N1.getOpcode() == ISD::AND && N1.getOperand(0).getOpcode() == ISD::SHL)
3063 if (N0.getOpcode() == ISD::AND) {
3064 if (!N0.getNode()->hasOneUse())
3066 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3067 if (!N01C || N01C->getZExtValue() != 0xFF00)
3069 N0 = N0.getOperand(0);
3070 LookPassAnd0 = true;
3073 if (N1.getOpcode() == ISD::AND) {
3074 if (!N1.getNode()->hasOneUse())
3076 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
3077 if (!N11C || N11C->getZExtValue() != 0xFF)
3079 N1 = N1.getOperand(0);
3080 LookPassAnd1 = true;
3083 if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
3085 if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
3087 if (!N0.getNode()->hasOneUse() ||
3088 !N1.getNode()->hasOneUse())
3091 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3092 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
3095 if (N01C->getZExtValue() != 8 || N11C->getZExtValue() != 8)
3098 // Look for (shl (and a, 0xff), 8), (srl (and a, 0xff00), 8)
3099 SDValue N00 = N0->getOperand(0);
3100 if (!LookPassAnd0 && N00.getOpcode() == ISD::AND) {
3101 if (!N00.getNode()->hasOneUse())
3103 ConstantSDNode *N001C = dyn_cast<ConstantSDNode>(N00.getOperand(1));
3104 if (!N001C || N001C->getZExtValue() != 0xFF)
3106 N00 = N00.getOperand(0);
3107 LookPassAnd0 = true;
3110 SDValue N10 = N1->getOperand(0);
3111 if (!LookPassAnd1 && N10.getOpcode() == ISD::AND) {
3112 if (!N10.getNode()->hasOneUse())
3114 ConstantSDNode *N101C = dyn_cast<ConstantSDNode>(N10.getOperand(1));
3115 if (!N101C || N101C->getZExtValue() != 0xFF00)
3117 N10 = N10.getOperand(0);
3118 LookPassAnd1 = true;
3124 // Make sure everything beyond the low halfword gets set to zero since the SRL
3125 // 16 will clear the top bits.
3126 unsigned OpSizeInBits = VT.getSizeInBits();
3127 if (DemandHighBits && OpSizeInBits > 16) {
3128 // If the left-shift isn't masked out then the only way this is a bswap is
3129 // if all bits beyond the low 8 are 0. In that case the entire pattern
3130 // reduces to a left shift anyway: leave it for other parts of the combiner.
3134 // However, if the right shift isn't masked out then it might be because
3135 // it's not needed. See if we can spot that too.
3136 if (!LookPassAnd1 &&
3137 !DAG.MaskedValueIsZero(
3138 N10, APInt::getHighBitsSet(OpSizeInBits, OpSizeInBits - 16)))
3142 SDValue Res = DAG.getNode(ISD::BSWAP, SDLoc(N), VT, N00);
3143 if (OpSizeInBits > 16)
3144 Res = DAG.getNode(ISD::SRL, SDLoc(N), VT, Res,
3145 DAG.getConstant(OpSizeInBits-16, getShiftAmountTy(VT)));
3149 /// Return true if the specified node is an element that makes up a 32-bit
3150 /// packed halfword byteswap.
3151 /// ((x & 0x000000ff) << 8) |
3152 /// ((x & 0x0000ff00) >> 8) |
3153 /// ((x & 0x00ff0000) << 8) |
3154 /// ((x & 0xff000000) >> 8)
3155 static bool isBSwapHWordElement(SDValue N, SmallVectorImpl<SDNode *> &Parts) {
3156 if (!N.getNode()->hasOneUse())
3159 unsigned Opc = N.getOpcode();
3160 if (Opc != ISD::AND && Opc != ISD::SHL && Opc != ISD::SRL)
3163 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3168 switch (N1C->getZExtValue()) {
3171 case 0xFF: Num = 0; break;
3172 case 0xFF00: Num = 1; break;
3173 case 0xFF0000: Num = 2; break;
3174 case 0xFF000000: Num = 3; break;
3177 // Look for (x & 0xff) << 8 as well as ((x << 8) & 0xff00).
3178 SDValue N0 = N.getOperand(0);
3179 if (Opc == ISD::AND) {
3180 if (Num == 0 || Num == 2) {
3182 // (x >> 8) & 0xff0000
3183 if (N0.getOpcode() != ISD::SRL)
3185 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3186 if (!C || C->getZExtValue() != 8)
3189 // (x << 8) & 0xff00
3190 // (x << 8) & 0xff000000
3191 if (N0.getOpcode() != ISD::SHL)
3193 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3194 if (!C || C->getZExtValue() != 8)
3197 } else if (Opc == ISD::SHL) {
3199 // (x & 0xff0000) << 8
3200 if (Num != 0 && Num != 2)
3202 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3203 if (!C || C->getZExtValue() != 8)
3205 } else { // Opc == ISD::SRL
3206 // (x & 0xff00) >> 8
3207 // (x & 0xff000000) >> 8
3208 if (Num != 1 && Num != 3)
3210 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3211 if (!C || C->getZExtValue() != 8)
3218 Parts[Num] = N0.getOperand(0).getNode();
3222 /// Match a 32-bit packed halfword bswap. That is
3223 /// ((x & 0x000000ff) << 8) |
3224 /// ((x & 0x0000ff00) >> 8) |
3225 /// ((x & 0x00ff0000) << 8) |
3226 /// ((x & 0xff000000) >> 8)
3227 /// => (rotl (bswap x), 16)
3228 SDValue DAGCombiner::MatchBSwapHWord(SDNode *N, SDValue N0, SDValue N1) {
3229 if (!LegalOperations)
3232 EVT VT = N->getValueType(0);
3235 if (!TLI.isOperationLegal(ISD::BSWAP, VT))
3238 SmallVector<SDNode*,4> Parts(4, (SDNode*)nullptr);
3240 // (or (or (and), (and)), (or (and), (and)))
3241 // (or (or (or (and), (and)), (and)), (and))
3242 if (N0.getOpcode() != ISD::OR)
3244 SDValue N00 = N0.getOperand(0);
3245 SDValue N01 = N0.getOperand(1);
3247 if (N1.getOpcode() == ISD::OR &&
3248 N00.getNumOperands() == 2 && N01.getNumOperands() == 2) {
3249 // (or (or (and), (and)), (or (and), (and)))
3250 SDValue N000 = N00.getOperand(0);
3251 if (!isBSwapHWordElement(N000, Parts))
3254 SDValue N001 = N00.getOperand(1);
3255 if (!isBSwapHWordElement(N001, Parts))
3257 SDValue N010 = N01.getOperand(0);
3258 if (!isBSwapHWordElement(N010, Parts))
3260 SDValue N011 = N01.getOperand(1);
3261 if (!isBSwapHWordElement(N011, Parts))
3264 // (or (or (or (and), (and)), (and)), (and))
3265 if (!isBSwapHWordElement(N1, Parts))
3267 if (!isBSwapHWordElement(N01, Parts))
3269 if (N00.getOpcode() != ISD::OR)
3271 SDValue N000 = N00.getOperand(0);
3272 if (!isBSwapHWordElement(N000, Parts))
3274 SDValue N001 = N00.getOperand(1);
3275 if (!isBSwapHWordElement(N001, Parts))
3279 // Make sure the parts are all coming from the same node.
3280 if (Parts[0] != Parts[1] || Parts[0] != Parts[2] || Parts[0] != Parts[3])
3283 SDValue BSwap = DAG.getNode(ISD::BSWAP, SDLoc(N), VT,
3284 SDValue(Parts[0],0));
3286 // Result of the bswap should be rotated by 16. If it's not legal, then
3287 // do (x << 16) | (x >> 16).
3288 SDValue ShAmt = DAG.getConstant(16, getShiftAmountTy(VT));
3289 if (TLI.isOperationLegalOrCustom(ISD::ROTL, VT))
3290 return DAG.getNode(ISD::ROTL, SDLoc(N), VT, BSwap, ShAmt);
3291 if (TLI.isOperationLegalOrCustom(ISD::ROTR, VT))
3292 return DAG.getNode(ISD::ROTR, SDLoc(N), VT, BSwap, ShAmt);
3293 return DAG.getNode(ISD::OR, SDLoc(N), VT,
3294 DAG.getNode(ISD::SHL, SDLoc(N), VT, BSwap, ShAmt),
3295 DAG.getNode(ISD::SRL, SDLoc(N), VT, BSwap, ShAmt));
3298 SDValue DAGCombiner::visitOR(SDNode *N) {
3299 SDValue N0 = N->getOperand(0);
3300 SDValue N1 = N->getOperand(1);
3301 SDValue LL, LR, RL, RR, CC0, CC1;
3302 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
3303 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
3304 EVT VT = N1.getValueType();
3307 if (VT.isVector()) {
3308 SDValue FoldedVOp = SimplifyVBinOp(N);
3309 if (FoldedVOp.getNode()) return FoldedVOp;
3311 // fold (or x, 0) -> x, vector edition
3312 if (ISD::isBuildVectorAllZeros(N0.getNode()))
3314 if (ISD::isBuildVectorAllZeros(N1.getNode()))
3317 // fold (or x, -1) -> -1, vector edition
3318 if (ISD::isBuildVectorAllOnes(N0.getNode()))
3320 if (ISD::isBuildVectorAllOnes(N1.getNode()))
3323 // fold (or (shuf A, V_0, MA), (shuf B, V_0, MB)) -> (shuf A, B, Mask1)
3324 // fold (or (shuf A, V_0, MA), (shuf B, V_0, MB)) -> (shuf B, A, Mask2)
3325 // Do this only if the resulting shuffle is legal.
3326 if (isa<ShuffleVectorSDNode>(N0) &&
3327 isa<ShuffleVectorSDNode>(N1) &&
3328 // Avoid folding a node with illegal type.
3329 TLI.isTypeLegal(VT) &&
3330 N0->getOperand(1) == N1->getOperand(1) &&
3331 ISD::isBuildVectorAllZeros(N0.getOperand(1).getNode())) {
3332 bool CanFold = true;
3333 unsigned NumElts = VT.getVectorNumElements();
3334 const ShuffleVectorSDNode *SV0 = cast<ShuffleVectorSDNode>(N0);
3335 const ShuffleVectorSDNode *SV1 = cast<ShuffleVectorSDNode>(N1);
3336 // We construct two shuffle masks:
3337 // - Mask1 is a shuffle mask for a shuffle with N0 as the first operand
3338 // and N1 as the second operand.
3339 // - Mask2 is a shuffle mask for a shuffle with N1 as the first operand
3340 // and N0 as the second operand.
3341 // We do this because OR is commutable and therefore there might be
3342 // two ways to fold this node into a shuffle.
3343 SmallVector<int,4> Mask1;
3344 SmallVector<int,4> Mask2;
3346 for (unsigned i = 0; i != NumElts && CanFold; ++i) {
3347 int M0 = SV0->getMaskElt(i);
3348 int M1 = SV1->getMaskElt(i);
3350 // Both shuffle indexes are undef. Propagate Undef.
3351 if (M0 < 0 && M1 < 0) {
3352 Mask1.push_back(M0);
3353 Mask2.push_back(M0);
3357 if (M0 < 0 || M1 < 0 ||
3358 (M0 < (int)NumElts && M1 < (int)NumElts) ||
3359 (M0 >= (int)NumElts && M1 >= (int)NumElts)) {
3364 Mask1.push_back(M0 < (int)NumElts ? M0 : M1 + NumElts);
3365 Mask2.push_back(M1 < (int)NumElts ? M1 : M0 + NumElts);
3369 // Fold this sequence only if the resulting shuffle is 'legal'.
3370 if (TLI.isShuffleMaskLegal(Mask1, VT))
3371 return DAG.getVectorShuffle(VT, SDLoc(N), N0->getOperand(0),
3372 N1->getOperand(0), &Mask1[0]);
3373 if (TLI.isShuffleMaskLegal(Mask2, VT))
3374 return DAG.getVectorShuffle(VT, SDLoc(N), N1->getOperand(0),
3375 N0->getOperand(0), &Mask2[0]);
3380 // fold (or x, undef) -> -1
3381 if (!LegalOperations &&
3382 (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)) {
3383 EVT EltVT = VT.isVector() ? VT.getVectorElementType() : VT;
3384 return DAG.getConstant(APInt::getAllOnesValue(EltVT.getSizeInBits()), VT);
3386 // fold (or c1, c2) -> c1|c2
3388 return DAG.FoldConstantArithmetic(ISD::OR, VT, N0C, N1C);
3389 // canonicalize constant to RHS
3391 return DAG.getNode(ISD::OR, SDLoc(N), VT, N1, N0);
3392 // fold (or x, 0) -> x
3393 if (N1C && N1C->isNullValue())
3395 // fold (or x, -1) -> -1
3396 if (N1C && N1C->isAllOnesValue())
3398 // fold (or x, c) -> c iff (x & ~c) == 0
3399 if (N1C && DAG.MaskedValueIsZero(N0, ~N1C->getAPIntValue()))
3402 // Recognize halfword bswaps as (bswap + rotl 16) or (bswap + shl 16)
3403 SDValue BSwap = MatchBSwapHWord(N, N0, N1);
3404 if (BSwap.getNode())
3406 BSwap = MatchBSwapHWordLow(N, N0, N1);
3407 if (BSwap.getNode())
3411 SDValue ROR = ReassociateOps(ISD::OR, SDLoc(N), N0, N1);
3414 // Canonicalize (or (and X, c1), c2) -> (and (or X, c2), c1|c2)
3415 // iff (c1 & c2) == 0.
3416 if (N1C && N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() &&
3417 isa<ConstantSDNode>(N0.getOperand(1))) {
3418 ConstantSDNode *C1 = cast<ConstantSDNode>(N0.getOperand(1));
3419 if ((C1->getAPIntValue() & N1C->getAPIntValue()) != 0) {
3420 SDValue COR = DAG.FoldConstantArithmetic(ISD::OR, VT, N1C, C1);
3423 return DAG.getNode(ISD::AND, SDLoc(N), VT,
3424 DAG.getNode(ISD::OR, SDLoc(N0), VT,
3425 N0.getOperand(0), N1), COR);
3428 // fold (or (setcc x), (setcc y)) -> (setcc (or x, y))
3429 if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){
3430 ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get();
3431 ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get();
3433 if (LR == RR && isa<ConstantSDNode>(LR) && Op0 == Op1 &&
3434 LL.getValueType().isInteger()) {
3435 // fold (or (setne X, 0), (setne Y, 0)) -> (setne (or X, Y), 0)
3436 // fold (or (setlt X, 0), (setlt Y, 0)) -> (setne (or X, Y), 0)
3437 if (cast<ConstantSDNode>(LR)->isNullValue() &&
3438 (Op1 == ISD::SETNE || Op1 == ISD::SETLT)) {
3439 SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(LR),
3440 LR.getValueType(), LL, RL);
3441 AddToWorklist(ORNode.getNode());
3442 return DAG.getSetCC(SDLoc(N), VT, ORNode, LR, Op1);
3444 // fold (or (setne X, -1), (setne Y, -1)) -> (setne (and X, Y), -1)
3445 // fold (or (setgt X, -1), (setgt Y -1)) -> (setgt (and X, Y), -1)
3446 if (cast<ConstantSDNode>(LR)->isAllOnesValue() &&
3447 (Op1 == ISD::SETNE || Op1 == ISD::SETGT)) {
3448 SDValue ANDNode = DAG.getNode(ISD::AND, SDLoc(LR),
3449 LR.getValueType(), LL, RL);
3450 AddToWorklist(ANDNode.getNode());
3451 return DAG.getSetCC(SDLoc(N), VT, ANDNode, LR, Op1);
3454 // canonicalize equivalent to ll == rl
3455 if (LL == RR && LR == RL) {
3456 Op1 = ISD::getSetCCSwappedOperands(Op1);
3459 if (LL == RL && LR == RR) {
3460 bool isInteger = LL.getValueType().isInteger();
3461 ISD::CondCode Result = ISD::getSetCCOrOperation(Op0, Op1, isInteger);
3462 if (Result != ISD::SETCC_INVALID &&
3463 (!LegalOperations ||
3464 (TLI.isCondCodeLegal(Result, LL.getSimpleValueType()) &&
3465 TLI.isOperationLegal(ISD::SETCC,
3466 getSetCCResultType(N0.getValueType())))))
3467 return DAG.getSetCC(SDLoc(N), N0.getValueType(),
3472 // Simplify: (or (op x...), (op y...)) -> (op (or x, y))
3473 if (N0.getOpcode() == N1.getOpcode()) {
3474 SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
3475 if (Tmp.getNode()) return Tmp;
3478 // (or (and X, C1), (and Y, C2)) -> (and (or X, Y), C3) if possible.
3479 if (N0.getOpcode() == ISD::AND &&
3480 N1.getOpcode() == ISD::AND &&
3481 N0.getOperand(1).getOpcode() == ISD::Constant &&
3482 N1.getOperand(1).getOpcode() == ISD::Constant &&
3483 // Don't increase # computations.
3484 (N0.getNode()->hasOneUse() || N1.getNode()->hasOneUse())) {
3485 // We can only do this xform if we know that bits from X that are set in C2
3486 // but not in C1 are already zero. Likewise for Y.
3487 const APInt &LHSMask =
3488 cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
3489 const APInt &RHSMask =
3490 cast<ConstantSDNode>(N1.getOperand(1))->getAPIntValue();
3492 if (DAG.MaskedValueIsZero(N0.getOperand(0), RHSMask&~LHSMask) &&
3493 DAG.MaskedValueIsZero(N1.getOperand(0), LHSMask&~RHSMask)) {
3494 SDValue X = DAG.getNode(ISD::OR, SDLoc(N0), VT,
3495 N0.getOperand(0), N1.getOperand(0));
3496 return DAG.getNode(ISD::AND, SDLoc(N), VT, X,
3497 DAG.getConstant(LHSMask | RHSMask, VT));
3501 // See if this is some rotate idiom.
3502 if (SDNode *Rot = MatchRotate(N0, N1, SDLoc(N)))
3503 return SDValue(Rot, 0);
3505 // Simplify the operands using demanded-bits information.
3506 if (!VT.isVector() &&
3507 SimplifyDemandedBits(SDValue(N, 0)))
3508 return SDValue(N, 0);
3513 /// Match "(X shl/srl V1) & V2" where V2 may not be present.
3514 static bool MatchRotateHalf(SDValue Op, SDValue &Shift, SDValue &Mask) {
3515 if (Op.getOpcode() == ISD::AND) {
3516 if (isa<ConstantSDNode>(Op.getOperand(1))) {
3517 Mask = Op.getOperand(1);
3518 Op = Op.getOperand(0);
3524 if (Op.getOpcode() == ISD::SRL || Op.getOpcode() == ISD::SHL) {
3532 // Return true if we can prove that, whenever Neg and Pos are both in the
3533 // range [0, OpSize), Neg == (Pos == 0 ? 0 : OpSize - Pos). This means that
3534 // for two opposing shifts shift1 and shift2 and a value X with OpBits bits:
3536 // (or (shift1 X, Neg), (shift2 X, Pos))
3538 // reduces to a rotate in direction shift2 by Pos or (equivalently) a rotate
3539 // in direction shift1 by Neg. The range [0, OpSize) means that we only need
3540 // to consider shift amounts with defined behavior.
3541 static bool matchRotateSub(SDValue Pos, SDValue Neg, unsigned OpSize) {
3542 // If OpSize is a power of 2 then:
3544 // (a) (Pos == 0 ? 0 : OpSize - Pos) == (OpSize - Pos) & (OpSize - 1)
3545 // (b) Neg == Neg & (OpSize - 1) whenever Neg is in [0, OpSize).
3547 // So if OpSize is a power of 2 and Neg is (and Neg', OpSize-1), we check
3548 // for the stronger condition:
3550 // Neg & (OpSize - 1) == (OpSize - Pos) & (OpSize - 1) [A]
3552 // for all Neg and Pos. Since Neg & (OpSize - 1) == Neg' & (OpSize - 1)
3553 // we can just replace Neg with Neg' for the rest of the function.
3555 // In other cases we check for the even stronger condition:
3557 // Neg == OpSize - Pos [B]
3559 // for all Neg and Pos. Note that the (or ...) then invokes undefined
3560 // behavior if Pos == 0 (and consequently Neg == OpSize).
3562 // We could actually use [A] whenever OpSize is a power of 2, but the
3563 // only extra cases that it would match are those uninteresting ones
3564 // where Neg and Pos are never in range at the same time. E.g. for
3565 // OpSize == 32, using [A] would allow a Neg of the form (sub 64, Pos)
3566 // as well as (sub 32, Pos), but:
3568 // (or (shift1 X, (sub 64, Pos)), (shift2 X, Pos))
3570 // always invokes undefined behavior for 32-bit X.
3572 // Below, Mask == OpSize - 1 when using [A] and is all-ones otherwise.
3573 unsigned MaskLoBits = 0;
3574 if (Neg.getOpcode() == ISD::AND &&
3575 isPowerOf2_64(OpSize) &&
3576 Neg.getOperand(1).getOpcode() == ISD::Constant &&
3577 cast<ConstantSDNode>(Neg.getOperand(1))->getAPIntValue() == OpSize - 1) {
3578 Neg = Neg.getOperand(0);
3579 MaskLoBits = Log2_64(OpSize);
3582 // Check whether Neg has the form (sub NegC, NegOp1) for some NegC and NegOp1.
3583 if (Neg.getOpcode() != ISD::SUB)
3585 ConstantSDNode *NegC = dyn_cast<ConstantSDNode>(Neg.getOperand(0));
3588 SDValue NegOp1 = Neg.getOperand(1);
3590 // On the RHS of [A], if Pos is Pos' & (OpSize - 1), just replace Pos with
3591 // Pos'. The truncation is redundant for the purpose of the equality.
3593 Pos.getOpcode() == ISD::AND &&
3594 Pos.getOperand(1).getOpcode() == ISD::Constant &&
3595 cast<ConstantSDNode>(Pos.getOperand(1))->getAPIntValue() == OpSize - 1)
3596 Pos = Pos.getOperand(0);
3598 // The condition we need is now:
3600 // (NegC - NegOp1) & Mask == (OpSize - Pos) & Mask
3602 // If NegOp1 == Pos then we need:
3604 // OpSize & Mask == NegC & Mask
3606 // (because "x & Mask" is a truncation and distributes through subtraction).
3609 Width = NegC->getAPIntValue();
3610 // Check for cases where Pos has the form (add NegOp1, PosC) for some PosC.
3611 // Then the condition we want to prove becomes:
3613 // (NegC - NegOp1) & Mask == (OpSize - (NegOp1 + PosC)) & Mask
3615 // which, again because "x & Mask" is a truncation, becomes:
3617 // NegC & Mask == (OpSize - PosC) & Mask
3618 // OpSize & Mask == (NegC + PosC) & Mask
3619 else if (Pos.getOpcode() == ISD::ADD &&
3620 Pos.getOperand(0) == NegOp1 &&
3621 Pos.getOperand(1).getOpcode() == ISD::Constant)
3622 Width = (cast<ConstantSDNode>(Pos.getOperand(1))->getAPIntValue() +
3623 NegC->getAPIntValue());
3627 // Now we just need to check that OpSize & Mask == Width & Mask.
3629 // Opsize & Mask is 0 since Mask is Opsize - 1.
3630 return Width.getLoBits(MaskLoBits) == 0;
3631 return Width == OpSize;
3634 // A subroutine of MatchRotate used once we have found an OR of two opposite
3635 // shifts of Shifted. If Neg == <operand size> - Pos then the OR reduces
3636 // to both (PosOpcode Shifted, Pos) and (NegOpcode Shifted, Neg), with the
3637 // former being preferred if supported. InnerPos and InnerNeg are Pos and
3638 // Neg with outer conversions stripped away.
3639 SDNode *DAGCombiner::MatchRotatePosNeg(SDValue Shifted, SDValue Pos,
3640 SDValue Neg, SDValue InnerPos,
3641 SDValue InnerNeg, unsigned PosOpcode,
3642 unsigned NegOpcode, SDLoc DL) {
3643 // fold (or (shl x, (*ext y)),
3644 // (srl x, (*ext (sub 32, y)))) ->
3645 // (rotl x, y) or (rotr x, (sub 32, y))
3647 // fold (or (shl x, (*ext (sub 32, y))),
3648 // (srl x, (*ext y))) ->
3649 // (rotr x, y) or (rotl x, (sub 32, y))
3650 EVT VT = Shifted.getValueType();
3651 if (matchRotateSub(InnerPos, InnerNeg, VT.getSizeInBits())) {
3652 bool HasPos = TLI.isOperationLegalOrCustom(PosOpcode, VT);
3653 return DAG.getNode(HasPos ? PosOpcode : NegOpcode, DL, VT, Shifted,
3654 HasPos ? Pos : Neg).getNode();
3660 // MatchRotate - Handle an 'or' of two operands. If this is one of the many
3661 // idioms for rotate, and if the target supports rotation instructions, generate
3663 SDNode *DAGCombiner::MatchRotate(SDValue LHS, SDValue RHS, SDLoc DL) {
3664 // Must be a legal type. Expanded 'n promoted things won't work with rotates.
3665 EVT VT = LHS.getValueType();
3666 if (!TLI.isTypeLegal(VT)) return nullptr;
3668 // The target must have at least one rotate flavor.
3669 bool HasROTL = TLI.isOperationLegalOrCustom(ISD::ROTL, VT);
3670 bool HasROTR = TLI.isOperationLegalOrCustom(ISD::ROTR, VT);
3671 if (!HasROTL && !HasROTR) return nullptr;
3673 // Match "(X shl/srl V1) & V2" where V2 may not be present.
3674 SDValue LHSShift; // The shift.
3675 SDValue LHSMask; // AND value if any.
3676 if (!MatchRotateHalf(LHS, LHSShift, LHSMask))
3677 return nullptr; // Not part of a rotate.
3679 SDValue RHSShift; // The shift.
3680 SDValue RHSMask; // AND value if any.
3681 if (!MatchRotateHalf(RHS, RHSShift, RHSMask))
3682 return nullptr; // Not part of a rotate.
3684 if (LHSShift.getOperand(0) != RHSShift.getOperand(0))
3685 return nullptr; // Not shifting the same value.
3687 if (LHSShift.getOpcode() == RHSShift.getOpcode())
3688 return nullptr; // Shifts must disagree.
3690 // Canonicalize shl to left side in a shl/srl pair.
3691 if (RHSShift.getOpcode() == ISD::SHL) {
3692 std::swap(LHS, RHS);
3693 std::swap(LHSShift, RHSShift);
3694 std::swap(LHSMask , RHSMask );
3697 unsigned OpSizeInBits = VT.getSizeInBits();
3698 SDValue LHSShiftArg = LHSShift.getOperand(0);
3699 SDValue LHSShiftAmt = LHSShift.getOperand(1);
3700 SDValue RHSShiftArg = RHSShift.getOperand(0);
3701 SDValue RHSShiftAmt = RHSShift.getOperand(1);
3703 // fold (or (shl x, C1), (srl x, C2)) -> (rotl x, C1)
3704 // fold (or (shl x, C1), (srl x, C2)) -> (rotr x, C2)
3705 if (LHSShiftAmt.getOpcode() == ISD::Constant &&
3706 RHSShiftAmt.getOpcode() == ISD::Constant) {
3707 uint64_t LShVal = cast<ConstantSDNode>(LHSShiftAmt)->getZExtValue();
3708 uint64_t RShVal = cast<ConstantSDNode>(RHSShiftAmt)->getZExtValue();
3709 if ((LShVal + RShVal) != OpSizeInBits)
3712 SDValue Rot = DAG.getNode(HasROTL ? ISD::ROTL : ISD::ROTR, DL, VT,
3713 LHSShiftArg, HasROTL ? LHSShiftAmt : RHSShiftAmt);
3715 // If there is an AND of either shifted operand, apply it to the result.
3716 if (LHSMask.getNode() || RHSMask.getNode()) {
3717 APInt Mask = APInt::getAllOnesValue(OpSizeInBits);
3719 if (LHSMask.getNode()) {
3720 APInt RHSBits = APInt::getLowBitsSet(OpSizeInBits, LShVal);
3721 Mask &= cast<ConstantSDNode>(LHSMask)->getAPIntValue() | RHSBits;
3723 if (RHSMask.getNode()) {
3724 APInt LHSBits = APInt::getHighBitsSet(OpSizeInBits, RShVal);
3725 Mask &= cast<ConstantSDNode>(RHSMask)->getAPIntValue() | LHSBits;
3728 Rot = DAG.getNode(ISD::AND, DL, VT, Rot, DAG.getConstant(Mask, VT));
3731 return Rot.getNode();
3734 // If there is a mask here, and we have a variable shift, we can't be sure
3735 // that we're masking out the right stuff.
3736 if (LHSMask.getNode() || RHSMask.getNode())
3739 // If the shift amount is sign/zext/any-extended just peel it off.
3740 SDValue LExtOp0 = LHSShiftAmt;
3741 SDValue RExtOp0 = RHSShiftAmt;
3742 if ((LHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND ||
3743 LHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND ||
3744 LHSShiftAmt.getOpcode() == ISD::ANY_EXTEND ||
3745 LHSShiftAmt.getOpcode() == ISD::TRUNCATE) &&
3746 (RHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND ||
3747 RHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND ||
3748 RHSShiftAmt.getOpcode() == ISD::ANY_EXTEND ||
3749 RHSShiftAmt.getOpcode() == ISD::TRUNCATE)) {
3750 LExtOp0 = LHSShiftAmt.getOperand(0);
3751 RExtOp0 = RHSShiftAmt.getOperand(0);
3754 SDNode *TryL = MatchRotatePosNeg(LHSShiftArg, LHSShiftAmt, RHSShiftAmt,
3755 LExtOp0, RExtOp0, ISD::ROTL, ISD::ROTR, DL);
3759 SDNode *TryR = MatchRotatePosNeg(RHSShiftArg, RHSShiftAmt, LHSShiftAmt,
3760 RExtOp0, LExtOp0, ISD::ROTR, ISD::ROTL, DL);
3767 SDValue DAGCombiner::visitXOR(SDNode *N) {
3768 SDValue N0 = N->getOperand(0);
3769 SDValue N1 = N->getOperand(1);
3770 SDValue LHS, RHS, CC;
3771 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
3772 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
3773 EVT VT = N0.getValueType();
3776 if (VT.isVector()) {
3777 SDValue FoldedVOp = SimplifyVBinOp(N);
3778 if (FoldedVOp.getNode()) return FoldedVOp;
3780 // fold (xor x, 0) -> x, vector edition
3781 if (ISD::isBuildVectorAllZeros(N0.getNode()))
3783 if (ISD::isBuildVectorAllZeros(N1.getNode()))
3787 // fold (xor undef, undef) -> 0. This is a common idiom (misuse).
3788 if (N0.getOpcode() == ISD::UNDEF && N1.getOpcode() == ISD::UNDEF)
3789 return DAG.getConstant(0, VT);
3790 // fold (xor x, undef) -> undef
3791 if (N0.getOpcode() == ISD::UNDEF)
3793 if (N1.getOpcode() == ISD::UNDEF)
3795 // fold (xor c1, c2) -> c1^c2
3797 return DAG.FoldConstantArithmetic(ISD::XOR, VT, N0C, N1C);
3798 // canonicalize constant to RHS
3800 return DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0);
3801 // fold (xor x, 0) -> x
3802 if (N1C && N1C->isNullValue())
3805 SDValue RXOR = ReassociateOps(ISD::XOR, SDLoc(N), N0, N1);
3809 // fold !(x cc y) -> (x !cc y)
3810 if (N1C && N1C->getAPIntValue() == 1 && isSetCCEquivalent(N0, LHS, RHS, CC)) {
3811 bool isInt = LHS.getValueType().isInteger();
3812 ISD::CondCode NotCC = ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(),
3815 if (!LegalOperations ||
3816 TLI.isCondCodeLegal(NotCC, LHS.getSimpleValueType())) {
3817 switch (N0.getOpcode()) {
3819 llvm_unreachable("Unhandled SetCC Equivalent!");
3821 return DAG.getSetCC(SDLoc(N), VT, LHS, RHS, NotCC);
3822 case ISD::SELECT_CC:
3823 return DAG.getSelectCC(SDLoc(N), LHS, RHS, N0.getOperand(2),
3824 N0.getOperand(3), NotCC);
3829 // fold (not (zext (setcc x, y))) -> (zext (not (setcc x, y)))
3830 if (N1C && N1C->getAPIntValue() == 1 && N0.getOpcode() == ISD::ZERO_EXTEND &&
3831 N0.getNode()->hasOneUse() &&
3832 isSetCCEquivalent(N0.getOperand(0), LHS, RHS, CC)){
3833 SDValue V = N0.getOperand(0);
3834 V = DAG.getNode(ISD::XOR, SDLoc(N0), V.getValueType(), V,
3835 DAG.getConstant(1, V.getValueType()));
3836 AddToWorklist(V.getNode());
3837 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, V);
3840 // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are setcc
3841 if (N1C && N1C->getAPIntValue() == 1 && VT == MVT::i1 &&
3842 (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
3843 SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
3844 if (isOneUseSetCC(RHS) || isOneUseSetCC(LHS)) {
3845 unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
3846 LHS = DAG.getNode(ISD::XOR, SDLoc(LHS), VT, LHS, N1); // LHS = ~LHS
3847 RHS = DAG.getNode(ISD::XOR, SDLoc(RHS), VT, RHS, N1); // RHS = ~RHS
3848 AddToWorklist(LHS.getNode()); AddToWorklist(RHS.getNode());
3849 return DAG.getNode(NewOpcode, SDLoc(N), VT, LHS, RHS);
3852 // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are constants
3853 if (N1C && N1C->isAllOnesValue() &&
3854 (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
3855 SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
3856 if (isa<ConstantSDNode>(RHS) || isa<ConstantSDNode>(LHS)) {
3857 unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
3858 LHS = DAG.getNode(ISD::XOR, SDLoc(LHS), VT, LHS, N1); // LHS = ~LHS
3859 RHS = DAG.getNode(ISD::XOR, SDLoc(RHS), VT, RHS, N1); // RHS = ~RHS
3860 AddToWorklist(LHS.getNode()); AddToWorklist(RHS.getNode());
3861 return DAG.getNode(NewOpcode, SDLoc(N), VT, LHS, RHS);
3864 // fold (xor (and x, y), y) -> (and (not x), y)
3865 if (N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() &&
3866 N0->getOperand(1) == N1) {
3867 SDValue X = N0->getOperand(0);
3868 SDValue NotX = DAG.getNOT(SDLoc(X), X, VT);
3869 AddToWorklist(NotX.getNode());
3870 return DAG.getNode(ISD::AND, SDLoc(N), VT, NotX, N1);
3872 // fold (xor (xor x, c1), c2) -> (xor x, (xor c1, c2))
3873 if (N1C && N0.getOpcode() == ISD::XOR) {
3874 ConstantSDNode *N00C = dyn_cast<ConstantSDNode>(N0.getOperand(0));
3875 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3877 return DAG.getNode(ISD::XOR, SDLoc(N), VT, N0.getOperand(1),
3878 DAG.getConstant(N1C->getAPIntValue() ^
3879 N00C->getAPIntValue(), VT));
3881 return DAG.getNode(ISD::XOR, SDLoc(N), VT, N0.getOperand(0),
3882 DAG.getConstant(N1C->getAPIntValue() ^
3883 N01C->getAPIntValue(), VT));
3885 // fold (xor x, x) -> 0
3887 return tryFoldToZero(SDLoc(N), TLI, VT, DAG, LegalOperations, LegalTypes);
3889 // Simplify: xor (op x...), (op y...) -> (op (xor x, y))
3890 if (N0.getOpcode() == N1.getOpcode()) {
3891 SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
3892 if (Tmp.getNode()) return Tmp;
3895 // Simplify the expression using non-local knowledge.
3896 if (!VT.isVector() &&
3897 SimplifyDemandedBits(SDValue(N, 0)))
3898 return SDValue(N, 0);
3903 /// Handle transforms common to the three shifts, when the shift amount is a
3905 SDValue DAGCombiner::visitShiftByConstant(SDNode *N, ConstantSDNode *Amt) {
3906 // We can't and shouldn't fold opaque constants.
3907 if (Amt->isOpaque())
3910 SDNode *LHS = N->getOperand(0).getNode();
3911 if (!LHS->hasOneUse()) return SDValue();
3913 // We want to pull some binops through shifts, so that we have (and (shift))
3914 // instead of (shift (and)), likewise for add, or, xor, etc. This sort of
3915 // thing happens with address calculations, so it's important to canonicalize
3917 bool HighBitSet = false; // Can we transform this if the high bit is set?
3919 switch (LHS->getOpcode()) {
3920 default: return SDValue();
3923 HighBitSet = false; // We can only transform sra if the high bit is clear.
3926 HighBitSet = true; // We can only transform sra if the high bit is set.
3929 if (N->getOpcode() != ISD::SHL)
3930 return SDValue(); // only shl(add) not sr[al](add).
3931 HighBitSet = false; // We can only transform sra if the high bit is clear.
3935 // We require the RHS of the binop to be a constant and not opaque as well.
3936 ConstantSDNode *BinOpCst = dyn_cast<ConstantSDNode>(LHS->getOperand(1));
3937 if (!BinOpCst || BinOpCst->isOpaque()) return SDValue();
3939 // FIXME: disable this unless the input to the binop is a shift by a constant.
3940 // If it is not a shift, it pessimizes some common cases like:
3942 // void foo(int *X, int i) { X[i & 1235] = 1; }
3943 // int bar(int *X, int i) { return X[i & 255]; }
3944 SDNode *BinOpLHSVal = LHS->getOperand(0).getNode();
3945 if ((BinOpLHSVal->getOpcode() != ISD::SHL &&
3946 BinOpLHSVal->getOpcode() != ISD::SRA &&
3947 BinOpLHSVal->getOpcode() != ISD::SRL) ||
3948 !isa<ConstantSDNode>(BinOpLHSVal->getOperand(1)))
3951 EVT VT = N->getValueType(0);
3953 // If this is a signed shift right, and the high bit is modified by the
3954 // logical operation, do not perform the transformation. The highBitSet
3955 // boolean indicates the value of the high bit of the constant which would
3956 // cause it to be modified for this operation.
3957 if (N->getOpcode() == ISD::SRA) {
3958 bool BinOpRHSSignSet = BinOpCst->getAPIntValue().isNegative();
3959 if (BinOpRHSSignSet != HighBitSet)
3963 if (!TLI.isDesirableToCommuteWithShift(LHS))
3966 // Fold the constants, shifting the binop RHS by the shift amount.
3967 SDValue NewRHS = DAG.getNode(N->getOpcode(), SDLoc(LHS->getOperand(1)),
3969 LHS->getOperand(1), N->getOperand(1));
3970 assert(isa<ConstantSDNode>(NewRHS) && "Folding was not successful!");
3972 // Create the new shift.
3973 SDValue NewShift = DAG.getNode(N->getOpcode(),
3974 SDLoc(LHS->getOperand(0)),
3975 VT, LHS->getOperand(0), N->getOperand(1));
3977 // Create the new binop.
3978 return DAG.getNode(LHS->getOpcode(), SDLoc(N), VT, NewShift, NewRHS);
3981 SDValue DAGCombiner::distributeTruncateThroughAnd(SDNode *N) {
3982 assert(N->getOpcode() == ISD::TRUNCATE);
3983 assert(N->getOperand(0).getOpcode() == ISD::AND);
3985 // (truncate:TruncVT (and N00, N01C)) -> (and (truncate:TruncVT N00), TruncC)
3986 if (N->hasOneUse() && N->getOperand(0).hasOneUse()) {
3987 SDValue N01 = N->getOperand(0).getOperand(1);
3989 if (ConstantSDNode *N01C = isConstOrConstSplat(N01)) {
3990 EVT TruncVT = N->getValueType(0);
3991 SDValue N00 = N->getOperand(0).getOperand(0);
3992 APInt TruncC = N01C->getAPIntValue();
3993 TruncC = TruncC.trunc(TruncVT.getScalarSizeInBits());
3995 return DAG.getNode(ISD::AND, SDLoc(N), TruncVT,
3996 DAG.getNode(ISD::TRUNCATE, SDLoc(N), TruncVT, N00),
3997 DAG.getConstant(TruncC, TruncVT));
4004 SDValue DAGCombiner::visitRotate(SDNode *N) {
4005 // fold (rot* x, (trunc (and y, c))) -> (rot* x, (and (trunc y), (trunc c))).
4006 if (N->getOperand(1).getOpcode() == ISD::TRUNCATE &&
4007 N->getOperand(1).getOperand(0).getOpcode() == ISD::AND) {
4008 SDValue NewOp1 = distributeTruncateThroughAnd(N->getOperand(1).getNode());
4009 if (NewOp1.getNode())
4010 return DAG.getNode(N->getOpcode(), SDLoc(N), N->getValueType(0),
4011 N->getOperand(0), NewOp1);
4016 SDValue DAGCombiner::visitSHL(SDNode *N) {
4017 SDValue N0 = N->getOperand(0);
4018 SDValue N1 = N->getOperand(1);
4019 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
4020 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4021 EVT VT = N0.getValueType();
4022 unsigned OpSizeInBits = VT.getScalarSizeInBits();
4025 if (VT.isVector()) {
4026 SDValue FoldedVOp = SimplifyVBinOp(N);
4027 if (FoldedVOp.getNode()) return FoldedVOp;
4029 BuildVectorSDNode *N1CV = dyn_cast<BuildVectorSDNode>(N1);
4030 // If setcc produces all-one true value then:
4031 // (shl (and (setcc) N01CV) N1CV) -> (and (setcc) N01CV<<N1CV)
4032 if (N1CV && N1CV->isConstant()) {
4033 if (N0.getOpcode() == ISD::AND) {
4034 SDValue N00 = N0->getOperand(0);
4035 SDValue N01 = N0->getOperand(1);
4036 BuildVectorSDNode *N01CV = dyn_cast<BuildVectorSDNode>(N01);
4038 if (N01CV && N01CV->isConstant() && N00.getOpcode() == ISD::SETCC &&
4039 TLI.getBooleanContents(N00.getOperand(0).getValueType()) ==
4040 TargetLowering::ZeroOrNegativeOneBooleanContent) {
4041 SDValue C = DAG.FoldConstantArithmetic(ISD::SHL, VT, N01CV, N1CV);
4043 return DAG.getNode(ISD::AND, SDLoc(N), VT, N00, C);
4046 N1C = isConstOrConstSplat(N1);
4051 // fold (shl c1, c2) -> c1<<c2
4053 return DAG.FoldConstantArithmetic(ISD::SHL, VT, N0C, N1C);
4054 // fold (shl 0, x) -> 0
4055 if (N0C && N0C->isNullValue())
4057 // fold (shl x, c >= size(x)) -> undef
4058 if (N1C && N1C->getZExtValue() >= OpSizeInBits)
4059 return DAG.getUNDEF(VT);
4060 // fold (shl x, 0) -> x
4061 if (N1C && N1C->isNullValue())
4063 // fold (shl undef, x) -> 0
4064 if (N0.getOpcode() == ISD::UNDEF)
4065 return DAG.getConstant(0, VT);
4066 // if (shl x, c) is known to be zero, return 0
4067 if (DAG.MaskedValueIsZero(SDValue(N, 0),
4068 APInt::getAllOnesValue(OpSizeInBits)))
4069 return DAG.getConstant(0, VT);
4070 // fold (shl x, (trunc (and y, c))) -> (shl x, (and (trunc y), (trunc c))).
4071 if (N1.getOpcode() == ISD::TRUNCATE &&
4072 N1.getOperand(0).getOpcode() == ISD::AND) {
4073 SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode());
4074 if (NewOp1.getNode())
4075 return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0, NewOp1);
4078 if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
4079 return SDValue(N, 0);
4081 // fold (shl (shl x, c1), c2) -> 0 or (shl x, (add c1, c2))
4082 if (N1C && N0.getOpcode() == ISD::SHL) {
4083 if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) {
4084 uint64_t c1 = N0C1->getZExtValue();
4085 uint64_t c2 = N1C->getZExtValue();
4086 if (c1 + c2 >= OpSizeInBits)
4087 return DAG.getConstant(0, VT);
4088 return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0.getOperand(0),
4089 DAG.getConstant(c1 + c2, N1.getValueType()));
4093 // fold (shl (ext (shl x, c1)), c2) -> (ext (shl x, (add c1, c2)))
4094 // For this to be valid, the second form must not preserve any of the bits
4095 // that are shifted out by the inner shift in the first form. This means
4096 // the outer shift size must be >= the number of bits added by the ext.
4097 // As a corollary, we don't care what kind of ext it is.
4098 if (N1C && (N0.getOpcode() == ISD::ZERO_EXTEND ||
4099 N0.getOpcode() == ISD::ANY_EXTEND ||
4100 N0.getOpcode() == ISD::SIGN_EXTEND) &&
4101 N0.getOperand(0).getOpcode() == ISD::SHL) {
4102 SDValue N0Op0 = N0.getOperand(0);
4103 if (ConstantSDNode *N0Op0C1 = isConstOrConstSplat(N0Op0.getOperand(1))) {
4104 uint64_t c1 = N0Op0C1->getZExtValue();
4105 uint64_t c2 = N1C->getZExtValue();
4106 EVT InnerShiftVT = N0Op0.getValueType();
4107 uint64_t InnerShiftSize = InnerShiftVT.getScalarSizeInBits();
4108 if (c2 >= OpSizeInBits - InnerShiftSize) {
4109 if (c1 + c2 >= OpSizeInBits)
4110 return DAG.getConstant(0, VT);
4111 return DAG.getNode(ISD::SHL, SDLoc(N0), VT,
4112 DAG.getNode(N0.getOpcode(), SDLoc(N0), VT,
4113 N0Op0->getOperand(0)),
4114 DAG.getConstant(c1 + c2, N1.getValueType()));
4119 // fold (shl (zext (srl x, C)), C) -> (zext (shl (srl x, C), C))
4120 // Only fold this if the inner zext has no other uses to avoid increasing
4121 // the total number of instructions.
4122 if (N1C && N0.getOpcode() == ISD::ZERO_EXTEND && N0.hasOneUse() &&
4123 N0.getOperand(0).getOpcode() == ISD::SRL) {
4124 SDValue N0Op0 = N0.getOperand(0);
4125 if (ConstantSDNode *N0Op0C1 = isConstOrConstSplat(N0Op0.getOperand(1))) {
4126 uint64_t c1 = N0Op0C1->getZExtValue();
4127 if (c1 < VT.getScalarSizeInBits()) {
4128 uint64_t c2 = N1C->getZExtValue();
4130 SDValue NewOp0 = N0.getOperand(0);
4131 EVT CountVT = NewOp0.getOperand(1).getValueType();
4132 SDValue NewSHL = DAG.getNode(ISD::SHL, SDLoc(N), NewOp0.getValueType(),
4133 NewOp0, DAG.getConstant(c2, CountVT));
4134 AddToWorklist(NewSHL.getNode());
4135 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N0), VT, NewSHL);
4141 // fold (shl (srl x, c1), c2) -> (and (shl x, (sub c2, c1), MASK) or
4142 // (and (srl x, (sub c1, c2), MASK)
4143 // Only fold this if the inner shift has no other uses -- if it does, folding
4144 // this will increase the total number of instructions.
4145 if (N1C && N0.getOpcode() == ISD::SRL && N0.hasOneUse()) {
4146 if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) {
4147 uint64_t c1 = N0C1->getZExtValue();
4148 if (c1 < OpSizeInBits) {
4149 uint64_t c2 = N1C->getZExtValue();
4150 APInt Mask = APInt::getHighBitsSet(OpSizeInBits, OpSizeInBits - c1);
4153 Mask = Mask.shl(c2 - c1);
4154 Shift = DAG.getNode(ISD::SHL, SDLoc(N), VT, N0.getOperand(0),
4155 DAG.getConstant(c2 - c1, N1.getValueType()));
4157 Mask = Mask.lshr(c1 - c2);
4158 Shift = DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0),
4159 DAG.getConstant(c1 - c2, N1.getValueType()));
4161 return DAG.getNode(ISD::AND, SDLoc(N0), VT, Shift,
4162 DAG.getConstant(Mask, VT));
4166 // fold (shl (sra x, c1), c1) -> (and x, (shl -1, c1))
4167 if (N1C && N0.getOpcode() == ISD::SRA && N1 == N0.getOperand(1)) {
4168 unsigned BitSize = VT.getScalarSizeInBits();
4169 SDValue HiBitsMask =
4170 DAG.getConstant(APInt::getHighBitsSet(BitSize,
4171 BitSize - N1C->getZExtValue()), VT);
4172 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0.getOperand(0),
4177 SDValue NewSHL = visitShiftByConstant(N, N1C);
4178 if (NewSHL.getNode())
4185 SDValue DAGCombiner::visitSRA(SDNode *N) {
4186 SDValue N0 = N->getOperand(0);
4187 SDValue N1 = N->getOperand(1);
4188 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
4189 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4190 EVT VT = N0.getValueType();
4191 unsigned OpSizeInBits = VT.getScalarType().getSizeInBits();
4194 if (VT.isVector()) {
4195 SDValue FoldedVOp = SimplifyVBinOp(N);
4196 if (FoldedVOp.getNode()) return FoldedVOp;
4198 N1C = isConstOrConstSplat(N1);
4201 // fold (sra c1, c2) -> (sra c1, c2)
4203 return DAG.FoldConstantArithmetic(ISD::SRA, VT, N0C, N1C);
4204 // fold (sra 0, x) -> 0
4205 if (N0C && N0C->isNullValue())
4207 // fold (sra -1, x) -> -1
4208 if (N0C && N0C->isAllOnesValue())
4210 // fold (sra x, (setge c, size(x))) -> undef
4211 if (N1C && N1C->getZExtValue() >= OpSizeInBits)
4212 return DAG.getUNDEF(VT);
4213 // fold (sra x, 0) -> x
4214 if (N1C && N1C->isNullValue())
4216 // fold (sra (shl x, c1), c1) -> sext_inreg for some c1 and target supports
4218 if (N1C && N0.getOpcode() == ISD::SHL && N1 == N0.getOperand(1)) {
4219 unsigned LowBits = OpSizeInBits - (unsigned)N1C->getZExtValue();
4220 EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), LowBits);
4222 ExtVT = EVT::getVectorVT(*DAG.getContext(),
4223 ExtVT, VT.getVectorNumElements());
4224 if ((!LegalOperations ||
4225 TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, ExtVT)))
4226 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
4227 N0.getOperand(0), DAG.getValueType(ExtVT));
4230 // fold (sra (sra x, c1), c2) -> (sra x, (add c1, c2))
4231 if (N1C && N0.getOpcode() == ISD::SRA) {
4232 if (ConstantSDNode *C1 = isConstOrConstSplat(N0.getOperand(1))) {
4233 unsigned Sum = N1C->getZExtValue() + C1->getZExtValue();
4234 if (Sum >= OpSizeInBits)
4235 Sum = OpSizeInBits - 1;
4236 return DAG.getNode(ISD::SRA, SDLoc(N), VT, N0.getOperand(0),
4237 DAG.getConstant(Sum, N1.getValueType()));
4241 // fold (sra (shl X, m), (sub result_size, n))
4242 // -> (sign_extend (trunc (shl X, (sub (sub result_size, n), m)))) for
4243 // result_size - n != m.
4244 // If truncate is free for the target sext(shl) is likely to result in better
4246 if (N0.getOpcode() == ISD::SHL && N1C) {
4247 // Get the two constanst of the shifts, CN0 = m, CN = n.
4248 const ConstantSDNode *N01C = isConstOrConstSplat(N0.getOperand(1));
4250 LLVMContext &Ctx = *DAG.getContext();
4251 // Determine what the truncate's result bitsize and type would be.
4252 EVT TruncVT = EVT::getIntegerVT(Ctx, OpSizeInBits - N1C->getZExtValue());
4255 TruncVT = EVT::getVectorVT(Ctx, TruncVT, VT.getVectorNumElements());
4257 // Determine the residual right-shift amount.
4258 signed ShiftAmt = N1C->getZExtValue() - N01C->getZExtValue();
4260 // If the shift is not a no-op (in which case this should be just a sign
4261 // extend already), the truncated to type is legal, sign_extend is legal
4262 // on that type, and the truncate to that type is both legal and free,
4263 // perform the transform.
4264 if ((ShiftAmt > 0) &&
4265 TLI.isOperationLegalOrCustom(ISD::SIGN_EXTEND, TruncVT) &&
4266 TLI.isOperationLegalOrCustom(ISD::TRUNCATE, VT) &&
4267 TLI.isTruncateFree(VT, TruncVT)) {
4269 SDValue Amt = DAG.getConstant(ShiftAmt,
4270 getShiftAmountTy(N0.getOperand(0).getValueType()));
4271 SDValue Shift = DAG.getNode(ISD::SRL, SDLoc(N0), VT,
4272 N0.getOperand(0), Amt);
4273 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0), TruncVT,
4275 return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N),
4276 N->getValueType(0), Trunc);
4281 // fold (sra x, (trunc (and y, c))) -> (sra x, (and (trunc y), (trunc c))).
4282 if (N1.getOpcode() == ISD::TRUNCATE &&
4283 N1.getOperand(0).getOpcode() == ISD::AND) {
4284 SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode());
4285 if (NewOp1.getNode())
4286 return DAG.getNode(ISD::SRA, SDLoc(N), VT, N0, NewOp1);
4289 // fold (sra (trunc (srl x, c1)), c2) -> (trunc (sra x, c1 + c2))
4290 // if c1 is equal to the number of bits the trunc removes
4291 if (N0.getOpcode() == ISD::TRUNCATE &&
4292 (N0.getOperand(0).getOpcode() == ISD::SRL ||
4293 N0.getOperand(0).getOpcode() == ISD::SRA) &&
4294 N0.getOperand(0).hasOneUse() &&
4295 N0.getOperand(0).getOperand(1).hasOneUse() &&
4297 SDValue N0Op0 = N0.getOperand(0);
4298 if (ConstantSDNode *LargeShift = isConstOrConstSplat(N0Op0.getOperand(1))) {
4299 unsigned LargeShiftVal = LargeShift->getZExtValue();
4300 EVT LargeVT = N0Op0.getValueType();
4302 if (LargeVT.getScalarSizeInBits() - OpSizeInBits == LargeShiftVal) {
4304 DAG.getConstant(LargeShiftVal + N1C->getZExtValue(),
4305 getShiftAmountTy(N0Op0.getOperand(0).getValueType()));
4306 SDValue SRA = DAG.getNode(ISD::SRA, SDLoc(N), LargeVT,
4307 N0Op0.getOperand(0), Amt);
4308 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, SRA);
4313 // Simplify, based on bits shifted out of the LHS.
4314 if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
4315 return SDValue(N, 0);
4318 // If the sign bit is known to be zero, switch this to a SRL.
4319 if (DAG.SignBitIsZero(N0))
4320 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, N1);
4323 SDValue NewSRA = visitShiftByConstant(N, N1C);
4324 if (NewSRA.getNode())
4331 SDValue DAGCombiner::visitSRL(SDNode *N) {
4332 SDValue N0 = N->getOperand(0);
4333 SDValue N1 = N->getOperand(1);
4334 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
4335 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4336 EVT VT = N0.getValueType();
4337 unsigned OpSizeInBits = VT.getScalarType().getSizeInBits();
4340 if (VT.isVector()) {
4341 SDValue FoldedVOp = SimplifyVBinOp(N);
4342 if (FoldedVOp.getNode()) return FoldedVOp;
4344 N1C = isConstOrConstSplat(N1);
4347 // fold (srl c1, c2) -> c1 >>u c2
4349 return DAG.FoldConstantArithmetic(ISD::SRL, VT, N0C, N1C);
4350 // fold (srl 0, x) -> 0
4351 if (N0C && N0C->isNullValue())
4353 // fold (srl x, c >= size(x)) -> undef
4354 if (N1C && N1C->getZExtValue() >= OpSizeInBits)
4355 return DAG.getUNDEF(VT);
4356 // fold (srl x, 0) -> x
4357 if (N1C && N1C->isNullValue())
4359 // if (srl x, c) is known to be zero, return 0
4360 if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0),
4361 APInt::getAllOnesValue(OpSizeInBits)))
4362 return DAG.getConstant(0, VT);
4364 // fold (srl (srl x, c1), c2) -> 0 or (srl x, (add c1, c2))
4365 if (N1C && N0.getOpcode() == ISD::SRL) {
4366 if (ConstantSDNode *N01C = isConstOrConstSplat(N0.getOperand(1))) {
4367 uint64_t c1 = N01C->getZExtValue();
4368 uint64_t c2 = N1C->getZExtValue();
4369 if (c1 + c2 >= OpSizeInBits)
4370 return DAG.getConstant(0, VT);
4371 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0),
4372 DAG.getConstant(c1 + c2, N1.getValueType()));
4376 // fold (srl (trunc (srl x, c1)), c2) -> 0 or (trunc (srl x, (add c1, c2)))
4377 if (N1C && N0.getOpcode() == ISD::TRUNCATE &&
4378 N0.getOperand(0).getOpcode() == ISD::SRL &&
4379 isa<ConstantSDNode>(N0.getOperand(0)->getOperand(1))) {
4381 cast<ConstantSDNode>(N0.getOperand(0)->getOperand(1))->getZExtValue();
4382 uint64_t c2 = N1C->getZExtValue();
4383 EVT InnerShiftVT = N0.getOperand(0).getValueType();
4384 EVT ShiftCountVT = N0.getOperand(0)->getOperand(1).getValueType();
4385 uint64_t InnerShiftSize = InnerShiftVT.getScalarType().getSizeInBits();
4386 // This is only valid if the OpSizeInBits + c1 = size of inner shift.
4387 if (c1 + OpSizeInBits == InnerShiftSize) {
4388 if (c1 + c2 >= InnerShiftSize)
4389 return DAG.getConstant(0, VT);
4390 return DAG.getNode(ISD::TRUNCATE, SDLoc(N0), VT,
4391 DAG.getNode(ISD::SRL, SDLoc(N0), InnerShiftVT,
4392 N0.getOperand(0)->getOperand(0),
4393 DAG.getConstant(c1 + c2, ShiftCountVT)));
4397 // fold (srl (shl x, c), c) -> (and x, cst2)
4398 if (N1C && N0.getOpcode() == ISD::SHL && N0.getOperand(1) == N1) {
4399 unsigned BitSize = N0.getScalarValueSizeInBits();
4400 if (BitSize <= 64) {
4401 uint64_t ShAmt = N1C->getZExtValue() + 64 - BitSize;
4402 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0.getOperand(0),
4403 DAG.getConstant(~0ULL >> ShAmt, VT));
4407 // fold (srl (anyextend x), c) -> (and (anyextend (srl x, c)), mask)
4408 if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
4409 // Shifting in all undef bits?
4410 EVT SmallVT = N0.getOperand(0).getValueType();
4411 unsigned BitSize = SmallVT.getScalarSizeInBits();
4412 if (N1C->getZExtValue() >= BitSize)
4413 return DAG.getUNDEF(VT);
4415 if (!LegalTypes || TLI.isTypeDesirableForOp(ISD::SRL, SmallVT)) {
4416 uint64_t ShiftAmt = N1C->getZExtValue();
4417 SDValue SmallShift = DAG.getNode(ISD::SRL, SDLoc(N0), SmallVT,
4419 DAG.getConstant(ShiftAmt, getShiftAmountTy(SmallVT)));
4420 AddToWorklist(SmallShift.getNode());
4421 APInt Mask = APInt::getAllOnesValue(OpSizeInBits).lshr(ShiftAmt);
4422 return DAG.getNode(ISD::AND, SDLoc(N), VT,
4423 DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, SmallShift),
4424 DAG.getConstant(Mask, VT));
4428 // fold (srl (sra X, Y), 31) -> (srl X, 31). This srl only looks at the sign
4429 // bit, which is unmodified by sra.
4430 if (N1C && N1C->getZExtValue() + 1 == OpSizeInBits) {
4431 if (N0.getOpcode() == ISD::SRA)
4432 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0), N1);
4435 // fold (srl (ctlz x), "5") -> x iff x has one bit set (the low bit).
4436 if (N1C && N0.getOpcode() == ISD::CTLZ &&
4437 N1C->getAPIntValue() == Log2_32(OpSizeInBits)) {
4438 APInt KnownZero, KnownOne;
4439 DAG.computeKnownBits(N0.getOperand(0), KnownZero, KnownOne);
4441 // If any of the input bits are KnownOne, then the input couldn't be all
4442 // zeros, thus the result of the srl will always be zero.
4443 if (KnownOne.getBoolValue()) return DAG.getConstant(0, VT);
4445 // If all of the bits input the to ctlz node are known to be zero, then
4446 // the result of the ctlz is "32" and the result of the shift is one.
4447 APInt UnknownBits = ~KnownZero;
4448 if (UnknownBits == 0) return DAG.getConstant(1, VT);
4450 // Otherwise, check to see if there is exactly one bit input to the ctlz.
4451 if ((UnknownBits & (UnknownBits - 1)) == 0) {
4452 // Okay, we know that only that the single bit specified by UnknownBits
4453 // could be set on input to the CTLZ node. If this bit is set, the SRL
4454 // will return 0, if it is clear, it returns 1. Change the CTLZ/SRL pair
4455 // to an SRL/XOR pair, which is likely to simplify more.
4456 unsigned ShAmt = UnknownBits.countTrailingZeros();
4457 SDValue Op = N0.getOperand(0);
4460 Op = DAG.getNode(ISD::SRL, SDLoc(N0), VT, Op,
4461 DAG.getConstant(ShAmt, getShiftAmountTy(Op.getValueType())));
4462 AddToWorklist(Op.getNode());
4465 return DAG.getNode(ISD::XOR, SDLoc(N), VT,
4466 Op, DAG.getConstant(1, VT));
4470 // fold (srl x, (trunc (and y, c))) -> (srl x, (and (trunc y), (trunc c))).
4471 if (N1.getOpcode() == ISD::TRUNCATE &&
4472 N1.getOperand(0).getOpcode() == ISD::AND) {
4473 SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode());
4474 if (NewOp1.getNode())
4475 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, NewOp1);
4478 // fold operands of srl based on knowledge that the low bits are not
4480 if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
4481 return SDValue(N, 0);
4484 SDValue NewSRL = visitShiftByConstant(N, N1C);
4485 if (NewSRL.getNode())
4489 // Attempt to convert a srl of a load into a narrower zero-extending load.
4490 SDValue NarrowLoad = ReduceLoadWidth(N);
4491 if (NarrowLoad.getNode())
4494 // Here is a common situation. We want to optimize:
4497 // %b = and i32 %a, 2
4498 // %c = srl i32 %b, 1
4499 // brcond i32 %c ...
4505 // %c = setcc eq %b, 0
4508 // However when after the source operand of SRL is optimized into AND, the SRL
4509 // itself may not be optimized further. Look for it and add the BRCOND into
4511 if (N->hasOneUse()) {
4512 SDNode *Use = *N->use_begin();
4513 if (Use->getOpcode() == ISD::BRCOND)
4515 else if (Use->getOpcode() == ISD::TRUNCATE && Use->hasOneUse()) {
4516 // Also look pass the truncate.
4517 Use = *Use->use_begin();
4518 if (Use->getOpcode() == ISD::BRCOND)
4526 SDValue DAGCombiner::visitCTLZ(SDNode *N) {
4527 SDValue N0 = N->getOperand(0);
4528 EVT VT = N->getValueType(0);
4530 // fold (ctlz c1) -> c2
4531 if (isa<ConstantSDNode>(N0))
4532 return DAG.getNode(ISD::CTLZ, SDLoc(N), VT, N0);
4536 SDValue DAGCombiner::visitCTLZ_ZERO_UNDEF(SDNode *N) {
4537 SDValue N0 = N->getOperand(0);
4538 EVT VT = N->getValueType(0);
4540 // fold (ctlz_zero_undef c1) -> c2
4541 if (isa<ConstantSDNode>(N0))
4542 return DAG.getNode(ISD::CTLZ_ZERO_UNDEF, SDLoc(N), VT, N0);
4546 SDValue DAGCombiner::visitCTTZ(SDNode *N) {
4547 SDValue N0 = N->getOperand(0);
4548 EVT VT = N->getValueType(0);
4550 // fold (cttz c1) -> c2
4551 if (isa<ConstantSDNode>(N0))
4552 return DAG.getNode(ISD::CTTZ, SDLoc(N), VT, N0);
4556 SDValue DAGCombiner::visitCTTZ_ZERO_UNDEF(SDNode *N) {
4557 SDValue N0 = N->getOperand(0);
4558 EVT VT = N->getValueType(0);
4560 // fold (cttz_zero_undef c1) -> c2
4561 if (isa<ConstantSDNode>(N0))
4562 return DAG.getNode(ISD::CTTZ_ZERO_UNDEF, SDLoc(N), VT, N0);
4566 SDValue DAGCombiner::visitCTPOP(SDNode *N) {
4567 SDValue N0 = N->getOperand(0);
4568 EVT VT = N->getValueType(0);
4570 // fold (ctpop c1) -> c2
4571 if (isa<ConstantSDNode>(N0))
4572 return DAG.getNode(ISD::CTPOP, SDLoc(N), VT, N0);
4576 SDValue DAGCombiner::visitSELECT(SDNode *N) {
4577 SDValue N0 = N->getOperand(0);
4578 SDValue N1 = N->getOperand(1);
4579 SDValue N2 = N->getOperand(2);
4580 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
4581 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4582 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2);
4583 EVT VT = N->getValueType(0);
4584 EVT VT0 = N0.getValueType();
4586 // fold (select C, X, X) -> X
4589 // fold (select true, X, Y) -> X
4590 if (N0C && !N0C->isNullValue())
4592 // fold (select false, X, Y) -> Y
4593 if (N0C && N0C->isNullValue())
4595 // fold (select C, 1, X) -> (or C, X)
4596 if (VT == MVT::i1 && N1C && N1C->getAPIntValue() == 1)
4597 return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N2);
4598 // fold (select C, 0, 1) -> (xor C, 1)
4599 // We can't do this reliably if integer based booleans have different contents
4600 // to floating point based booleans. This is because we can't tell whether we
4601 // have an integer-based boolean or a floating-point-based boolean unless we
4602 // can find the SETCC that produced it and inspect its operands. This is
4603 // fairly easy if C is the SETCC node, but it can potentially be
4604 // undiscoverable (or not reasonably discoverable). For example, it could be
4605 // in another basic block or it could require searching a complicated
4607 if (VT.isInteger() &&
4608 (VT0 == MVT::i1 || (VT0.isInteger() &&
4609 TLI.getBooleanContents(false, false) ==
4610 TLI.getBooleanContents(false, true) &&
4611 TLI.getBooleanContents(false, false) ==
4612 TargetLowering::ZeroOrOneBooleanContent)) &&
4613 N1C && N2C && N1C->isNullValue() && N2C->getAPIntValue() == 1) {
4616 return DAG.getNode(ISD::XOR, SDLoc(N), VT0,
4617 N0, DAG.getConstant(1, VT0));
4618 XORNode = DAG.getNode(ISD::XOR, SDLoc(N0), VT0,
4619 N0, DAG.getConstant(1, VT0));
4620 AddToWorklist(XORNode.getNode());
4622 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, XORNode);
4623 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, XORNode);
4625 // fold (select C, 0, X) -> (and (not C), X)
4626 if (VT == VT0 && VT == MVT::i1 && N1C && N1C->isNullValue()) {
4627 SDValue NOTNode = DAG.getNOT(SDLoc(N0), N0, VT);
4628 AddToWorklist(NOTNode.getNode());
4629 return DAG.getNode(ISD::AND, SDLoc(N), VT, NOTNode, N2);
4631 // fold (select C, X, 1) -> (or (not C), X)
4632 if (VT == VT0 && VT == MVT::i1 && N2C && N2C->getAPIntValue() == 1) {
4633 SDValue NOTNode = DAG.getNOT(SDLoc(N0), N0, VT);
4634 AddToWorklist(NOTNode.getNode());
4635 return DAG.getNode(ISD::OR, SDLoc(N), VT, NOTNode, N1);
4637 // fold (select C, X, 0) -> (and C, X)
4638 if (VT == MVT::i1 && N2C && N2C->isNullValue())
4639 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, N1);
4640 // fold (select X, X, Y) -> (or X, Y)
4641 // fold (select X, 1, Y) -> (or X, Y)
4642 if (VT == MVT::i1 && (N0 == N1 || (N1C && N1C->getAPIntValue() == 1)))
4643 return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N2);
4644 // fold (select X, Y, X) -> (and X, Y)
4645 // fold (select X, Y, 0) -> (and X, Y)
4646 if (VT == MVT::i1 && (N0 == N2 || (N2C && N2C->getAPIntValue() == 0)))
4647 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, N1);
4649 // If we can fold this based on the true/false value, do so.
4650 if (SimplifySelectOps(N, N1, N2))
4651 return SDValue(N, 0); // Don't revisit N.
4653 // fold selects based on a setcc into other things, such as min/max/abs
4654 if (N0.getOpcode() == ISD::SETCC) {
4655 if ((!LegalOperations &&
4656 TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT)) ||
4657 TLI.isOperationLegal(ISD::SELECT_CC, VT))
4658 return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT,
4659 N0.getOperand(0), N0.getOperand(1),
4660 N1, N2, N0.getOperand(2));
4661 return SimplifySelect(SDLoc(N), N0, N1, N2);
4668 std::pair<SDValue, SDValue> SplitVSETCC(const SDNode *N, SelectionDAG &DAG) {
4671 std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(N->getValueType(0));
4673 // Split the inputs.
4674 SDValue Lo, Hi, LL, LH, RL, RH;
4675 std::tie(LL, LH) = DAG.SplitVectorOperand(N, 0);
4676 std::tie(RL, RH) = DAG.SplitVectorOperand(N, 1);
4678 Lo = DAG.getNode(N->getOpcode(), DL, LoVT, LL, RL, N->getOperand(2));
4679 Hi = DAG.getNode(N->getOpcode(), DL, HiVT, LH, RH, N->getOperand(2));
4681 return std::make_pair(Lo, Hi);
4684 // This function assumes all the vselect's arguments are CONCAT_VECTOR
4685 // nodes and that the condition is a BV of ConstantSDNodes (or undefs).
4686 static SDValue ConvertSelectToConcatVector(SDNode *N, SelectionDAG &DAG) {
4688 SDValue Cond = N->getOperand(0);
4689 SDValue LHS = N->getOperand(1);
4690 SDValue RHS = N->getOperand(2);
4691 EVT VT = N->getValueType(0);
4692 int NumElems = VT.getVectorNumElements();
4693 assert(LHS.getOpcode() == ISD::CONCAT_VECTORS &&
4694 RHS.getOpcode() == ISD::CONCAT_VECTORS &&
4695 Cond.getOpcode() == ISD::BUILD_VECTOR);
4697 // CONCAT_VECTOR can take an arbitrary number of arguments. We only care about
4698 // binary ones here.
4699 if (LHS->getNumOperands() != 2 || RHS->getNumOperands() != 2)
4702 // We're sure we have an even number of elements due to the
4703 // concat_vectors we have as arguments to vselect.
4704 // Skip BV elements until we find one that's not an UNDEF
4705 // After we find an UNDEF element, keep looping until we get to half the
4706 // length of the BV and see if all the non-undef nodes are the same.
4707 ConstantSDNode *BottomHalf = nullptr;
4708 for (int i = 0; i < NumElems / 2; ++i) {
4709 if (Cond->getOperand(i)->getOpcode() == ISD::UNDEF)
4712 if (BottomHalf == nullptr)
4713 BottomHalf = cast<ConstantSDNode>(Cond.getOperand(i));
4714 else if (Cond->getOperand(i).getNode() != BottomHalf)
4718 // Do the same for the second half of the BuildVector
4719 ConstantSDNode *TopHalf = nullptr;
4720 for (int i = NumElems / 2; i < NumElems; ++i) {
4721 if (Cond->getOperand(i)->getOpcode() == ISD::UNDEF)
4724 if (TopHalf == nullptr)
4725 TopHalf = cast<ConstantSDNode>(Cond.getOperand(i));
4726 else if (Cond->getOperand(i).getNode() != TopHalf)
4730 assert(TopHalf && BottomHalf &&
4731 "One half of the selector was all UNDEFs and the other was all the "
4732 "same value. This should have been addressed before this function.");
4734 ISD::CONCAT_VECTORS, dl, VT,
4735 BottomHalf->isNullValue() ? RHS->getOperand(0) : LHS->getOperand(0),
4736 TopHalf->isNullValue() ? RHS->getOperand(1) : LHS->getOperand(1));
4739 SDValue DAGCombiner::visitVSELECT(SDNode *N) {
4740 SDValue N0 = N->getOperand(0);
4741 SDValue N1 = N->getOperand(1);
4742 SDValue N2 = N->getOperand(2);
4745 // Canonicalize integer abs.
4746 // vselect (setg[te] X, 0), X, -X ->
4747 // vselect (setgt X, -1), X, -X ->
4748 // vselect (setl[te] X, 0), -X, X ->
4749 // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
4750 if (N0.getOpcode() == ISD::SETCC) {
4751 SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
4752 ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
4754 bool RHSIsAllZeros = ISD::isBuildVectorAllZeros(RHS.getNode());
4756 if (((RHSIsAllZeros && (CC == ISD::SETGT || CC == ISD::SETGE)) ||
4757 (ISD::isBuildVectorAllOnes(RHS.getNode()) && CC == ISD::SETGT)) &&
4758 N1 == LHS && N2.getOpcode() == ISD::SUB && N1 == N2.getOperand(1))
4759 isAbs = ISD::isBuildVectorAllZeros(N2.getOperand(0).getNode());
4760 else if ((RHSIsAllZeros && (CC == ISD::SETLT || CC == ISD::SETLE)) &&
4761 N2 == LHS && N1.getOpcode() == ISD::SUB && N2 == N1.getOperand(1))
4762 isAbs = ISD::isBuildVectorAllZeros(N1.getOperand(0).getNode());
4765 EVT VT = LHS.getValueType();
4766 SDValue Shift = DAG.getNode(
4767 ISD::SRA, DL, VT, LHS,
4768 DAG.getConstant(VT.getScalarType().getSizeInBits() - 1, VT));
4769 SDValue Add = DAG.getNode(ISD::ADD, DL, VT, LHS, Shift);
4770 AddToWorklist(Shift.getNode());
4771 AddToWorklist(Add.getNode());
4772 return DAG.getNode(ISD::XOR, DL, VT, Add, Shift);
4776 // If the VSELECT result requires splitting and the mask is provided by a
4777 // SETCC, then split both nodes and its operands before legalization. This
4778 // prevents the type legalizer from unrolling SETCC into scalar comparisons
4779 // and enables future optimizations (e.g. min/max pattern matching on X86).
4780 if (N0.getOpcode() == ISD::SETCC) {
4781 EVT VT = N->getValueType(0);
4783 // Check if any splitting is required.
4784 if (TLI.getTypeAction(*DAG.getContext(), VT) !=
4785 TargetLowering::TypeSplitVector)
4788 SDValue Lo, Hi, CCLo, CCHi, LL, LH, RL, RH;
4789 std::tie(CCLo, CCHi) = SplitVSETCC(N0.getNode(), DAG);
4790 std::tie(LL, LH) = DAG.SplitVectorOperand(N, 1);
4791 std::tie(RL, RH) = DAG.SplitVectorOperand(N, 2);
4793 Lo = DAG.getNode(N->getOpcode(), DL, LL.getValueType(), CCLo, LL, RL);
4794 Hi = DAG.getNode(N->getOpcode(), DL, LH.getValueType(), CCHi, LH, RH);
4796 // Add the new VSELECT nodes to the work list in case they need to be split
4798 AddToWorklist(Lo.getNode());
4799 AddToWorklist(Hi.getNode());
4801 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
4804 // Fold (vselect (build_vector all_ones), N1, N2) -> N1
4805 if (ISD::isBuildVectorAllOnes(N0.getNode()))
4807 // Fold (vselect (build_vector all_zeros), N1, N2) -> N2
4808 if (ISD::isBuildVectorAllZeros(N0.getNode()))
4811 // The ConvertSelectToConcatVector function is assuming both the above
4812 // checks for (vselect (build_vector all{ones,zeros) ...) have been made
4814 if (N1.getOpcode() == ISD::CONCAT_VECTORS &&
4815 N2.getOpcode() == ISD::CONCAT_VECTORS &&
4816 ISD::isBuildVectorOfConstantSDNodes(N0.getNode())) {
4817 SDValue CV = ConvertSelectToConcatVector(N, DAG);
4825 SDValue DAGCombiner::visitSELECT_CC(SDNode *N) {
4826 SDValue N0 = N->getOperand(0);
4827 SDValue N1 = N->getOperand(1);
4828 SDValue N2 = N->getOperand(2);
4829 SDValue N3 = N->getOperand(3);
4830 SDValue N4 = N->getOperand(4);
4831 ISD::CondCode CC = cast<CondCodeSDNode>(N4)->get();
4833 // fold select_cc lhs, rhs, x, x, cc -> x
4837 // Determine if the condition we're dealing with is constant
4838 SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()),
4839 N0, N1, CC, SDLoc(N), false);
4840 if (SCC.getNode()) {
4841 AddToWorklist(SCC.getNode());
4843 if (ConstantSDNode *SCCC = dyn_cast<ConstantSDNode>(SCC.getNode())) {
4844 if (!SCCC->isNullValue())
4845 return N2; // cond always true -> true val
4847 return N3; // cond always false -> false val
4850 // Fold to a simpler select_cc
4851 if (SCC.getOpcode() == ISD::SETCC)
4852 return DAG.getNode(ISD::SELECT_CC, SDLoc(N), N2.getValueType(),
4853 SCC.getOperand(0), SCC.getOperand(1), N2, N3,
4857 // If we can fold this based on the true/false value, do so.
4858 if (SimplifySelectOps(N, N2, N3))
4859 return SDValue(N, 0); // Don't revisit N.
4861 // fold select_cc into other things, such as min/max/abs
4862 return SimplifySelectCC(SDLoc(N), N0, N1, N2, N3, CC);
4865 SDValue DAGCombiner::visitSETCC(SDNode *N) {
4866 return SimplifySetCC(N->getValueType(0), N->getOperand(0), N->getOperand(1),
4867 cast<CondCodeSDNode>(N->getOperand(2))->get(),
4871 // tryToFoldExtendOfConstant - Try to fold a sext/zext/aext
4872 // dag node into a ConstantSDNode or a build_vector of constants.
4873 // This function is called by the DAGCombiner when visiting sext/zext/aext
4874 // dag nodes (see for example method DAGCombiner::visitSIGN_EXTEND).
4875 // Vector extends are not folded if operations are legal; this is to
4876 // avoid introducing illegal build_vector dag nodes.
4877 static SDNode *tryToFoldExtendOfConstant(SDNode *N, const TargetLowering &TLI,
4878 SelectionDAG &DAG, bool LegalTypes,
4879 bool LegalOperations) {
4880 unsigned Opcode = N->getOpcode();
4881 SDValue N0 = N->getOperand(0);
4882 EVT VT = N->getValueType(0);
4884 assert((Opcode == ISD::SIGN_EXTEND || Opcode == ISD::ZERO_EXTEND ||
4885 Opcode == ISD::ANY_EXTEND) && "Expected EXTEND dag node in input!");
4887 // fold (sext c1) -> c1
4888 // fold (zext c1) -> c1
4889 // fold (aext c1) -> c1
4890 if (isa<ConstantSDNode>(N0))
4891 return DAG.getNode(Opcode, SDLoc(N), VT, N0).getNode();
4893 // fold (sext (build_vector AllConstants) -> (build_vector AllConstants)
4894 // fold (zext (build_vector AllConstants) -> (build_vector AllConstants)
4895 // fold (aext (build_vector AllConstants) -> (build_vector AllConstants)
4896 EVT SVT = VT.getScalarType();
4897 if (!(VT.isVector() &&
4898 (!LegalTypes || (!LegalOperations && TLI.isTypeLegal(SVT))) &&
4899 ISD::isBuildVectorOfConstantSDNodes(N0.getNode())))
4902 // We can fold this node into a build_vector.
4903 unsigned VTBits = SVT.getSizeInBits();
4904 unsigned EVTBits = N0->getValueType(0).getScalarType().getSizeInBits();
4905 unsigned ShAmt = VTBits - EVTBits;
4906 SmallVector<SDValue, 8> Elts;
4907 unsigned NumElts = N0->getNumOperands();
4910 for (unsigned i=0; i != NumElts; ++i) {
4911 SDValue Op = N0->getOperand(i);
4912 if (Op->getOpcode() == ISD::UNDEF) {
4913 Elts.push_back(DAG.getUNDEF(SVT));
4917 ConstantSDNode *CurrentND = cast<ConstantSDNode>(Op);
4918 const APInt &C = APInt(VTBits, CurrentND->getAPIntValue().getZExtValue());
4919 if (Opcode == ISD::SIGN_EXTEND)
4920 Elts.push_back(DAG.getConstant(C.shl(ShAmt).ashr(ShAmt).getZExtValue(),
4923 Elts.push_back(DAG.getConstant(C.shl(ShAmt).lshr(ShAmt).getZExtValue(),
4927 return DAG.getNode(ISD::BUILD_VECTOR, DL, VT, Elts).getNode();
4930 // ExtendUsesToFormExtLoad - Trying to extend uses of a load to enable this:
4931 // "fold ({s|z|a}ext (load x)) -> ({s|z|a}ext (truncate ({s|z|a}extload x)))"
4932 // transformation. Returns true if extension are possible and the above
4933 // mentioned transformation is profitable.
4934 static bool ExtendUsesToFormExtLoad(SDNode *N, SDValue N0,
4936 SmallVectorImpl<SDNode *> &ExtendNodes,
4937 const TargetLowering &TLI) {
4938 bool HasCopyToRegUses = false;
4939 bool isTruncFree = TLI.isTruncateFree(N->getValueType(0), N0.getValueType());
4940 for (SDNode::use_iterator UI = N0.getNode()->use_begin(),
4941 UE = N0.getNode()->use_end();
4946 if (UI.getUse().getResNo() != N0.getResNo())
4948 // FIXME: Only extend SETCC N, N and SETCC N, c for now.
4949 if (ExtOpc != ISD::ANY_EXTEND && User->getOpcode() == ISD::SETCC) {
4950 ISD::CondCode CC = cast<CondCodeSDNode>(User->getOperand(2))->get();
4951 if (ExtOpc == ISD::ZERO_EXTEND && ISD::isSignedIntSetCC(CC))
4952 // Sign bits will be lost after a zext.
4955 for (unsigned i = 0; i != 2; ++i) {
4956 SDValue UseOp = User->getOperand(i);
4959 if (!isa<ConstantSDNode>(UseOp))
4964 ExtendNodes.push_back(User);
4967 // If truncates aren't free and there are users we can't
4968 // extend, it isn't worthwhile.
4971 // Remember if this value is live-out.
4972 if (User->getOpcode() == ISD::CopyToReg)
4973 HasCopyToRegUses = true;
4976 if (HasCopyToRegUses) {
4977 bool BothLiveOut = false;
4978 for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
4980 SDUse &Use = UI.getUse();
4981 if (Use.getResNo() == 0 && Use.getUser()->getOpcode() == ISD::CopyToReg) {
4987 // Both unextended and extended values are live out. There had better be
4988 // a good reason for the transformation.
4989 return ExtendNodes.size();
4994 void DAGCombiner::ExtendSetCCUses(const SmallVectorImpl<SDNode *> &SetCCs,
4995 SDValue Trunc, SDValue ExtLoad, SDLoc DL,
4996 ISD::NodeType ExtType) {
4997 // Extend SetCC uses if necessary.
4998 for (unsigned i = 0, e = SetCCs.size(); i != e; ++i) {
4999 SDNode *SetCC = SetCCs[i];
5000 SmallVector<SDValue, 4> Ops;
5002 for (unsigned j = 0; j != 2; ++j) {
5003 SDValue SOp = SetCC->getOperand(j);
5005 Ops.push_back(ExtLoad);
5007 Ops.push_back(DAG.getNode(ExtType, DL, ExtLoad->getValueType(0), SOp));
5010 Ops.push_back(SetCC->getOperand(2));
5011 CombineTo(SetCC, DAG.getNode(ISD::SETCC, DL, SetCC->getValueType(0), Ops));
5015 SDValue DAGCombiner::visitSIGN_EXTEND(SDNode *N) {
5016 SDValue N0 = N->getOperand(0);
5017 EVT VT = N->getValueType(0);
5019 if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
5021 return SDValue(Res, 0);
5023 // fold (sext (sext x)) -> (sext x)
5024 // fold (sext (aext x)) -> (sext x)
5025 if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
5026 return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT,
5029 if (N0.getOpcode() == ISD::TRUNCATE) {
5030 // fold (sext (truncate (load x))) -> (sext (smaller load x))
5031 // fold (sext (truncate (srl (load x), c))) -> (sext (smaller load (x+c/n)))
5032 SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
5033 if (NarrowLoad.getNode()) {
5034 SDNode* oye = N0.getNode()->getOperand(0).getNode();
5035 if (NarrowLoad.getNode() != N0.getNode()) {
5036 CombineTo(N0.getNode(), NarrowLoad);
5037 // CombineTo deleted the truncate, if needed, but not what's under it.
5040 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5043 // See if the value being truncated is already sign extended. If so, just
5044 // eliminate the trunc/sext pair.
5045 SDValue Op = N0.getOperand(0);
5046 unsigned OpBits = Op.getValueType().getScalarType().getSizeInBits();
5047 unsigned MidBits = N0.getValueType().getScalarType().getSizeInBits();
5048 unsigned DestBits = VT.getScalarType().getSizeInBits();
5049 unsigned NumSignBits = DAG.ComputeNumSignBits(Op);
5051 if (OpBits == DestBits) {
5052 // Op is i32, Mid is i8, and Dest is i32. If Op has more than 24 sign
5053 // bits, it is already ready.
5054 if (NumSignBits > DestBits-MidBits)
5056 } else if (OpBits < DestBits) {
5057 // Op is i32, Mid is i8, and Dest is i64. If Op has more than 24 sign
5058 // bits, just sext from i32.
5059 if (NumSignBits > OpBits-MidBits)
5060 return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, Op);
5062 // Op is i64, Mid is i8, and Dest is i32. If Op has more than 56 sign
5063 // bits, just truncate to i32.
5064 if (NumSignBits > OpBits-MidBits)
5065 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
5068 // fold (sext (truncate x)) -> (sextinreg x).
5069 if (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG,
5070 N0.getValueType())) {
5071 if (OpBits < DestBits)
5072 Op = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N0), VT, Op);
5073 else if (OpBits > DestBits)
5074 Op = DAG.getNode(ISD::TRUNCATE, SDLoc(N0), VT, Op);
5075 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, Op,
5076 DAG.getValueType(N0.getValueType()));
5080 // fold (sext (load x)) -> (sext (truncate (sextload x)))
5081 // None of the supported targets knows how to perform load and sign extend
5082 // on vectors in one instruction. We only perform this transformation on
5084 if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() &&
5085 ISD::isUNINDEXEDLoad(N0.getNode()) &&
5086 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
5087 TLI.isLoadExtLegal(ISD::SEXTLOAD, N0.getValueType()))) {
5088 bool DoXform = true;
5089 SmallVector<SDNode*, 4> SetCCs;
5090 if (!N0.hasOneUse())
5091 DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::SIGN_EXTEND, SetCCs, TLI);
5093 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5094 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
5096 LN0->getBasePtr(), N0.getValueType(),
5097 LN0->getMemOperand());
5098 CombineTo(N, ExtLoad);
5099 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
5100 N0.getValueType(), ExtLoad);
5101 CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
5102 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
5104 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5108 // fold (sext (sextload x)) -> (sext (truncate (sextload x)))
5109 // fold (sext ( extload x)) -> (sext (truncate (sextload x)))
5110 if ((ISD::isSEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) &&
5111 ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) {
5112 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5113 EVT MemVT = LN0->getMemoryVT();
5114 if ((!LegalOperations && !LN0->isVolatile()) ||
5115 TLI.isLoadExtLegal(ISD::SEXTLOAD, MemVT)) {
5116 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
5118 LN0->getBasePtr(), MemVT,
5119 LN0->getMemOperand());
5120 CombineTo(N, ExtLoad);
5121 CombineTo(N0.getNode(),
5122 DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
5123 N0.getValueType(), ExtLoad),
5124 ExtLoad.getValue(1));
5125 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5129 // fold (sext (and/or/xor (load x), cst)) ->
5130 // (and/or/xor (sextload x), (sext cst))
5131 if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR ||
5132 N0.getOpcode() == ISD::XOR) &&
5133 isa<LoadSDNode>(N0.getOperand(0)) &&
5134 N0.getOperand(1).getOpcode() == ISD::Constant &&
5135 TLI.isLoadExtLegal(ISD::SEXTLOAD, N0.getValueType()) &&
5136 (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) {
5137 LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0));
5138 if (LN0->getExtensionType() != ISD::ZEXTLOAD && LN0->isUnindexed()) {
5139 bool DoXform = true;
5140 SmallVector<SDNode*, 4> SetCCs;
5141 if (!N0.hasOneUse())
5142 DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0), ISD::SIGN_EXTEND,
5145 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(LN0), VT,
5146 LN0->getChain(), LN0->getBasePtr(),
5148 LN0->getMemOperand());
5149 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
5150 Mask = Mask.sext(VT.getSizeInBits());
5151 SDValue And = DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
5152 ExtLoad, DAG.getConstant(Mask, VT));
5153 SDValue Trunc = DAG.getNode(ISD::TRUNCATE,
5154 SDLoc(N0.getOperand(0)),
5155 N0.getOperand(0).getValueType(), ExtLoad);
5157 CombineTo(N0.getOperand(0).getNode(), Trunc, ExtLoad.getValue(1));
5158 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
5160 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5165 if (N0.getOpcode() == ISD::SETCC) {
5166 EVT N0VT = N0.getOperand(0).getValueType();
5167 // sext(setcc) -> sext_in_reg(vsetcc) for vectors.
5168 // Only do this before legalize for now.
5169 if (VT.isVector() && !LegalOperations &&
5170 TLI.getBooleanContents(N0VT) ==
5171 TargetLowering::ZeroOrNegativeOneBooleanContent) {
5172 // On some architectures (such as SSE/NEON/etc) the SETCC result type is
5173 // of the same size as the compared operands. Only optimize sext(setcc())
5174 // if this is the case.
5175 EVT SVT = getSetCCResultType(N0VT);
5177 // We know that the # elements of the results is the same as the
5178 // # elements of the compare (and the # elements of the compare result
5179 // for that matter). Check to see that they are the same size. If so,
5180 // we know that the element size of the sext'd result matches the
5181 // element size of the compare operands.
5182 if (VT.getSizeInBits() == SVT.getSizeInBits())
5183 return DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
5185 cast<CondCodeSDNode>(N0.getOperand(2))->get());
5187 // If the desired elements are smaller or larger than the source
5188 // elements we can use a matching integer vector type and then
5189 // truncate/sign extend
5190 EVT MatchingVectorType = N0VT.changeVectorElementTypeToInteger();
5191 if (SVT == MatchingVectorType) {
5192 SDValue VsetCC = DAG.getSetCC(SDLoc(N), MatchingVectorType,
5193 N0.getOperand(0), N0.getOperand(1),
5194 cast<CondCodeSDNode>(N0.getOperand(2))->get());
5195 return DAG.getSExtOrTrunc(VsetCC, SDLoc(N), VT);
5199 // sext(setcc x, y, cc) -> (select (setcc x, y, cc), -1, 0)
5200 unsigned ElementWidth = VT.getScalarType().getSizeInBits();
5202 DAG.getConstant(APInt::getAllOnesValue(ElementWidth), VT);
5204 SimplifySelectCC(SDLoc(N), N0.getOperand(0), N0.getOperand(1),
5205 NegOne, DAG.getConstant(0, VT),
5206 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
5207 if (SCC.getNode()) return SCC;
5209 if (!VT.isVector()) {
5210 EVT SetCCVT = getSetCCResultType(N0.getOperand(0).getValueType());
5211 if (!LegalOperations || TLI.isOperationLegal(ISD::SETCC, SetCCVT)) {
5213 ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
5214 SDValue SetCC = DAG.getSetCC(DL,
5216 N0.getOperand(0), N0.getOperand(1), CC);
5217 EVT SelectVT = getSetCCResultType(VT);
5218 return DAG.getSelect(DL, VT,
5219 DAG.getSExtOrTrunc(SetCC, DL, SelectVT),
5220 NegOne, DAG.getConstant(0, VT));
5226 // fold (sext x) -> (zext x) if the sign bit is known zero.
5227 if ((!LegalOperations || TLI.isOperationLegal(ISD::ZERO_EXTEND, VT)) &&
5228 DAG.SignBitIsZero(N0))
5229 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, N0);
5234 // isTruncateOf - If N is a truncate of some other value, return true, record
5235 // the value being truncated in Op and which of Op's bits are zero in KnownZero.
5236 // This function computes KnownZero to avoid a duplicated call to
5237 // computeKnownBits in the caller.
5238 static bool isTruncateOf(SelectionDAG &DAG, SDValue N, SDValue &Op,
5241 if (N->getOpcode() == ISD::TRUNCATE) {
5242 Op = N->getOperand(0);
5243 DAG.computeKnownBits(Op, KnownZero, KnownOne);
5247 if (N->getOpcode() != ISD::SETCC || N->getValueType(0) != MVT::i1 ||
5248 cast<CondCodeSDNode>(N->getOperand(2))->get() != ISD::SETNE)
5251 SDValue Op0 = N->getOperand(0);
5252 SDValue Op1 = N->getOperand(1);
5253 assert(Op0.getValueType() == Op1.getValueType());
5255 ConstantSDNode *COp0 = dyn_cast<ConstantSDNode>(Op0);
5256 ConstantSDNode *COp1 = dyn_cast<ConstantSDNode>(Op1);
5257 if (COp0 && COp0->isNullValue())
5259 else if (COp1 && COp1->isNullValue())
5264 DAG.computeKnownBits(Op, KnownZero, KnownOne);
5266 if (!(KnownZero | APInt(Op.getValueSizeInBits(), 1)).isAllOnesValue())
5272 SDValue DAGCombiner::visitZERO_EXTEND(SDNode *N) {
5273 SDValue N0 = N->getOperand(0);
5274 EVT VT = N->getValueType(0);
5276 if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
5278 return SDValue(Res, 0);
5280 // fold (zext (zext x)) -> (zext x)
5281 // fold (zext (aext x)) -> (zext x)
5282 if (N0.getOpcode() == ISD::ZERO_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
5283 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT,
5286 // fold (zext (truncate x)) -> (zext x) or
5287 // (zext (truncate x)) -> (truncate x)
5288 // This is valid when the truncated bits of x are already zero.
5289 // FIXME: We should extend this to work for vectors too.
5292 if (!VT.isVector() && isTruncateOf(DAG, N0, Op, KnownZero)) {
5293 APInt TruncatedBits =
5294 (Op.getValueSizeInBits() == N0.getValueSizeInBits()) ?
5295 APInt(Op.getValueSizeInBits(), 0) :
5296 APInt::getBitsSet(Op.getValueSizeInBits(),
5297 N0.getValueSizeInBits(),
5298 std::min(Op.getValueSizeInBits(),
5299 VT.getSizeInBits()));
5300 if (TruncatedBits == (KnownZero & TruncatedBits)) {
5301 if (VT.bitsGT(Op.getValueType()))
5302 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, Op);
5303 if (VT.bitsLT(Op.getValueType()))
5304 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
5310 // fold (zext (truncate (load x))) -> (zext (smaller load x))
5311 // fold (zext (truncate (srl (load x), c))) -> (zext (small load (x+c/n)))
5312 if (N0.getOpcode() == ISD::TRUNCATE) {
5313 SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
5314 if (NarrowLoad.getNode()) {
5315 SDNode* oye = N0.getNode()->getOperand(0).getNode();
5316 if (NarrowLoad.getNode() != N0.getNode()) {
5317 CombineTo(N0.getNode(), NarrowLoad);
5318 // CombineTo deleted the truncate, if needed, but not what's under it.
5321 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5325 // fold (zext (truncate x)) -> (and x, mask)
5326 if (N0.getOpcode() == ISD::TRUNCATE &&
5327 (!LegalOperations || TLI.isOperationLegal(ISD::AND, VT))) {
5329 // fold (zext (truncate (load x))) -> (zext (smaller load x))
5330 // fold (zext (truncate (srl (load x), c))) -> (zext (smaller load (x+c/n)))
5331 SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
5332 if (NarrowLoad.getNode()) {
5333 SDNode* oye = N0.getNode()->getOperand(0).getNode();
5334 if (NarrowLoad.getNode() != N0.getNode()) {
5335 CombineTo(N0.getNode(), NarrowLoad);
5336 // CombineTo deleted the truncate, if needed, but not what's under it.
5339 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5342 SDValue Op = N0.getOperand(0);
5343 if (Op.getValueType().bitsLT(VT)) {
5344 Op = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, Op);
5345 AddToWorklist(Op.getNode());
5346 } else if (Op.getValueType().bitsGT(VT)) {
5347 Op = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
5348 AddToWorklist(Op.getNode());
5350 return DAG.getZeroExtendInReg(Op, SDLoc(N),
5351 N0.getValueType().getScalarType());
5354 // Fold (zext (and (trunc x), cst)) -> (and x, cst),
5355 // if either of the casts is not free.
5356 if (N0.getOpcode() == ISD::AND &&
5357 N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
5358 N0.getOperand(1).getOpcode() == ISD::Constant &&
5359 (!TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(),
5360 N0.getValueType()) ||
5361 !TLI.isZExtFree(N0.getValueType(), VT))) {
5362 SDValue X = N0.getOperand(0).getOperand(0);
5363 if (X.getValueType().bitsLT(VT)) {
5364 X = DAG.getNode(ISD::ANY_EXTEND, SDLoc(X), VT, X);
5365 } else if (X.getValueType().bitsGT(VT)) {
5366 X = DAG.getNode(ISD::TRUNCATE, SDLoc(X), VT, X);
5368 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
5369 Mask = Mask.zext(VT.getSizeInBits());
5370 return DAG.getNode(ISD::AND, SDLoc(N), VT,
5371 X, DAG.getConstant(Mask, VT));
5374 // fold (zext (load x)) -> (zext (truncate (zextload x)))
5375 // None of the supported targets knows how to perform load and vector_zext
5376 // on vectors in one instruction. We only perform this transformation on
5378 if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() &&
5379 ISD::isUNINDEXEDLoad(N0.getNode()) &&
5380 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
5381 TLI.isLoadExtLegal(ISD::ZEXTLOAD, N0.getValueType()))) {
5382 bool DoXform = true;
5383 SmallVector<SDNode*, 4> SetCCs;
5384 if (!N0.hasOneUse())
5385 DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ZERO_EXTEND, SetCCs, TLI);
5387 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5388 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT,
5390 LN0->getBasePtr(), N0.getValueType(),
5391 LN0->getMemOperand());
5392 CombineTo(N, ExtLoad);
5393 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
5394 N0.getValueType(), ExtLoad);
5395 CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
5397 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
5399 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5403 // fold (zext (and/or/xor (load x), cst)) ->
5404 // (and/or/xor (zextload x), (zext cst))
5405 if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR ||
5406 N0.getOpcode() == ISD::XOR) &&
5407 isa<LoadSDNode>(N0.getOperand(0)) &&
5408 N0.getOperand(1).getOpcode() == ISD::Constant &&
5409 TLI.isLoadExtLegal(ISD::ZEXTLOAD, N0.getValueType()) &&
5410 (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) {
5411 LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0));
5412 if (LN0->getExtensionType() != ISD::SEXTLOAD && LN0->isUnindexed()) {
5413 bool DoXform = true;
5414 SmallVector<SDNode*, 4> SetCCs;
5415 if (!N0.hasOneUse())
5416 DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0), ISD::ZERO_EXTEND,
5419 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), VT,
5420 LN0->getChain(), LN0->getBasePtr(),
5422 LN0->getMemOperand());
5423 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
5424 Mask = Mask.zext(VT.getSizeInBits());
5425 SDValue And = DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
5426 ExtLoad, DAG.getConstant(Mask, VT));
5427 SDValue Trunc = DAG.getNode(ISD::TRUNCATE,
5428 SDLoc(N0.getOperand(0)),
5429 N0.getOperand(0).getValueType(), ExtLoad);
5431 CombineTo(N0.getOperand(0).getNode(), Trunc, ExtLoad.getValue(1));
5432 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
5434 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5439 // fold (zext (zextload x)) -> (zext (truncate (zextload x)))
5440 // fold (zext ( extload x)) -> (zext (truncate (zextload x)))
5441 if ((ISD::isZEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) &&
5442 ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) {
5443 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5444 EVT MemVT = LN0->getMemoryVT();
5445 if ((!LegalOperations && !LN0->isVolatile()) ||
5446 TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT)) {
5447 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT,
5449 LN0->getBasePtr(), MemVT,
5450 LN0->getMemOperand());
5451 CombineTo(N, ExtLoad);
5452 CombineTo(N0.getNode(),
5453 DAG.getNode(ISD::TRUNCATE, SDLoc(N0), N0.getValueType(),
5455 ExtLoad.getValue(1));
5456 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5460 if (N0.getOpcode() == ISD::SETCC) {
5461 if (!LegalOperations && VT.isVector() &&
5462 N0.getValueType().getVectorElementType() == MVT::i1) {
5463 EVT N0VT = N0.getOperand(0).getValueType();
5464 if (getSetCCResultType(N0VT) == N0.getValueType())
5467 // zext(setcc) -> (and (vsetcc), (1, 1, ...) for vectors.
5468 // Only do this before legalize for now.
5469 EVT EltVT = VT.getVectorElementType();
5470 SmallVector<SDValue,8> OneOps(VT.getVectorNumElements(),
5471 DAG.getConstant(1, EltVT));
5472 if (VT.getSizeInBits() == N0VT.getSizeInBits())
5473 // We know that the # elements of the results is the same as the
5474 // # elements of the compare (and the # elements of the compare result
5475 // for that matter). Check to see that they are the same size. If so,
5476 // we know that the element size of the sext'd result matches the
5477 // element size of the compare operands.
5478 return DAG.getNode(ISD::AND, SDLoc(N), VT,
5479 DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
5481 cast<CondCodeSDNode>(N0.getOperand(2))->get()),
5482 DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT,
5485 // If the desired elements are smaller or larger than the source
5486 // elements we can use a matching integer vector type and then
5487 // truncate/sign extend
5488 EVT MatchingElementType =
5489 EVT::getIntegerVT(*DAG.getContext(),
5490 N0VT.getScalarType().getSizeInBits());
5491 EVT MatchingVectorType =
5492 EVT::getVectorVT(*DAG.getContext(), MatchingElementType,
5493 N0VT.getVectorNumElements());
5495 DAG.getSetCC(SDLoc(N), MatchingVectorType, N0.getOperand(0),
5497 cast<CondCodeSDNode>(N0.getOperand(2))->get());
5498 return DAG.getNode(ISD::AND, SDLoc(N), VT,
5499 DAG.getSExtOrTrunc(VsetCC, SDLoc(N), VT),
5500 DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, OneOps));
5503 // zext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
5505 SimplifySelectCC(SDLoc(N), N0.getOperand(0), N0.getOperand(1),
5506 DAG.getConstant(1, VT), DAG.getConstant(0, VT),
5507 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
5508 if (SCC.getNode()) return SCC;
5511 // (zext (shl (zext x), cst)) -> (shl (zext x), cst)
5512 if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL) &&
5513 isa<ConstantSDNode>(N0.getOperand(1)) &&
5514 N0.getOperand(0).getOpcode() == ISD::ZERO_EXTEND &&
5516 SDValue ShAmt = N0.getOperand(1);
5517 unsigned ShAmtVal = cast<ConstantSDNode>(ShAmt)->getZExtValue();
5518 if (N0.getOpcode() == ISD::SHL) {
5519 SDValue InnerZExt = N0.getOperand(0);
5520 // If the original shl may be shifting out bits, do not perform this
5522 unsigned KnownZeroBits = InnerZExt.getValueType().getSizeInBits() -
5523 InnerZExt.getOperand(0).getValueType().getSizeInBits();
5524 if (ShAmtVal > KnownZeroBits)
5530 // Ensure that the shift amount is wide enough for the shifted value.
5531 if (VT.getSizeInBits() >= 256)
5532 ShAmt = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, ShAmt);
5534 return DAG.getNode(N0.getOpcode(), DL, VT,
5535 DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0)),
5542 SDValue DAGCombiner::visitANY_EXTEND(SDNode *N) {
5543 SDValue N0 = N->getOperand(0);
5544 EVT VT = N->getValueType(0);
5546 if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
5548 return SDValue(Res, 0);
5550 // fold (aext (aext x)) -> (aext x)
5551 // fold (aext (zext x)) -> (zext x)
5552 // fold (aext (sext x)) -> (sext x)
5553 if (N0.getOpcode() == ISD::ANY_EXTEND ||
5554 N0.getOpcode() == ISD::ZERO_EXTEND ||
5555 N0.getOpcode() == ISD::SIGN_EXTEND)
5556 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, N0.getOperand(0));
5558 // fold (aext (truncate (load x))) -> (aext (smaller load x))
5559 // fold (aext (truncate (srl (load x), c))) -> (aext (small load (x+c/n)))
5560 if (N0.getOpcode() == ISD::TRUNCATE) {
5561 SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
5562 if (NarrowLoad.getNode()) {
5563 SDNode* oye = N0.getNode()->getOperand(0).getNode();
5564 if (NarrowLoad.getNode() != N0.getNode()) {
5565 CombineTo(N0.getNode(), NarrowLoad);
5566 // CombineTo deleted the truncate, if needed, but not what's under it.
5569 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5573 // fold (aext (truncate x))
5574 if (N0.getOpcode() == ISD::TRUNCATE) {
5575 SDValue TruncOp = N0.getOperand(0);
5576 if (TruncOp.getValueType() == VT)
5577 return TruncOp; // x iff x size == zext size.
5578 if (TruncOp.getValueType().bitsGT(VT))
5579 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, TruncOp);
5580 return DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, TruncOp);
5583 // Fold (aext (and (trunc x), cst)) -> (and x, cst)
5584 // if the trunc is not free.
5585 if (N0.getOpcode() == ISD::AND &&
5586 N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
5587 N0.getOperand(1).getOpcode() == ISD::Constant &&
5588 !TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(),
5589 N0.getValueType())) {
5590 SDValue X = N0.getOperand(0).getOperand(0);
5591 if (X.getValueType().bitsLT(VT)) {
5592 X = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, X);
5593 } else if (X.getValueType().bitsGT(VT)) {
5594 X = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, X);
5596 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
5597 Mask = Mask.zext(VT.getSizeInBits());
5598 return DAG.getNode(ISD::AND, SDLoc(N), VT,
5599 X, DAG.getConstant(Mask, VT));
5602 // fold (aext (load x)) -> (aext (truncate (extload x)))
5603 // None of the supported targets knows how to perform load and any_ext
5604 // on vectors in one instruction. We only perform this transformation on
5606 if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() &&
5607 ISD::isUNINDEXEDLoad(N0.getNode()) &&
5608 TLI.isLoadExtLegal(ISD::EXTLOAD, N0.getValueType())) {
5609 bool DoXform = true;
5610 SmallVector<SDNode*, 4> SetCCs;
5611 if (!N0.hasOneUse())
5612 DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ANY_EXTEND, SetCCs, TLI);
5614 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5615 SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT,
5617 LN0->getBasePtr(), N0.getValueType(),
5618 LN0->getMemOperand());
5619 CombineTo(N, ExtLoad);
5620 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
5621 N0.getValueType(), ExtLoad);
5622 CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
5623 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
5625 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5629 // fold (aext (zextload x)) -> (aext (truncate (zextload x)))
5630 // fold (aext (sextload x)) -> (aext (truncate (sextload x)))
5631 // fold (aext ( extload x)) -> (aext (truncate (extload x)))
5632 if (N0.getOpcode() == ISD::LOAD &&
5633 !ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
5635 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5636 ISD::LoadExtType ExtType = LN0->getExtensionType();
5637 EVT MemVT = LN0->getMemoryVT();
5638 if (!LegalOperations || TLI.isLoadExtLegal(ExtType, MemVT)) {
5639 SDValue ExtLoad = DAG.getExtLoad(ExtType, SDLoc(N),
5640 VT, LN0->getChain(), LN0->getBasePtr(),
5641 MemVT, LN0->getMemOperand());
5642 CombineTo(N, ExtLoad);
5643 CombineTo(N0.getNode(),
5644 DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
5645 N0.getValueType(), ExtLoad),
5646 ExtLoad.getValue(1));
5647 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5651 if (N0.getOpcode() == ISD::SETCC) {
5653 // aext(setcc) -> vsetcc
5654 // aext(setcc) -> truncate(vsetcc)
5655 // aext(setcc) -> aext(vsetcc)
5656 // Only do this before legalize for now.
5657 if (VT.isVector() && !LegalOperations) {
5658 EVT N0VT = N0.getOperand(0).getValueType();
5659 // We know that the # elements of the results is the same as the
5660 // # elements of the compare (and the # elements of the compare result
5661 // for that matter). Check to see that they are the same size. If so,
5662 // we know that the element size of the sext'd result matches the
5663 // element size of the compare operands.
5664 if (VT.getSizeInBits() == N0VT.getSizeInBits())
5665 return DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
5667 cast<CondCodeSDNode>(N0.getOperand(2))->get());
5668 // If the desired elements are smaller or larger than the source
5669 // elements we can use a matching integer vector type and then
5670 // truncate/any extend
5672 EVT MatchingVectorType = N0VT.changeVectorElementTypeToInteger();
5674 DAG.getSetCC(SDLoc(N), MatchingVectorType, N0.getOperand(0),
5676 cast<CondCodeSDNode>(N0.getOperand(2))->get());
5677 return DAG.getAnyExtOrTrunc(VsetCC, SDLoc(N), VT);
5681 // aext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
5683 SimplifySelectCC(SDLoc(N), N0.getOperand(0), N0.getOperand(1),
5684 DAG.getConstant(1, VT), DAG.getConstant(0, VT),
5685 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
5693 /// See if the specified operand can be simplified with the knowledge that only
5694 /// the bits specified by Mask are used. If so, return the simpler operand,
5695 /// otherwise return a null SDValue.
5696 SDValue DAGCombiner::GetDemandedBits(SDValue V, const APInt &Mask) {
5697 switch (V.getOpcode()) {
5699 case ISD::Constant: {
5700 const ConstantSDNode *CV = cast<ConstantSDNode>(V.getNode());
5701 assert(CV && "Const value should be ConstSDNode.");
5702 const APInt &CVal = CV->getAPIntValue();
5703 APInt NewVal = CVal & Mask;
5705 return DAG.getConstant(NewVal, V.getValueType());
5710 // If the LHS or RHS don't contribute bits to the or, drop them.
5711 if (DAG.MaskedValueIsZero(V.getOperand(0), Mask))
5712 return V.getOperand(1);
5713 if (DAG.MaskedValueIsZero(V.getOperand(1), Mask))
5714 return V.getOperand(0);
5717 // Only look at single-use SRLs.
5718 if (!V.getNode()->hasOneUse())
5720 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(V.getOperand(1))) {
5721 // See if we can recursively simplify the LHS.
5722 unsigned Amt = RHSC->getZExtValue();
5724 // Watch out for shift count overflow though.
5725 if (Amt >= Mask.getBitWidth()) break;
5726 APInt NewMask = Mask << Amt;
5727 SDValue SimplifyLHS = GetDemandedBits(V.getOperand(0), NewMask);
5728 if (SimplifyLHS.getNode())
5729 return DAG.getNode(ISD::SRL, SDLoc(V), V.getValueType(),
5730 SimplifyLHS, V.getOperand(1));
5736 /// If the result of a wider load is shifted to right of N bits and then
5737 /// truncated to a narrower type and where N is a multiple of number of bits of
5738 /// the narrower type, transform it to a narrower load from address + N / num of
5739 /// bits of new type. If the result is to be extended, also fold the extension
5740 /// to form a extending load.
5741 SDValue DAGCombiner::ReduceLoadWidth(SDNode *N) {
5742 unsigned Opc = N->getOpcode();
5744 ISD::LoadExtType ExtType = ISD::NON_EXTLOAD;
5745 SDValue N0 = N->getOperand(0);
5746 EVT VT = N->getValueType(0);
5749 // This transformation isn't valid for vector loads.
5753 // Special case: SIGN_EXTEND_INREG is basically truncating to ExtVT then
5755 if (Opc == ISD::SIGN_EXTEND_INREG) {
5756 ExtType = ISD::SEXTLOAD;
5757 ExtVT = cast<VTSDNode>(N->getOperand(1))->getVT();
5758 } else if (Opc == ISD::SRL) {
5759 // Another special-case: SRL is basically zero-extending a narrower value.
5760 ExtType = ISD::ZEXTLOAD;
5762 ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1));
5763 if (!N01) return SDValue();
5764 ExtVT = EVT::getIntegerVT(*DAG.getContext(),
5765 VT.getSizeInBits() - N01->getZExtValue());
5767 if (LegalOperations && !TLI.isLoadExtLegal(ExtType, ExtVT))
5770 unsigned EVTBits = ExtVT.getSizeInBits();
5772 // Do not generate loads of non-round integer types since these can
5773 // be expensive (and would be wrong if the type is not byte sized).
5774 if (!ExtVT.isRound())
5778 if (N0.getOpcode() == ISD::SRL && N0.hasOneUse()) {
5779 if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
5780 ShAmt = N01->getZExtValue();
5781 // Is the shift amount a multiple of size of VT?
5782 if ((ShAmt & (EVTBits-1)) == 0) {
5783 N0 = N0.getOperand(0);
5784 // Is the load width a multiple of size of VT?
5785 if ((N0.getValueType().getSizeInBits() & (EVTBits-1)) != 0)
5789 // At this point, we must have a load or else we can't do the transform.
5790 if (!isa<LoadSDNode>(N0)) return SDValue();
5792 // Because a SRL must be assumed to *need* to zero-extend the high bits
5793 // (as opposed to anyext the high bits), we can't combine the zextload
5794 // lowering of SRL and an sextload.
5795 if (cast<LoadSDNode>(N0)->getExtensionType() == ISD::SEXTLOAD)
5798 // If the shift amount is larger than the input type then we're not
5799 // accessing any of the loaded bytes. If the load was a zextload/extload
5800 // then the result of the shift+trunc is zero/undef (handled elsewhere).
5801 if (ShAmt >= cast<LoadSDNode>(N0)->getMemoryVT().getSizeInBits())
5806 // If the load is shifted left (and the result isn't shifted back right),
5807 // we can fold the truncate through the shift.
5808 unsigned ShLeftAmt = 0;
5809 if (ShAmt == 0 && N0.getOpcode() == ISD::SHL && N0.hasOneUse() &&
5810 ExtVT == VT && TLI.isNarrowingProfitable(N0.getValueType(), VT)) {
5811 if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
5812 ShLeftAmt = N01->getZExtValue();
5813 N0 = N0.getOperand(0);
5817 // If we haven't found a load, we can't narrow it. Don't transform one with
5818 // multiple uses, this would require adding a new load.
5819 if (!isa<LoadSDNode>(N0) || !N0.hasOneUse())
5822 // Don't change the width of a volatile load.
5823 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5824 if (LN0->isVolatile())
5827 // Verify that we are actually reducing a load width here.
5828 if (LN0->getMemoryVT().getSizeInBits() < EVTBits)
5831 // For the transform to be legal, the load must produce only two values
5832 // (the value loaded and the chain). Don't transform a pre-increment
5833 // load, for example, which produces an extra value. Otherwise the
5834 // transformation is not equivalent, and the downstream logic to replace
5835 // uses gets things wrong.
5836 if (LN0->getNumValues() > 2)
5839 // If the load that we're shrinking is an extload and we're not just
5840 // discarding the extension we can't simply shrink the load. Bail.
5841 // TODO: It would be possible to merge the extensions in some cases.
5842 if (LN0->getExtensionType() != ISD::NON_EXTLOAD &&
5843 LN0->getMemoryVT().getSizeInBits() < ExtVT.getSizeInBits() + ShAmt)
5846 EVT PtrType = N0.getOperand(1).getValueType();
5848 if (PtrType == MVT::Untyped || PtrType.isExtended())
5849 // It's not possible to generate a constant of extended or untyped type.
5852 // For big endian targets, we need to adjust the offset to the pointer to
5853 // load the correct bytes.
5854 if (TLI.isBigEndian()) {
5855 unsigned LVTStoreBits = LN0->getMemoryVT().getStoreSizeInBits();
5856 unsigned EVTStoreBits = ExtVT.getStoreSizeInBits();
5857 ShAmt = LVTStoreBits - EVTStoreBits - ShAmt;
5860 uint64_t PtrOff = ShAmt / 8;
5861 unsigned NewAlign = MinAlign(LN0->getAlignment(), PtrOff);
5862 SDValue NewPtr = DAG.getNode(ISD::ADD, SDLoc(LN0),
5863 PtrType, LN0->getBasePtr(),
5864 DAG.getConstant(PtrOff, PtrType));
5865 AddToWorklist(NewPtr.getNode());
5868 if (ExtType == ISD::NON_EXTLOAD)
5869 Load = DAG.getLoad(VT, SDLoc(N0), LN0->getChain(), NewPtr,
5870 LN0->getPointerInfo().getWithOffset(PtrOff),
5871 LN0->isVolatile(), LN0->isNonTemporal(),
5872 LN0->isInvariant(), NewAlign, LN0->getAAInfo());
5874 Load = DAG.getExtLoad(ExtType, SDLoc(N0), VT, LN0->getChain(),NewPtr,
5875 LN0->getPointerInfo().getWithOffset(PtrOff),
5876 ExtVT, LN0->isVolatile(), LN0->isNonTemporal(),
5877 LN0->isInvariant(), NewAlign, LN0->getAAInfo());
5879 // Replace the old load's chain with the new load's chain.
5880 WorklistRemover DeadNodes(*this);
5881 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1));
5883 // Shift the result left, if we've swallowed a left shift.
5884 SDValue Result = Load;
5885 if (ShLeftAmt != 0) {
5886 EVT ShImmTy = getShiftAmountTy(Result.getValueType());
5887 if (!isUIntN(ShImmTy.getSizeInBits(), ShLeftAmt))
5889 // If the shift amount is as large as the result size (but, presumably,
5890 // no larger than the source) then the useful bits of the result are
5891 // zero; we can't simply return the shortened shift, because the result
5892 // of that operation is undefined.
5893 if (ShLeftAmt >= VT.getSizeInBits())
5894 Result = DAG.getConstant(0, VT);
5896 Result = DAG.getNode(ISD::SHL, SDLoc(N0), VT,
5897 Result, DAG.getConstant(ShLeftAmt, ShImmTy));
5900 // Return the new loaded value.
5904 SDValue DAGCombiner::visitSIGN_EXTEND_INREG(SDNode *N) {
5905 SDValue N0 = N->getOperand(0);
5906 SDValue N1 = N->getOperand(1);
5907 EVT VT = N->getValueType(0);
5908 EVT EVT = cast<VTSDNode>(N1)->getVT();
5909 unsigned VTBits = VT.getScalarType().getSizeInBits();
5910 unsigned EVTBits = EVT.getScalarType().getSizeInBits();
5912 // fold (sext_in_reg c1) -> c1
5913 if (isa<ConstantSDNode>(N0) || N0.getOpcode() == ISD::UNDEF)
5914 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, N0, N1);
5916 // If the input is already sign extended, just drop the extension.
5917 if (DAG.ComputeNumSignBits(N0) >= VTBits-EVTBits+1)
5920 // fold (sext_in_reg (sext_in_reg x, VT2), VT1) -> (sext_in_reg x, minVT) pt2
5921 if (N0.getOpcode() == ISD::SIGN_EXTEND_INREG &&
5922 EVT.bitsLT(cast<VTSDNode>(N0.getOperand(1))->getVT()))
5923 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
5924 N0.getOperand(0), N1);
5926 // fold (sext_in_reg (sext x)) -> (sext x)
5927 // fold (sext_in_reg (aext x)) -> (sext x)
5928 // if x is small enough.
5929 if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND) {
5930 SDValue N00 = N0.getOperand(0);
5931 if (N00.getValueType().getScalarType().getSizeInBits() <= EVTBits &&
5932 (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND, VT)))
5933 return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, N00, N1);
5936 // fold (sext_in_reg x) -> (zext_in_reg x) if the sign bit is known zero.
5937 if (DAG.MaskedValueIsZero(N0, APInt::getBitsSet(VTBits, EVTBits-1, EVTBits)))
5938 return DAG.getZeroExtendInReg(N0, SDLoc(N), EVT);
5940 // fold operands of sext_in_reg based on knowledge that the top bits are not
5942 if (SimplifyDemandedBits(SDValue(N, 0)))
5943 return SDValue(N, 0);
5945 // fold (sext_in_reg (load x)) -> (smaller sextload x)
5946 // fold (sext_in_reg (srl (load x), c)) -> (smaller sextload (x+c/evtbits))
5947 SDValue NarrowLoad = ReduceLoadWidth(N);
5948 if (NarrowLoad.getNode())
5951 // fold (sext_in_reg (srl X, 24), i8) -> (sra X, 24)
5952 // fold (sext_in_reg (srl X, 23), i8) -> (sra X, 23) iff possible.
5953 // We already fold "(sext_in_reg (srl X, 25), i8) -> srl X, 25" above.
5954 if (N0.getOpcode() == ISD::SRL) {
5955 if (ConstantSDNode *ShAmt = dyn_cast<ConstantSDNode>(N0.getOperand(1)))
5956 if (ShAmt->getZExtValue()+EVTBits <= VTBits) {
5957 // We can turn this into an SRA iff the input to the SRL is already sign
5959 unsigned InSignBits = DAG.ComputeNumSignBits(N0.getOperand(0));
5960 if (VTBits-(ShAmt->getZExtValue()+EVTBits) < InSignBits)
5961 return DAG.getNode(ISD::SRA, SDLoc(N), VT,
5962 N0.getOperand(0), N0.getOperand(1));
5966 // fold (sext_inreg (extload x)) -> (sextload x)
5967 if (ISD::isEXTLoad(N0.getNode()) &&
5968 ISD::isUNINDEXEDLoad(N0.getNode()) &&
5969 EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
5970 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
5971 TLI.isLoadExtLegal(ISD::SEXTLOAD, EVT))) {
5972 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5973 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
5975 LN0->getBasePtr(), EVT,
5976 LN0->getMemOperand());
5977 CombineTo(N, ExtLoad);
5978 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
5979 AddToWorklist(ExtLoad.getNode());
5980 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5982 // fold (sext_inreg (zextload x)) -> (sextload x) iff load has one use
5983 if (ISD::isZEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
5985 EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
5986 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
5987 TLI.isLoadExtLegal(ISD::SEXTLOAD, EVT))) {
5988 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5989 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
5991 LN0->getBasePtr(), EVT,
5992 LN0->getMemOperand());
5993 CombineTo(N, ExtLoad);
5994 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
5995 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5998 // Form (sext_inreg (bswap >> 16)) or (sext_inreg (rotl (bswap) 16))
5999 if (EVTBits <= 16 && N0.getOpcode() == ISD::OR) {
6000 SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0),
6001 N0.getOperand(1), false);
6002 if (BSwap.getNode())
6003 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
6007 // Fold a sext_inreg of a build_vector of ConstantSDNodes or undefs
6008 // into a build_vector.
6009 if (ISD::isBuildVectorOfConstantSDNodes(N0.getNode())) {
6010 SmallVector<SDValue, 8> Elts;
6011 unsigned NumElts = N0->getNumOperands();
6012 unsigned ShAmt = VTBits - EVTBits;
6014 for (unsigned i = 0; i != NumElts; ++i) {
6015 SDValue Op = N0->getOperand(i);
6016 if (Op->getOpcode() == ISD::UNDEF) {
6021 ConstantSDNode *CurrentND = cast<ConstantSDNode>(Op);
6022 const APInt &C = APInt(VTBits, CurrentND->getAPIntValue().getZExtValue());
6023 Elts.push_back(DAG.getConstant(C.shl(ShAmt).ashr(ShAmt).getZExtValue(),
6024 Op.getValueType()));
6027 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, Elts);
6033 SDValue DAGCombiner::visitTRUNCATE(SDNode *N) {
6034 SDValue N0 = N->getOperand(0);
6035 EVT VT = N->getValueType(0);
6036 bool isLE = TLI.isLittleEndian();
6039 if (N0.getValueType() == N->getValueType(0))
6041 // fold (truncate c1) -> c1
6042 if (isa<ConstantSDNode>(N0))
6043 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0);
6044 // fold (truncate (truncate x)) -> (truncate x)
6045 if (N0.getOpcode() == ISD::TRUNCATE)
6046 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0));
6047 // fold (truncate (ext x)) -> (ext x) or (truncate x) or x
6048 if (N0.getOpcode() == ISD::ZERO_EXTEND ||
6049 N0.getOpcode() == ISD::SIGN_EXTEND ||
6050 N0.getOpcode() == ISD::ANY_EXTEND) {
6051 if (N0.getOperand(0).getValueType().bitsLT(VT))
6052 // if the source is smaller than the dest, we still need an extend
6053 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
6055 if (N0.getOperand(0).getValueType().bitsGT(VT))
6056 // if the source is larger than the dest, than we just need the truncate
6057 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0));
6058 // if the source and dest are the same type, we can drop both the extend
6059 // and the truncate.
6060 return N0.getOperand(0);
6063 // Fold extract-and-trunc into a narrow extract. For example:
6064 // i64 x = EXTRACT_VECTOR_ELT(v2i64 val, i32 1)
6065 // i32 y = TRUNCATE(i64 x)
6067 // v16i8 b = BITCAST (v2i64 val)
6068 // i8 x = EXTRACT_VECTOR_ELT(v16i8 b, i32 8)
6070 // Note: We only run this optimization after type legalization (which often
6071 // creates this pattern) and before operation legalization after which
6072 // we need to be more careful about the vector instructions that we generate.
6073 if (N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
6074 LegalTypes && !LegalOperations && N0->hasOneUse() && VT != MVT::i1) {
6076 EVT VecTy = N0.getOperand(0).getValueType();
6077 EVT ExTy = N0.getValueType();
6078 EVT TrTy = N->getValueType(0);
6080 unsigned NumElem = VecTy.getVectorNumElements();
6081 unsigned SizeRatio = ExTy.getSizeInBits()/TrTy.getSizeInBits();
6083 EVT NVT = EVT::getVectorVT(*DAG.getContext(), TrTy, SizeRatio * NumElem);
6084 assert(NVT.getSizeInBits() == VecTy.getSizeInBits() && "Invalid Size");
6086 SDValue EltNo = N0->getOperand(1);
6087 if (isa<ConstantSDNode>(EltNo) && isTypeLegal(NVT)) {
6088 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
6089 EVT IndexTy = TLI.getVectorIdxTy();
6090 int Index = isLE ? (Elt*SizeRatio) : (Elt*SizeRatio + (SizeRatio-1));
6092 SDValue V = DAG.getNode(ISD::BITCAST, SDLoc(N),
6093 NVT, N0.getOperand(0));
6095 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT,
6097 DAG.getConstant(Index, IndexTy));
6101 // trunc (select c, a, b) -> select c, (trunc a), (trunc b)
6102 if (N0.getOpcode() == ISD::SELECT) {
6103 EVT SrcVT = N0.getValueType();
6104 if ((!LegalOperations || TLI.isOperationLegal(ISD::SELECT, SrcVT)) &&
6105 TLI.isTruncateFree(SrcVT, VT)) {
6107 SDValue Cond = N0.getOperand(0);
6108 SDValue TruncOp0 = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(1));
6109 SDValue TruncOp1 = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(2));
6110 return DAG.getNode(ISD::SELECT, SDLoc(N), VT, Cond, TruncOp0, TruncOp1);
6114 // Fold a series of buildvector, bitcast, and truncate if possible.
6116 // (2xi32 trunc (bitcast ((4xi32)buildvector x, x, y, y) 2xi64)) to
6117 // (2xi32 (buildvector x, y)).
6118 if (Level == AfterLegalizeVectorOps && VT.isVector() &&
6119 N0.getOpcode() == ISD::BITCAST && N0.hasOneUse() &&
6120 N0.getOperand(0).getOpcode() == ISD::BUILD_VECTOR &&
6121 N0.getOperand(0).hasOneUse()) {
6123 SDValue BuildVect = N0.getOperand(0);
6124 EVT BuildVectEltTy = BuildVect.getValueType().getVectorElementType();
6125 EVT TruncVecEltTy = VT.getVectorElementType();
6127 // Check that the element types match.
6128 if (BuildVectEltTy == TruncVecEltTy) {
6129 // Now we only need to compute the offset of the truncated elements.
6130 unsigned BuildVecNumElts = BuildVect.getNumOperands();
6131 unsigned TruncVecNumElts = VT.getVectorNumElements();
6132 unsigned TruncEltOffset = BuildVecNumElts / TruncVecNumElts;
6134 assert((BuildVecNumElts % TruncVecNumElts) == 0 &&
6135 "Invalid number of elements");
6137 SmallVector<SDValue, 8> Opnds;
6138 for (unsigned i = 0, e = BuildVecNumElts; i != e; i += TruncEltOffset)
6139 Opnds.push_back(BuildVect.getOperand(i));
6141 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, Opnds);
6145 // See if we can simplify the input to this truncate through knowledge that
6146 // only the low bits are being used.
6147 // For example "trunc (or (shl x, 8), y)" // -> trunc y
6148 // Currently we only perform this optimization on scalars because vectors
6149 // may have different active low bits.
6150 if (!VT.isVector()) {
6152 GetDemandedBits(N0, APInt::getLowBitsSet(N0.getValueSizeInBits(),
6153 VT.getSizeInBits()));
6154 if (Shorter.getNode())
6155 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Shorter);
6157 // fold (truncate (load x)) -> (smaller load x)
6158 // fold (truncate (srl (load x), c)) -> (smaller load (x+c/evtbits))
6159 if (!LegalTypes || TLI.isTypeDesirableForOp(N0.getOpcode(), VT)) {
6160 SDValue Reduced = ReduceLoadWidth(N);
6161 if (Reduced.getNode())
6163 // Handle the case where the load remains an extending load even
6164 // after truncation.
6165 if (N0.hasOneUse() && ISD::isUNINDEXEDLoad(N0.getNode())) {
6166 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6167 if (!LN0->isVolatile() &&
6168 LN0->getMemoryVT().getStoreSizeInBits() < VT.getSizeInBits()) {
6169 SDValue NewLoad = DAG.getExtLoad(LN0->getExtensionType(), SDLoc(LN0),
6170 VT, LN0->getChain(), LN0->getBasePtr(),
6172 LN0->getMemOperand());
6173 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLoad.getValue(1));
6178 // fold (trunc (concat ... x ...)) -> (concat ..., (trunc x), ...)),
6179 // where ... are all 'undef'.
6180 if (N0.getOpcode() == ISD::CONCAT_VECTORS && !LegalTypes) {
6181 SmallVector<EVT, 8> VTs;
6184 unsigned NumDefs = 0;
6186 for (unsigned i = 0, e = N0.getNumOperands(); i != e; ++i) {
6187 SDValue X = N0.getOperand(i);
6188 if (X.getOpcode() != ISD::UNDEF) {
6193 // Stop if more than one members are non-undef.
6196 VTs.push_back(EVT::getVectorVT(*DAG.getContext(),
6197 VT.getVectorElementType(),
6198 X.getValueType().getVectorNumElements()));
6202 return DAG.getUNDEF(VT);
6205 assert(V.getNode() && "The single defined operand is empty!");
6206 SmallVector<SDValue, 8> Opnds;
6207 for (unsigned i = 0, e = VTs.size(); i != e; ++i) {
6209 Opnds.push_back(DAG.getUNDEF(VTs[i]));
6212 SDValue NV = DAG.getNode(ISD::TRUNCATE, SDLoc(V), VTs[i], V);
6213 AddToWorklist(NV.getNode());
6214 Opnds.push_back(NV);
6216 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Opnds);
6220 // Simplify the operands using demanded-bits information.
6221 if (!VT.isVector() &&
6222 SimplifyDemandedBits(SDValue(N, 0)))
6223 return SDValue(N, 0);
6228 static SDNode *getBuildPairElt(SDNode *N, unsigned i) {
6229 SDValue Elt = N->getOperand(i);
6230 if (Elt.getOpcode() != ISD::MERGE_VALUES)
6231 return Elt.getNode();
6232 return Elt.getOperand(Elt.getResNo()).getNode();
6235 /// build_pair (load, load) -> load
6236 /// if load locations are consecutive.
6237 SDValue DAGCombiner::CombineConsecutiveLoads(SDNode *N, EVT VT) {
6238 assert(N->getOpcode() == ISD::BUILD_PAIR);
6240 LoadSDNode *LD1 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 0));
6241 LoadSDNode *LD2 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 1));
6242 if (!LD1 || !LD2 || !ISD::isNON_EXTLoad(LD1) || !LD1->hasOneUse() ||
6243 LD1->getAddressSpace() != LD2->getAddressSpace())
6245 EVT LD1VT = LD1->getValueType(0);
6247 if (ISD::isNON_EXTLoad(LD2) &&
6249 // If both are volatile this would reduce the number of volatile loads.
6250 // If one is volatile it might be ok, but play conservative and bail out.
6251 !LD1->isVolatile() &&
6252 !LD2->isVolatile() &&
6253 DAG.isConsecutiveLoad(LD2, LD1, LD1VT.getSizeInBits()/8, 1)) {
6254 unsigned Align = LD1->getAlignment();
6255 unsigned NewAlign = TLI.getDataLayout()->
6256 getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
6258 if (NewAlign <= Align &&
6259 (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT)))
6260 return DAG.getLoad(VT, SDLoc(N), LD1->getChain(),
6261 LD1->getBasePtr(), LD1->getPointerInfo(),
6262 false, false, false, Align);
6268 SDValue DAGCombiner::visitBITCAST(SDNode *N) {
6269 SDValue N0 = N->getOperand(0);
6270 EVT VT = N->getValueType(0);
6272 // If the input is a BUILD_VECTOR with all constant elements, fold this now.
6273 // Only do this before legalize, since afterward the target may be depending
6274 // on the bitconvert.
6275 // First check to see if this is all constant.
6277 N0.getOpcode() == ISD::BUILD_VECTOR && N0.getNode()->hasOneUse() &&
6279 bool isSimple = cast<BuildVectorSDNode>(N0)->isConstant();
6281 EVT DestEltVT = N->getValueType(0).getVectorElementType();
6282 assert(!DestEltVT.isVector() &&
6283 "Element type of vector ValueType must not be vector!");
6285 return ConstantFoldBITCASTofBUILD_VECTOR(N0.getNode(), DestEltVT);
6288 // If the input is a constant, let getNode fold it.
6289 if (isa<ConstantSDNode>(N0) || isa<ConstantFPSDNode>(N0)) {
6290 SDValue Res = DAG.getNode(ISD::BITCAST, SDLoc(N), VT, N0);
6291 if (Res.getNode() != N) {
6292 if (!LegalOperations ||
6293 TLI.isOperationLegal(Res.getNode()->getOpcode(), VT))
6296 // Folding it resulted in an illegal node, and it's too late to
6297 // do that. Clean up the old node and forego the transformation.
6298 // Ideally this won't happen very often, because instcombine
6299 // and the earlier dagcombine runs (where illegal nodes are
6300 // permitted) should have folded most of them already.
6301 deleteAndRecombine(Res.getNode());
6305 // (conv (conv x, t1), t2) -> (conv x, t2)
6306 if (N0.getOpcode() == ISD::BITCAST)
6307 return DAG.getNode(ISD::BITCAST, SDLoc(N), VT,
6310 // fold (conv (load x)) -> (load (conv*)x)
6311 // If the resultant load doesn't need a higher alignment than the original!
6312 if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
6313 // Do not change the width of a volatile load.
6314 !cast<LoadSDNode>(N0)->isVolatile() &&
6315 // Do not remove the cast if the types differ in endian layout.
6316 TLI.hasBigEndianPartOrdering(N0.getValueType()) ==
6317 TLI.hasBigEndianPartOrdering(VT) &&
6318 (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT)) &&
6319 TLI.isLoadBitCastBeneficial(N0.getValueType(), VT)) {
6320 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6321 unsigned Align = TLI.getDataLayout()->
6322 getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
6323 unsigned OrigAlign = LN0->getAlignment();
6325 if (Align <= OrigAlign) {
6326 SDValue Load = DAG.getLoad(VT, SDLoc(N), LN0->getChain(),
6327 LN0->getBasePtr(), LN0->getPointerInfo(),
6328 LN0->isVolatile(), LN0->isNonTemporal(),
6329 LN0->isInvariant(), OrigAlign,
6331 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1));
6336 // fold (bitconvert (fneg x)) -> (xor (bitconvert x), signbit)
6337 // fold (bitconvert (fabs x)) -> (and (bitconvert x), (not signbit))
6338 // This often reduces constant pool loads.
6339 if (((N0.getOpcode() == ISD::FNEG && !TLI.isFNegFree(N0.getValueType())) ||
6340 (N0.getOpcode() == ISD::FABS && !TLI.isFAbsFree(N0.getValueType()))) &&
6341 N0.getNode()->hasOneUse() && VT.isInteger() &&
6342 !VT.isVector() && !N0.getValueType().isVector()) {
6343 SDValue NewConv = DAG.getNode(ISD::BITCAST, SDLoc(N0), VT,
6345 AddToWorklist(NewConv.getNode());
6347 APInt SignBit = APInt::getSignBit(VT.getSizeInBits());
6348 if (N0.getOpcode() == ISD::FNEG)
6349 return DAG.getNode(ISD::XOR, SDLoc(N), VT,
6350 NewConv, DAG.getConstant(SignBit, VT));
6351 assert(N0.getOpcode() == ISD::FABS);
6352 return DAG.getNode(ISD::AND, SDLoc(N), VT,
6353 NewConv, DAG.getConstant(~SignBit, VT));
6356 // fold (bitconvert (fcopysign cst, x)) ->
6357 // (or (and (bitconvert x), sign), (and cst, (not sign)))
6358 // Note that we don't handle (copysign x, cst) because this can always be
6359 // folded to an fneg or fabs.
6360 if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse() &&
6361 isa<ConstantFPSDNode>(N0.getOperand(0)) &&
6362 VT.isInteger() && !VT.isVector()) {
6363 unsigned OrigXWidth = N0.getOperand(1).getValueType().getSizeInBits();
6364 EVT IntXVT = EVT::getIntegerVT(*DAG.getContext(), OrigXWidth);
6365 if (isTypeLegal(IntXVT)) {
6366 SDValue X = DAG.getNode(ISD::BITCAST, SDLoc(N0),
6367 IntXVT, N0.getOperand(1));
6368 AddToWorklist(X.getNode());
6370 // If X has a different width than the result/lhs, sext it or truncate it.
6371 unsigned VTWidth = VT.getSizeInBits();
6372 if (OrigXWidth < VTWidth) {
6373 X = DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, X);
6374 AddToWorklist(X.getNode());
6375 } else if (OrigXWidth > VTWidth) {
6376 // To get the sign bit in the right place, we have to shift it right
6377 // before truncating.
6378 X = DAG.getNode(ISD::SRL, SDLoc(X),
6379 X.getValueType(), X,
6380 DAG.getConstant(OrigXWidth-VTWidth, X.getValueType()));
6381 AddToWorklist(X.getNode());
6382 X = DAG.getNode(ISD::TRUNCATE, SDLoc(X), VT, X);
6383 AddToWorklist(X.getNode());
6386 APInt SignBit = APInt::getSignBit(VT.getSizeInBits());
6387 X = DAG.getNode(ISD::AND, SDLoc(X), VT,
6388 X, DAG.getConstant(SignBit, VT));
6389 AddToWorklist(X.getNode());
6391 SDValue Cst = DAG.getNode(ISD::BITCAST, SDLoc(N0),
6392 VT, N0.getOperand(0));
6393 Cst = DAG.getNode(ISD::AND, SDLoc(Cst), VT,
6394 Cst, DAG.getConstant(~SignBit, VT));
6395 AddToWorklist(Cst.getNode());
6397 return DAG.getNode(ISD::OR, SDLoc(N), VT, X, Cst);
6401 // bitconvert(build_pair(ld, ld)) -> ld iff load locations are consecutive.
6402 if (N0.getOpcode() == ISD::BUILD_PAIR) {
6403 SDValue CombineLD = CombineConsecutiveLoads(N0.getNode(), VT);
6404 if (CombineLD.getNode())
6411 SDValue DAGCombiner::visitBUILD_PAIR(SDNode *N) {
6412 EVT VT = N->getValueType(0);
6413 return CombineConsecutiveLoads(N, VT);
6416 /// We know that BV is a build_vector node with Constant, ConstantFP or Undef
6417 /// operands. DstEltVT indicates the destination element value type.
6418 SDValue DAGCombiner::
6419 ConstantFoldBITCASTofBUILD_VECTOR(SDNode *BV, EVT DstEltVT) {
6420 EVT SrcEltVT = BV->getValueType(0).getVectorElementType();
6422 // If this is already the right type, we're done.
6423 if (SrcEltVT == DstEltVT) return SDValue(BV, 0);
6425 unsigned SrcBitSize = SrcEltVT.getSizeInBits();
6426 unsigned DstBitSize = DstEltVT.getSizeInBits();
6428 // If this is a conversion of N elements of one type to N elements of another
6429 // type, convert each element. This handles FP<->INT cases.
6430 if (SrcBitSize == DstBitSize) {
6431 EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT,
6432 BV->getValueType(0).getVectorNumElements());
6434 // Due to the FP element handling below calling this routine recursively,
6435 // we can end up with a scalar-to-vector node here.
6436 if (BV->getOpcode() == ISD::SCALAR_TO_VECTOR)
6437 return DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(BV), VT,
6438 DAG.getNode(ISD::BITCAST, SDLoc(BV),
6439 DstEltVT, BV->getOperand(0)));
6441 SmallVector<SDValue, 8> Ops;
6442 for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) {
6443 SDValue Op = BV->getOperand(i);
6444 // If the vector element type is not legal, the BUILD_VECTOR operands
6445 // are promoted and implicitly truncated. Make that explicit here.
6446 if (Op.getValueType() != SrcEltVT)
6447 Op = DAG.getNode(ISD::TRUNCATE, SDLoc(BV), SrcEltVT, Op);
6448 Ops.push_back(DAG.getNode(ISD::BITCAST, SDLoc(BV),
6450 AddToWorklist(Ops.back().getNode());
6452 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(BV), VT, Ops);
6455 // Otherwise, we're growing or shrinking the elements. To avoid having to
6456 // handle annoying details of growing/shrinking FP values, we convert them to
6458 if (SrcEltVT.isFloatingPoint()) {
6459 // Convert the input float vector to a int vector where the elements are the
6461 assert((SrcEltVT == MVT::f32 || SrcEltVT == MVT::f64) && "Unknown FP VT!");
6462 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), SrcEltVT.getSizeInBits());
6463 BV = ConstantFoldBITCASTofBUILD_VECTOR(BV, IntVT).getNode();
6467 // Now we know the input is an integer vector. If the output is a FP type,
6468 // convert to integer first, then to FP of the right size.
6469 if (DstEltVT.isFloatingPoint()) {
6470 assert((DstEltVT == MVT::f32 || DstEltVT == MVT::f64) && "Unknown FP VT!");
6471 EVT TmpVT = EVT::getIntegerVT(*DAG.getContext(), DstEltVT.getSizeInBits());
6472 SDNode *Tmp = ConstantFoldBITCASTofBUILD_VECTOR(BV, TmpVT).getNode();
6474 // Next, convert to FP elements of the same size.
6475 return ConstantFoldBITCASTofBUILD_VECTOR(Tmp, DstEltVT);
6478 // Okay, we know the src/dst types are both integers of differing types.
6479 // Handling growing first.
6480 assert(SrcEltVT.isInteger() && DstEltVT.isInteger());
6481 if (SrcBitSize < DstBitSize) {
6482 unsigned NumInputsPerOutput = DstBitSize/SrcBitSize;
6484 SmallVector<SDValue, 8> Ops;
6485 for (unsigned i = 0, e = BV->getNumOperands(); i != e;
6486 i += NumInputsPerOutput) {
6487 bool isLE = TLI.isLittleEndian();
6488 APInt NewBits = APInt(DstBitSize, 0);
6489 bool EltIsUndef = true;
6490 for (unsigned j = 0; j != NumInputsPerOutput; ++j) {
6491 // Shift the previously computed bits over.
6492 NewBits <<= SrcBitSize;
6493 SDValue Op = BV->getOperand(i+ (isLE ? (NumInputsPerOutput-j-1) : j));
6494 if (Op.getOpcode() == ISD::UNDEF) continue;
6497 NewBits |= cast<ConstantSDNode>(Op)->getAPIntValue().
6498 zextOrTrunc(SrcBitSize).zext(DstBitSize);
6502 Ops.push_back(DAG.getUNDEF(DstEltVT));
6504 Ops.push_back(DAG.getConstant(NewBits, DstEltVT));
6507 EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT, Ops.size());
6508 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(BV), VT, Ops);
6511 // Finally, this must be the case where we are shrinking elements: each input
6512 // turns into multiple outputs.
6513 bool isS2V = ISD::isScalarToVector(BV);
6514 unsigned NumOutputsPerInput = SrcBitSize/DstBitSize;
6515 EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT,
6516 NumOutputsPerInput*BV->getNumOperands());
6517 SmallVector<SDValue, 8> Ops;
6519 for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) {
6520 if (BV->getOperand(i).getOpcode() == ISD::UNDEF) {
6521 for (unsigned j = 0; j != NumOutputsPerInput; ++j)
6522 Ops.push_back(DAG.getUNDEF(DstEltVT));
6526 APInt OpVal = cast<ConstantSDNode>(BV->getOperand(i))->
6527 getAPIntValue().zextOrTrunc(SrcBitSize);
6529 for (unsigned j = 0; j != NumOutputsPerInput; ++j) {
6530 APInt ThisVal = OpVal.trunc(DstBitSize);
6531 Ops.push_back(DAG.getConstant(ThisVal, DstEltVT));
6532 if (isS2V && i == 0 && j == 0 && ThisVal.zext(SrcBitSize) == OpVal)
6533 // Simply turn this into a SCALAR_TO_VECTOR of the new type.
6534 return DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(BV), VT,
6536 OpVal = OpVal.lshr(DstBitSize);
6539 // For big endian targets, swap the order of the pieces of each element.
6540 if (TLI.isBigEndian())
6541 std::reverse(Ops.end()-NumOutputsPerInput, Ops.end());
6544 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(BV), VT, Ops);
6547 SDValue DAGCombiner::visitFADD(SDNode *N) {
6548 SDValue N0 = N->getOperand(0);
6549 SDValue N1 = N->getOperand(1);
6550 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6551 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6552 EVT VT = N->getValueType(0);
6553 const TargetOptions &Options = DAG.getTarget().Options;
6556 if (VT.isVector()) {
6557 SDValue FoldedVOp = SimplifyVBinOp(N);
6558 if (FoldedVOp.getNode()) return FoldedVOp;
6561 // fold (fadd c1, c2) -> c1 + c2
6563 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N1);
6564 // canonicalize constant to RHS
6565 if (N0CFP && !N1CFP)
6566 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N1, N0);
6567 // fold (fadd A, 0) -> A
6568 if (Options.UnsafeFPMath && N1CFP && N1CFP->getValueAPF().isZero())
6570 // fold (fadd A, (fneg B)) -> (fsub A, B)
6571 if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) &&
6572 isNegatibleForFree(N1, LegalOperations, TLI, &Options) == 2)
6573 return DAG.getNode(ISD::FSUB, SDLoc(N), VT, N0,
6574 GetNegatedExpression(N1, DAG, LegalOperations));
6575 // fold (fadd (fneg A), B) -> (fsub B, A)
6576 if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) &&
6577 isNegatibleForFree(N0, LegalOperations, TLI, &Options) == 2)
6578 return DAG.getNode(ISD::FSUB, SDLoc(N), VT, N1,
6579 GetNegatedExpression(N0, DAG, LegalOperations));
6581 // If allowed, fold (fadd (fadd x, c1), c2) -> (fadd x, (fadd c1, c2))
6582 if (Options.UnsafeFPMath && N1CFP &&
6583 N0.getOpcode() == ISD::FADD && N0.getNode()->hasOneUse() &&
6584 isa<ConstantFPSDNode>(N0.getOperand(1)))
6585 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0.getOperand(0),
6586 DAG.getNode(ISD::FADD, SDLoc(N), VT,
6587 N0.getOperand(1), N1));
6589 // No FP constant should be created after legalization as Instruction
6590 // Selection pass has hard time in dealing with FP constant.
6592 // We don't need test this condition for transformation like following, as
6593 // the DAG being transformed implies it is legal to take FP constant as
6596 // (fadd (fmul c, x), x) -> (fmul c+1, x)
6598 bool AllowNewFpConst = (Level < AfterLegalizeDAG);
6600 // If allow, fold (fadd (fneg x), x) -> 0.0
6601 if (AllowNewFpConst && Options.UnsafeFPMath &&
6602 N0.getOpcode() == ISD::FNEG && N0.getOperand(0) == N1)
6603 return DAG.getConstantFP(0.0, VT);
6605 // If allow, fold (fadd x, (fneg x)) -> 0.0
6606 if (AllowNewFpConst && Options.UnsafeFPMath &&
6607 N1.getOpcode() == ISD::FNEG && N1.getOperand(0) == N0)
6608 return DAG.getConstantFP(0.0, VT);
6610 // In unsafe math mode, we can fold chains of FADD's of the same value
6611 // into multiplications. This transform is not safe in general because
6612 // we are reducing the number of rounding steps.
6613 if (Options.UnsafeFPMath && TLI.isOperationLegalOrCustom(ISD::FMUL, VT) &&
6615 if (N0.getOpcode() == ISD::FMUL) {
6616 ConstantFPSDNode *CFP00 = dyn_cast<ConstantFPSDNode>(N0.getOperand(0));
6617 ConstantFPSDNode *CFP01 = dyn_cast<ConstantFPSDNode>(N0.getOperand(1));
6619 // (fadd (fmul c, x), x) -> (fmul x, c+1)
6620 if (CFP00 && !CFP01 && N0.getOperand(1) == N1) {
6621 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6623 DAG.getConstantFP(1.0, VT));
6624 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6628 // (fadd (fmul x, c), x) -> (fmul x, c+1)
6629 if (CFP01 && !CFP00 && N0.getOperand(0) == N1) {
6630 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6632 DAG.getConstantFP(1.0, VT));
6633 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6637 // (fadd (fmul c, x), (fadd x, x)) -> (fmul x, c+2)
6638 if (CFP00 && !CFP01 && N1.getOpcode() == ISD::FADD &&
6639 N1.getOperand(0) == N1.getOperand(1) &&
6640 N0.getOperand(1) == N1.getOperand(0)) {
6641 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6643 DAG.getConstantFP(2.0, VT));
6644 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6645 N0.getOperand(1), NewCFP);
6648 // (fadd (fmul x, c), (fadd x, x)) -> (fmul x, c+2)
6649 if (CFP01 && !CFP00 && N1.getOpcode() == ISD::FADD &&
6650 N1.getOperand(0) == N1.getOperand(1) &&
6651 N0.getOperand(0) == N1.getOperand(0)) {
6652 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6654 DAG.getConstantFP(2.0, VT));
6655 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6656 N0.getOperand(0), NewCFP);
6660 if (N1.getOpcode() == ISD::FMUL) {
6661 ConstantFPSDNode *CFP10 = dyn_cast<ConstantFPSDNode>(N1.getOperand(0));
6662 ConstantFPSDNode *CFP11 = dyn_cast<ConstantFPSDNode>(N1.getOperand(1));
6664 // (fadd x, (fmul c, x)) -> (fmul x, c+1)
6665 if (CFP10 && !CFP11 && N1.getOperand(1) == N0) {
6666 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6668 DAG.getConstantFP(1.0, VT));
6669 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6673 // (fadd x, (fmul x, c)) -> (fmul x, c+1)
6674 if (CFP11 && !CFP10 && N1.getOperand(0) == N0) {
6675 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6677 DAG.getConstantFP(1.0, VT));
6678 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6683 // (fadd (fadd x, x), (fmul c, x)) -> (fmul x, c+2)
6684 if (CFP10 && !CFP11 && N0.getOpcode() == ISD::FADD &&
6685 N0.getOperand(0) == N0.getOperand(1) &&
6686 N1.getOperand(1) == N0.getOperand(0)) {
6687 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6689 DAG.getConstantFP(2.0, VT));
6690 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6691 N1.getOperand(1), NewCFP);
6694 // (fadd (fadd x, x), (fmul x, c)) -> (fmul x, c+2)
6695 if (CFP11 && !CFP10 && N0.getOpcode() == ISD::FADD &&
6696 N0.getOperand(0) == N0.getOperand(1) &&
6697 N1.getOperand(0) == N0.getOperand(0)) {
6698 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6700 DAG.getConstantFP(2.0, VT));
6701 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6702 N1.getOperand(0), NewCFP);
6706 if (N0.getOpcode() == ISD::FADD && AllowNewFpConst) {
6707 ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N0.getOperand(0));
6708 // (fadd (fadd x, x), x) -> (fmul x, 3.0)
6709 if (!CFP && N0.getOperand(0) == N0.getOperand(1) &&
6710 (N0.getOperand(0) == N1))
6711 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6712 N1, DAG.getConstantFP(3.0, VT));
6715 if (N1.getOpcode() == ISD::FADD && AllowNewFpConst) {
6716 ConstantFPSDNode *CFP10 = dyn_cast<ConstantFPSDNode>(N1.getOperand(0));
6717 // (fadd x, (fadd x, x)) -> (fmul x, 3.0)
6718 if (!CFP10 && N1.getOperand(0) == N1.getOperand(1) &&
6719 N1.getOperand(0) == N0)
6720 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6721 N0, DAG.getConstantFP(3.0, VT));
6724 // (fadd (fadd x, x), (fadd x, x)) -> (fmul x, 4.0)
6725 if (AllowNewFpConst &&
6726 N0.getOpcode() == ISD::FADD && N1.getOpcode() == ISD::FADD &&
6727 N0.getOperand(0) == N0.getOperand(1) &&
6728 N1.getOperand(0) == N1.getOperand(1) &&
6729 N0.getOperand(0) == N1.getOperand(0))
6730 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6732 DAG.getConstantFP(4.0, VT));
6735 // FADD -> FMA combines:
6736 if ((Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath) &&
6739 ->getTargetLowering()
6740 ->isFMAFasterThanFMulAndFAdd(VT) &&
6741 (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT))) {
6743 // fold (fadd (fmul x, y), z) -> (fma x, y, z)
6744 if (N0.getOpcode() == ISD::FMUL && N0->hasOneUse())
6745 return DAG.getNode(ISD::FMA, SDLoc(N), VT,
6746 N0.getOperand(0), N0.getOperand(1), N1);
6748 // fold (fadd x, (fmul y, z)) -> (fma y, z, x)
6749 // Note: Commutes FADD operands.
6750 if (N1.getOpcode() == ISD::FMUL && N1->hasOneUse())
6751 return DAG.getNode(ISD::FMA, SDLoc(N), VT,
6752 N1.getOperand(0), N1.getOperand(1), N0);
6758 SDValue DAGCombiner::visitFSUB(SDNode *N) {
6759 SDValue N0 = N->getOperand(0);
6760 SDValue N1 = N->getOperand(1);
6761 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6762 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6763 EVT VT = N->getValueType(0);
6765 const TargetOptions &Options = DAG.getTarget().Options;
6768 if (VT.isVector()) {
6769 SDValue FoldedVOp = SimplifyVBinOp(N);
6770 if (FoldedVOp.getNode()) return FoldedVOp;
6773 // fold (fsub c1, c2) -> c1-c2
6775 return DAG.getNode(ISD::FSUB, SDLoc(N), VT, N0, N1);
6777 // fold (fsub A, (fneg B)) -> (fadd A, B)
6778 if (isNegatibleForFree(N1, LegalOperations, TLI, &Options))
6779 return DAG.getNode(ISD::FADD, dl, VT, N0,
6780 GetNegatedExpression(N1, DAG, LegalOperations));
6782 // If 'unsafe math' is enabled, fold lots of things.
6783 if (Options.UnsafeFPMath) {
6785 if (N1CFP && N1CFP->getValueAPF().isZero())
6788 // (fsub 0, B) -> -B
6789 if (N0CFP && N0CFP->getValueAPF().isZero()) {
6790 if (isNegatibleForFree(N1, LegalOperations, TLI, &Options))
6791 return GetNegatedExpression(N1, DAG, LegalOperations);
6792 if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
6793 return DAG.getNode(ISD::FNEG, dl, VT, N1);
6796 // (fsub x, x) -> 0.0
6798 return DAG.getConstantFP(0.0f, VT);
6800 // (fsub x, (fadd x, y)) -> (fneg y)
6801 // (fsub x, (fadd y, x)) -> (fneg y)
6802 if (N1.getOpcode() == ISD::FADD) {
6803 SDValue N10 = N1->getOperand(0);
6804 SDValue N11 = N1->getOperand(1);
6806 if (N10 == N0 && isNegatibleForFree(N11, LegalOperations, TLI, &Options))
6807 return GetNegatedExpression(N11, DAG, LegalOperations);
6809 if (N11 == N0 && isNegatibleForFree(N10, LegalOperations, TLI, &Options))
6810 return GetNegatedExpression(N10, DAG, LegalOperations);
6814 // FSUB -> FMA combines:
6815 if ((Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath) &&
6816 DAG.getTarget().getSubtargetImpl()
6817 ->getTargetLowering()
6818 ->isFMAFasterThanFMulAndFAdd(VT) &&
6819 (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT))) {
6821 // fold (fsub (fmul x, y), z) -> (fma x, y, (fneg z))
6822 if (N0.getOpcode() == ISD::FMUL && N0->hasOneUse())
6823 return DAG.getNode(ISD::FMA, dl, VT,
6824 N0.getOperand(0), N0.getOperand(1),
6825 DAG.getNode(ISD::FNEG, dl, VT, N1));
6827 // fold (fsub x, (fmul y, z)) -> (fma (fneg y), z, x)
6828 // Note: Commutes FSUB operands.
6829 if (N1.getOpcode() == ISD::FMUL && N1->hasOneUse())
6830 return DAG.getNode(ISD::FMA, dl, VT,
6831 DAG.getNode(ISD::FNEG, dl, VT,
6833 N1.getOperand(1), N0);
6835 // fold (fsub (fneg (fmul, x, y)), z) -> (fma (fneg x), y, (fneg z))
6836 if (N0.getOpcode() == ISD::FNEG &&
6837 N0.getOperand(0).getOpcode() == ISD::FMUL &&
6838 N0->hasOneUse() && N0.getOperand(0).hasOneUse()) {
6839 SDValue N00 = N0.getOperand(0).getOperand(0);
6840 SDValue N01 = N0.getOperand(0).getOperand(1);
6841 return DAG.getNode(ISD::FMA, dl, VT,
6842 DAG.getNode(ISD::FNEG, dl, VT, N00), N01,
6843 DAG.getNode(ISD::FNEG, dl, VT, N1));
6850 SDValue DAGCombiner::visitFMUL(SDNode *N) {
6851 SDValue N0 = N->getOperand(0);
6852 SDValue N1 = N->getOperand(1);
6853 ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0);
6854 ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1);
6855 EVT VT = N->getValueType(0);
6856 const TargetOptions &Options = DAG.getTarget().Options;
6859 if (VT.isVector()) {
6860 SDValue FoldedVOp = SimplifyVBinOp(N);
6861 if (FoldedVOp.getNode()) return FoldedVOp;
6864 // fold (fmul c1, c2) -> c1*c2
6866 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0, N1);
6867 // canonicalize constant to RHS
6868 if (N0CFP && !N1CFP)
6869 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N1, N0);
6870 // fold (fmul A, 0) -> 0
6871 if (Options.UnsafeFPMath && N1CFP && N1CFP->getValueAPF().isZero())
6873 // fold (fmul A, 1.0) -> A
6874 if (N1CFP && N1CFP->isExactlyValue(1.0))
6877 // fold (fmul X, 2.0) -> (fadd X, X)
6878 if (N1CFP && N1CFP->isExactlyValue(+2.0))
6879 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N0);
6880 // fold (fmul X, -1.0) -> (fneg X)
6881 if (N1CFP && N1CFP->isExactlyValue(-1.0))
6882 if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
6883 return DAG.getNode(ISD::FNEG, SDLoc(N), VT, N0);
6885 // fold (fmul (fneg X), (fneg Y)) -> (fmul X, Y)
6886 if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI, &Options)) {
6887 if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI, &Options)) {
6888 // Both can be negated for free, check to see if at least one is cheaper
6890 if (LHSNeg == 2 || RHSNeg == 2)
6891 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6892 GetNegatedExpression(N0, DAG, LegalOperations),
6893 GetNegatedExpression(N1, DAG, LegalOperations));
6897 // If allowed, fold (fmul (fmul x, c1), c2) -> (fmul x, (fmul c1, c2))
6898 if (Options.UnsafeFPMath && N1CFP && N0.getOpcode() == ISD::FMUL &&
6899 N0.getNode()->hasOneUse() && isConstOrConstSplatFP(N0.getOperand(1))) {
6900 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0.getOperand(0),
6901 DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6902 N0.getOperand(1), N1));
6908 SDValue DAGCombiner::visitFMA(SDNode *N) {
6909 SDValue N0 = N->getOperand(0);
6910 SDValue N1 = N->getOperand(1);
6911 SDValue N2 = N->getOperand(2);
6912 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6913 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6914 EVT VT = N->getValueType(0);
6916 const TargetOptions &Options = DAG.getTarget().Options;
6918 // Constant fold FMA.
6919 if (isa<ConstantFPSDNode>(N0) &&
6920 isa<ConstantFPSDNode>(N1) &&
6921 isa<ConstantFPSDNode>(N2)) {
6922 return DAG.getNode(ISD::FMA, dl, VT, N0, N1, N2);
6925 if (Options.UnsafeFPMath) {
6926 if (N0CFP && N0CFP->isZero())
6928 if (N1CFP && N1CFP->isZero())
6931 if (N0CFP && N0CFP->isExactlyValue(1.0))
6932 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N1, N2);
6933 if (N1CFP && N1CFP->isExactlyValue(1.0))
6934 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N2);
6936 // Canonicalize (fma c, x, y) -> (fma x, c, y)
6937 if (N0CFP && !N1CFP)
6938 return DAG.getNode(ISD::FMA, SDLoc(N), VT, N1, N0, N2);
6940 // (fma x, c1, (fmul x, c2)) -> (fmul x, c1+c2)
6941 if (Options.UnsafeFPMath && N1CFP &&
6942 N2.getOpcode() == ISD::FMUL &&
6943 N0 == N2.getOperand(0) &&
6944 N2.getOperand(1).getOpcode() == ISD::ConstantFP) {
6945 return DAG.getNode(ISD::FMUL, dl, VT, N0,
6946 DAG.getNode(ISD::FADD, dl, VT, N1, N2.getOperand(1)));
6950 // (fma (fmul x, c1), c2, y) -> (fma x, c1*c2, y)
6951 if (Options.UnsafeFPMath &&
6952 N0.getOpcode() == ISD::FMUL && N1CFP &&
6953 N0.getOperand(1).getOpcode() == ISD::ConstantFP) {
6954 return DAG.getNode(ISD::FMA, dl, VT,
6956 DAG.getNode(ISD::FMUL, dl, VT, N1, N0.getOperand(1)),
6960 // (fma x, 1, y) -> (fadd x, y)
6961 // (fma x, -1, y) -> (fadd (fneg x), y)
6963 if (N1CFP->isExactlyValue(1.0))
6964 return DAG.getNode(ISD::FADD, dl, VT, N0, N2);
6966 if (N1CFP->isExactlyValue(-1.0) &&
6967 (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))) {
6968 SDValue RHSNeg = DAG.getNode(ISD::FNEG, dl, VT, N0);
6969 AddToWorklist(RHSNeg.getNode());
6970 return DAG.getNode(ISD::FADD, dl, VT, N2, RHSNeg);
6974 // (fma x, c, x) -> (fmul x, (c+1))
6975 if (Options.UnsafeFPMath && N1CFP && N0 == N2)
6976 return DAG.getNode(ISD::FMUL, dl, VT, N0,
6977 DAG.getNode(ISD::FADD, dl, VT,
6978 N1, DAG.getConstantFP(1.0, VT)));
6980 // (fma x, c, (fneg x)) -> (fmul x, (c-1))
6981 if (Options.UnsafeFPMath && N1CFP &&
6982 N2.getOpcode() == ISD::FNEG && N2.getOperand(0) == N0)
6983 return DAG.getNode(ISD::FMUL, dl, VT, N0,
6984 DAG.getNode(ISD::FADD, dl, VT,
6985 N1, DAG.getConstantFP(-1.0, VT)));
6991 SDValue DAGCombiner::visitFDIV(SDNode *N) {
6992 SDValue N0 = N->getOperand(0);
6993 SDValue N1 = N->getOperand(1);
6994 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6995 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6996 EVT VT = N->getValueType(0);
6997 const TargetOptions &Options = DAG.getTarget().Options;
7000 if (VT.isVector()) {
7001 SDValue FoldedVOp = SimplifyVBinOp(N);
7002 if (FoldedVOp.getNode()) return FoldedVOp;
7005 // fold (fdiv c1, c2) -> c1/c2
7007 return DAG.getNode(ISD::FDIV, SDLoc(N), VT, N0, N1);
7009 // fold (fdiv X, c2) -> fmul X, 1/c2 if losing precision is acceptable.
7010 if (N1CFP && Options.UnsafeFPMath) {
7011 // Compute the reciprocal 1.0 / c2.
7012 APFloat N1APF = N1CFP->getValueAPF();
7013 APFloat Recip(N1APF.getSemantics(), 1); // 1.0
7014 APFloat::opStatus st = Recip.divide(N1APF, APFloat::rmNearestTiesToEven);
7015 // Only do the transform if the reciprocal is a legal fp immediate that
7016 // isn't too nasty (eg NaN, denormal, ...).
7017 if ((st == APFloat::opOK || st == APFloat::opInexact) && // Not too nasty
7018 (!LegalOperations ||
7019 // FIXME: custom lowering of ConstantFP might fail (see e.g. ARM
7020 // backend)... we should handle this gracefully after Legalize.
7021 // TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT) ||
7022 TLI.isOperationLegal(llvm::ISD::ConstantFP, VT) ||
7023 TLI.isFPImmLegal(Recip, VT)))
7024 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0,
7025 DAG.getConstantFP(Recip, VT));
7028 // (fdiv (fneg X), (fneg Y)) -> (fdiv X, Y)
7029 if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI, &Options)) {
7030 if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI, &Options)) {
7031 // Both can be negated for free, check to see if at least one is cheaper
7033 if (LHSNeg == 2 || RHSNeg == 2)
7034 return DAG.getNode(ISD::FDIV, SDLoc(N), VT,
7035 GetNegatedExpression(N0, DAG, LegalOperations),
7036 GetNegatedExpression(N1, DAG, LegalOperations));
7043 SDValue DAGCombiner::visitFREM(SDNode *N) {
7044 SDValue N0 = N->getOperand(0);
7045 SDValue N1 = N->getOperand(1);
7046 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7047 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
7048 EVT VT = N->getValueType(0);
7050 // fold (frem c1, c2) -> fmod(c1,c2)
7052 return DAG.getNode(ISD::FREM, SDLoc(N), VT, N0, N1);
7057 SDValue DAGCombiner::visitFCOPYSIGN(SDNode *N) {
7058 SDValue N0 = N->getOperand(0);
7059 SDValue N1 = N->getOperand(1);
7060 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7061 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
7062 EVT VT = N->getValueType(0);
7064 if (N0CFP && N1CFP) // Constant fold
7065 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, N0, N1);
7068 const APFloat& V = N1CFP->getValueAPF();
7069 // copysign(x, c1) -> fabs(x) iff ispos(c1)
7070 // copysign(x, c1) -> fneg(fabs(x)) iff isneg(c1)
7071 if (!V.isNegative()) {
7072 if (!LegalOperations || TLI.isOperationLegal(ISD::FABS, VT))
7073 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
7075 if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
7076 return DAG.getNode(ISD::FNEG, SDLoc(N), VT,
7077 DAG.getNode(ISD::FABS, SDLoc(N0), VT, N0));
7081 // copysign(fabs(x), y) -> copysign(x, y)
7082 // copysign(fneg(x), y) -> copysign(x, y)
7083 // copysign(copysign(x,z), y) -> copysign(x, y)
7084 if (N0.getOpcode() == ISD::FABS || N0.getOpcode() == ISD::FNEG ||
7085 N0.getOpcode() == ISD::FCOPYSIGN)
7086 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
7087 N0.getOperand(0), N1);
7089 // copysign(x, abs(y)) -> abs(x)
7090 if (N1.getOpcode() == ISD::FABS)
7091 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
7093 // copysign(x, copysign(y,z)) -> copysign(x, z)
7094 if (N1.getOpcode() == ISD::FCOPYSIGN)
7095 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
7096 N0, N1.getOperand(1));
7098 // copysign(x, fp_extend(y)) -> copysign(x, y)
7099 // copysign(x, fp_round(y)) -> copysign(x, y)
7100 if (N1.getOpcode() == ISD::FP_EXTEND || N1.getOpcode() == ISD::FP_ROUND)
7101 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
7102 N0, N1.getOperand(0));
7107 SDValue DAGCombiner::visitSINT_TO_FP(SDNode *N) {
7108 SDValue N0 = N->getOperand(0);
7109 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
7110 EVT VT = N->getValueType(0);
7111 EVT OpVT = N0.getValueType();
7113 // fold (sint_to_fp c1) -> c1fp
7115 // ...but only if the target supports immediate floating-point values
7116 (!LegalOperations ||
7117 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT)))
7118 return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0);
7120 // If the input is a legal type, and SINT_TO_FP is not legal on this target,
7121 // but UINT_TO_FP is legal on this target, try to convert.
7122 if (!TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT) &&
7123 TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT)) {
7124 // If the sign bit is known to be zero, we can change this to UINT_TO_FP.
7125 if (DAG.SignBitIsZero(N0))
7126 return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0);
7129 // The next optimizations are desirable only if SELECT_CC can be lowered.
7130 if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT) || !LegalOperations) {
7131 // fold (sint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc)
7132 if (N0.getOpcode() == ISD::SETCC && N0.getValueType() == MVT::i1 &&
7134 (!LegalOperations ||
7135 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
7137 { N0.getOperand(0), N0.getOperand(1),
7138 DAG.getConstantFP(-1.0, VT) , DAG.getConstantFP(0.0, VT),
7140 return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT, Ops);
7143 // fold (sint_to_fp (zext (setcc x, y, cc))) ->
7144 // (select_cc x, y, 1.0, 0.0,, cc)
7145 if (N0.getOpcode() == ISD::ZERO_EXTEND &&
7146 N0.getOperand(0).getOpcode() == ISD::SETCC &&!VT.isVector() &&
7147 (!LegalOperations ||
7148 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
7150 { N0.getOperand(0).getOperand(0), N0.getOperand(0).getOperand(1),
7151 DAG.getConstantFP(1.0, VT) , DAG.getConstantFP(0.0, VT),
7152 N0.getOperand(0).getOperand(2) };
7153 return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT, Ops);
7160 SDValue DAGCombiner::visitUINT_TO_FP(SDNode *N) {
7161 SDValue N0 = N->getOperand(0);
7162 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
7163 EVT VT = N->getValueType(0);
7164 EVT OpVT = N0.getValueType();
7166 // fold (uint_to_fp c1) -> c1fp
7168 // ...but only if the target supports immediate floating-point values
7169 (!LegalOperations ||
7170 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT)))
7171 return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0);
7173 // If the input is a legal type, and UINT_TO_FP is not legal on this target,
7174 // but SINT_TO_FP is legal on this target, try to convert.
7175 if (!TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT) &&
7176 TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT)) {
7177 // If the sign bit is known to be zero, we can change this to SINT_TO_FP.
7178 if (DAG.SignBitIsZero(N0))
7179 return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0);
7182 // The next optimizations are desirable only if SELECT_CC can be lowered.
7183 if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT) || !LegalOperations) {
7184 // fold (uint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc)
7186 if (N0.getOpcode() == ISD::SETCC && !VT.isVector() &&
7187 (!LegalOperations ||
7188 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
7190 { N0.getOperand(0), N0.getOperand(1),
7191 DAG.getConstantFP(1.0, VT), DAG.getConstantFP(0.0, VT),
7193 return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT, Ops);
7200 SDValue DAGCombiner::visitFP_TO_SINT(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_sint c1fp) -> c1
7207 return DAG.getNode(ISD::FP_TO_SINT, SDLoc(N), VT, N0);
7212 SDValue DAGCombiner::visitFP_TO_UINT(SDNode *N) {
7213 SDValue N0 = N->getOperand(0);
7214 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7215 EVT VT = N->getValueType(0);
7217 // fold (fp_to_uint c1fp) -> c1
7219 return DAG.getNode(ISD::FP_TO_UINT, SDLoc(N), VT, N0);
7224 SDValue DAGCombiner::visitFP_ROUND(SDNode *N) {
7225 SDValue N0 = N->getOperand(0);
7226 SDValue N1 = N->getOperand(1);
7227 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7228 EVT VT = N->getValueType(0);
7230 // fold (fp_round c1fp) -> c1fp
7232 return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT, N0, N1);
7234 // fold (fp_round (fp_extend x)) -> x
7235 if (N0.getOpcode() == ISD::FP_EXTEND && VT == N0.getOperand(0).getValueType())
7236 return N0.getOperand(0);
7238 // fold (fp_round (fp_round x)) -> (fp_round x)
7239 if (N0.getOpcode() == ISD::FP_ROUND) {
7240 // This is a value preserving truncation if both round's are.
7241 bool IsTrunc = N->getConstantOperandVal(1) == 1 &&
7242 N0.getNode()->getConstantOperandVal(1) == 1;
7243 return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT, N0.getOperand(0),
7244 DAG.getIntPtrConstant(IsTrunc));
7247 // fold (fp_round (copysign X, Y)) -> (copysign (fp_round X), Y)
7248 if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse()) {
7249 SDValue Tmp = DAG.getNode(ISD::FP_ROUND, SDLoc(N0), VT,
7250 N0.getOperand(0), N1);
7251 AddToWorklist(Tmp.getNode());
7252 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
7253 Tmp, N0.getOperand(1));
7259 SDValue DAGCombiner::visitFP_ROUND_INREG(SDNode *N) {
7260 SDValue N0 = N->getOperand(0);
7261 EVT VT = N->getValueType(0);
7262 EVT EVT = cast<VTSDNode>(N->getOperand(1))->getVT();
7263 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7265 // fold (fp_round_inreg c1fp) -> c1fp
7266 if (N0CFP && isTypeLegal(EVT)) {
7267 SDValue Round = DAG.getConstantFP(*N0CFP->getConstantFPValue(), EVT);
7268 return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, Round);
7274 SDValue DAGCombiner::visitFP_EXTEND(SDNode *N) {
7275 SDValue N0 = N->getOperand(0);
7276 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7277 EVT VT = N->getValueType(0);
7279 // If this is fp_round(fpextend), don't fold it, allow ourselves to be folded.
7280 if (N->hasOneUse() &&
7281 N->use_begin()->getOpcode() == ISD::FP_ROUND)
7284 // fold (fp_extend c1fp) -> c1fp
7286 return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, N0);
7288 // Turn fp_extend(fp_round(X, 1)) -> x since the fp_round doesn't affect the
7290 if (N0.getOpcode() == ISD::FP_ROUND
7291 && N0.getNode()->getConstantOperandVal(1) == 1) {
7292 SDValue In = N0.getOperand(0);
7293 if (In.getValueType() == VT) return In;
7294 if (VT.bitsLT(In.getValueType()))
7295 return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT,
7296 In, N0.getOperand(1));
7297 return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, In);
7300 // fold (fpext (load x)) -> (fpext (fptrunc (extload x)))
7301 if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
7302 TLI.isLoadExtLegal(ISD::EXTLOAD, N0.getValueType())) {
7303 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
7304 SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT,
7306 LN0->getBasePtr(), N0.getValueType(),
7307 LN0->getMemOperand());
7308 CombineTo(N, ExtLoad);
7309 CombineTo(N0.getNode(),
7310 DAG.getNode(ISD::FP_ROUND, SDLoc(N0),
7311 N0.getValueType(), ExtLoad, DAG.getIntPtrConstant(1)),
7312 ExtLoad.getValue(1));
7313 return SDValue(N, 0); // Return N so it doesn't get rechecked!
7319 SDValue DAGCombiner::visitFCEIL(SDNode *N) {
7320 SDValue N0 = N->getOperand(0);
7321 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7322 EVT VT = N->getValueType(0);
7324 // fold (fceil c1) -> fceil(c1)
7326 return DAG.getNode(ISD::FCEIL, SDLoc(N), VT, N0);
7331 SDValue DAGCombiner::visitFTRUNC(SDNode *N) {
7332 SDValue N0 = N->getOperand(0);
7333 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7334 EVT VT = N->getValueType(0);
7336 // fold (ftrunc c1) -> ftrunc(c1)
7338 return DAG.getNode(ISD::FTRUNC, SDLoc(N), VT, N0);
7343 SDValue DAGCombiner::visitFFLOOR(SDNode *N) {
7344 SDValue N0 = N->getOperand(0);
7345 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7346 EVT VT = N->getValueType(0);
7348 // fold (ffloor c1) -> ffloor(c1)
7350 return DAG.getNode(ISD::FFLOOR, SDLoc(N), VT, N0);
7355 // FIXME: FNEG and FABS have a lot in common; refactor.
7356 SDValue DAGCombiner::visitFNEG(SDNode *N) {
7357 SDValue N0 = N->getOperand(0);
7358 EVT VT = N->getValueType(0);
7360 if (VT.isVector()) {
7361 SDValue FoldedVOp = SimplifyVUnaryOp(N);
7362 if (FoldedVOp.getNode()) return FoldedVOp;
7365 // Constant fold FNEG.
7366 if (isa<ConstantFPSDNode>(N0))
7367 return DAG.getNode(ISD::FNEG, SDLoc(N), VT, N->getOperand(0));
7369 if (isNegatibleForFree(N0, LegalOperations, DAG.getTargetLoweringInfo(),
7370 &DAG.getTarget().Options))
7371 return GetNegatedExpression(N0, DAG, LegalOperations);
7373 // Transform fneg(bitconvert(x)) -> bitconvert(x ^ sign) to avoid loading
7374 // constant pool values.
7375 if (!TLI.isFNegFree(VT) &&
7376 N0.getOpcode() == ISD::BITCAST &&
7377 N0.getNode()->hasOneUse()) {
7378 SDValue Int = N0.getOperand(0);
7379 EVT IntVT = Int.getValueType();
7380 if (IntVT.isInteger() && !IntVT.isVector()) {
7382 if (N0.getValueType().isVector()) {
7383 // For a vector, get a mask such as 0x80... per scalar element
7385 SignMask = APInt::getSignBit(N0.getValueType().getScalarSizeInBits());
7386 SignMask = APInt::getSplat(IntVT.getSizeInBits(), SignMask);
7388 // For a scalar, just generate 0x80...
7389 SignMask = APInt::getSignBit(IntVT.getSizeInBits());
7391 Int = DAG.getNode(ISD::XOR, SDLoc(N0), IntVT, Int,
7392 DAG.getConstant(SignMask, IntVT));
7393 AddToWorklist(Int.getNode());
7394 return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Int);
7398 // (fneg (fmul c, x)) -> (fmul -c, x)
7399 if (N0.getOpcode() == ISD::FMUL) {
7400 ConstantFPSDNode *CFP1 = dyn_cast<ConstantFPSDNode>(N0.getOperand(1));
7402 APFloat CVal = CFP1->getValueAPF();
7404 if (Level >= AfterLegalizeDAG &&
7405 (TLI.isFPImmLegal(CVal, N->getValueType(0)) ||
7406 TLI.isOperationLegal(ISD::ConstantFP, N->getValueType(0))))
7408 ISD::FMUL, SDLoc(N), VT, N0.getOperand(0),
7409 DAG.getNode(ISD::FNEG, SDLoc(N), VT, N0.getOperand(1)));
7416 SDValue DAGCombiner::visitFABS(SDNode *N) {
7417 SDValue N0 = N->getOperand(0);
7418 EVT VT = N->getValueType(0);
7420 if (VT.isVector()) {
7421 SDValue FoldedVOp = SimplifyVUnaryOp(N);
7422 if (FoldedVOp.getNode()) return FoldedVOp;
7425 // fold (fabs c1) -> fabs(c1)
7426 if (isa<ConstantFPSDNode>(N0))
7427 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
7429 // fold (fabs (fabs x)) -> (fabs x)
7430 if (N0.getOpcode() == ISD::FABS)
7431 return N->getOperand(0);
7433 // fold (fabs (fneg x)) -> (fabs x)
7434 // fold (fabs (fcopysign x, y)) -> (fabs x)
7435 if (N0.getOpcode() == ISD::FNEG || N0.getOpcode() == ISD::FCOPYSIGN)
7436 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0.getOperand(0));
7438 // Transform fabs(bitconvert(x)) -> bitconvert(x & ~sign) to avoid loading
7439 // constant pool values.
7440 if (!TLI.isFAbsFree(VT) &&
7441 N0.getOpcode() == ISD::BITCAST &&
7442 N0.getNode()->hasOneUse()) {
7443 SDValue Int = N0.getOperand(0);
7444 EVT IntVT = Int.getValueType();
7445 if (IntVT.isInteger() && !IntVT.isVector()) {
7447 if (N0.getValueType().isVector()) {
7448 // For a vector, get a mask such as 0x7f... per scalar element
7450 SignMask = ~APInt::getSignBit(N0.getValueType().getScalarSizeInBits());
7451 SignMask = APInt::getSplat(IntVT.getSizeInBits(), SignMask);
7453 // For a scalar, just generate 0x7f...
7454 SignMask = ~APInt::getSignBit(IntVT.getSizeInBits());
7456 Int = DAG.getNode(ISD::AND, SDLoc(N0), IntVT, Int,
7457 DAG.getConstant(SignMask, IntVT));
7458 AddToWorklist(Int.getNode());
7459 return DAG.getNode(ISD::BITCAST, SDLoc(N), N->getValueType(0), Int);
7466 SDValue DAGCombiner::visitBRCOND(SDNode *N) {
7467 SDValue Chain = N->getOperand(0);
7468 SDValue N1 = N->getOperand(1);
7469 SDValue N2 = N->getOperand(2);
7471 // If N is a constant we could fold this into a fallthrough or unconditional
7472 // branch. However that doesn't happen very often in normal code, because
7473 // Instcombine/SimplifyCFG should have handled the available opportunities.
7474 // If we did this folding here, it would be necessary to update the
7475 // MachineBasicBlock CFG, which is awkward.
7477 // fold a brcond with a setcc condition into a BR_CC node if BR_CC is legal
7479 if (N1.getOpcode() == ISD::SETCC &&
7480 TLI.isOperationLegalOrCustom(ISD::BR_CC,
7481 N1.getOperand(0).getValueType())) {
7482 return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other,
7483 Chain, N1.getOperand(2),
7484 N1.getOperand(0), N1.getOperand(1), N2);
7487 if ((N1.hasOneUse() && N1.getOpcode() == ISD::SRL) ||
7488 ((N1.getOpcode() == ISD::TRUNCATE && N1.hasOneUse()) &&
7489 (N1.getOperand(0).hasOneUse() &&
7490 N1.getOperand(0).getOpcode() == ISD::SRL))) {
7491 SDNode *Trunc = nullptr;
7492 if (N1.getOpcode() == ISD::TRUNCATE) {
7493 // Look pass the truncate.
7494 Trunc = N1.getNode();
7495 N1 = N1.getOperand(0);
7498 // Match this pattern so that we can generate simpler code:
7501 // %b = and i32 %a, 2
7502 // %c = srl i32 %b, 1
7503 // brcond i32 %c ...
7508 // %b = and i32 %a, 2
7509 // %c = setcc eq %b, 0
7512 // This applies only when the AND constant value has one bit set and the
7513 // SRL constant is equal to the log2 of the AND constant. The back-end is
7514 // smart enough to convert the result into a TEST/JMP sequence.
7515 SDValue Op0 = N1.getOperand(0);
7516 SDValue Op1 = N1.getOperand(1);
7518 if (Op0.getOpcode() == ISD::AND &&
7519 Op1.getOpcode() == ISD::Constant) {
7520 SDValue AndOp1 = Op0.getOperand(1);
7522 if (AndOp1.getOpcode() == ISD::Constant) {
7523 const APInt &AndConst = cast<ConstantSDNode>(AndOp1)->getAPIntValue();
7525 if (AndConst.isPowerOf2() &&
7526 cast<ConstantSDNode>(Op1)->getAPIntValue()==AndConst.logBase2()) {
7528 DAG.getSetCC(SDLoc(N),
7529 getSetCCResultType(Op0.getValueType()),
7530 Op0, DAG.getConstant(0, Op0.getValueType()),
7533 SDValue NewBRCond = DAG.getNode(ISD::BRCOND, SDLoc(N),
7534 MVT::Other, Chain, SetCC, N2);
7535 // Don't add the new BRCond into the worklist or else SimplifySelectCC
7536 // will convert it back to (X & C1) >> C2.
7537 CombineTo(N, NewBRCond, false);
7538 // Truncate is dead.
7540 deleteAndRecombine(Trunc);
7541 // Replace the uses of SRL with SETCC
7542 WorklistRemover DeadNodes(*this);
7543 DAG.ReplaceAllUsesOfValueWith(N1, SetCC);
7544 deleteAndRecombine(N1.getNode());
7545 return SDValue(N, 0); // Return N so it doesn't get rechecked!
7551 // Restore N1 if the above transformation doesn't match.
7552 N1 = N->getOperand(1);
7555 // Transform br(xor(x, y)) -> br(x != y)
7556 // Transform br(xor(xor(x,y), 1)) -> br (x == y)
7557 if (N1.hasOneUse() && N1.getOpcode() == ISD::XOR) {
7558 SDNode *TheXor = N1.getNode();
7559 SDValue Op0 = TheXor->getOperand(0);
7560 SDValue Op1 = TheXor->getOperand(1);
7561 if (Op0.getOpcode() == Op1.getOpcode()) {
7562 // Avoid missing important xor optimizations.
7563 SDValue Tmp = visitXOR(TheXor);
7564 if (Tmp.getNode()) {
7565 if (Tmp.getNode() != TheXor) {
7566 DEBUG(dbgs() << "\nReplacing.8 ";
7568 dbgs() << "\nWith: ";
7569 Tmp.getNode()->dump(&DAG);
7571 WorklistRemover DeadNodes(*this);
7572 DAG.ReplaceAllUsesOfValueWith(N1, Tmp);
7573 deleteAndRecombine(TheXor);
7574 return DAG.getNode(ISD::BRCOND, SDLoc(N),
7575 MVT::Other, Chain, Tmp, N2);
7578 // visitXOR has changed XOR's operands or replaced the XOR completely,
7580 return SDValue(N, 0);
7584 if (Op0.getOpcode() != ISD::SETCC && Op1.getOpcode() != ISD::SETCC) {
7586 if (ConstantSDNode *RHSCI = dyn_cast<ConstantSDNode>(Op0))
7587 if (RHSCI->getAPIntValue() == 1 && Op0.hasOneUse() &&
7588 Op0.getOpcode() == ISD::XOR) {
7589 TheXor = Op0.getNode();
7593 EVT SetCCVT = N1.getValueType();
7595 SetCCVT = getSetCCResultType(SetCCVT);
7596 SDValue SetCC = DAG.getSetCC(SDLoc(TheXor),
7599 Equal ? ISD::SETEQ : ISD::SETNE);
7600 // Replace the uses of XOR with SETCC
7601 WorklistRemover DeadNodes(*this);
7602 DAG.ReplaceAllUsesOfValueWith(N1, SetCC);
7603 deleteAndRecombine(N1.getNode());
7604 return DAG.getNode(ISD::BRCOND, SDLoc(N),
7605 MVT::Other, Chain, SetCC, N2);
7612 // Operand List for BR_CC: Chain, CondCC, CondLHS, CondRHS, DestBB.
7614 SDValue DAGCombiner::visitBR_CC(SDNode *N) {
7615 CondCodeSDNode *CC = cast<CondCodeSDNode>(N->getOperand(1));
7616 SDValue CondLHS = N->getOperand(2), CondRHS = N->getOperand(3);
7618 // If N is a constant we could fold this into a fallthrough or unconditional
7619 // branch. However that doesn't happen very often in normal code, because
7620 // Instcombine/SimplifyCFG should have handled the available opportunities.
7621 // If we did this folding here, it would be necessary to update the
7622 // MachineBasicBlock CFG, which is awkward.
7624 // Use SimplifySetCC to simplify SETCC's.
7625 SDValue Simp = SimplifySetCC(getSetCCResultType(CondLHS.getValueType()),
7626 CondLHS, CondRHS, CC->get(), SDLoc(N),
7628 if (Simp.getNode()) AddToWorklist(Simp.getNode());
7630 // fold to a simpler setcc
7631 if (Simp.getNode() && Simp.getOpcode() == ISD::SETCC)
7632 return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other,
7633 N->getOperand(0), Simp.getOperand(2),
7634 Simp.getOperand(0), Simp.getOperand(1),
7640 /// Return true if 'Use' is a load or a store that uses N as its base pointer
7641 /// and that N may be folded in the load / store addressing mode.
7642 static bool canFoldInAddressingMode(SDNode *N, SDNode *Use,
7644 const TargetLowering &TLI) {
7646 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Use)) {
7647 if (LD->isIndexed() || LD->getBasePtr().getNode() != N)
7649 VT = Use->getValueType(0);
7650 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(Use)) {
7651 if (ST->isIndexed() || ST->getBasePtr().getNode() != N)
7653 VT = ST->getValue().getValueType();
7657 TargetLowering::AddrMode AM;
7658 if (N->getOpcode() == ISD::ADD) {
7659 ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1));
7662 AM.BaseOffs = Offset->getSExtValue();
7666 } else if (N->getOpcode() == ISD::SUB) {
7667 ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1));
7670 AM.BaseOffs = -Offset->getSExtValue();
7677 return TLI.isLegalAddressingMode(AM, VT.getTypeForEVT(*DAG.getContext()));
7680 /// Try turning a load/store into a pre-indexed load/store when the base
7681 /// pointer is an add or subtract and it has other uses besides the load/store.
7682 /// After the transformation, the new indexed load/store has effectively folded
7683 /// the add/subtract in and all of its other uses are redirected to the
7685 bool DAGCombiner::CombineToPreIndexedLoadStore(SDNode *N) {
7686 if (Level < AfterLegalizeDAG)
7692 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
7693 if (LD->isIndexed())
7695 VT = LD->getMemoryVT();
7696 if (!TLI.isIndexedLoadLegal(ISD::PRE_INC, VT) &&
7697 !TLI.isIndexedLoadLegal(ISD::PRE_DEC, VT))
7699 Ptr = LD->getBasePtr();
7700 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
7701 if (ST->isIndexed())
7703 VT = ST->getMemoryVT();
7704 if (!TLI.isIndexedStoreLegal(ISD::PRE_INC, VT) &&
7705 !TLI.isIndexedStoreLegal(ISD::PRE_DEC, VT))
7707 Ptr = ST->getBasePtr();
7713 // If the pointer is not an add/sub, or if it doesn't have multiple uses, bail
7714 // out. There is no reason to make this a preinc/predec.
7715 if ((Ptr.getOpcode() != ISD::ADD && Ptr.getOpcode() != ISD::SUB) ||
7716 Ptr.getNode()->hasOneUse())
7719 // Ask the target to do addressing mode selection.
7722 ISD::MemIndexedMode AM = ISD::UNINDEXED;
7723 if (!TLI.getPreIndexedAddressParts(N, BasePtr, Offset, AM, DAG))
7726 // Backends without true r+i pre-indexed forms may need to pass a
7727 // constant base with a variable offset so that constant coercion
7728 // will work with the patterns in canonical form.
7729 bool Swapped = false;
7730 if (isa<ConstantSDNode>(BasePtr)) {
7731 std::swap(BasePtr, Offset);
7735 // Don't create a indexed load / store with zero offset.
7736 if (isa<ConstantSDNode>(Offset) &&
7737 cast<ConstantSDNode>(Offset)->isNullValue())
7740 // Try turning it into a pre-indexed load / store except when:
7741 // 1) The new base ptr is a frame index.
7742 // 2) If N is a store and the new base ptr is either the same as or is a
7743 // predecessor of the value being stored.
7744 // 3) Another use of old base ptr is a predecessor of N. If ptr is folded
7745 // that would create a cycle.
7746 // 4) All uses are load / store ops that use it as old base ptr.
7748 // Check #1. Preinc'ing a frame index would require copying the stack pointer
7749 // (plus the implicit offset) to a register to preinc anyway.
7750 if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr))
7755 SDValue Val = cast<StoreSDNode>(N)->getValue();
7756 if (Val == BasePtr || BasePtr.getNode()->isPredecessorOf(Val.getNode()))
7760 // If the offset is a constant, there may be other adds of constants that
7761 // can be folded with this one. We should do this to avoid having to keep
7762 // a copy of the original base pointer.
7763 SmallVector<SDNode *, 16> OtherUses;
7764 if (isa<ConstantSDNode>(Offset))
7765 for (SDNode *Use : BasePtr.getNode()->uses()) {
7766 if (Use == Ptr.getNode())
7769 if (Use->isPredecessorOf(N))
7772 if (Use->getOpcode() != ISD::ADD && Use->getOpcode() != ISD::SUB) {
7777 SDValue Op0 = Use->getOperand(0), Op1 = Use->getOperand(1);
7778 if (Op1.getNode() == BasePtr.getNode())
7779 std::swap(Op0, Op1);
7780 assert(Op0.getNode() == BasePtr.getNode() &&
7781 "Use of ADD/SUB but not an operand");
7783 if (!isa<ConstantSDNode>(Op1)) {
7788 // FIXME: In some cases, we can be smarter about this.
7789 if (Op1.getValueType() != Offset.getValueType()) {
7794 OtherUses.push_back(Use);
7798 std::swap(BasePtr, Offset);
7800 // Now check for #3 and #4.
7801 bool RealUse = false;
7803 // Caches for hasPredecessorHelper
7804 SmallPtrSet<const SDNode *, 32> Visited;
7805 SmallVector<const SDNode *, 16> Worklist;
7807 for (SDNode *Use : Ptr.getNode()->uses()) {
7810 if (N->hasPredecessorHelper(Use, Visited, Worklist))
7813 // If Ptr may be folded in addressing mode of other use, then it's
7814 // not profitable to do this transformation.
7815 if (!canFoldInAddressingMode(Ptr.getNode(), Use, DAG, TLI))
7824 Result = DAG.getIndexedLoad(SDValue(N,0), SDLoc(N),
7825 BasePtr, Offset, AM);
7827 Result = DAG.getIndexedStore(SDValue(N,0), SDLoc(N),
7828 BasePtr, Offset, AM);
7831 DEBUG(dbgs() << "\nReplacing.4 ";
7833 dbgs() << "\nWith: ";
7834 Result.getNode()->dump(&DAG);
7836 WorklistRemover DeadNodes(*this);
7838 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0));
7839 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2));
7841 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1));
7844 // Finally, since the node is now dead, remove it from the graph.
7845 deleteAndRecombine(N);
7848 std::swap(BasePtr, Offset);
7850 // Replace other uses of BasePtr that can be updated to use Ptr
7851 for (unsigned i = 0, e = OtherUses.size(); i != e; ++i) {
7852 unsigned OffsetIdx = 1;
7853 if (OtherUses[i]->getOperand(OffsetIdx).getNode() == BasePtr.getNode())
7855 assert(OtherUses[i]->getOperand(!OffsetIdx).getNode() ==
7856 BasePtr.getNode() && "Expected BasePtr operand");
7858 // We need to replace ptr0 in the following expression:
7859 // x0 * offset0 + y0 * ptr0 = t0
7861 // x1 * offset1 + y1 * ptr0 = t1 (the indexed load/store)
7863 // where x0, x1, y0 and y1 in {-1, 1} are given by the types of the
7864 // indexed load/store and the expresion that needs to be re-written.
7866 // Therefore, we have:
7867 // t0 = (x0 * offset0 - x1 * y0 * y1 *offset1) + (y0 * y1) * t1
7869 ConstantSDNode *CN =
7870 cast<ConstantSDNode>(OtherUses[i]->getOperand(OffsetIdx));
7872 APInt Offset0 = CN->getAPIntValue();
7873 APInt Offset1 = cast<ConstantSDNode>(Offset)->getAPIntValue();
7875 X0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 1) ? -1 : 1;
7876 Y0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 0) ? -1 : 1;
7877 X1 = (AM == ISD::PRE_DEC && !Swapped) ? -1 : 1;
7878 Y1 = (AM == ISD::PRE_DEC && Swapped) ? -1 : 1;
7880 unsigned Opcode = (Y0 * Y1 < 0) ? ISD::SUB : ISD::ADD;
7882 APInt CNV = Offset0;
7883 if (X0 < 0) CNV = -CNV;
7884 if (X1 * Y0 * Y1 < 0) CNV = CNV + Offset1;
7885 else CNV = CNV - Offset1;
7887 // We can now generate the new expression.
7888 SDValue NewOp1 = DAG.getConstant(CNV, CN->getValueType(0));
7889 SDValue NewOp2 = Result.getValue(isLoad ? 1 : 0);
7891 SDValue NewUse = DAG.getNode(Opcode,
7892 SDLoc(OtherUses[i]),
7893 OtherUses[i]->getValueType(0), NewOp1, NewOp2);
7894 DAG.ReplaceAllUsesOfValueWith(SDValue(OtherUses[i], 0), NewUse);
7895 deleteAndRecombine(OtherUses[i]);
7898 // Replace the uses of Ptr with uses of the updated base value.
7899 DAG.ReplaceAllUsesOfValueWith(Ptr, Result.getValue(isLoad ? 1 : 0));
7900 deleteAndRecombine(Ptr.getNode());
7905 /// Try to combine a load/store with a add/sub of the base pointer node into a
7906 /// post-indexed load/store. The transformation folded the add/subtract into the
7907 /// new indexed load/store effectively and all of its uses are redirected to the
7909 bool DAGCombiner::CombineToPostIndexedLoadStore(SDNode *N) {
7910 if (Level < AfterLegalizeDAG)
7916 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
7917 if (LD->isIndexed())
7919 VT = LD->getMemoryVT();
7920 if (!TLI.isIndexedLoadLegal(ISD::POST_INC, VT) &&
7921 !TLI.isIndexedLoadLegal(ISD::POST_DEC, VT))
7923 Ptr = LD->getBasePtr();
7924 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
7925 if (ST->isIndexed())
7927 VT = ST->getMemoryVT();
7928 if (!TLI.isIndexedStoreLegal(ISD::POST_INC, VT) &&
7929 !TLI.isIndexedStoreLegal(ISD::POST_DEC, VT))
7931 Ptr = ST->getBasePtr();
7937 if (Ptr.getNode()->hasOneUse())
7940 for (SDNode *Op : Ptr.getNode()->uses()) {
7942 (Op->getOpcode() != ISD::ADD && Op->getOpcode() != ISD::SUB))
7947 ISD::MemIndexedMode AM = ISD::UNINDEXED;
7948 if (TLI.getPostIndexedAddressParts(N, Op, BasePtr, Offset, AM, DAG)) {
7949 // Don't create a indexed load / store with zero offset.
7950 if (isa<ConstantSDNode>(Offset) &&
7951 cast<ConstantSDNode>(Offset)->isNullValue())
7954 // Try turning it into a post-indexed load / store except when
7955 // 1) All uses are load / store ops that use it as base ptr (and
7956 // it may be folded as addressing mmode).
7957 // 2) Op must be independent of N, i.e. Op is neither a predecessor
7958 // nor a successor of N. Otherwise, if Op is folded that would
7961 if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr))
7965 bool TryNext = false;
7966 for (SDNode *Use : BasePtr.getNode()->uses()) {
7967 if (Use == Ptr.getNode())
7970 // If all the uses are load / store addresses, then don't do the
7972 if (Use->getOpcode() == ISD::ADD || Use->getOpcode() == ISD::SUB){
7973 bool RealUse = false;
7974 for (SDNode *UseUse : Use->uses()) {
7975 if (!canFoldInAddressingMode(Use, UseUse, DAG, TLI))
7990 if (!Op->isPredecessorOf(N) && !N->isPredecessorOf(Op)) {
7991 SDValue Result = isLoad
7992 ? DAG.getIndexedLoad(SDValue(N,0), SDLoc(N),
7993 BasePtr, Offset, AM)
7994 : DAG.getIndexedStore(SDValue(N,0), SDLoc(N),
7995 BasePtr, Offset, AM);
7998 DEBUG(dbgs() << "\nReplacing.5 ";
8000 dbgs() << "\nWith: ";
8001 Result.getNode()->dump(&DAG);
8003 WorklistRemover DeadNodes(*this);
8005 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0));
8006 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2));
8008 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1));
8011 // Finally, since the node is now dead, remove it from the graph.
8012 deleteAndRecombine(N);
8014 // Replace the uses of Use with uses of the updated base value.
8015 DAG.ReplaceAllUsesOfValueWith(SDValue(Op, 0),
8016 Result.getValue(isLoad ? 1 : 0));
8017 deleteAndRecombine(Op);
8026 /// \brief Return the base-pointer arithmetic from an indexed \p LD.
8027 SDValue DAGCombiner::SplitIndexingFromLoad(LoadSDNode *LD) {
8028 ISD::MemIndexedMode AM = LD->getAddressingMode();
8029 assert(AM != ISD::UNINDEXED);
8030 SDValue BP = LD->getOperand(1);
8031 SDValue Inc = LD->getOperand(2);
8033 // Some backends use TargetConstants for load offsets, but don't expect
8034 // TargetConstants in general ADD nodes. We can convert these constants into
8035 // regular Constants (if the constant is not opaque).
8036 assert((Inc.getOpcode() != ISD::TargetConstant ||
8037 !cast<ConstantSDNode>(Inc)->isOpaque()) &&
8038 "Cannot split out indexing using opaque target constants");
8039 if (Inc.getOpcode() == ISD::TargetConstant) {
8040 ConstantSDNode *ConstInc = cast<ConstantSDNode>(Inc);
8041 Inc = DAG.getConstant(*ConstInc->getConstantIntValue(),
8042 ConstInc->getValueType(0));
8046 (AM == ISD::PRE_INC || AM == ISD::POST_INC ? ISD::ADD : ISD::SUB);
8047 return DAG.getNode(Opc, SDLoc(LD), BP.getSimpleValueType(), BP, Inc);
8050 SDValue DAGCombiner::visitLOAD(SDNode *N) {
8051 LoadSDNode *LD = cast<LoadSDNode>(N);
8052 SDValue Chain = LD->getChain();
8053 SDValue Ptr = LD->getBasePtr();
8055 // If load is not volatile and there are no uses of the loaded value (and
8056 // the updated indexed value in case of indexed loads), change uses of the
8057 // chain value into uses of the chain input (i.e. delete the dead load).
8058 if (!LD->isVolatile()) {
8059 if (N->getValueType(1) == MVT::Other) {
8061 if (!N->hasAnyUseOfValue(0)) {
8062 // It's not safe to use the two value CombineTo variant here. e.g.
8063 // v1, chain2 = load chain1, loc
8064 // v2, chain3 = load chain2, loc
8066 // Now we replace use of chain2 with chain1. This makes the second load
8067 // isomorphic to the one we are deleting, and thus makes this load live.
8068 DEBUG(dbgs() << "\nReplacing.6 ";
8070 dbgs() << "\nWith chain: ";
8071 Chain.getNode()->dump(&DAG);
8073 WorklistRemover DeadNodes(*this);
8074 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain);
8077 deleteAndRecombine(N);
8079 return SDValue(N, 0); // Return N so it doesn't get rechecked!
8083 assert(N->getValueType(2) == MVT::Other && "Malformed indexed loads?");
8085 // If this load has an opaque TargetConstant offset, then we cannot split
8086 // the indexing into an add/sub directly (that TargetConstant may not be
8087 // valid for a different type of node, and we cannot convert an opaque
8088 // target constant into a regular constant).
8089 bool HasOTCInc = LD->getOperand(2).getOpcode() == ISD::TargetConstant &&
8090 cast<ConstantSDNode>(LD->getOperand(2))->isOpaque();
8092 if (!N->hasAnyUseOfValue(0) &&
8093 ((MaySplitLoadIndex && !HasOTCInc) || !N->hasAnyUseOfValue(1))) {
8094 SDValue Undef = DAG.getUNDEF(N->getValueType(0));
8096 if (N->hasAnyUseOfValue(1) && MaySplitLoadIndex && !HasOTCInc) {
8097 Index = SplitIndexingFromLoad(LD);
8098 // Try to fold the base pointer arithmetic into subsequent loads and
8100 AddUsersToWorklist(N);
8102 Index = DAG.getUNDEF(N->getValueType(1));
8103 DEBUG(dbgs() << "\nReplacing.7 ";
8105 dbgs() << "\nWith: ";
8106 Undef.getNode()->dump(&DAG);
8107 dbgs() << " and 2 other values\n");
8108 WorklistRemover DeadNodes(*this);
8109 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Undef);
8110 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Index);
8111 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 2), Chain);
8112 deleteAndRecombine(N);
8113 return SDValue(N, 0); // Return N so it doesn't get rechecked!
8118 // If this load is directly stored, replace the load value with the stored
8120 // TODO: Handle store large -> read small portion.
8121 // TODO: Handle TRUNCSTORE/LOADEXT
8122 if (ISD::isNormalLoad(N) && !LD->isVolatile()) {
8123 if (ISD::isNON_TRUNCStore(Chain.getNode())) {
8124 StoreSDNode *PrevST = cast<StoreSDNode>(Chain);
8125 if (PrevST->getBasePtr() == Ptr &&
8126 PrevST->getValue().getValueType() == N->getValueType(0))
8127 return CombineTo(N, Chain.getOperand(1), Chain);
8131 // Try to infer better alignment information than the load already has.
8132 if (OptLevel != CodeGenOpt::None && LD->isUnindexed()) {
8133 if (unsigned Align = DAG.InferPtrAlignment(Ptr)) {
8134 if (Align > LD->getMemOperand()->getBaseAlignment()) {
8136 DAG.getExtLoad(LD->getExtensionType(), SDLoc(N),
8137 LD->getValueType(0),
8138 Chain, Ptr, LD->getPointerInfo(),
8140 LD->isVolatile(), LD->isNonTemporal(),
8141 LD->isInvariant(), Align, LD->getAAInfo());
8142 return CombineTo(N, NewLoad, SDValue(NewLoad.getNode(), 1), true);
8147 bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA :
8148 TLI.getTargetMachine().getSubtarget<TargetSubtargetInfo>().useAA();
8150 if (CombinerAAOnlyFunc.getNumOccurrences() &&
8151 CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
8154 if (UseAA && LD->isUnindexed()) {
8155 // Walk up chain skipping non-aliasing memory nodes.
8156 SDValue BetterChain = FindBetterChain(N, Chain);
8158 // If there is a better chain.
8159 if (Chain != BetterChain) {
8162 // Replace the chain to void dependency.
8163 if (LD->getExtensionType() == ISD::NON_EXTLOAD) {
8164 ReplLoad = DAG.getLoad(N->getValueType(0), SDLoc(LD),
8165 BetterChain, Ptr, LD->getMemOperand());
8167 ReplLoad = DAG.getExtLoad(LD->getExtensionType(), SDLoc(LD),
8168 LD->getValueType(0),
8169 BetterChain, Ptr, LD->getMemoryVT(),
8170 LD->getMemOperand());
8173 // Create token factor to keep old chain connected.
8174 SDValue Token = DAG.getNode(ISD::TokenFactor, SDLoc(N),
8175 MVT::Other, Chain, ReplLoad.getValue(1));
8177 // Make sure the new and old chains are cleaned up.
8178 AddToWorklist(Token.getNode());
8180 // Replace uses with load result and token factor. Don't add users
8182 return CombineTo(N, ReplLoad.getValue(0), Token, false);
8186 // Try transforming N to an indexed load.
8187 if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
8188 return SDValue(N, 0);
8190 // Try to slice up N to more direct loads if the slices are mapped to
8191 // different register banks or pairing can take place.
8193 return SDValue(N, 0);
8199 /// \brief Helper structure used to slice a load in smaller loads.
8200 /// Basically a slice is obtained from the following sequence:
8201 /// Origin = load Ty1, Base
8202 /// Shift = srl Ty1 Origin, CstTy Amount
8203 /// Inst = trunc Shift to Ty2
8205 /// Then, it will be rewriten into:
8206 /// Slice = load SliceTy, Base + SliceOffset
8207 /// [Inst = zext Slice to Ty2], only if SliceTy <> Ty2
8209 /// SliceTy is deduced from the number of bits that are actually used to
8211 struct LoadedSlice {
8212 /// \brief Helper structure used to compute the cost of a slice.
8214 /// Are we optimizing for code size.
8219 unsigned CrossRegisterBanksCopies;
8223 Cost(bool ForCodeSize = false)
8224 : ForCodeSize(ForCodeSize), Loads(0), Truncates(0),
8225 CrossRegisterBanksCopies(0), ZExts(0), Shift(0) {}
8227 /// \brief Get the cost of one isolated slice.
8228 Cost(const LoadedSlice &LS, bool ForCodeSize = false)
8229 : ForCodeSize(ForCodeSize), Loads(1), Truncates(0),
8230 CrossRegisterBanksCopies(0), ZExts(0), Shift(0) {
8231 EVT TruncType = LS.Inst->getValueType(0);
8232 EVT LoadedType = LS.getLoadedType();
8233 if (TruncType != LoadedType &&
8234 !LS.DAG->getTargetLoweringInfo().isZExtFree(LoadedType, TruncType))
8238 /// \brief Account for slicing gain in the current cost.
8239 /// Slicing provide a few gains like removing a shift or a
8240 /// truncate. This method allows to grow the cost of the original
8241 /// load with the gain from this slice.
8242 void addSliceGain(const LoadedSlice &LS) {
8243 // Each slice saves a truncate.
8244 const TargetLowering &TLI = LS.DAG->getTargetLoweringInfo();
8245 if (!TLI.isTruncateFree(LS.Inst->getValueType(0),
8246 LS.Inst->getOperand(0).getValueType()))
8248 // If there is a shift amount, this slice gets rid of it.
8251 // If this slice can merge a cross register bank copy, account for it.
8252 if (LS.canMergeExpensiveCrossRegisterBankCopy())
8253 ++CrossRegisterBanksCopies;
8256 Cost &operator+=(const Cost &RHS) {
8258 Truncates += RHS.Truncates;
8259 CrossRegisterBanksCopies += RHS.CrossRegisterBanksCopies;
8265 bool operator==(const Cost &RHS) const {
8266 return Loads == RHS.Loads && Truncates == RHS.Truncates &&
8267 CrossRegisterBanksCopies == RHS.CrossRegisterBanksCopies &&
8268 ZExts == RHS.ZExts && Shift == RHS.Shift;
8271 bool operator!=(const Cost &RHS) const { return !(*this == RHS); }
8273 bool operator<(const Cost &RHS) const {
8274 // Assume cross register banks copies are as expensive as loads.
8275 // FIXME: Do we want some more target hooks?
8276 unsigned ExpensiveOpsLHS = Loads + CrossRegisterBanksCopies;
8277 unsigned ExpensiveOpsRHS = RHS.Loads + RHS.CrossRegisterBanksCopies;
8278 // Unless we are optimizing for code size, consider the
8279 // expensive operation first.
8280 if (!ForCodeSize && ExpensiveOpsLHS != ExpensiveOpsRHS)
8281 return ExpensiveOpsLHS < ExpensiveOpsRHS;
8282 return (Truncates + ZExts + Shift + ExpensiveOpsLHS) <
8283 (RHS.Truncates + RHS.ZExts + RHS.Shift + ExpensiveOpsRHS);
8286 bool operator>(const Cost &RHS) const { return RHS < *this; }
8288 bool operator<=(const Cost &RHS) const { return !(RHS < *this); }
8290 bool operator>=(const Cost &RHS) const { return !(*this < RHS); }
8292 // The last instruction that represent the slice. This should be a
8293 // truncate instruction.
8295 // The original load instruction.
8297 // The right shift amount in bits from the original load.
8299 // The DAG from which Origin came from.
8300 // This is used to get some contextual information about legal types, etc.
8303 LoadedSlice(SDNode *Inst = nullptr, LoadSDNode *Origin = nullptr,
8304 unsigned Shift = 0, SelectionDAG *DAG = nullptr)
8305 : Inst(Inst), Origin(Origin), Shift(Shift), DAG(DAG) {}
8307 LoadedSlice(const LoadedSlice &LS)
8308 : Inst(LS.Inst), Origin(LS.Origin), Shift(LS.Shift), DAG(LS.DAG) {}
8310 /// \brief Get the bits used in a chunk of bits \p BitWidth large.
8311 /// \return Result is \p BitWidth and has used bits set to 1 and
8312 /// not used bits set to 0.
8313 APInt getUsedBits() const {
8314 // Reproduce the trunc(lshr) sequence:
8315 // - Start from the truncated value.
8316 // - Zero extend to the desired bit width.
8318 assert(Origin && "No original load to compare against.");
8319 unsigned BitWidth = Origin->getValueSizeInBits(0);
8320 assert(Inst && "This slice is not bound to an instruction");
8321 assert(Inst->getValueSizeInBits(0) <= BitWidth &&
8322 "Extracted slice is bigger than the whole type!");
8323 APInt UsedBits(Inst->getValueSizeInBits(0), 0);
8324 UsedBits.setAllBits();
8325 UsedBits = UsedBits.zext(BitWidth);
8330 /// \brief Get the size of the slice to be loaded in bytes.
8331 unsigned getLoadedSize() const {
8332 unsigned SliceSize = getUsedBits().countPopulation();
8333 assert(!(SliceSize & 0x7) && "Size is not a multiple of a byte.");
8334 return SliceSize / 8;
8337 /// \brief Get the type that will be loaded for this slice.
8338 /// Note: This may not be the final type for the slice.
8339 EVT getLoadedType() const {
8340 assert(DAG && "Missing context");
8341 LLVMContext &Ctxt = *DAG->getContext();
8342 return EVT::getIntegerVT(Ctxt, getLoadedSize() * 8);
8345 /// \brief Get the alignment of the load used for this slice.
8346 unsigned getAlignment() const {
8347 unsigned Alignment = Origin->getAlignment();
8348 unsigned Offset = getOffsetFromBase();
8350 Alignment = MinAlign(Alignment, Alignment + Offset);
8354 /// \brief Check if this slice can be rewritten with legal operations.
8355 bool isLegal() const {
8356 // An invalid slice is not legal.
8357 if (!Origin || !Inst || !DAG)
8360 // Offsets are for indexed load only, we do not handle that.
8361 if (Origin->getOffset().getOpcode() != ISD::UNDEF)
8364 const TargetLowering &TLI = DAG->getTargetLoweringInfo();
8366 // Check that the type is legal.
8367 EVT SliceType = getLoadedType();
8368 if (!TLI.isTypeLegal(SliceType))
8371 // Check that the load is legal for this type.
8372 if (!TLI.isOperationLegal(ISD::LOAD, SliceType))
8375 // Check that the offset can be computed.
8376 // 1. Check its type.
8377 EVT PtrType = Origin->getBasePtr().getValueType();
8378 if (PtrType == MVT::Untyped || PtrType.isExtended())
8381 // 2. Check that it fits in the immediate.
8382 if (!TLI.isLegalAddImmediate(getOffsetFromBase()))
8385 // 3. Check that the computation is legal.
8386 if (!TLI.isOperationLegal(ISD::ADD, PtrType))
8389 // Check that the zext is legal if it needs one.
8390 EVT TruncateType = Inst->getValueType(0);
8391 if (TruncateType != SliceType &&
8392 !TLI.isOperationLegal(ISD::ZERO_EXTEND, TruncateType))
8398 /// \brief Get the offset in bytes of this slice in the original chunk of
8400 /// \pre DAG != nullptr.
8401 uint64_t getOffsetFromBase() const {
8402 assert(DAG && "Missing context.");
8404 DAG->getTargetLoweringInfo().getDataLayout()->isBigEndian();
8405 assert(!(Shift & 0x7) && "Shifts not aligned on Bytes are not supported.");
8406 uint64_t Offset = Shift / 8;
8407 unsigned TySizeInBytes = Origin->getValueSizeInBits(0) / 8;
8408 assert(!(Origin->getValueSizeInBits(0) & 0x7) &&
8409 "The size of the original loaded type is not a multiple of a"
8411 // If Offset is bigger than TySizeInBytes, it means we are loading all
8412 // zeros. This should have been optimized before in the process.
8413 assert(TySizeInBytes > Offset &&
8414 "Invalid shift amount for given loaded size");
8416 Offset = TySizeInBytes - Offset - getLoadedSize();
8420 /// \brief Generate the sequence of instructions to load the slice
8421 /// represented by this object and redirect the uses of this slice to
8422 /// this new sequence of instructions.
8423 /// \pre this->Inst && this->Origin are valid Instructions and this
8424 /// object passed the legal check: LoadedSlice::isLegal returned true.
8425 /// \return The last instruction of the sequence used to load the slice.
8426 SDValue loadSlice() const {
8427 assert(Inst && Origin && "Unable to replace a non-existing slice.");
8428 const SDValue &OldBaseAddr = Origin->getBasePtr();
8429 SDValue BaseAddr = OldBaseAddr;
8430 // Get the offset in that chunk of bytes w.r.t. the endianess.
8431 int64_t Offset = static_cast<int64_t>(getOffsetFromBase());
8432 assert(Offset >= 0 && "Offset too big to fit in int64_t!");
8434 // BaseAddr = BaseAddr + Offset.
8435 EVT ArithType = BaseAddr.getValueType();
8436 BaseAddr = DAG->getNode(ISD::ADD, SDLoc(Origin), ArithType, BaseAddr,
8437 DAG->getConstant(Offset, ArithType));
8440 // Create the type of the loaded slice according to its size.
8441 EVT SliceType = getLoadedType();
8443 // Create the load for the slice.
8444 SDValue LastInst = DAG->getLoad(
8445 SliceType, SDLoc(Origin), Origin->getChain(), BaseAddr,
8446 Origin->getPointerInfo().getWithOffset(Offset), Origin->isVolatile(),
8447 Origin->isNonTemporal(), Origin->isInvariant(), getAlignment());
8448 // If the final type is not the same as the loaded type, this means that
8449 // we have to pad with zero. Create a zero extend for that.
8450 EVT FinalType = Inst->getValueType(0);
8451 if (SliceType != FinalType)
8453 DAG->getNode(ISD::ZERO_EXTEND, SDLoc(LastInst), FinalType, LastInst);
8457 /// \brief Check if this slice can be merged with an expensive cross register
8458 /// bank copy. E.g.,
8460 /// f = bitcast i32 i to float
8461 bool canMergeExpensiveCrossRegisterBankCopy() const {
8462 if (!Inst || !Inst->hasOneUse())
8464 SDNode *Use = *Inst->use_begin();
8465 if (Use->getOpcode() != ISD::BITCAST)
8467 assert(DAG && "Missing context");
8468 const TargetLowering &TLI = DAG->getTargetLoweringInfo();
8469 EVT ResVT = Use->getValueType(0);
8470 const TargetRegisterClass *ResRC = TLI.getRegClassFor(ResVT.getSimpleVT());
8471 const TargetRegisterClass *ArgRC =
8472 TLI.getRegClassFor(Use->getOperand(0).getValueType().getSimpleVT());
8473 if (ArgRC == ResRC || !TLI.isOperationLegal(ISD::LOAD, ResVT))
8476 // At this point, we know that we perform a cross-register-bank copy.
8477 // Check if it is expensive.
8478 const TargetRegisterInfo *TRI =
8479 TLI.getTargetMachine().getSubtargetImpl()->getRegisterInfo();
8480 // Assume bitcasts are cheap, unless both register classes do not
8481 // explicitly share a common sub class.
8482 if (!TRI || TRI->getCommonSubClass(ArgRC, ResRC))
8485 // Check if it will be merged with the load.
8486 // 1. Check the alignment constraint.
8487 unsigned RequiredAlignment = TLI.getDataLayout()->getABITypeAlignment(
8488 ResVT.getTypeForEVT(*DAG->getContext()));
8490 if (RequiredAlignment > getAlignment())
8493 // 2. Check that the load is a legal operation for that type.
8494 if (!TLI.isOperationLegal(ISD::LOAD, ResVT))
8497 // 3. Check that we do not have a zext in the way.
8498 if (Inst->getValueType(0) != getLoadedType())
8506 /// \brief Check that all bits set in \p UsedBits form a dense region, i.e.,
8507 /// \p UsedBits looks like 0..0 1..1 0..0.
8508 static bool areUsedBitsDense(const APInt &UsedBits) {
8509 // If all the bits are one, this is dense!
8510 if (UsedBits.isAllOnesValue())
8513 // Get rid of the unused bits on the right.
8514 APInt NarrowedUsedBits = UsedBits.lshr(UsedBits.countTrailingZeros());
8515 // Get rid of the unused bits on the left.
8516 if (NarrowedUsedBits.countLeadingZeros())
8517 NarrowedUsedBits = NarrowedUsedBits.trunc(NarrowedUsedBits.getActiveBits());
8518 // Check that the chunk of bits is completely used.
8519 return NarrowedUsedBits.isAllOnesValue();
8522 /// \brief Check whether or not \p First and \p Second are next to each other
8523 /// in memory. This means that there is no hole between the bits loaded
8524 /// by \p First and the bits loaded by \p Second.
8525 static bool areSlicesNextToEachOther(const LoadedSlice &First,
8526 const LoadedSlice &Second) {
8527 assert(First.Origin == Second.Origin && First.Origin &&
8528 "Unable to match different memory origins.");
8529 APInt UsedBits = First.getUsedBits();
8530 assert((UsedBits & Second.getUsedBits()) == 0 &&
8531 "Slices are not supposed to overlap.");
8532 UsedBits |= Second.getUsedBits();
8533 return areUsedBitsDense(UsedBits);
8536 /// \brief Adjust the \p GlobalLSCost according to the target
8537 /// paring capabilities and the layout of the slices.
8538 /// \pre \p GlobalLSCost should account for at least as many loads as
8539 /// there is in the slices in \p LoadedSlices.
8540 static void adjustCostForPairing(SmallVectorImpl<LoadedSlice> &LoadedSlices,
8541 LoadedSlice::Cost &GlobalLSCost) {
8542 unsigned NumberOfSlices = LoadedSlices.size();
8543 // If there is less than 2 elements, no pairing is possible.
8544 if (NumberOfSlices < 2)
8547 // Sort the slices so that elements that are likely to be next to each
8548 // other in memory are next to each other in the list.
8549 std::sort(LoadedSlices.begin(), LoadedSlices.end(),
8550 [](const LoadedSlice &LHS, const LoadedSlice &RHS) {
8551 assert(LHS.Origin == RHS.Origin && "Different bases not implemented.");
8552 return LHS.getOffsetFromBase() < RHS.getOffsetFromBase();
8554 const TargetLowering &TLI = LoadedSlices[0].DAG->getTargetLoweringInfo();
8555 // First (resp. Second) is the first (resp. Second) potentially candidate
8556 // to be placed in a paired load.
8557 const LoadedSlice *First = nullptr;
8558 const LoadedSlice *Second = nullptr;
8559 for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice,
8560 // Set the beginning of the pair.
8563 Second = &LoadedSlices[CurrSlice];
8565 // If First is NULL, it means we start a new pair.
8566 // Get to the next slice.
8570 EVT LoadedType = First->getLoadedType();
8572 // If the types of the slices are different, we cannot pair them.
8573 if (LoadedType != Second->getLoadedType())
8576 // Check if the target supplies paired loads for this type.
8577 unsigned RequiredAlignment = 0;
8578 if (!TLI.hasPairedLoad(LoadedType, RequiredAlignment)) {
8579 // move to the next pair, this type is hopeless.
8583 // Check if we meet the alignment requirement.
8584 if (RequiredAlignment > First->getAlignment())
8587 // Check that both loads are next to each other in memory.
8588 if (!areSlicesNextToEachOther(*First, *Second))
8591 assert(GlobalLSCost.Loads > 0 && "We save more loads than we created!");
8592 --GlobalLSCost.Loads;
8593 // Move to the next pair.
8598 /// \brief Check the profitability of all involved LoadedSlice.
8599 /// Currently, it is considered profitable if there is exactly two
8600 /// involved slices (1) which are (2) next to each other in memory, and
8601 /// whose cost (\see LoadedSlice::Cost) is smaller than the original load (3).
8603 /// Note: The order of the elements in \p LoadedSlices may be modified, but not
8604 /// the elements themselves.
8606 /// FIXME: When the cost model will be mature enough, we can relax
8607 /// constraints (1) and (2).
8608 static bool isSlicingProfitable(SmallVectorImpl<LoadedSlice> &LoadedSlices,
8609 const APInt &UsedBits, bool ForCodeSize) {
8610 unsigned NumberOfSlices = LoadedSlices.size();
8611 if (StressLoadSlicing)
8612 return NumberOfSlices > 1;
8615 if (NumberOfSlices != 2)
8619 if (!areUsedBitsDense(UsedBits))
8623 LoadedSlice::Cost OrigCost(ForCodeSize), GlobalSlicingCost(ForCodeSize);
8624 // The original code has one big load.
8626 for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice) {
8627 const LoadedSlice &LS = LoadedSlices[CurrSlice];
8628 // Accumulate the cost of all the slices.
8629 LoadedSlice::Cost SliceCost(LS, ForCodeSize);
8630 GlobalSlicingCost += SliceCost;
8632 // Account as cost in the original configuration the gain obtained
8633 // with the current slices.
8634 OrigCost.addSliceGain(LS);
8637 // If the target supports paired load, adjust the cost accordingly.
8638 adjustCostForPairing(LoadedSlices, GlobalSlicingCost);
8639 return OrigCost > GlobalSlicingCost;
8642 /// \brief If the given load, \p LI, is used only by trunc or trunc(lshr)
8643 /// operations, split it in the various pieces being extracted.
8645 /// This sort of thing is introduced by SROA.
8646 /// This slicing takes care not to insert overlapping loads.
8647 /// \pre LI is a simple load (i.e., not an atomic or volatile load).
8648 bool DAGCombiner::SliceUpLoad(SDNode *N) {
8649 if (Level < AfterLegalizeDAG)
8652 LoadSDNode *LD = cast<LoadSDNode>(N);
8653 if (LD->isVolatile() || !ISD::isNormalLoad(LD) ||
8654 !LD->getValueType(0).isInteger())
8657 // Keep track of already used bits to detect overlapping values.
8658 // In that case, we will just abort the transformation.
8659 APInt UsedBits(LD->getValueSizeInBits(0), 0);
8661 SmallVector<LoadedSlice, 4> LoadedSlices;
8663 // Check if this load is used as several smaller chunks of bits.
8664 // Basically, look for uses in trunc or trunc(lshr) and record a new chain
8665 // of computation for each trunc.
8666 for (SDNode::use_iterator UI = LD->use_begin(), UIEnd = LD->use_end();
8667 UI != UIEnd; ++UI) {
8668 // Skip the uses of the chain.
8669 if (UI.getUse().getResNo() != 0)
8675 // Check if this is a trunc(lshr).
8676 if (User->getOpcode() == ISD::SRL && User->hasOneUse() &&
8677 isa<ConstantSDNode>(User->getOperand(1))) {
8678 Shift = cast<ConstantSDNode>(User->getOperand(1))->getZExtValue();
8679 User = *User->use_begin();
8682 // At this point, User is a Truncate, iff we encountered, trunc or
8684 if (User->getOpcode() != ISD::TRUNCATE)
8687 // The width of the type must be a power of 2 and greater than 8-bits.
8688 // Otherwise the load cannot be represented in LLVM IR.
8689 // Moreover, if we shifted with a non-8-bits multiple, the slice
8690 // will be across several bytes. We do not support that.
8691 unsigned Width = User->getValueSizeInBits(0);
8692 if (Width < 8 || !isPowerOf2_32(Width) || (Shift & 0x7))
8695 // Build the slice for this chain of computations.
8696 LoadedSlice LS(User, LD, Shift, &DAG);
8697 APInt CurrentUsedBits = LS.getUsedBits();
8699 // Check if this slice overlaps with another.
8700 if ((CurrentUsedBits & UsedBits) != 0)
8702 // Update the bits used globally.
8703 UsedBits |= CurrentUsedBits;
8705 // Check if the new slice would be legal.
8709 // Record the slice.
8710 LoadedSlices.push_back(LS);
8713 // Abort slicing if it does not seem to be profitable.
8714 if (!isSlicingProfitable(LoadedSlices, UsedBits, ForCodeSize))
8719 // Rewrite each chain to use an independent load.
8720 // By construction, each chain can be represented by a unique load.
8722 // Prepare the argument for the new token factor for all the slices.
8723 SmallVector<SDValue, 8> ArgChains;
8724 for (SmallVectorImpl<LoadedSlice>::const_iterator
8725 LSIt = LoadedSlices.begin(),
8726 LSItEnd = LoadedSlices.end();
8727 LSIt != LSItEnd; ++LSIt) {
8728 SDValue SliceInst = LSIt->loadSlice();
8729 CombineTo(LSIt->Inst, SliceInst, true);
8730 if (SliceInst.getNode()->getOpcode() != ISD::LOAD)
8731 SliceInst = SliceInst.getOperand(0);
8732 assert(SliceInst->getOpcode() == ISD::LOAD &&
8733 "It takes more than a zext to get to the loaded slice!!");
8734 ArgChains.push_back(SliceInst.getValue(1));
8737 SDValue Chain = DAG.getNode(ISD::TokenFactor, SDLoc(LD), MVT::Other,
8739 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain);
8743 /// Check to see if V is (and load (ptr), imm), where the load is having
8744 /// specific bytes cleared out. If so, return the byte size being masked out
8745 /// and the shift amount.
8746 static std::pair<unsigned, unsigned>
8747 CheckForMaskedLoad(SDValue V, SDValue Ptr, SDValue Chain) {
8748 std::pair<unsigned, unsigned> Result(0, 0);
8750 // Check for the structure we're looking for.
8751 if (V->getOpcode() != ISD::AND ||
8752 !isa<ConstantSDNode>(V->getOperand(1)) ||
8753 !ISD::isNormalLoad(V->getOperand(0).getNode()))
8756 // Check the chain and pointer.
8757 LoadSDNode *LD = cast<LoadSDNode>(V->getOperand(0));
8758 if (LD->getBasePtr() != Ptr) return Result; // Not from same pointer.
8760 // The store should be chained directly to the load or be an operand of a
8762 if (LD == Chain.getNode())
8764 else if (Chain->getOpcode() != ISD::TokenFactor)
8765 return Result; // Fail.
8768 for (unsigned i = 0, e = Chain->getNumOperands(); i != e; ++i)
8769 if (Chain->getOperand(i).getNode() == LD) {
8773 if (!isOk) return Result;
8776 // This only handles simple types.
8777 if (V.getValueType() != MVT::i16 &&
8778 V.getValueType() != MVT::i32 &&
8779 V.getValueType() != MVT::i64)
8782 // Check the constant mask. Invert it so that the bits being masked out are
8783 // 0 and the bits being kept are 1. Use getSExtValue so that leading bits
8784 // follow the sign bit for uniformity.
8785 uint64_t NotMask = ~cast<ConstantSDNode>(V->getOperand(1))->getSExtValue();
8786 unsigned NotMaskLZ = countLeadingZeros(NotMask);
8787 if (NotMaskLZ & 7) return Result; // Must be multiple of a byte.
8788 unsigned NotMaskTZ = countTrailingZeros(NotMask);
8789 if (NotMaskTZ & 7) return Result; // Must be multiple of a byte.
8790 if (NotMaskLZ == 64) return Result; // All zero mask.
8792 // See if we have a continuous run of bits. If so, we have 0*1+0*
8793 if (CountTrailingOnes_64(NotMask >> NotMaskTZ)+NotMaskTZ+NotMaskLZ != 64)
8796 // Adjust NotMaskLZ down to be from the actual size of the int instead of i64.
8797 if (V.getValueType() != MVT::i64 && NotMaskLZ)
8798 NotMaskLZ -= 64-V.getValueSizeInBits();
8800 unsigned MaskedBytes = (V.getValueSizeInBits()-NotMaskLZ-NotMaskTZ)/8;
8801 switch (MaskedBytes) {
8805 default: return Result; // All one mask, or 5-byte mask.
8808 // Verify that the first bit starts at a multiple of mask so that the access
8809 // is aligned the same as the access width.
8810 if (NotMaskTZ && NotMaskTZ/8 % MaskedBytes) return Result;
8812 Result.first = MaskedBytes;
8813 Result.second = NotMaskTZ/8;
8818 /// Check to see if IVal is something that provides a value as specified by
8819 /// MaskInfo. If so, replace the specified store with a narrower store of
8822 ShrinkLoadReplaceStoreWithStore(const std::pair<unsigned, unsigned> &MaskInfo,
8823 SDValue IVal, StoreSDNode *St,
8825 unsigned NumBytes = MaskInfo.first;
8826 unsigned ByteShift = MaskInfo.second;
8827 SelectionDAG &DAG = DC->getDAG();
8829 // Check to see if IVal is all zeros in the part being masked in by the 'or'
8830 // that uses this. If not, this is not a replacement.
8831 APInt Mask = ~APInt::getBitsSet(IVal.getValueSizeInBits(),
8832 ByteShift*8, (ByteShift+NumBytes)*8);
8833 if (!DAG.MaskedValueIsZero(IVal, Mask)) return nullptr;
8835 // Check that it is legal on the target to do this. It is legal if the new
8836 // VT we're shrinking to (i8/i16/i32) is legal or we're still before type
8838 MVT VT = MVT::getIntegerVT(NumBytes*8);
8839 if (!DC->isTypeLegal(VT))
8842 // Okay, we can do this! Replace the 'St' store with a store of IVal that is
8843 // shifted by ByteShift and truncated down to NumBytes.
8845 IVal = DAG.getNode(ISD::SRL, SDLoc(IVal), IVal.getValueType(), IVal,
8846 DAG.getConstant(ByteShift*8,
8847 DC->getShiftAmountTy(IVal.getValueType())));
8849 // Figure out the offset for the store and the alignment of the access.
8851 unsigned NewAlign = St->getAlignment();
8853 if (DAG.getTargetLoweringInfo().isLittleEndian())
8854 StOffset = ByteShift;
8856 StOffset = IVal.getValueType().getStoreSize() - ByteShift - NumBytes;
8858 SDValue Ptr = St->getBasePtr();
8860 Ptr = DAG.getNode(ISD::ADD, SDLoc(IVal), Ptr.getValueType(),
8861 Ptr, DAG.getConstant(StOffset, Ptr.getValueType()));
8862 NewAlign = MinAlign(NewAlign, StOffset);
8865 // Truncate down to the new size.
8866 IVal = DAG.getNode(ISD::TRUNCATE, SDLoc(IVal), VT, IVal);
8869 return DAG.getStore(St->getChain(), SDLoc(St), IVal, Ptr,
8870 St->getPointerInfo().getWithOffset(StOffset),
8871 false, false, NewAlign).getNode();
8875 /// Look for sequence of load / op / store where op is one of 'or', 'xor', and
8876 /// 'and' of immediates. If 'op' is only touching some of the loaded bits, try
8877 /// narrowing the load and store if it would end up being a win for performance
8879 SDValue DAGCombiner::ReduceLoadOpStoreWidth(SDNode *N) {
8880 StoreSDNode *ST = cast<StoreSDNode>(N);
8881 if (ST->isVolatile())
8884 SDValue Chain = ST->getChain();
8885 SDValue Value = ST->getValue();
8886 SDValue Ptr = ST->getBasePtr();
8887 EVT VT = Value.getValueType();
8889 if (ST->isTruncatingStore() || VT.isVector() || !Value.hasOneUse())
8892 unsigned Opc = Value.getOpcode();
8894 // If this is "store (or X, Y), P" and X is "(and (load P), cst)", where cst
8895 // is a byte mask indicating a consecutive number of bytes, check to see if
8896 // Y is known to provide just those bytes. If so, we try to replace the
8897 // load + replace + store sequence with a single (narrower) store, which makes
8899 if (Opc == ISD::OR) {
8900 std::pair<unsigned, unsigned> MaskedLoad;
8901 MaskedLoad = CheckForMaskedLoad(Value.getOperand(0), Ptr, Chain);
8902 if (MaskedLoad.first)
8903 if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad,
8904 Value.getOperand(1), ST,this))
8905 return SDValue(NewST, 0);
8907 // Or is commutative, so try swapping X and Y.
8908 MaskedLoad = CheckForMaskedLoad(Value.getOperand(1), Ptr, Chain);
8909 if (MaskedLoad.first)
8910 if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad,
8911 Value.getOperand(0), ST,this))
8912 return SDValue(NewST, 0);
8915 if ((Opc != ISD::OR && Opc != ISD::XOR && Opc != ISD::AND) ||
8916 Value.getOperand(1).getOpcode() != ISD::Constant)
8919 SDValue N0 = Value.getOperand(0);
8920 if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
8921 Chain == SDValue(N0.getNode(), 1)) {
8922 LoadSDNode *LD = cast<LoadSDNode>(N0);
8923 if (LD->getBasePtr() != Ptr ||
8924 LD->getPointerInfo().getAddrSpace() !=
8925 ST->getPointerInfo().getAddrSpace())
8928 // Find the type to narrow it the load / op / store to.
8929 SDValue N1 = Value.getOperand(1);
8930 unsigned BitWidth = N1.getValueSizeInBits();
8931 APInt Imm = cast<ConstantSDNode>(N1)->getAPIntValue();
8932 if (Opc == ISD::AND)
8933 Imm ^= APInt::getAllOnesValue(BitWidth);
8934 if (Imm == 0 || Imm.isAllOnesValue())
8936 unsigned ShAmt = Imm.countTrailingZeros();
8937 unsigned MSB = BitWidth - Imm.countLeadingZeros() - 1;
8938 unsigned NewBW = NextPowerOf2(MSB - ShAmt);
8939 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW);
8940 while (NewBW < BitWidth &&
8941 !(TLI.isOperationLegalOrCustom(Opc, NewVT) &&
8942 TLI.isNarrowingProfitable(VT, NewVT))) {
8943 NewBW = NextPowerOf2(NewBW);
8944 NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW);
8946 if (NewBW >= BitWidth)
8949 // If the lsb changed does not start at the type bitwidth boundary,
8950 // start at the previous one.
8952 ShAmt = (((ShAmt + NewBW - 1) / NewBW) * NewBW) - NewBW;
8953 APInt Mask = APInt::getBitsSet(BitWidth, ShAmt,
8954 std::min(BitWidth, ShAmt + NewBW));
8955 if ((Imm & Mask) == Imm) {
8956 APInt NewImm = (Imm & Mask).lshr(ShAmt).trunc(NewBW);
8957 if (Opc == ISD::AND)
8958 NewImm ^= APInt::getAllOnesValue(NewBW);
8959 uint64_t PtrOff = ShAmt / 8;
8960 // For big endian targets, we need to adjust the offset to the pointer to
8961 // load the correct bytes.
8962 if (TLI.isBigEndian())
8963 PtrOff = (BitWidth + 7 - NewBW) / 8 - PtrOff;
8965 unsigned NewAlign = MinAlign(LD->getAlignment(), PtrOff);
8966 Type *NewVTTy = NewVT.getTypeForEVT(*DAG.getContext());
8967 if (NewAlign < TLI.getDataLayout()->getABITypeAlignment(NewVTTy))
8970 SDValue NewPtr = DAG.getNode(ISD::ADD, SDLoc(LD),
8971 Ptr.getValueType(), Ptr,
8972 DAG.getConstant(PtrOff, Ptr.getValueType()));
8973 SDValue NewLD = DAG.getLoad(NewVT, SDLoc(N0),
8974 LD->getChain(), NewPtr,
8975 LD->getPointerInfo().getWithOffset(PtrOff),
8976 LD->isVolatile(), LD->isNonTemporal(),
8977 LD->isInvariant(), NewAlign,
8979 SDValue NewVal = DAG.getNode(Opc, SDLoc(Value), NewVT, NewLD,
8980 DAG.getConstant(NewImm, NewVT));
8981 SDValue NewST = DAG.getStore(Chain, SDLoc(N),
8983 ST->getPointerInfo().getWithOffset(PtrOff),
8984 false, false, NewAlign);
8986 AddToWorklist(NewPtr.getNode());
8987 AddToWorklist(NewLD.getNode());
8988 AddToWorklist(NewVal.getNode());
8989 WorklistRemover DeadNodes(*this);
8990 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLD.getValue(1));
8999 /// For a given floating point load / store pair, if the load value isn't used
9000 /// by any other operations, then consider transforming the pair to integer
9001 /// load / store operations if the target deems the transformation profitable.
9002 SDValue DAGCombiner::TransformFPLoadStorePair(SDNode *N) {
9003 StoreSDNode *ST = cast<StoreSDNode>(N);
9004 SDValue Chain = ST->getChain();
9005 SDValue Value = ST->getValue();
9006 if (ISD::isNormalStore(ST) && ISD::isNormalLoad(Value.getNode()) &&
9007 Value.hasOneUse() &&
9008 Chain == SDValue(Value.getNode(), 1)) {
9009 LoadSDNode *LD = cast<LoadSDNode>(Value);
9010 EVT VT = LD->getMemoryVT();
9011 if (!VT.isFloatingPoint() ||
9012 VT != ST->getMemoryVT() ||
9013 LD->isNonTemporal() ||
9014 ST->isNonTemporal() ||
9015 LD->getPointerInfo().getAddrSpace() != 0 ||
9016 ST->getPointerInfo().getAddrSpace() != 0)
9019 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), VT.getSizeInBits());
9020 if (!TLI.isOperationLegal(ISD::LOAD, IntVT) ||
9021 !TLI.isOperationLegal(ISD::STORE, IntVT) ||
9022 !TLI.isDesirableToTransformToIntegerOp(ISD::LOAD, VT) ||
9023 !TLI.isDesirableToTransformToIntegerOp(ISD::STORE, VT))
9026 unsigned LDAlign = LD->getAlignment();
9027 unsigned STAlign = ST->getAlignment();
9028 Type *IntVTTy = IntVT.getTypeForEVT(*DAG.getContext());
9029 unsigned ABIAlign = TLI.getDataLayout()->getABITypeAlignment(IntVTTy);
9030 if (LDAlign < ABIAlign || STAlign < ABIAlign)
9033 SDValue NewLD = DAG.getLoad(IntVT, SDLoc(Value),
9034 LD->getChain(), LD->getBasePtr(),
9035 LD->getPointerInfo(),
9036 false, false, false, LDAlign);
9038 SDValue NewST = DAG.getStore(NewLD.getValue(1), SDLoc(N),
9039 NewLD, ST->getBasePtr(),
9040 ST->getPointerInfo(),
9041 false, false, STAlign);
9043 AddToWorklist(NewLD.getNode());
9044 AddToWorklist(NewST.getNode());
9045 WorklistRemover DeadNodes(*this);
9046 DAG.ReplaceAllUsesOfValueWith(Value.getValue(1), NewLD.getValue(1));
9054 /// Helper struct to parse and store a memory address as base + index + offset.
9055 /// We ignore sign extensions when it is safe to do so.
9056 /// The following two expressions are not equivalent. To differentiate we need
9057 /// to store whether there was a sign extension involved in the index
9059 /// (load (i64 add (i64 copyfromreg %c)
9060 /// (i64 signextend (add (i8 load %index)
9064 /// (load (i64 add (i64 copyfromreg %c)
9065 /// (i64 signextend (i32 add (i32 signextend (i8 load %index))
9067 struct BaseIndexOffset {
9071 bool IsIndexSignExt;
9073 BaseIndexOffset() : Offset(0), IsIndexSignExt(false) {}
9075 BaseIndexOffset(SDValue Base, SDValue Index, int64_t Offset,
9076 bool IsIndexSignExt) :
9077 Base(Base), Index(Index), Offset(Offset), IsIndexSignExt(IsIndexSignExt) {}
9079 bool equalBaseIndex(const BaseIndexOffset &Other) {
9080 return Other.Base == Base && Other.Index == Index &&
9081 Other.IsIndexSignExt == IsIndexSignExt;
9084 /// Parses tree in Ptr for base, index, offset addresses.
9085 static BaseIndexOffset match(SDValue Ptr) {
9086 bool IsIndexSignExt = false;
9088 // We only can pattern match BASE + INDEX + OFFSET. If Ptr is not an ADD
9089 // instruction, then it could be just the BASE or everything else we don't
9090 // know how to handle. Just use Ptr as BASE and give up.
9091 if (Ptr->getOpcode() != ISD::ADD)
9092 return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
9094 // We know that we have at least an ADD instruction. Try to pattern match
9095 // the simple case of BASE + OFFSET.
9096 if (isa<ConstantSDNode>(Ptr->getOperand(1))) {
9097 int64_t Offset = cast<ConstantSDNode>(Ptr->getOperand(1))->getSExtValue();
9098 return BaseIndexOffset(Ptr->getOperand(0), SDValue(), Offset,
9102 // Inside a loop the current BASE pointer is calculated using an ADD and a
9103 // MUL instruction. In this case Ptr is the actual BASE pointer.
9104 // (i64 add (i64 %array_ptr)
9105 // (i64 mul (i64 %induction_var)
9106 // (i64 %element_size)))
9107 if (Ptr->getOperand(1)->getOpcode() == ISD::MUL)
9108 return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
9110 // Look at Base + Index + Offset cases.
9111 SDValue Base = Ptr->getOperand(0);
9112 SDValue IndexOffset = Ptr->getOperand(1);
9114 // Skip signextends.
9115 if (IndexOffset->getOpcode() == ISD::SIGN_EXTEND) {
9116 IndexOffset = IndexOffset->getOperand(0);
9117 IsIndexSignExt = true;
9120 // Either the case of Base + Index (no offset) or something else.
9121 if (IndexOffset->getOpcode() != ISD::ADD)
9122 return BaseIndexOffset(Base, IndexOffset, 0, IsIndexSignExt);
9124 // Now we have the case of Base + Index + offset.
9125 SDValue Index = IndexOffset->getOperand(0);
9126 SDValue Offset = IndexOffset->getOperand(1);
9128 if (!isa<ConstantSDNode>(Offset))
9129 return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
9131 // Ignore signextends.
9132 if (Index->getOpcode() == ISD::SIGN_EXTEND) {
9133 Index = Index->getOperand(0);
9134 IsIndexSignExt = true;
9135 } else IsIndexSignExt = false;
9137 int64_t Off = cast<ConstantSDNode>(Offset)->getSExtValue();
9138 return BaseIndexOffset(Base, Index, Off, IsIndexSignExt);
9142 /// Holds a pointer to an LSBaseSDNode as well as information on where it
9143 /// is located in a sequence of memory operations connected by a chain.
9145 MemOpLink (LSBaseSDNode *N, int64_t Offset, unsigned Seq):
9146 MemNode(N), OffsetFromBase(Offset), SequenceNum(Seq) { }
9147 // Ptr to the mem node.
9148 LSBaseSDNode *MemNode;
9149 // Offset from the base ptr.
9150 int64_t OffsetFromBase;
9151 // What is the sequence number of this mem node.
9152 // Lowest mem operand in the DAG starts at zero.
9153 unsigned SequenceNum;
9156 bool DAGCombiner::MergeConsecutiveStores(StoreSDNode* St) {
9157 EVT MemVT = St->getMemoryVT();
9158 int64_t ElementSizeBytes = MemVT.getSizeInBits()/8;
9159 bool NoVectors = DAG.getMachineFunction().getFunction()->getAttributes().
9160 hasAttribute(AttributeSet::FunctionIndex, Attribute::NoImplicitFloat);
9162 // Don't merge vectors into wider inputs.
9163 if (MemVT.isVector() || !MemVT.isSimple())
9166 // Perform an early exit check. Do not bother looking at stored values that
9167 // are not constants or loads.
9168 SDValue StoredVal = St->getValue();
9169 bool IsLoadSrc = isa<LoadSDNode>(StoredVal);
9170 if (!isa<ConstantSDNode>(StoredVal) && !isa<ConstantFPSDNode>(StoredVal) &&
9174 // Only look at ends of store sequences.
9175 SDValue Chain = SDValue(St, 0);
9176 if (Chain->hasOneUse() && Chain->use_begin()->getOpcode() == ISD::STORE)
9179 // This holds the base pointer, index, and the offset in bytes from the base
9181 BaseIndexOffset BasePtr = BaseIndexOffset::match(St->getBasePtr());
9183 // We must have a base and an offset.
9184 if (!BasePtr.Base.getNode())
9187 // Do not handle stores to undef base pointers.
9188 if (BasePtr.Base.getOpcode() == ISD::UNDEF)
9191 // Save the LoadSDNodes that we find in the chain.
9192 // We need to make sure that these nodes do not interfere with
9193 // any of the store nodes.
9194 SmallVector<LSBaseSDNode*, 8> AliasLoadNodes;
9196 // Save the StoreSDNodes that we find in the chain.
9197 SmallVector<MemOpLink, 8> StoreNodes;
9199 // Walk up the chain and look for nodes with offsets from the same
9200 // base pointer. Stop when reaching an instruction with a different kind
9201 // or instruction which has a different base pointer.
9203 StoreSDNode *Index = St;
9205 // If the chain has more than one use, then we can't reorder the mem ops.
9206 if (Index != St && !SDValue(Index, 0)->hasOneUse())
9209 // Find the base pointer and offset for this memory node.
9210 BaseIndexOffset Ptr = BaseIndexOffset::match(Index->getBasePtr());
9212 // Check that the base pointer is the same as the original one.
9213 if (!Ptr.equalBaseIndex(BasePtr))
9216 // Check that the alignment is the same.
9217 if (Index->getAlignment() != St->getAlignment())
9220 // The memory operands must not be volatile.
9221 if (Index->isVolatile() || Index->isIndexed())
9225 if (StoreSDNode *St = dyn_cast<StoreSDNode>(Index))
9226 if (St->isTruncatingStore())
9229 // The stored memory type must be the same.
9230 if (Index->getMemoryVT() != MemVT)
9233 // We do not allow unaligned stores because we want to prevent overriding
9235 if (Index->getAlignment()*8 != MemVT.getSizeInBits())
9238 // We found a potential memory operand to merge.
9239 StoreNodes.push_back(MemOpLink(Index, Ptr.Offset, Seq++));
9241 // Find the next memory operand in the chain. If the next operand in the
9242 // chain is a store then move up and continue the scan with the next
9243 // memory operand. If the next operand is a load save it and use alias
9244 // information to check if it interferes with anything.
9245 SDNode *NextInChain = Index->getChain().getNode();
9247 if (StoreSDNode *STn = dyn_cast<StoreSDNode>(NextInChain)) {
9248 // We found a store node. Use it for the next iteration.
9251 } else if (LoadSDNode *Ldn = dyn_cast<LoadSDNode>(NextInChain)) {
9252 if (Ldn->isVolatile()) {
9257 // Save the load node for later. Continue the scan.
9258 AliasLoadNodes.push_back(Ldn);
9259 NextInChain = Ldn->getChain().getNode();
9268 // Check if there is anything to merge.
9269 if (StoreNodes.size() < 2)
9272 // Sort the memory operands according to their distance from the base pointer.
9273 std::sort(StoreNodes.begin(), StoreNodes.end(),
9274 [](MemOpLink LHS, MemOpLink RHS) {
9275 return LHS.OffsetFromBase < RHS.OffsetFromBase ||
9276 (LHS.OffsetFromBase == RHS.OffsetFromBase &&
9277 LHS.SequenceNum > RHS.SequenceNum);
9280 // Scan the memory operations on the chain and find the first non-consecutive
9281 // store memory address.
9282 unsigned LastConsecutiveStore = 0;
9283 int64_t StartAddress = StoreNodes[0].OffsetFromBase;
9284 for (unsigned i = 0, e = StoreNodes.size(); i < e; ++i) {
9286 // Check that the addresses are consecutive starting from the second
9287 // element in the list of stores.
9289 int64_t CurrAddress = StoreNodes[i].OffsetFromBase;
9290 if (CurrAddress - StartAddress != (ElementSizeBytes * i))
9295 // Check if this store interferes with any of the loads that we found.
9296 for (unsigned ld = 0, lde = AliasLoadNodes.size(); ld < lde; ++ld)
9297 if (isAlias(AliasLoadNodes[ld], StoreNodes[i].MemNode)) {
9301 // We found a load that alias with this store. Stop the sequence.
9305 // Mark this node as useful.
9306 LastConsecutiveStore = i;
9309 // The node with the lowest store address.
9310 LSBaseSDNode *FirstInChain = StoreNodes[0].MemNode;
9312 // Store the constants into memory as one consecutive store.
9314 unsigned LastLegalType = 0;
9315 unsigned LastLegalVectorType = 0;
9316 bool NonZero = false;
9317 for (unsigned i=0; i<LastConsecutiveStore+1; ++i) {
9318 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
9319 SDValue StoredVal = St->getValue();
9321 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(StoredVal)) {
9322 NonZero |= !C->isNullValue();
9323 } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(StoredVal)) {
9324 NonZero |= !C->getConstantFPValue()->isNullValue();
9330 // Find a legal type for the constant store.
9331 unsigned StoreBW = (i+1) * ElementSizeBytes * 8;
9332 EVT StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
9333 if (TLI.isTypeLegal(StoreTy))
9334 LastLegalType = i+1;
9335 // Or check whether a truncstore is legal.
9336 else if (TLI.getTypeAction(*DAG.getContext(), StoreTy) ==
9337 TargetLowering::TypePromoteInteger) {
9338 EVT LegalizedStoredValueTy =
9339 TLI.getTypeToTransformTo(*DAG.getContext(), StoredVal.getValueType());
9340 if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy))
9341 LastLegalType = i+1;
9344 // Find a legal type for the vector store.
9345 EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT, i+1);
9346 if (TLI.isTypeLegal(Ty))
9347 LastLegalVectorType = i + 1;
9350 // We only use vectors if the constant is known to be zero and the
9351 // function is not marked with the noimplicitfloat attribute.
9352 if (NonZero || NoVectors)
9353 LastLegalVectorType = 0;
9355 // Check if we found a legal integer type to store.
9356 if (LastLegalType == 0 && LastLegalVectorType == 0)
9359 bool UseVector = (LastLegalVectorType > LastLegalType) && !NoVectors;
9360 unsigned NumElem = UseVector ? LastLegalVectorType : LastLegalType;
9362 // Make sure we have something to merge.
9366 unsigned EarliestNodeUsed = 0;
9367 for (unsigned i=0; i < NumElem; ++i) {
9368 // Find a chain for the new wide-store operand. Notice that some
9369 // of the store nodes that we found may not be selected for inclusion
9370 // in the wide store. The chain we use needs to be the chain of the
9371 // earliest store node which is *used* and replaced by the wide store.
9372 if (StoreNodes[i].SequenceNum > StoreNodes[EarliestNodeUsed].SequenceNum)
9373 EarliestNodeUsed = i;
9376 // The earliest Node in the DAG.
9377 LSBaseSDNode *EarliestOp = StoreNodes[EarliestNodeUsed].MemNode;
9378 SDLoc DL(StoreNodes[0].MemNode);
9382 // Find a legal type for the vector store.
9383 EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT, NumElem);
9384 assert(TLI.isTypeLegal(Ty) && "Illegal vector store");
9385 StoredVal = DAG.getConstant(0, Ty);
9387 unsigned StoreBW = NumElem * ElementSizeBytes * 8;
9388 APInt StoreInt(StoreBW, 0);
9390 // Construct a single integer constant which is made of the smaller
9392 bool IsLE = TLI.isLittleEndian();
9393 for (unsigned i = 0; i < NumElem ; ++i) {
9394 unsigned Idx = IsLE ?(NumElem - 1 - i) : i;
9395 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[Idx].MemNode);
9396 SDValue Val = St->getValue();
9397 StoreInt<<=ElementSizeBytes*8;
9398 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Val)) {
9399 StoreInt|=C->getAPIntValue().zext(StoreBW);
9400 } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Val)) {
9401 StoreInt|= C->getValueAPF().bitcastToAPInt().zext(StoreBW);
9403 assert(false && "Invalid constant element type");
9407 // Create the new Load and Store operations.
9408 EVT StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
9409 StoredVal = DAG.getConstant(StoreInt, StoreTy);
9412 SDValue NewStore = DAG.getStore(EarliestOp->getChain(), DL, StoredVal,
9413 FirstInChain->getBasePtr(),
9414 FirstInChain->getPointerInfo(),
9416 FirstInChain->getAlignment());
9418 // Replace the first store with the new store
9419 CombineTo(EarliestOp, NewStore);
9420 // Erase all other stores.
9421 for (unsigned i = 0; i < NumElem ; ++i) {
9422 if (StoreNodes[i].MemNode == EarliestOp)
9424 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
9425 // ReplaceAllUsesWith will replace all uses that existed when it was
9426 // called, but graph optimizations may cause new ones to appear. For
9427 // example, the case in pr14333 looks like
9429 // St's chain -> St -> another store -> X
9431 // And the only difference from St to the other store is the chain.
9432 // When we change it's chain to be St's chain they become identical,
9433 // get CSEed and the net result is that X is now a use of St.
9434 // Since we know that St is redundant, just iterate.
9435 while (!St->use_empty())
9436 DAG.ReplaceAllUsesWith(SDValue(St, 0), St->getChain());
9437 deleteAndRecombine(St);
9443 // Below we handle the case of multiple consecutive stores that
9444 // come from multiple consecutive loads. We merge them into a single
9445 // wide load and a single wide store.
9447 // Look for load nodes which are used by the stored values.
9448 SmallVector<MemOpLink, 8> LoadNodes;
9450 // Find acceptable loads. Loads need to have the same chain (token factor),
9451 // must not be zext, volatile, indexed, and they must be consecutive.
9452 BaseIndexOffset LdBasePtr;
9453 for (unsigned i=0; i<LastConsecutiveStore+1; ++i) {
9454 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
9455 LoadSDNode *Ld = dyn_cast<LoadSDNode>(St->getValue());
9458 // Loads must only have one use.
9459 if (!Ld->hasNUsesOfValue(1, 0))
9462 // Check that the alignment is the same as the stores.
9463 if (Ld->getAlignment() != St->getAlignment())
9466 // The memory operands must not be volatile.
9467 if (Ld->isVolatile() || Ld->isIndexed())
9470 // We do not accept ext loads.
9471 if (Ld->getExtensionType() != ISD::NON_EXTLOAD)
9474 // The stored memory type must be the same.
9475 if (Ld->getMemoryVT() != MemVT)
9478 BaseIndexOffset LdPtr = BaseIndexOffset::match(Ld->getBasePtr());
9479 // If this is not the first ptr that we check.
9480 if (LdBasePtr.Base.getNode()) {
9481 // The base ptr must be the same.
9482 if (!LdPtr.equalBaseIndex(LdBasePtr))
9485 // Check that all other base pointers are the same as this one.
9489 // We found a potential memory operand to merge.
9490 LoadNodes.push_back(MemOpLink(Ld, LdPtr.Offset, 0));
9493 if (LoadNodes.size() < 2)
9496 // If we have load/store pair instructions and we only have two values,
9498 unsigned RequiredAlignment;
9499 if (LoadNodes.size() == 2 && TLI.hasPairedLoad(MemVT, RequiredAlignment) &&
9500 St->getAlignment() >= RequiredAlignment)
9503 // Scan the memory operations on the chain and find the first non-consecutive
9504 // load memory address. These variables hold the index in the store node
9506 unsigned LastConsecutiveLoad = 0;
9507 // This variable refers to the size and not index in the array.
9508 unsigned LastLegalVectorType = 0;
9509 unsigned LastLegalIntegerType = 0;
9510 StartAddress = LoadNodes[0].OffsetFromBase;
9511 SDValue FirstChain = LoadNodes[0].MemNode->getChain();
9512 for (unsigned i = 1; i < LoadNodes.size(); ++i) {
9513 // All loads much share the same chain.
9514 if (LoadNodes[i].MemNode->getChain() != FirstChain)
9517 int64_t CurrAddress = LoadNodes[i].OffsetFromBase;
9518 if (CurrAddress - StartAddress != (ElementSizeBytes * i))
9520 LastConsecutiveLoad = i;
9522 // Find a legal type for the vector store.
9523 EVT StoreTy = EVT::getVectorVT(*DAG.getContext(), MemVT, i+1);
9524 if (TLI.isTypeLegal(StoreTy))
9525 LastLegalVectorType = i + 1;
9527 // Find a legal type for the integer store.
9528 unsigned StoreBW = (i+1) * ElementSizeBytes * 8;
9529 StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
9530 if (TLI.isTypeLegal(StoreTy))
9531 LastLegalIntegerType = i + 1;
9532 // Or check whether a truncstore and extload is legal.
9533 else if (TLI.getTypeAction(*DAG.getContext(), StoreTy) ==
9534 TargetLowering::TypePromoteInteger) {
9535 EVT LegalizedStoredValueTy =
9536 TLI.getTypeToTransformTo(*DAG.getContext(), StoreTy);
9537 if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy) &&
9538 TLI.isLoadExtLegal(ISD::ZEXTLOAD, StoreTy) &&
9539 TLI.isLoadExtLegal(ISD::SEXTLOAD, StoreTy) &&
9540 TLI.isLoadExtLegal(ISD::EXTLOAD, StoreTy))
9541 LastLegalIntegerType = i+1;
9545 // Only use vector types if the vector type is larger than the integer type.
9546 // If they are the same, use integers.
9547 bool UseVectorTy = LastLegalVectorType > LastLegalIntegerType && !NoVectors;
9548 unsigned LastLegalType = std::max(LastLegalVectorType, LastLegalIntegerType);
9550 // We add +1 here because the LastXXX variables refer to location while
9551 // the NumElem refers to array/index size.
9552 unsigned NumElem = std::min(LastConsecutiveStore, LastConsecutiveLoad) + 1;
9553 NumElem = std::min(LastLegalType, NumElem);
9558 // The earliest Node in the DAG.
9559 unsigned EarliestNodeUsed = 0;
9560 LSBaseSDNode *EarliestOp = StoreNodes[EarliestNodeUsed].MemNode;
9561 for (unsigned i=1; i<NumElem; ++i) {
9562 // Find a chain for the new wide-store operand. Notice that some
9563 // of the store nodes that we found may not be selected for inclusion
9564 // in the wide store. The chain we use needs to be the chain of the
9565 // earliest store node which is *used* and replaced by the wide store.
9566 if (StoreNodes[i].SequenceNum > StoreNodes[EarliestNodeUsed].SequenceNum)
9567 EarliestNodeUsed = i;
9570 // Find if it is better to use vectors or integers to load and store
9574 JointMemOpVT = EVT::getVectorVT(*DAG.getContext(), MemVT, NumElem);
9576 unsigned StoreBW = NumElem * ElementSizeBytes * 8;
9577 JointMemOpVT = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
9580 SDLoc LoadDL(LoadNodes[0].MemNode);
9581 SDLoc StoreDL(StoreNodes[0].MemNode);
9583 LoadSDNode *FirstLoad = cast<LoadSDNode>(LoadNodes[0].MemNode);
9584 SDValue NewLoad = DAG.getLoad(JointMemOpVT, LoadDL,
9585 FirstLoad->getChain(),
9586 FirstLoad->getBasePtr(),
9587 FirstLoad->getPointerInfo(),
9588 false, false, false,
9589 FirstLoad->getAlignment());
9591 SDValue NewStore = DAG.getStore(EarliestOp->getChain(), StoreDL, NewLoad,
9592 FirstInChain->getBasePtr(),
9593 FirstInChain->getPointerInfo(), false, false,
9594 FirstInChain->getAlignment());
9596 // Replace one of the loads with the new load.
9597 LoadSDNode *Ld = cast<LoadSDNode>(LoadNodes[0].MemNode);
9598 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1),
9599 SDValue(NewLoad.getNode(), 1));
9601 // Remove the rest of the load chains.
9602 for (unsigned i = 1; i < NumElem ; ++i) {
9603 // Replace all chain users of the old load nodes with the chain of the new
9605 LoadSDNode *Ld = cast<LoadSDNode>(LoadNodes[i].MemNode);
9606 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), Ld->getChain());
9609 // Replace the first store with the new store.
9610 CombineTo(EarliestOp, NewStore);
9611 // Erase all other stores.
9612 for (unsigned i = 0; i < NumElem ; ++i) {
9613 // Remove all Store nodes.
9614 if (StoreNodes[i].MemNode == EarliestOp)
9616 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
9617 DAG.ReplaceAllUsesOfValueWith(SDValue(St, 0), St->getChain());
9618 deleteAndRecombine(St);
9624 SDValue DAGCombiner::visitSTORE(SDNode *N) {
9625 StoreSDNode *ST = cast<StoreSDNode>(N);
9626 SDValue Chain = ST->getChain();
9627 SDValue Value = ST->getValue();
9628 SDValue Ptr = ST->getBasePtr();
9630 // If this is a store of a bit convert, store the input value if the
9631 // resultant store does not need a higher alignment than the original.
9632 if (Value.getOpcode() == ISD::BITCAST && !ST->isTruncatingStore() &&
9633 ST->isUnindexed()) {
9634 unsigned OrigAlign = ST->getAlignment();
9635 EVT SVT = Value.getOperand(0).getValueType();
9636 unsigned Align = TLI.getDataLayout()->
9637 getABITypeAlignment(SVT.getTypeForEVT(*DAG.getContext()));
9638 if (Align <= OrigAlign &&
9639 ((!LegalOperations && !ST->isVolatile()) ||
9640 TLI.isOperationLegalOrCustom(ISD::STORE, SVT)))
9641 return DAG.getStore(Chain, SDLoc(N), Value.getOperand(0),
9642 Ptr, ST->getPointerInfo(), ST->isVolatile(),
9643 ST->isNonTemporal(), OrigAlign,
9647 // Turn 'store undef, Ptr' -> nothing.
9648 if (Value.getOpcode() == ISD::UNDEF && ST->isUnindexed())
9651 // Turn 'store float 1.0, Ptr' -> 'store int 0x12345678, Ptr'
9652 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Value)) {
9653 // NOTE: If the original store is volatile, this transform must not increase
9654 // the number of stores. For example, on x86-32 an f64 can be stored in one
9655 // processor operation but an i64 (which is not legal) requires two. So the
9656 // transform should not be done in this case.
9657 if (Value.getOpcode() != ISD::TargetConstantFP) {
9659 switch (CFP->getSimpleValueType(0).SimpleTy) {
9660 default: llvm_unreachable("Unknown FP type");
9661 case MVT::f16: // We don't do this for these yet.
9667 if ((isTypeLegal(MVT::i32) && !LegalOperations && !ST->isVolatile()) ||
9668 TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) {
9669 Tmp = DAG.getConstant((uint32_t)CFP->getValueAPF().
9670 bitcastToAPInt().getZExtValue(), MVT::i32);
9671 return DAG.getStore(Chain, SDLoc(N), Tmp,
9672 Ptr, ST->getMemOperand());
9676 if ((TLI.isTypeLegal(MVT::i64) && !LegalOperations &&
9677 !ST->isVolatile()) ||
9678 TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i64)) {
9679 Tmp = DAG.getConstant(CFP->getValueAPF().bitcastToAPInt().
9680 getZExtValue(), MVT::i64);
9681 return DAG.getStore(Chain, SDLoc(N), Tmp,
9682 Ptr, ST->getMemOperand());
9685 if (!ST->isVolatile() &&
9686 TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) {
9687 // Many FP stores are not made apparent until after legalize, e.g. for
9688 // argument passing. Since this is so common, custom legalize the
9689 // 64-bit integer store into two 32-bit stores.
9690 uint64_t Val = CFP->getValueAPF().bitcastToAPInt().getZExtValue();
9691 SDValue Lo = DAG.getConstant(Val & 0xFFFFFFFF, MVT::i32);
9692 SDValue Hi = DAG.getConstant(Val >> 32, MVT::i32);
9693 if (TLI.isBigEndian()) std::swap(Lo, Hi);
9695 unsigned Alignment = ST->getAlignment();
9696 bool isVolatile = ST->isVolatile();
9697 bool isNonTemporal = ST->isNonTemporal();
9698 AAMDNodes AAInfo = ST->getAAInfo();
9700 SDValue St0 = DAG.getStore(Chain, SDLoc(ST), Lo,
9701 Ptr, ST->getPointerInfo(),
9702 isVolatile, isNonTemporal,
9703 ST->getAlignment(), AAInfo);
9704 Ptr = DAG.getNode(ISD::ADD, SDLoc(N), Ptr.getValueType(), Ptr,
9705 DAG.getConstant(4, Ptr.getValueType()));
9706 Alignment = MinAlign(Alignment, 4U);
9707 SDValue St1 = DAG.getStore(Chain, SDLoc(ST), Hi,
9708 Ptr, ST->getPointerInfo().getWithOffset(4),
9709 isVolatile, isNonTemporal,
9711 return DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other,
9720 // Try to infer better alignment information than the store already has.
9721 if (OptLevel != CodeGenOpt::None && ST->isUnindexed()) {
9722 if (unsigned Align = DAG.InferPtrAlignment(Ptr)) {
9723 if (Align > ST->getAlignment())
9724 return DAG.getTruncStore(Chain, SDLoc(N), Value,
9725 Ptr, ST->getPointerInfo(), ST->getMemoryVT(),
9726 ST->isVolatile(), ST->isNonTemporal(), Align,
9731 // Try transforming a pair floating point load / store ops to integer
9732 // load / store ops.
9733 SDValue NewST = TransformFPLoadStorePair(N);
9734 if (NewST.getNode())
9737 bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA :
9738 TLI.getTargetMachine().getSubtarget<TargetSubtargetInfo>().useAA();
9740 if (CombinerAAOnlyFunc.getNumOccurrences() &&
9741 CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
9744 if (UseAA && ST->isUnindexed()) {
9745 // Walk up chain skipping non-aliasing memory nodes.
9746 SDValue BetterChain = FindBetterChain(N, Chain);
9748 // If there is a better chain.
9749 if (Chain != BetterChain) {
9752 // Replace the chain to avoid dependency.
9753 if (ST->isTruncatingStore()) {
9754 ReplStore = DAG.getTruncStore(BetterChain, SDLoc(N), Value, Ptr,
9755 ST->getMemoryVT(), ST->getMemOperand());
9757 ReplStore = DAG.getStore(BetterChain, SDLoc(N), Value, Ptr,
9758 ST->getMemOperand());
9761 // Create token to keep both nodes around.
9762 SDValue Token = DAG.getNode(ISD::TokenFactor, SDLoc(N),
9763 MVT::Other, Chain, ReplStore);
9765 // Make sure the new and old chains are cleaned up.
9766 AddToWorklist(Token.getNode());
9768 // Don't add users to work list.
9769 return CombineTo(N, Token, false);
9773 // Try transforming N to an indexed store.
9774 if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
9775 return SDValue(N, 0);
9777 // FIXME: is there such a thing as a truncating indexed store?
9778 if (ST->isTruncatingStore() && ST->isUnindexed() &&
9779 Value.getValueType().isInteger()) {
9780 // See if we can simplify the input to this truncstore with knowledge that
9781 // only the low bits are being used. For example:
9782 // "truncstore (or (shl x, 8), y), i8" -> "truncstore y, i8"
9784 GetDemandedBits(Value,
9785 APInt::getLowBitsSet(
9786 Value.getValueType().getScalarType().getSizeInBits(),
9787 ST->getMemoryVT().getScalarType().getSizeInBits()));
9788 AddToWorklist(Value.getNode());
9789 if (Shorter.getNode())
9790 return DAG.getTruncStore(Chain, SDLoc(N), Shorter,
9791 Ptr, ST->getMemoryVT(), ST->getMemOperand());
9793 // Otherwise, see if we can simplify the operation with
9794 // SimplifyDemandedBits, which only works if the value has a single use.
9795 if (SimplifyDemandedBits(Value,
9796 APInt::getLowBitsSet(
9797 Value.getValueType().getScalarType().getSizeInBits(),
9798 ST->getMemoryVT().getScalarType().getSizeInBits())))
9799 return SDValue(N, 0);
9802 // If this is a load followed by a store to the same location, then the store
9804 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Value)) {
9805 if (Ld->getBasePtr() == Ptr && ST->getMemoryVT() == Ld->getMemoryVT() &&
9806 ST->isUnindexed() && !ST->isVolatile() &&
9807 // There can't be any side effects between the load and store, such as
9809 Chain.reachesChainWithoutSideEffects(SDValue(Ld, 1))) {
9810 // The store is dead, remove it.
9815 // If this is an FP_ROUND or TRUNC followed by a store, fold this into a
9816 // truncating store. We can do this even if this is already a truncstore.
9817 if ((Value.getOpcode() == ISD::FP_ROUND || Value.getOpcode() == ISD::TRUNCATE)
9818 && Value.getNode()->hasOneUse() && ST->isUnindexed() &&
9819 TLI.isTruncStoreLegal(Value.getOperand(0).getValueType(),
9820 ST->getMemoryVT())) {
9821 return DAG.getTruncStore(Chain, SDLoc(N), Value.getOperand(0),
9822 Ptr, ST->getMemoryVT(), ST->getMemOperand());
9825 // Only perform this optimization before the types are legal, because we
9826 // don't want to perform this optimization on every DAGCombine invocation.
9828 bool EverChanged = false;
9831 // There can be multiple store sequences on the same chain.
9832 // Keep trying to merge store sequences until we are unable to do so
9833 // or until we merge the last store on the chain.
9834 bool Changed = MergeConsecutiveStores(ST);
9835 EverChanged |= Changed;
9836 if (!Changed) break;
9837 } while (ST->getOpcode() != ISD::DELETED_NODE);
9840 return SDValue(N, 0);
9843 return ReduceLoadOpStoreWidth(N);
9846 SDValue DAGCombiner::visitINSERT_VECTOR_ELT(SDNode *N) {
9847 SDValue InVec = N->getOperand(0);
9848 SDValue InVal = N->getOperand(1);
9849 SDValue EltNo = N->getOperand(2);
9852 // If the inserted element is an UNDEF, just use the input vector.
9853 if (InVal.getOpcode() == ISD::UNDEF)
9856 EVT VT = InVec.getValueType();
9858 // If we can't generate a legal BUILD_VECTOR, exit
9859 if (LegalOperations && !TLI.isOperationLegal(ISD::BUILD_VECTOR, VT))
9862 // Check that we know which element is being inserted
9863 if (!isa<ConstantSDNode>(EltNo))
9865 unsigned Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
9867 // Canonicalize insert_vector_elt dag nodes.
9869 // (insert_vector_elt (insert_vector_elt A, Idx0), Idx1)
9870 // -> (insert_vector_elt (insert_vector_elt A, Idx1), Idx0)
9872 // Do this only if the child insert_vector node has one use; also
9873 // do this only if indices are both constants and Idx1 < Idx0.
9874 if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT && InVec.hasOneUse()
9875 && isa<ConstantSDNode>(InVec.getOperand(2))) {
9877 cast<ConstantSDNode>(InVec.getOperand(2))->getZExtValue();
9878 if (Elt < OtherElt) {
9880 SDValue NewOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, SDLoc(N), VT,
9881 InVec.getOperand(0), InVal, EltNo);
9882 AddToWorklist(NewOp.getNode());
9883 return DAG.getNode(ISD::INSERT_VECTOR_ELT, SDLoc(InVec.getNode()),
9884 VT, NewOp, InVec.getOperand(1), InVec.getOperand(2));
9888 // Check that the operand is a BUILD_VECTOR (or UNDEF, which can essentially
9889 // be converted to a BUILD_VECTOR). Fill in the Ops vector with the
9891 SmallVector<SDValue, 8> Ops;
9892 // Do not combine these two vectors if the output vector will not replace
9893 // the input vector.
9894 if (InVec.getOpcode() == ISD::BUILD_VECTOR && InVec.hasOneUse()) {
9895 Ops.append(InVec.getNode()->op_begin(),
9896 InVec.getNode()->op_end());
9897 } else if (InVec.getOpcode() == ISD::UNDEF) {
9898 unsigned NElts = VT.getVectorNumElements();
9899 Ops.append(NElts, DAG.getUNDEF(InVal.getValueType()));
9904 // Insert the element
9905 if (Elt < Ops.size()) {
9906 // All the operands of BUILD_VECTOR must have the same type;
9907 // we enforce that here.
9908 EVT OpVT = Ops[0].getValueType();
9909 if (InVal.getValueType() != OpVT)
9910 InVal = OpVT.bitsGT(InVal.getValueType()) ?
9911 DAG.getNode(ISD::ANY_EXTEND, dl, OpVT, InVal) :
9912 DAG.getNode(ISD::TRUNCATE, dl, OpVT, InVal);
9916 // Return the new vector
9917 return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
9920 SDValue DAGCombiner::ReplaceExtractVectorEltOfLoadWithNarrowedLoad(
9921 SDNode *EVE, EVT InVecVT, SDValue EltNo, LoadSDNode *OriginalLoad) {
9922 EVT ResultVT = EVE->getValueType(0);
9923 EVT VecEltVT = InVecVT.getVectorElementType();
9924 unsigned Align = OriginalLoad->getAlignment();
9925 unsigned NewAlign = TLI.getDataLayout()->getABITypeAlignment(
9926 VecEltVT.getTypeForEVT(*DAG.getContext()));
9928 if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, VecEltVT))
9933 SDValue NewPtr = OriginalLoad->getBasePtr();
9935 EVT PtrType = NewPtr.getValueType();
9936 MachinePointerInfo MPI;
9937 if (auto *ConstEltNo = dyn_cast<ConstantSDNode>(EltNo)) {
9938 int Elt = ConstEltNo->getZExtValue();
9939 unsigned PtrOff = VecEltVT.getSizeInBits() * Elt / 8;
9940 if (TLI.isBigEndian())
9941 PtrOff = InVecVT.getSizeInBits() / 8 - PtrOff;
9942 Offset = DAG.getConstant(PtrOff, PtrType);
9943 MPI = OriginalLoad->getPointerInfo().getWithOffset(PtrOff);
9945 Offset = DAG.getNode(
9946 ISD::MUL, SDLoc(EVE), EltNo.getValueType(), EltNo,
9947 DAG.getConstant(VecEltVT.getStoreSize(), EltNo.getValueType()));
9948 if (TLI.isBigEndian())
9949 Offset = DAG.getNode(
9950 ISD::SUB, SDLoc(EVE), EltNo.getValueType(),
9951 DAG.getConstant(InVecVT.getStoreSize(), EltNo.getValueType()), Offset);
9952 MPI = OriginalLoad->getPointerInfo();
9954 NewPtr = DAG.getNode(ISD::ADD, SDLoc(EVE), PtrType, NewPtr, Offset);
9956 // The replacement we need to do here is a little tricky: we need to
9957 // replace an extractelement of a load with a load.
9958 // Use ReplaceAllUsesOfValuesWith to do the replacement.
9959 // Note that this replacement assumes that the extractvalue is the only
9960 // use of the load; that's okay because we don't want to perform this
9961 // transformation in other cases anyway.
9964 if (ResultVT.bitsGT(VecEltVT)) {
9965 // If the result type of vextract is wider than the load, then issue an
9966 // extending load instead.
9967 ISD::LoadExtType ExtType = TLI.isLoadExtLegal(ISD::ZEXTLOAD, VecEltVT)
9970 Load = DAG.getExtLoad(
9971 ExtType, SDLoc(EVE), ResultVT, OriginalLoad->getChain(), NewPtr, MPI,
9972 VecEltVT, OriginalLoad->isVolatile(), OriginalLoad->isNonTemporal(),
9973 OriginalLoad->isInvariant(), Align, OriginalLoad->getAAInfo());
9974 Chain = Load.getValue(1);
9977 VecEltVT, SDLoc(EVE), OriginalLoad->getChain(), NewPtr, MPI,
9978 OriginalLoad->isVolatile(), OriginalLoad->isNonTemporal(),
9979 OriginalLoad->isInvariant(), Align, OriginalLoad->getAAInfo());
9980 Chain = Load.getValue(1);
9981 if (ResultVT.bitsLT(VecEltVT))
9982 Load = DAG.getNode(ISD::TRUNCATE, SDLoc(EVE), ResultVT, Load);
9984 Load = DAG.getNode(ISD::BITCAST, SDLoc(EVE), ResultVT, Load);
9986 WorklistRemover DeadNodes(*this);
9987 SDValue From[] = { SDValue(EVE, 0), SDValue(OriginalLoad, 1) };
9988 SDValue To[] = { Load, Chain };
9989 DAG.ReplaceAllUsesOfValuesWith(From, To, 2);
9990 // Since we're explicitly calling ReplaceAllUses, add the new node to the
9991 // worklist explicitly as well.
9992 AddToWorklist(Load.getNode());
9993 AddUsersToWorklist(Load.getNode()); // Add users too
9994 // Make sure to revisit this node to clean it up; it will usually be dead.
9997 return SDValue(EVE, 0);
10000 SDValue DAGCombiner::visitEXTRACT_VECTOR_ELT(SDNode *N) {
10001 // (vextract (scalar_to_vector val, 0) -> val
10002 SDValue InVec = N->getOperand(0);
10003 EVT VT = InVec.getValueType();
10004 EVT NVT = N->getValueType(0);
10006 if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR) {
10007 // Check if the result type doesn't match the inserted element type. A
10008 // SCALAR_TO_VECTOR may truncate the inserted element and the
10009 // EXTRACT_VECTOR_ELT may widen the extracted vector.
10010 SDValue InOp = InVec.getOperand(0);
10011 if (InOp.getValueType() != NVT) {
10012 assert(InOp.getValueType().isInteger() && NVT.isInteger());
10013 return DAG.getSExtOrTrunc(InOp, SDLoc(InVec), NVT);
10018 SDValue EltNo = N->getOperand(1);
10019 bool ConstEltNo = isa<ConstantSDNode>(EltNo);
10021 // Transform: (EXTRACT_VECTOR_ELT( VECTOR_SHUFFLE )) -> EXTRACT_VECTOR_ELT.
10022 // We only perform this optimization before the op legalization phase because
10023 // we may introduce new vector instructions which are not backed by TD
10024 // patterns. For example on AVX, extracting elements from a wide vector
10025 // without using extract_subvector. However, if we can find an underlying
10026 // scalar value, then we can always use that.
10027 if (InVec.getOpcode() == ISD::VECTOR_SHUFFLE
10029 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
10030 int NumElem = VT.getVectorNumElements();
10031 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(InVec);
10032 // Find the new index to extract from.
10033 int OrigElt = SVOp->getMaskElt(Elt);
10035 // Extracting an undef index is undef.
10037 return DAG.getUNDEF(NVT);
10039 // Select the right vector half to extract from.
10041 if (OrigElt < NumElem) {
10042 SVInVec = InVec->getOperand(0);
10044 SVInVec = InVec->getOperand(1);
10045 OrigElt -= NumElem;
10048 if (SVInVec.getOpcode() == ISD::BUILD_VECTOR) {
10049 SDValue InOp = SVInVec.getOperand(OrigElt);
10050 if (InOp.getValueType() != NVT) {
10051 assert(InOp.getValueType().isInteger() && NVT.isInteger());
10052 InOp = DAG.getSExtOrTrunc(InOp, SDLoc(SVInVec), NVT);
10058 // FIXME: We should handle recursing on other vector shuffles and
10059 // scalar_to_vector here as well.
10061 if (!LegalOperations) {
10062 EVT IndexTy = TLI.getVectorIdxTy();
10063 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SDLoc(N), NVT,
10064 SVInVec, DAG.getConstant(OrigElt, IndexTy));
10068 bool BCNumEltsChanged = false;
10069 EVT ExtVT = VT.getVectorElementType();
10072 // If the result of load has to be truncated, then it's not necessarily
10074 if (NVT.bitsLT(LVT) && !TLI.isTruncateFree(LVT, NVT))
10077 if (InVec.getOpcode() == ISD::BITCAST) {
10078 // Don't duplicate a load with other uses.
10079 if (!InVec.hasOneUse())
10082 EVT BCVT = InVec.getOperand(0).getValueType();
10083 if (!BCVT.isVector() || ExtVT.bitsGT(BCVT.getVectorElementType()))
10085 if (VT.getVectorNumElements() != BCVT.getVectorNumElements())
10086 BCNumEltsChanged = true;
10087 InVec = InVec.getOperand(0);
10088 ExtVT = BCVT.getVectorElementType();
10091 // (vextract (vN[if]M load $addr), i) -> ([if]M load $addr + i * size)
10092 if (!LegalOperations && !ConstEltNo && InVec.hasOneUse() &&
10093 ISD::isNormalLoad(InVec.getNode()) &&
10094 !N->getOperand(1)->hasPredecessor(InVec.getNode())) {
10095 SDValue Index = N->getOperand(1);
10096 if (LoadSDNode *OrigLoad = dyn_cast<LoadSDNode>(InVec))
10097 return ReplaceExtractVectorEltOfLoadWithNarrowedLoad(N, VT, Index,
10101 // Perform only after legalization to ensure build_vector / vector_shuffle
10102 // optimizations have already been done.
10103 if (!LegalOperations) return SDValue();
10105 // (vextract (v4f32 load $addr), c) -> (f32 load $addr+c*size)
10106 // (vextract (v4f32 s2v (f32 load $addr)), c) -> (f32 load $addr+c*size)
10107 // (vextract (v4f32 shuffle (load $addr), <1,u,u,u>), 0) -> (f32 load $addr)
10110 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
10112 LoadSDNode *LN0 = nullptr;
10113 const ShuffleVectorSDNode *SVN = nullptr;
10114 if (ISD::isNormalLoad(InVec.getNode())) {
10115 LN0 = cast<LoadSDNode>(InVec);
10116 } else if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR &&
10117 InVec.getOperand(0).getValueType() == ExtVT &&
10118 ISD::isNormalLoad(InVec.getOperand(0).getNode())) {
10119 // Don't duplicate a load with other uses.
10120 if (!InVec.hasOneUse())
10123 LN0 = cast<LoadSDNode>(InVec.getOperand(0));
10124 } else if ((SVN = dyn_cast<ShuffleVectorSDNode>(InVec))) {
10125 // (vextract (vector_shuffle (load $addr), v2, <1, u, u, u>), 1)
10127 // (load $addr+1*size)
10129 // Don't duplicate a load with other uses.
10130 if (!InVec.hasOneUse())
10133 // If the bit convert changed the number of elements, it is unsafe
10134 // to examine the mask.
10135 if (BCNumEltsChanged)
10138 // Select the input vector, guarding against out of range extract vector.
10139 unsigned NumElems = VT.getVectorNumElements();
10140 int Idx = (Elt > (int)NumElems) ? -1 : SVN->getMaskElt(Elt);
10141 InVec = (Idx < (int)NumElems) ? InVec.getOperand(0) : InVec.getOperand(1);
10143 if (InVec.getOpcode() == ISD::BITCAST) {
10144 // Don't duplicate a load with other uses.
10145 if (!InVec.hasOneUse())
10148 InVec = InVec.getOperand(0);
10150 if (ISD::isNormalLoad(InVec.getNode())) {
10151 LN0 = cast<LoadSDNode>(InVec);
10152 Elt = (Idx < (int)NumElems) ? Idx : Idx - (int)NumElems;
10153 EltNo = DAG.getConstant(Elt, EltNo.getValueType());
10157 // Make sure we found a non-volatile load and the extractelement is
10159 if (!LN0 || !LN0->hasNUsesOfValue(1,0) || LN0->isVolatile())
10162 // If Idx was -1 above, Elt is going to be -1, so just return undef.
10164 return DAG.getUNDEF(LVT);
10166 return ReplaceExtractVectorEltOfLoadWithNarrowedLoad(N, VT, EltNo, LN0);
10172 // Simplify (build_vec (ext )) to (bitcast (build_vec ))
10173 SDValue DAGCombiner::reduceBuildVecExtToExtBuildVec(SDNode *N) {
10174 // We perform this optimization post type-legalization because
10175 // the type-legalizer often scalarizes integer-promoted vectors.
10176 // Performing this optimization before may create bit-casts which
10177 // will be type-legalized to complex code sequences.
10178 // We perform this optimization only before the operation legalizer because we
10179 // may introduce illegal operations.
10180 if (Level != AfterLegalizeVectorOps && Level != AfterLegalizeTypes)
10183 unsigned NumInScalars = N->getNumOperands();
10185 EVT VT = N->getValueType(0);
10187 // Check to see if this is a BUILD_VECTOR of a bunch of values
10188 // which come from any_extend or zero_extend nodes. If so, we can create
10189 // a new BUILD_VECTOR using bit-casts which may enable other BUILD_VECTOR
10190 // optimizations. We do not handle sign-extend because we can't fill the sign
10192 EVT SourceType = MVT::Other;
10193 bool AllAnyExt = true;
10195 for (unsigned i = 0; i != NumInScalars; ++i) {
10196 SDValue In = N->getOperand(i);
10197 // Ignore undef inputs.
10198 if (In.getOpcode() == ISD::UNDEF) continue;
10200 bool AnyExt = In.getOpcode() == ISD::ANY_EXTEND;
10201 bool ZeroExt = In.getOpcode() == ISD::ZERO_EXTEND;
10203 // Abort if the element is not an extension.
10204 if (!ZeroExt && !AnyExt) {
10205 SourceType = MVT::Other;
10209 // The input is a ZeroExt or AnyExt. Check the original type.
10210 EVT InTy = In.getOperand(0).getValueType();
10212 // Check that all of the widened source types are the same.
10213 if (SourceType == MVT::Other)
10216 else if (InTy != SourceType) {
10217 // Multiple income types. Abort.
10218 SourceType = MVT::Other;
10222 // Check if all of the extends are ANY_EXTENDs.
10223 AllAnyExt &= AnyExt;
10226 // In order to have valid types, all of the inputs must be extended from the
10227 // same source type and all of the inputs must be any or zero extend.
10228 // Scalar sizes must be a power of two.
10229 EVT OutScalarTy = VT.getScalarType();
10230 bool ValidTypes = SourceType != MVT::Other &&
10231 isPowerOf2_32(OutScalarTy.getSizeInBits()) &&
10232 isPowerOf2_32(SourceType.getSizeInBits());
10234 // Create a new simpler BUILD_VECTOR sequence which other optimizations can
10235 // turn into a single shuffle instruction.
10239 bool isLE = TLI.isLittleEndian();
10240 unsigned ElemRatio = OutScalarTy.getSizeInBits()/SourceType.getSizeInBits();
10241 assert(ElemRatio > 1 && "Invalid element size ratio");
10242 SDValue Filler = AllAnyExt ? DAG.getUNDEF(SourceType):
10243 DAG.getConstant(0, SourceType);
10245 unsigned NewBVElems = ElemRatio * VT.getVectorNumElements();
10246 SmallVector<SDValue, 8> Ops(NewBVElems, Filler);
10248 // Populate the new build_vector
10249 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
10250 SDValue Cast = N->getOperand(i);
10251 assert((Cast.getOpcode() == ISD::ANY_EXTEND ||
10252 Cast.getOpcode() == ISD::ZERO_EXTEND ||
10253 Cast.getOpcode() == ISD::UNDEF) && "Invalid cast opcode");
10255 if (Cast.getOpcode() == ISD::UNDEF)
10256 In = DAG.getUNDEF(SourceType);
10258 In = Cast->getOperand(0);
10259 unsigned Index = isLE ? (i * ElemRatio) :
10260 (i * ElemRatio + (ElemRatio - 1));
10262 assert(Index < Ops.size() && "Invalid index");
10266 // The type of the new BUILD_VECTOR node.
10267 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), SourceType, NewBVElems);
10268 assert(VecVT.getSizeInBits() == VT.getSizeInBits() &&
10269 "Invalid vector size");
10270 // Check if the new vector type is legal.
10271 if (!isTypeLegal(VecVT)) return SDValue();
10273 // Make the new BUILD_VECTOR.
10274 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, VecVT, Ops);
10276 // The new BUILD_VECTOR node has the potential to be further optimized.
10277 AddToWorklist(BV.getNode());
10278 // Bitcast to the desired type.
10279 return DAG.getNode(ISD::BITCAST, dl, VT, BV);
10282 SDValue DAGCombiner::reduceBuildVecConvertToConvertBuildVec(SDNode *N) {
10283 EVT VT = N->getValueType(0);
10285 unsigned NumInScalars = N->getNumOperands();
10288 EVT SrcVT = MVT::Other;
10289 unsigned Opcode = ISD::DELETED_NODE;
10290 unsigned NumDefs = 0;
10292 for (unsigned i = 0; i != NumInScalars; ++i) {
10293 SDValue In = N->getOperand(i);
10294 unsigned Opc = In.getOpcode();
10296 if (Opc == ISD::UNDEF)
10299 // If all scalar values are floats and converted from integers.
10300 if (Opcode == ISD::DELETED_NODE &&
10301 (Opc == ISD::UINT_TO_FP || Opc == ISD::SINT_TO_FP)) {
10308 EVT InVT = In.getOperand(0).getValueType();
10310 // If all scalar values are typed differently, bail out. It's chosen to
10311 // simplify BUILD_VECTOR of integer types.
10312 if (SrcVT == MVT::Other)
10319 // If the vector has just one element defined, it's not worth to fold it into
10320 // a vectorized one.
10324 assert((Opcode == ISD::UINT_TO_FP || Opcode == ISD::SINT_TO_FP)
10325 && "Should only handle conversion from integer to float.");
10326 assert(SrcVT != MVT::Other && "Cannot determine source type!");
10328 EVT NVT = EVT::getVectorVT(*DAG.getContext(), SrcVT, NumInScalars);
10330 if (!TLI.isOperationLegalOrCustom(Opcode, NVT))
10333 SmallVector<SDValue, 8> Opnds;
10334 for (unsigned i = 0; i != NumInScalars; ++i) {
10335 SDValue In = N->getOperand(i);
10337 if (In.getOpcode() == ISD::UNDEF)
10338 Opnds.push_back(DAG.getUNDEF(SrcVT));
10340 Opnds.push_back(In.getOperand(0));
10342 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, NVT, Opnds);
10343 AddToWorklist(BV.getNode());
10345 return DAG.getNode(Opcode, dl, VT, BV);
10348 SDValue DAGCombiner::visitBUILD_VECTOR(SDNode *N) {
10349 unsigned NumInScalars = N->getNumOperands();
10351 EVT VT = N->getValueType(0);
10353 // A vector built entirely of undefs is undef.
10354 if (ISD::allOperandsUndef(N))
10355 return DAG.getUNDEF(VT);
10357 SDValue V = reduceBuildVecExtToExtBuildVec(N);
10361 V = reduceBuildVecConvertToConvertBuildVec(N);
10365 // Check to see if this is a BUILD_VECTOR of a bunch of EXTRACT_VECTOR_ELT
10366 // operations. If so, and if the EXTRACT_VECTOR_ELT vector inputs come from
10367 // at most two distinct vectors, turn this into a shuffle node.
10369 // May only combine to shuffle after legalize if shuffle is legal.
10370 if (LegalOperations && !TLI.isOperationLegal(ISD::VECTOR_SHUFFLE, VT))
10373 SDValue VecIn1, VecIn2;
10374 for (unsigned i = 0; i != NumInScalars; ++i) {
10375 // Ignore undef inputs.
10376 if (N->getOperand(i).getOpcode() == ISD::UNDEF) continue;
10378 // If this input is something other than a EXTRACT_VECTOR_ELT with a
10379 // constant index, bail out.
10380 if (N->getOperand(i).getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
10381 !isa<ConstantSDNode>(N->getOperand(i).getOperand(1))) {
10382 VecIn1 = VecIn2 = SDValue(nullptr, 0);
10386 // We allow up to two distinct input vectors.
10387 SDValue ExtractedFromVec = N->getOperand(i).getOperand(0);
10388 if (ExtractedFromVec == VecIn1 || ExtractedFromVec == VecIn2)
10391 if (!VecIn1.getNode()) {
10392 VecIn1 = ExtractedFromVec;
10393 } else if (!VecIn2.getNode()) {
10394 VecIn2 = ExtractedFromVec;
10396 // Too many inputs.
10397 VecIn1 = VecIn2 = SDValue(nullptr, 0);
10402 // If everything is good, we can make a shuffle operation.
10403 if (VecIn1.getNode()) {
10404 SmallVector<int, 8> Mask;
10405 for (unsigned i = 0; i != NumInScalars; ++i) {
10406 if (N->getOperand(i).getOpcode() == ISD::UNDEF) {
10407 Mask.push_back(-1);
10411 // If extracting from the first vector, just use the index directly.
10412 SDValue Extract = N->getOperand(i);
10413 SDValue ExtVal = Extract.getOperand(1);
10414 if (Extract.getOperand(0) == VecIn1) {
10415 unsigned ExtIndex = cast<ConstantSDNode>(ExtVal)->getZExtValue();
10416 if (ExtIndex > VT.getVectorNumElements())
10419 Mask.push_back(ExtIndex);
10423 // Otherwise, use InIdx + VecSize
10424 unsigned Idx = cast<ConstantSDNode>(ExtVal)->getZExtValue();
10425 Mask.push_back(Idx+NumInScalars);
10428 // We can't generate a shuffle node with mismatched input and output types.
10429 // Attempt to transform a single input vector to the correct type.
10430 if ((VT != VecIn1.getValueType())) {
10431 // We don't support shuffeling between TWO values of different types.
10432 if (VecIn2.getNode())
10435 // We only support widening of vectors which are half the size of the
10436 // output registers. For example XMM->YMM widening on X86 with AVX.
10437 if (VecIn1.getValueType().getSizeInBits()*2 != VT.getSizeInBits())
10440 // If the input vector type has a different base type to the output
10441 // vector type, bail out.
10442 if (VecIn1.getValueType().getVectorElementType() !=
10443 VT.getVectorElementType())
10446 // Widen the input vector by adding undef values.
10447 VecIn1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
10448 VecIn1, DAG.getUNDEF(VecIn1.getValueType()));
10451 // If VecIn2 is unused then change it to undef.
10452 VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(VT);
10454 // Check that we were able to transform all incoming values to the same
10456 if (VecIn2.getValueType() != VecIn1.getValueType() ||
10457 VecIn1.getValueType() != VT)
10460 // Only type-legal BUILD_VECTOR nodes are converted to shuffle nodes.
10461 if (!isTypeLegal(VT))
10464 // Return the new VECTOR_SHUFFLE node.
10468 return DAG.getVectorShuffle(VT, dl, Ops[0], Ops[1], &Mask[0]);
10474 SDValue DAGCombiner::visitCONCAT_VECTORS(SDNode *N) {
10475 // TODO: Check to see if this is a CONCAT_VECTORS of a bunch of
10476 // EXTRACT_SUBVECTOR operations. If so, and if the EXTRACT_SUBVECTOR vector
10477 // inputs come from at most two distinct vectors, turn this into a shuffle
10480 // If we only have one input vector, we don't need to do any concatenation.
10481 if (N->getNumOperands() == 1)
10482 return N->getOperand(0);
10484 // Check if all of the operands are undefs.
10485 EVT VT = N->getValueType(0);
10486 if (ISD::allOperandsUndef(N))
10487 return DAG.getUNDEF(VT);
10489 // Optimize concat_vectors where one of the vectors is undef.
10490 if (N->getNumOperands() == 2 &&
10491 N->getOperand(1)->getOpcode() == ISD::UNDEF) {
10492 SDValue In = N->getOperand(0);
10493 assert(In.getValueType().isVector() && "Must concat vectors");
10495 // Transform: concat_vectors(scalar, undef) -> scalar_to_vector(sclr).
10496 if (In->getOpcode() == ISD::BITCAST &&
10497 !In->getOperand(0)->getValueType(0).isVector()) {
10498 SDValue Scalar = In->getOperand(0);
10499 EVT SclTy = Scalar->getValueType(0);
10501 if (!SclTy.isFloatingPoint() && !SclTy.isInteger())
10504 EVT NVT = EVT::getVectorVT(*DAG.getContext(), SclTy,
10505 VT.getSizeInBits() / SclTy.getSizeInBits());
10506 if (!TLI.isTypeLegal(NVT) || !TLI.isTypeLegal(Scalar.getValueType()))
10509 SDLoc dl = SDLoc(N);
10510 SDValue Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, NVT, Scalar);
10511 return DAG.getNode(ISD::BITCAST, dl, VT, Res);
10515 // fold (concat_vectors (BUILD_VECTOR A, B, ...), (BUILD_VECTOR C, D, ...))
10516 // -> (BUILD_VECTOR A, B, ..., C, D, ...)
10517 if (N->getNumOperands() == 2 &&
10518 N->getOperand(0).getOpcode() == ISD::BUILD_VECTOR &&
10519 N->getOperand(1).getOpcode() == ISD::BUILD_VECTOR) {
10520 EVT VT = N->getValueType(0);
10521 SDValue N0 = N->getOperand(0);
10522 SDValue N1 = N->getOperand(1);
10523 SmallVector<SDValue, 8> Opnds;
10524 unsigned BuildVecNumElts = N0.getNumOperands();
10526 EVT SclTy0 = N0.getOperand(0)->getValueType(0);
10527 EVT SclTy1 = N1.getOperand(0)->getValueType(0);
10528 if (SclTy0.isFloatingPoint()) {
10529 for (unsigned i = 0; i != BuildVecNumElts; ++i)
10530 Opnds.push_back(N0.getOperand(i));
10531 for (unsigned i = 0; i != BuildVecNumElts; ++i)
10532 Opnds.push_back(N1.getOperand(i));
10534 // If BUILD_VECTOR are from built from integer, they may have different
10535 // operand types. Get the smaller type and truncate all operands to it.
10536 EVT MinTy = SclTy0.bitsLE(SclTy1) ? SclTy0 : SclTy1;
10537 for (unsigned i = 0; i != BuildVecNumElts; ++i)
10538 Opnds.push_back(DAG.getNode(ISD::TRUNCATE, SDLoc(N), MinTy,
10539 N0.getOperand(i)));
10540 for (unsigned i = 0; i != BuildVecNumElts; ++i)
10541 Opnds.push_back(DAG.getNode(ISD::TRUNCATE, SDLoc(N), MinTy,
10542 N1.getOperand(i)));
10545 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, Opnds);
10548 // Type legalization of vectors and DAG canonicalization of SHUFFLE_VECTOR
10549 // nodes often generate nop CONCAT_VECTOR nodes.
10550 // Scan the CONCAT_VECTOR operands and look for a CONCAT operations that
10551 // place the incoming vectors at the exact same location.
10552 SDValue SingleSource = SDValue();
10553 unsigned PartNumElem = N->getOperand(0).getValueType().getVectorNumElements();
10555 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
10556 SDValue Op = N->getOperand(i);
10558 if (Op.getOpcode() == ISD::UNDEF)
10561 // Check if this is the identity extract:
10562 if (Op.getOpcode() != ISD::EXTRACT_SUBVECTOR)
10565 // Find the single incoming vector for the extract_subvector.
10566 if (SingleSource.getNode()) {
10567 if (Op.getOperand(0) != SingleSource)
10570 SingleSource = Op.getOperand(0);
10572 // Check the source type is the same as the type of the result.
10573 // If not, this concat may extend the vector, so we can not
10574 // optimize it away.
10575 if (SingleSource.getValueType() != N->getValueType(0))
10579 unsigned IdentityIndex = i * PartNumElem;
10580 ConstantSDNode *CS = dyn_cast<ConstantSDNode>(Op.getOperand(1));
10581 // The extract index must be constant.
10585 // Check that we are reading from the identity index.
10586 if (CS->getZExtValue() != IdentityIndex)
10590 if (SingleSource.getNode())
10591 return SingleSource;
10596 SDValue DAGCombiner::visitEXTRACT_SUBVECTOR(SDNode* N) {
10597 EVT NVT = N->getValueType(0);
10598 SDValue V = N->getOperand(0);
10600 if (V->getOpcode() == ISD::CONCAT_VECTORS) {
10602 // (extract_subvec (concat V1, V2, ...), i)
10605 // Only operand 0 is checked as 'concat' assumes all inputs of the same
10607 if (V->getOperand(0).getValueType() != NVT)
10609 unsigned Idx = dyn_cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
10610 unsigned NumElems = NVT.getVectorNumElements();
10611 assert((Idx % NumElems) == 0 &&
10612 "IDX in concat is not a multiple of the result vector length.");
10613 return V->getOperand(Idx / NumElems);
10617 if (V->getOpcode() == ISD::BITCAST)
10618 V = V.getOperand(0);
10620 if (V->getOpcode() == ISD::INSERT_SUBVECTOR) {
10622 // Handle only simple case where vector being inserted and vector
10623 // being extracted are of same type, and are half size of larger vectors.
10624 EVT BigVT = V->getOperand(0).getValueType();
10625 EVT SmallVT = V->getOperand(1).getValueType();
10626 if (!NVT.bitsEq(SmallVT) || NVT.getSizeInBits()*2 != BigVT.getSizeInBits())
10629 // Only handle cases where both indexes are constants with the same type.
10630 ConstantSDNode *ExtIdx = dyn_cast<ConstantSDNode>(N->getOperand(1));
10631 ConstantSDNode *InsIdx = dyn_cast<ConstantSDNode>(V->getOperand(2));
10633 if (InsIdx && ExtIdx &&
10634 InsIdx->getValueType(0).getSizeInBits() <= 64 &&
10635 ExtIdx->getValueType(0).getSizeInBits() <= 64) {
10637 // (extract_subvec (insert_subvec V1, V2, InsIdx), ExtIdx)
10639 // indices are equal or bit offsets are equal => V1
10640 // otherwise => (extract_subvec V1, ExtIdx)
10641 if (InsIdx->getZExtValue() * SmallVT.getScalarType().getSizeInBits() ==
10642 ExtIdx->getZExtValue() * NVT.getScalarType().getSizeInBits())
10643 return DAG.getNode(ISD::BITCAST, dl, NVT, V->getOperand(1));
10644 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, NVT,
10645 DAG.getNode(ISD::BITCAST, dl,
10646 N->getOperand(0).getValueType(),
10647 V->getOperand(0)), N->getOperand(1));
10654 // Tries to turn a shuffle of two CONCAT_VECTORS into a single concat.
10655 static SDValue partitionShuffleOfConcats(SDNode *N, SelectionDAG &DAG) {
10656 EVT VT = N->getValueType(0);
10657 unsigned NumElts = VT.getVectorNumElements();
10659 SDValue N0 = N->getOperand(0);
10660 SDValue N1 = N->getOperand(1);
10661 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
10663 SmallVector<SDValue, 4> Ops;
10664 EVT ConcatVT = N0.getOperand(0).getValueType();
10665 unsigned NumElemsPerConcat = ConcatVT.getVectorNumElements();
10666 unsigned NumConcats = NumElts / NumElemsPerConcat;
10668 // Look at every vector that's inserted. We're looking for exact
10669 // subvector-sized copies from a concatenated vector
10670 for (unsigned I = 0; I != NumConcats; ++I) {
10671 // Make sure we're dealing with a copy.
10672 unsigned Begin = I * NumElemsPerConcat;
10673 bool AllUndef = true, NoUndef = true;
10674 for (unsigned J = Begin; J != Begin + NumElemsPerConcat; ++J) {
10675 if (SVN->getMaskElt(J) >= 0)
10682 if (SVN->getMaskElt(Begin) % NumElemsPerConcat != 0)
10685 for (unsigned J = 1; J != NumElemsPerConcat; ++J)
10686 if (SVN->getMaskElt(Begin + J - 1) + 1 != SVN->getMaskElt(Begin + J))
10689 unsigned FirstElt = SVN->getMaskElt(Begin) / NumElemsPerConcat;
10690 if (FirstElt < N0.getNumOperands())
10691 Ops.push_back(N0.getOperand(FirstElt));
10693 Ops.push_back(N1.getOperand(FirstElt - N0.getNumOperands()));
10695 } else if (AllUndef) {
10696 Ops.push_back(DAG.getUNDEF(N0.getOperand(0).getValueType()));
10697 } else { // Mixed with general masks and undefs, can't do optimization.
10702 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Ops);
10705 SDValue DAGCombiner::visitVECTOR_SHUFFLE(SDNode *N) {
10706 EVT VT = N->getValueType(0);
10707 unsigned NumElts = VT.getVectorNumElements();
10709 SDValue N0 = N->getOperand(0);
10710 SDValue N1 = N->getOperand(1);
10712 assert(N0.getValueType() == VT && "Vector shuffle must be normalized in DAG");
10714 // Canonicalize shuffle undef, undef -> undef
10715 if (N0.getOpcode() == ISD::UNDEF && N1.getOpcode() == ISD::UNDEF)
10716 return DAG.getUNDEF(VT);
10718 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
10720 // Canonicalize shuffle v, v -> v, undef
10722 SmallVector<int, 8> NewMask;
10723 for (unsigned i = 0; i != NumElts; ++i) {
10724 int Idx = SVN->getMaskElt(i);
10725 if (Idx >= (int)NumElts) Idx -= NumElts;
10726 NewMask.push_back(Idx);
10728 return DAG.getVectorShuffle(VT, SDLoc(N), N0, DAG.getUNDEF(VT),
10732 // Canonicalize shuffle undef, v -> v, undef. Commute the shuffle mask.
10733 if (N0.getOpcode() == ISD::UNDEF) {
10734 SmallVector<int, 8> NewMask;
10735 for (unsigned i = 0; i != NumElts; ++i) {
10736 int Idx = SVN->getMaskElt(i);
10738 if (Idx >= (int)NumElts)
10741 Idx = -1; // remove reference to lhs
10743 NewMask.push_back(Idx);
10745 return DAG.getVectorShuffle(VT, SDLoc(N), N1, DAG.getUNDEF(VT),
10749 // Remove references to rhs if it is undef
10750 if (N1.getOpcode() == ISD::UNDEF) {
10751 bool Changed = false;
10752 SmallVector<int, 8> NewMask;
10753 for (unsigned i = 0; i != NumElts; ++i) {
10754 int Idx = SVN->getMaskElt(i);
10755 if (Idx >= (int)NumElts) {
10759 NewMask.push_back(Idx);
10762 return DAG.getVectorShuffle(VT, SDLoc(N), N0, N1, &NewMask[0]);
10765 // If it is a splat, check if the argument vector is another splat or a
10766 // build_vector with all scalar elements the same.
10767 if (SVN->isSplat() && SVN->getSplatIndex() < (int)NumElts) {
10768 SDNode *V = N0.getNode();
10770 // If this is a bit convert that changes the element type of the vector but
10771 // not the number of vector elements, look through it. Be careful not to
10772 // look though conversions that change things like v4f32 to v2f64.
10773 if (V->getOpcode() == ISD::BITCAST) {
10774 SDValue ConvInput = V->getOperand(0);
10775 if (ConvInput.getValueType().isVector() &&
10776 ConvInput.getValueType().getVectorNumElements() == NumElts)
10777 V = ConvInput.getNode();
10780 if (V->getOpcode() == ISD::BUILD_VECTOR) {
10781 assert(V->getNumOperands() == NumElts &&
10782 "BUILD_VECTOR has wrong number of operands");
10784 bool AllSame = true;
10785 for (unsigned i = 0; i != NumElts; ++i) {
10786 if (V->getOperand(i).getOpcode() != ISD::UNDEF) {
10787 Base = V->getOperand(i);
10791 // Splat of <u, u, u, u>, return <u, u, u, u>
10792 if (!Base.getNode())
10794 for (unsigned i = 0; i != NumElts; ++i) {
10795 if (V->getOperand(i) != Base) {
10800 // Splat of <x, x, x, x>, return <x, x, x, x>
10806 if (N0.getOpcode() == ISD::CONCAT_VECTORS &&
10807 Level < AfterLegalizeVectorOps &&
10808 (N1.getOpcode() == ISD::UNDEF ||
10809 (N1.getOpcode() == ISD::CONCAT_VECTORS &&
10810 N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType()))) {
10811 SDValue V = partitionShuffleOfConcats(N, DAG);
10817 // If this shuffle node is simply a swizzle of another shuffle node,
10818 // then try to simplify it.
10819 if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG &&
10820 N1.getOpcode() == ISD::UNDEF) {
10822 ShuffleVectorSDNode *OtherSV = cast<ShuffleVectorSDNode>(N0);
10824 // The incoming shuffle must be of the same type as the result of the
10825 // current shuffle.
10826 assert(OtherSV->getOperand(0).getValueType() == VT &&
10827 "Shuffle types don't match");
10829 SmallVector<int, 4> Mask;
10830 // Compute the combined shuffle mask.
10831 for (unsigned i = 0; i != NumElts; ++i) {
10832 int Idx = SVN->getMaskElt(i);
10833 assert(Idx < (int)NumElts && "Index references undef operand");
10834 // Next, this index comes from the first value, which is the incoming
10835 // shuffle. Adopt the incoming index.
10837 Idx = OtherSV->getMaskElt(Idx);
10838 Mask.push_back(Idx);
10841 // Check if all indices in Mask are Undef. In case, propagate Undef.
10842 bool isUndefMask = true;
10843 for (unsigned i = 0; i != NumElts && isUndefMask; ++i)
10844 isUndefMask &= Mask[i] < 0;
10847 return DAG.getUNDEF(VT);
10849 bool CommuteOperands = false;
10850 if (N0.getOperand(1).getOpcode() != ISD::UNDEF) {
10851 // To be valid, the combine shuffle mask should only reference elements
10852 // from one of the two vectors in input to the inner shufflevector.
10853 bool IsValidMask = true;
10854 for (unsigned i = 0; i != NumElts && IsValidMask; ++i)
10855 // See if the combined mask only reference undefs or elements coming
10856 // from the first shufflevector operand.
10857 IsValidMask = Mask[i] < 0 || (unsigned)Mask[i] < NumElts;
10859 if (!IsValidMask) {
10860 IsValidMask = true;
10861 for (unsigned i = 0; i != NumElts && IsValidMask; ++i)
10862 // Check that all the elements come from the second shuffle operand.
10863 IsValidMask = Mask[i] < 0 || (unsigned)Mask[i] >= NumElts;
10864 CommuteOperands = IsValidMask;
10867 // Early exit if the combined shuffle mask is not valid.
10872 // See if this pair of shuffles can be safely folded according to either
10873 // of the following rules:
10874 // shuffle(shuffle(x, y), undef) -> x
10875 // shuffle(shuffle(x, undef), undef) -> x
10876 // shuffle(shuffle(x, y), undef) -> y
10877 bool IsIdentityMask = true;
10878 unsigned BaseMaskIndex = CommuteOperands ? NumElts : 0;
10879 for (unsigned i = 0; i != NumElts && IsIdentityMask; ++i) {
10884 // The combined shuffle must map each index to itself.
10885 IsIdentityMask = (unsigned)Mask[i] == i + BaseMaskIndex;
10888 if (IsIdentityMask) {
10889 if (CommuteOperands)
10890 // optimize shuffle(shuffle(x, y), undef) -> y.
10891 return OtherSV->getOperand(1);
10893 // optimize shuffle(shuffle(x, undef), undef) -> x
10894 // optimize shuffle(shuffle(x, y), undef) -> x
10895 return OtherSV->getOperand(0);
10898 // It may still be beneficial to combine the two shuffles if the
10899 // resulting shuffle is legal.
10900 if (TLI.isTypeLegal(VT)) {
10901 if (!CommuteOperands) {
10902 if (TLI.isShuffleMaskLegal(Mask, VT))
10903 // shuffle(shuffle(x, undef, M1), undef, M2) -> shuffle(x, undef, M3).
10904 // shuffle(shuffle(x, y, M1), undef, M2) -> shuffle(x, undef, M3)
10905 return DAG.getVectorShuffle(VT, SDLoc(N), N0->getOperand(0), N1,
10908 // Compute the commuted shuffle mask.
10909 for (unsigned i = 0; i != NumElts; ++i) {
10913 else if (idx < (int)NumElts)
10914 Mask[i] = idx + NumElts;
10916 Mask[i] = idx - NumElts;
10919 if (TLI.isShuffleMaskLegal(Mask, VT))
10920 // shuffle(shuffle(x, y, M1), undef, M2) -> shuffle(y, undef, M3)
10921 return DAG.getVectorShuffle(VT, SDLoc(N), N0->getOperand(1), N1,
10927 // Canonicalize shuffles according to rules:
10928 // shuffle(A, shuffle(A, B)) -> shuffle(shuffle(A,B), A)
10929 // shuffle(B, shuffle(A, B)) -> shuffle(shuffle(A,B), B)
10930 // shuffle(B, shuffle(A, Undef)) -> shuffle(shuffle(A, Undef), B)
10931 if (N1.getOpcode() == ISD::VECTOR_SHUFFLE && N0.getOpcode() != ISD::UNDEF &&
10932 N0.getOpcode() != ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG &&
10933 TLI.isTypeLegal(VT)) {
10934 // The incoming shuffle must be of the same type as the result of the
10935 // current shuffle.
10936 assert(N1->getOperand(0).getValueType() == VT &&
10937 "Shuffle types don't match");
10939 SDValue SV0 = N1->getOperand(0);
10940 SDValue SV1 = N1->getOperand(1);
10941 bool HasSameOp0 = N0 == SV0;
10942 bool IsSV1Undef = SV1.getOpcode() == ISD::UNDEF;
10943 if (HasSameOp0 || IsSV1Undef || N0 == SV1)
10944 // Commute the operands of this shuffle so that next rule
10946 return DAG.getCommutedVectorShuffle(*SVN);
10949 // Try to fold according to rules:
10950 // shuffle(shuffle(A, B, M0), B, M1) -> shuffle(A, B, M2)
10951 // shuffle(shuffle(A, B, M0), A, M1) -> shuffle(A, B, M2)
10952 // shuffle(shuffle(A, Undef, M0), B, M1) -> shuffle(A, B, M2)
10953 // shuffle(shuffle(A, Undef, M0), A, M1) -> shuffle(A, Undef, M2)
10954 // Don't try to fold shuffles with illegal type.
10955 if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG &&
10956 N1.getOpcode() != ISD::UNDEF && TLI.isTypeLegal(VT)) {
10957 ShuffleVectorSDNode *OtherSV = cast<ShuffleVectorSDNode>(N0);
10959 // The incoming shuffle must be of the same type as the result of the
10960 // current shuffle.
10961 assert(OtherSV->getOperand(0).getValueType() == VT &&
10962 "Shuffle types don't match");
10964 SDValue SV0 = OtherSV->getOperand(0);
10965 SDValue SV1 = OtherSV->getOperand(1);
10966 bool HasSameOp0 = N1 == SV0;
10967 bool IsSV1Undef = SV1.getOpcode() == ISD::UNDEF;
10968 if (!HasSameOp0 && !IsSV1Undef && N1 != SV1)
10972 SmallVector<int, 4> Mask;
10973 // Compute the combined shuffle mask for a shuffle with SV0 as the first
10974 // operand, and SV1 as the second operand.
10975 for (unsigned i = 0; i != NumElts; ++i) {
10976 int Idx = SVN->getMaskElt(i);
10978 // Propagate Undef.
10979 Mask.push_back(Idx);
10983 if (Idx < (int)NumElts) {
10984 Idx = OtherSV->getMaskElt(Idx);
10985 if (IsSV1Undef && Idx >= (int) NumElts)
10986 Idx = -1; // Propagate Undef.
10988 Idx = HasSameOp0 ? Idx - NumElts : Idx;
10990 Mask.push_back(Idx);
10993 // Check if all indices in Mask are Undef. In case, propagate Undef.
10994 bool isUndefMask = true;
10995 for (unsigned i = 0; i != NumElts && isUndefMask; ++i)
10996 isUndefMask &= Mask[i] < 0;
10999 return DAG.getUNDEF(VT);
11001 // Avoid introducing shuffles with illegal mask.
11002 if (TLI.isShuffleMaskLegal(Mask, VT)) {
11004 // shuffle(shuffle(A, Undef, M0), B, M1) -> shuffle(A, B, M2)
11005 // shuffle(shuffle(A, Undef, M0), A, M1) -> shuffle(A, Undef, M2)
11006 return DAG.getVectorShuffle(VT, SDLoc(N), SV0, N1, &Mask[0]);
11007 return DAG.getVectorShuffle(VT, SDLoc(N), SV0, SV1, &Mask[0]);
11014 SDValue DAGCombiner::visitINSERT_SUBVECTOR(SDNode *N) {
11015 SDValue N0 = N->getOperand(0);
11016 SDValue N2 = N->getOperand(2);
11018 // If the input vector is a concatenation, and the insert replaces
11019 // one of the halves, we can optimize into a single concat_vectors.
11020 if (N0.getOpcode() == ISD::CONCAT_VECTORS &&
11021 N0->getNumOperands() == 2 && N2.getOpcode() == ISD::Constant) {
11022 APInt InsIdx = cast<ConstantSDNode>(N2)->getAPIntValue();
11023 EVT VT = N->getValueType(0);
11025 // Lower half: fold (insert_subvector (concat_vectors X, Y), Z) ->
11026 // (concat_vectors Z, Y)
11028 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
11029 N->getOperand(1), N0.getOperand(1));
11031 // Upper half: fold (insert_subvector (concat_vectors X, Y), Z) ->
11032 // (concat_vectors X, Z)
11033 if (InsIdx == VT.getVectorNumElements()/2)
11034 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
11035 N0.getOperand(0), N->getOperand(1));
11041 /// Returns a vector_shuffle if it able to transform an AND to a vector_shuffle
11042 /// with the destination vector and a zero vector.
11043 /// e.g. AND V, <0xffffffff, 0, 0xffffffff, 0>. ==>
11044 /// vector_shuffle V, Zero, <0, 4, 2, 4>
11045 SDValue DAGCombiner::XformToShuffleWithZero(SDNode *N) {
11046 EVT VT = N->getValueType(0);
11048 SDValue LHS = N->getOperand(0);
11049 SDValue RHS = N->getOperand(1);
11050 if (N->getOpcode() == ISD::AND) {
11051 if (RHS.getOpcode() == ISD::BITCAST)
11052 RHS = RHS.getOperand(0);
11053 if (RHS.getOpcode() == ISD::BUILD_VECTOR) {
11054 SmallVector<int, 8> Indices;
11055 unsigned NumElts = RHS.getNumOperands();
11056 for (unsigned i = 0; i != NumElts; ++i) {
11057 SDValue Elt = RHS.getOperand(i);
11058 if (!isa<ConstantSDNode>(Elt))
11061 if (cast<ConstantSDNode>(Elt)->isAllOnesValue())
11062 Indices.push_back(i);
11063 else if (cast<ConstantSDNode>(Elt)->isNullValue())
11064 Indices.push_back(NumElts);
11069 // Let's see if the target supports this vector_shuffle.
11070 EVT RVT = RHS.getValueType();
11071 if (!TLI.isVectorClearMaskLegal(Indices, RVT))
11074 // Return the new VECTOR_SHUFFLE node.
11075 EVT EltVT = RVT.getVectorElementType();
11076 SmallVector<SDValue,8> ZeroOps(RVT.getVectorNumElements(),
11077 DAG.getConstant(0, EltVT));
11078 SDValue Zero = DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), RVT, ZeroOps);
11079 LHS = DAG.getNode(ISD::BITCAST, dl, RVT, LHS);
11080 SDValue Shuf = DAG.getVectorShuffle(RVT, dl, LHS, Zero, &Indices[0]);
11081 return DAG.getNode(ISD::BITCAST, dl, VT, Shuf);
11088 /// Visit a binary vector operation, like ADD.
11089 SDValue DAGCombiner::SimplifyVBinOp(SDNode *N) {
11090 assert(N->getValueType(0).isVector() &&
11091 "SimplifyVBinOp only works on vectors!");
11093 SDValue LHS = N->getOperand(0);
11094 SDValue RHS = N->getOperand(1);
11095 SDValue Shuffle = XformToShuffleWithZero(N);
11096 if (Shuffle.getNode()) return Shuffle;
11098 // If the LHS and RHS are BUILD_VECTOR nodes, see if we can constant fold
11100 if (LHS.getOpcode() == ISD::BUILD_VECTOR &&
11101 RHS.getOpcode() == ISD::BUILD_VECTOR) {
11102 // Check if both vectors are constants. If not bail out.
11103 if (!(cast<BuildVectorSDNode>(LHS)->isConstant() &&
11104 cast<BuildVectorSDNode>(RHS)->isConstant()))
11107 SmallVector<SDValue, 8> Ops;
11108 for (unsigned i = 0, e = LHS.getNumOperands(); i != e; ++i) {
11109 SDValue LHSOp = LHS.getOperand(i);
11110 SDValue RHSOp = RHS.getOperand(i);
11112 // Can't fold divide by zero.
11113 if (N->getOpcode() == ISD::SDIV || N->getOpcode() == ISD::UDIV ||
11114 N->getOpcode() == ISD::FDIV) {
11115 if ((RHSOp.getOpcode() == ISD::Constant &&
11116 cast<ConstantSDNode>(RHSOp.getNode())->isNullValue()) ||
11117 (RHSOp.getOpcode() == ISD::ConstantFP &&
11118 cast<ConstantFPSDNode>(RHSOp.getNode())->getValueAPF().isZero()))
11122 EVT VT = LHSOp.getValueType();
11123 EVT RVT = RHSOp.getValueType();
11125 // Integer BUILD_VECTOR operands may have types larger than the element
11126 // size (e.g., when the element type is not legal). Prior to type
11127 // legalization, the types may not match between the two BUILD_VECTORS.
11128 // Truncate one of the operands to make them match.
11129 if (RVT.getSizeInBits() > VT.getSizeInBits()) {
11130 RHSOp = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, RHSOp);
11132 LHSOp = DAG.getNode(ISD::TRUNCATE, SDLoc(N), RVT, LHSOp);
11136 SDValue FoldOp = DAG.getNode(N->getOpcode(), SDLoc(LHS), VT,
11138 if (FoldOp.getOpcode() != ISD::UNDEF &&
11139 FoldOp.getOpcode() != ISD::Constant &&
11140 FoldOp.getOpcode() != ISD::ConstantFP)
11142 Ops.push_back(FoldOp);
11143 AddToWorklist(FoldOp.getNode());
11146 if (Ops.size() == LHS.getNumOperands())
11147 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), LHS.getValueType(), Ops);
11150 // Type legalization might introduce new shuffles in the DAG.
11151 // Fold (VBinOp (shuffle (A, Undef, Mask)), (shuffle (B, Undef, Mask)))
11152 // -> (shuffle (VBinOp (A, B)), Undef, Mask).
11153 if (LegalTypes && isa<ShuffleVectorSDNode>(LHS) &&
11154 isa<ShuffleVectorSDNode>(RHS) && LHS.hasOneUse() && RHS.hasOneUse() &&
11155 LHS.getOperand(1).getOpcode() == ISD::UNDEF &&
11156 RHS.getOperand(1).getOpcode() == ISD::UNDEF) {
11157 ShuffleVectorSDNode *SVN0 = cast<ShuffleVectorSDNode>(LHS);
11158 ShuffleVectorSDNode *SVN1 = cast<ShuffleVectorSDNode>(RHS);
11160 if (SVN0->getMask().equals(SVN1->getMask())) {
11161 EVT VT = N->getValueType(0);
11162 SDValue UndefVector = LHS.getOperand(1);
11163 SDValue NewBinOp = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
11164 LHS.getOperand(0), RHS.getOperand(0));
11165 AddUsersToWorklist(N);
11166 return DAG.getVectorShuffle(VT, SDLoc(N), NewBinOp, UndefVector,
11167 &SVN0->getMask()[0]);
11174 /// Visit a binary vector operation, like FABS/FNEG.
11175 SDValue DAGCombiner::SimplifyVUnaryOp(SDNode *N) {
11176 assert(N->getValueType(0).isVector() &&
11177 "SimplifyVUnaryOp only works on vectors!");
11179 SDValue N0 = N->getOperand(0);
11181 if (N0.getOpcode() != ISD::BUILD_VECTOR)
11184 // Operand is a BUILD_VECTOR node, see if we can constant fold it.
11185 SmallVector<SDValue, 8> Ops;
11186 for (unsigned i = 0, e = N0.getNumOperands(); i != e; ++i) {
11187 SDValue Op = N0.getOperand(i);
11188 if (Op.getOpcode() != ISD::UNDEF &&
11189 Op.getOpcode() != ISD::ConstantFP)
11191 EVT EltVT = Op.getValueType();
11192 SDValue FoldOp = DAG.getNode(N->getOpcode(), SDLoc(N0), EltVT, Op);
11193 if (FoldOp.getOpcode() != ISD::UNDEF &&
11194 FoldOp.getOpcode() != ISD::ConstantFP)
11196 Ops.push_back(FoldOp);
11197 AddToWorklist(FoldOp.getNode());
11200 if (Ops.size() != N0.getNumOperands())
11203 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), N0.getValueType(), Ops);
11206 SDValue DAGCombiner::SimplifySelect(SDLoc DL, SDValue N0,
11207 SDValue N1, SDValue N2){
11208 assert(N0.getOpcode() ==ISD::SETCC && "First argument must be a SetCC node!");
11210 SDValue SCC = SimplifySelectCC(DL, N0.getOperand(0), N0.getOperand(1), N1, N2,
11211 cast<CondCodeSDNode>(N0.getOperand(2))->get());
11213 // If we got a simplified select_cc node back from SimplifySelectCC, then
11214 // break it down into a new SETCC node, and a new SELECT node, and then return
11215 // the SELECT node, since we were called with a SELECT node.
11216 if (SCC.getNode()) {
11217 // Check to see if we got a select_cc back (to turn into setcc/select).
11218 // Otherwise, just return whatever node we got back, like fabs.
11219 if (SCC.getOpcode() == ISD::SELECT_CC) {
11220 SDValue SETCC = DAG.getNode(ISD::SETCC, SDLoc(N0),
11222 SCC.getOperand(0), SCC.getOperand(1),
11223 SCC.getOperand(4));
11224 AddToWorklist(SETCC.getNode());
11225 return DAG.getSelect(SDLoc(SCC), SCC.getValueType(), SETCC,
11226 SCC.getOperand(2), SCC.getOperand(3));
11234 /// Given a SELECT or a SELECT_CC node, where LHS and RHS are the two values
11235 /// being selected between, see if we can simplify the select. Callers of this
11236 /// should assume that TheSelect is deleted if this returns true. As such, they
11237 /// should return the appropriate thing (e.g. the node) back to the top-level of
11238 /// the DAG combiner loop to avoid it being looked at.
11239 bool DAGCombiner::SimplifySelectOps(SDNode *TheSelect, SDValue LHS,
11242 // Cannot simplify select with vector condition
11243 if (TheSelect->getOperand(0).getValueType().isVector()) return false;
11245 // If this is a select from two identical things, try to pull the operation
11246 // through the select.
11247 if (LHS.getOpcode() != RHS.getOpcode() ||
11248 !LHS.hasOneUse() || !RHS.hasOneUse())
11251 // If this is a load and the token chain is identical, replace the select
11252 // of two loads with a load through a select of the address to load from.
11253 // This triggers in things like "select bool X, 10.0, 123.0" after the FP
11254 // constants have been dropped into the constant pool.
11255 if (LHS.getOpcode() == ISD::LOAD) {
11256 LoadSDNode *LLD = cast<LoadSDNode>(LHS);
11257 LoadSDNode *RLD = cast<LoadSDNode>(RHS);
11259 // Token chains must be identical.
11260 if (LHS.getOperand(0) != RHS.getOperand(0) ||
11261 // Do not let this transformation reduce the number of volatile loads.
11262 LLD->isVolatile() || RLD->isVolatile() ||
11263 // If this is an EXTLOAD, the VT's must match.
11264 LLD->getMemoryVT() != RLD->getMemoryVT() ||
11265 // If this is an EXTLOAD, the kind of extension must match.
11266 (LLD->getExtensionType() != RLD->getExtensionType() &&
11267 // The only exception is if one of the extensions is anyext.
11268 LLD->getExtensionType() != ISD::EXTLOAD &&
11269 RLD->getExtensionType() != ISD::EXTLOAD) ||
11270 // FIXME: this discards src value information. This is
11271 // over-conservative. It would be beneficial to be able to remember
11272 // both potential memory locations. Since we are discarding
11273 // src value info, don't do the transformation if the memory
11274 // locations are not in the default address space.
11275 LLD->getPointerInfo().getAddrSpace() != 0 ||
11276 RLD->getPointerInfo().getAddrSpace() != 0 ||
11277 !TLI.isOperationLegalOrCustom(TheSelect->getOpcode(),
11278 LLD->getBasePtr().getValueType()))
11281 // Check that the select condition doesn't reach either load. If so,
11282 // folding this will induce a cycle into the DAG. If not, this is safe to
11283 // xform, so create a select of the addresses.
11285 if (TheSelect->getOpcode() == ISD::SELECT) {
11286 SDNode *CondNode = TheSelect->getOperand(0).getNode();
11287 if ((LLD->hasAnyUseOfValue(1) && LLD->isPredecessorOf(CondNode)) ||
11288 (RLD->hasAnyUseOfValue(1) && RLD->isPredecessorOf(CondNode)))
11290 // The loads must not depend on one another.
11291 if (LLD->isPredecessorOf(RLD) ||
11292 RLD->isPredecessorOf(LLD))
11294 Addr = DAG.getSelect(SDLoc(TheSelect),
11295 LLD->getBasePtr().getValueType(),
11296 TheSelect->getOperand(0), LLD->getBasePtr(),
11297 RLD->getBasePtr());
11298 } else { // Otherwise SELECT_CC
11299 SDNode *CondLHS = TheSelect->getOperand(0).getNode();
11300 SDNode *CondRHS = TheSelect->getOperand(1).getNode();
11302 if ((LLD->hasAnyUseOfValue(1) &&
11303 (LLD->isPredecessorOf(CondLHS) || LLD->isPredecessorOf(CondRHS))) ||
11304 (RLD->hasAnyUseOfValue(1) &&
11305 (RLD->isPredecessorOf(CondLHS) || RLD->isPredecessorOf(CondRHS))))
11308 Addr = DAG.getNode(ISD::SELECT_CC, SDLoc(TheSelect),
11309 LLD->getBasePtr().getValueType(),
11310 TheSelect->getOperand(0),
11311 TheSelect->getOperand(1),
11312 LLD->getBasePtr(), RLD->getBasePtr(),
11313 TheSelect->getOperand(4));
11317 // It is safe to replace the two loads if they have different alignments,
11318 // but the new load must be the minimum (most restrictive) alignment of the
11320 bool isInvariant = LLD->getAlignment() & RLD->getAlignment();
11321 unsigned Alignment = std::min(LLD->getAlignment(), RLD->getAlignment());
11322 if (LLD->getExtensionType() == ISD::NON_EXTLOAD) {
11323 Load = DAG.getLoad(TheSelect->getValueType(0),
11325 // FIXME: Discards pointer and AA info.
11326 LLD->getChain(), Addr, MachinePointerInfo(),
11327 LLD->isVolatile(), LLD->isNonTemporal(),
11328 isInvariant, Alignment);
11330 Load = DAG.getExtLoad(LLD->getExtensionType() == ISD::EXTLOAD ?
11331 RLD->getExtensionType() : LLD->getExtensionType(),
11333 TheSelect->getValueType(0),
11334 // FIXME: Discards pointer and AA info.
11335 LLD->getChain(), Addr, MachinePointerInfo(),
11336 LLD->getMemoryVT(), LLD->isVolatile(),
11337 LLD->isNonTemporal(), isInvariant, Alignment);
11340 // Users of the select now use the result of the load.
11341 CombineTo(TheSelect, Load);
11343 // Users of the old loads now use the new load's chain. We know the
11344 // old-load value is dead now.
11345 CombineTo(LHS.getNode(), Load.getValue(0), Load.getValue(1));
11346 CombineTo(RHS.getNode(), Load.getValue(0), Load.getValue(1));
11353 /// Simplify an expression of the form (N0 cond N1) ? N2 : N3
11354 /// where 'cond' is the comparison specified by CC.
11355 SDValue DAGCombiner::SimplifySelectCC(SDLoc DL, SDValue N0, SDValue N1,
11356 SDValue N2, SDValue N3,
11357 ISD::CondCode CC, bool NotExtCompare) {
11358 // (x ? y : y) -> y.
11359 if (N2 == N3) return N2;
11361 EVT VT = N2.getValueType();
11362 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
11363 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2.getNode());
11364 ConstantSDNode *N3C = dyn_cast<ConstantSDNode>(N3.getNode());
11366 // Determine if the condition we're dealing with is constant
11367 SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()),
11368 N0, N1, CC, DL, false);
11369 if (SCC.getNode()) AddToWorklist(SCC.getNode());
11370 ConstantSDNode *SCCC = dyn_cast_or_null<ConstantSDNode>(SCC.getNode());
11372 // fold select_cc true, x, y -> x
11373 if (SCCC && !SCCC->isNullValue())
11375 // fold select_cc false, x, y -> y
11376 if (SCCC && SCCC->isNullValue())
11379 // Check to see if we can simplify the select into an fabs node
11380 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N1)) {
11381 // Allow either -0.0 or 0.0
11382 if (CFP->getValueAPF().isZero()) {
11383 // select (setg[te] X, +/-0.0), X, fneg(X) -> fabs
11384 if ((CC == ISD::SETGE || CC == ISD::SETGT) &&
11385 N0 == N2 && N3.getOpcode() == ISD::FNEG &&
11386 N2 == N3.getOperand(0))
11387 return DAG.getNode(ISD::FABS, DL, VT, N0);
11389 // select (setl[te] X, +/-0.0), fneg(X), X -> fabs
11390 if ((CC == ISD::SETLT || CC == ISD::SETLE) &&
11391 N0 == N3 && N2.getOpcode() == ISD::FNEG &&
11392 N2.getOperand(0) == N3)
11393 return DAG.getNode(ISD::FABS, DL, VT, N3);
11397 // Turn "(a cond b) ? 1.0f : 2.0f" into "load (tmp + ((a cond b) ? 0 : 4)"
11398 // where "tmp" is a constant pool entry containing an array with 1.0 and 2.0
11399 // in it. This is a win when the constant is not otherwise available because
11400 // it replaces two constant pool loads with one. We only do this if the FP
11401 // type is known to be legal, because if it isn't, then we are before legalize
11402 // types an we want the other legalization to happen first (e.g. to avoid
11403 // messing with soft float) and if the ConstantFP is not legal, because if
11404 // it is legal, we may not need to store the FP constant in a constant pool.
11405 if (ConstantFPSDNode *TV = dyn_cast<ConstantFPSDNode>(N2))
11406 if (ConstantFPSDNode *FV = dyn_cast<ConstantFPSDNode>(N3)) {
11407 if (TLI.isTypeLegal(N2.getValueType()) &&
11408 (TLI.getOperationAction(ISD::ConstantFP, N2.getValueType()) !=
11409 TargetLowering::Legal &&
11410 !TLI.isFPImmLegal(TV->getValueAPF(), TV->getValueType(0)) &&
11411 !TLI.isFPImmLegal(FV->getValueAPF(), FV->getValueType(0))) &&
11412 // If both constants have multiple uses, then we won't need to do an
11413 // extra load, they are likely around in registers for other users.
11414 (TV->hasOneUse() || FV->hasOneUse())) {
11415 Constant *Elts[] = {
11416 const_cast<ConstantFP*>(FV->getConstantFPValue()),
11417 const_cast<ConstantFP*>(TV->getConstantFPValue())
11419 Type *FPTy = Elts[0]->getType();
11420 const DataLayout &TD = *TLI.getDataLayout();
11422 // Create a ConstantArray of the two constants.
11423 Constant *CA = ConstantArray::get(ArrayType::get(FPTy, 2), Elts);
11424 SDValue CPIdx = DAG.getConstantPool(CA, TLI.getPointerTy(),
11425 TD.getPrefTypeAlignment(FPTy));
11426 unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
11428 // Get the offsets to the 0 and 1 element of the array so that we can
11429 // select between them.
11430 SDValue Zero = DAG.getIntPtrConstant(0);
11431 unsigned EltSize = (unsigned)TD.getTypeAllocSize(Elts[0]->getType());
11432 SDValue One = DAG.getIntPtrConstant(EltSize);
11434 SDValue Cond = DAG.getSetCC(DL,
11435 getSetCCResultType(N0.getValueType()),
11437 AddToWorklist(Cond.getNode());
11438 SDValue CstOffset = DAG.getSelect(DL, Zero.getValueType(),
11440 AddToWorklist(CstOffset.getNode());
11441 CPIdx = DAG.getNode(ISD::ADD, DL, CPIdx.getValueType(), CPIdx,
11443 AddToWorklist(CPIdx.getNode());
11444 return DAG.getLoad(TV->getValueType(0), DL, DAG.getEntryNode(), CPIdx,
11445 MachinePointerInfo::getConstantPool(), false,
11446 false, false, Alignment);
11451 // Check to see if we can perform the "gzip trick", transforming
11452 // (select_cc setlt X, 0, A, 0) -> (and (sra X, (sub size(X), 1), A)
11453 if (N1C && N3C && N3C->isNullValue() && CC == ISD::SETLT &&
11454 (N1C->isNullValue() || // (a < 0) ? b : 0
11455 (N1C->getAPIntValue() == 1 && N0 == N2))) { // (a < 1) ? a : 0
11456 EVT XType = N0.getValueType();
11457 EVT AType = N2.getValueType();
11458 if (XType.bitsGE(AType)) {
11459 // and (sra X, size(X)-1, A) -> "and (srl X, C2), A" iff A is a
11460 // single-bit constant.
11461 if (N2C && ((N2C->getAPIntValue() & (N2C->getAPIntValue()-1)) == 0)) {
11462 unsigned ShCtV = N2C->getAPIntValue().logBase2();
11463 ShCtV = XType.getSizeInBits()-ShCtV-1;
11464 SDValue ShCt = DAG.getConstant(ShCtV,
11465 getShiftAmountTy(N0.getValueType()));
11466 SDValue Shift = DAG.getNode(ISD::SRL, SDLoc(N0),
11468 AddToWorklist(Shift.getNode());
11470 if (XType.bitsGT(AType)) {
11471 Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift);
11472 AddToWorklist(Shift.getNode());
11475 return DAG.getNode(ISD::AND, DL, AType, Shift, N2);
11478 SDValue Shift = DAG.getNode(ISD::SRA, SDLoc(N0),
11480 DAG.getConstant(XType.getSizeInBits()-1,
11481 getShiftAmountTy(N0.getValueType())));
11482 AddToWorklist(Shift.getNode());
11484 if (XType.bitsGT(AType)) {
11485 Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift);
11486 AddToWorklist(Shift.getNode());
11489 return DAG.getNode(ISD::AND, DL, AType, Shift, N2);
11493 // fold (select_cc seteq (and x, y), 0, 0, A) -> (and (shr (shl x)) A)
11494 // where y is has a single bit set.
11495 // A plaintext description would be, we can turn the SELECT_CC into an AND
11496 // when the condition can be materialized as an all-ones register. Any
11497 // single bit-test can be materialized as an all-ones register with
11498 // shift-left and shift-right-arith.
11499 if (CC == ISD::SETEQ && N0->getOpcode() == ISD::AND &&
11500 N0->getValueType(0) == VT &&
11501 N1C && N1C->isNullValue() &&
11502 N2C && N2C->isNullValue()) {
11503 SDValue AndLHS = N0->getOperand(0);
11504 ConstantSDNode *ConstAndRHS = dyn_cast<ConstantSDNode>(N0->getOperand(1));
11505 if (ConstAndRHS && ConstAndRHS->getAPIntValue().countPopulation() == 1) {
11506 // Shift the tested bit over the sign bit.
11507 APInt AndMask = ConstAndRHS->getAPIntValue();
11509 DAG.getConstant(AndMask.countLeadingZeros(),
11510 getShiftAmountTy(AndLHS.getValueType()));
11511 SDValue Shl = DAG.getNode(ISD::SHL, SDLoc(N0), VT, AndLHS, ShlAmt);
11513 // Now arithmetic right shift it all the way over, so the result is either
11514 // all-ones, or zero.
11516 DAG.getConstant(AndMask.getBitWidth()-1,
11517 getShiftAmountTy(Shl.getValueType()));
11518 SDValue Shr = DAG.getNode(ISD::SRA, SDLoc(N0), VT, Shl, ShrAmt);
11520 return DAG.getNode(ISD::AND, DL, VT, Shr, N3);
11524 // fold select C, 16, 0 -> shl C, 4
11525 if (N2C && N3C && N3C->isNullValue() && N2C->getAPIntValue().isPowerOf2() &&
11526 TLI.getBooleanContents(N0.getValueType()) ==
11527 TargetLowering::ZeroOrOneBooleanContent) {
11529 // If the caller doesn't want us to simplify this into a zext of a compare,
11531 if (NotExtCompare && N2C->getAPIntValue() == 1)
11534 // Get a SetCC of the condition
11535 // NOTE: Don't create a SETCC if it's not legal on this target.
11536 if (!LegalOperations ||
11537 TLI.isOperationLegal(ISD::SETCC,
11538 LegalTypes ? getSetCCResultType(N0.getValueType()) : MVT::i1)) {
11540 // cast from setcc result type to select result type
11542 SCC = DAG.getSetCC(DL, getSetCCResultType(N0.getValueType()),
11544 if (N2.getValueType().bitsLT(SCC.getValueType()))
11545 Temp = DAG.getZeroExtendInReg(SCC, SDLoc(N2),
11546 N2.getValueType());
11548 Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2),
11549 N2.getValueType(), SCC);
11551 SCC = DAG.getSetCC(SDLoc(N0), MVT::i1, N0, N1, CC);
11552 Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2),
11553 N2.getValueType(), SCC);
11556 AddToWorklist(SCC.getNode());
11557 AddToWorklist(Temp.getNode());
11559 if (N2C->getAPIntValue() == 1)
11562 // shl setcc result by log2 n2c
11563 return DAG.getNode(
11564 ISD::SHL, DL, N2.getValueType(), Temp,
11565 DAG.getConstant(N2C->getAPIntValue().logBase2(),
11566 getShiftAmountTy(Temp.getValueType())));
11570 // Check to see if this is the equivalent of setcc
11571 // FIXME: Turn all of these into setcc if setcc if setcc is legal
11572 // otherwise, go ahead with the folds.
11573 if (0 && N3C && N3C->isNullValue() && N2C && (N2C->getAPIntValue() == 1ULL)) {
11574 EVT XType = N0.getValueType();
11575 if (!LegalOperations ||
11576 TLI.isOperationLegal(ISD::SETCC, getSetCCResultType(XType))) {
11577 SDValue Res = DAG.getSetCC(DL, getSetCCResultType(XType), N0, N1, CC);
11578 if (Res.getValueType() != VT)
11579 Res = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, Res);
11583 // fold (seteq X, 0) -> (srl (ctlz X, log2(size(X))))
11584 if (N1C && N1C->isNullValue() && CC == ISD::SETEQ &&
11585 (!LegalOperations ||
11586 TLI.isOperationLegal(ISD::CTLZ, XType))) {
11587 SDValue Ctlz = DAG.getNode(ISD::CTLZ, SDLoc(N0), XType, N0);
11588 return DAG.getNode(ISD::SRL, DL, XType, Ctlz,
11589 DAG.getConstant(Log2_32(XType.getSizeInBits()),
11590 getShiftAmountTy(Ctlz.getValueType())));
11592 // fold (setgt X, 0) -> (srl (and (-X, ~X), size(X)-1))
11593 if (N1C && N1C->isNullValue() && CC == ISD::SETGT) {
11594 SDValue NegN0 = DAG.getNode(ISD::SUB, SDLoc(N0),
11595 XType, DAG.getConstant(0, XType), N0);
11596 SDValue NotN0 = DAG.getNOT(SDLoc(N0), N0, XType);
11597 return DAG.getNode(ISD::SRL, DL, XType,
11598 DAG.getNode(ISD::AND, DL, XType, NegN0, NotN0),
11599 DAG.getConstant(XType.getSizeInBits()-1,
11600 getShiftAmountTy(XType)));
11602 // fold (setgt X, -1) -> (xor (srl (X, size(X)-1), 1))
11603 if (N1C && N1C->isAllOnesValue() && CC == ISD::SETGT) {
11604 SDValue Sign = DAG.getNode(ISD::SRL, SDLoc(N0), XType, N0,
11605 DAG.getConstant(XType.getSizeInBits()-1,
11606 getShiftAmountTy(N0.getValueType())));
11607 return DAG.getNode(ISD::XOR, DL, XType, Sign, DAG.getConstant(1, XType));
11611 // Check to see if this is an integer abs.
11612 // select_cc setg[te] X, 0, X, -X ->
11613 // select_cc setgt X, -1, X, -X ->
11614 // select_cc setl[te] X, 0, -X, X ->
11615 // select_cc setlt X, 1, -X, X ->
11616 // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
11618 ConstantSDNode *SubC = nullptr;
11619 if (((N1C->isNullValue() && (CC == ISD::SETGT || CC == ISD::SETGE)) ||
11620 (N1C->isAllOnesValue() && CC == ISD::SETGT)) &&
11621 N0 == N2 && N3.getOpcode() == ISD::SUB && N0 == N3.getOperand(1))
11622 SubC = dyn_cast<ConstantSDNode>(N3.getOperand(0));
11623 else if (((N1C->isNullValue() && (CC == ISD::SETLT || CC == ISD::SETLE)) ||
11624 (N1C->isOne() && CC == ISD::SETLT)) &&
11625 N0 == N3 && N2.getOpcode() == ISD::SUB && N0 == N2.getOperand(1))
11626 SubC = dyn_cast<ConstantSDNode>(N2.getOperand(0));
11628 EVT XType = N0.getValueType();
11629 if (SubC && SubC->isNullValue() && XType.isInteger()) {
11630 SDValue Shift = DAG.getNode(ISD::SRA, SDLoc(N0), XType,
11632 DAG.getConstant(XType.getSizeInBits()-1,
11633 getShiftAmountTy(N0.getValueType())));
11634 SDValue Add = DAG.getNode(ISD::ADD, SDLoc(N0),
11636 AddToWorklist(Shift.getNode());
11637 AddToWorklist(Add.getNode());
11638 return DAG.getNode(ISD::XOR, DL, XType, Add, Shift);
11645 /// This is a stub for TargetLowering::SimplifySetCC.
11646 SDValue DAGCombiner::SimplifySetCC(EVT VT, SDValue N0,
11647 SDValue N1, ISD::CondCode Cond,
11648 SDLoc DL, bool foldBooleans) {
11649 TargetLowering::DAGCombinerInfo
11650 DagCombineInfo(DAG, Level, false, this);
11651 return TLI.SimplifySetCC(VT, N0, N1, Cond, foldBooleans, DagCombineInfo, DL);
11654 /// Given an ISD::SDIV node expressing a divide by constant, return
11655 /// a DAG expression to select that will generate the same value by multiplying
11656 /// by a magic number. See:
11657 /// <http://the.wall.riscom.net/books/proc/ppc/cwg/code2.html>
11658 SDValue DAGCombiner::BuildSDIV(SDNode *N) {
11659 ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1));
11663 // Avoid division by zero.
11664 if (!C->getAPIntValue())
11667 std::vector<SDNode*> Built;
11669 TLI.BuildSDIV(N, C->getAPIntValue(), DAG, LegalOperations, &Built);
11671 for (SDNode *N : Built)
11676 /// Given an ISD::SDIV node expressing a divide by constant power of 2, return a
11677 /// DAG expression that will generate the same value by right shifting.
11678 SDValue DAGCombiner::BuildSDIVPow2(SDNode *N) {
11679 ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1));
11683 // Avoid division by zero.
11684 if (!C->getAPIntValue())
11687 std::vector<SDNode *> Built;
11688 SDValue S = TLI.BuildSDIVPow2(N, C->getAPIntValue(), DAG, &Built);
11690 for (SDNode *N : Built)
11695 /// Given an ISD::UDIV node expressing a divide by constant, return a DAG
11696 /// expression that will generate the same value by multiplying by a magic
11698 /// <http://the.wall.riscom.net/books/proc/ppc/cwg/code2.html>
11699 SDValue DAGCombiner::BuildUDIV(SDNode *N) {
11700 ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1));
11704 // Avoid division by zero.
11705 if (!C->getAPIntValue())
11708 std::vector<SDNode*> Built;
11710 TLI.BuildUDIV(N, C->getAPIntValue(), DAG, LegalOperations, &Built);
11712 for (SDNode *N : Built)
11717 /// Return true if base is a frame index, which is known not to alias with
11718 /// anything but itself. Provides base object and offset as results.
11719 static bool FindBaseOffset(SDValue Ptr, SDValue &Base, int64_t &Offset,
11720 const GlobalValue *&GV, const void *&CV) {
11721 // Assume it is a primitive operation.
11722 Base = Ptr; Offset = 0; GV = nullptr; CV = nullptr;
11724 // If it's an adding a simple constant then integrate the offset.
11725 if (Base.getOpcode() == ISD::ADD) {
11726 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Base.getOperand(1))) {
11727 Base = Base.getOperand(0);
11728 Offset += C->getZExtValue();
11732 // Return the underlying GlobalValue, and update the Offset. Return false
11733 // for GlobalAddressSDNode since the same GlobalAddress may be represented
11734 // by multiple nodes with different offsets.
11735 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Base)) {
11736 GV = G->getGlobal();
11737 Offset += G->getOffset();
11741 // Return the underlying Constant value, and update the Offset. Return false
11742 // for ConstantSDNodes since the same constant pool entry may be represented
11743 // by multiple nodes with different offsets.
11744 if (ConstantPoolSDNode *C = dyn_cast<ConstantPoolSDNode>(Base)) {
11745 CV = C->isMachineConstantPoolEntry() ? (const void *)C->getMachineCPVal()
11746 : (const void *)C->getConstVal();
11747 Offset += C->getOffset();
11750 // If it's any of the following then it can't alias with anything but itself.
11751 return isa<FrameIndexSDNode>(Base);
11754 /// Return true if there is any possibility that the two addresses overlap.
11755 bool DAGCombiner::isAlias(LSBaseSDNode *Op0, LSBaseSDNode *Op1) const {
11756 // If they are the same then they must be aliases.
11757 if (Op0->getBasePtr() == Op1->getBasePtr()) return true;
11759 // If they are both volatile then they cannot be reordered.
11760 if (Op0->isVolatile() && Op1->isVolatile()) return true;
11762 // Gather base node and offset information.
11763 SDValue Base1, Base2;
11764 int64_t Offset1, Offset2;
11765 const GlobalValue *GV1, *GV2;
11766 const void *CV1, *CV2;
11767 bool isFrameIndex1 = FindBaseOffset(Op0->getBasePtr(),
11768 Base1, Offset1, GV1, CV1);
11769 bool isFrameIndex2 = FindBaseOffset(Op1->getBasePtr(),
11770 Base2, Offset2, GV2, CV2);
11772 // If they have a same base address then check to see if they overlap.
11773 if (Base1 == Base2 || (GV1 && (GV1 == GV2)) || (CV1 && (CV1 == CV2)))
11774 return !((Offset1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= Offset2 ||
11775 (Offset2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= Offset1);
11777 // It is possible for different frame indices to alias each other, mostly
11778 // when tail call optimization reuses return address slots for arguments.
11779 // To catch this case, look up the actual index of frame indices to compute
11780 // the real alias relationship.
11781 if (isFrameIndex1 && isFrameIndex2) {
11782 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
11783 Offset1 += MFI->getObjectOffset(cast<FrameIndexSDNode>(Base1)->getIndex());
11784 Offset2 += MFI->getObjectOffset(cast<FrameIndexSDNode>(Base2)->getIndex());
11785 return !((Offset1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= Offset2 ||
11786 (Offset2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= Offset1);
11789 // Otherwise, if we know what the bases are, and they aren't identical, then
11790 // we know they cannot alias.
11791 if ((isFrameIndex1 || CV1 || GV1) && (isFrameIndex2 || CV2 || GV2))
11794 // If we know required SrcValue1 and SrcValue2 have relatively large alignment
11795 // compared to the size and offset of the access, we may be able to prove they
11796 // do not alias. This check is conservative for now to catch cases created by
11797 // splitting vector types.
11798 if ((Op0->getOriginalAlignment() == Op1->getOriginalAlignment()) &&
11799 (Op0->getSrcValueOffset() != Op1->getSrcValueOffset()) &&
11800 (Op0->getMemoryVT().getSizeInBits() >> 3 ==
11801 Op1->getMemoryVT().getSizeInBits() >> 3) &&
11802 (Op0->getOriginalAlignment() > Op0->getMemoryVT().getSizeInBits()) >> 3) {
11803 int64_t OffAlign1 = Op0->getSrcValueOffset() % Op0->getOriginalAlignment();
11804 int64_t OffAlign2 = Op1->getSrcValueOffset() % Op1->getOriginalAlignment();
11806 // There is no overlap between these relatively aligned accesses of similar
11807 // size, return no alias.
11808 if ((OffAlign1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= OffAlign2 ||
11809 (OffAlign2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= OffAlign1)
11813 bool UseAA = CombinerGlobalAA.getNumOccurrences() > 0 ? CombinerGlobalAA :
11814 TLI.getTargetMachine().getSubtarget<TargetSubtargetInfo>().useAA();
11816 if (CombinerAAOnlyFunc.getNumOccurrences() &&
11817 CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
11821 Op0->getMemOperand()->getValue() && Op1->getMemOperand()->getValue()) {
11822 // Use alias analysis information.
11823 int64_t MinOffset = std::min(Op0->getSrcValueOffset(),
11824 Op1->getSrcValueOffset());
11825 int64_t Overlap1 = (Op0->getMemoryVT().getSizeInBits() >> 3) +
11826 Op0->getSrcValueOffset() - MinOffset;
11827 int64_t Overlap2 = (Op1->getMemoryVT().getSizeInBits() >> 3) +
11828 Op1->getSrcValueOffset() - MinOffset;
11829 AliasAnalysis::AliasResult AAResult =
11830 AA.alias(AliasAnalysis::Location(Op0->getMemOperand()->getValue(),
11832 UseTBAA ? Op0->getAAInfo() : AAMDNodes()),
11833 AliasAnalysis::Location(Op1->getMemOperand()->getValue(),
11835 UseTBAA ? Op1->getAAInfo() : AAMDNodes()));
11836 if (AAResult == AliasAnalysis::NoAlias)
11840 // Otherwise we have to assume they alias.
11844 /// Walk up chain skipping non-aliasing memory nodes,
11845 /// looking for aliasing nodes and adding them to the Aliases vector.
11846 void DAGCombiner::GatherAllAliases(SDNode *N, SDValue OriginalChain,
11847 SmallVectorImpl<SDValue> &Aliases) {
11848 SmallVector<SDValue, 8> Chains; // List of chains to visit.
11849 SmallPtrSet<SDNode *, 16> Visited; // Visited node set.
11851 // Get alias information for node.
11852 bool IsLoad = isa<LoadSDNode>(N) && !cast<LSBaseSDNode>(N)->isVolatile();
11855 Chains.push_back(OriginalChain);
11856 unsigned Depth = 0;
11858 // Look at each chain and determine if it is an alias. If so, add it to the
11859 // aliases list. If not, then continue up the chain looking for the next
11861 while (!Chains.empty()) {
11862 SDValue Chain = Chains.back();
11865 // For TokenFactor nodes, look at each operand and only continue up the
11866 // chain until we find two aliases. If we've seen two aliases, assume we'll
11867 // find more and revert to original chain since the xform is unlikely to be
11870 // FIXME: The depth check could be made to return the last non-aliasing
11871 // chain we found before we hit a tokenfactor rather than the original
11873 if (Depth > 6 || Aliases.size() == 2) {
11875 Aliases.push_back(OriginalChain);
11879 // Don't bother if we've been before.
11880 if (!Visited.insert(Chain.getNode()))
11883 switch (Chain.getOpcode()) {
11884 case ISD::EntryToken:
11885 // Entry token is ideal chain operand, but handled in FindBetterChain.
11890 // Get alias information for Chain.
11891 bool IsOpLoad = isa<LoadSDNode>(Chain.getNode()) &&
11892 !cast<LSBaseSDNode>(Chain.getNode())->isVolatile();
11894 // If chain is alias then stop here.
11895 if (!(IsLoad && IsOpLoad) &&
11896 isAlias(cast<LSBaseSDNode>(N), cast<LSBaseSDNode>(Chain.getNode()))) {
11897 Aliases.push_back(Chain);
11899 // Look further up the chain.
11900 Chains.push_back(Chain.getOperand(0));
11906 case ISD::TokenFactor:
11907 // We have to check each of the operands of the token factor for "small"
11908 // token factors, so we queue them up. Adding the operands to the queue
11909 // (stack) in reverse order maintains the original order and increases the
11910 // likelihood that getNode will find a matching token factor (CSE.)
11911 if (Chain.getNumOperands() > 16) {
11912 Aliases.push_back(Chain);
11915 for (unsigned n = Chain.getNumOperands(); n;)
11916 Chains.push_back(Chain.getOperand(--n));
11921 // For all other instructions we will just have to take what we can get.
11922 Aliases.push_back(Chain);
11927 // We need to be careful here to also search for aliases through the
11928 // value operand of a store, etc. Consider the following situation:
11930 // L1 = load Token1, %52
11931 // S1 = store Token1, L1, %51
11932 // L2 = load Token1, %52+8
11933 // S2 = store Token1, L2, %51+8
11934 // Token2 = Token(S1, S2)
11935 // L3 = load Token2, %53
11936 // S3 = store Token2, L3, %52
11937 // L4 = load Token2, %53+8
11938 // S4 = store Token2, L4, %52+8
11939 // If we search for aliases of S3 (which loads address %52), and we look
11940 // only through the chain, then we'll miss the trivial dependence on L1
11941 // (which also loads from %52). We then might change all loads and
11942 // stores to use Token1 as their chain operand, which could result in
11943 // copying %53 into %52 before copying %52 into %51 (which should
11946 // The problem is, however, that searching for such data dependencies
11947 // can become expensive, and the cost is not directly related to the
11948 // chain depth. Instead, we'll rule out such configurations here by
11949 // insisting that we've visited all chain users (except for users
11950 // of the original chain, which is not necessary). When doing this,
11951 // we need to look through nodes we don't care about (otherwise, things
11952 // like register copies will interfere with trivial cases).
11954 SmallVector<const SDNode *, 16> Worklist;
11955 for (const SDNode *N : Visited)
11956 if (N != OriginalChain.getNode())
11957 Worklist.push_back(N);
11959 while (!Worklist.empty()) {
11960 const SDNode *M = Worklist.pop_back_val();
11962 // We have already visited M, and want to make sure we've visited any uses
11963 // of M that we care about. For uses that we've not visisted, and don't
11964 // care about, queue them to the worklist.
11966 for (SDNode::use_iterator UI = M->use_begin(),
11967 UIE = M->use_end(); UI != UIE; ++UI)
11968 if (UI.getUse().getValueType() == MVT::Other && Visited.insert(*UI)) {
11969 if (isa<MemIntrinsicSDNode>(*UI) || isa<MemSDNode>(*UI)) {
11970 // We've not visited this use, and we care about it (it could have an
11971 // ordering dependency with the original node).
11973 Aliases.push_back(OriginalChain);
11977 // We've not visited this use, but we don't care about it. Mark it as
11978 // visited and enqueue it to the worklist.
11979 Worklist.push_back(*UI);
11984 /// Walk up chain skipping non-aliasing memory nodes, looking for a better chain
11985 /// (aliasing node.)
11986 SDValue DAGCombiner::FindBetterChain(SDNode *N, SDValue OldChain) {
11987 SmallVector<SDValue, 8> Aliases; // Ops for replacing token factor.
11989 // Accumulate all the aliases to this node.
11990 GatherAllAliases(N, OldChain, Aliases);
11992 // If no operands then chain to entry token.
11993 if (Aliases.size() == 0)
11994 return DAG.getEntryNode();
11996 // If a single operand then chain to it. We don't need to revisit it.
11997 if (Aliases.size() == 1)
12000 // Construct a custom tailored token factor.
12001 return DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other, Aliases);
12004 /// This is the entry point for the file.
12005 void SelectionDAG::Combine(CombineLevel Level, AliasAnalysis &AA,
12006 CodeGenOpt::Level OptLevel) {
12007 /// This is the main entry point to this class.
12008 DAGCombiner(*this, AA, OptLevel).Run(Level);