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/SmallBitVector.h"
21 #include "llvm/ADT/SmallPtrSet.h"
22 #include "llvm/ADT/SetVector.h"
23 #include "llvm/ADT/Statistic.h"
24 #include "llvm/Analysis/AliasAnalysis.h"
25 #include "llvm/CodeGen/MachineFrameInfo.h"
26 #include "llvm/CodeGen/MachineFunction.h"
27 #include "llvm/IR/DataLayout.h"
28 #include "llvm/IR/DerivedTypes.h"
29 #include "llvm/IR/Function.h"
30 #include "llvm/IR/LLVMContext.h"
31 #include "llvm/Support/CommandLine.h"
32 #include "llvm/Support/Debug.h"
33 #include "llvm/Support/ErrorHandling.h"
34 #include "llvm/Support/MathExtras.h"
35 #include "llvm/Support/raw_ostream.h"
36 #include "llvm/Target/TargetLowering.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 visitFSQRT(SDNode *N);
280 SDValue visitFCOPYSIGN(SDNode *N);
281 SDValue visitSINT_TO_FP(SDNode *N);
282 SDValue visitUINT_TO_FP(SDNode *N);
283 SDValue visitFP_TO_SINT(SDNode *N);
284 SDValue visitFP_TO_UINT(SDNode *N);
285 SDValue visitFP_ROUND(SDNode *N);
286 SDValue visitFP_ROUND_INREG(SDNode *N);
287 SDValue visitFP_EXTEND(SDNode *N);
288 SDValue visitFNEG(SDNode *N);
289 SDValue visitFABS(SDNode *N);
290 SDValue visitFCEIL(SDNode *N);
291 SDValue visitFTRUNC(SDNode *N);
292 SDValue visitFFLOOR(SDNode *N);
293 SDValue visitFMINNUM(SDNode *N);
294 SDValue visitFMAXNUM(SDNode *N);
295 SDValue visitBRCOND(SDNode *N);
296 SDValue visitBR_CC(SDNode *N);
297 SDValue visitLOAD(SDNode *N);
298 SDValue visitSTORE(SDNode *N);
299 SDValue visitINSERT_VECTOR_ELT(SDNode *N);
300 SDValue visitEXTRACT_VECTOR_ELT(SDNode *N);
301 SDValue visitBUILD_VECTOR(SDNode *N);
302 SDValue visitCONCAT_VECTORS(SDNode *N);
303 SDValue visitEXTRACT_SUBVECTOR(SDNode *N);
304 SDValue visitVECTOR_SHUFFLE(SDNode *N);
305 SDValue visitINSERT_SUBVECTOR(SDNode *N);
306 SDValue visitMLOAD(SDNode *N);
307 SDValue visitMSTORE(SDNode *N);
309 SDValue XformToShuffleWithZero(SDNode *N);
310 SDValue ReassociateOps(unsigned Opc, SDLoc DL, SDValue LHS, SDValue RHS);
312 SDValue visitShiftByConstant(SDNode *N, ConstantSDNode *Amt);
314 bool SimplifySelectOps(SDNode *SELECT, SDValue LHS, SDValue RHS);
315 SDValue SimplifyBinOpWithSameOpcodeHands(SDNode *N);
316 SDValue SimplifySelect(SDLoc DL, SDValue N0, SDValue N1, SDValue N2);
317 SDValue SimplifySelectCC(SDLoc DL, SDValue N0, SDValue N1, SDValue N2,
318 SDValue N3, ISD::CondCode CC,
319 bool NotExtCompare = false);
320 SDValue SimplifySetCC(EVT VT, SDValue N0, SDValue N1, ISD::CondCode Cond,
321 SDLoc DL, bool foldBooleans = true);
323 bool isSetCCEquivalent(SDValue N, SDValue &LHS, SDValue &RHS,
325 bool isOneUseSetCC(SDValue N) const;
327 SDValue SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp,
329 SDValue CombineConsecutiveLoads(SDNode *N, EVT VT);
330 SDValue ConstantFoldBITCASTofBUILD_VECTOR(SDNode *, EVT);
331 SDValue BuildSDIV(SDNode *N);
332 SDValue BuildSDIVPow2(SDNode *N);
333 SDValue BuildUDIV(SDNode *N);
334 SDValue BuildReciprocalEstimate(SDValue Op);
335 SDValue BuildRsqrtEstimate(SDValue Op);
336 SDValue BuildRsqrtNROneConst(SDValue Op, SDValue Est, unsigned Iterations);
337 SDValue BuildRsqrtNRTwoConst(SDValue Op, SDValue Est, unsigned Iterations);
338 SDValue MatchBSwapHWordLow(SDNode *N, SDValue N0, SDValue N1,
339 bool DemandHighBits = true);
340 SDValue MatchBSwapHWord(SDNode *N, SDValue N0, SDValue N1);
341 SDNode *MatchRotatePosNeg(SDValue Shifted, SDValue Pos, SDValue Neg,
342 SDValue InnerPos, SDValue InnerNeg,
343 unsigned PosOpcode, unsigned NegOpcode,
345 SDNode *MatchRotate(SDValue LHS, SDValue RHS, SDLoc DL);
346 SDValue ReduceLoadWidth(SDNode *N);
347 SDValue ReduceLoadOpStoreWidth(SDNode *N);
348 SDValue TransformFPLoadStorePair(SDNode *N);
349 SDValue reduceBuildVecExtToExtBuildVec(SDNode *N);
350 SDValue reduceBuildVecConvertToConvertBuildVec(SDNode *N);
352 SDValue GetDemandedBits(SDValue V, const APInt &Mask);
354 /// Walk up chain skipping non-aliasing memory nodes,
355 /// looking for aliasing nodes and adding them to the Aliases vector.
356 void GatherAllAliases(SDNode *N, SDValue OriginalChain,
357 SmallVectorImpl<SDValue> &Aliases);
359 /// Return true if there is any possibility that the two addresses overlap.
360 bool isAlias(LSBaseSDNode *Op0, LSBaseSDNode *Op1) const;
362 /// Walk up chain skipping non-aliasing memory nodes, looking for a better
363 /// chain (aliasing node.)
364 SDValue FindBetterChain(SDNode *N, SDValue Chain);
366 /// Merge consecutive store operations into a wide store.
367 /// This optimization uses wide integers or vectors when possible.
368 /// \return True if some memory operations were changed.
369 bool MergeConsecutiveStores(StoreSDNode *N);
371 /// \brief Try to transform a truncation where C is a constant:
372 /// (trunc (and X, C)) -> (and (trunc X), (trunc C))
374 /// \p N needs to be a truncation and its first operand an AND. Other
375 /// requirements are checked by the function (e.g. that trunc is
376 /// single-use) and if missed an empty SDValue is returned.
377 SDValue distributeTruncateThroughAnd(SDNode *N);
380 DAGCombiner(SelectionDAG &D, AliasAnalysis &A, CodeGenOpt::Level OL)
381 : DAG(D), TLI(D.getTargetLoweringInfo()), Level(BeforeLegalizeTypes),
382 OptLevel(OL), LegalOperations(false), LegalTypes(false), AA(A) {
383 AttributeSet FnAttrs =
384 DAG.getMachineFunction().getFunction()->getAttributes();
386 FnAttrs.hasAttribute(AttributeSet::FunctionIndex,
387 Attribute::OptimizeForSize) ||
388 FnAttrs.hasAttribute(AttributeSet::FunctionIndex, Attribute::MinSize);
391 /// Runs the dag combiner on all nodes in the work list
392 void Run(CombineLevel AtLevel);
394 SelectionDAG &getDAG() const { return DAG; }
396 /// Returns a type large enough to hold any valid shift amount - before type
397 /// legalization these can be huge.
398 EVT getShiftAmountTy(EVT LHSTy) {
399 assert(LHSTy.isInteger() && "Shift amount is not an integer type!");
400 if (LHSTy.isVector())
402 return LegalTypes ? TLI.getScalarShiftAmountTy(LHSTy)
403 : TLI.getPointerTy();
406 /// This method returns true if we are running before type legalization or
407 /// if the specified VT is legal.
408 bool isTypeLegal(const EVT &VT) {
409 if (!LegalTypes) return true;
410 return TLI.isTypeLegal(VT);
413 /// Convenience wrapper around TargetLowering::getSetCCResultType
414 EVT getSetCCResultType(EVT VT) const {
415 return TLI.getSetCCResultType(*DAG.getContext(), VT);
422 /// This class is a DAGUpdateListener that removes any deleted
423 /// nodes from the worklist.
424 class WorklistRemover : public SelectionDAG::DAGUpdateListener {
427 explicit WorklistRemover(DAGCombiner &dc)
428 : SelectionDAG::DAGUpdateListener(dc.getDAG()), DC(dc) {}
430 void NodeDeleted(SDNode *N, SDNode *E) override {
431 DC.removeFromWorklist(N);
436 //===----------------------------------------------------------------------===//
437 // TargetLowering::DAGCombinerInfo implementation
438 //===----------------------------------------------------------------------===//
440 void TargetLowering::DAGCombinerInfo::AddToWorklist(SDNode *N) {
441 ((DAGCombiner*)DC)->AddToWorklist(N);
444 void TargetLowering::DAGCombinerInfo::RemoveFromWorklist(SDNode *N) {
445 ((DAGCombiner*)DC)->removeFromWorklist(N);
448 SDValue TargetLowering::DAGCombinerInfo::
449 CombineTo(SDNode *N, const std::vector<SDValue> &To, bool AddTo) {
450 return ((DAGCombiner*)DC)->CombineTo(N, &To[0], To.size(), AddTo);
453 SDValue TargetLowering::DAGCombinerInfo::
454 CombineTo(SDNode *N, SDValue Res, bool AddTo) {
455 return ((DAGCombiner*)DC)->CombineTo(N, Res, AddTo);
459 SDValue TargetLowering::DAGCombinerInfo::
460 CombineTo(SDNode *N, SDValue Res0, SDValue Res1, bool AddTo) {
461 return ((DAGCombiner*)DC)->CombineTo(N, Res0, Res1, AddTo);
464 void TargetLowering::DAGCombinerInfo::
465 CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) {
466 return ((DAGCombiner*)DC)->CommitTargetLoweringOpt(TLO);
469 //===----------------------------------------------------------------------===//
471 //===----------------------------------------------------------------------===//
473 void DAGCombiner::deleteAndRecombine(SDNode *N) {
474 removeFromWorklist(N);
476 // If the operands of this node are only used by the node, they will now be
477 // dead. Make sure to re-visit them and recursively delete dead nodes.
478 for (const SDValue &Op : N->ops())
479 // For an operand generating multiple values, one of the values may
480 // become dead allowing further simplification (e.g. split index
481 // arithmetic from an indexed load).
482 if (Op->hasOneUse() || Op->getNumValues() > 1)
483 AddToWorklist(Op.getNode());
488 /// Return 1 if we can compute the negated form of the specified expression for
489 /// the same cost as the expression itself, or 2 if we can compute the negated
490 /// form more cheaply than the expression itself.
491 static char isNegatibleForFree(SDValue Op, bool LegalOperations,
492 const TargetLowering &TLI,
493 const TargetOptions *Options,
494 unsigned Depth = 0) {
495 // fneg is removable even if it has multiple uses.
496 if (Op.getOpcode() == ISD::FNEG) return 2;
498 // Don't allow anything with multiple uses.
499 if (!Op.hasOneUse()) return 0;
501 // Don't recurse exponentially.
502 if (Depth > 6) return 0;
504 switch (Op.getOpcode()) {
505 default: return false;
506 case ISD::ConstantFP:
507 // Don't invert constant FP values after legalize. The negated constant
508 // isn't necessarily legal.
509 return LegalOperations ? 0 : 1;
511 // FIXME: determine better conditions for this xform.
512 if (!Options->UnsafeFPMath) return 0;
514 // After operation legalization, it might not be legal to create new FSUBs.
515 if (LegalOperations &&
516 !TLI.isOperationLegalOrCustom(ISD::FSUB, Op.getValueType()))
519 // fold (fneg (fadd A, B)) -> (fsub (fneg A), B)
520 if (char V = isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI,
523 // fold (fneg (fadd A, B)) -> (fsub (fneg B), A)
524 return isNegatibleForFree(Op.getOperand(1), LegalOperations, TLI, Options,
527 // We can't turn -(A-B) into B-A when we honor signed zeros.
528 if (!Options->UnsafeFPMath) return 0;
530 // fold (fneg (fsub A, B)) -> (fsub B, A)
535 if (Options->HonorSignDependentRoundingFPMath()) return 0;
537 // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y) or (fmul X, (fneg Y))
538 if (char V = isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI,
542 return isNegatibleForFree(Op.getOperand(1), LegalOperations, TLI, Options,
548 return isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI, Options,
553 /// If isNegatibleForFree returns true, return the newly negated expression.
554 static SDValue GetNegatedExpression(SDValue Op, SelectionDAG &DAG,
555 bool LegalOperations, unsigned Depth = 0) {
556 const TargetOptions &Options = DAG.getTarget().Options;
557 // fneg is removable even if it has multiple uses.
558 if (Op.getOpcode() == ISD::FNEG) return Op.getOperand(0);
560 // Don't allow anything with multiple uses.
561 assert(Op.hasOneUse() && "Unknown reuse!");
563 assert(Depth <= 6 && "GetNegatedExpression doesn't match isNegatibleForFree");
564 switch (Op.getOpcode()) {
565 default: llvm_unreachable("Unknown code");
566 case ISD::ConstantFP: {
567 APFloat V = cast<ConstantFPSDNode>(Op)->getValueAPF();
569 return DAG.getConstantFP(V, Op.getValueType());
572 // FIXME: determine better conditions for this xform.
573 assert(Options.UnsafeFPMath);
575 // fold (fneg (fadd A, B)) -> (fsub (fneg A), B)
576 if (isNegatibleForFree(Op.getOperand(0), LegalOperations,
577 DAG.getTargetLoweringInfo(), &Options, Depth+1))
578 return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
579 GetNegatedExpression(Op.getOperand(0), DAG,
580 LegalOperations, Depth+1),
582 // fold (fneg (fadd A, B)) -> (fsub (fneg B), A)
583 return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
584 GetNegatedExpression(Op.getOperand(1), DAG,
585 LegalOperations, Depth+1),
588 // We can't turn -(A-B) into B-A when we honor signed zeros.
589 assert(Options.UnsafeFPMath);
591 // fold (fneg (fsub 0, B)) -> B
592 if (ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(Op.getOperand(0)))
593 if (N0CFP->getValueAPF().isZero())
594 return Op.getOperand(1);
596 // fold (fneg (fsub A, B)) -> (fsub B, A)
597 return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
598 Op.getOperand(1), Op.getOperand(0));
602 assert(!Options.HonorSignDependentRoundingFPMath());
604 // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y)
605 if (isNegatibleForFree(Op.getOperand(0), LegalOperations,
606 DAG.getTargetLoweringInfo(), &Options, Depth+1))
607 return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
608 GetNegatedExpression(Op.getOperand(0), DAG,
609 LegalOperations, Depth+1),
612 // fold (fneg (fmul X, Y)) -> (fmul X, (fneg Y))
613 return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
615 GetNegatedExpression(Op.getOperand(1), DAG,
616 LegalOperations, Depth+1));
620 return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
621 GetNegatedExpression(Op.getOperand(0), DAG,
622 LegalOperations, Depth+1));
624 return DAG.getNode(ISD::FP_ROUND, SDLoc(Op), Op.getValueType(),
625 GetNegatedExpression(Op.getOperand(0), DAG,
626 LegalOperations, Depth+1),
631 // Return true if this node is a setcc, or is a select_cc
632 // that selects between the target values used for true and false, making it
633 // equivalent to a setcc. Also, set the incoming LHS, RHS, and CC references to
634 // the appropriate nodes based on the type of node we are checking. This
635 // simplifies life a bit for the callers.
636 bool DAGCombiner::isSetCCEquivalent(SDValue N, SDValue &LHS, SDValue &RHS,
638 if (N.getOpcode() == ISD::SETCC) {
639 LHS = N.getOperand(0);
640 RHS = N.getOperand(1);
641 CC = N.getOperand(2);
645 if (N.getOpcode() != ISD::SELECT_CC ||
646 !TLI.isConstTrueVal(N.getOperand(2).getNode()) ||
647 !TLI.isConstFalseVal(N.getOperand(3).getNode()))
650 if (TLI.getBooleanContents(N.getValueType()) ==
651 TargetLowering::UndefinedBooleanContent)
654 LHS = N.getOperand(0);
655 RHS = N.getOperand(1);
656 CC = N.getOperand(4);
660 /// Return true if this is a SetCC-equivalent operation with only one use.
661 /// If this is true, it allows the users to invert the operation for free when
662 /// it is profitable to do so.
663 bool DAGCombiner::isOneUseSetCC(SDValue N) const {
665 if (isSetCCEquivalent(N, N0, N1, N2) && N.getNode()->hasOneUse())
670 /// Returns true if N is a BUILD_VECTOR node whose
671 /// elements are all the same constant or undefined.
672 static bool isConstantSplatVector(SDNode *N, APInt& SplatValue) {
673 BuildVectorSDNode *C = dyn_cast<BuildVectorSDNode>(N);
678 unsigned SplatBitSize;
680 EVT EltVT = N->getValueType(0).getVectorElementType();
681 return (C->isConstantSplat(SplatValue, SplatUndef, SplatBitSize,
683 EltVT.getSizeInBits() >= SplatBitSize);
686 // \brief Returns the SDNode if it is a constant BuildVector or constant.
687 static SDNode *isConstantBuildVectorOrConstantInt(SDValue N) {
688 if (isa<ConstantSDNode>(N))
690 BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N);
691 if (BV && BV->isConstant())
696 // \brief Returns the SDNode if it is a constant splat BuildVector or constant
698 static ConstantSDNode *isConstOrConstSplat(SDValue N) {
699 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N))
702 if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) {
703 BitVector UndefElements;
704 ConstantSDNode *CN = BV->getConstantSplatNode(&UndefElements);
706 // BuildVectors can truncate their operands. Ignore that case here.
707 // FIXME: We blindly ignore splats which include undef which is overly
709 if (CN && UndefElements.none() &&
710 CN->getValueType(0) == N.getValueType().getScalarType())
717 // \brief Returns the SDNode if it is a constant splat BuildVector or constant
719 static ConstantFPSDNode *isConstOrConstSplatFP(SDValue N) {
720 if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(N))
723 if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) {
724 BitVector UndefElements;
725 ConstantFPSDNode *CN = BV->getConstantFPSplatNode(&UndefElements);
727 if (CN && UndefElements.none())
734 SDValue DAGCombiner::ReassociateOps(unsigned Opc, SDLoc DL,
735 SDValue N0, SDValue N1) {
736 EVT VT = N0.getValueType();
737 if (N0.getOpcode() == Opc) {
738 if (SDNode *L = isConstantBuildVectorOrConstantInt(N0.getOperand(1))) {
739 if (SDNode *R = isConstantBuildVectorOrConstantInt(N1)) {
740 // reassoc. (op (op x, c1), c2) -> (op x, (op c1, c2))
741 SDValue OpNode = DAG.FoldConstantArithmetic(Opc, VT, L, R);
742 if (!OpNode.getNode())
744 return DAG.getNode(Opc, DL, VT, N0.getOperand(0), OpNode);
746 if (N0.hasOneUse()) {
747 // reassoc. (op (op x, c1), y) -> (op (op x, y), c1) iff x+c1 has one
749 SDValue OpNode = DAG.getNode(Opc, SDLoc(N0), VT, N0.getOperand(0), N1);
750 if (!OpNode.getNode())
752 AddToWorklist(OpNode.getNode());
753 return DAG.getNode(Opc, DL, VT, OpNode, N0.getOperand(1));
758 if (N1.getOpcode() == Opc) {
759 if (SDNode *R = isConstantBuildVectorOrConstantInt(N1.getOperand(1))) {
760 if (SDNode *L = isConstantBuildVectorOrConstantInt(N0)) {
761 // reassoc. (op c2, (op x, c1)) -> (op x, (op c1, c2))
762 SDValue OpNode = DAG.FoldConstantArithmetic(Opc, VT, R, L);
763 if (!OpNode.getNode())
765 return DAG.getNode(Opc, DL, VT, N1.getOperand(0), OpNode);
767 if (N1.hasOneUse()) {
768 // reassoc. (op y, (op x, c1)) -> (op (op x, y), c1) iff x+c1 has one
770 SDValue OpNode = DAG.getNode(Opc, SDLoc(N0), VT, N1.getOperand(0), N0);
771 if (!OpNode.getNode())
773 AddToWorklist(OpNode.getNode());
774 return DAG.getNode(Opc, DL, VT, OpNode, N1.getOperand(1));
782 SDValue DAGCombiner::CombineTo(SDNode *N, const SDValue *To, unsigned NumTo,
784 assert(N->getNumValues() == NumTo && "Broken CombineTo call!");
786 DEBUG(dbgs() << "\nReplacing.1 ";
788 dbgs() << "\nWith: ";
789 To[0].getNode()->dump(&DAG);
790 dbgs() << " and " << NumTo-1 << " other values\n";
791 for (unsigned i = 0, e = NumTo; i != e; ++i)
792 assert((!To[i].getNode() ||
793 N->getValueType(i) == To[i].getValueType()) &&
794 "Cannot combine value to value of different type!"));
795 WorklistRemover DeadNodes(*this);
796 DAG.ReplaceAllUsesWith(N, To);
798 // Push the new nodes and any users onto the worklist
799 for (unsigned i = 0, e = NumTo; i != e; ++i) {
800 if (To[i].getNode()) {
801 AddToWorklist(To[i].getNode());
802 AddUsersToWorklist(To[i].getNode());
807 // Finally, if the node is now dead, remove it from the graph. The node
808 // may not be dead if the replacement process recursively simplified to
809 // something else needing this node.
811 deleteAndRecombine(N);
812 return SDValue(N, 0);
816 CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) {
817 // Replace all uses. If any nodes become isomorphic to other nodes and
818 // are deleted, make sure to remove them from our worklist.
819 WorklistRemover DeadNodes(*this);
820 DAG.ReplaceAllUsesOfValueWith(TLO.Old, TLO.New);
822 // Push the new node and any (possibly new) users onto the worklist.
823 AddToWorklist(TLO.New.getNode());
824 AddUsersToWorklist(TLO.New.getNode());
826 // Finally, if the node is now dead, remove it from the graph. The node
827 // may not be dead if the replacement process recursively simplified to
828 // something else needing this node.
829 if (TLO.Old.getNode()->use_empty())
830 deleteAndRecombine(TLO.Old.getNode());
833 /// Check the specified integer node value to see if it can be simplified or if
834 /// things it uses can be simplified by bit propagation. If so, return true.
835 bool DAGCombiner::SimplifyDemandedBits(SDValue Op, const APInt &Demanded) {
836 TargetLowering::TargetLoweringOpt TLO(DAG, LegalTypes, LegalOperations);
837 APInt KnownZero, KnownOne;
838 if (!TLI.SimplifyDemandedBits(Op, Demanded, KnownZero, KnownOne, TLO))
842 AddToWorklist(Op.getNode());
844 // Replace the old value with the new one.
846 DEBUG(dbgs() << "\nReplacing.2 ";
847 TLO.Old.getNode()->dump(&DAG);
848 dbgs() << "\nWith: ";
849 TLO.New.getNode()->dump(&DAG);
852 CommitTargetLoweringOpt(TLO);
856 void DAGCombiner::ReplaceLoadWithPromotedLoad(SDNode *Load, SDNode *ExtLoad) {
858 EVT VT = Load->getValueType(0);
859 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, dl, VT, SDValue(ExtLoad, 0));
861 DEBUG(dbgs() << "\nReplacing.9 ";
863 dbgs() << "\nWith: ";
864 Trunc.getNode()->dump(&DAG);
866 WorklistRemover DeadNodes(*this);
867 DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 0), Trunc);
868 DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 1), SDValue(ExtLoad, 1));
869 deleteAndRecombine(Load);
870 AddToWorklist(Trunc.getNode());
873 SDValue DAGCombiner::PromoteOperand(SDValue Op, EVT PVT, bool &Replace) {
876 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Op)) {
877 EVT MemVT = LD->getMemoryVT();
878 ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD)
879 ? (TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT) ? ISD::ZEXTLOAD
881 : LD->getExtensionType();
883 return DAG.getExtLoad(ExtType, dl, PVT,
884 LD->getChain(), LD->getBasePtr(),
885 MemVT, LD->getMemOperand());
888 unsigned Opc = Op.getOpcode();
891 case ISD::AssertSext:
892 return DAG.getNode(ISD::AssertSext, dl, PVT,
893 SExtPromoteOperand(Op.getOperand(0), PVT),
895 case ISD::AssertZext:
896 return DAG.getNode(ISD::AssertZext, dl, PVT,
897 ZExtPromoteOperand(Op.getOperand(0), PVT),
899 case ISD::Constant: {
901 Op.getValueType().isByteSized() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
902 return DAG.getNode(ExtOpc, dl, PVT, Op);
906 if (!TLI.isOperationLegal(ISD::ANY_EXTEND, PVT))
908 return DAG.getNode(ISD::ANY_EXTEND, dl, PVT, Op);
911 SDValue DAGCombiner::SExtPromoteOperand(SDValue Op, EVT PVT) {
912 if (!TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, PVT))
914 EVT OldVT = Op.getValueType();
916 bool Replace = false;
917 SDValue NewOp = PromoteOperand(Op, PVT, Replace);
918 if (!NewOp.getNode())
920 AddToWorklist(NewOp.getNode());
923 ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode());
924 return DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, NewOp.getValueType(), NewOp,
925 DAG.getValueType(OldVT));
928 SDValue DAGCombiner::ZExtPromoteOperand(SDValue Op, EVT PVT) {
929 EVT OldVT = Op.getValueType();
931 bool Replace = false;
932 SDValue NewOp = PromoteOperand(Op, PVT, Replace);
933 if (!NewOp.getNode())
935 AddToWorklist(NewOp.getNode());
938 ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode());
939 return DAG.getZeroExtendInReg(NewOp, dl, OldVT);
942 /// Promote the specified integer binary operation if the target indicates it is
943 /// beneficial. e.g. On x86, it's usually better to promote i16 operations to
944 /// i32 since i16 instructions are longer.
945 SDValue DAGCombiner::PromoteIntBinOp(SDValue Op) {
946 if (!LegalOperations)
949 EVT VT = Op.getValueType();
950 if (VT.isVector() || !VT.isInteger())
953 // If operation type is 'undesirable', e.g. i16 on x86, consider
955 unsigned Opc = Op.getOpcode();
956 if (TLI.isTypeDesirableForOp(Opc, VT))
960 // Consult target whether it is a good idea to promote this operation and
961 // what's the right type to promote it to.
962 if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
963 assert(PVT != VT && "Don't know what type to promote to!");
965 bool Replace0 = false;
966 SDValue N0 = Op.getOperand(0);
967 SDValue NN0 = PromoteOperand(N0, PVT, Replace0);
971 bool Replace1 = false;
972 SDValue N1 = Op.getOperand(1);
977 NN1 = PromoteOperand(N1, PVT, Replace1);
982 AddToWorklist(NN0.getNode());
984 AddToWorklist(NN1.getNode());
987 ReplaceLoadWithPromotedLoad(N0.getNode(), NN0.getNode());
989 ReplaceLoadWithPromotedLoad(N1.getNode(), NN1.getNode());
991 DEBUG(dbgs() << "\nPromoting ";
992 Op.getNode()->dump(&DAG));
994 return DAG.getNode(ISD::TRUNCATE, dl, VT,
995 DAG.getNode(Opc, dl, PVT, NN0, NN1));
1000 /// Promote the specified integer shift operation if the target indicates it is
1001 /// beneficial. e.g. On x86, it's usually better to promote i16 operations to
1002 /// i32 since i16 instructions are longer.
1003 SDValue DAGCombiner::PromoteIntShiftOp(SDValue Op) {
1004 if (!LegalOperations)
1007 EVT VT = Op.getValueType();
1008 if (VT.isVector() || !VT.isInteger())
1011 // If operation type is 'undesirable', e.g. i16 on x86, consider
1013 unsigned Opc = Op.getOpcode();
1014 if (TLI.isTypeDesirableForOp(Opc, VT))
1018 // Consult target whether it is a good idea to promote this operation and
1019 // what's the right type to promote it to.
1020 if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1021 assert(PVT != VT && "Don't know what type to promote to!");
1023 bool Replace = false;
1024 SDValue N0 = Op.getOperand(0);
1025 if (Opc == ISD::SRA)
1026 N0 = SExtPromoteOperand(Op.getOperand(0), PVT);
1027 else if (Opc == ISD::SRL)
1028 N0 = ZExtPromoteOperand(Op.getOperand(0), PVT);
1030 N0 = PromoteOperand(N0, PVT, Replace);
1034 AddToWorklist(N0.getNode());
1036 ReplaceLoadWithPromotedLoad(Op.getOperand(0).getNode(), N0.getNode());
1038 DEBUG(dbgs() << "\nPromoting ";
1039 Op.getNode()->dump(&DAG));
1041 return DAG.getNode(ISD::TRUNCATE, dl, VT,
1042 DAG.getNode(Opc, dl, PVT, N0, Op.getOperand(1)));
1047 SDValue DAGCombiner::PromoteExtend(SDValue Op) {
1048 if (!LegalOperations)
1051 EVT VT = Op.getValueType();
1052 if (VT.isVector() || !VT.isInteger())
1055 // If operation type is 'undesirable', e.g. i16 on x86, consider
1057 unsigned Opc = Op.getOpcode();
1058 if (TLI.isTypeDesirableForOp(Opc, VT))
1062 // Consult target whether it is a good idea to promote this operation and
1063 // what's the right type to promote it to.
1064 if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1065 assert(PVT != VT && "Don't know what type to promote to!");
1066 // fold (aext (aext x)) -> (aext x)
1067 // fold (aext (zext x)) -> (zext x)
1068 // fold (aext (sext x)) -> (sext x)
1069 DEBUG(dbgs() << "\nPromoting ";
1070 Op.getNode()->dump(&DAG));
1071 return DAG.getNode(Op.getOpcode(), SDLoc(Op), VT, Op.getOperand(0));
1076 bool DAGCombiner::PromoteLoad(SDValue Op) {
1077 if (!LegalOperations)
1080 EVT VT = Op.getValueType();
1081 if (VT.isVector() || !VT.isInteger())
1084 // If operation type is 'undesirable', e.g. i16 on x86, consider
1086 unsigned Opc = Op.getOpcode();
1087 if (TLI.isTypeDesirableForOp(Opc, VT))
1091 // Consult target whether it is a good idea to promote this operation and
1092 // what's the right type to promote it to.
1093 if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1094 assert(PVT != VT && "Don't know what type to promote to!");
1097 SDNode *N = Op.getNode();
1098 LoadSDNode *LD = cast<LoadSDNode>(N);
1099 EVT MemVT = LD->getMemoryVT();
1100 ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD)
1101 ? (TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT) ? ISD::ZEXTLOAD
1103 : LD->getExtensionType();
1104 SDValue NewLD = DAG.getExtLoad(ExtType, dl, PVT,
1105 LD->getChain(), LD->getBasePtr(),
1106 MemVT, LD->getMemOperand());
1107 SDValue Result = DAG.getNode(ISD::TRUNCATE, dl, VT, NewLD);
1109 DEBUG(dbgs() << "\nPromoting ";
1112 Result.getNode()->dump(&DAG);
1114 WorklistRemover DeadNodes(*this);
1115 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result);
1116 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), NewLD.getValue(1));
1117 deleteAndRecombine(N);
1118 AddToWorklist(Result.getNode());
1124 /// \brief Recursively delete a node which has no uses and any operands for
1125 /// which it is the only use.
1127 /// Note that this both deletes the nodes and removes them from the worklist.
1128 /// It also adds any nodes who have had a user deleted to the worklist as they
1129 /// may now have only one use and subject to other combines.
1130 bool DAGCombiner::recursivelyDeleteUnusedNodes(SDNode *N) {
1131 if (!N->use_empty())
1134 SmallSetVector<SDNode *, 16> Nodes;
1137 N = Nodes.pop_back_val();
1141 if (N->use_empty()) {
1142 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1143 Nodes.insert(N->getOperand(i).getNode());
1145 removeFromWorklist(N);
1150 } while (!Nodes.empty());
1154 //===----------------------------------------------------------------------===//
1155 // Main DAG Combiner implementation
1156 //===----------------------------------------------------------------------===//
1158 void DAGCombiner::Run(CombineLevel AtLevel) {
1159 // set the instance variables, so that the various visit routines may use it.
1161 LegalOperations = Level >= AfterLegalizeVectorOps;
1162 LegalTypes = Level >= AfterLegalizeTypes;
1164 // Early exit if this basic block is in an optnone function.
1165 AttributeSet FnAttrs =
1166 DAG.getMachineFunction().getFunction()->getAttributes();
1167 if (FnAttrs.hasAttribute(AttributeSet::FunctionIndex,
1168 Attribute::OptimizeNone))
1171 // Add all the dag nodes to the worklist.
1172 for (SelectionDAG::allnodes_iterator I = DAG.allnodes_begin(),
1173 E = DAG.allnodes_end(); I != E; ++I)
1176 // Create a dummy node (which is not added to allnodes), that adds a reference
1177 // to the root node, preventing it from being deleted, and tracking any
1178 // changes of the root.
1179 HandleSDNode Dummy(DAG.getRoot());
1181 // while the worklist isn't empty, find a node and
1182 // try and combine it.
1183 while (!WorklistMap.empty()) {
1185 // The Worklist holds the SDNodes in order, but it may contain null entries.
1187 N = Worklist.pop_back_val();
1190 bool GoodWorklistEntry = WorklistMap.erase(N);
1191 (void)GoodWorklistEntry;
1192 assert(GoodWorklistEntry &&
1193 "Found a worklist entry without a corresponding map entry!");
1195 // If N has no uses, it is dead. Make sure to revisit all N's operands once
1196 // N is deleted from the DAG, since they too may now be dead or may have a
1197 // reduced number of uses, allowing other xforms.
1198 if (recursivelyDeleteUnusedNodes(N))
1201 WorklistRemover DeadNodes(*this);
1203 // If this combine is running after legalizing the DAG, re-legalize any
1204 // nodes pulled off the worklist.
1205 if (Level == AfterLegalizeDAG) {
1206 SmallSetVector<SDNode *, 16> UpdatedNodes;
1207 bool NIsValid = DAG.LegalizeOp(N, UpdatedNodes);
1209 for (SDNode *LN : UpdatedNodes) {
1211 AddUsersToWorklist(LN);
1217 DEBUG(dbgs() << "\nCombining: "; N->dump(&DAG));
1219 // Add any operands of the new node which have not yet been combined to the
1220 // worklist as well. Because the worklist uniques things already, this
1221 // won't repeatedly process the same operand.
1222 CombinedNodes.insert(N);
1223 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1224 if (!CombinedNodes.count(N->getOperand(i).getNode()))
1225 AddToWorklist(N->getOperand(i).getNode());
1227 SDValue RV = combine(N);
1234 // If we get back the same node we passed in, rather than a new node or
1235 // zero, we know that the node must have defined multiple values and
1236 // CombineTo was used. Since CombineTo takes care of the worklist
1237 // mechanics for us, we have no work to do in this case.
1238 if (RV.getNode() == N)
1241 assert(N->getOpcode() != ISD::DELETED_NODE &&
1242 RV.getNode()->getOpcode() != ISD::DELETED_NODE &&
1243 "Node was deleted but visit returned new node!");
1245 DEBUG(dbgs() << " ... into: ";
1246 RV.getNode()->dump(&DAG));
1248 // Transfer debug value.
1249 DAG.TransferDbgValues(SDValue(N, 0), RV);
1250 if (N->getNumValues() == RV.getNode()->getNumValues())
1251 DAG.ReplaceAllUsesWith(N, RV.getNode());
1253 assert(N->getValueType(0) == RV.getValueType() &&
1254 N->getNumValues() == 1 && "Type mismatch");
1256 DAG.ReplaceAllUsesWith(N, &OpV);
1259 // Push the new node and any users onto the worklist
1260 AddToWorklist(RV.getNode());
1261 AddUsersToWorklist(RV.getNode());
1263 // Finally, if the node is now dead, remove it from the graph. The node
1264 // may not be dead if the replacement process recursively simplified to
1265 // something else needing this node. This will also take care of adding any
1266 // operands which have lost a user to the worklist.
1267 recursivelyDeleteUnusedNodes(N);
1270 // If the root changed (e.g. it was a dead load, update the root).
1271 DAG.setRoot(Dummy.getValue());
1272 DAG.RemoveDeadNodes();
1275 SDValue DAGCombiner::visit(SDNode *N) {
1276 switch (N->getOpcode()) {
1278 case ISD::TokenFactor: return visitTokenFactor(N);
1279 case ISD::MERGE_VALUES: return visitMERGE_VALUES(N);
1280 case ISD::ADD: return visitADD(N);
1281 case ISD::SUB: return visitSUB(N);
1282 case ISD::ADDC: return visitADDC(N);
1283 case ISD::SUBC: return visitSUBC(N);
1284 case ISD::ADDE: return visitADDE(N);
1285 case ISD::SUBE: return visitSUBE(N);
1286 case ISD::MUL: return visitMUL(N);
1287 case ISD::SDIV: return visitSDIV(N);
1288 case ISD::UDIV: return visitUDIV(N);
1289 case ISD::SREM: return visitSREM(N);
1290 case ISD::UREM: return visitUREM(N);
1291 case ISD::MULHU: return visitMULHU(N);
1292 case ISD::MULHS: return visitMULHS(N);
1293 case ISD::SMUL_LOHI: return visitSMUL_LOHI(N);
1294 case ISD::UMUL_LOHI: return visitUMUL_LOHI(N);
1295 case ISD::SMULO: return visitSMULO(N);
1296 case ISD::UMULO: return visitUMULO(N);
1297 case ISD::SDIVREM: return visitSDIVREM(N);
1298 case ISD::UDIVREM: return visitUDIVREM(N);
1299 case ISD::AND: return visitAND(N);
1300 case ISD::OR: return visitOR(N);
1301 case ISD::XOR: return visitXOR(N);
1302 case ISD::SHL: return visitSHL(N);
1303 case ISD::SRA: return visitSRA(N);
1304 case ISD::SRL: return visitSRL(N);
1306 case ISD::ROTL: return visitRotate(N);
1307 case ISD::CTLZ: return visitCTLZ(N);
1308 case ISD::CTLZ_ZERO_UNDEF: return visitCTLZ_ZERO_UNDEF(N);
1309 case ISD::CTTZ: return visitCTTZ(N);
1310 case ISD::CTTZ_ZERO_UNDEF: return visitCTTZ_ZERO_UNDEF(N);
1311 case ISD::CTPOP: return visitCTPOP(N);
1312 case ISD::SELECT: return visitSELECT(N);
1313 case ISD::VSELECT: return visitVSELECT(N);
1314 case ISD::SELECT_CC: return visitSELECT_CC(N);
1315 case ISD::SETCC: return visitSETCC(N);
1316 case ISD::SIGN_EXTEND: return visitSIGN_EXTEND(N);
1317 case ISD::ZERO_EXTEND: return visitZERO_EXTEND(N);
1318 case ISD::ANY_EXTEND: return visitANY_EXTEND(N);
1319 case ISD::SIGN_EXTEND_INREG: return visitSIGN_EXTEND_INREG(N);
1320 case ISD::TRUNCATE: return visitTRUNCATE(N);
1321 case ISD::BITCAST: return visitBITCAST(N);
1322 case ISD::BUILD_PAIR: return visitBUILD_PAIR(N);
1323 case ISD::FADD: return visitFADD(N);
1324 case ISD::FSUB: return visitFSUB(N);
1325 case ISD::FMUL: return visitFMUL(N);
1326 case ISD::FMA: return visitFMA(N);
1327 case ISD::FDIV: return visitFDIV(N);
1328 case ISD::FREM: return visitFREM(N);
1329 case ISD::FSQRT: return visitFSQRT(N);
1330 case ISD::FCOPYSIGN: return visitFCOPYSIGN(N);
1331 case ISD::SINT_TO_FP: return visitSINT_TO_FP(N);
1332 case ISD::UINT_TO_FP: return visitUINT_TO_FP(N);
1333 case ISD::FP_TO_SINT: return visitFP_TO_SINT(N);
1334 case ISD::FP_TO_UINT: return visitFP_TO_UINT(N);
1335 case ISD::FP_ROUND: return visitFP_ROUND(N);
1336 case ISD::FP_ROUND_INREG: return visitFP_ROUND_INREG(N);
1337 case ISD::FP_EXTEND: return visitFP_EXTEND(N);
1338 case ISD::FNEG: return visitFNEG(N);
1339 case ISD::FABS: return visitFABS(N);
1340 case ISD::FFLOOR: return visitFFLOOR(N);
1341 case ISD::FMINNUM: return visitFMINNUM(N);
1342 case ISD::FMAXNUM: return visitFMAXNUM(N);
1343 case ISD::FCEIL: return visitFCEIL(N);
1344 case ISD::FTRUNC: return visitFTRUNC(N);
1345 case ISD::BRCOND: return visitBRCOND(N);
1346 case ISD::BR_CC: return visitBR_CC(N);
1347 case ISD::LOAD: return visitLOAD(N);
1348 case ISD::STORE: return visitSTORE(N);
1349 case ISD::INSERT_VECTOR_ELT: return visitINSERT_VECTOR_ELT(N);
1350 case ISD::EXTRACT_VECTOR_ELT: return visitEXTRACT_VECTOR_ELT(N);
1351 case ISD::BUILD_VECTOR: return visitBUILD_VECTOR(N);
1352 case ISD::CONCAT_VECTORS: return visitCONCAT_VECTORS(N);
1353 case ISD::EXTRACT_SUBVECTOR: return visitEXTRACT_SUBVECTOR(N);
1354 case ISD::VECTOR_SHUFFLE: return visitVECTOR_SHUFFLE(N);
1355 case ISD::INSERT_SUBVECTOR: return visitINSERT_SUBVECTOR(N);
1356 case ISD::MLOAD: return visitMLOAD(N);
1357 case ISD::MSTORE: return visitMSTORE(N);
1362 SDValue DAGCombiner::combine(SDNode *N) {
1363 SDValue RV = visit(N);
1365 // If nothing happened, try a target-specific DAG combine.
1366 if (!RV.getNode()) {
1367 assert(N->getOpcode() != ISD::DELETED_NODE &&
1368 "Node was deleted but visit returned NULL!");
1370 if (N->getOpcode() >= ISD::BUILTIN_OP_END ||
1371 TLI.hasTargetDAGCombine((ISD::NodeType)N->getOpcode())) {
1373 // Expose the DAG combiner to the target combiner impls.
1374 TargetLowering::DAGCombinerInfo
1375 DagCombineInfo(DAG, Level, false, this);
1377 RV = TLI.PerformDAGCombine(N, DagCombineInfo);
1381 // If nothing happened still, try promoting the operation.
1382 if (!RV.getNode()) {
1383 switch (N->getOpcode()) {
1391 RV = PromoteIntBinOp(SDValue(N, 0));
1396 RV = PromoteIntShiftOp(SDValue(N, 0));
1398 case ISD::SIGN_EXTEND:
1399 case ISD::ZERO_EXTEND:
1400 case ISD::ANY_EXTEND:
1401 RV = PromoteExtend(SDValue(N, 0));
1404 if (PromoteLoad(SDValue(N, 0)))
1410 // If N is a commutative binary node, try commuting it to enable more
1412 if (!RV.getNode() && SelectionDAG::isCommutativeBinOp(N->getOpcode()) &&
1413 N->getNumValues() == 1) {
1414 SDValue N0 = N->getOperand(0);
1415 SDValue N1 = N->getOperand(1);
1417 // Constant operands are canonicalized to RHS.
1418 if (isa<ConstantSDNode>(N0) || !isa<ConstantSDNode>(N1)) {
1419 SDValue Ops[] = {N1, N0};
1421 if (const BinaryWithFlagsSDNode *BinNode =
1422 dyn_cast<BinaryWithFlagsSDNode>(N)) {
1423 CSENode = DAG.getNodeIfExists(
1424 N->getOpcode(), N->getVTList(), Ops, BinNode->hasNoUnsignedWrap(),
1425 BinNode->hasNoSignedWrap(), BinNode->isExact());
1427 CSENode = DAG.getNodeIfExists(N->getOpcode(), N->getVTList(), Ops);
1430 return SDValue(CSENode, 0);
1437 /// Given a node, return its input chain if it has one, otherwise return a null
1439 static SDValue getInputChainForNode(SDNode *N) {
1440 if (unsigned NumOps = N->getNumOperands()) {
1441 if (N->getOperand(0).getValueType() == MVT::Other)
1442 return N->getOperand(0);
1443 if (N->getOperand(NumOps-1).getValueType() == MVT::Other)
1444 return N->getOperand(NumOps-1);
1445 for (unsigned i = 1; i < NumOps-1; ++i)
1446 if (N->getOperand(i).getValueType() == MVT::Other)
1447 return N->getOperand(i);
1452 SDValue DAGCombiner::visitTokenFactor(SDNode *N) {
1453 // If N has two operands, where one has an input chain equal to the other,
1454 // the 'other' chain is redundant.
1455 if (N->getNumOperands() == 2) {
1456 if (getInputChainForNode(N->getOperand(0).getNode()) == N->getOperand(1))
1457 return N->getOperand(0);
1458 if (getInputChainForNode(N->getOperand(1).getNode()) == N->getOperand(0))
1459 return N->getOperand(1);
1462 SmallVector<SDNode *, 8> TFs; // List of token factors to visit.
1463 SmallVector<SDValue, 8> Ops; // Ops for replacing token factor.
1464 SmallPtrSet<SDNode*, 16> SeenOps;
1465 bool Changed = false; // If we should replace this token factor.
1467 // Start out with this token factor.
1470 // Iterate through token factors. The TFs grows when new token factors are
1472 for (unsigned i = 0; i < TFs.size(); ++i) {
1473 SDNode *TF = TFs[i];
1475 // Check each of the operands.
1476 for (unsigned i = 0, ie = TF->getNumOperands(); i != ie; ++i) {
1477 SDValue Op = TF->getOperand(i);
1479 switch (Op.getOpcode()) {
1480 case ISD::EntryToken:
1481 // Entry tokens don't need to be added to the list. They are
1486 case ISD::TokenFactor:
1487 if (Op.hasOneUse() &&
1488 std::find(TFs.begin(), TFs.end(), Op.getNode()) == TFs.end()) {
1489 // Queue up for processing.
1490 TFs.push_back(Op.getNode());
1491 // Clean up in case the token factor is removed.
1492 AddToWorklist(Op.getNode());
1499 // Only add if it isn't already in the list.
1500 if (SeenOps.insert(Op.getNode()).second)
1511 // If we've change things around then replace token factor.
1514 // The entry token is the only possible outcome.
1515 Result = DAG.getEntryNode();
1517 // New and improved token factor.
1518 Result = DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other, Ops);
1521 // Don't add users to work list.
1522 return CombineTo(N, Result, false);
1528 /// MERGE_VALUES can always be eliminated.
1529 SDValue DAGCombiner::visitMERGE_VALUES(SDNode *N) {
1530 WorklistRemover DeadNodes(*this);
1531 // Replacing results may cause a different MERGE_VALUES to suddenly
1532 // be CSE'd with N, and carry its uses with it. Iterate until no
1533 // uses remain, to ensure that the node can be safely deleted.
1534 // First add the users of this node to the work list so that they
1535 // can be tried again once they have new operands.
1536 AddUsersToWorklist(N);
1538 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1539 DAG.ReplaceAllUsesOfValueWith(SDValue(N, i), N->getOperand(i));
1540 } while (!N->use_empty());
1541 deleteAndRecombine(N);
1542 return SDValue(N, 0); // Return N so it doesn't get rechecked!
1545 SDValue DAGCombiner::visitADD(SDNode *N) {
1546 SDValue N0 = N->getOperand(0);
1547 SDValue N1 = N->getOperand(1);
1548 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1549 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1550 EVT VT = N0.getValueType();
1553 if (VT.isVector()) {
1554 SDValue FoldedVOp = SimplifyVBinOp(N);
1555 if (FoldedVOp.getNode()) return FoldedVOp;
1557 // fold (add x, 0) -> x, vector edition
1558 if (ISD::isBuildVectorAllZeros(N1.getNode()))
1560 if (ISD::isBuildVectorAllZeros(N0.getNode()))
1564 // fold (add x, undef) -> undef
1565 if (N0.getOpcode() == ISD::UNDEF)
1567 if (N1.getOpcode() == ISD::UNDEF)
1569 // fold (add c1, c2) -> c1+c2
1571 return DAG.FoldConstantArithmetic(ISD::ADD, VT, N0C, N1C);
1572 // canonicalize constant to RHS
1574 return DAG.getNode(ISD::ADD, SDLoc(N), VT, N1, N0);
1575 // fold (add x, 0) -> x
1576 if (N1C && N1C->isNullValue())
1578 // fold (add Sym, c) -> Sym+c
1579 if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N0))
1580 if (!LegalOperations && TLI.isOffsetFoldingLegal(GA) && N1C &&
1581 GA->getOpcode() == ISD::GlobalAddress)
1582 return DAG.getGlobalAddress(GA->getGlobal(), SDLoc(N1C), VT,
1584 (uint64_t)N1C->getSExtValue());
1585 // fold ((c1-A)+c2) -> (c1+c2)-A
1586 if (N1C && N0.getOpcode() == ISD::SUB)
1587 if (ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getOperand(0)))
1588 return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1589 DAG.getConstant(N1C->getAPIntValue()+
1590 N0C->getAPIntValue(), VT),
1593 SDValue RADD = ReassociateOps(ISD::ADD, SDLoc(N), N0, N1);
1596 // fold ((0-A) + B) -> B-A
1597 if (N0.getOpcode() == ISD::SUB && isa<ConstantSDNode>(N0.getOperand(0)) &&
1598 cast<ConstantSDNode>(N0.getOperand(0))->isNullValue())
1599 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1, N0.getOperand(1));
1600 // fold (A + (0-B)) -> A-B
1601 if (N1.getOpcode() == ISD::SUB && isa<ConstantSDNode>(N1.getOperand(0)) &&
1602 cast<ConstantSDNode>(N1.getOperand(0))->isNullValue())
1603 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, N1.getOperand(1));
1604 // fold (A+(B-A)) -> B
1605 if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(1))
1606 return N1.getOperand(0);
1607 // fold ((B-A)+A) -> B
1608 if (N0.getOpcode() == ISD::SUB && N1 == N0.getOperand(1))
1609 return N0.getOperand(0);
1610 // fold (A+(B-(A+C))) to (B-C)
1611 if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD &&
1612 N0 == N1.getOperand(1).getOperand(0))
1613 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1.getOperand(0),
1614 N1.getOperand(1).getOperand(1));
1615 // fold (A+(B-(C+A))) to (B-C)
1616 if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD &&
1617 N0 == N1.getOperand(1).getOperand(1))
1618 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1.getOperand(0),
1619 N1.getOperand(1).getOperand(0));
1620 // fold (A+((B-A)+or-C)) to (B+or-C)
1621 if ((N1.getOpcode() == ISD::SUB || N1.getOpcode() == ISD::ADD) &&
1622 N1.getOperand(0).getOpcode() == ISD::SUB &&
1623 N0 == N1.getOperand(0).getOperand(1))
1624 return DAG.getNode(N1.getOpcode(), SDLoc(N), VT,
1625 N1.getOperand(0).getOperand(0), N1.getOperand(1));
1627 // fold (A-B)+(C-D) to (A+C)-(B+D) when A or C is constant
1628 if (N0.getOpcode() == ISD::SUB && N1.getOpcode() == ISD::SUB) {
1629 SDValue N00 = N0.getOperand(0);
1630 SDValue N01 = N0.getOperand(1);
1631 SDValue N10 = N1.getOperand(0);
1632 SDValue N11 = N1.getOperand(1);
1634 if (isa<ConstantSDNode>(N00) || isa<ConstantSDNode>(N10))
1635 return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1636 DAG.getNode(ISD::ADD, SDLoc(N0), VT, N00, N10),
1637 DAG.getNode(ISD::ADD, SDLoc(N1), VT, N01, N11));
1640 if (!VT.isVector() && SimplifyDemandedBits(SDValue(N, 0)))
1641 return SDValue(N, 0);
1643 // fold (a+b) -> (a|b) iff a and b share no bits.
1644 if (VT.isInteger() && !VT.isVector()) {
1645 APInt LHSZero, LHSOne;
1646 APInt RHSZero, RHSOne;
1647 DAG.computeKnownBits(N0, LHSZero, LHSOne);
1649 if (LHSZero.getBoolValue()) {
1650 DAG.computeKnownBits(N1, RHSZero, RHSOne);
1652 // If all possibly-set bits on the LHS are clear on the RHS, return an OR.
1653 // If all possibly-set bits on the RHS are clear on the LHS, return an OR.
1654 if ((RHSZero & ~LHSZero) == ~LHSZero || (LHSZero & ~RHSZero) == ~RHSZero){
1655 if (!LegalOperations || TLI.isOperationLegal(ISD::OR, VT))
1656 return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N1);
1661 // fold (add x, shl(0 - y, n)) -> sub(x, shl(y, n))
1662 if (N1.getOpcode() == ISD::SHL &&
1663 N1.getOperand(0).getOpcode() == ISD::SUB)
1664 if (ConstantSDNode *C =
1665 dyn_cast<ConstantSDNode>(N1.getOperand(0).getOperand(0)))
1666 if (C->getAPIntValue() == 0)
1667 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N0,
1668 DAG.getNode(ISD::SHL, SDLoc(N), VT,
1669 N1.getOperand(0).getOperand(1),
1671 if (N0.getOpcode() == ISD::SHL &&
1672 N0.getOperand(0).getOpcode() == ISD::SUB)
1673 if (ConstantSDNode *C =
1674 dyn_cast<ConstantSDNode>(N0.getOperand(0).getOperand(0)))
1675 if (C->getAPIntValue() == 0)
1676 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1,
1677 DAG.getNode(ISD::SHL, SDLoc(N), VT,
1678 N0.getOperand(0).getOperand(1),
1681 if (N1.getOpcode() == ISD::AND) {
1682 SDValue AndOp0 = N1.getOperand(0);
1683 ConstantSDNode *AndOp1 = dyn_cast<ConstantSDNode>(N1->getOperand(1));
1684 unsigned NumSignBits = DAG.ComputeNumSignBits(AndOp0);
1685 unsigned DestBits = VT.getScalarType().getSizeInBits();
1687 // (add z, (and (sbbl x, x), 1)) -> (sub z, (sbbl x, x))
1688 // and similar xforms where the inner op is either ~0 or 0.
1689 if (NumSignBits == DestBits && AndOp1 && AndOp1->isOne()) {
1691 return DAG.getNode(ISD::SUB, DL, VT, N->getOperand(0), AndOp0);
1695 // add (sext i1), X -> sub X, (zext i1)
1696 if (N0.getOpcode() == ISD::SIGN_EXTEND &&
1697 N0.getOperand(0).getValueType() == MVT::i1 &&
1698 !TLI.isOperationLegal(ISD::SIGN_EXTEND, MVT::i1)) {
1700 SDValue ZExt = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0));
1701 return DAG.getNode(ISD::SUB, DL, VT, N1, ZExt);
1704 // add X, (sextinreg Y i1) -> sub X, (and Y 1)
1705 if (N1.getOpcode() == ISD::SIGN_EXTEND_INREG) {
1706 VTSDNode *TN = cast<VTSDNode>(N1.getOperand(1));
1707 if (TN->getVT() == MVT::i1) {
1709 SDValue ZExt = DAG.getNode(ISD::AND, DL, VT, N1.getOperand(0),
1710 DAG.getConstant(1, VT));
1711 return DAG.getNode(ISD::SUB, DL, VT, N0, 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(),
1880 // sub X, (sextinreg Y i1) -> add X, (and Y 1)
1881 if (N1.getOpcode() == ISD::SIGN_EXTEND_INREG) {
1882 VTSDNode *TN = cast<VTSDNode>(N1.getOperand(1));
1883 if (TN->getVT() == MVT::i1) {
1885 SDValue ZExt = DAG.getNode(ISD::AND, DL, VT, N1.getOperand(0),
1886 DAG.getConstant(1, VT));
1887 return DAG.getNode(ISD::ADD, DL, VT, N0, ZExt);
1894 SDValue DAGCombiner::visitSUBC(SDNode *N) {
1895 SDValue N0 = N->getOperand(0);
1896 SDValue N1 = N->getOperand(1);
1897 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1898 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1899 EVT VT = N0.getValueType();
1901 // If the flag result is dead, turn this into an SUB.
1902 if (!N->hasAnyUseOfValue(1))
1903 return CombineTo(N, DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, N1),
1904 DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
1907 // fold (subc x, x) -> 0 + no borrow
1909 return CombineTo(N, DAG.getConstant(0, VT),
1910 DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
1913 // fold (subc x, 0) -> x + no borrow
1914 if (N1C && N1C->isNullValue())
1915 return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
1918 // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1) + no borrow
1919 if (N0C && N0C->isAllOnesValue())
1920 return CombineTo(N, DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0),
1921 DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
1927 SDValue DAGCombiner::visitSUBE(SDNode *N) {
1928 SDValue N0 = N->getOperand(0);
1929 SDValue N1 = N->getOperand(1);
1930 SDValue CarryIn = N->getOperand(2);
1932 // fold (sube x, y, false) -> (subc x, y)
1933 if (CarryIn.getOpcode() == ISD::CARRY_FALSE)
1934 return DAG.getNode(ISD::SUBC, SDLoc(N), N->getVTList(), N0, N1);
1939 SDValue DAGCombiner::visitMUL(SDNode *N) {
1940 SDValue N0 = N->getOperand(0);
1941 SDValue N1 = N->getOperand(1);
1942 EVT VT = N0.getValueType();
1944 // fold (mul x, undef) -> 0
1945 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
1946 return DAG.getConstant(0, VT);
1948 bool N0IsConst = false;
1949 bool N1IsConst = false;
1950 APInt ConstValue0, ConstValue1;
1952 if (VT.isVector()) {
1953 SDValue FoldedVOp = SimplifyVBinOp(N);
1954 if (FoldedVOp.getNode()) return FoldedVOp;
1956 N0IsConst = isConstantSplatVector(N0.getNode(), ConstValue0);
1957 N1IsConst = isConstantSplatVector(N1.getNode(), ConstValue1);
1959 N0IsConst = dyn_cast<ConstantSDNode>(N0) != nullptr;
1960 ConstValue0 = N0IsConst ? (dyn_cast<ConstantSDNode>(N0))->getAPIntValue()
1962 N1IsConst = dyn_cast<ConstantSDNode>(N1) != nullptr;
1963 ConstValue1 = N1IsConst ? (dyn_cast<ConstantSDNode>(N1))->getAPIntValue()
1967 // fold (mul c1, c2) -> c1*c2
1968 if (N0IsConst && N1IsConst)
1969 return DAG.FoldConstantArithmetic(ISD::MUL, VT, N0.getNode(), N1.getNode());
1971 // canonicalize constant to RHS
1972 if (N0IsConst && !N1IsConst)
1973 return DAG.getNode(ISD::MUL, SDLoc(N), VT, N1, N0);
1974 // fold (mul x, 0) -> 0
1975 if (N1IsConst && ConstValue1 == 0)
1977 // We require a splat of the entire scalar bit width for non-contiguous
1980 ConstValue1.getBitWidth() == VT.getScalarType().getSizeInBits();
1981 // fold (mul x, 1) -> x
1982 if (N1IsConst && ConstValue1 == 1 && IsFullSplat)
1984 // fold (mul x, -1) -> 0-x
1985 if (N1IsConst && ConstValue1.isAllOnesValue())
1986 return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1987 DAG.getConstant(0, VT), N0);
1988 // fold (mul x, (1 << c)) -> x << c
1989 if (N1IsConst && ConstValue1.isPowerOf2() && IsFullSplat)
1990 return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0,
1991 DAG.getConstant(ConstValue1.logBase2(),
1992 getShiftAmountTy(N0.getValueType())));
1993 // fold (mul x, -(1 << c)) -> -(x << c) or (-x) << c
1994 if (N1IsConst && (-ConstValue1).isPowerOf2() && IsFullSplat) {
1995 unsigned Log2Val = (-ConstValue1).logBase2();
1996 // FIXME: If the input is something that is easily negated (e.g. a
1997 // single-use add), we should put the negate there.
1998 return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1999 DAG.getConstant(0, VT),
2000 DAG.getNode(ISD::SHL, SDLoc(N), VT, N0,
2001 DAG.getConstant(Log2Val,
2002 getShiftAmountTy(N0.getValueType()))));
2006 // (mul (shl X, c1), c2) -> (mul X, c2 << c1)
2007 if (N1IsConst && N0.getOpcode() == ISD::SHL &&
2008 (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
2009 isa<ConstantSDNode>(N0.getOperand(1)))) {
2010 SDValue C3 = DAG.getNode(ISD::SHL, SDLoc(N), VT,
2011 N1, N0.getOperand(1));
2012 AddToWorklist(C3.getNode());
2013 return DAG.getNode(ISD::MUL, SDLoc(N), VT,
2014 N0.getOperand(0), C3);
2017 // Change (mul (shl X, C), Y) -> (shl (mul X, Y), C) when the shift has one
2020 SDValue Sh(nullptr,0), Y(nullptr,0);
2021 // Check for both (mul (shl X, C), Y) and (mul Y, (shl X, C)).
2022 if (N0.getOpcode() == ISD::SHL &&
2023 (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
2024 isa<ConstantSDNode>(N0.getOperand(1))) &&
2025 N0.getNode()->hasOneUse()) {
2027 } else if (N1.getOpcode() == ISD::SHL &&
2028 isa<ConstantSDNode>(N1.getOperand(1)) &&
2029 N1.getNode()->hasOneUse()) {
2034 SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT,
2035 Sh.getOperand(0), Y);
2036 return DAG.getNode(ISD::SHL, SDLoc(N), VT,
2037 Mul, Sh.getOperand(1));
2041 // fold (mul (add x, c1), c2) -> (add (mul x, c2), c1*c2)
2042 if (N1IsConst && N0.getOpcode() == ISD::ADD && N0.getNode()->hasOneUse() &&
2043 (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
2044 isa<ConstantSDNode>(N0.getOperand(1))))
2045 return DAG.getNode(ISD::ADD, SDLoc(N), VT,
2046 DAG.getNode(ISD::MUL, SDLoc(N0), VT,
2047 N0.getOperand(0), N1),
2048 DAG.getNode(ISD::MUL, SDLoc(N1), VT,
2049 N0.getOperand(1), N1));
2052 SDValue RMUL = ReassociateOps(ISD::MUL, SDLoc(N), N0, N1);
2059 SDValue DAGCombiner::visitSDIV(SDNode *N) {
2060 SDValue N0 = N->getOperand(0);
2061 SDValue N1 = N->getOperand(1);
2062 ConstantSDNode *N0C = isConstOrConstSplat(N0);
2063 ConstantSDNode *N1C = isConstOrConstSplat(N1);
2064 EVT VT = N->getValueType(0);
2067 if (VT.isVector()) {
2068 SDValue FoldedVOp = SimplifyVBinOp(N);
2069 if (FoldedVOp.getNode()) return FoldedVOp;
2072 // fold (sdiv c1, c2) -> c1/c2
2073 if (N0C && N1C && !N1C->isNullValue())
2074 return DAG.FoldConstantArithmetic(ISD::SDIV, VT, N0C, N1C);
2075 // fold (sdiv X, 1) -> X
2076 if (N1C && N1C->getAPIntValue() == 1LL)
2078 // fold (sdiv X, -1) -> 0-X
2079 if (N1C && N1C->isAllOnesValue())
2080 return DAG.getNode(ISD::SUB, SDLoc(N), VT,
2081 DAG.getConstant(0, VT), N0);
2082 // If we know the sign bits of both operands are zero, strength reduce to a
2083 // udiv instead. Handles (X&15) /s 4 -> X&15 >> 2
2084 if (!VT.isVector()) {
2085 if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
2086 return DAG.getNode(ISD::UDIV, SDLoc(N), N1.getValueType(),
2090 // fold (sdiv X, pow2) -> simple ops after legalize
2091 if (N1C && !N1C->isNullValue() && (N1C->getAPIntValue().isPowerOf2() ||
2092 (-N1C->getAPIntValue()).isPowerOf2())) {
2093 // If dividing by powers of two is cheap, then don't perform the following
2095 if (TLI.isPow2SDivCheap())
2098 // Target-specific implementation of sdiv x, pow2.
2099 SDValue Res = BuildSDIVPow2(N);
2103 unsigned lg2 = N1C->getAPIntValue().countTrailingZeros();
2105 // Splat the sign bit into the register
2107 DAG.getNode(ISD::SRA, SDLoc(N), VT, N0,
2108 DAG.getConstant(VT.getScalarSizeInBits() - 1,
2109 getShiftAmountTy(N0.getValueType())));
2110 AddToWorklist(SGN.getNode());
2112 // Add (N0 < 0) ? abs2 - 1 : 0;
2114 DAG.getNode(ISD::SRL, SDLoc(N), VT, SGN,
2115 DAG.getConstant(VT.getScalarSizeInBits() - lg2,
2116 getShiftAmountTy(SGN.getValueType())));
2117 SDValue ADD = DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, SRL);
2118 AddToWorklist(SRL.getNode());
2119 AddToWorklist(ADD.getNode()); // Divide by pow2
2120 SDValue SRA = DAG.getNode(ISD::SRA, SDLoc(N), VT, ADD,
2121 DAG.getConstant(lg2, getShiftAmountTy(ADD.getValueType())));
2123 // If we're dividing by a positive value, we're done. Otherwise, we must
2124 // negate the result.
2125 if (N1C->getAPIntValue().isNonNegative())
2128 AddToWorklist(SRA.getNode());
2129 return DAG.getNode(ISD::SUB, SDLoc(N), VT, DAG.getConstant(0, VT), SRA);
2132 // if integer divide is expensive and we satisfy the requirements, emit an
2133 // alternate sequence.
2134 if (N1C && !TLI.isIntDivCheap()) {
2135 SDValue Op = BuildSDIV(N);
2136 if (Op.getNode()) return Op;
2140 if (N0.getOpcode() == ISD::UNDEF)
2141 return DAG.getConstant(0, VT);
2142 // X / undef -> undef
2143 if (N1.getOpcode() == ISD::UNDEF)
2149 SDValue DAGCombiner::visitUDIV(SDNode *N) {
2150 SDValue N0 = N->getOperand(0);
2151 SDValue N1 = N->getOperand(1);
2152 ConstantSDNode *N0C = isConstOrConstSplat(N0);
2153 ConstantSDNode *N1C = isConstOrConstSplat(N1);
2154 EVT VT = N->getValueType(0);
2157 if (VT.isVector()) {
2158 SDValue FoldedVOp = SimplifyVBinOp(N);
2159 if (FoldedVOp.getNode()) return FoldedVOp;
2162 // fold (udiv c1, c2) -> c1/c2
2163 if (N0C && N1C && !N1C->isNullValue())
2164 return DAG.FoldConstantArithmetic(ISD::UDIV, VT, N0C, N1C);
2165 // fold (udiv x, (1 << c)) -> x >>u c
2166 if (N1C && N1C->getAPIntValue().isPowerOf2())
2167 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0,
2168 DAG.getConstant(N1C->getAPIntValue().logBase2(),
2169 getShiftAmountTy(N0.getValueType())));
2170 // fold (udiv x, (shl c, y)) -> x >>u (log2(c)+y) iff c is power of 2
2171 if (N1.getOpcode() == ISD::SHL) {
2172 if (ConstantSDNode *SHC = dyn_cast<ConstantSDNode>(N1.getOperand(0))) {
2173 if (SHC->getAPIntValue().isPowerOf2()) {
2174 EVT ADDVT = N1.getOperand(1).getValueType();
2175 SDValue Add = DAG.getNode(ISD::ADD, SDLoc(N), ADDVT,
2177 DAG.getConstant(SHC->getAPIntValue()
2180 AddToWorklist(Add.getNode());
2181 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, Add);
2185 // fold (udiv x, c) -> alternate
2186 if (N1C && !TLI.isIntDivCheap()) {
2187 SDValue Op = BuildUDIV(N);
2188 if (Op.getNode()) return Op;
2192 if (N0.getOpcode() == ISD::UNDEF)
2193 return DAG.getConstant(0, VT);
2194 // X / undef -> undef
2195 if (N1.getOpcode() == ISD::UNDEF)
2201 SDValue DAGCombiner::visitSREM(SDNode *N) {
2202 SDValue N0 = N->getOperand(0);
2203 SDValue N1 = N->getOperand(1);
2204 ConstantSDNode *N0C = isConstOrConstSplat(N0);
2205 ConstantSDNode *N1C = isConstOrConstSplat(N1);
2206 EVT VT = N->getValueType(0);
2208 // fold (srem c1, c2) -> c1%c2
2209 if (N0C && N1C && !N1C->isNullValue())
2210 return DAG.FoldConstantArithmetic(ISD::SREM, VT, N0C, N1C);
2211 // If we know the sign bits of both operands are zero, strength reduce to a
2212 // urem instead. Handles (X & 0x0FFFFFFF) %s 16 -> X&15
2213 if (!VT.isVector()) {
2214 if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
2215 return DAG.getNode(ISD::UREM, SDLoc(N), VT, N0, N1);
2218 // If X/C can be simplified by the division-by-constant logic, lower
2219 // X%C to the equivalent of X-X/C*C.
2220 if (N1C && !N1C->isNullValue()) {
2221 SDValue Div = DAG.getNode(ISD::SDIV, SDLoc(N), VT, N0, N1);
2222 AddToWorklist(Div.getNode());
2223 SDValue OptimizedDiv = combine(Div.getNode());
2224 if (OptimizedDiv.getNode() && OptimizedDiv.getNode() != Div.getNode()) {
2225 SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT,
2227 SDValue Sub = DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, Mul);
2228 AddToWorklist(Mul.getNode());
2234 if (N0.getOpcode() == ISD::UNDEF)
2235 return DAG.getConstant(0, VT);
2236 // X % undef -> undef
2237 if (N1.getOpcode() == ISD::UNDEF)
2243 SDValue DAGCombiner::visitUREM(SDNode *N) {
2244 SDValue N0 = N->getOperand(0);
2245 SDValue N1 = N->getOperand(1);
2246 ConstantSDNode *N0C = isConstOrConstSplat(N0);
2247 ConstantSDNode *N1C = isConstOrConstSplat(N1);
2248 EVT VT = N->getValueType(0);
2250 // fold (urem c1, c2) -> c1%c2
2251 if (N0C && N1C && !N1C->isNullValue())
2252 return DAG.FoldConstantArithmetic(ISD::UREM, VT, N0C, N1C);
2253 // fold (urem x, pow2) -> (and x, pow2-1)
2254 if (N1C && !N1C->isNullValue() && N1C->getAPIntValue().isPowerOf2())
2255 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0,
2256 DAG.getConstant(N1C->getAPIntValue()-1,VT));
2257 // fold (urem x, (shl pow2, y)) -> (and x, (add (shl pow2, y), -1))
2258 if (N1.getOpcode() == ISD::SHL) {
2259 if (ConstantSDNode *SHC = dyn_cast<ConstantSDNode>(N1.getOperand(0))) {
2260 if (SHC->getAPIntValue().isPowerOf2()) {
2262 DAG.getNode(ISD::ADD, SDLoc(N), VT, N1,
2263 DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()),
2265 AddToWorklist(Add.getNode());
2266 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, Add);
2271 // If X/C can be simplified by the division-by-constant logic, lower
2272 // X%C to the equivalent of X-X/C*C.
2273 if (N1C && !N1C->isNullValue()) {
2274 SDValue Div = DAG.getNode(ISD::UDIV, SDLoc(N), VT, N0, N1);
2275 AddToWorklist(Div.getNode());
2276 SDValue OptimizedDiv = combine(Div.getNode());
2277 if (OptimizedDiv.getNode() && OptimizedDiv.getNode() != Div.getNode()) {
2278 SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT,
2280 SDValue Sub = DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, Mul);
2281 AddToWorklist(Mul.getNode());
2287 if (N0.getOpcode() == ISD::UNDEF)
2288 return DAG.getConstant(0, VT);
2289 // X % undef -> undef
2290 if (N1.getOpcode() == ISD::UNDEF)
2296 SDValue DAGCombiner::visitMULHS(SDNode *N) {
2297 SDValue N0 = N->getOperand(0);
2298 SDValue N1 = N->getOperand(1);
2299 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2300 EVT VT = N->getValueType(0);
2303 // fold (mulhs x, 0) -> 0
2304 if (N1C && N1C->isNullValue())
2306 // fold (mulhs x, 1) -> (sra x, size(x)-1)
2307 if (N1C && N1C->getAPIntValue() == 1)
2308 return DAG.getNode(ISD::SRA, SDLoc(N), N0.getValueType(), N0,
2309 DAG.getConstant(N0.getValueType().getSizeInBits() - 1,
2310 getShiftAmountTy(N0.getValueType())));
2311 // fold (mulhs x, undef) -> 0
2312 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2313 return DAG.getConstant(0, VT);
2315 // If the type twice as wide is legal, transform the mulhs to a wider multiply
2317 if (VT.isSimple() && !VT.isVector()) {
2318 MVT Simple = VT.getSimpleVT();
2319 unsigned SimpleSize = Simple.getSizeInBits();
2320 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2321 if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2322 N0 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N0);
2323 N1 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N1);
2324 N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1);
2325 N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1,
2326 DAG.getConstant(SimpleSize, getShiftAmountTy(N1.getValueType())));
2327 return DAG.getNode(ISD::TRUNCATE, DL, VT, N1);
2334 SDValue DAGCombiner::visitMULHU(SDNode *N) {
2335 SDValue N0 = N->getOperand(0);
2336 SDValue N1 = N->getOperand(1);
2337 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2338 EVT VT = N->getValueType(0);
2341 // fold (mulhu x, 0) -> 0
2342 if (N1C && N1C->isNullValue())
2344 // fold (mulhu x, 1) -> 0
2345 if (N1C && N1C->getAPIntValue() == 1)
2346 return DAG.getConstant(0, N0.getValueType());
2347 // fold (mulhu x, undef) -> 0
2348 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2349 return DAG.getConstant(0, VT);
2351 // If the type twice as wide is legal, transform the mulhu to a wider multiply
2353 if (VT.isSimple() && !VT.isVector()) {
2354 MVT Simple = VT.getSimpleVT();
2355 unsigned SimpleSize = Simple.getSizeInBits();
2356 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2357 if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2358 N0 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N0);
2359 N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N1);
2360 N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1);
2361 N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1,
2362 DAG.getConstant(SimpleSize, getShiftAmountTy(N1.getValueType())));
2363 return DAG.getNode(ISD::TRUNCATE, DL, VT, N1);
2370 /// Perform optimizations common to nodes that compute two values. LoOp and HiOp
2371 /// give the opcodes for the two computations that are being performed. Return
2372 /// true if a simplification was made.
2373 SDValue DAGCombiner::SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp,
2375 // If the high half is not needed, just compute the low half.
2376 bool HiExists = N->hasAnyUseOfValue(1);
2378 (!LegalOperations ||
2379 TLI.isOperationLegalOrCustom(LoOp, N->getValueType(0)))) {
2380 SDValue Res = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0), N->ops());
2381 return CombineTo(N, Res, Res);
2384 // If the low half is not needed, just compute the high half.
2385 bool LoExists = N->hasAnyUseOfValue(0);
2387 (!LegalOperations ||
2388 TLI.isOperationLegal(HiOp, N->getValueType(1)))) {
2389 SDValue Res = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1), N->ops());
2390 return CombineTo(N, Res, Res);
2393 // If both halves are used, return as it is.
2394 if (LoExists && HiExists)
2397 // If the two computed results can be simplified separately, separate them.
2399 SDValue Lo = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0), N->ops());
2400 AddToWorklist(Lo.getNode());
2401 SDValue LoOpt = combine(Lo.getNode());
2402 if (LoOpt.getNode() && LoOpt.getNode() != Lo.getNode() &&
2403 (!LegalOperations ||
2404 TLI.isOperationLegal(LoOpt.getOpcode(), LoOpt.getValueType())))
2405 return CombineTo(N, LoOpt, LoOpt);
2409 SDValue Hi = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1), N->ops());
2410 AddToWorklist(Hi.getNode());
2411 SDValue HiOpt = combine(Hi.getNode());
2412 if (HiOpt.getNode() && HiOpt != Hi &&
2413 (!LegalOperations ||
2414 TLI.isOperationLegal(HiOpt.getOpcode(), HiOpt.getValueType())))
2415 return CombineTo(N, HiOpt, HiOpt);
2421 SDValue DAGCombiner::visitSMUL_LOHI(SDNode *N) {
2422 SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHS);
2423 if (Res.getNode()) return Res;
2425 EVT VT = N->getValueType(0);
2428 // If the type twice as wide is legal, transform the mulhu to a wider multiply
2430 if (VT.isSimple() && !VT.isVector()) {
2431 MVT Simple = VT.getSimpleVT();
2432 unsigned SimpleSize = Simple.getSizeInBits();
2433 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2434 if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2435 SDValue Lo = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(0));
2436 SDValue Hi = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(1));
2437 Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi);
2438 // Compute the high part as N1.
2439 Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo,
2440 DAG.getConstant(SimpleSize, getShiftAmountTy(Lo.getValueType())));
2441 Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi);
2442 // Compute the low part as N0.
2443 Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo);
2444 return CombineTo(N, Lo, Hi);
2451 SDValue DAGCombiner::visitUMUL_LOHI(SDNode *N) {
2452 SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHU);
2453 if (Res.getNode()) return Res;
2455 EVT VT = N->getValueType(0);
2458 // If the type twice as wide is legal, transform the mulhu to a wider multiply
2460 if (VT.isSimple() && !VT.isVector()) {
2461 MVT Simple = VT.getSimpleVT();
2462 unsigned SimpleSize = Simple.getSizeInBits();
2463 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2464 if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2465 SDValue Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(0));
2466 SDValue Hi = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(1));
2467 Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi);
2468 // Compute the high part as N1.
2469 Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo,
2470 DAG.getConstant(SimpleSize, getShiftAmountTy(Lo.getValueType())));
2471 Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi);
2472 // Compute the low part as N0.
2473 Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo);
2474 return CombineTo(N, Lo, Hi);
2481 SDValue DAGCombiner::visitSMULO(SDNode *N) {
2482 // (smulo x, 2) -> (saddo x, x)
2483 if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1)))
2484 if (C2->getAPIntValue() == 2)
2485 return DAG.getNode(ISD::SADDO, SDLoc(N), N->getVTList(),
2486 N->getOperand(0), N->getOperand(0));
2491 SDValue DAGCombiner::visitUMULO(SDNode *N) {
2492 // (umulo x, 2) -> (uaddo x, x)
2493 if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1)))
2494 if (C2->getAPIntValue() == 2)
2495 return DAG.getNode(ISD::UADDO, SDLoc(N), N->getVTList(),
2496 N->getOperand(0), N->getOperand(0));
2501 SDValue DAGCombiner::visitSDIVREM(SDNode *N) {
2502 SDValue Res = SimplifyNodeWithTwoResults(N, ISD::SDIV, ISD::SREM);
2503 if (Res.getNode()) return Res;
2508 SDValue DAGCombiner::visitUDIVREM(SDNode *N) {
2509 SDValue Res = SimplifyNodeWithTwoResults(N, ISD::UDIV, ISD::UREM);
2510 if (Res.getNode()) return Res;
2515 /// If this is a binary operator with two operands of the same opcode, try to
2517 SDValue DAGCombiner::SimplifyBinOpWithSameOpcodeHands(SDNode *N) {
2518 SDValue N0 = N->getOperand(0), N1 = N->getOperand(1);
2519 EVT VT = N0.getValueType();
2520 assert(N0.getOpcode() == N1.getOpcode() && "Bad input!");
2522 // Bail early if none of these transforms apply.
2523 if (N0.getNode()->getNumOperands() == 0) return SDValue();
2525 // For each of OP in AND/OR/XOR:
2526 // fold (OP (zext x), (zext y)) -> (zext (OP x, y))
2527 // fold (OP (sext x), (sext y)) -> (sext (OP x, y))
2528 // fold (OP (aext x), (aext y)) -> (aext (OP x, y))
2529 // fold (OP (bswap x), (bswap y)) -> (bswap (OP x, y))
2530 // fold (OP (trunc x), (trunc y)) -> (trunc (OP x, y)) (if trunc isn't free)
2532 // do not sink logical op inside of a vector extend, since it may combine
2534 EVT Op0VT = N0.getOperand(0).getValueType();
2535 if ((N0.getOpcode() == ISD::ZERO_EXTEND ||
2536 N0.getOpcode() == ISD::SIGN_EXTEND ||
2537 N0.getOpcode() == ISD::BSWAP ||
2538 // Avoid infinite looping with PromoteIntBinOp.
2539 (N0.getOpcode() == ISD::ANY_EXTEND &&
2540 (!LegalTypes || TLI.isTypeDesirableForOp(N->getOpcode(), Op0VT))) ||
2541 (N0.getOpcode() == ISD::TRUNCATE &&
2542 (!TLI.isZExtFree(VT, Op0VT) ||
2543 !TLI.isTruncateFree(Op0VT, VT)) &&
2544 TLI.isTypeLegal(Op0VT))) &&
2546 Op0VT == N1.getOperand(0).getValueType() &&
2547 (!LegalOperations || TLI.isOperationLegal(N->getOpcode(), Op0VT))) {
2548 SDValue ORNode = DAG.getNode(N->getOpcode(), SDLoc(N0),
2549 N0.getOperand(0).getValueType(),
2550 N0.getOperand(0), N1.getOperand(0));
2551 AddToWorklist(ORNode.getNode());
2552 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, ORNode);
2555 // For each of OP in SHL/SRL/SRA/AND...
2556 // fold (and (OP x, z), (OP y, z)) -> (OP (and x, y), z)
2557 // fold (or (OP x, z), (OP y, z)) -> (OP (or x, y), z)
2558 // fold (xor (OP x, z), (OP y, z)) -> (OP (xor x, y), z)
2559 if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL ||
2560 N0.getOpcode() == ISD::SRA || N0.getOpcode() == ISD::AND) &&
2561 N0.getOperand(1) == N1.getOperand(1)) {
2562 SDValue ORNode = DAG.getNode(N->getOpcode(), SDLoc(N0),
2563 N0.getOperand(0).getValueType(),
2564 N0.getOperand(0), N1.getOperand(0));
2565 AddToWorklist(ORNode.getNode());
2566 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
2567 ORNode, N0.getOperand(1));
2570 // Simplify xor/and/or (bitcast(A), bitcast(B)) -> bitcast(op (A,B))
2571 // Only perform this optimization after type legalization and before
2572 // LegalizeVectorOprs. LegalizeVectorOprs promotes vector operations by
2573 // adding bitcasts. For example (xor v4i32) is promoted to (v2i64), and
2574 // we don't want to undo this promotion.
2575 // We also handle SCALAR_TO_VECTOR because xor/or/and operations are cheaper
2577 if ((N0.getOpcode() == ISD::BITCAST ||
2578 N0.getOpcode() == ISD::SCALAR_TO_VECTOR) &&
2579 Level == AfterLegalizeTypes) {
2580 SDValue In0 = N0.getOperand(0);
2581 SDValue In1 = N1.getOperand(0);
2582 EVT In0Ty = In0.getValueType();
2583 EVT In1Ty = In1.getValueType();
2585 // If both incoming values are integers, and the original types are the
2587 if (In0Ty.isInteger() && In1Ty.isInteger() && In0Ty == In1Ty) {
2588 SDValue Op = DAG.getNode(N->getOpcode(), DL, In0Ty, In0, In1);
2589 SDValue BC = DAG.getNode(N0.getOpcode(), DL, VT, Op);
2590 AddToWorklist(Op.getNode());
2595 // Xor/and/or are indifferent to the swizzle operation (shuffle of one value).
2596 // Simplify xor/and/or (shuff(A), shuff(B)) -> shuff(op (A,B))
2597 // If both shuffles use the same mask, and both shuffle within a single
2598 // vector, then it is worthwhile to move the swizzle after the operation.
2599 // The type-legalizer generates this pattern when loading illegal
2600 // vector types from memory. In many cases this allows additional shuffle
2602 // There are other cases where moving the shuffle after the xor/and/or
2603 // is profitable even if shuffles don't perform a swizzle.
2604 // If both shuffles use the same mask, and both shuffles have the same first
2605 // or second operand, then it might still be profitable to move the shuffle
2606 // after the xor/and/or operation.
2607 if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG) {
2608 ShuffleVectorSDNode *SVN0 = cast<ShuffleVectorSDNode>(N0);
2609 ShuffleVectorSDNode *SVN1 = cast<ShuffleVectorSDNode>(N1);
2611 assert(N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType() &&
2612 "Inputs to shuffles are not the same type");
2614 // Check that both shuffles use the same mask. The masks are known to be of
2615 // the same length because the result vector type is the same.
2616 // Check also that shuffles have only one use to avoid introducing extra
2618 if (SVN0->hasOneUse() && SVN1->hasOneUse() &&
2619 SVN0->getMask().equals(SVN1->getMask())) {
2620 SDValue ShOp = N0->getOperand(1);
2622 // Don't try to fold this node if it requires introducing a
2623 // build vector of all zeros that might be illegal at this stage.
2624 if (N->getOpcode() == ISD::XOR && ShOp.getOpcode() != ISD::UNDEF) {
2626 ShOp = DAG.getConstant(0, VT);
2631 // (AND (shuf (A, C), shuf (B, C)) -> shuf (AND (A, B), C)
2632 // (OR (shuf (A, C), shuf (B, C)) -> shuf (OR (A, B), C)
2633 // (XOR (shuf (A, C), shuf (B, C)) -> shuf (XOR (A, B), V_0)
2634 if (N0.getOperand(1) == N1.getOperand(1) && ShOp.getNode()) {
2635 SDValue NewNode = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
2636 N0->getOperand(0), N1->getOperand(0));
2637 AddToWorklist(NewNode.getNode());
2638 return DAG.getVectorShuffle(VT, SDLoc(N), NewNode, ShOp,
2639 &SVN0->getMask()[0]);
2642 // Don't try to fold this node if it requires introducing a
2643 // build vector of all zeros that might be illegal at this stage.
2644 ShOp = N0->getOperand(0);
2645 if (N->getOpcode() == ISD::XOR && ShOp.getOpcode() != ISD::UNDEF) {
2647 ShOp = DAG.getConstant(0, VT);
2652 // (AND (shuf (C, A), shuf (C, B)) -> shuf (C, AND (A, B))
2653 // (OR (shuf (C, A), shuf (C, B)) -> shuf (C, OR (A, B))
2654 // (XOR (shuf (C, A), shuf (C, B)) -> shuf (V_0, XOR (A, B))
2655 if (N0->getOperand(0) == N1->getOperand(0) && ShOp.getNode()) {
2656 SDValue NewNode = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
2657 N0->getOperand(1), N1->getOperand(1));
2658 AddToWorklist(NewNode.getNode());
2659 return DAG.getVectorShuffle(VT, SDLoc(N), ShOp, NewNode,
2660 &SVN0->getMask()[0]);
2668 SDValue DAGCombiner::visitAND(SDNode *N) {
2669 SDValue N0 = N->getOperand(0);
2670 SDValue N1 = N->getOperand(1);
2671 SDValue LL, LR, RL, RR, CC0, CC1;
2672 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
2673 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2674 EVT VT = N1.getValueType();
2675 unsigned BitWidth = VT.getScalarType().getSizeInBits();
2678 if (VT.isVector()) {
2679 SDValue FoldedVOp = SimplifyVBinOp(N);
2680 if (FoldedVOp.getNode()) return FoldedVOp;
2682 // fold (and x, 0) -> 0, vector edition
2683 if (ISD::isBuildVectorAllZeros(N0.getNode()))
2684 // do not return N0, because undef node may exist in N0
2685 return DAG.getConstant(
2686 APInt::getNullValue(
2687 N0.getValueType().getScalarType().getSizeInBits()),
2689 if (ISD::isBuildVectorAllZeros(N1.getNode()))
2690 // do not return N1, because undef node may exist in N1
2691 return DAG.getConstant(
2692 APInt::getNullValue(
2693 N1.getValueType().getScalarType().getSizeInBits()),
2696 // fold (and x, -1) -> x, vector edition
2697 if (ISD::isBuildVectorAllOnes(N0.getNode()))
2699 if (ISD::isBuildVectorAllOnes(N1.getNode()))
2703 // fold (and x, undef) -> 0
2704 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2705 return DAG.getConstant(0, VT);
2706 // fold (and c1, c2) -> c1&c2
2708 return DAG.FoldConstantArithmetic(ISD::AND, VT, N0C, N1C);
2709 // canonicalize constant to RHS
2711 return DAG.getNode(ISD::AND, SDLoc(N), VT, N1, N0);
2712 // fold (and x, -1) -> x
2713 if (N1C && N1C->isAllOnesValue())
2715 // if (and x, c) is known to be zero, return 0
2716 if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0),
2717 APInt::getAllOnesValue(BitWidth)))
2718 return DAG.getConstant(0, VT);
2720 SDValue RAND = ReassociateOps(ISD::AND, SDLoc(N), N0, N1);
2723 // fold (and (or x, C), D) -> D if (C & D) == D
2724 if (N1C && N0.getOpcode() == ISD::OR)
2725 if (ConstantSDNode *ORI = dyn_cast<ConstantSDNode>(N0.getOperand(1)))
2726 if ((ORI->getAPIntValue() & N1C->getAPIntValue()) == N1C->getAPIntValue())
2728 // fold (and (any_ext V), c) -> (zero_ext V) if 'and' only clears top bits.
2729 if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
2730 SDValue N0Op0 = N0.getOperand(0);
2731 APInt Mask = ~N1C->getAPIntValue();
2732 Mask = Mask.trunc(N0Op0.getValueSizeInBits());
2733 if (DAG.MaskedValueIsZero(N0Op0, Mask)) {
2734 SDValue Zext = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N),
2735 N0.getValueType(), N0Op0);
2737 // Replace uses of the AND with uses of the Zero extend node.
2740 // We actually want to replace all uses of the any_extend with the
2741 // zero_extend, to avoid duplicating things. This will later cause this
2742 // AND to be folded.
2743 CombineTo(N0.getNode(), Zext);
2744 return SDValue(N, 0); // Return N so it doesn't get rechecked!
2747 // similarly fold (and (X (load ([non_ext|any_ext|zero_ext] V))), c) ->
2748 // (X (load ([non_ext|zero_ext] V))) if 'and' only clears top bits which must
2749 // already be zero by virtue of the width of the base type of the load.
2751 // the 'X' node here can either be nothing or an extract_vector_elt to catch
2753 if ((N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
2754 N0.getOperand(0).getOpcode() == ISD::LOAD) ||
2755 N0.getOpcode() == ISD::LOAD) {
2756 LoadSDNode *Load = cast<LoadSDNode>( (N0.getOpcode() == ISD::LOAD) ?
2757 N0 : N0.getOperand(0) );
2759 // Get the constant (if applicable) the zero'th operand is being ANDed with.
2760 // This can be a pure constant or a vector splat, in which case we treat the
2761 // vector as a scalar and use the splat value.
2762 APInt Constant = APInt::getNullValue(1);
2763 if (const ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
2764 Constant = C->getAPIntValue();
2765 } else if (BuildVectorSDNode *Vector = dyn_cast<BuildVectorSDNode>(N1)) {
2766 APInt SplatValue, SplatUndef;
2767 unsigned SplatBitSize;
2769 bool IsSplat = Vector->isConstantSplat(SplatValue, SplatUndef,
2770 SplatBitSize, HasAnyUndefs);
2772 // Undef bits can contribute to a possible optimisation if set, so
2774 SplatValue |= SplatUndef;
2776 // The splat value may be something like "0x00FFFFFF", which means 0 for
2777 // the first vector value and FF for the rest, repeating. We need a mask
2778 // that will apply equally to all members of the vector, so AND all the
2779 // lanes of the constant together.
2780 EVT VT = Vector->getValueType(0);
2781 unsigned BitWidth = VT.getVectorElementType().getSizeInBits();
2783 // If the splat value has been compressed to a bitlength lower
2784 // than the size of the vector lane, we need to re-expand it to
2786 if (BitWidth > SplatBitSize)
2787 for (SplatValue = SplatValue.zextOrTrunc(BitWidth);
2788 SplatBitSize < BitWidth;
2789 SplatBitSize = SplatBitSize * 2)
2790 SplatValue |= SplatValue.shl(SplatBitSize);
2792 Constant = APInt::getAllOnesValue(BitWidth);
2793 for (unsigned i = 0, n = SplatBitSize/BitWidth; i < n; ++i)
2794 Constant &= SplatValue.lshr(i*BitWidth).zextOrTrunc(BitWidth);
2798 // If we want to change an EXTLOAD to a ZEXTLOAD, ensure a ZEXTLOAD is
2799 // actually legal and isn't going to get expanded, else this is a false
2801 bool CanZextLoadProfitably = TLI.isLoadExtLegal(ISD::ZEXTLOAD,
2802 Load->getMemoryVT());
2804 // Resize the constant to the same size as the original memory access before
2805 // extension. If it is still the AllOnesValue then this AND is completely
2808 Constant.zextOrTrunc(Load->getMemoryVT().getScalarType().getSizeInBits());
2811 switch (Load->getExtensionType()) {
2812 default: B = false; break;
2813 case ISD::EXTLOAD: B = CanZextLoadProfitably; break;
2815 case ISD::NON_EXTLOAD: B = true; break;
2818 if (B && Constant.isAllOnesValue()) {
2819 // If the load type was an EXTLOAD, convert to ZEXTLOAD in order to
2820 // preserve semantics once we get rid of the AND.
2821 SDValue NewLoad(Load, 0);
2822 if (Load->getExtensionType() == ISD::EXTLOAD) {
2823 NewLoad = DAG.getLoad(Load->getAddressingMode(), ISD::ZEXTLOAD,
2824 Load->getValueType(0), SDLoc(Load),
2825 Load->getChain(), Load->getBasePtr(),
2826 Load->getOffset(), Load->getMemoryVT(),
2827 Load->getMemOperand());
2828 // Replace uses of the EXTLOAD with the new ZEXTLOAD.
2829 if (Load->getNumValues() == 3) {
2830 // PRE/POST_INC loads have 3 values.
2831 SDValue To[] = { NewLoad.getValue(0), NewLoad.getValue(1),
2832 NewLoad.getValue(2) };
2833 CombineTo(Load, To, 3, true);
2835 CombineTo(Load, NewLoad.getValue(0), NewLoad.getValue(1));
2839 // Fold the AND away, taking care not to fold to the old load node if we
2841 CombineTo(N, (N0.getNode() == Load) ? NewLoad : N0);
2843 return SDValue(N, 0); // Return N so it doesn't get rechecked!
2846 // fold (and (setcc x), (setcc y)) -> (setcc (and x, y))
2847 if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){
2848 ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get();
2849 ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get();
2851 if (LR == RR && isa<ConstantSDNode>(LR) && Op0 == Op1 &&
2852 LL.getValueType().isInteger()) {
2853 // fold (and (seteq X, 0), (seteq Y, 0)) -> (seteq (or X, Y), 0)
2854 if (cast<ConstantSDNode>(LR)->isNullValue() && Op1 == ISD::SETEQ) {
2855 SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(N0),
2856 LR.getValueType(), LL, RL);
2857 AddToWorklist(ORNode.getNode());
2858 return DAG.getSetCC(SDLoc(N), VT, ORNode, LR, Op1);
2860 // fold (and (seteq X, -1), (seteq Y, -1)) -> (seteq (and X, Y), -1)
2861 if (cast<ConstantSDNode>(LR)->isAllOnesValue() && Op1 == ISD::SETEQ) {
2862 SDValue ANDNode = DAG.getNode(ISD::AND, SDLoc(N0),
2863 LR.getValueType(), LL, RL);
2864 AddToWorklist(ANDNode.getNode());
2865 return DAG.getSetCC(SDLoc(N), VT, ANDNode, LR, Op1);
2867 // fold (and (setgt X, -1), (setgt Y, -1)) -> (setgt (or X, Y), -1)
2868 if (cast<ConstantSDNode>(LR)->isAllOnesValue() && Op1 == ISD::SETGT) {
2869 SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(N0),
2870 LR.getValueType(), LL, RL);
2871 AddToWorklist(ORNode.getNode());
2872 return DAG.getSetCC(SDLoc(N), VT, ORNode, LR, Op1);
2875 // Simplify (and (setne X, 0), (setne X, -1)) -> (setuge (add X, 1), 2)
2876 if (LL == RL && isa<ConstantSDNode>(LR) && isa<ConstantSDNode>(RR) &&
2877 Op0 == Op1 && LL.getValueType().isInteger() &&
2878 Op0 == ISD::SETNE && ((cast<ConstantSDNode>(LR)->isNullValue() &&
2879 cast<ConstantSDNode>(RR)->isAllOnesValue()) ||
2880 (cast<ConstantSDNode>(LR)->isAllOnesValue() &&
2881 cast<ConstantSDNode>(RR)->isNullValue()))) {
2882 SDValue ADDNode = DAG.getNode(ISD::ADD, SDLoc(N0), LL.getValueType(),
2883 LL, DAG.getConstant(1, LL.getValueType()));
2884 AddToWorklist(ADDNode.getNode());
2885 return DAG.getSetCC(SDLoc(N), VT, ADDNode,
2886 DAG.getConstant(2, LL.getValueType()), ISD::SETUGE);
2888 // canonicalize equivalent to ll == rl
2889 if (LL == RR && LR == RL) {
2890 Op1 = ISD::getSetCCSwappedOperands(Op1);
2893 if (LL == RL && LR == RR) {
2894 bool isInteger = LL.getValueType().isInteger();
2895 ISD::CondCode Result = ISD::getSetCCAndOperation(Op0, Op1, isInteger);
2896 if (Result != ISD::SETCC_INVALID &&
2897 (!LegalOperations ||
2898 (TLI.isCondCodeLegal(Result, LL.getSimpleValueType()) &&
2899 TLI.isOperationLegal(ISD::SETCC,
2900 getSetCCResultType(N0.getSimpleValueType())))))
2901 return DAG.getSetCC(SDLoc(N), N0.getValueType(),
2906 // Simplify: (and (op x...), (op y...)) -> (op (and x, y))
2907 if (N0.getOpcode() == N1.getOpcode()) {
2908 SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
2909 if (Tmp.getNode()) return Tmp;
2912 // fold (and (sign_extend_inreg x, i16 to i32), 1) -> (and x, 1)
2913 // fold (and (sra)) -> (and (srl)) when possible.
2914 if (!VT.isVector() &&
2915 SimplifyDemandedBits(SDValue(N, 0)))
2916 return SDValue(N, 0);
2918 // fold (zext_inreg (extload x)) -> (zextload x)
2919 if (ISD::isEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode())) {
2920 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
2921 EVT MemVT = LN0->getMemoryVT();
2922 // If we zero all the possible extended bits, then we can turn this into
2923 // a zextload if we are running before legalize or the operation is legal.
2924 unsigned BitWidth = N1.getValueType().getScalarType().getSizeInBits();
2925 if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth,
2926 BitWidth - MemVT.getScalarType().getSizeInBits())) &&
2927 ((!LegalOperations && !LN0->isVolatile()) ||
2928 TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT))) {
2929 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N0), VT,
2930 LN0->getChain(), LN0->getBasePtr(),
2931 MemVT, LN0->getMemOperand());
2933 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
2934 return SDValue(N, 0); // Return N so it doesn't get rechecked!
2937 // fold (zext_inreg (sextload x)) -> (zextload x) iff load has one use
2938 if (ISD::isSEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
2940 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
2941 EVT MemVT = LN0->getMemoryVT();
2942 // If we zero all the possible extended bits, then we can turn this into
2943 // a zextload if we are running before legalize or the operation is legal.
2944 unsigned BitWidth = N1.getValueType().getScalarType().getSizeInBits();
2945 if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth,
2946 BitWidth - MemVT.getScalarType().getSizeInBits())) &&
2947 ((!LegalOperations && !LN0->isVolatile()) ||
2948 TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT))) {
2949 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N0), VT,
2950 LN0->getChain(), LN0->getBasePtr(),
2951 MemVT, LN0->getMemOperand());
2953 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
2954 return SDValue(N, 0); // Return N so it doesn't get rechecked!
2958 // fold (and (load x), 255) -> (zextload x, i8)
2959 // fold (and (extload x, i16), 255) -> (zextload x, i8)
2960 // fold (and (any_ext (extload x, i16)), 255) -> (zextload x, i8)
2961 if (N1C && (N0.getOpcode() == ISD::LOAD ||
2962 (N0.getOpcode() == ISD::ANY_EXTEND &&
2963 N0.getOperand(0).getOpcode() == ISD::LOAD))) {
2964 bool HasAnyExt = N0.getOpcode() == ISD::ANY_EXTEND;
2965 LoadSDNode *LN0 = HasAnyExt
2966 ? cast<LoadSDNode>(N0.getOperand(0))
2967 : cast<LoadSDNode>(N0);
2968 if (LN0->getExtensionType() != ISD::SEXTLOAD &&
2969 LN0->isUnindexed() && N0.hasOneUse() && SDValue(LN0, 0).hasOneUse()) {
2970 uint32_t ActiveBits = N1C->getAPIntValue().getActiveBits();
2971 if (ActiveBits > 0 && APIntOps::isMask(ActiveBits, N1C->getAPIntValue())){
2972 EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), ActiveBits);
2973 EVT LoadedVT = LN0->getMemoryVT();
2975 if (ExtVT == LoadedVT &&
2976 (!LegalOperations || TLI.isLoadExtLegal(ISD::ZEXTLOAD, ExtVT))) {
2977 EVT LoadResultTy = HasAnyExt ? LN0->getValueType(0) : VT;
2980 DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), LoadResultTy,
2981 LN0->getChain(), LN0->getBasePtr(), ExtVT,
2982 LN0->getMemOperand());
2984 CombineTo(LN0, NewLoad, NewLoad.getValue(1));
2985 return SDValue(N, 0); // Return N so it doesn't get rechecked!
2988 // Do not change the width of a volatile load.
2989 // Do not generate loads of non-round integer types since these can
2990 // be expensive (and would be wrong if the type is not byte sized).
2991 if (!LN0->isVolatile() && LoadedVT.bitsGT(ExtVT) && ExtVT.isRound() &&
2992 (!LegalOperations || TLI.isLoadExtLegal(ISD::ZEXTLOAD, ExtVT))) {
2993 EVT PtrType = LN0->getOperand(1).getValueType();
2995 unsigned Alignment = LN0->getAlignment();
2996 SDValue NewPtr = LN0->getBasePtr();
2998 // For big endian targets, we need to add an offset to the pointer
2999 // to load the correct bytes. For little endian systems, we merely
3000 // need to read fewer bytes from the same pointer.
3001 if (TLI.isBigEndian()) {
3002 unsigned LVTStoreBytes = LoadedVT.getStoreSize();
3003 unsigned EVTStoreBytes = ExtVT.getStoreSize();
3004 unsigned PtrOff = LVTStoreBytes - EVTStoreBytes;
3005 NewPtr = DAG.getNode(ISD::ADD, SDLoc(LN0), PtrType,
3006 NewPtr, DAG.getConstant(PtrOff, PtrType));
3007 Alignment = MinAlign(Alignment, PtrOff);
3010 AddToWorklist(NewPtr.getNode());
3012 EVT LoadResultTy = HasAnyExt ? LN0->getValueType(0) : VT;
3014 DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), LoadResultTy,
3015 LN0->getChain(), NewPtr,
3016 LN0->getPointerInfo(),
3017 ExtVT, LN0->isVolatile(), LN0->isNonTemporal(),
3018 LN0->isInvariant(), Alignment, LN0->getAAInfo());
3020 CombineTo(LN0, Load, Load.getValue(1));
3021 return SDValue(N, 0); // Return N so it doesn't get rechecked!
3027 if (N0.getOpcode() == ISD::ADD && N1.getOpcode() == ISD::SRL &&
3028 VT.getSizeInBits() <= 64) {
3029 if (ConstantSDNode *ADDI = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
3030 APInt ADDC = ADDI->getAPIntValue();
3031 if (!TLI.isLegalAddImmediate(ADDC.getSExtValue())) {
3032 // Look for (and (add x, c1), (lshr y, c2)). If C1 wasn't a legal
3033 // immediate for an add, but it is legal if its top c2 bits are set,
3034 // transform the ADD so the immediate doesn't need to be materialized
3036 if (ConstantSDNode *SRLI = dyn_cast<ConstantSDNode>(N1.getOperand(1))) {
3037 APInt Mask = APInt::getHighBitsSet(VT.getSizeInBits(),
3038 SRLI->getZExtValue());
3039 if (DAG.MaskedValueIsZero(N0.getOperand(1), Mask)) {
3041 if (TLI.isLegalAddImmediate(ADDC.getSExtValue())) {
3043 DAG.getNode(ISD::ADD, SDLoc(N0), VT,
3044 N0.getOperand(0), DAG.getConstant(ADDC, VT));
3045 CombineTo(N0.getNode(), NewAdd);
3046 return SDValue(N, 0); // Return N so it doesn't get rechecked!
3054 // fold (and (or (srl N, 8), (shl N, 8)), 0xffff) -> (srl (bswap N), const)
3055 if (N1C && N1C->getAPIntValue() == 0xffff && N0.getOpcode() == ISD::OR) {
3056 SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0),
3057 N0.getOperand(1), false);
3058 if (BSwap.getNode())
3065 /// Match (a >> 8) | (a << 8) as (bswap a) >> 16.
3066 SDValue DAGCombiner::MatchBSwapHWordLow(SDNode *N, SDValue N0, SDValue N1,
3067 bool DemandHighBits) {
3068 if (!LegalOperations)
3071 EVT VT = N->getValueType(0);
3072 if (VT != MVT::i64 && VT != MVT::i32 && VT != MVT::i16)
3074 if (!TLI.isOperationLegal(ISD::BSWAP, VT))
3077 // Recognize (and (shl a, 8), 0xff), (and (srl a, 8), 0xff00)
3078 bool LookPassAnd0 = false;
3079 bool LookPassAnd1 = false;
3080 if (N0.getOpcode() == ISD::AND && N0.getOperand(0).getOpcode() == ISD::SRL)
3082 if (N1.getOpcode() == ISD::AND && N1.getOperand(0).getOpcode() == ISD::SHL)
3084 if (N0.getOpcode() == ISD::AND) {
3085 if (!N0.getNode()->hasOneUse())
3087 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3088 if (!N01C || N01C->getZExtValue() != 0xFF00)
3090 N0 = N0.getOperand(0);
3091 LookPassAnd0 = true;
3094 if (N1.getOpcode() == ISD::AND) {
3095 if (!N1.getNode()->hasOneUse())
3097 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
3098 if (!N11C || N11C->getZExtValue() != 0xFF)
3100 N1 = N1.getOperand(0);
3101 LookPassAnd1 = true;
3104 if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
3106 if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
3108 if (!N0.getNode()->hasOneUse() ||
3109 !N1.getNode()->hasOneUse())
3112 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3113 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
3116 if (N01C->getZExtValue() != 8 || N11C->getZExtValue() != 8)
3119 // Look for (shl (and a, 0xff), 8), (srl (and a, 0xff00), 8)
3120 SDValue N00 = N0->getOperand(0);
3121 if (!LookPassAnd0 && N00.getOpcode() == ISD::AND) {
3122 if (!N00.getNode()->hasOneUse())
3124 ConstantSDNode *N001C = dyn_cast<ConstantSDNode>(N00.getOperand(1));
3125 if (!N001C || N001C->getZExtValue() != 0xFF)
3127 N00 = N00.getOperand(0);
3128 LookPassAnd0 = true;
3131 SDValue N10 = N1->getOperand(0);
3132 if (!LookPassAnd1 && N10.getOpcode() == ISD::AND) {
3133 if (!N10.getNode()->hasOneUse())
3135 ConstantSDNode *N101C = dyn_cast<ConstantSDNode>(N10.getOperand(1));
3136 if (!N101C || N101C->getZExtValue() != 0xFF00)
3138 N10 = N10.getOperand(0);
3139 LookPassAnd1 = true;
3145 // Make sure everything beyond the low halfword gets set to zero since the SRL
3146 // 16 will clear the top bits.
3147 unsigned OpSizeInBits = VT.getSizeInBits();
3148 if (DemandHighBits && OpSizeInBits > 16) {
3149 // If the left-shift isn't masked out then the only way this is a bswap is
3150 // if all bits beyond the low 8 are 0. In that case the entire pattern
3151 // reduces to a left shift anyway: leave it for other parts of the combiner.
3155 // However, if the right shift isn't masked out then it might be because
3156 // it's not needed. See if we can spot that too.
3157 if (!LookPassAnd1 &&
3158 !DAG.MaskedValueIsZero(
3159 N10, APInt::getHighBitsSet(OpSizeInBits, OpSizeInBits - 16)))
3163 SDValue Res = DAG.getNode(ISD::BSWAP, SDLoc(N), VT, N00);
3164 if (OpSizeInBits > 16)
3165 Res = DAG.getNode(ISD::SRL, SDLoc(N), VT, Res,
3166 DAG.getConstant(OpSizeInBits-16, getShiftAmountTy(VT)));
3170 /// Return true if the specified node is an element that makes up a 32-bit
3171 /// packed halfword byteswap.
3172 /// ((x & 0x000000ff) << 8) |
3173 /// ((x & 0x0000ff00) >> 8) |
3174 /// ((x & 0x00ff0000) << 8) |
3175 /// ((x & 0xff000000) >> 8)
3176 static bool isBSwapHWordElement(SDValue N, MutableArrayRef<SDNode *> Parts) {
3177 if (!N.getNode()->hasOneUse())
3180 unsigned Opc = N.getOpcode();
3181 if (Opc != ISD::AND && Opc != ISD::SHL && Opc != ISD::SRL)
3184 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3189 switch (N1C->getZExtValue()) {
3192 case 0xFF: Num = 0; break;
3193 case 0xFF00: Num = 1; break;
3194 case 0xFF0000: Num = 2; break;
3195 case 0xFF000000: Num = 3; break;
3198 // Look for (x & 0xff) << 8 as well as ((x << 8) & 0xff00).
3199 SDValue N0 = N.getOperand(0);
3200 if (Opc == ISD::AND) {
3201 if (Num == 0 || Num == 2) {
3203 // (x >> 8) & 0xff0000
3204 if (N0.getOpcode() != ISD::SRL)
3206 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3207 if (!C || C->getZExtValue() != 8)
3210 // (x << 8) & 0xff00
3211 // (x << 8) & 0xff000000
3212 if (N0.getOpcode() != ISD::SHL)
3214 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3215 if (!C || C->getZExtValue() != 8)
3218 } else if (Opc == ISD::SHL) {
3220 // (x & 0xff0000) << 8
3221 if (Num != 0 && Num != 2)
3223 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3224 if (!C || C->getZExtValue() != 8)
3226 } else { // Opc == ISD::SRL
3227 // (x & 0xff00) >> 8
3228 // (x & 0xff000000) >> 8
3229 if (Num != 1 && Num != 3)
3231 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3232 if (!C || C->getZExtValue() != 8)
3239 Parts[Num] = N0.getOperand(0).getNode();
3243 /// Match a 32-bit packed halfword bswap. That is
3244 /// ((x & 0x000000ff) << 8) |
3245 /// ((x & 0x0000ff00) >> 8) |
3246 /// ((x & 0x00ff0000) << 8) |
3247 /// ((x & 0xff000000) >> 8)
3248 /// => (rotl (bswap x), 16)
3249 SDValue DAGCombiner::MatchBSwapHWord(SDNode *N, SDValue N0, SDValue N1) {
3250 if (!LegalOperations)
3253 EVT VT = N->getValueType(0);
3256 if (!TLI.isOperationLegal(ISD::BSWAP, VT))
3260 // (or (or (and), (and)), (or (and), (and)))
3261 // (or (or (or (and), (and)), (and)), (and))
3262 if (N0.getOpcode() != ISD::OR)
3264 SDValue N00 = N0.getOperand(0);
3265 SDValue N01 = N0.getOperand(1);
3266 SDNode *Parts[4] = {};
3268 if (N1.getOpcode() == ISD::OR &&
3269 N00.getNumOperands() == 2 && N01.getNumOperands() == 2) {
3270 // (or (or (and), (and)), (or (and), (and)))
3271 SDValue N000 = N00.getOperand(0);
3272 if (!isBSwapHWordElement(N000, Parts))
3275 SDValue N001 = N00.getOperand(1);
3276 if (!isBSwapHWordElement(N001, Parts))
3278 SDValue N010 = N01.getOperand(0);
3279 if (!isBSwapHWordElement(N010, Parts))
3281 SDValue N011 = N01.getOperand(1);
3282 if (!isBSwapHWordElement(N011, Parts))
3285 // (or (or (or (and), (and)), (and)), (and))
3286 if (!isBSwapHWordElement(N1, Parts))
3288 if (!isBSwapHWordElement(N01, Parts))
3290 if (N00.getOpcode() != ISD::OR)
3292 SDValue N000 = N00.getOperand(0);
3293 if (!isBSwapHWordElement(N000, Parts))
3295 SDValue N001 = N00.getOperand(1);
3296 if (!isBSwapHWordElement(N001, Parts))
3300 // Make sure the parts are all coming from the same node.
3301 if (Parts[0] != Parts[1] || Parts[0] != Parts[2] || Parts[0] != Parts[3])
3304 SDValue BSwap = DAG.getNode(ISD::BSWAP, SDLoc(N), VT,
3305 SDValue(Parts[0],0));
3307 // Result of the bswap should be rotated by 16. If it's not legal, then
3308 // do (x << 16) | (x >> 16).
3309 SDValue ShAmt = DAG.getConstant(16, getShiftAmountTy(VT));
3310 if (TLI.isOperationLegalOrCustom(ISD::ROTL, VT))
3311 return DAG.getNode(ISD::ROTL, SDLoc(N), VT, BSwap, ShAmt);
3312 if (TLI.isOperationLegalOrCustom(ISD::ROTR, VT))
3313 return DAG.getNode(ISD::ROTR, SDLoc(N), VT, BSwap, ShAmt);
3314 return DAG.getNode(ISD::OR, SDLoc(N), VT,
3315 DAG.getNode(ISD::SHL, SDLoc(N), VT, BSwap, ShAmt),
3316 DAG.getNode(ISD::SRL, SDLoc(N), VT, BSwap, ShAmt));
3319 SDValue DAGCombiner::visitOR(SDNode *N) {
3320 SDValue N0 = N->getOperand(0);
3321 SDValue N1 = N->getOperand(1);
3322 SDValue LL, LR, RL, RR, CC0, CC1;
3323 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
3324 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
3325 EVT VT = N1.getValueType();
3328 if (VT.isVector()) {
3329 SDValue FoldedVOp = SimplifyVBinOp(N);
3330 if (FoldedVOp.getNode()) return FoldedVOp;
3332 // fold (or x, 0) -> x, vector edition
3333 if (ISD::isBuildVectorAllZeros(N0.getNode()))
3335 if (ISD::isBuildVectorAllZeros(N1.getNode()))
3338 // fold (or x, -1) -> -1, vector edition
3339 if (ISD::isBuildVectorAllOnes(N0.getNode()))
3340 // do not return N0, because undef node may exist in N0
3341 return DAG.getConstant(
3342 APInt::getAllOnesValue(
3343 N0.getValueType().getScalarType().getSizeInBits()),
3345 if (ISD::isBuildVectorAllOnes(N1.getNode()))
3346 // do not return N1, because undef node may exist in N1
3347 return DAG.getConstant(
3348 APInt::getAllOnesValue(
3349 N1.getValueType().getScalarType().getSizeInBits()),
3352 // fold (or (shuf A, V_0, MA), (shuf B, V_0, MB)) -> (shuf A, B, Mask1)
3353 // fold (or (shuf A, V_0, MA), (shuf B, V_0, MB)) -> (shuf B, A, Mask2)
3354 // Do this only if the resulting shuffle is legal.
3355 if (isa<ShuffleVectorSDNode>(N0) &&
3356 isa<ShuffleVectorSDNode>(N1) &&
3357 // Avoid folding a node with illegal type.
3358 TLI.isTypeLegal(VT) &&
3359 N0->getOperand(1) == N1->getOperand(1) &&
3360 ISD::isBuildVectorAllZeros(N0.getOperand(1).getNode())) {
3361 bool CanFold = true;
3362 unsigned NumElts = VT.getVectorNumElements();
3363 const ShuffleVectorSDNode *SV0 = cast<ShuffleVectorSDNode>(N0);
3364 const ShuffleVectorSDNode *SV1 = cast<ShuffleVectorSDNode>(N1);
3365 // We construct two shuffle masks:
3366 // - Mask1 is a shuffle mask for a shuffle with N0 as the first operand
3367 // and N1 as the second operand.
3368 // - Mask2 is a shuffle mask for a shuffle with N1 as the first operand
3369 // and N0 as the second operand.
3370 // We do this because OR is commutable and therefore there might be
3371 // two ways to fold this node into a shuffle.
3372 SmallVector<int,4> Mask1;
3373 SmallVector<int,4> Mask2;
3375 for (unsigned i = 0; i != NumElts && CanFold; ++i) {
3376 int M0 = SV0->getMaskElt(i);
3377 int M1 = SV1->getMaskElt(i);
3379 // Both shuffle indexes are undef. Propagate Undef.
3380 if (M0 < 0 && M1 < 0) {
3381 Mask1.push_back(M0);
3382 Mask2.push_back(M0);
3386 if (M0 < 0 || M1 < 0 ||
3387 (M0 < (int)NumElts && M1 < (int)NumElts) ||
3388 (M0 >= (int)NumElts && M1 >= (int)NumElts)) {
3393 Mask1.push_back(M0 < (int)NumElts ? M0 : M1 + NumElts);
3394 Mask2.push_back(M1 < (int)NumElts ? M1 : M0 + NumElts);
3398 // Fold this sequence only if the resulting shuffle is 'legal'.
3399 if (TLI.isShuffleMaskLegal(Mask1, VT))
3400 return DAG.getVectorShuffle(VT, SDLoc(N), N0->getOperand(0),
3401 N1->getOperand(0), &Mask1[0]);
3402 if (TLI.isShuffleMaskLegal(Mask2, VT))
3403 return DAG.getVectorShuffle(VT, SDLoc(N), N1->getOperand(0),
3404 N0->getOperand(0), &Mask2[0]);
3409 // fold (or x, undef) -> -1
3410 if (!LegalOperations &&
3411 (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)) {
3412 EVT EltVT = VT.isVector() ? VT.getVectorElementType() : VT;
3413 return DAG.getConstant(APInt::getAllOnesValue(EltVT.getSizeInBits()), VT);
3415 // fold (or c1, c2) -> c1|c2
3417 return DAG.FoldConstantArithmetic(ISD::OR, VT, N0C, N1C);
3418 // canonicalize constant to RHS
3420 return DAG.getNode(ISD::OR, SDLoc(N), VT, N1, N0);
3421 // fold (or x, 0) -> x
3422 if (N1C && N1C->isNullValue())
3424 // fold (or x, -1) -> -1
3425 if (N1C && N1C->isAllOnesValue())
3427 // fold (or x, c) -> c iff (x & ~c) == 0
3428 if (N1C && DAG.MaskedValueIsZero(N0, ~N1C->getAPIntValue()))
3431 // Recognize halfword bswaps as (bswap + rotl 16) or (bswap + shl 16)
3432 SDValue BSwap = MatchBSwapHWord(N, N0, N1);
3433 if (BSwap.getNode())
3435 BSwap = MatchBSwapHWordLow(N, N0, N1);
3436 if (BSwap.getNode())
3440 SDValue ROR = ReassociateOps(ISD::OR, SDLoc(N), N0, N1);
3443 // Canonicalize (or (and X, c1), c2) -> (and (or X, c2), c1|c2)
3444 // iff (c1 & c2) == 0.
3445 if (N1C && N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() &&
3446 isa<ConstantSDNode>(N0.getOperand(1))) {
3447 ConstantSDNode *C1 = cast<ConstantSDNode>(N0.getOperand(1));
3448 if ((C1->getAPIntValue() & N1C->getAPIntValue()) != 0) {
3449 SDValue COR = DAG.FoldConstantArithmetic(ISD::OR, VT, N1C, C1);
3452 return DAG.getNode(ISD::AND, SDLoc(N), VT,
3453 DAG.getNode(ISD::OR, SDLoc(N0), VT,
3454 N0.getOperand(0), N1), COR);
3457 // fold (or (setcc x), (setcc y)) -> (setcc (or x, y))
3458 if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){
3459 ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get();
3460 ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get();
3462 if (LR == RR && isa<ConstantSDNode>(LR) && Op0 == Op1 &&
3463 LL.getValueType().isInteger()) {
3464 // fold (or (setne X, 0), (setne Y, 0)) -> (setne (or X, Y), 0)
3465 // fold (or (setlt X, 0), (setlt Y, 0)) -> (setne (or X, Y), 0)
3466 if (cast<ConstantSDNode>(LR)->isNullValue() &&
3467 (Op1 == ISD::SETNE || Op1 == ISD::SETLT)) {
3468 SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(LR),
3469 LR.getValueType(), LL, RL);
3470 AddToWorklist(ORNode.getNode());
3471 return DAG.getSetCC(SDLoc(N), VT, ORNode, LR, Op1);
3473 // fold (or (setne X, -1), (setne Y, -1)) -> (setne (and X, Y), -1)
3474 // fold (or (setgt X, -1), (setgt Y -1)) -> (setgt (and X, Y), -1)
3475 if (cast<ConstantSDNode>(LR)->isAllOnesValue() &&
3476 (Op1 == ISD::SETNE || Op1 == ISD::SETGT)) {
3477 SDValue ANDNode = DAG.getNode(ISD::AND, SDLoc(LR),
3478 LR.getValueType(), LL, RL);
3479 AddToWorklist(ANDNode.getNode());
3480 return DAG.getSetCC(SDLoc(N), VT, ANDNode, LR, Op1);
3483 // canonicalize equivalent to ll == rl
3484 if (LL == RR && LR == RL) {
3485 Op1 = ISD::getSetCCSwappedOperands(Op1);
3488 if (LL == RL && LR == RR) {
3489 bool isInteger = LL.getValueType().isInteger();
3490 ISD::CondCode Result = ISD::getSetCCOrOperation(Op0, Op1, isInteger);
3491 if (Result != ISD::SETCC_INVALID &&
3492 (!LegalOperations ||
3493 (TLI.isCondCodeLegal(Result, LL.getSimpleValueType()) &&
3494 TLI.isOperationLegal(ISD::SETCC,
3495 getSetCCResultType(N0.getValueType())))))
3496 return DAG.getSetCC(SDLoc(N), N0.getValueType(),
3501 // Simplify: (or (op x...), (op y...)) -> (op (or x, y))
3502 if (N0.getOpcode() == N1.getOpcode()) {
3503 SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
3504 if (Tmp.getNode()) return Tmp;
3507 // (or (and X, C1), (and Y, C2)) -> (and (or X, Y), C3) if possible.
3508 if (N0.getOpcode() == ISD::AND &&
3509 N1.getOpcode() == ISD::AND &&
3510 N0.getOperand(1).getOpcode() == ISD::Constant &&
3511 N1.getOperand(1).getOpcode() == ISD::Constant &&
3512 // Don't increase # computations.
3513 (N0.getNode()->hasOneUse() || N1.getNode()->hasOneUse())) {
3514 // We can only do this xform if we know that bits from X that are set in C2
3515 // but not in C1 are already zero. Likewise for Y.
3516 const APInt &LHSMask =
3517 cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
3518 const APInt &RHSMask =
3519 cast<ConstantSDNode>(N1.getOperand(1))->getAPIntValue();
3521 if (DAG.MaskedValueIsZero(N0.getOperand(0), RHSMask&~LHSMask) &&
3522 DAG.MaskedValueIsZero(N1.getOperand(0), LHSMask&~RHSMask)) {
3523 SDValue X = DAG.getNode(ISD::OR, SDLoc(N0), VT,
3524 N0.getOperand(0), N1.getOperand(0));
3525 return DAG.getNode(ISD::AND, SDLoc(N), VT, X,
3526 DAG.getConstant(LHSMask | RHSMask, VT));
3530 // See if this is some rotate idiom.
3531 if (SDNode *Rot = MatchRotate(N0, N1, SDLoc(N)))
3532 return SDValue(Rot, 0);
3534 // Simplify the operands using demanded-bits information.
3535 if (!VT.isVector() &&
3536 SimplifyDemandedBits(SDValue(N, 0)))
3537 return SDValue(N, 0);
3542 /// Match "(X shl/srl V1) & V2" where V2 may not be present.
3543 static bool MatchRotateHalf(SDValue Op, SDValue &Shift, SDValue &Mask) {
3544 if (Op.getOpcode() == ISD::AND) {
3545 if (isa<ConstantSDNode>(Op.getOperand(1))) {
3546 Mask = Op.getOperand(1);
3547 Op = Op.getOperand(0);
3553 if (Op.getOpcode() == ISD::SRL || Op.getOpcode() == ISD::SHL) {
3561 // Return true if we can prove that, whenever Neg and Pos are both in the
3562 // range [0, OpSize), Neg == (Pos == 0 ? 0 : OpSize - Pos). This means that
3563 // for two opposing shifts shift1 and shift2 and a value X with OpBits bits:
3565 // (or (shift1 X, Neg), (shift2 X, Pos))
3567 // reduces to a rotate in direction shift2 by Pos or (equivalently) a rotate
3568 // in direction shift1 by Neg. The range [0, OpSize) means that we only need
3569 // to consider shift amounts with defined behavior.
3570 static bool matchRotateSub(SDValue Pos, SDValue Neg, unsigned OpSize) {
3571 // If OpSize is a power of 2 then:
3573 // (a) (Pos == 0 ? 0 : OpSize - Pos) == (OpSize - Pos) & (OpSize - 1)
3574 // (b) Neg == Neg & (OpSize - 1) whenever Neg is in [0, OpSize).
3576 // So if OpSize is a power of 2 and Neg is (and Neg', OpSize-1), we check
3577 // for the stronger condition:
3579 // Neg & (OpSize - 1) == (OpSize - Pos) & (OpSize - 1) [A]
3581 // for all Neg and Pos. Since Neg & (OpSize - 1) == Neg' & (OpSize - 1)
3582 // we can just replace Neg with Neg' for the rest of the function.
3584 // In other cases we check for the even stronger condition:
3586 // Neg == OpSize - Pos [B]
3588 // for all Neg and Pos. Note that the (or ...) then invokes undefined
3589 // behavior if Pos == 0 (and consequently Neg == OpSize).
3591 // We could actually use [A] whenever OpSize is a power of 2, but the
3592 // only extra cases that it would match are those uninteresting ones
3593 // where Neg and Pos are never in range at the same time. E.g. for
3594 // OpSize == 32, using [A] would allow a Neg of the form (sub 64, Pos)
3595 // as well as (sub 32, Pos), but:
3597 // (or (shift1 X, (sub 64, Pos)), (shift2 X, Pos))
3599 // always invokes undefined behavior for 32-bit X.
3601 // Below, Mask == OpSize - 1 when using [A] and is all-ones otherwise.
3602 unsigned MaskLoBits = 0;
3603 if (Neg.getOpcode() == ISD::AND &&
3604 isPowerOf2_64(OpSize) &&
3605 Neg.getOperand(1).getOpcode() == ISD::Constant &&
3606 cast<ConstantSDNode>(Neg.getOperand(1))->getAPIntValue() == OpSize - 1) {
3607 Neg = Neg.getOperand(0);
3608 MaskLoBits = Log2_64(OpSize);
3611 // Check whether Neg has the form (sub NegC, NegOp1) for some NegC and NegOp1.
3612 if (Neg.getOpcode() != ISD::SUB)
3614 ConstantSDNode *NegC = dyn_cast<ConstantSDNode>(Neg.getOperand(0));
3617 SDValue NegOp1 = Neg.getOperand(1);
3619 // On the RHS of [A], if Pos is Pos' & (OpSize - 1), just replace Pos with
3620 // Pos'. The truncation is redundant for the purpose of the equality.
3622 Pos.getOpcode() == ISD::AND &&
3623 Pos.getOperand(1).getOpcode() == ISD::Constant &&
3624 cast<ConstantSDNode>(Pos.getOperand(1))->getAPIntValue() == OpSize - 1)
3625 Pos = Pos.getOperand(0);
3627 // The condition we need is now:
3629 // (NegC - NegOp1) & Mask == (OpSize - Pos) & Mask
3631 // If NegOp1 == Pos then we need:
3633 // OpSize & Mask == NegC & Mask
3635 // (because "x & Mask" is a truncation and distributes through subtraction).
3638 Width = NegC->getAPIntValue();
3639 // Check for cases where Pos has the form (add NegOp1, PosC) for some PosC.
3640 // Then the condition we want to prove becomes:
3642 // (NegC - NegOp1) & Mask == (OpSize - (NegOp1 + PosC)) & Mask
3644 // which, again because "x & Mask" is a truncation, becomes:
3646 // NegC & Mask == (OpSize - PosC) & Mask
3647 // OpSize & Mask == (NegC + PosC) & Mask
3648 else if (Pos.getOpcode() == ISD::ADD &&
3649 Pos.getOperand(0) == NegOp1 &&
3650 Pos.getOperand(1).getOpcode() == ISD::Constant)
3651 Width = (cast<ConstantSDNode>(Pos.getOperand(1))->getAPIntValue() +
3652 NegC->getAPIntValue());
3656 // Now we just need to check that OpSize & Mask == Width & Mask.
3658 // Opsize & Mask is 0 since Mask is Opsize - 1.
3659 return Width.getLoBits(MaskLoBits) == 0;
3660 return Width == OpSize;
3663 // A subroutine of MatchRotate used once we have found an OR of two opposite
3664 // shifts of Shifted. If Neg == <operand size> - Pos then the OR reduces
3665 // to both (PosOpcode Shifted, Pos) and (NegOpcode Shifted, Neg), with the
3666 // former being preferred if supported. InnerPos and InnerNeg are Pos and
3667 // Neg with outer conversions stripped away.
3668 SDNode *DAGCombiner::MatchRotatePosNeg(SDValue Shifted, SDValue Pos,
3669 SDValue Neg, SDValue InnerPos,
3670 SDValue InnerNeg, unsigned PosOpcode,
3671 unsigned NegOpcode, SDLoc DL) {
3672 // fold (or (shl x, (*ext y)),
3673 // (srl x, (*ext (sub 32, y)))) ->
3674 // (rotl x, y) or (rotr x, (sub 32, y))
3676 // fold (or (shl x, (*ext (sub 32, y))),
3677 // (srl x, (*ext y))) ->
3678 // (rotr x, y) or (rotl x, (sub 32, y))
3679 EVT VT = Shifted.getValueType();
3680 if (matchRotateSub(InnerPos, InnerNeg, VT.getSizeInBits())) {
3681 bool HasPos = TLI.isOperationLegalOrCustom(PosOpcode, VT);
3682 return DAG.getNode(HasPos ? PosOpcode : NegOpcode, DL, VT, Shifted,
3683 HasPos ? Pos : Neg).getNode();
3689 // MatchRotate - Handle an 'or' of two operands. If this is one of the many
3690 // idioms for rotate, and if the target supports rotation instructions, generate
3692 SDNode *DAGCombiner::MatchRotate(SDValue LHS, SDValue RHS, SDLoc DL) {
3693 // Must be a legal type. Expanded 'n promoted things won't work with rotates.
3694 EVT VT = LHS.getValueType();
3695 if (!TLI.isTypeLegal(VT)) return nullptr;
3697 // The target must have at least one rotate flavor.
3698 bool HasROTL = TLI.isOperationLegalOrCustom(ISD::ROTL, VT);
3699 bool HasROTR = TLI.isOperationLegalOrCustom(ISD::ROTR, VT);
3700 if (!HasROTL && !HasROTR) return nullptr;
3702 // Match "(X shl/srl V1) & V2" where V2 may not be present.
3703 SDValue LHSShift; // The shift.
3704 SDValue LHSMask; // AND value if any.
3705 if (!MatchRotateHalf(LHS, LHSShift, LHSMask))
3706 return nullptr; // Not part of a rotate.
3708 SDValue RHSShift; // The shift.
3709 SDValue RHSMask; // AND value if any.
3710 if (!MatchRotateHalf(RHS, RHSShift, RHSMask))
3711 return nullptr; // Not part of a rotate.
3713 if (LHSShift.getOperand(0) != RHSShift.getOperand(0))
3714 return nullptr; // Not shifting the same value.
3716 if (LHSShift.getOpcode() == RHSShift.getOpcode())
3717 return nullptr; // Shifts must disagree.
3719 // Canonicalize shl to left side in a shl/srl pair.
3720 if (RHSShift.getOpcode() == ISD::SHL) {
3721 std::swap(LHS, RHS);
3722 std::swap(LHSShift, RHSShift);
3723 std::swap(LHSMask , RHSMask );
3726 unsigned OpSizeInBits = VT.getSizeInBits();
3727 SDValue LHSShiftArg = LHSShift.getOperand(0);
3728 SDValue LHSShiftAmt = LHSShift.getOperand(1);
3729 SDValue RHSShiftArg = RHSShift.getOperand(0);
3730 SDValue RHSShiftAmt = RHSShift.getOperand(1);
3732 // fold (or (shl x, C1), (srl x, C2)) -> (rotl x, C1)
3733 // fold (or (shl x, C1), (srl x, C2)) -> (rotr x, C2)
3734 if (LHSShiftAmt.getOpcode() == ISD::Constant &&
3735 RHSShiftAmt.getOpcode() == ISD::Constant) {
3736 uint64_t LShVal = cast<ConstantSDNode>(LHSShiftAmt)->getZExtValue();
3737 uint64_t RShVal = cast<ConstantSDNode>(RHSShiftAmt)->getZExtValue();
3738 if ((LShVal + RShVal) != OpSizeInBits)
3741 SDValue Rot = DAG.getNode(HasROTL ? ISD::ROTL : ISD::ROTR, DL, VT,
3742 LHSShiftArg, HasROTL ? LHSShiftAmt : RHSShiftAmt);
3744 // If there is an AND of either shifted operand, apply it to the result.
3745 if (LHSMask.getNode() || RHSMask.getNode()) {
3746 APInt Mask = APInt::getAllOnesValue(OpSizeInBits);
3748 if (LHSMask.getNode()) {
3749 APInt RHSBits = APInt::getLowBitsSet(OpSizeInBits, LShVal);
3750 Mask &= cast<ConstantSDNode>(LHSMask)->getAPIntValue() | RHSBits;
3752 if (RHSMask.getNode()) {
3753 APInt LHSBits = APInt::getHighBitsSet(OpSizeInBits, RShVal);
3754 Mask &= cast<ConstantSDNode>(RHSMask)->getAPIntValue() | LHSBits;
3757 Rot = DAG.getNode(ISD::AND, DL, VT, Rot, DAG.getConstant(Mask, VT));
3760 return Rot.getNode();
3763 // If there is a mask here, and we have a variable shift, we can't be sure
3764 // that we're masking out the right stuff.
3765 if (LHSMask.getNode() || RHSMask.getNode())
3768 // If the shift amount is sign/zext/any-extended just peel it off.
3769 SDValue LExtOp0 = LHSShiftAmt;
3770 SDValue RExtOp0 = RHSShiftAmt;
3771 if ((LHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND ||
3772 LHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND ||
3773 LHSShiftAmt.getOpcode() == ISD::ANY_EXTEND ||
3774 LHSShiftAmt.getOpcode() == ISD::TRUNCATE) &&
3775 (RHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND ||
3776 RHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND ||
3777 RHSShiftAmt.getOpcode() == ISD::ANY_EXTEND ||
3778 RHSShiftAmt.getOpcode() == ISD::TRUNCATE)) {
3779 LExtOp0 = LHSShiftAmt.getOperand(0);
3780 RExtOp0 = RHSShiftAmt.getOperand(0);
3783 SDNode *TryL = MatchRotatePosNeg(LHSShiftArg, LHSShiftAmt, RHSShiftAmt,
3784 LExtOp0, RExtOp0, ISD::ROTL, ISD::ROTR, DL);
3788 SDNode *TryR = MatchRotatePosNeg(RHSShiftArg, RHSShiftAmt, LHSShiftAmt,
3789 RExtOp0, LExtOp0, ISD::ROTR, ISD::ROTL, DL);
3796 SDValue DAGCombiner::visitXOR(SDNode *N) {
3797 SDValue N0 = N->getOperand(0);
3798 SDValue N1 = N->getOperand(1);
3799 SDValue LHS, RHS, CC;
3800 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
3801 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
3802 EVT VT = N0.getValueType();
3805 if (VT.isVector()) {
3806 SDValue FoldedVOp = SimplifyVBinOp(N);
3807 if (FoldedVOp.getNode()) return FoldedVOp;
3809 // fold (xor x, 0) -> x, vector edition
3810 if (ISD::isBuildVectorAllZeros(N0.getNode()))
3812 if (ISD::isBuildVectorAllZeros(N1.getNode()))
3816 // fold (xor undef, undef) -> 0. This is a common idiom (misuse).
3817 if (N0.getOpcode() == ISD::UNDEF && N1.getOpcode() == ISD::UNDEF)
3818 return DAG.getConstant(0, VT);
3819 // fold (xor x, undef) -> undef
3820 if (N0.getOpcode() == ISD::UNDEF)
3822 if (N1.getOpcode() == ISD::UNDEF)
3824 // fold (xor c1, c2) -> c1^c2
3826 return DAG.FoldConstantArithmetic(ISD::XOR, VT, N0C, N1C);
3827 // canonicalize constant to RHS
3829 return DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0);
3830 // fold (xor x, 0) -> x
3831 if (N1C && N1C->isNullValue())
3834 SDValue RXOR = ReassociateOps(ISD::XOR, SDLoc(N), N0, N1);
3838 // fold !(x cc y) -> (x !cc y)
3839 if (TLI.isConstTrueVal(N1.getNode()) && isSetCCEquivalent(N0, LHS, RHS, CC)) {
3840 bool isInt = LHS.getValueType().isInteger();
3841 ISD::CondCode NotCC = ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(),
3844 if (!LegalOperations ||
3845 TLI.isCondCodeLegal(NotCC, LHS.getSimpleValueType())) {
3846 switch (N0.getOpcode()) {
3848 llvm_unreachable("Unhandled SetCC Equivalent!");
3850 return DAG.getSetCC(SDLoc(N), VT, LHS, RHS, NotCC);
3851 case ISD::SELECT_CC:
3852 return DAG.getSelectCC(SDLoc(N), LHS, RHS, N0.getOperand(2),
3853 N0.getOperand(3), NotCC);
3858 // fold (not (zext (setcc x, y))) -> (zext (not (setcc x, y)))
3859 if (N1C && N1C->getAPIntValue() == 1 && N0.getOpcode() == ISD::ZERO_EXTEND &&
3860 N0.getNode()->hasOneUse() &&
3861 isSetCCEquivalent(N0.getOperand(0), LHS, RHS, CC)){
3862 SDValue V = N0.getOperand(0);
3863 V = DAG.getNode(ISD::XOR, SDLoc(N0), V.getValueType(), V,
3864 DAG.getConstant(1, V.getValueType()));
3865 AddToWorklist(V.getNode());
3866 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, V);
3869 // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are setcc
3870 if (N1C && N1C->getAPIntValue() == 1 && VT == MVT::i1 &&
3871 (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
3872 SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
3873 if (isOneUseSetCC(RHS) || isOneUseSetCC(LHS)) {
3874 unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
3875 LHS = DAG.getNode(ISD::XOR, SDLoc(LHS), VT, LHS, N1); // LHS = ~LHS
3876 RHS = DAG.getNode(ISD::XOR, SDLoc(RHS), VT, RHS, N1); // RHS = ~RHS
3877 AddToWorklist(LHS.getNode()); AddToWorklist(RHS.getNode());
3878 return DAG.getNode(NewOpcode, SDLoc(N), VT, LHS, RHS);
3881 // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are constants
3882 if (N1C && N1C->isAllOnesValue() &&
3883 (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
3884 SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
3885 if (isa<ConstantSDNode>(RHS) || isa<ConstantSDNode>(LHS)) {
3886 unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
3887 LHS = DAG.getNode(ISD::XOR, SDLoc(LHS), VT, LHS, N1); // LHS = ~LHS
3888 RHS = DAG.getNode(ISD::XOR, SDLoc(RHS), VT, RHS, N1); // RHS = ~RHS
3889 AddToWorklist(LHS.getNode()); AddToWorklist(RHS.getNode());
3890 return DAG.getNode(NewOpcode, SDLoc(N), VT, LHS, RHS);
3893 // fold (xor (and x, y), y) -> (and (not x), y)
3894 if (N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() &&
3895 N0->getOperand(1) == N1) {
3896 SDValue X = N0->getOperand(0);
3897 SDValue NotX = DAG.getNOT(SDLoc(X), X, VT);
3898 AddToWorklist(NotX.getNode());
3899 return DAG.getNode(ISD::AND, SDLoc(N), VT, NotX, N1);
3901 // fold (xor (xor x, c1), c2) -> (xor x, (xor c1, c2))
3902 if (N1C && N0.getOpcode() == ISD::XOR) {
3903 ConstantSDNode *N00C = dyn_cast<ConstantSDNode>(N0.getOperand(0));
3904 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3906 return DAG.getNode(ISD::XOR, SDLoc(N), VT, N0.getOperand(1),
3907 DAG.getConstant(N1C->getAPIntValue() ^
3908 N00C->getAPIntValue(), VT));
3910 return DAG.getNode(ISD::XOR, SDLoc(N), VT, N0.getOperand(0),
3911 DAG.getConstant(N1C->getAPIntValue() ^
3912 N01C->getAPIntValue(), VT));
3914 // fold (xor x, x) -> 0
3916 return tryFoldToZero(SDLoc(N), TLI, VT, DAG, LegalOperations, LegalTypes);
3918 // Simplify: xor (op x...), (op y...) -> (op (xor x, y))
3919 if (N0.getOpcode() == N1.getOpcode()) {
3920 SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
3921 if (Tmp.getNode()) return Tmp;
3924 // Simplify the expression using non-local knowledge.
3925 if (!VT.isVector() &&
3926 SimplifyDemandedBits(SDValue(N, 0)))
3927 return SDValue(N, 0);
3932 /// Handle transforms common to the three shifts, when the shift amount is a
3934 SDValue DAGCombiner::visitShiftByConstant(SDNode *N, ConstantSDNode *Amt) {
3935 // We can't and shouldn't fold opaque constants.
3936 if (Amt->isOpaque())
3939 SDNode *LHS = N->getOperand(0).getNode();
3940 if (!LHS->hasOneUse()) return SDValue();
3942 // We want to pull some binops through shifts, so that we have (and (shift))
3943 // instead of (shift (and)), likewise for add, or, xor, etc. This sort of
3944 // thing happens with address calculations, so it's important to canonicalize
3946 bool HighBitSet = false; // Can we transform this if the high bit is set?
3948 switch (LHS->getOpcode()) {
3949 default: return SDValue();
3952 HighBitSet = false; // We can only transform sra if the high bit is clear.
3955 HighBitSet = true; // We can only transform sra if the high bit is set.
3958 if (N->getOpcode() != ISD::SHL)
3959 return SDValue(); // only shl(add) not sr[al](add).
3960 HighBitSet = false; // We can only transform sra if the high bit is clear.
3964 // We require the RHS of the binop to be a constant and not opaque as well.
3965 ConstantSDNode *BinOpCst = dyn_cast<ConstantSDNode>(LHS->getOperand(1));
3966 if (!BinOpCst || BinOpCst->isOpaque()) return SDValue();
3968 // FIXME: disable this unless the input to the binop is a shift by a constant.
3969 // If it is not a shift, it pessimizes some common cases like:
3971 // void foo(int *X, int i) { X[i & 1235] = 1; }
3972 // int bar(int *X, int i) { return X[i & 255]; }
3973 SDNode *BinOpLHSVal = LHS->getOperand(0).getNode();
3974 if ((BinOpLHSVal->getOpcode() != ISD::SHL &&
3975 BinOpLHSVal->getOpcode() != ISD::SRA &&
3976 BinOpLHSVal->getOpcode() != ISD::SRL) ||
3977 !isa<ConstantSDNode>(BinOpLHSVal->getOperand(1)))
3980 EVT VT = N->getValueType(0);
3982 // If this is a signed shift right, and the high bit is modified by the
3983 // logical operation, do not perform the transformation. The highBitSet
3984 // boolean indicates the value of the high bit of the constant which would
3985 // cause it to be modified for this operation.
3986 if (N->getOpcode() == ISD::SRA) {
3987 bool BinOpRHSSignSet = BinOpCst->getAPIntValue().isNegative();
3988 if (BinOpRHSSignSet != HighBitSet)
3992 if (!TLI.isDesirableToCommuteWithShift(LHS))
3995 // Fold the constants, shifting the binop RHS by the shift amount.
3996 SDValue NewRHS = DAG.getNode(N->getOpcode(), SDLoc(LHS->getOperand(1)),
3998 LHS->getOperand(1), N->getOperand(1));
3999 assert(isa<ConstantSDNode>(NewRHS) && "Folding was not successful!");
4001 // Create the new shift.
4002 SDValue NewShift = DAG.getNode(N->getOpcode(),
4003 SDLoc(LHS->getOperand(0)),
4004 VT, LHS->getOperand(0), N->getOperand(1));
4006 // Create the new binop.
4007 return DAG.getNode(LHS->getOpcode(), SDLoc(N), VT, NewShift, NewRHS);
4010 SDValue DAGCombiner::distributeTruncateThroughAnd(SDNode *N) {
4011 assert(N->getOpcode() == ISD::TRUNCATE);
4012 assert(N->getOperand(0).getOpcode() == ISD::AND);
4014 // (truncate:TruncVT (and N00, N01C)) -> (and (truncate:TruncVT N00), TruncC)
4015 if (N->hasOneUse() && N->getOperand(0).hasOneUse()) {
4016 SDValue N01 = N->getOperand(0).getOperand(1);
4018 if (ConstantSDNode *N01C = isConstOrConstSplat(N01)) {
4019 EVT TruncVT = N->getValueType(0);
4020 SDValue N00 = N->getOperand(0).getOperand(0);
4021 APInt TruncC = N01C->getAPIntValue();
4022 TruncC = TruncC.trunc(TruncVT.getScalarSizeInBits());
4024 return DAG.getNode(ISD::AND, SDLoc(N), TruncVT,
4025 DAG.getNode(ISD::TRUNCATE, SDLoc(N), TruncVT, N00),
4026 DAG.getConstant(TruncC, TruncVT));
4033 SDValue DAGCombiner::visitRotate(SDNode *N) {
4034 // fold (rot* x, (trunc (and y, c))) -> (rot* x, (and (trunc y), (trunc c))).
4035 if (N->getOperand(1).getOpcode() == ISD::TRUNCATE &&
4036 N->getOperand(1).getOperand(0).getOpcode() == ISD::AND) {
4037 SDValue NewOp1 = distributeTruncateThroughAnd(N->getOperand(1).getNode());
4038 if (NewOp1.getNode())
4039 return DAG.getNode(N->getOpcode(), SDLoc(N), N->getValueType(0),
4040 N->getOperand(0), NewOp1);
4045 SDValue DAGCombiner::visitSHL(SDNode *N) {
4046 SDValue N0 = N->getOperand(0);
4047 SDValue N1 = N->getOperand(1);
4048 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
4049 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4050 EVT VT = N0.getValueType();
4051 unsigned OpSizeInBits = VT.getScalarSizeInBits();
4054 if (VT.isVector()) {
4055 SDValue FoldedVOp = SimplifyVBinOp(N);
4056 if (FoldedVOp.getNode()) return FoldedVOp;
4058 BuildVectorSDNode *N1CV = dyn_cast<BuildVectorSDNode>(N1);
4059 // If setcc produces all-one true value then:
4060 // (shl (and (setcc) N01CV) N1CV) -> (and (setcc) N01CV<<N1CV)
4061 if (N1CV && N1CV->isConstant()) {
4062 if (N0.getOpcode() == ISD::AND) {
4063 SDValue N00 = N0->getOperand(0);
4064 SDValue N01 = N0->getOperand(1);
4065 BuildVectorSDNode *N01CV = dyn_cast<BuildVectorSDNode>(N01);
4067 if (N01CV && N01CV->isConstant() && N00.getOpcode() == ISD::SETCC &&
4068 TLI.getBooleanContents(N00.getOperand(0).getValueType()) ==
4069 TargetLowering::ZeroOrNegativeOneBooleanContent) {
4070 SDValue C = DAG.FoldConstantArithmetic(ISD::SHL, VT, N01CV, N1CV);
4072 return DAG.getNode(ISD::AND, SDLoc(N), VT, N00, C);
4075 N1C = isConstOrConstSplat(N1);
4080 // fold (shl c1, c2) -> c1<<c2
4082 return DAG.FoldConstantArithmetic(ISD::SHL, VT, N0C, N1C);
4083 // fold (shl 0, x) -> 0
4084 if (N0C && N0C->isNullValue())
4086 // fold (shl x, c >= size(x)) -> undef
4087 if (N1C && N1C->getZExtValue() >= OpSizeInBits)
4088 return DAG.getUNDEF(VT);
4089 // fold (shl x, 0) -> x
4090 if (N1C && N1C->isNullValue())
4092 // fold (shl undef, x) -> 0
4093 if (N0.getOpcode() == ISD::UNDEF)
4094 return DAG.getConstant(0, VT);
4095 // if (shl x, c) is known to be zero, return 0
4096 if (DAG.MaskedValueIsZero(SDValue(N, 0),
4097 APInt::getAllOnesValue(OpSizeInBits)))
4098 return DAG.getConstant(0, VT);
4099 // fold (shl x, (trunc (and y, c))) -> (shl x, (and (trunc y), (trunc c))).
4100 if (N1.getOpcode() == ISD::TRUNCATE &&
4101 N1.getOperand(0).getOpcode() == ISD::AND) {
4102 SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode());
4103 if (NewOp1.getNode())
4104 return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0, NewOp1);
4107 if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
4108 return SDValue(N, 0);
4110 // fold (shl (shl x, c1), c2) -> 0 or (shl x, (add c1, c2))
4111 if (N1C && N0.getOpcode() == ISD::SHL) {
4112 if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) {
4113 uint64_t c1 = N0C1->getZExtValue();
4114 uint64_t c2 = N1C->getZExtValue();
4115 if (c1 + c2 >= OpSizeInBits)
4116 return DAG.getConstant(0, VT);
4117 return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0.getOperand(0),
4118 DAG.getConstant(c1 + c2, N1.getValueType()));
4122 // fold (shl (ext (shl x, c1)), c2) -> (ext (shl x, (add c1, c2)))
4123 // For this to be valid, the second form must not preserve any of the bits
4124 // that are shifted out by the inner shift in the first form. This means
4125 // the outer shift size must be >= the number of bits added by the ext.
4126 // As a corollary, we don't care what kind of ext it is.
4127 if (N1C && (N0.getOpcode() == ISD::ZERO_EXTEND ||
4128 N0.getOpcode() == ISD::ANY_EXTEND ||
4129 N0.getOpcode() == ISD::SIGN_EXTEND) &&
4130 N0.getOperand(0).getOpcode() == ISD::SHL) {
4131 SDValue N0Op0 = N0.getOperand(0);
4132 if (ConstantSDNode *N0Op0C1 = isConstOrConstSplat(N0Op0.getOperand(1))) {
4133 uint64_t c1 = N0Op0C1->getZExtValue();
4134 uint64_t c2 = N1C->getZExtValue();
4135 EVT InnerShiftVT = N0Op0.getValueType();
4136 uint64_t InnerShiftSize = InnerShiftVT.getScalarSizeInBits();
4137 if (c2 >= OpSizeInBits - InnerShiftSize) {
4138 if (c1 + c2 >= OpSizeInBits)
4139 return DAG.getConstant(0, VT);
4140 return DAG.getNode(ISD::SHL, SDLoc(N0), VT,
4141 DAG.getNode(N0.getOpcode(), SDLoc(N0), VT,
4142 N0Op0->getOperand(0)),
4143 DAG.getConstant(c1 + c2, N1.getValueType()));
4148 // fold (shl (zext (srl x, C)), C) -> (zext (shl (srl x, C), C))
4149 // Only fold this if the inner zext has no other uses to avoid increasing
4150 // the total number of instructions.
4151 if (N1C && N0.getOpcode() == ISD::ZERO_EXTEND && N0.hasOneUse() &&
4152 N0.getOperand(0).getOpcode() == ISD::SRL) {
4153 SDValue N0Op0 = N0.getOperand(0);
4154 if (ConstantSDNode *N0Op0C1 = isConstOrConstSplat(N0Op0.getOperand(1))) {
4155 uint64_t c1 = N0Op0C1->getZExtValue();
4156 if (c1 < VT.getScalarSizeInBits()) {
4157 uint64_t c2 = N1C->getZExtValue();
4159 SDValue NewOp0 = N0.getOperand(0);
4160 EVT CountVT = NewOp0.getOperand(1).getValueType();
4161 SDValue NewSHL = DAG.getNode(ISD::SHL, SDLoc(N), NewOp0.getValueType(),
4162 NewOp0, DAG.getConstant(c2, CountVT));
4163 AddToWorklist(NewSHL.getNode());
4164 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N0), VT, NewSHL);
4170 // fold (shl (srl x, c1), c2) -> (and (shl x, (sub c2, c1), MASK) or
4171 // (and (srl x, (sub c1, c2), MASK)
4172 // Only fold this if the inner shift has no other uses -- if it does, folding
4173 // this will increase the total number of instructions.
4174 if (N1C && N0.getOpcode() == ISD::SRL && N0.hasOneUse()) {
4175 if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) {
4176 uint64_t c1 = N0C1->getZExtValue();
4177 if (c1 < OpSizeInBits) {
4178 uint64_t c2 = N1C->getZExtValue();
4179 APInt Mask = APInt::getHighBitsSet(OpSizeInBits, OpSizeInBits - c1);
4182 Mask = Mask.shl(c2 - c1);
4183 Shift = DAG.getNode(ISD::SHL, SDLoc(N), VT, N0.getOperand(0),
4184 DAG.getConstant(c2 - c1, N1.getValueType()));
4186 Mask = Mask.lshr(c1 - c2);
4187 Shift = DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0),
4188 DAG.getConstant(c1 - c2, N1.getValueType()));
4190 return DAG.getNode(ISD::AND, SDLoc(N0), VT, Shift,
4191 DAG.getConstant(Mask, VT));
4195 // fold (shl (sra x, c1), c1) -> (and x, (shl -1, c1))
4196 if (N1C && N0.getOpcode() == ISD::SRA && N1 == N0.getOperand(1)) {
4197 unsigned BitSize = VT.getScalarSizeInBits();
4198 SDValue HiBitsMask =
4199 DAG.getConstant(APInt::getHighBitsSet(BitSize,
4200 BitSize - N1C->getZExtValue()), VT);
4201 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0.getOperand(0),
4205 // fold (shl (add x, c1), c2) -> (add (shl x, c2), c1 << c2)
4206 // Variant of version done on multiply, except mul by a power of 2 is turned
4209 if (N1C && N0.getOpcode() == ISD::ADD && N0.getNode()->hasOneUse() &&
4210 (isa<ConstantSDNode>(N0.getOperand(1)) ||
4211 isConstantSplatVector(N0.getOperand(1).getNode(), Val))) {
4212 SDValue Shl0 = DAG.getNode(ISD::SHL, SDLoc(N0), VT, N0.getOperand(0), N1);
4213 SDValue Shl1 = DAG.getNode(ISD::SHL, SDLoc(N1), VT, N0.getOperand(1), N1);
4214 return DAG.getNode(ISD::ADD, SDLoc(N), VT, Shl0, Shl1);
4218 SDValue NewSHL = visitShiftByConstant(N, N1C);
4219 if (NewSHL.getNode())
4226 SDValue DAGCombiner::visitSRA(SDNode *N) {
4227 SDValue N0 = N->getOperand(0);
4228 SDValue N1 = N->getOperand(1);
4229 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
4230 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4231 EVT VT = N0.getValueType();
4232 unsigned OpSizeInBits = VT.getScalarType().getSizeInBits();
4235 if (VT.isVector()) {
4236 SDValue FoldedVOp = SimplifyVBinOp(N);
4237 if (FoldedVOp.getNode()) return FoldedVOp;
4239 N1C = isConstOrConstSplat(N1);
4242 // fold (sra c1, c2) -> (sra c1, c2)
4244 return DAG.FoldConstantArithmetic(ISD::SRA, VT, N0C, N1C);
4245 // fold (sra 0, x) -> 0
4246 if (N0C && N0C->isNullValue())
4248 // fold (sra -1, x) -> -1
4249 if (N0C && N0C->isAllOnesValue())
4251 // fold (sra x, (setge c, size(x))) -> undef
4252 if (N1C && N1C->getZExtValue() >= OpSizeInBits)
4253 return DAG.getUNDEF(VT);
4254 // fold (sra x, 0) -> x
4255 if (N1C && N1C->isNullValue())
4257 // fold (sra (shl x, c1), c1) -> sext_inreg for some c1 and target supports
4259 if (N1C && N0.getOpcode() == ISD::SHL && N1 == N0.getOperand(1)) {
4260 unsigned LowBits = OpSizeInBits - (unsigned)N1C->getZExtValue();
4261 EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), LowBits);
4263 ExtVT = EVT::getVectorVT(*DAG.getContext(),
4264 ExtVT, VT.getVectorNumElements());
4265 if ((!LegalOperations ||
4266 TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, ExtVT)))
4267 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
4268 N0.getOperand(0), DAG.getValueType(ExtVT));
4271 // fold (sra (sra x, c1), c2) -> (sra x, (add c1, c2))
4272 if (N1C && N0.getOpcode() == ISD::SRA) {
4273 if (ConstantSDNode *C1 = isConstOrConstSplat(N0.getOperand(1))) {
4274 unsigned Sum = N1C->getZExtValue() + C1->getZExtValue();
4275 if (Sum >= OpSizeInBits)
4276 Sum = OpSizeInBits - 1;
4277 return DAG.getNode(ISD::SRA, SDLoc(N), VT, N0.getOperand(0),
4278 DAG.getConstant(Sum, N1.getValueType()));
4282 // fold (sra (shl X, m), (sub result_size, n))
4283 // -> (sign_extend (trunc (shl X, (sub (sub result_size, n), m)))) for
4284 // result_size - n != m.
4285 // If truncate is free for the target sext(shl) is likely to result in better
4287 if (N0.getOpcode() == ISD::SHL && N1C) {
4288 // Get the two constanst of the shifts, CN0 = m, CN = n.
4289 const ConstantSDNode *N01C = isConstOrConstSplat(N0.getOperand(1));
4291 LLVMContext &Ctx = *DAG.getContext();
4292 // Determine what the truncate's result bitsize and type would be.
4293 EVT TruncVT = EVT::getIntegerVT(Ctx, OpSizeInBits - N1C->getZExtValue());
4296 TruncVT = EVT::getVectorVT(Ctx, TruncVT, VT.getVectorNumElements());
4298 // Determine the residual right-shift amount.
4299 signed ShiftAmt = N1C->getZExtValue() - N01C->getZExtValue();
4301 // If the shift is not a no-op (in which case this should be just a sign
4302 // extend already), the truncated to type is legal, sign_extend is legal
4303 // on that type, and the truncate to that type is both legal and free,
4304 // perform the transform.
4305 if ((ShiftAmt > 0) &&
4306 TLI.isOperationLegalOrCustom(ISD::SIGN_EXTEND, TruncVT) &&
4307 TLI.isOperationLegalOrCustom(ISD::TRUNCATE, VT) &&
4308 TLI.isTruncateFree(VT, TruncVT)) {
4310 SDValue Amt = DAG.getConstant(ShiftAmt,
4311 getShiftAmountTy(N0.getOperand(0).getValueType()));
4312 SDValue Shift = DAG.getNode(ISD::SRL, SDLoc(N0), VT,
4313 N0.getOperand(0), Amt);
4314 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0), TruncVT,
4316 return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N),
4317 N->getValueType(0), Trunc);
4322 // fold (sra x, (trunc (and y, c))) -> (sra x, (and (trunc y), (trunc c))).
4323 if (N1.getOpcode() == ISD::TRUNCATE &&
4324 N1.getOperand(0).getOpcode() == ISD::AND) {
4325 SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode());
4326 if (NewOp1.getNode())
4327 return DAG.getNode(ISD::SRA, SDLoc(N), VT, N0, NewOp1);
4330 // fold (sra (trunc (srl x, c1)), c2) -> (trunc (sra x, c1 + c2))
4331 // if c1 is equal to the number of bits the trunc removes
4332 if (N0.getOpcode() == ISD::TRUNCATE &&
4333 (N0.getOperand(0).getOpcode() == ISD::SRL ||
4334 N0.getOperand(0).getOpcode() == ISD::SRA) &&
4335 N0.getOperand(0).hasOneUse() &&
4336 N0.getOperand(0).getOperand(1).hasOneUse() &&
4338 SDValue N0Op0 = N0.getOperand(0);
4339 if (ConstantSDNode *LargeShift = isConstOrConstSplat(N0Op0.getOperand(1))) {
4340 unsigned LargeShiftVal = LargeShift->getZExtValue();
4341 EVT LargeVT = N0Op0.getValueType();
4343 if (LargeVT.getScalarSizeInBits() - OpSizeInBits == LargeShiftVal) {
4345 DAG.getConstant(LargeShiftVal + N1C->getZExtValue(),
4346 getShiftAmountTy(N0Op0.getOperand(0).getValueType()));
4347 SDValue SRA = DAG.getNode(ISD::SRA, SDLoc(N), LargeVT,
4348 N0Op0.getOperand(0), Amt);
4349 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, SRA);
4354 // Simplify, based on bits shifted out of the LHS.
4355 if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
4356 return SDValue(N, 0);
4359 // If the sign bit is known to be zero, switch this to a SRL.
4360 if (DAG.SignBitIsZero(N0))
4361 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, N1);
4364 SDValue NewSRA = visitShiftByConstant(N, N1C);
4365 if (NewSRA.getNode())
4372 SDValue DAGCombiner::visitSRL(SDNode *N) {
4373 SDValue N0 = N->getOperand(0);
4374 SDValue N1 = N->getOperand(1);
4375 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
4376 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4377 EVT VT = N0.getValueType();
4378 unsigned OpSizeInBits = VT.getScalarType().getSizeInBits();
4381 if (VT.isVector()) {
4382 SDValue FoldedVOp = SimplifyVBinOp(N);
4383 if (FoldedVOp.getNode()) return FoldedVOp;
4385 N1C = isConstOrConstSplat(N1);
4388 // fold (srl c1, c2) -> c1 >>u c2
4390 return DAG.FoldConstantArithmetic(ISD::SRL, VT, N0C, N1C);
4391 // fold (srl 0, x) -> 0
4392 if (N0C && N0C->isNullValue())
4394 // fold (srl x, c >= size(x)) -> undef
4395 if (N1C && N1C->getZExtValue() >= OpSizeInBits)
4396 return DAG.getUNDEF(VT);
4397 // fold (srl x, 0) -> x
4398 if (N1C && N1C->isNullValue())
4400 // if (srl x, c) is known to be zero, return 0
4401 if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0),
4402 APInt::getAllOnesValue(OpSizeInBits)))
4403 return DAG.getConstant(0, VT);
4405 // fold (srl (srl x, c1), c2) -> 0 or (srl x, (add c1, c2))
4406 if (N1C && N0.getOpcode() == ISD::SRL) {
4407 if (ConstantSDNode *N01C = isConstOrConstSplat(N0.getOperand(1))) {
4408 uint64_t c1 = N01C->getZExtValue();
4409 uint64_t c2 = N1C->getZExtValue();
4410 if (c1 + c2 >= OpSizeInBits)
4411 return DAG.getConstant(0, VT);
4412 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0),
4413 DAG.getConstant(c1 + c2, N1.getValueType()));
4417 // fold (srl (trunc (srl x, c1)), c2) -> 0 or (trunc (srl x, (add c1, c2)))
4418 if (N1C && N0.getOpcode() == ISD::TRUNCATE &&
4419 N0.getOperand(0).getOpcode() == ISD::SRL &&
4420 isa<ConstantSDNode>(N0.getOperand(0)->getOperand(1))) {
4422 cast<ConstantSDNode>(N0.getOperand(0)->getOperand(1))->getZExtValue();
4423 uint64_t c2 = N1C->getZExtValue();
4424 EVT InnerShiftVT = N0.getOperand(0).getValueType();
4425 EVT ShiftCountVT = N0.getOperand(0)->getOperand(1).getValueType();
4426 uint64_t InnerShiftSize = InnerShiftVT.getScalarType().getSizeInBits();
4427 // This is only valid if the OpSizeInBits + c1 = size of inner shift.
4428 if (c1 + OpSizeInBits == InnerShiftSize) {
4429 if (c1 + c2 >= InnerShiftSize)
4430 return DAG.getConstant(0, VT);
4431 return DAG.getNode(ISD::TRUNCATE, SDLoc(N0), VT,
4432 DAG.getNode(ISD::SRL, SDLoc(N0), InnerShiftVT,
4433 N0.getOperand(0)->getOperand(0),
4434 DAG.getConstant(c1 + c2, ShiftCountVT)));
4438 // fold (srl (shl x, c), c) -> (and x, cst2)
4439 if (N1C && N0.getOpcode() == ISD::SHL && N0.getOperand(1) == N1) {
4440 unsigned BitSize = N0.getScalarValueSizeInBits();
4441 if (BitSize <= 64) {
4442 uint64_t ShAmt = N1C->getZExtValue() + 64 - BitSize;
4443 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0.getOperand(0),
4444 DAG.getConstant(~0ULL >> ShAmt, VT));
4448 // fold (srl (anyextend x), c) -> (and (anyextend (srl x, c)), mask)
4449 if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
4450 // Shifting in all undef bits?
4451 EVT SmallVT = N0.getOperand(0).getValueType();
4452 unsigned BitSize = SmallVT.getScalarSizeInBits();
4453 if (N1C->getZExtValue() >= BitSize)
4454 return DAG.getUNDEF(VT);
4456 if (!LegalTypes || TLI.isTypeDesirableForOp(ISD::SRL, SmallVT)) {
4457 uint64_t ShiftAmt = N1C->getZExtValue();
4458 SDValue SmallShift = DAG.getNode(ISD::SRL, SDLoc(N0), SmallVT,
4460 DAG.getConstant(ShiftAmt, getShiftAmountTy(SmallVT)));
4461 AddToWorklist(SmallShift.getNode());
4462 APInt Mask = APInt::getAllOnesValue(OpSizeInBits).lshr(ShiftAmt);
4463 return DAG.getNode(ISD::AND, SDLoc(N), VT,
4464 DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, SmallShift),
4465 DAG.getConstant(Mask, VT));
4469 // fold (srl (sra X, Y), 31) -> (srl X, 31). This srl only looks at the sign
4470 // bit, which is unmodified by sra.
4471 if (N1C && N1C->getZExtValue() + 1 == OpSizeInBits) {
4472 if (N0.getOpcode() == ISD::SRA)
4473 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0), N1);
4476 // fold (srl (ctlz x), "5") -> x iff x has one bit set (the low bit).
4477 if (N1C && N0.getOpcode() == ISD::CTLZ &&
4478 N1C->getAPIntValue() == Log2_32(OpSizeInBits)) {
4479 APInt KnownZero, KnownOne;
4480 DAG.computeKnownBits(N0.getOperand(0), KnownZero, KnownOne);
4482 // If any of the input bits are KnownOne, then the input couldn't be all
4483 // zeros, thus the result of the srl will always be zero.
4484 if (KnownOne.getBoolValue()) return DAG.getConstant(0, VT);
4486 // If all of the bits input the to ctlz node are known to be zero, then
4487 // the result of the ctlz is "32" and the result of the shift is one.
4488 APInt UnknownBits = ~KnownZero;
4489 if (UnknownBits == 0) return DAG.getConstant(1, VT);
4491 // Otherwise, check to see if there is exactly one bit input to the ctlz.
4492 if ((UnknownBits & (UnknownBits - 1)) == 0) {
4493 // Okay, we know that only that the single bit specified by UnknownBits
4494 // could be set on input to the CTLZ node. If this bit is set, the SRL
4495 // will return 0, if it is clear, it returns 1. Change the CTLZ/SRL pair
4496 // to an SRL/XOR pair, which is likely to simplify more.
4497 unsigned ShAmt = UnknownBits.countTrailingZeros();
4498 SDValue Op = N0.getOperand(0);
4501 Op = DAG.getNode(ISD::SRL, SDLoc(N0), VT, Op,
4502 DAG.getConstant(ShAmt, getShiftAmountTy(Op.getValueType())));
4503 AddToWorklist(Op.getNode());
4506 return DAG.getNode(ISD::XOR, SDLoc(N), VT,
4507 Op, DAG.getConstant(1, VT));
4511 // fold (srl x, (trunc (and y, c))) -> (srl x, (and (trunc y), (trunc c))).
4512 if (N1.getOpcode() == ISD::TRUNCATE &&
4513 N1.getOperand(0).getOpcode() == ISD::AND) {
4514 SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode());
4515 if (NewOp1.getNode())
4516 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, NewOp1);
4519 // fold operands of srl based on knowledge that the low bits are not
4521 if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
4522 return SDValue(N, 0);
4525 SDValue NewSRL = visitShiftByConstant(N, N1C);
4526 if (NewSRL.getNode())
4530 // Attempt to convert a srl of a load into a narrower zero-extending load.
4531 SDValue NarrowLoad = ReduceLoadWidth(N);
4532 if (NarrowLoad.getNode())
4535 // Here is a common situation. We want to optimize:
4538 // %b = and i32 %a, 2
4539 // %c = srl i32 %b, 1
4540 // brcond i32 %c ...
4546 // %c = setcc eq %b, 0
4549 // However when after the source operand of SRL is optimized into AND, the SRL
4550 // itself may not be optimized further. Look for it and add the BRCOND into
4552 if (N->hasOneUse()) {
4553 SDNode *Use = *N->use_begin();
4554 if (Use->getOpcode() == ISD::BRCOND)
4556 else if (Use->getOpcode() == ISD::TRUNCATE && Use->hasOneUse()) {
4557 // Also look pass the truncate.
4558 Use = *Use->use_begin();
4559 if (Use->getOpcode() == ISD::BRCOND)
4567 SDValue DAGCombiner::visitCTLZ(SDNode *N) {
4568 SDValue N0 = N->getOperand(0);
4569 EVT VT = N->getValueType(0);
4571 // fold (ctlz c1) -> c2
4572 if (isa<ConstantSDNode>(N0))
4573 return DAG.getNode(ISD::CTLZ, SDLoc(N), VT, N0);
4577 SDValue DAGCombiner::visitCTLZ_ZERO_UNDEF(SDNode *N) {
4578 SDValue N0 = N->getOperand(0);
4579 EVT VT = N->getValueType(0);
4581 // fold (ctlz_zero_undef c1) -> c2
4582 if (isa<ConstantSDNode>(N0))
4583 return DAG.getNode(ISD::CTLZ_ZERO_UNDEF, SDLoc(N), VT, N0);
4587 SDValue DAGCombiner::visitCTTZ(SDNode *N) {
4588 SDValue N0 = N->getOperand(0);
4589 EVT VT = N->getValueType(0);
4591 // fold (cttz c1) -> c2
4592 if (isa<ConstantSDNode>(N0))
4593 return DAG.getNode(ISD::CTTZ, SDLoc(N), VT, N0);
4597 SDValue DAGCombiner::visitCTTZ_ZERO_UNDEF(SDNode *N) {
4598 SDValue N0 = N->getOperand(0);
4599 EVT VT = N->getValueType(0);
4601 // fold (cttz_zero_undef c1) -> c2
4602 if (isa<ConstantSDNode>(N0))
4603 return DAG.getNode(ISD::CTTZ_ZERO_UNDEF, SDLoc(N), VT, N0);
4607 SDValue DAGCombiner::visitCTPOP(SDNode *N) {
4608 SDValue N0 = N->getOperand(0);
4609 EVT VT = N->getValueType(0);
4611 // fold (ctpop c1) -> c2
4612 if (isa<ConstantSDNode>(N0))
4613 return DAG.getNode(ISD::CTPOP, SDLoc(N), VT, N0);
4617 SDValue DAGCombiner::visitSELECT(SDNode *N) {
4618 SDValue N0 = N->getOperand(0);
4619 SDValue N1 = N->getOperand(1);
4620 SDValue N2 = N->getOperand(2);
4621 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
4622 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4623 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2);
4624 EVT VT = N->getValueType(0);
4625 EVT VT0 = N0.getValueType();
4627 // fold (select C, X, X) -> X
4630 // fold (select true, X, Y) -> X
4631 if (N0C && !N0C->isNullValue())
4633 // fold (select false, X, Y) -> Y
4634 if (N0C && N0C->isNullValue())
4636 // fold (select C, 1, X) -> (or C, X)
4637 if (VT == MVT::i1 && N1C && N1C->getAPIntValue() == 1)
4638 return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N2);
4639 // fold (select C, 0, 1) -> (xor C, 1)
4640 // We can't do this reliably if integer based booleans have different contents
4641 // to floating point based booleans. This is because we can't tell whether we
4642 // have an integer-based boolean or a floating-point-based boolean unless we
4643 // can find the SETCC that produced it and inspect its operands. This is
4644 // fairly easy if C is the SETCC node, but it can potentially be
4645 // undiscoverable (or not reasonably discoverable). For example, it could be
4646 // in another basic block or it could require searching a complicated
4648 if (VT.isInteger() &&
4649 (VT0 == MVT::i1 || (VT0.isInteger() &&
4650 TLI.getBooleanContents(false, false) ==
4651 TLI.getBooleanContents(false, true) &&
4652 TLI.getBooleanContents(false, false) ==
4653 TargetLowering::ZeroOrOneBooleanContent)) &&
4654 N1C && N2C && N1C->isNullValue() && N2C->getAPIntValue() == 1) {
4657 return DAG.getNode(ISD::XOR, SDLoc(N), VT0,
4658 N0, DAG.getConstant(1, VT0));
4659 XORNode = DAG.getNode(ISD::XOR, SDLoc(N0), VT0,
4660 N0, DAG.getConstant(1, VT0));
4661 AddToWorklist(XORNode.getNode());
4663 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, XORNode);
4664 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, XORNode);
4666 // fold (select C, 0, X) -> (and (not C), X)
4667 if (VT == VT0 && VT == MVT::i1 && N1C && N1C->isNullValue()) {
4668 SDValue NOTNode = DAG.getNOT(SDLoc(N0), N0, VT);
4669 AddToWorklist(NOTNode.getNode());
4670 return DAG.getNode(ISD::AND, SDLoc(N), VT, NOTNode, N2);
4672 // fold (select C, X, 1) -> (or (not C), X)
4673 if (VT == VT0 && VT == MVT::i1 && N2C && N2C->getAPIntValue() == 1) {
4674 SDValue NOTNode = DAG.getNOT(SDLoc(N0), N0, VT);
4675 AddToWorklist(NOTNode.getNode());
4676 return DAG.getNode(ISD::OR, SDLoc(N), VT, NOTNode, N1);
4678 // fold (select C, X, 0) -> (and C, X)
4679 if (VT == MVT::i1 && N2C && N2C->isNullValue())
4680 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, N1);
4681 // fold (select X, X, Y) -> (or X, Y)
4682 // fold (select X, 1, Y) -> (or X, Y)
4683 if (VT == MVT::i1 && (N0 == N1 || (N1C && N1C->getAPIntValue() == 1)))
4684 return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N2);
4685 // fold (select X, Y, X) -> (and X, Y)
4686 // fold (select X, Y, 0) -> (and X, Y)
4687 if (VT == MVT::i1 && (N0 == N2 || (N2C && N2C->getAPIntValue() == 0)))
4688 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, N1);
4690 // If we can fold this based on the true/false value, do so.
4691 if (SimplifySelectOps(N, N1, N2))
4692 return SDValue(N, 0); // Don't revisit N.
4694 // fold selects based on a setcc into other things, such as min/max/abs
4695 if (N0.getOpcode() == ISD::SETCC) {
4696 if ((!LegalOperations &&
4697 TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT)) ||
4698 TLI.isOperationLegal(ISD::SELECT_CC, VT))
4699 return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT,
4700 N0.getOperand(0), N0.getOperand(1),
4701 N1, N2, N0.getOperand(2));
4702 return SimplifySelect(SDLoc(N), N0, N1, N2);
4709 std::pair<SDValue, SDValue> SplitVSETCC(const SDNode *N, SelectionDAG &DAG) {
4712 std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(N->getValueType(0));
4714 // Split the inputs.
4715 SDValue Lo, Hi, LL, LH, RL, RH;
4716 std::tie(LL, LH) = DAG.SplitVectorOperand(N, 0);
4717 std::tie(RL, RH) = DAG.SplitVectorOperand(N, 1);
4719 Lo = DAG.getNode(N->getOpcode(), DL, LoVT, LL, RL, N->getOperand(2));
4720 Hi = DAG.getNode(N->getOpcode(), DL, HiVT, LH, RH, N->getOperand(2));
4722 return std::make_pair(Lo, Hi);
4725 // This function assumes all the vselect's arguments are CONCAT_VECTOR
4726 // nodes and that the condition is a BV of ConstantSDNodes (or undefs).
4727 static SDValue ConvertSelectToConcatVector(SDNode *N, SelectionDAG &DAG) {
4729 SDValue Cond = N->getOperand(0);
4730 SDValue LHS = N->getOperand(1);
4731 SDValue RHS = N->getOperand(2);
4732 EVT VT = N->getValueType(0);
4733 int NumElems = VT.getVectorNumElements();
4734 assert(LHS.getOpcode() == ISD::CONCAT_VECTORS &&
4735 RHS.getOpcode() == ISD::CONCAT_VECTORS &&
4736 Cond.getOpcode() == ISD::BUILD_VECTOR);
4738 // CONCAT_VECTOR can take an arbitrary number of arguments. We only care about
4739 // binary ones here.
4740 if (LHS->getNumOperands() != 2 || RHS->getNumOperands() != 2)
4743 // We're sure we have an even number of elements due to the
4744 // concat_vectors we have as arguments to vselect.
4745 // Skip BV elements until we find one that's not an UNDEF
4746 // After we find an UNDEF element, keep looping until we get to half the
4747 // length of the BV and see if all the non-undef nodes are the same.
4748 ConstantSDNode *BottomHalf = nullptr;
4749 for (int i = 0; i < NumElems / 2; ++i) {
4750 if (Cond->getOperand(i)->getOpcode() == ISD::UNDEF)
4753 if (BottomHalf == nullptr)
4754 BottomHalf = cast<ConstantSDNode>(Cond.getOperand(i));
4755 else if (Cond->getOperand(i).getNode() != BottomHalf)
4759 // Do the same for the second half of the BuildVector
4760 ConstantSDNode *TopHalf = nullptr;
4761 for (int i = NumElems / 2; i < NumElems; ++i) {
4762 if (Cond->getOperand(i)->getOpcode() == ISD::UNDEF)
4765 if (TopHalf == nullptr)
4766 TopHalf = cast<ConstantSDNode>(Cond.getOperand(i));
4767 else if (Cond->getOperand(i).getNode() != TopHalf)
4771 assert(TopHalf && BottomHalf &&
4772 "One half of the selector was all UNDEFs and the other was all the "
4773 "same value. This should have been addressed before this function.");
4775 ISD::CONCAT_VECTORS, dl, VT,
4776 BottomHalf->isNullValue() ? RHS->getOperand(0) : LHS->getOperand(0),
4777 TopHalf->isNullValue() ? RHS->getOperand(1) : LHS->getOperand(1));
4780 SDValue DAGCombiner::visitMSTORE(SDNode *N) {
4782 if (Level >= AfterLegalizeTypes)
4785 MaskedStoreSDNode *MST = dyn_cast<MaskedStoreSDNode>(N);
4786 SDValue Mask = MST->getMask();
4787 SDValue Data = MST->getData();
4790 // If the MSTORE data type requires splitting and the mask is provided by a
4791 // SETCC, then split both nodes and its operands before legalization. This
4792 // prevents the type legalizer from unrolling SETCC into scalar comparisons
4793 // and enables future optimizations (e.g. min/max pattern matching on X86).
4794 if (Mask.getOpcode() == ISD::SETCC) {
4796 // Check if any splitting is required.
4797 if (TLI.getTypeAction(*DAG.getContext(), Data.getValueType()) !=
4798 TargetLowering::TypeSplitVector)
4801 SDValue MaskLo, MaskHi, Lo, Hi;
4802 std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG);
4805 std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(MST->getValueType(0));
4807 SDValue Chain = MST->getChain();
4808 SDValue Ptr = MST->getBasePtr();
4810 EVT MemoryVT = MST->getMemoryVT();
4811 unsigned Alignment = MST->getOriginalAlignment();
4813 // if Alignment is equal to the vector size,
4814 // take the half of it for the second part
4815 unsigned SecondHalfAlignment =
4816 (Alignment == Data->getValueType(0).getSizeInBits()/8) ?
4817 Alignment/2 : Alignment;
4819 EVT LoMemVT, HiMemVT;
4820 std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT);
4822 SDValue DataLo, DataHi;
4823 std::tie(DataLo, DataHi) = DAG.SplitVector(Data, DL);
4825 MachineMemOperand *MMO = DAG.getMachineFunction().
4826 getMachineMemOperand(MST->getPointerInfo(),
4827 MachineMemOperand::MOStore, LoMemVT.getStoreSize(),
4828 Alignment, MST->getAAInfo(), MST->getRanges());
4830 Lo = DAG.getMaskedStore(Chain, DL, DataLo, Ptr, MaskLo, MMO);
4832 unsigned IncrementSize = LoMemVT.getSizeInBits()/8;
4833 Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr,
4834 DAG.getConstant(IncrementSize, Ptr.getValueType()));
4836 MMO = DAG.getMachineFunction().
4837 getMachineMemOperand(MST->getPointerInfo(),
4838 MachineMemOperand::MOStore, HiMemVT.getStoreSize(),
4839 SecondHalfAlignment, MST->getAAInfo(),
4842 Hi = DAG.getMaskedStore(Chain, DL, DataHi, Ptr, MaskHi, MMO);
4844 AddToWorklist(Lo.getNode());
4845 AddToWorklist(Hi.getNode());
4847 return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo, Hi);
4852 SDValue DAGCombiner::visitMLOAD(SDNode *N) {
4854 if (Level >= AfterLegalizeTypes)
4857 MaskedLoadSDNode *MLD = dyn_cast<MaskedLoadSDNode>(N);
4858 SDValue Mask = MLD->getMask();
4861 // If the MLOAD result requires splitting and the mask is provided by a
4862 // SETCC, then split both nodes and its operands before legalization. This
4863 // prevents the type legalizer from unrolling SETCC into scalar comparisons
4864 // and enables future optimizations (e.g. min/max pattern matching on X86).
4866 if (Mask.getOpcode() == ISD::SETCC) {
4867 EVT VT = N->getValueType(0);
4869 // Check if any splitting is required.
4870 if (TLI.getTypeAction(*DAG.getContext(), VT) !=
4871 TargetLowering::TypeSplitVector)
4874 SDValue MaskLo, MaskHi, Lo, Hi;
4875 std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG);
4877 SDValue Src0 = MLD->getSrc0();
4878 SDValue Src0Lo, Src0Hi;
4879 std::tie(Src0Lo, Src0Hi) = DAG.SplitVector(Src0, DL);
4882 std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(MLD->getValueType(0));
4884 SDValue Chain = MLD->getChain();
4885 SDValue Ptr = MLD->getBasePtr();
4886 EVT MemoryVT = MLD->getMemoryVT();
4887 unsigned Alignment = MLD->getOriginalAlignment();
4889 // if Alignment is equal to the vector size,
4890 // take the half of it for the second part
4891 unsigned SecondHalfAlignment =
4892 (Alignment == MLD->getValueType(0).getSizeInBits()/8) ?
4893 Alignment/2 : Alignment;
4895 EVT LoMemVT, HiMemVT;
4896 std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT);
4898 MachineMemOperand *MMO = DAG.getMachineFunction().
4899 getMachineMemOperand(MLD->getPointerInfo(),
4900 MachineMemOperand::MOLoad, LoMemVT.getStoreSize(),
4901 Alignment, MLD->getAAInfo(), MLD->getRanges());
4903 Lo = DAG.getMaskedLoad(LoVT, DL, Chain, Ptr, MaskLo, Src0Lo, MMO);
4905 unsigned IncrementSize = LoMemVT.getSizeInBits()/8;
4906 Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr,
4907 DAG.getConstant(IncrementSize, Ptr.getValueType()));
4909 MMO = DAG.getMachineFunction().
4910 getMachineMemOperand(MLD->getPointerInfo(),
4911 MachineMemOperand::MOLoad, HiMemVT.getStoreSize(),
4912 SecondHalfAlignment, MLD->getAAInfo(), MLD->getRanges());
4914 Hi = DAG.getMaskedLoad(HiVT, DL, Chain, Ptr, MaskHi, Src0Hi, MMO);
4916 AddToWorklist(Lo.getNode());
4917 AddToWorklist(Hi.getNode());
4919 // Build a factor node to remember that this load is independent of the
4921 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo.getValue(1),
4924 // Legalized the chain result - switch anything that used the old chain to
4926 DAG.ReplaceAllUsesOfValueWith(SDValue(MLD, 1), Chain);
4928 SDValue LoadRes = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
4930 SDValue RetOps[] = { LoadRes, Chain };
4931 return DAG.getMergeValues(RetOps, DL);
4936 SDValue DAGCombiner::visitVSELECT(SDNode *N) {
4937 SDValue N0 = N->getOperand(0);
4938 SDValue N1 = N->getOperand(1);
4939 SDValue N2 = N->getOperand(2);
4942 // Canonicalize integer abs.
4943 // vselect (setg[te] X, 0), X, -X ->
4944 // vselect (setgt X, -1), X, -X ->
4945 // vselect (setl[te] X, 0), -X, X ->
4946 // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
4947 if (N0.getOpcode() == ISD::SETCC) {
4948 SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
4949 ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
4951 bool RHSIsAllZeros = ISD::isBuildVectorAllZeros(RHS.getNode());
4953 if (((RHSIsAllZeros && (CC == ISD::SETGT || CC == ISD::SETGE)) ||
4954 (ISD::isBuildVectorAllOnes(RHS.getNode()) && CC == ISD::SETGT)) &&
4955 N1 == LHS && N2.getOpcode() == ISD::SUB && N1 == N2.getOperand(1))
4956 isAbs = ISD::isBuildVectorAllZeros(N2.getOperand(0).getNode());
4957 else if ((RHSIsAllZeros && (CC == ISD::SETLT || CC == ISD::SETLE)) &&
4958 N2 == LHS && N1.getOpcode() == ISD::SUB && N2 == N1.getOperand(1))
4959 isAbs = ISD::isBuildVectorAllZeros(N1.getOperand(0).getNode());
4962 EVT VT = LHS.getValueType();
4963 SDValue Shift = DAG.getNode(
4964 ISD::SRA, DL, VT, LHS,
4965 DAG.getConstant(VT.getScalarType().getSizeInBits() - 1, VT));
4966 SDValue Add = DAG.getNode(ISD::ADD, DL, VT, LHS, Shift);
4967 AddToWorklist(Shift.getNode());
4968 AddToWorklist(Add.getNode());
4969 return DAG.getNode(ISD::XOR, DL, VT, Add, Shift);
4973 // If the VSELECT result requires splitting and the mask is provided by a
4974 // SETCC, then split both nodes and its operands before legalization. This
4975 // prevents the type legalizer from unrolling SETCC into scalar comparisons
4976 // and enables future optimizations (e.g. min/max pattern matching on X86).
4977 if (N0.getOpcode() == ISD::SETCC) {
4978 EVT VT = N->getValueType(0);
4980 // Check if any splitting is required.
4981 if (TLI.getTypeAction(*DAG.getContext(), VT) !=
4982 TargetLowering::TypeSplitVector)
4985 SDValue Lo, Hi, CCLo, CCHi, LL, LH, RL, RH;
4986 std::tie(CCLo, CCHi) = SplitVSETCC(N0.getNode(), DAG);
4987 std::tie(LL, LH) = DAG.SplitVectorOperand(N, 1);
4988 std::tie(RL, RH) = DAG.SplitVectorOperand(N, 2);
4990 Lo = DAG.getNode(N->getOpcode(), DL, LL.getValueType(), CCLo, LL, RL);
4991 Hi = DAG.getNode(N->getOpcode(), DL, LH.getValueType(), CCHi, LH, RH);
4993 // Add the new VSELECT nodes to the work list in case they need to be split
4995 AddToWorklist(Lo.getNode());
4996 AddToWorklist(Hi.getNode());
4998 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
5001 // Fold (vselect (build_vector all_ones), N1, N2) -> N1
5002 if (ISD::isBuildVectorAllOnes(N0.getNode()))
5004 // Fold (vselect (build_vector all_zeros), N1, N2) -> N2
5005 if (ISD::isBuildVectorAllZeros(N0.getNode()))
5008 // The ConvertSelectToConcatVector function is assuming both the above
5009 // checks for (vselect (build_vector all{ones,zeros) ...) have been made
5011 if (N1.getOpcode() == ISD::CONCAT_VECTORS &&
5012 N2.getOpcode() == ISD::CONCAT_VECTORS &&
5013 ISD::isBuildVectorOfConstantSDNodes(N0.getNode())) {
5014 SDValue CV = ConvertSelectToConcatVector(N, DAG);
5022 SDValue DAGCombiner::visitSELECT_CC(SDNode *N) {
5023 SDValue N0 = N->getOperand(0);
5024 SDValue N1 = N->getOperand(1);
5025 SDValue N2 = N->getOperand(2);
5026 SDValue N3 = N->getOperand(3);
5027 SDValue N4 = N->getOperand(4);
5028 ISD::CondCode CC = cast<CondCodeSDNode>(N4)->get();
5030 // fold select_cc lhs, rhs, x, x, cc -> x
5034 // Determine if the condition we're dealing with is constant
5035 SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()),
5036 N0, N1, CC, SDLoc(N), false);
5037 if (SCC.getNode()) {
5038 AddToWorklist(SCC.getNode());
5040 if (ConstantSDNode *SCCC = dyn_cast<ConstantSDNode>(SCC.getNode())) {
5041 if (!SCCC->isNullValue())
5042 return N2; // cond always true -> true val
5044 return N3; // cond always false -> false val
5047 // Fold to a simpler select_cc
5048 if (SCC.getOpcode() == ISD::SETCC)
5049 return DAG.getNode(ISD::SELECT_CC, SDLoc(N), N2.getValueType(),
5050 SCC.getOperand(0), SCC.getOperand(1), N2, N3,
5054 // If we can fold this based on the true/false value, do so.
5055 if (SimplifySelectOps(N, N2, N3))
5056 return SDValue(N, 0); // Don't revisit N.
5058 // fold select_cc into other things, such as min/max/abs
5059 return SimplifySelectCC(SDLoc(N), N0, N1, N2, N3, CC);
5062 SDValue DAGCombiner::visitSETCC(SDNode *N) {
5063 return SimplifySetCC(N->getValueType(0), N->getOperand(0), N->getOperand(1),
5064 cast<CondCodeSDNode>(N->getOperand(2))->get(),
5068 // tryToFoldExtendOfConstant - Try to fold a sext/zext/aext
5069 // dag node into a ConstantSDNode or a build_vector of constants.
5070 // This function is called by the DAGCombiner when visiting sext/zext/aext
5071 // dag nodes (see for example method DAGCombiner::visitSIGN_EXTEND).
5072 // Vector extends are not folded if operations are legal; this is to
5073 // avoid introducing illegal build_vector dag nodes.
5074 static SDNode *tryToFoldExtendOfConstant(SDNode *N, const TargetLowering &TLI,
5075 SelectionDAG &DAG, bool LegalTypes,
5076 bool LegalOperations) {
5077 unsigned Opcode = N->getOpcode();
5078 SDValue N0 = N->getOperand(0);
5079 EVT VT = N->getValueType(0);
5081 assert((Opcode == ISD::SIGN_EXTEND || Opcode == ISD::ZERO_EXTEND ||
5082 Opcode == ISD::ANY_EXTEND) && "Expected EXTEND dag node in input!");
5084 // fold (sext c1) -> c1
5085 // fold (zext c1) -> c1
5086 // fold (aext c1) -> c1
5087 if (isa<ConstantSDNode>(N0))
5088 return DAG.getNode(Opcode, SDLoc(N), VT, N0).getNode();
5090 // fold (sext (build_vector AllConstants) -> (build_vector AllConstants)
5091 // fold (zext (build_vector AllConstants) -> (build_vector AllConstants)
5092 // fold (aext (build_vector AllConstants) -> (build_vector AllConstants)
5093 EVT SVT = VT.getScalarType();
5094 if (!(VT.isVector() &&
5095 (!LegalTypes || (!LegalOperations && TLI.isTypeLegal(SVT))) &&
5096 ISD::isBuildVectorOfConstantSDNodes(N0.getNode())))
5099 // We can fold this node into a build_vector.
5100 unsigned VTBits = SVT.getSizeInBits();
5101 unsigned EVTBits = N0->getValueType(0).getScalarType().getSizeInBits();
5102 unsigned ShAmt = VTBits - EVTBits;
5103 SmallVector<SDValue, 8> Elts;
5104 unsigned NumElts = N0->getNumOperands();
5107 for (unsigned i=0; i != NumElts; ++i) {
5108 SDValue Op = N0->getOperand(i);
5109 if (Op->getOpcode() == ISD::UNDEF) {
5110 Elts.push_back(DAG.getUNDEF(SVT));
5114 ConstantSDNode *CurrentND = cast<ConstantSDNode>(Op);
5115 const APInt &C = APInt(VTBits, CurrentND->getAPIntValue().getZExtValue());
5116 if (Opcode == ISD::SIGN_EXTEND)
5117 Elts.push_back(DAG.getConstant(C.shl(ShAmt).ashr(ShAmt).getZExtValue(),
5120 Elts.push_back(DAG.getConstant(C.shl(ShAmt).lshr(ShAmt).getZExtValue(),
5124 return DAG.getNode(ISD::BUILD_VECTOR, DL, VT, Elts).getNode();
5127 // ExtendUsesToFormExtLoad - Trying to extend uses of a load to enable this:
5128 // "fold ({s|z|a}ext (load x)) -> ({s|z|a}ext (truncate ({s|z|a}extload x)))"
5129 // transformation. Returns true if extension are possible and the above
5130 // mentioned transformation is profitable.
5131 static bool ExtendUsesToFormExtLoad(SDNode *N, SDValue N0,
5133 SmallVectorImpl<SDNode *> &ExtendNodes,
5134 const TargetLowering &TLI) {
5135 bool HasCopyToRegUses = false;
5136 bool isTruncFree = TLI.isTruncateFree(N->getValueType(0), N0.getValueType());
5137 for (SDNode::use_iterator UI = N0.getNode()->use_begin(),
5138 UE = N0.getNode()->use_end();
5143 if (UI.getUse().getResNo() != N0.getResNo())
5145 // FIXME: Only extend SETCC N, N and SETCC N, c for now.
5146 if (ExtOpc != ISD::ANY_EXTEND && User->getOpcode() == ISD::SETCC) {
5147 ISD::CondCode CC = cast<CondCodeSDNode>(User->getOperand(2))->get();
5148 if (ExtOpc == ISD::ZERO_EXTEND && ISD::isSignedIntSetCC(CC))
5149 // Sign bits will be lost after a zext.
5152 for (unsigned i = 0; i != 2; ++i) {
5153 SDValue UseOp = User->getOperand(i);
5156 if (!isa<ConstantSDNode>(UseOp))
5161 ExtendNodes.push_back(User);
5164 // If truncates aren't free and there are users we can't
5165 // extend, it isn't worthwhile.
5168 // Remember if this value is live-out.
5169 if (User->getOpcode() == ISD::CopyToReg)
5170 HasCopyToRegUses = true;
5173 if (HasCopyToRegUses) {
5174 bool BothLiveOut = false;
5175 for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
5177 SDUse &Use = UI.getUse();
5178 if (Use.getResNo() == 0 && Use.getUser()->getOpcode() == ISD::CopyToReg) {
5184 // Both unextended and extended values are live out. There had better be
5185 // a good reason for the transformation.
5186 return ExtendNodes.size();
5191 void DAGCombiner::ExtendSetCCUses(const SmallVectorImpl<SDNode *> &SetCCs,
5192 SDValue Trunc, SDValue ExtLoad, SDLoc DL,
5193 ISD::NodeType ExtType) {
5194 // Extend SetCC uses if necessary.
5195 for (unsigned i = 0, e = SetCCs.size(); i != e; ++i) {
5196 SDNode *SetCC = SetCCs[i];
5197 SmallVector<SDValue, 4> Ops;
5199 for (unsigned j = 0; j != 2; ++j) {
5200 SDValue SOp = SetCC->getOperand(j);
5202 Ops.push_back(ExtLoad);
5204 Ops.push_back(DAG.getNode(ExtType, DL, ExtLoad->getValueType(0), SOp));
5207 Ops.push_back(SetCC->getOperand(2));
5208 CombineTo(SetCC, DAG.getNode(ISD::SETCC, DL, SetCC->getValueType(0), Ops));
5212 SDValue DAGCombiner::visitSIGN_EXTEND(SDNode *N) {
5213 SDValue N0 = N->getOperand(0);
5214 EVT VT = N->getValueType(0);
5216 if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
5218 return SDValue(Res, 0);
5220 // fold (sext (sext x)) -> (sext x)
5221 // fold (sext (aext x)) -> (sext x)
5222 if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
5223 return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT,
5226 if (N0.getOpcode() == ISD::TRUNCATE) {
5227 // fold (sext (truncate (load x))) -> (sext (smaller load x))
5228 // fold (sext (truncate (srl (load x), c))) -> (sext (smaller load (x+c/n)))
5229 SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
5230 if (NarrowLoad.getNode()) {
5231 SDNode* oye = N0.getNode()->getOperand(0).getNode();
5232 if (NarrowLoad.getNode() != N0.getNode()) {
5233 CombineTo(N0.getNode(), NarrowLoad);
5234 // CombineTo deleted the truncate, if needed, but not what's under it.
5237 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5240 // See if the value being truncated is already sign extended. If so, just
5241 // eliminate the trunc/sext pair.
5242 SDValue Op = N0.getOperand(0);
5243 unsigned OpBits = Op.getValueType().getScalarType().getSizeInBits();
5244 unsigned MidBits = N0.getValueType().getScalarType().getSizeInBits();
5245 unsigned DestBits = VT.getScalarType().getSizeInBits();
5246 unsigned NumSignBits = DAG.ComputeNumSignBits(Op);
5248 if (OpBits == DestBits) {
5249 // Op is i32, Mid is i8, and Dest is i32. If Op has more than 24 sign
5250 // bits, it is already ready.
5251 if (NumSignBits > DestBits-MidBits)
5253 } else if (OpBits < DestBits) {
5254 // Op is i32, Mid is i8, and Dest is i64. If Op has more than 24 sign
5255 // bits, just sext from i32.
5256 if (NumSignBits > OpBits-MidBits)
5257 return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, Op);
5259 // Op is i64, Mid is i8, and Dest is i32. If Op has more than 56 sign
5260 // bits, just truncate to i32.
5261 if (NumSignBits > OpBits-MidBits)
5262 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
5265 // fold (sext (truncate x)) -> (sextinreg x).
5266 if (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG,
5267 N0.getValueType())) {
5268 if (OpBits < DestBits)
5269 Op = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N0), VT, Op);
5270 else if (OpBits > DestBits)
5271 Op = DAG.getNode(ISD::TRUNCATE, SDLoc(N0), VT, Op);
5272 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, Op,
5273 DAG.getValueType(N0.getValueType()));
5277 // fold (sext (load x)) -> (sext (truncate (sextload x)))
5278 // None of the supported targets knows how to perform load and sign extend
5279 // on vectors in one instruction. We only perform this transformation on
5281 if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() &&
5282 ISD::isUNINDEXEDLoad(N0.getNode()) &&
5283 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
5284 TLI.isLoadExtLegal(ISD::SEXTLOAD, N0.getValueType()))) {
5285 bool DoXform = true;
5286 SmallVector<SDNode*, 4> SetCCs;
5287 if (!N0.hasOneUse())
5288 DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::SIGN_EXTEND, SetCCs, TLI);
5290 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5291 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
5293 LN0->getBasePtr(), N0.getValueType(),
5294 LN0->getMemOperand());
5295 CombineTo(N, ExtLoad);
5296 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
5297 N0.getValueType(), ExtLoad);
5298 CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
5299 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
5301 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5305 // fold (sext (sextload x)) -> (sext (truncate (sextload x)))
5306 // fold (sext ( extload x)) -> (sext (truncate (sextload x)))
5307 if ((ISD::isSEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) &&
5308 ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) {
5309 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5310 EVT MemVT = LN0->getMemoryVT();
5311 if ((!LegalOperations && !LN0->isVolatile()) ||
5312 TLI.isLoadExtLegal(ISD::SEXTLOAD, MemVT)) {
5313 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
5315 LN0->getBasePtr(), MemVT,
5316 LN0->getMemOperand());
5317 CombineTo(N, ExtLoad);
5318 CombineTo(N0.getNode(),
5319 DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
5320 N0.getValueType(), ExtLoad),
5321 ExtLoad.getValue(1));
5322 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5326 // fold (sext (and/or/xor (load x), cst)) ->
5327 // (and/or/xor (sextload x), (sext cst))
5328 if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR ||
5329 N0.getOpcode() == ISD::XOR) &&
5330 isa<LoadSDNode>(N0.getOperand(0)) &&
5331 N0.getOperand(1).getOpcode() == ISD::Constant &&
5332 TLI.isLoadExtLegal(ISD::SEXTLOAD, N0.getValueType()) &&
5333 (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) {
5334 LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0));
5335 if (LN0->getExtensionType() != ISD::ZEXTLOAD && LN0->isUnindexed()) {
5336 bool DoXform = true;
5337 SmallVector<SDNode*, 4> SetCCs;
5338 if (!N0.hasOneUse())
5339 DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0), ISD::SIGN_EXTEND,
5342 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(LN0), VT,
5343 LN0->getChain(), LN0->getBasePtr(),
5345 LN0->getMemOperand());
5346 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
5347 Mask = Mask.sext(VT.getSizeInBits());
5348 SDValue And = DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
5349 ExtLoad, DAG.getConstant(Mask, VT));
5350 SDValue Trunc = DAG.getNode(ISD::TRUNCATE,
5351 SDLoc(N0.getOperand(0)),
5352 N0.getOperand(0).getValueType(), ExtLoad);
5354 CombineTo(N0.getOperand(0).getNode(), Trunc, ExtLoad.getValue(1));
5355 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
5357 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5362 if (N0.getOpcode() == ISD::SETCC) {
5363 EVT N0VT = N0.getOperand(0).getValueType();
5364 // sext(setcc) -> sext_in_reg(vsetcc) for vectors.
5365 // Only do this before legalize for now.
5366 if (VT.isVector() && !LegalOperations &&
5367 TLI.getBooleanContents(N0VT) ==
5368 TargetLowering::ZeroOrNegativeOneBooleanContent) {
5369 // On some architectures (such as SSE/NEON/etc) the SETCC result type is
5370 // of the same size as the compared operands. Only optimize sext(setcc())
5371 // if this is the case.
5372 EVT SVT = getSetCCResultType(N0VT);
5374 // We know that the # elements of the results is the same as the
5375 // # elements of the compare (and the # elements of the compare result
5376 // for that matter). Check to see that they are the same size. If so,
5377 // we know that the element size of the sext'd result matches the
5378 // element size of the compare operands.
5379 if (VT.getSizeInBits() == SVT.getSizeInBits())
5380 return DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
5382 cast<CondCodeSDNode>(N0.getOperand(2))->get());
5384 // If the desired elements are smaller or larger than the source
5385 // elements we can use a matching integer vector type and then
5386 // truncate/sign extend
5387 EVT MatchingVectorType = N0VT.changeVectorElementTypeToInteger();
5388 if (SVT == MatchingVectorType) {
5389 SDValue VsetCC = DAG.getSetCC(SDLoc(N), MatchingVectorType,
5390 N0.getOperand(0), N0.getOperand(1),
5391 cast<CondCodeSDNode>(N0.getOperand(2))->get());
5392 return DAG.getSExtOrTrunc(VsetCC, SDLoc(N), VT);
5396 // sext(setcc x, y, cc) -> (select (setcc x, y, cc), -1, 0)
5397 unsigned ElementWidth = VT.getScalarType().getSizeInBits();
5399 DAG.getConstant(APInt::getAllOnesValue(ElementWidth), VT);
5401 SimplifySelectCC(SDLoc(N), N0.getOperand(0), N0.getOperand(1),
5402 NegOne, DAG.getConstant(0, VT),
5403 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
5404 if (SCC.getNode()) return SCC;
5406 if (!VT.isVector()) {
5407 EVT SetCCVT = getSetCCResultType(N0.getOperand(0).getValueType());
5408 if (!LegalOperations || TLI.isOperationLegal(ISD::SETCC, SetCCVT)) {
5410 ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
5411 SDValue SetCC = DAG.getSetCC(DL, SetCCVT,
5412 N0.getOperand(0), N0.getOperand(1), CC);
5413 return DAG.getSelect(DL, VT, SetCC,
5414 NegOne, DAG.getConstant(0, VT));
5419 // fold (sext x) -> (zext x) if the sign bit is known zero.
5420 if ((!LegalOperations || TLI.isOperationLegal(ISD::ZERO_EXTEND, VT)) &&
5421 DAG.SignBitIsZero(N0))
5422 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, N0);
5427 // isTruncateOf - If N is a truncate of some other value, return true, record
5428 // the value being truncated in Op and which of Op's bits are zero in KnownZero.
5429 // This function computes KnownZero to avoid a duplicated call to
5430 // computeKnownBits in the caller.
5431 static bool isTruncateOf(SelectionDAG &DAG, SDValue N, SDValue &Op,
5434 if (N->getOpcode() == ISD::TRUNCATE) {
5435 Op = N->getOperand(0);
5436 DAG.computeKnownBits(Op, KnownZero, KnownOne);
5440 if (N->getOpcode() != ISD::SETCC || N->getValueType(0) != MVT::i1 ||
5441 cast<CondCodeSDNode>(N->getOperand(2))->get() != ISD::SETNE)
5444 SDValue Op0 = N->getOperand(0);
5445 SDValue Op1 = N->getOperand(1);
5446 assert(Op0.getValueType() == Op1.getValueType());
5448 ConstantSDNode *COp0 = dyn_cast<ConstantSDNode>(Op0);
5449 ConstantSDNode *COp1 = dyn_cast<ConstantSDNode>(Op1);
5450 if (COp0 && COp0->isNullValue())
5452 else if (COp1 && COp1->isNullValue())
5457 DAG.computeKnownBits(Op, KnownZero, KnownOne);
5459 if (!(KnownZero | APInt(Op.getValueSizeInBits(), 1)).isAllOnesValue())
5465 SDValue DAGCombiner::visitZERO_EXTEND(SDNode *N) {
5466 SDValue N0 = N->getOperand(0);
5467 EVT VT = N->getValueType(0);
5469 if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
5471 return SDValue(Res, 0);
5473 // fold (zext (zext x)) -> (zext x)
5474 // fold (zext (aext x)) -> (zext x)
5475 if (N0.getOpcode() == ISD::ZERO_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
5476 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT,
5479 // fold (zext (truncate x)) -> (zext x) or
5480 // (zext (truncate x)) -> (truncate x)
5481 // This is valid when the truncated bits of x are already zero.
5482 // FIXME: We should extend this to work for vectors too.
5485 if (!VT.isVector() && isTruncateOf(DAG, N0, Op, KnownZero)) {
5486 APInt TruncatedBits =
5487 (Op.getValueSizeInBits() == N0.getValueSizeInBits()) ?
5488 APInt(Op.getValueSizeInBits(), 0) :
5489 APInt::getBitsSet(Op.getValueSizeInBits(),
5490 N0.getValueSizeInBits(),
5491 std::min(Op.getValueSizeInBits(),
5492 VT.getSizeInBits()));
5493 if (TruncatedBits == (KnownZero & TruncatedBits)) {
5494 if (VT.bitsGT(Op.getValueType()))
5495 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, Op);
5496 if (VT.bitsLT(Op.getValueType()))
5497 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
5503 // fold (zext (truncate (load x))) -> (zext (smaller load x))
5504 // fold (zext (truncate (srl (load x), c))) -> (zext (small load (x+c/n)))
5505 if (N0.getOpcode() == ISD::TRUNCATE) {
5506 SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
5507 if (NarrowLoad.getNode()) {
5508 SDNode* oye = N0.getNode()->getOperand(0).getNode();
5509 if (NarrowLoad.getNode() != N0.getNode()) {
5510 CombineTo(N0.getNode(), NarrowLoad);
5511 // CombineTo deleted the truncate, if needed, but not what's under it.
5514 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5518 // fold (zext (truncate x)) -> (and x, mask)
5519 if (N0.getOpcode() == ISD::TRUNCATE &&
5520 (!LegalOperations || TLI.isOperationLegal(ISD::AND, VT))) {
5522 // fold (zext (truncate (load x))) -> (zext (smaller load x))
5523 // fold (zext (truncate (srl (load x), c))) -> (zext (smaller load (x+c/n)))
5524 SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
5525 if (NarrowLoad.getNode()) {
5526 SDNode* oye = N0.getNode()->getOperand(0).getNode();
5527 if (NarrowLoad.getNode() != N0.getNode()) {
5528 CombineTo(N0.getNode(), NarrowLoad);
5529 // CombineTo deleted the truncate, if needed, but not what's under it.
5532 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5535 SDValue Op = N0.getOperand(0);
5536 if (Op.getValueType().bitsLT(VT)) {
5537 Op = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, Op);
5538 AddToWorklist(Op.getNode());
5539 } else if (Op.getValueType().bitsGT(VT)) {
5540 Op = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
5541 AddToWorklist(Op.getNode());
5543 return DAG.getZeroExtendInReg(Op, SDLoc(N),
5544 N0.getValueType().getScalarType());
5547 // Fold (zext (and (trunc x), cst)) -> (and x, cst),
5548 // if either of the casts is not free.
5549 if (N0.getOpcode() == ISD::AND &&
5550 N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
5551 N0.getOperand(1).getOpcode() == ISD::Constant &&
5552 (!TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(),
5553 N0.getValueType()) ||
5554 !TLI.isZExtFree(N0.getValueType(), VT))) {
5555 SDValue X = N0.getOperand(0).getOperand(0);
5556 if (X.getValueType().bitsLT(VT)) {
5557 X = DAG.getNode(ISD::ANY_EXTEND, SDLoc(X), VT, X);
5558 } else if (X.getValueType().bitsGT(VT)) {
5559 X = DAG.getNode(ISD::TRUNCATE, SDLoc(X), VT, X);
5561 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
5562 Mask = Mask.zext(VT.getSizeInBits());
5563 return DAG.getNode(ISD::AND, SDLoc(N), VT,
5564 X, DAG.getConstant(Mask, VT));
5567 // fold (zext (load x)) -> (zext (truncate (zextload x)))
5568 // None of the supported targets knows how to perform load and vector_zext
5569 // on vectors in one instruction. We only perform this transformation on
5571 if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() &&
5572 ISD::isUNINDEXEDLoad(N0.getNode()) &&
5573 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
5574 TLI.isLoadExtLegal(ISD::ZEXTLOAD, N0.getValueType()))) {
5575 bool DoXform = true;
5576 SmallVector<SDNode*, 4> SetCCs;
5577 if (!N0.hasOneUse())
5578 DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ZERO_EXTEND, SetCCs, TLI);
5580 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5581 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT,
5583 LN0->getBasePtr(), N0.getValueType(),
5584 LN0->getMemOperand());
5585 CombineTo(N, ExtLoad);
5586 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
5587 N0.getValueType(), ExtLoad);
5588 CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
5590 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
5592 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5596 // fold (zext (and/or/xor (load x), cst)) ->
5597 // (and/or/xor (zextload x), (zext cst))
5598 if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR ||
5599 N0.getOpcode() == ISD::XOR) &&
5600 isa<LoadSDNode>(N0.getOperand(0)) &&
5601 N0.getOperand(1).getOpcode() == ISD::Constant &&
5602 TLI.isLoadExtLegal(ISD::ZEXTLOAD, N0.getValueType()) &&
5603 (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) {
5604 LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0));
5605 if (LN0->getExtensionType() != ISD::SEXTLOAD && LN0->isUnindexed()) {
5606 bool DoXform = true;
5607 SmallVector<SDNode*, 4> SetCCs;
5608 if (!N0.hasOneUse())
5609 DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0), ISD::ZERO_EXTEND,
5612 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), VT,
5613 LN0->getChain(), LN0->getBasePtr(),
5615 LN0->getMemOperand());
5616 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
5617 Mask = Mask.zext(VT.getSizeInBits());
5618 SDValue And = DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
5619 ExtLoad, DAG.getConstant(Mask, VT));
5620 SDValue Trunc = DAG.getNode(ISD::TRUNCATE,
5621 SDLoc(N0.getOperand(0)),
5622 N0.getOperand(0).getValueType(), ExtLoad);
5624 CombineTo(N0.getOperand(0).getNode(), Trunc, ExtLoad.getValue(1));
5625 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
5627 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5632 // fold (zext (zextload x)) -> (zext (truncate (zextload x)))
5633 // fold (zext ( extload x)) -> (zext (truncate (zextload x)))
5634 if ((ISD::isZEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) &&
5635 ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) {
5636 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5637 EVT MemVT = LN0->getMemoryVT();
5638 if ((!LegalOperations && !LN0->isVolatile()) ||
5639 TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT)) {
5640 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT,
5642 LN0->getBasePtr(), MemVT,
5643 LN0->getMemOperand());
5644 CombineTo(N, ExtLoad);
5645 CombineTo(N0.getNode(),
5646 DAG.getNode(ISD::TRUNCATE, SDLoc(N0), N0.getValueType(),
5648 ExtLoad.getValue(1));
5649 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5653 if (N0.getOpcode() == ISD::SETCC) {
5654 if (!LegalOperations && VT.isVector() &&
5655 N0.getValueType().getVectorElementType() == MVT::i1) {
5656 EVT N0VT = N0.getOperand(0).getValueType();
5657 if (getSetCCResultType(N0VT) == N0.getValueType())
5660 // zext(setcc) -> (and (vsetcc), (1, 1, ...) for vectors.
5661 // Only do this before legalize for now.
5662 EVT EltVT = VT.getVectorElementType();
5663 SmallVector<SDValue,8> OneOps(VT.getVectorNumElements(),
5664 DAG.getConstant(1, EltVT));
5665 if (VT.getSizeInBits() == N0VT.getSizeInBits())
5666 // We know that the # elements of the results is the same as the
5667 // # elements of the compare (and the # elements of the compare result
5668 // for that matter). Check to see that they are the same size. If so,
5669 // we know that the element size of the sext'd result matches the
5670 // element size of the compare operands.
5671 return DAG.getNode(ISD::AND, SDLoc(N), VT,
5672 DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
5674 cast<CondCodeSDNode>(N0.getOperand(2))->get()),
5675 DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT,
5678 // If the desired elements are smaller or larger than the source
5679 // elements we can use a matching integer vector type and then
5680 // truncate/sign extend
5681 EVT MatchingElementType =
5682 EVT::getIntegerVT(*DAG.getContext(),
5683 N0VT.getScalarType().getSizeInBits());
5684 EVT MatchingVectorType =
5685 EVT::getVectorVT(*DAG.getContext(), MatchingElementType,
5686 N0VT.getVectorNumElements());
5688 DAG.getSetCC(SDLoc(N), MatchingVectorType, N0.getOperand(0),
5690 cast<CondCodeSDNode>(N0.getOperand(2))->get());
5691 return DAG.getNode(ISD::AND, SDLoc(N), VT,
5692 DAG.getSExtOrTrunc(VsetCC, SDLoc(N), VT),
5693 DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, OneOps));
5696 // zext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
5698 SimplifySelectCC(SDLoc(N), N0.getOperand(0), N0.getOperand(1),
5699 DAG.getConstant(1, VT), DAG.getConstant(0, VT),
5700 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
5701 if (SCC.getNode()) return SCC;
5704 // (zext (shl (zext x), cst)) -> (shl (zext x), cst)
5705 if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL) &&
5706 isa<ConstantSDNode>(N0.getOperand(1)) &&
5707 N0.getOperand(0).getOpcode() == ISD::ZERO_EXTEND &&
5709 SDValue ShAmt = N0.getOperand(1);
5710 unsigned ShAmtVal = cast<ConstantSDNode>(ShAmt)->getZExtValue();
5711 if (N0.getOpcode() == ISD::SHL) {
5712 SDValue InnerZExt = N0.getOperand(0);
5713 // If the original shl may be shifting out bits, do not perform this
5715 unsigned KnownZeroBits = InnerZExt.getValueType().getSizeInBits() -
5716 InnerZExt.getOperand(0).getValueType().getSizeInBits();
5717 if (ShAmtVal > KnownZeroBits)
5723 // Ensure that the shift amount is wide enough for the shifted value.
5724 if (VT.getSizeInBits() >= 256)
5725 ShAmt = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, ShAmt);
5727 return DAG.getNode(N0.getOpcode(), DL, VT,
5728 DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0)),
5735 SDValue DAGCombiner::visitANY_EXTEND(SDNode *N) {
5736 SDValue N0 = N->getOperand(0);
5737 EVT VT = N->getValueType(0);
5739 if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
5741 return SDValue(Res, 0);
5743 // fold (aext (aext x)) -> (aext x)
5744 // fold (aext (zext x)) -> (zext x)
5745 // fold (aext (sext x)) -> (sext x)
5746 if (N0.getOpcode() == ISD::ANY_EXTEND ||
5747 N0.getOpcode() == ISD::ZERO_EXTEND ||
5748 N0.getOpcode() == ISD::SIGN_EXTEND)
5749 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, N0.getOperand(0));
5751 // fold (aext (truncate (load x))) -> (aext (smaller load x))
5752 // fold (aext (truncate (srl (load x), c))) -> (aext (small load (x+c/n)))
5753 if (N0.getOpcode() == ISD::TRUNCATE) {
5754 SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
5755 if (NarrowLoad.getNode()) {
5756 SDNode* oye = N0.getNode()->getOperand(0).getNode();
5757 if (NarrowLoad.getNode() != N0.getNode()) {
5758 CombineTo(N0.getNode(), NarrowLoad);
5759 // CombineTo deleted the truncate, if needed, but not what's under it.
5762 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5766 // fold (aext (truncate x))
5767 if (N0.getOpcode() == ISD::TRUNCATE) {
5768 SDValue TruncOp = N0.getOperand(0);
5769 if (TruncOp.getValueType() == VT)
5770 return TruncOp; // x iff x size == zext size.
5771 if (TruncOp.getValueType().bitsGT(VT))
5772 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, TruncOp);
5773 return DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, TruncOp);
5776 // Fold (aext (and (trunc x), cst)) -> (and x, cst)
5777 // if the trunc is not free.
5778 if (N0.getOpcode() == ISD::AND &&
5779 N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
5780 N0.getOperand(1).getOpcode() == ISD::Constant &&
5781 !TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(),
5782 N0.getValueType())) {
5783 SDValue X = N0.getOperand(0).getOperand(0);
5784 if (X.getValueType().bitsLT(VT)) {
5785 X = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, X);
5786 } else if (X.getValueType().bitsGT(VT)) {
5787 X = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, X);
5789 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
5790 Mask = Mask.zext(VT.getSizeInBits());
5791 return DAG.getNode(ISD::AND, SDLoc(N), VT,
5792 X, DAG.getConstant(Mask, VT));
5795 // fold (aext (load x)) -> (aext (truncate (extload x)))
5796 // None of the supported targets knows how to perform load and any_ext
5797 // on vectors in one instruction. We only perform this transformation on
5799 if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() &&
5800 ISD::isUNINDEXEDLoad(N0.getNode()) &&
5801 TLI.isLoadExtLegal(ISD::EXTLOAD, N0.getValueType())) {
5802 bool DoXform = true;
5803 SmallVector<SDNode*, 4> SetCCs;
5804 if (!N0.hasOneUse())
5805 DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ANY_EXTEND, SetCCs, TLI);
5807 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5808 SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT,
5810 LN0->getBasePtr(), N0.getValueType(),
5811 LN0->getMemOperand());
5812 CombineTo(N, ExtLoad);
5813 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
5814 N0.getValueType(), ExtLoad);
5815 CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
5816 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
5818 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5822 // fold (aext (zextload x)) -> (aext (truncate (zextload x)))
5823 // fold (aext (sextload x)) -> (aext (truncate (sextload x)))
5824 // fold (aext ( extload x)) -> (aext (truncate (extload x)))
5825 if (N0.getOpcode() == ISD::LOAD &&
5826 !ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
5828 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5829 ISD::LoadExtType ExtType = LN0->getExtensionType();
5830 EVT MemVT = LN0->getMemoryVT();
5831 if (!LegalOperations || TLI.isLoadExtLegal(ExtType, MemVT)) {
5832 SDValue ExtLoad = DAG.getExtLoad(ExtType, SDLoc(N),
5833 VT, LN0->getChain(), LN0->getBasePtr(),
5834 MemVT, LN0->getMemOperand());
5835 CombineTo(N, ExtLoad);
5836 CombineTo(N0.getNode(),
5837 DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
5838 N0.getValueType(), ExtLoad),
5839 ExtLoad.getValue(1));
5840 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5844 if (N0.getOpcode() == ISD::SETCC) {
5846 // aext(setcc) -> vsetcc
5847 // aext(setcc) -> truncate(vsetcc)
5848 // aext(setcc) -> aext(vsetcc)
5849 // Only do this before legalize for now.
5850 if (VT.isVector() && !LegalOperations) {
5851 EVT N0VT = N0.getOperand(0).getValueType();
5852 // We know that the # elements of the results is the same as the
5853 // # elements of the compare (and the # elements of the compare result
5854 // for that matter). Check to see that they are the same size. If so,
5855 // we know that the element size of the sext'd result matches the
5856 // element size of the compare operands.
5857 if (VT.getSizeInBits() == N0VT.getSizeInBits())
5858 return DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
5860 cast<CondCodeSDNode>(N0.getOperand(2))->get());
5861 // If the desired elements are smaller or larger than the source
5862 // elements we can use a matching integer vector type and then
5863 // truncate/any extend
5865 EVT MatchingVectorType = N0VT.changeVectorElementTypeToInteger();
5867 DAG.getSetCC(SDLoc(N), MatchingVectorType, N0.getOperand(0),
5869 cast<CondCodeSDNode>(N0.getOperand(2))->get());
5870 return DAG.getAnyExtOrTrunc(VsetCC, SDLoc(N), VT);
5874 // aext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
5876 SimplifySelectCC(SDLoc(N), N0.getOperand(0), N0.getOperand(1),
5877 DAG.getConstant(1, VT), DAG.getConstant(0, VT),
5878 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
5886 /// See if the specified operand can be simplified with the knowledge that only
5887 /// the bits specified by Mask are used. If so, return the simpler operand,
5888 /// otherwise return a null SDValue.
5889 SDValue DAGCombiner::GetDemandedBits(SDValue V, const APInt &Mask) {
5890 switch (V.getOpcode()) {
5892 case ISD::Constant: {
5893 const ConstantSDNode *CV = cast<ConstantSDNode>(V.getNode());
5894 assert(CV && "Const value should be ConstSDNode.");
5895 const APInt &CVal = CV->getAPIntValue();
5896 APInt NewVal = CVal & Mask;
5898 return DAG.getConstant(NewVal, V.getValueType());
5903 // If the LHS or RHS don't contribute bits to the or, drop them.
5904 if (DAG.MaskedValueIsZero(V.getOperand(0), Mask))
5905 return V.getOperand(1);
5906 if (DAG.MaskedValueIsZero(V.getOperand(1), Mask))
5907 return V.getOperand(0);
5910 // Only look at single-use SRLs.
5911 if (!V.getNode()->hasOneUse())
5913 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(V.getOperand(1))) {
5914 // See if we can recursively simplify the LHS.
5915 unsigned Amt = RHSC->getZExtValue();
5917 // Watch out for shift count overflow though.
5918 if (Amt >= Mask.getBitWidth()) break;
5919 APInt NewMask = Mask << Amt;
5920 SDValue SimplifyLHS = GetDemandedBits(V.getOperand(0), NewMask);
5921 if (SimplifyLHS.getNode())
5922 return DAG.getNode(ISD::SRL, SDLoc(V), V.getValueType(),
5923 SimplifyLHS, V.getOperand(1));
5929 /// If the result of a wider load is shifted to right of N bits and then
5930 /// truncated to a narrower type and where N is a multiple of number of bits of
5931 /// the narrower type, transform it to a narrower load from address + N / num of
5932 /// bits of new type. If the result is to be extended, also fold the extension
5933 /// to form a extending load.
5934 SDValue DAGCombiner::ReduceLoadWidth(SDNode *N) {
5935 unsigned Opc = N->getOpcode();
5937 ISD::LoadExtType ExtType = ISD::NON_EXTLOAD;
5938 SDValue N0 = N->getOperand(0);
5939 EVT VT = N->getValueType(0);
5942 // This transformation isn't valid for vector loads.
5946 // Special case: SIGN_EXTEND_INREG is basically truncating to ExtVT then
5948 if (Opc == ISD::SIGN_EXTEND_INREG) {
5949 ExtType = ISD::SEXTLOAD;
5950 ExtVT = cast<VTSDNode>(N->getOperand(1))->getVT();
5951 } else if (Opc == ISD::SRL) {
5952 // Another special-case: SRL is basically zero-extending a narrower value.
5953 ExtType = ISD::ZEXTLOAD;
5955 ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1));
5956 if (!N01) return SDValue();
5957 ExtVT = EVT::getIntegerVT(*DAG.getContext(),
5958 VT.getSizeInBits() - N01->getZExtValue());
5960 if (LegalOperations && !TLI.isLoadExtLegal(ExtType, ExtVT))
5963 unsigned EVTBits = ExtVT.getSizeInBits();
5965 // Do not generate loads of non-round integer types since these can
5966 // be expensive (and would be wrong if the type is not byte sized).
5967 if (!ExtVT.isRound())
5971 if (N0.getOpcode() == ISD::SRL && N0.hasOneUse()) {
5972 if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
5973 ShAmt = N01->getZExtValue();
5974 // Is the shift amount a multiple of size of VT?
5975 if ((ShAmt & (EVTBits-1)) == 0) {
5976 N0 = N0.getOperand(0);
5977 // Is the load width a multiple of size of VT?
5978 if ((N0.getValueType().getSizeInBits() & (EVTBits-1)) != 0)
5982 // At this point, we must have a load or else we can't do the transform.
5983 if (!isa<LoadSDNode>(N0)) return SDValue();
5985 // Because a SRL must be assumed to *need* to zero-extend the high bits
5986 // (as opposed to anyext the high bits), we can't combine the zextload
5987 // lowering of SRL and an sextload.
5988 if (cast<LoadSDNode>(N0)->getExtensionType() == ISD::SEXTLOAD)
5991 // If the shift amount is larger than the input type then we're not
5992 // accessing any of the loaded bytes. If the load was a zextload/extload
5993 // then the result of the shift+trunc is zero/undef (handled elsewhere).
5994 if (ShAmt >= cast<LoadSDNode>(N0)->getMemoryVT().getSizeInBits())
5999 // If the load is shifted left (and the result isn't shifted back right),
6000 // we can fold the truncate through the shift.
6001 unsigned ShLeftAmt = 0;
6002 if (ShAmt == 0 && N0.getOpcode() == ISD::SHL && N0.hasOneUse() &&
6003 ExtVT == VT && TLI.isNarrowingProfitable(N0.getValueType(), VT)) {
6004 if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
6005 ShLeftAmt = N01->getZExtValue();
6006 N0 = N0.getOperand(0);
6010 // If we haven't found a load, we can't narrow it. Don't transform one with
6011 // multiple uses, this would require adding a new load.
6012 if (!isa<LoadSDNode>(N0) || !N0.hasOneUse())
6015 // Don't change the width of a volatile load.
6016 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6017 if (LN0->isVolatile())
6020 // Verify that we are actually reducing a load width here.
6021 if (LN0->getMemoryVT().getSizeInBits() < EVTBits)
6024 // For the transform to be legal, the load must produce only two values
6025 // (the value loaded and the chain). Don't transform a pre-increment
6026 // load, for example, which produces an extra value. Otherwise the
6027 // transformation is not equivalent, and the downstream logic to replace
6028 // uses gets things wrong.
6029 if (LN0->getNumValues() > 2)
6032 // If the load that we're shrinking is an extload and we're not just
6033 // discarding the extension we can't simply shrink the load. Bail.
6034 // TODO: It would be possible to merge the extensions in some cases.
6035 if (LN0->getExtensionType() != ISD::NON_EXTLOAD &&
6036 LN0->getMemoryVT().getSizeInBits() < ExtVT.getSizeInBits() + ShAmt)
6039 if (!TLI.shouldReduceLoadWidth(LN0, ExtType, ExtVT))
6042 EVT PtrType = N0.getOperand(1).getValueType();
6044 if (PtrType == MVT::Untyped || PtrType.isExtended())
6045 // It's not possible to generate a constant of extended or untyped type.
6048 // For big endian targets, we need to adjust the offset to the pointer to
6049 // load the correct bytes.
6050 if (TLI.isBigEndian()) {
6051 unsigned LVTStoreBits = LN0->getMemoryVT().getStoreSizeInBits();
6052 unsigned EVTStoreBits = ExtVT.getStoreSizeInBits();
6053 ShAmt = LVTStoreBits - EVTStoreBits - ShAmt;
6056 uint64_t PtrOff = ShAmt / 8;
6057 unsigned NewAlign = MinAlign(LN0->getAlignment(), PtrOff);
6058 SDValue NewPtr = DAG.getNode(ISD::ADD, SDLoc(LN0),
6059 PtrType, LN0->getBasePtr(),
6060 DAG.getConstant(PtrOff, PtrType));
6061 AddToWorklist(NewPtr.getNode());
6064 if (ExtType == ISD::NON_EXTLOAD)
6065 Load = DAG.getLoad(VT, SDLoc(N0), LN0->getChain(), NewPtr,
6066 LN0->getPointerInfo().getWithOffset(PtrOff),
6067 LN0->isVolatile(), LN0->isNonTemporal(),
6068 LN0->isInvariant(), NewAlign, LN0->getAAInfo());
6070 Load = DAG.getExtLoad(ExtType, SDLoc(N0), VT, LN0->getChain(),NewPtr,
6071 LN0->getPointerInfo().getWithOffset(PtrOff),
6072 ExtVT, LN0->isVolatile(), LN0->isNonTemporal(),
6073 LN0->isInvariant(), NewAlign, LN0->getAAInfo());
6075 // Replace the old load's chain with the new load's chain.
6076 WorklistRemover DeadNodes(*this);
6077 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1));
6079 // Shift the result left, if we've swallowed a left shift.
6080 SDValue Result = Load;
6081 if (ShLeftAmt != 0) {
6082 EVT ShImmTy = getShiftAmountTy(Result.getValueType());
6083 if (!isUIntN(ShImmTy.getSizeInBits(), ShLeftAmt))
6085 // If the shift amount is as large as the result size (but, presumably,
6086 // no larger than the source) then the useful bits of the result are
6087 // zero; we can't simply return the shortened shift, because the result
6088 // of that operation is undefined.
6089 if (ShLeftAmt >= VT.getSizeInBits())
6090 Result = DAG.getConstant(0, VT);
6092 Result = DAG.getNode(ISD::SHL, SDLoc(N0), VT,
6093 Result, DAG.getConstant(ShLeftAmt, ShImmTy));
6096 // Return the new loaded value.
6100 SDValue DAGCombiner::visitSIGN_EXTEND_INREG(SDNode *N) {
6101 SDValue N0 = N->getOperand(0);
6102 SDValue N1 = N->getOperand(1);
6103 EVT VT = N->getValueType(0);
6104 EVT EVT = cast<VTSDNode>(N1)->getVT();
6105 unsigned VTBits = VT.getScalarType().getSizeInBits();
6106 unsigned EVTBits = EVT.getScalarType().getSizeInBits();
6108 // fold (sext_in_reg c1) -> c1
6109 if (isa<ConstantSDNode>(N0) || N0.getOpcode() == ISD::UNDEF)
6110 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, N0, N1);
6112 // If the input is already sign extended, just drop the extension.
6113 if (DAG.ComputeNumSignBits(N0) >= VTBits-EVTBits+1)
6116 // fold (sext_in_reg (sext_in_reg x, VT2), VT1) -> (sext_in_reg x, minVT) pt2
6117 if (N0.getOpcode() == ISD::SIGN_EXTEND_INREG &&
6118 EVT.bitsLT(cast<VTSDNode>(N0.getOperand(1))->getVT()))
6119 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
6120 N0.getOperand(0), N1);
6122 // fold (sext_in_reg (sext x)) -> (sext x)
6123 // fold (sext_in_reg (aext x)) -> (sext x)
6124 // if x is small enough.
6125 if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND) {
6126 SDValue N00 = N0.getOperand(0);
6127 if (N00.getValueType().getScalarType().getSizeInBits() <= EVTBits &&
6128 (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND, VT)))
6129 return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, N00, N1);
6132 // fold (sext_in_reg x) -> (zext_in_reg x) if the sign bit is known zero.
6133 if (DAG.MaskedValueIsZero(N0, APInt::getBitsSet(VTBits, EVTBits-1, EVTBits)))
6134 return DAG.getZeroExtendInReg(N0, SDLoc(N), EVT);
6136 // fold operands of sext_in_reg based on knowledge that the top bits are not
6138 if (SimplifyDemandedBits(SDValue(N, 0)))
6139 return SDValue(N, 0);
6141 // fold (sext_in_reg (load x)) -> (smaller sextload x)
6142 // fold (sext_in_reg (srl (load x), c)) -> (smaller sextload (x+c/evtbits))
6143 SDValue NarrowLoad = ReduceLoadWidth(N);
6144 if (NarrowLoad.getNode())
6147 // fold (sext_in_reg (srl X, 24), i8) -> (sra X, 24)
6148 // fold (sext_in_reg (srl X, 23), i8) -> (sra X, 23) iff possible.
6149 // We already fold "(sext_in_reg (srl X, 25), i8) -> srl X, 25" above.
6150 if (N0.getOpcode() == ISD::SRL) {
6151 if (ConstantSDNode *ShAmt = dyn_cast<ConstantSDNode>(N0.getOperand(1)))
6152 if (ShAmt->getZExtValue()+EVTBits <= VTBits) {
6153 // We can turn this into an SRA iff the input to the SRL is already sign
6155 unsigned InSignBits = DAG.ComputeNumSignBits(N0.getOperand(0));
6156 if (VTBits-(ShAmt->getZExtValue()+EVTBits) < InSignBits)
6157 return DAG.getNode(ISD::SRA, SDLoc(N), VT,
6158 N0.getOperand(0), N0.getOperand(1));
6162 // fold (sext_inreg (extload x)) -> (sextload x)
6163 if (ISD::isEXTLoad(N0.getNode()) &&
6164 ISD::isUNINDEXEDLoad(N0.getNode()) &&
6165 EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
6166 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
6167 TLI.isLoadExtLegal(ISD::SEXTLOAD, EVT))) {
6168 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6169 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
6171 LN0->getBasePtr(), EVT,
6172 LN0->getMemOperand());
6173 CombineTo(N, ExtLoad);
6174 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
6175 AddToWorklist(ExtLoad.getNode());
6176 return SDValue(N, 0); // Return N so it doesn't get rechecked!
6178 // fold (sext_inreg (zextload x)) -> (sextload x) iff load has one use
6179 if (ISD::isZEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
6181 EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
6182 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
6183 TLI.isLoadExtLegal(ISD::SEXTLOAD, EVT))) {
6184 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6185 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
6187 LN0->getBasePtr(), EVT,
6188 LN0->getMemOperand());
6189 CombineTo(N, ExtLoad);
6190 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
6191 return SDValue(N, 0); // Return N so it doesn't get rechecked!
6194 // Form (sext_inreg (bswap >> 16)) or (sext_inreg (rotl (bswap) 16))
6195 if (EVTBits <= 16 && N0.getOpcode() == ISD::OR) {
6196 SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0),
6197 N0.getOperand(1), false);
6198 if (BSwap.getNode())
6199 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
6203 // Fold a sext_inreg of a build_vector of ConstantSDNodes or undefs
6204 // into a build_vector.
6205 if (ISD::isBuildVectorOfConstantSDNodes(N0.getNode())) {
6206 SmallVector<SDValue, 8> Elts;
6207 unsigned NumElts = N0->getNumOperands();
6208 unsigned ShAmt = VTBits - EVTBits;
6210 for (unsigned i = 0; i != NumElts; ++i) {
6211 SDValue Op = N0->getOperand(i);
6212 if (Op->getOpcode() == ISD::UNDEF) {
6217 ConstantSDNode *CurrentND = cast<ConstantSDNode>(Op);
6218 const APInt &C = APInt(VTBits, CurrentND->getAPIntValue().getZExtValue());
6219 Elts.push_back(DAG.getConstant(C.shl(ShAmt).ashr(ShAmt).getZExtValue(),
6220 Op.getValueType()));
6223 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, Elts);
6229 SDValue DAGCombiner::visitTRUNCATE(SDNode *N) {
6230 SDValue N0 = N->getOperand(0);
6231 EVT VT = N->getValueType(0);
6232 bool isLE = TLI.isLittleEndian();
6235 if (N0.getValueType() == N->getValueType(0))
6237 // fold (truncate c1) -> c1
6238 if (isa<ConstantSDNode>(N0))
6239 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0);
6240 // fold (truncate (truncate x)) -> (truncate x)
6241 if (N0.getOpcode() == ISD::TRUNCATE)
6242 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0));
6243 // fold (truncate (ext x)) -> (ext x) or (truncate x) or x
6244 if (N0.getOpcode() == ISD::ZERO_EXTEND ||
6245 N0.getOpcode() == ISD::SIGN_EXTEND ||
6246 N0.getOpcode() == ISD::ANY_EXTEND) {
6247 if (N0.getOperand(0).getValueType().bitsLT(VT))
6248 // if the source is smaller than the dest, we still need an extend
6249 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
6251 if (N0.getOperand(0).getValueType().bitsGT(VT))
6252 // if the source is larger than the dest, than we just need the truncate
6253 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0));
6254 // if the source and dest are the same type, we can drop both the extend
6255 // and the truncate.
6256 return N0.getOperand(0);
6259 // Fold extract-and-trunc into a narrow extract. For example:
6260 // i64 x = EXTRACT_VECTOR_ELT(v2i64 val, i32 1)
6261 // i32 y = TRUNCATE(i64 x)
6263 // v16i8 b = BITCAST (v2i64 val)
6264 // i8 x = EXTRACT_VECTOR_ELT(v16i8 b, i32 8)
6266 // Note: We only run this optimization after type legalization (which often
6267 // creates this pattern) and before operation legalization after which
6268 // we need to be more careful about the vector instructions that we generate.
6269 if (N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
6270 LegalTypes && !LegalOperations && N0->hasOneUse() && VT != MVT::i1) {
6272 EVT VecTy = N0.getOperand(0).getValueType();
6273 EVT ExTy = N0.getValueType();
6274 EVT TrTy = N->getValueType(0);
6276 unsigned NumElem = VecTy.getVectorNumElements();
6277 unsigned SizeRatio = ExTy.getSizeInBits()/TrTy.getSizeInBits();
6279 EVT NVT = EVT::getVectorVT(*DAG.getContext(), TrTy, SizeRatio * NumElem);
6280 assert(NVT.getSizeInBits() == VecTy.getSizeInBits() && "Invalid Size");
6282 SDValue EltNo = N0->getOperand(1);
6283 if (isa<ConstantSDNode>(EltNo) && isTypeLegal(NVT)) {
6284 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
6285 EVT IndexTy = TLI.getVectorIdxTy();
6286 int Index = isLE ? (Elt*SizeRatio) : (Elt*SizeRatio + (SizeRatio-1));
6288 SDValue V = DAG.getNode(ISD::BITCAST, SDLoc(N),
6289 NVT, N0.getOperand(0));
6291 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT,
6293 DAG.getConstant(Index, IndexTy));
6297 // trunc (select c, a, b) -> select c, (trunc a), (trunc b)
6298 if (N0.getOpcode() == ISD::SELECT) {
6299 EVT SrcVT = N0.getValueType();
6300 if ((!LegalOperations || TLI.isOperationLegal(ISD::SELECT, SrcVT)) &&
6301 TLI.isTruncateFree(SrcVT, VT)) {
6303 SDValue Cond = N0.getOperand(0);
6304 SDValue TruncOp0 = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(1));
6305 SDValue TruncOp1 = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(2));
6306 return DAG.getNode(ISD::SELECT, SDLoc(N), VT, Cond, TruncOp0, TruncOp1);
6310 // Fold a series of buildvector, bitcast, and truncate if possible.
6312 // (2xi32 trunc (bitcast ((4xi32)buildvector x, x, y, y) 2xi64)) to
6313 // (2xi32 (buildvector x, y)).
6314 if (Level == AfterLegalizeVectorOps && VT.isVector() &&
6315 N0.getOpcode() == ISD::BITCAST && N0.hasOneUse() &&
6316 N0.getOperand(0).getOpcode() == ISD::BUILD_VECTOR &&
6317 N0.getOperand(0).hasOneUse()) {
6319 SDValue BuildVect = N0.getOperand(0);
6320 EVT BuildVectEltTy = BuildVect.getValueType().getVectorElementType();
6321 EVT TruncVecEltTy = VT.getVectorElementType();
6323 // Check that the element types match.
6324 if (BuildVectEltTy == TruncVecEltTy) {
6325 // Now we only need to compute the offset of the truncated elements.
6326 unsigned BuildVecNumElts = BuildVect.getNumOperands();
6327 unsigned TruncVecNumElts = VT.getVectorNumElements();
6328 unsigned TruncEltOffset = BuildVecNumElts / TruncVecNumElts;
6330 assert((BuildVecNumElts % TruncVecNumElts) == 0 &&
6331 "Invalid number of elements");
6333 SmallVector<SDValue, 8> Opnds;
6334 for (unsigned i = 0, e = BuildVecNumElts; i != e; i += TruncEltOffset)
6335 Opnds.push_back(BuildVect.getOperand(i));
6337 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, Opnds);
6341 // See if we can simplify the input to this truncate through knowledge that
6342 // only the low bits are being used.
6343 // For example "trunc (or (shl x, 8), y)" // -> trunc y
6344 // Currently we only perform this optimization on scalars because vectors
6345 // may have different active low bits.
6346 if (!VT.isVector()) {
6348 GetDemandedBits(N0, APInt::getLowBitsSet(N0.getValueSizeInBits(),
6349 VT.getSizeInBits()));
6350 if (Shorter.getNode())
6351 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Shorter);
6353 // fold (truncate (load x)) -> (smaller load x)
6354 // fold (truncate (srl (load x), c)) -> (smaller load (x+c/evtbits))
6355 if (!LegalTypes || TLI.isTypeDesirableForOp(N0.getOpcode(), VT)) {
6356 SDValue Reduced = ReduceLoadWidth(N);
6357 if (Reduced.getNode())
6359 // Handle the case where the load remains an extending load even
6360 // after truncation.
6361 if (N0.hasOneUse() && ISD::isUNINDEXEDLoad(N0.getNode())) {
6362 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6363 if (!LN0->isVolatile() &&
6364 LN0->getMemoryVT().getStoreSizeInBits() < VT.getSizeInBits()) {
6365 SDValue NewLoad = DAG.getExtLoad(LN0->getExtensionType(), SDLoc(LN0),
6366 VT, LN0->getChain(), LN0->getBasePtr(),
6368 LN0->getMemOperand());
6369 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLoad.getValue(1));
6374 // fold (trunc (concat ... x ...)) -> (concat ..., (trunc x), ...)),
6375 // where ... are all 'undef'.
6376 if (N0.getOpcode() == ISD::CONCAT_VECTORS && !LegalTypes) {
6377 SmallVector<EVT, 8> VTs;
6380 unsigned NumDefs = 0;
6382 for (unsigned i = 0, e = N0.getNumOperands(); i != e; ++i) {
6383 SDValue X = N0.getOperand(i);
6384 if (X.getOpcode() != ISD::UNDEF) {
6389 // Stop if more than one members are non-undef.
6392 VTs.push_back(EVT::getVectorVT(*DAG.getContext(),
6393 VT.getVectorElementType(),
6394 X.getValueType().getVectorNumElements()));
6398 return DAG.getUNDEF(VT);
6401 assert(V.getNode() && "The single defined operand is empty!");
6402 SmallVector<SDValue, 8> Opnds;
6403 for (unsigned i = 0, e = VTs.size(); i != e; ++i) {
6405 Opnds.push_back(DAG.getUNDEF(VTs[i]));
6408 SDValue NV = DAG.getNode(ISD::TRUNCATE, SDLoc(V), VTs[i], V);
6409 AddToWorklist(NV.getNode());
6410 Opnds.push_back(NV);
6412 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Opnds);
6416 // Simplify the operands using demanded-bits information.
6417 if (!VT.isVector() &&
6418 SimplifyDemandedBits(SDValue(N, 0)))
6419 return SDValue(N, 0);
6424 static SDNode *getBuildPairElt(SDNode *N, unsigned i) {
6425 SDValue Elt = N->getOperand(i);
6426 if (Elt.getOpcode() != ISD::MERGE_VALUES)
6427 return Elt.getNode();
6428 return Elt.getOperand(Elt.getResNo()).getNode();
6431 /// build_pair (load, load) -> load
6432 /// if load locations are consecutive.
6433 SDValue DAGCombiner::CombineConsecutiveLoads(SDNode *N, EVT VT) {
6434 assert(N->getOpcode() == ISD::BUILD_PAIR);
6436 LoadSDNode *LD1 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 0));
6437 LoadSDNode *LD2 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 1));
6438 if (!LD1 || !LD2 || !ISD::isNON_EXTLoad(LD1) || !LD1->hasOneUse() ||
6439 LD1->getAddressSpace() != LD2->getAddressSpace())
6441 EVT LD1VT = LD1->getValueType(0);
6443 if (ISD::isNON_EXTLoad(LD2) &&
6445 // If both are volatile this would reduce the number of volatile loads.
6446 // If one is volatile it might be ok, but play conservative and bail out.
6447 !LD1->isVolatile() &&
6448 !LD2->isVolatile() &&
6449 DAG.isConsecutiveLoad(LD2, LD1, LD1VT.getSizeInBits()/8, 1)) {
6450 unsigned Align = LD1->getAlignment();
6451 unsigned NewAlign = TLI.getDataLayout()->
6452 getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
6454 if (NewAlign <= Align &&
6455 (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT)))
6456 return DAG.getLoad(VT, SDLoc(N), LD1->getChain(),
6457 LD1->getBasePtr(), LD1->getPointerInfo(),
6458 false, false, false, Align);
6464 SDValue DAGCombiner::visitBITCAST(SDNode *N) {
6465 SDValue N0 = N->getOperand(0);
6466 EVT VT = N->getValueType(0);
6468 // If the input is a BUILD_VECTOR with all constant elements, fold this now.
6469 // Only do this before legalize, since afterward the target may be depending
6470 // on the bitconvert.
6471 // First check to see if this is all constant.
6473 N0.getOpcode() == ISD::BUILD_VECTOR && N0.getNode()->hasOneUse() &&
6475 bool isSimple = cast<BuildVectorSDNode>(N0)->isConstant();
6477 EVT DestEltVT = N->getValueType(0).getVectorElementType();
6478 assert(!DestEltVT.isVector() &&
6479 "Element type of vector ValueType must not be vector!");
6481 return ConstantFoldBITCASTofBUILD_VECTOR(N0.getNode(), DestEltVT);
6484 // If the input is a constant, let getNode fold it.
6485 if (isa<ConstantSDNode>(N0) || isa<ConstantFPSDNode>(N0)) {
6486 SDValue Res = DAG.getNode(ISD::BITCAST, SDLoc(N), VT, N0);
6487 if (Res.getNode() != N) {
6488 if (!LegalOperations ||
6489 TLI.isOperationLegal(Res.getNode()->getOpcode(), VT))
6492 // Folding it resulted in an illegal node, and it's too late to
6493 // do that. Clean up the old node and forego the transformation.
6494 // Ideally this won't happen very often, because instcombine
6495 // and the earlier dagcombine runs (where illegal nodes are
6496 // permitted) should have folded most of them already.
6497 deleteAndRecombine(Res.getNode());
6501 // (conv (conv x, t1), t2) -> (conv x, t2)
6502 if (N0.getOpcode() == ISD::BITCAST)
6503 return DAG.getNode(ISD::BITCAST, SDLoc(N), VT,
6506 // fold (conv (load x)) -> (load (conv*)x)
6507 // If the resultant load doesn't need a higher alignment than the original!
6508 if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
6509 // Do not change the width of a volatile load.
6510 !cast<LoadSDNode>(N0)->isVolatile() &&
6511 // Do not remove the cast if the types differ in endian layout.
6512 TLI.hasBigEndianPartOrdering(N0.getValueType()) ==
6513 TLI.hasBigEndianPartOrdering(VT) &&
6514 (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT)) &&
6515 TLI.isLoadBitCastBeneficial(N0.getValueType(), VT)) {
6516 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6517 unsigned Align = TLI.getDataLayout()->
6518 getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
6519 unsigned OrigAlign = LN0->getAlignment();
6521 if (Align <= OrigAlign) {
6522 SDValue Load = DAG.getLoad(VT, SDLoc(N), LN0->getChain(),
6523 LN0->getBasePtr(), LN0->getPointerInfo(),
6524 LN0->isVolatile(), LN0->isNonTemporal(),
6525 LN0->isInvariant(), OrigAlign,
6527 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1));
6532 // fold (bitconvert (fneg x)) -> (xor (bitconvert x), signbit)
6533 // fold (bitconvert (fabs x)) -> (and (bitconvert x), (not signbit))
6534 // This often reduces constant pool loads.
6535 if (((N0.getOpcode() == ISD::FNEG && !TLI.isFNegFree(N0.getValueType())) ||
6536 (N0.getOpcode() == ISD::FABS && !TLI.isFAbsFree(N0.getValueType()))) &&
6537 N0.getNode()->hasOneUse() && VT.isInteger() &&
6538 !VT.isVector() && !N0.getValueType().isVector()) {
6539 SDValue NewConv = DAG.getNode(ISD::BITCAST, SDLoc(N0), VT,
6541 AddToWorklist(NewConv.getNode());
6543 APInt SignBit = APInt::getSignBit(VT.getSizeInBits());
6544 if (N0.getOpcode() == ISD::FNEG)
6545 return DAG.getNode(ISD::XOR, SDLoc(N), VT,
6546 NewConv, DAG.getConstant(SignBit, VT));
6547 assert(N0.getOpcode() == ISD::FABS);
6548 return DAG.getNode(ISD::AND, SDLoc(N), VT,
6549 NewConv, DAG.getConstant(~SignBit, VT));
6552 // fold (bitconvert (fcopysign cst, x)) ->
6553 // (or (and (bitconvert x), sign), (and cst, (not sign)))
6554 // Note that we don't handle (copysign x, cst) because this can always be
6555 // folded to an fneg or fabs.
6556 if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse() &&
6557 isa<ConstantFPSDNode>(N0.getOperand(0)) &&
6558 VT.isInteger() && !VT.isVector()) {
6559 unsigned OrigXWidth = N0.getOperand(1).getValueType().getSizeInBits();
6560 EVT IntXVT = EVT::getIntegerVT(*DAG.getContext(), OrigXWidth);
6561 if (isTypeLegal(IntXVT)) {
6562 SDValue X = DAG.getNode(ISD::BITCAST, SDLoc(N0),
6563 IntXVT, N0.getOperand(1));
6564 AddToWorklist(X.getNode());
6566 // If X has a different width than the result/lhs, sext it or truncate it.
6567 unsigned VTWidth = VT.getSizeInBits();
6568 if (OrigXWidth < VTWidth) {
6569 X = DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, X);
6570 AddToWorklist(X.getNode());
6571 } else if (OrigXWidth > VTWidth) {
6572 // To get the sign bit in the right place, we have to shift it right
6573 // before truncating.
6574 X = DAG.getNode(ISD::SRL, SDLoc(X),
6575 X.getValueType(), X,
6576 DAG.getConstant(OrigXWidth-VTWidth, X.getValueType()));
6577 AddToWorklist(X.getNode());
6578 X = DAG.getNode(ISD::TRUNCATE, SDLoc(X), VT, X);
6579 AddToWorklist(X.getNode());
6582 APInt SignBit = APInt::getSignBit(VT.getSizeInBits());
6583 X = DAG.getNode(ISD::AND, SDLoc(X), VT,
6584 X, DAG.getConstant(SignBit, VT));
6585 AddToWorklist(X.getNode());
6587 SDValue Cst = DAG.getNode(ISD::BITCAST, SDLoc(N0),
6588 VT, N0.getOperand(0));
6589 Cst = DAG.getNode(ISD::AND, SDLoc(Cst), VT,
6590 Cst, DAG.getConstant(~SignBit, VT));
6591 AddToWorklist(Cst.getNode());
6593 return DAG.getNode(ISD::OR, SDLoc(N), VT, X, Cst);
6597 // bitconvert(build_pair(ld, ld)) -> ld iff load locations are consecutive.
6598 if (N0.getOpcode() == ISD::BUILD_PAIR) {
6599 SDValue CombineLD = CombineConsecutiveLoads(N0.getNode(), VT);
6600 if (CombineLD.getNode())
6607 SDValue DAGCombiner::visitBUILD_PAIR(SDNode *N) {
6608 EVT VT = N->getValueType(0);
6609 return CombineConsecutiveLoads(N, VT);
6612 /// We know that BV is a build_vector node with Constant, ConstantFP or Undef
6613 /// operands. DstEltVT indicates the destination element value type.
6614 SDValue DAGCombiner::
6615 ConstantFoldBITCASTofBUILD_VECTOR(SDNode *BV, EVT DstEltVT) {
6616 EVT SrcEltVT = BV->getValueType(0).getVectorElementType();
6618 // If this is already the right type, we're done.
6619 if (SrcEltVT == DstEltVT) return SDValue(BV, 0);
6621 unsigned SrcBitSize = SrcEltVT.getSizeInBits();
6622 unsigned DstBitSize = DstEltVT.getSizeInBits();
6624 // If this is a conversion of N elements of one type to N elements of another
6625 // type, convert each element. This handles FP<->INT cases.
6626 if (SrcBitSize == DstBitSize) {
6627 EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT,
6628 BV->getValueType(0).getVectorNumElements());
6630 // Due to the FP element handling below calling this routine recursively,
6631 // we can end up with a scalar-to-vector node here.
6632 if (BV->getOpcode() == ISD::SCALAR_TO_VECTOR)
6633 return DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(BV), VT,
6634 DAG.getNode(ISD::BITCAST, SDLoc(BV),
6635 DstEltVT, BV->getOperand(0)));
6637 SmallVector<SDValue, 8> Ops;
6638 for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) {
6639 SDValue Op = BV->getOperand(i);
6640 // If the vector element type is not legal, the BUILD_VECTOR operands
6641 // are promoted and implicitly truncated. Make that explicit here.
6642 if (Op.getValueType() != SrcEltVT)
6643 Op = DAG.getNode(ISD::TRUNCATE, SDLoc(BV), SrcEltVT, Op);
6644 Ops.push_back(DAG.getNode(ISD::BITCAST, SDLoc(BV),
6646 AddToWorklist(Ops.back().getNode());
6648 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(BV), VT, Ops);
6651 // Otherwise, we're growing or shrinking the elements. To avoid having to
6652 // handle annoying details of growing/shrinking FP values, we convert them to
6654 if (SrcEltVT.isFloatingPoint()) {
6655 // Convert the input float vector to a int vector where the elements are the
6657 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), SrcEltVT.getSizeInBits());
6658 BV = ConstantFoldBITCASTofBUILD_VECTOR(BV, IntVT).getNode();
6662 // Now we know the input is an integer vector. If the output is a FP type,
6663 // convert to integer first, then to FP of the right size.
6664 if (DstEltVT.isFloatingPoint()) {
6665 EVT TmpVT = EVT::getIntegerVT(*DAG.getContext(), DstEltVT.getSizeInBits());
6666 SDNode *Tmp = ConstantFoldBITCASTofBUILD_VECTOR(BV, TmpVT).getNode();
6668 // Next, convert to FP elements of the same size.
6669 return ConstantFoldBITCASTofBUILD_VECTOR(Tmp, DstEltVT);
6672 // Okay, we know the src/dst types are both integers of differing types.
6673 // Handling growing first.
6674 assert(SrcEltVT.isInteger() && DstEltVT.isInteger());
6675 if (SrcBitSize < DstBitSize) {
6676 unsigned NumInputsPerOutput = DstBitSize/SrcBitSize;
6678 SmallVector<SDValue, 8> Ops;
6679 for (unsigned i = 0, e = BV->getNumOperands(); i != e;
6680 i += NumInputsPerOutput) {
6681 bool isLE = TLI.isLittleEndian();
6682 APInt NewBits = APInt(DstBitSize, 0);
6683 bool EltIsUndef = true;
6684 for (unsigned j = 0; j != NumInputsPerOutput; ++j) {
6685 // Shift the previously computed bits over.
6686 NewBits <<= SrcBitSize;
6687 SDValue Op = BV->getOperand(i+ (isLE ? (NumInputsPerOutput-j-1) : j));
6688 if (Op.getOpcode() == ISD::UNDEF) continue;
6691 NewBits |= cast<ConstantSDNode>(Op)->getAPIntValue().
6692 zextOrTrunc(SrcBitSize).zext(DstBitSize);
6696 Ops.push_back(DAG.getUNDEF(DstEltVT));
6698 Ops.push_back(DAG.getConstant(NewBits, DstEltVT));
6701 EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT, Ops.size());
6702 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(BV), VT, Ops);
6705 // Finally, this must be the case where we are shrinking elements: each input
6706 // turns into multiple outputs.
6707 bool isS2V = ISD::isScalarToVector(BV);
6708 unsigned NumOutputsPerInput = SrcBitSize/DstBitSize;
6709 EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT,
6710 NumOutputsPerInput*BV->getNumOperands());
6711 SmallVector<SDValue, 8> Ops;
6713 for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) {
6714 if (BV->getOperand(i).getOpcode() == ISD::UNDEF) {
6715 for (unsigned j = 0; j != NumOutputsPerInput; ++j)
6716 Ops.push_back(DAG.getUNDEF(DstEltVT));
6720 APInt OpVal = cast<ConstantSDNode>(BV->getOperand(i))->
6721 getAPIntValue().zextOrTrunc(SrcBitSize);
6723 for (unsigned j = 0; j != NumOutputsPerInput; ++j) {
6724 APInt ThisVal = OpVal.trunc(DstBitSize);
6725 Ops.push_back(DAG.getConstant(ThisVal, DstEltVT));
6726 if (isS2V && i == 0 && j == 0 && ThisVal.zext(SrcBitSize) == OpVal)
6727 // Simply turn this into a SCALAR_TO_VECTOR of the new type.
6728 return DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(BV), VT,
6730 OpVal = OpVal.lshr(DstBitSize);
6733 // For big endian targets, swap the order of the pieces of each element.
6734 if (TLI.isBigEndian())
6735 std::reverse(Ops.end()-NumOutputsPerInput, Ops.end());
6738 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(BV), VT, Ops);
6741 SDValue DAGCombiner::visitFADD(SDNode *N) {
6742 SDValue N0 = N->getOperand(0);
6743 SDValue N1 = N->getOperand(1);
6744 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6745 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6746 EVT VT = N->getValueType(0);
6747 const TargetOptions &Options = DAG.getTarget().Options;
6750 if (VT.isVector()) {
6751 SDValue FoldedVOp = SimplifyVBinOp(N);
6752 if (FoldedVOp.getNode()) return FoldedVOp;
6755 // fold (fadd c1, c2) -> c1 + c2
6757 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N1);
6759 // canonicalize constant to RHS
6760 if (N0CFP && !N1CFP)
6761 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N1, N0);
6763 // fold (fadd A, (fneg B)) -> (fsub A, B)
6764 if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) &&
6765 isNegatibleForFree(N1, LegalOperations, TLI, &Options) == 2)
6766 return DAG.getNode(ISD::FSUB, SDLoc(N), VT, N0,
6767 GetNegatedExpression(N1, DAG, LegalOperations));
6769 // fold (fadd (fneg A), B) -> (fsub B, A)
6770 if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) &&
6771 isNegatibleForFree(N0, LegalOperations, TLI, &Options) == 2)
6772 return DAG.getNode(ISD::FSUB, SDLoc(N), VT, N1,
6773 GetNegatedExpression(N0, DAG, LegalOperations));
6775 // If 'unsafe math' is enabled, fold lots of things.
6776 if (Options.UnsafeFPMath) {
6777 // No FP constant should be created after legalization as Instruction
6778 // Selection pass has a hard time dealing with FP constants.
6779 bool AllowNewConst = (Level < AfterLegalizeDAG);
6781 // fold (fadd A, 0) -> A
6782 if (N1CFP && N1CFP->getValueAPF().isZero())
6785 // fold (fadd (fadd x, c1), c2) -> (fadd x, (fadd c1, c2))
6786 if (N1CFP && N0.getOpcode() == ISD::FADD && N0.getNode()->hasOneUse() &&
6787 isa<ConstantFPSDNode>(N0.getOperand(1)))
6788 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0.getOperand(0),
6789 DAG.getNode(ISD::FADD, SDLoc(N), VT,
6790 N0.getOperand(1), N1));
6792 // If allowed, fold (fadd (fneg x), x) -> 0.0
6793 if (AllowNewConst && N0.getOpcode() == ISD::FNEG && N0.getOperand(0) == N1)
6794 return DAG.getConstantFP(0.0, VT);
6796 // If allowed, fold (fadd x, (fneg x)) -> 0.0
6797 if (AllowNewConst && N1.getOpcode() == ISD::FNEG && N1.getOperand(0) == N0)
6798 return DAG.getConstantFP(0.0, VT);
6800 // We can fold chains of FADD's of the same value into multiplications.
6801 // This transform is not safe in general because we are reducing the number
6802 // of rounding steps.
6803 if (TLI.isOperationLegalOrCustom(ISD::FMUL, VT) && !N0CFP && !N1CFP) {
6804 if (N0.getOpcode() == ISD::FMUL) {
6805 ConstantFPSDNode *CFP00 = dyn_cast<ConstantFPSDNode>(N0.getOperand(0));
6806 ConstantFPSDNode *CFP01 = dyn_cast<ConstantFPSDNode>(N0.getOperand(1));
6808 // (fadd (fmul x, c), x) -> (fmul x, c+1)
6809 if (CFP01 && !CFP00 && N0.getOperand(0) == N1) {
6810 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6812 DAG.getConstantFP(1.0, VT));
6813 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N1, NewCFP);
6816 // (fadd (fmul x, c), (fadd x, x)) -> (fmul x, c+2)
6817 if (CFP01 && !CFP00 && N1.getOpcode() == ISD::FADD &&
6818 N1.getOperand(0) == N1.getOperand(1) &&
6819 N0.getOperand(0) == N1.getOperand(0)) {
6820 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6822 DAG.getConstantFP(2.0, VT));
6823 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6824 N0.getOperand(0), NewCFP);
6828 if (N1.getOpcode() == ISD::FMUL) {
6829 ConstantFPSDNode *CFP10 = dyn_cast<ConstantFPSDNode>(N1.getOperand(0));
6830 ConstantFPSDNode *CFP11 = dyn_cast<ConstantFPSDNode>(N1.getOperand(1));
6832 // (fadd x, (fmul x, c)) -> (fmul x, c+1)
6833 if (CFP11 && !CFP10 && N1.getOperand(0) == N0) {
6834 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6836 DAG.getConstantFP(1.0, VT));
6837 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0, NewCFP);
6840 // (fadd (fadd x, x), (fmul x, c)) -> (fmul x, c+2)
6841 if (CFP11 && !CFP10 && N0.getOpcode() == ISD::FADD &&
6842 N0.getOperand(0) == N0.getOperand(1) &&
6843 N1.getOperand(0) == N0.getOperand(0)) {
6844 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6846 DAG.getConstantFP(2.0, VT));
6847 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N1.getOperand(0), NewCFP);
6851 if (N0.getOpcode() == ISD::FADD && AllowNewConst) {
6852 ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N0.getOperand(0));
6853 // (fadd (fadd x, x), x) -> (fmul x, 3.0)
6854 if (!CFP && N0.getOperand(0) == N0.getOperand(1) &&
6855 (N0.getOperand(0) == N1))
6856 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6857 N1, DAG.getConstantFP(3.0, VT));
6860 if (N1.getOpcode() == ISD::FADD && AllowNewConst) {
6861 ConstantFPSDNode *CFP10 = dyn_cast<ConstantFPSDNode>(N1.getOperand(0));
6862 // (fadd x, (fadd x, x)) -> (fmul x, 3.0)
6863 if (!CFP10 && N1.getOperand(0) == N1.getOperand(1) &&
6864 N1.getOperand(0) == N0)
6865 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6866 N0, DAG.getConstantFP(3.0, VT));
6869 // (fadd (fadd x, x), (fadd x, x)) -> (fmul x, 4.0)
6870 if (AllowNewConst &&
6871 N0.getOpcode() == ISD::FADD && N1.getOpcode() == ISD::FADD &&
6872 N0.getOperand(0) == N0.getOperand(1) &&
6873 N1.getOperand(0) == N1.getOperand(1) &&
6874 N0.getOperand(0) == N1.getOperand(0))
6875 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6876 N0.getOperand(0), DAG.getConstantFP(4.0, VT));
6878 } // enable-unsafe-fp-math
6880 // FADD -> FMA combines:
6881 if ((Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath) &&
6882 TLI.isFMAFasterThanFMulAndFAdd(VT) &&
6883 (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT))) {
6885 // fold (fadd (fmul x, y), z) -> (fma x, y, z)
6886 if (N0.getOpcode() == ISD::FMUL &&
6887 (N0->hasOneUse() || TLI.enableAggressiveFMAFusion(VT)))
6888 return DAG.getNode(ISD::FMA, SDLoc(N), VT,
6889 N0.getOperand(0), N0.getOperand(1), N1);
6891 // fold (fadd x, (fmul y, z)) -> (fma y, z, x)
6892 // Note: Commutes FADD operands.
6893 if (N1.getOpcode() == ISD::FMUL &&
6894 (N1->hasOneUse() || TLI.enableAggressiveFMAFusion(VT)))
6895 return DAG.getNode(ISD::FMA, SDLoc(N), VT,
6896 N1.getOperand(0), N1.getOperand(1), N0);
6902 SDValue DAGCombiner::visitFSUB(SDNode *N) {
6903 SDValue N0 = N->getOperand(0);
6904 SDValue N1 = N->getOperand(1);
6905 ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0);
6906 ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1);
6907 EVT VT = N->getValueType(0);
6909 const TargetOptions &Options = DAG.getTarget().Options;
6912 if (VT.isVector()) {
6913 SDValue FoldedVOp = SimplifyVBinOp(N);
6914 if (FoldedVOp.getNode()) return FoldedVOp;
6917 // fold (fsub c1, c2) -> c1-c2
6919 return DAG.getNode(ISD::FSUB, SDLoc(N), VT, N0, N1);
6921 // fold (fsub A, (fneg B)) -> (fadd A, B)
6922 if (isNegatibleForFree(N1, LegalOperations, TLI, &Options))
6923 return DAG.getNode(ISD::FADD, dl, VT, N0,
6924 GetNegatedExpression(N1, DAG, LegalOperations));
6926 // If 'unsafe math' is enabled, fold lots of things.
6927 if (Options.UnsafeFPMath) {
6929 if (N1CFP && N1CFP->getValueAPF().isZero())
6932 // (fsub 0, B) -> -B
6933 if (N0CFP && N0CFP->getValueAPF().isZero()) {
6934 if (isNegatibleForFree(N1, LegalOperations, TLI, &Options))
6935 return GetNegatedExpression(N1, DAG, LegalOperations);
6936 if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
6937 return DAG.getNode(ISD::FNEG, dl, VT, N1);
6940 // (fsub x, x) -> 0.0
6942 return DAG.getConstantFP(0.0f, VT);
6944 // (fsub x, (fadd x, y)) -> (fneg y)
6945 // (fsub x, (fadd y, x)) -> (fneg y)
6946 if (N1.getOpcode() == ISD::FADD) {
6947 SDValue N10 = N1->getOperand(0);
6948 SDValue N11 = N1->getOperand(1);
6950 if (N10 == N0 && isNegatibleForFree(N11, LegalOperations, TLI, &Options))
6951 return GetNegatedExpression(N11, DAG, LegalOperations);
6953 if (N11 == N0 && isNegatibleForFree(N10, LegalOperations, TLI, &Options))
6954 return GetNegatedExpression(N10, DAG, LegalOperations);
6958 // FSUB -> FMA combines:
6959 if ((Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath) &&
6960 TLI.isFMAFasterThanFMulAndFAdd(VT) &&
6961 (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT))) {
6963 // fold (fsub (fmul x, y), z) -> (fma x, y, (fneg z))
6964 if (N0.getOpcode() == ISD::FMUL &&
6965 (N0->hasOneUse() || TLI.enableAggressiveFMAFusion(VT)))
6966 return DAG.getNode(ISD::FMA, dl, VT,
6967 N0.getOperand(0), N0.getOperand(1),
6968 DAG.getNode(ISD::FNEG, dl, VT, N1));
6970 // fold (fsub x, (fmul y, z)) -> (fma (fneg y), z, x)
6971 // Note: Commutes FSUB operands.
6972 if (N1.getOpcode() == ISD::FMUL &&
6973 (N1->hasOneUse() || TLI.enableAggressiveFMAFusion(VT)))
6974 return DAG.getNode(ISD::FMA, dl, VT,
6975 DAG.getNode(ISD::FNEG, dl, VT,
6977 N1.getOperand(1), N0);
6979 // fold (fsub (fneg (fmul, x, y)), z) -> (fma (fneg x), y, (fneg z))
6980 if (N0.getOpcode() == ISD::FNEG &&
6981 N0.getOperand(0).getOpcode() == ISD::FMUL &&
6982 ((N0->hasOneUse() && N0.getOperand(0).hasOneUse()) ||
6983 TLI.enableAggressiveFMAFusion(VT))) {
6984 SDValue N00 = N0.getOperand(0).getOperand(0);
6985 SDValue N01 = N0.getOperand(0).getOperand(1);
6986 return DAG.getNode(ISD::FMA, dl, VT,
6987 DAG.getNode(ISD::FNEG, dl, VT, N00), N01,
6988 DAG.getNode(ISD::FNEG, dl, VT, N1));
6995 SDValue DAGCombiner::visitFMUL(SDNode *N) {
6996 SDValue N0 = N->getOperand(0);
6997 SDValue N1 = N->getOperand(1);
6998 ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0);
6999 ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1);
7000 EVT VT = N->getValueType(0);
7001 const TargetOptions &Options = DAG.getTarget().Options;
7004 if (VT.isVector()) {
7005 // This just handles C1 * C2 for vectors. Other vector folds are below.
7006 SDValue FoldedVOp = SimplifyVBinOp(N);
7007 if (FoldedVOp.getNode())
7009 // Canonicalize vector constant to RHS.
7010 if (N0.getOpcode() == ISD::BUILD_VECTOR &&
7011 N1.getOpcode() != ISD::BUILD_VECTOR)
7012 if (auto *BV0 = dyn_cast<BuildVectorSDNode>(N0))
7013 if (BV0->isConstant())
7014 return DAG.getNode(N->getOpcode(), SDLoc(N), VT, N1, N0);
7017 // fold (fmul c1, c2) -> c1*c2
7019 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0, N1);
7021 // canonicalize constant to RHS
7022 if (N0CFP && !N1CFP)
7023 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N1, N0);
7025 // fold (fmul A, 1.0) -> A
7026 if (N1CFP && N1CFP->isExactlyValue(1.0))
7029 if (Options.UnsafeFPMath) {
7030 // fold (fmul A, 0) -> 0
7031 if (N1CFP && N1CFP->getValueAPF().isZero())
7034 // fold (fmul (fmul x, c1), c2) -> (fmul x, (fmul c1, c2))
7035 if (N0.getOpcode() == ISD::FMUL) {
7036 // Fold scalars or any vector constants (not just splats).
7037 // This fold is done in general by InstCombine, but extra fmul insts
7038 // may have been generated during lowering.
7039 SDValue N01 = N0.getOperand(1);
7040 auto *BV1 = dyn_cast<BuildVectorSDNode>(N1);
7041 auto *BV01 = dyn_cast<BuildVectorSDNode>(N01);
7042 if ((N1CFP && isConstOrConstSplatFP(N01)) ||
7043 (BV1 && BV01 && BV1->isConstant() && BV01->isConstant())) {
7045 SDValue MulConsts = DAG.getNode(ISD::FMUL, SL, VT, N01, N1);
7046 return DAG.getNode(ISD::FMUL, SL, VT, N0.getOperand(0), MulConsts);
7050 // fold (fmul (fadd x, x), c) -> (fmul x, (fmul 2.0, c))
7051 // Undo the fmul 2.0, x -> fadd x, x transformation, since if it occurs
7052 // during an early run of DAGCombiner can prevent folding with fmuls
7053 // inserted during lowering.
7054 if (N0.getOpcode() == ISD::FADD && N0.getOperand(0) == N0.getOperand(1)) {
7056 const SDValue Two = DAG.getConstantFP(2.0, VT);
7057 SDValue MulConsts = DAG.getNode(ISD::FMUL, SL, VT, Two, N1);
7058 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0.getOperand(0), MulConsts);
7062 // fold (fmul X, 2.0) -> (fadd X, X)
7063 if (N1CFP && N1CFP->isExactlyValue(+2.0))
7064 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N0);
7066 // fold (fmul X, -1.0) -> (fneg X)
7067 if (N1CFP && N1CFP->isExactlyValue(-1.0))
7068 if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
7069 return DAG.getNode(ISD::FNEG, SDLoc(N), VT, N0);
7071 // fold (fmul (fneg X), (fneg Y)) -> (fmul X, Y)
7072 if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI, &Options)) {
7073 if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI, &Options)) {
7074 // Both can be negated for free, check to see if at least one is cheaper
7076 if (LHSNeg == 2 || RHSNeg == 2)
7077 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
7078 GetNegatedExpression(N0, DAG, LegalOperations),
7079 GetNegatedExpression(N1, DAG, LegalOperations));
7086 SDValue DAGCombiner::visitFMA(SDNode *N) {
7087 SDValue N0 = N->getOperand(0);
7088 SDValue N1 = N->getOperand(1);
7089 SDValue N2 = N->getOperand(2);
7090 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7091 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
7092 EVT VT = N->getValueType(0);
7094 const TargetOptions &Options = DAG.getTarget().Options;
7096 // Constant fold FMA.
7097 if (isa<ConstantFPSDNode>(N0) &&
7098 isa<ConstantFPSDNode>(N1) &&
7099 isa<ConstantFPSDNode>(N2)) {
7100 return DAG.getNode(ISD::FMA, dl, VT, N0, N1, N2);
7103 if (Options.UnsafeFPMath) {
7104 if (N0CFP && N0CFP->isZero())
7106 if (N1CFP && N1CFP->isZero())
7109 if (N0CFP && N0CFP->isExactlyValue(1.0))
7110 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N1, N2);
7111 if (N1CFP && N1CFP->isExactlyValue(1.0))
7112 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N2);
7114 // Canonicalize (fma c, x, y) -> (fma x, c, y)
7115 if (N0CFP && !N1CFP)
7116 return DAG.getNode(ISD::FMA, SDLoc(N), VT, N1, N0, N2);
7118 // (fma x, c1, (fmul x, c2)) -> (fmul x, c1+c2)
7119 if (Options.UnsafeFPMath && N1CFP &&
7120 N2.getOpcode() == ISD::FMUL &&
7121 N0 == N2.getOperand(0) &&
7122 N2.getOperand(1).getOpcode() == ISD::ConstantFP) {
7123 return DAG.getNode(ISD::FMUL, dl, VT, N0,
7124 DAG.getNode(ISD::FADD, dl, VT, N1, N2.getOperand(1)));
7128 // (fma (fmul x, c1), c2, y) -> (fma x, c1*c2, y)
7129 if (Options.UnsafeFPMath &&
7130 N0.getOpcode() == ISD::FMUL && N1CFP &&
7131 N0.getOperand(1).getOpcode() == ISD::ConstantFP) {
7132 return DAG.getNode(ISD::FMA, dl, VT,
7134 DAG.getNode(ISD::FMUL, dl, VT, N1, N0.getOperand(1)),
7138 // (fma x, 1, y) -> (fadd x, y)
7139 // (fma x, -1, y) -> (fadd (fneg x), y)
7141 if (N1CFP->isExactlyValue(1.0))
7142 return DAG.getNode(ISD::FADD, dl, VT, N0, N2);
7144 if (N1CFP->isExactlyValue(-1.0) &&
7145 (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))) {
7146 SDValue RHSNeg = DAG.getNode(ISD::FNEG, dl, VT, N0);
7147 AddToWorklist(RHSNeg.getNode());
7148 return DAG.getNode(ISD::FADD, dl, VT, N2, RHSNeg);
7152 // (fma x, c, x) -> (fmul x, (c+1))
7153 if (Options.UnsafeFPMath && N1CFP && N0 == N2)
7154 return DAG.getNode(ISD::FMUL, dl, VT, N0,
7155 DAG.getNode(ISD::FADD, dl, VT,
7156 N1, DAG.getConstantFP(1.0, VT)));
7158 // (fma x, c, (fneg x)) -> (fmul x, (c-1))
7159 if (Options.UnsafeFPMath && N1CFP &&
7160 N2.getOpcode() == ISD::FNEG && N2.getOperand(0) == N0)
7161 return DAG.getNode(ISD::FMUL, dl, VT, N0,
7162 DAG.getNode(ISD::FADD, dl, VT,
7163 N1, DAG.getConstantFP(-1.0, VT)));
7169 SDValue DAGCombiner::visitFDIV(SDNode *N) {
7170 SDValue N0 = N->getOperand(0);
7171 SDValue N1 = N->getOperand(1);
7172 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7173 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
7174 EVT VT = N->getValueType(0);
7176 const TargetOptions &Options = DAG.getTarget().Options;
7179 if (VT.isVector()) {
7180 SDValue FoldedVOp = SimplifyVBinOp(N);
7181 if (FoldedVOp.getNode()) return FoldedVOp;
7184 // fold (fdiv c1, c2) -> c1/c2
7186 return DAG.getNode(ISD::FDIV, SDLoc(N), VT, N0, N1);
7188 if (Options.UnsafeFPMath) {
7189 // fold (fdiv X, c2) -> fmul X, 1/c2 if losing precision is acceptable.
7191 // Compute the reciprocal 1.0 / c2.
7192 APFloat N1APF = N1CFP->getValueAPF();
7193 APFloat Recip(N1APF.getSemantics(), 1); // 1.0
7194 APFloat::opStatus st = Recip.divide(N1APF, APFloat::rmNearestTiesToEven);
7195 // Only do the transform if the reciprocal is a legal fp immediate that
7196 // isn't too nasty (eg NaN, denormal, ...).
7197 if ((st == APFloat::opOK || st == APFloat::opInexact) && // Not too nasty
7198 (!LegalOperations ||
7199 // FIXME: custom lowering of ConstantFP might fail (see e.g. ARM
7200 // backend)... we should handle this gracefully after Legalize.
7201 // TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT) ||
7202 TLI.isOperationLegal(llvm::ISD::ConstantFP, VT) ||
7203 TLI.isFPImmLegal(Recip, VT)))
7204 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0,
7205 DAG.getConstantFP(Recip, VT));
7208 // If this FDIV is part of a reciprocal square root, it may be folded
7209 // into a target-specific square root estimate instruction.
7210 if (N1.getOpcode() == ISD::FSQRT) {
7211 if (SDValue RV = BuildRsqrtEstimate(N1.getOperand(0))) {
7212 return DAG.getNode(ISD::FMUL, DL, VT, N0, RV);
7214 } else if (N1.getOpcode() == ISD::FP_EXTEND &&
7215 N1.getOperand(0).getOpcode() == ISD::FSQRT) {
7216 if (SDValue RV = BuildRsqrtEstimate(N1.getOperand(0).getOperand(0))) {
7217 RV = DAG.getNode(ISD::FP_EXTEND, SDLoc(N1), VT, RV);
7218 AddToWorklist(RV.getNode());
7219 return DAG.getNode(ISD::FMUL, DL, VT, N0, RV);
7221 } else if (N1.getOpcode() == ISD::FP_ROUND &&
7222 N1.getOperand(0).getOpcode() == ISD::FSQRT) {
7223 if (SDValue RV = BuildRsqrtEstimate(N1.getOperand(0).getOperand(0))) {
7224 RV = DAG.getNode(ISD::FP_ROUND, SDLoc(N1), VT, RV, N1.getOperand(1));
7225 AddToWorklist(RV.getNode());
7226 return DAG.getNode(ISD::FMUL, DL, VT, N0, RV);
7228 } else if (N1.getOpcode() == ISD::FMUL) {
7229 // Look through an FMUL. Even though this won't remove the FDIV directly,
7230 // it's still worthwhile to get rid of the FSQRT if possible.
7233 if (N1.getOperand(0).getOpcode() == ISD::FSQRT) {
7234 SqrtOp = N1.getOperand(0);
7235 OtherOp = N1.getOperand(1);
7236 } else if (N1.getOperand(1).getOpcode() == ISD::FSQRT) {
7237 SqrtOp = N1.getOperand(1);
7238 OtherOp = N1.getOperand(0);
7240 if (SqrtOp.getNode()) {
7241 // We found a FSQRT, so try to make this fold:
7242 // x / (y * sqrt(z)) -> x * (rsqrt(z) / y)
7243 if (SDValue RV = BuildRsqrtEstimate(SqrtOp.getOperand(0))) {
7244 RV = DAG.getNode(ISD::FDIV, SDLoc(N1), VT, RV, OtherOp);
7245 AddToWorklist(RV.getNode());
7246 return DAG.getNode(ISD::FMUL, DL, VT, N0, RV);
7251 // Fold into a reciprocal estimate and multiply instead of a real divide.
7252 if (SDValue RV = BuildReciprocalEstimate(N1)) {
7253 AddToWorklist(RV.getNode());
7254 return DAG.getNode(ISD::FMUL, DL, VT, N0, RV);
7258 // (fdiv (fneg X), (fneg Y)) -> (fdiv X, Y)
7259 if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI, &Options)) {
7260 if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI, &Options)) {
7261 // Both can be negated for free, check to see if at least one is cheaper
7263 if (LHSNeg == 2 || RHSNeg == 2)
7264 return DAG.getNode(ISD::FDIV, SDLoc(N), VT,
7265 GetNegatedExpression(N0, DAG, LegalOperations),
7266 GetNegatedExpression(N1, DAG, LegalOperations));
7270 // Combine multiple FDIVs with the same divisor into multiple FMULs by the
7272 // E.g., (a / D; b / D;) -> (recip = 1.0 / D; a * recip; b * recip)
7273 // Notice that this is not always beneficial. One reason is different target
7274 // may have different costs for FDIV and FMUL, so sometimes the cost of two
7275 // FDIVs may be lower than the cost of one FDIV and two FMULs. Another reason
7276 // is the critical path is increased from "one FDIV" to "one FDIV + one FMUL".
7277 if (Options.UnsafeFPMath) {
7278 // Skip if current node is a reciprocal.
7279 if (N0CFP && N0CFP->isExactlyValue(1.0))
7282 SmallVector<SDNode *, 4> Users;
7283 // Find all FDIV users of the same divisor.
7284 for (SDNode::use_iterator UI = N1.getNode()->use_begin(),
7285 UE = N1.getNode()->use_end();
7287 SDNode *User = UI.getUse().getUser();
7288 if (User->getOpcode() == ISD::FDIV && User->getOperand(1) == N1)
7289 Users.push_back(User);
7292 if (TLI.combineRepeatedFPDivisors(Users.size())) {
7293 SDValue FPOne = DAG.getConstantFP(1.0, VT); // floating point 1.0
7294 SDValue Reciprocal = DAG.getNode(ISD::FDIV, SDLoc(N), VT, FPOne, N1);
7296 // Dividend / Divisor -> Dividend * Reciprocal
7297 for (auto I = Users.begin(), E = Users.end(); I != E; ++I) {
7298 if ((*I)->getOperand(0) != FPOne) {
7299 SDValue NewNode = DAG.getNode(ISD::FMUL, SDLoc(*I), VT,
7300 (*I)->getOperand(0), Reciprocal);
7301 DAG.ReplaceAllUsesWith(*I, NewNode.getNode());
7311 SDValue DAGCombiner::visitFREM(SDNode *N) {
7312 SDValue N0 = N->getOperand(0);
7313 SDValue N1 = N->getOperand(1);
7314 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7315 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
7316 EVT VT = N->getValueType(0);
7318 // fold (frem c1, c2) -> fmod(c1,c2)
7320 return DAG.getNode(ISD::FREM, SDLoc(N), VT, N0, N1);
7325 SDValue DAGCombiner::visitFSQRT(SDNode *N) {
7326 if (DAG.getTarget().Options.UnsafeFPMath) {
7327 // Compute this as X * (1/sqrt(X)) = X * (X ** -0.5)
7328 if (SDValue RV = BuildRsqrtEstimate(N->getOperand(0))) {
7329 EVT VT = RV.getValueType();
7330 RV = DAG.getNode(ISD::FMUL, SDLoc(N), VT, N->getOperand(0), RV);
7331 AddToWorklist(RV.getNode());
7333 // Unfortunately, RV is now NaN if the input was exactly 0.
7334 // Select out this case and force the answer to 0.
7335 SDValue Zero = DAG.getConstantFP(0.0, VT);
7337 DAG.getSetCC(SDLoc(N), TLI.getSetCCResultType(*DAG.getContext(), VT),
7338 N->getOperand(0), Zero, ISD::SETEQ);
7339 AddToWorklist(ZeroCmp.getNode());
7340 AddToWorklist(RV.getNode());
7342 RV = DAG.getNode(VT.isVector() ? ISD::VSELECT : ISD::SELECT,
7343 SDLoc(N), VT, ZeroCmp, Zero, RV);
7350 SDValue DAGCombiner::visitFCOPYSIGN(SDNode *N) {
7351 SDValue N0 = N->getOperand(0);
7352 SDValue N1 = N->getOperand(1);
7353 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7354 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
7355 EVT VT = N->getValueType(0);
7357 if (N0CFP && N1CFP) // Constant fold
7358 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, N0, N1);
7361 const APFloat& V = N1CFP->getValueAPF();
7362 // copysign(x, c1) -> fabs(x) iff ispos(c1)
7363 // copysign(x, c1) -> fneg(fabs(x)) iff isneg(c1)
7364 if (!V.isNegative()) {
7365 if (!LegalOperations || TLI.isOperationLegal(ISD::FABS, VT))
7366 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
7368 if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
7369 return DAG.getNode(ISD::FNEG, SDLoc(N), VT,
7370 DAG.getNode(ISD::FABS, SDLoc(N0), VT, N0));
7374 // copysign(fabs(x), y) -> copysign(x, y)
7375 // copysign(fneg(x), y) -> copysign(x, y)
7376 // copysign(copysign(x,z), y) -> copysign(x, y)
7377 if (N0.getOpcode() == ISD::FABS || N0.getOpcode() == ISD::FNEG ||
7378 N0.getOpcode() == ISD::FCOPYSIGN)
7379 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
7380 N0.getOperand(0), N1);
7382 // copysign(x, abs(y)) -> abs(x)
7383 if (N1.getOpcode() == ISD::FABS)
7384 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
7386 // copysign(x, copysign(y,z)) -> copysign(x, z)
7387 if (N1.getOpcode() == ISD::FCOPYSIGN)
7388 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
7389 N0, N1.getOperand(1));
7391 // copysign(x, fp_extend(y)) -> copysign(x, y)
7392 // copysign(x, fp_round(y)) -> copysign(x, y)
7393 if (N1.getOpcode() == ISD::FP_EXTEND || N1.getOpcode() == ISD::FP_ROUND)
7394 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
7395 N0, N1.getOperand(0));
7400 SDValue DAGCombiner::visitSINT_TO_FP(SDNode *N) {
7401 SDValue N0 = N->getOperand(0);
7402 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
7403 EVT VT = N->getValueType(0);
7404 EVT OpVT = N0.getValueType();
7406 // fold (sint_to_fp c1) -> c1fp
7408 // ...but only if the target supports immediate floating-point values
7409 (!LegalOperations ||
7410 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT)))
7411 return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0);
7413 // If the input is a legal type, and SINT_TO_FP is not legal on this target,
7414 // but UINT_TO_FP is legal on this target, try to convert.
7415 if (!TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT) &&
7416 TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT)) {
7417 // If the sign bit is known to be zero, we can change this to UINT_TO_FP.
7418 if (DAG.SignBitIsZero(N0))
7419 return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0);
7422 // The next optimizations are desirable only if SELECT_CC can be lowered.
7423 if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT) || !LegalOperations) {
7424 // fold (sint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc)
7425 if (N0.getOpcode() == ISD::SETCC && N0.getValueType() == MVT::i1 &&
7427 (!LegalOperations ||
7428 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
7430 { N0.getOperand(0), N0.getOperand(1),
7431 DAG.getConstantFP(-1.0, VT) , DAG.getConstantFP(0.0, VT),
7433 return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT, Ops);
7436 // fold (sint_to_fp (zext (setcc x, y, cc))) ->
7437 // (select_cc x, y, 1.0, 0.0,, cc)
7438 if (N0.getOpcode() == ISD::ZERO_EXTEND &&
7439 N0.getOperand(0).getOpcode() == ISD::SETCC &&!VT.isVector() &&
7440 (!LegalOperations ||
7441 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
7443 { N0.getOperand(0).getOperand(0), N0.getOperand(0).getOperand(1),
7444 DAG.getConstantFP(1.0, VT) , DAG.getConstantFP(0.0, VT),
7445 N0.getOperand(0).getOperand(2) };
7446 return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT, Ops);
7453 SDValue DAGCombiner::visitUINT_TO_FP(SDNode *N) {
7454 SDValue N0 = N->getOperand(0);
7455 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
7456 EVT VT = N->getValueType(0);
7457 EVT OpVT = N0.getValueType();
7459 // fold (uint_to_fp c1) -> c1fp
7461 // ...but only if the target supports immediate floating-point values
7462 (!LegalOperations ||
7463 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT)))
7464 return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0);
7466 // If the input is a legal type, and UINT_TO_FP is not legal on this target,
7467 // but SINT_TO_FP is legal on this target, try to convert.
7468 if (!TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT) &&
7469 TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT)) {
7470 // If the sign bit is known to be zero, we can change this to SINT_TO_FP.
7471 if (DAG.SignBitIsZero(N0))
7472 return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0);
7475 // The next optimizations are desirable only if SELECT_CC can be lowered.
7476 if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT) || !LegalOperations) {
7477 // fold (uint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc)
7479 if (N0.getOpcode() == ISD::SETCC && !VT.isVector() &&
7480 (!LegalOperations ||
7481 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
7483 { N0.getOperand(0), N0.getOperand(1),
7484 DAG.getConstantFP(1.0, VT), DAG.getConstantFP(0.0, VT),
7486 return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT, Ops);
7493 SDValue DAGCombiner::visitFP_TO_SINT(SDNode *N) {
7494 SDValue N0 = N->getOperand(0);
7495 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7496 EVT VT = N->getValueType(0);
7498 // fold (fp_to_sint c1fp) -> c1
7500 return DAG.getNode(ISD::FP_TO_SINT, SDLoc(N), VT, N0);
7505 SDValue DAGCombiner::visitFP_TO_UINT(SDNode *N) {
7506 SDValue N0 = N->getOperand(0);
7507 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7508 EVT VT = N->getValueType(0);
7510 // fold (fp_to_uint c1fp) -> c1
7512 return DAG.getNode(ISD::FP_TO_UINT, SDLoc(N), VT, N0);
7517 SDValue DAGCombiner::visitFP_ROUND(SDNode *N) {
7518 SDValue N0 = N->getOperand(0);
7519 SDValue N1 = N->getOperand(1);
7520 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7521 EVT VT = N->getValueType(0);
7523 // fold (fp_round c1fp) -> c1fp
7525 return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT, N0, N1);
7527 // fold (fp_round (fp_extend x)) -> x
7528 if (N0.getOpcode() == ISD::FP_EXTEND && VT == N0.getOperand(0).getValueType())
7529 return N0.getOperand(0);
7531 // fold (fp_round (fp_round x)) -> (fp_round x)
7532 if (N0.getOpcode() == ISD::FP_ROUND) {
7533 // This is a value preserving truncation if both round's are.
7534 bool IsTrunc = N->getConstantOperandVal(1) == 1 &&
7535 N0.getNode()->getConstantOperandVal(1) == 1;
7536 return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT, N0.getOperand(0),
7537 DAG.getIntPtrConstant(IsTrunc));
7540 // fold (fp_round (copysign X, Y)) -> (copysign (fp_round X), Y)
7541 if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse()) {
7542 SDValue Tmp = DAG.getNode(ISD::FP_ROUND, SDLoc(N0), VT,
7543 N0.getOperand(0), N1);
7544 AddToWorklist(Tmp.getNode());
7545 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
7546 Tmp, N0.getOperand(1));
7552 SDValue DAGCombiner::visitFP_ROUND_INREG(SDNode *N) {
7553 SDValue N0 = N->getOperand(0);
7554 EVT VT = N->getValueType(0);
7555 EVT EVT = cast<VTSDNode>(N->getOperand(1))->getVT();
7556 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7558 // fold (fp_round_inreg c1fp) -> c1fp
7559 if (N0CFP && isTypeLegal(EVT)) {
7560 SDValue Round = DAG.getConstantFP(*N0CFP->getConstantFPValue(), EVT);
7561 return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, Round);
7567 SDValue DAGCombiner::visitFP_EXTEND(SDNode *N) {
7568 SDValue N0 = N->getOperand(0);
7569 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7570 EVT VT = N->getValueType(0);
7572 // If this is fp_round(fpextend), don't fold it, allow ourselves to be folded.
7573 if (N->hasOneUse() &&
7574 N->use_begin()->getOpcode() == ISD::FP_ROUND)
7577 // fold (fp_extend c1fp) -> c1fp
7579 return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, N0);
7581 // Turn fp_extend(fp_round(X, 1)) -> x since the fp_round doesn't affect the
7583 if (N0.getOpcode() == ISD::FP_ROUND
7584 && N0.getNode()->getConstantOperandVal(1) == 1) {
7585 SDValue In = N0.getOperand(0);
7586 if (In.getValueType() == VT) return In;
7587 if (VT.bitsLT(In.getValueType()))
7588 return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT,
7589 In, N0.getOperand(1));
7590 return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, In);
7593 // fold (fpext (load x)) -> (fpext (fptrunc (extload x)))
7594 if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
7595 TLI.isLoadExtLegal(ISD::EXTLOAD, N0.getValueType())) {
7596 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
7597 SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT,
7599 LN0->getBasePtr(), N0.getValueType(),
7600 LN0->getMemOperand());
7601 CombineTo(N, ExtLoad);
7602 CombineTo(N0.getNode(),
7603 DAG.getNode(ISD::FP_ROUND, SDLoc(N0),
7604 N0.getValueType(), ExtLoad, DAG.getIntPtrConstant(1)),
7605 ExtLoad.getValue(1));
7606 return SDValue(N, 0); // Return N so it doesn't get rechecked!
7612 SDValue DAGCombiner::visitFCEIL(SDNode *N) {
7613 SDValue N0 = N->getOperand(0);
7614 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7615 EVT VT = N->getValueType(0);
7617 // fold (fceil c1) -> fceil(c1)
7619 return DAG.getNode(ISD::FCEIL, SDLoc(N), VT, N0);
7624 SDValue DAGCombiner::visitFTRUNC(SDNode *N) {
7625 SDValue N0 = N->getOperand(0);
7626 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7627 EVT VT = N->getValueType(0);
7629 // fold (ftrunc c1) -> ftrunc(c1)
7631 return DAG.getNode(ISD::FTRUNC, SDLoc(N), VT, N0);
7636 SDValue DAGCombiner::visitFFLOOR(SDNode *N) {
7637 SDValue N0 = N->getOperand(0);
7638 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7639 EVT VT = N->getValueType(0);
7641 // fold (ffloor c1) -> ffloor(c1)
7643 return DAG.getNode(ISD::FFLOOR, SDLoc(N), VT, N0);
7648 // FIXME: FNEG and FABS have a lot in common; refactor.
7649 SDValue DAGCombiner::visitFNEG(SDNode *N) {
7650 SDValue N0 = N->getOperand(0);
7651 EVT VT = N->getValueType(0);
7653 if (VT.isVector()) {
7654 SDValue FoldedVOp = SimplifyVUnaryOp(N);
7655 if (FoldedVOp.getNode()) return FoldedVOp;
7658 // Constant fold FNEG.
7659 if (isa<ConstantFPSDNode>(N0))
7660 return DAG.getNode(ISD::FNEG, SDLoc(N), VT, N->getOperand(0));
7662 if (isNegatibleForFree(N0, LegalOperations, DAG.getTargetLoweringInfo(),
7663 &DAG.getTarget().Options))
7664 return GetNegatedExpression(N0, DAG, LegalOperations);
7666 // Transform fneg(bitconvert(x)) -> bitconvert(x ^ sign) to avoid loading
7667 // constant pool values.
7668 if (!TLI.isFNegFree(VT) &&
7669 N0.getOpcode() == ISD::BITCAST &&
7670 N0.getNode()->hasOneUse()) {
7671 SDValue Int = N0.getOperand(0);
7672 EVT IntVT = Int.getValueType();
7673 if (IntVT.isInteger() && !IntVT.isVector()) {
7675 if (N0.getValueType().isVector()) {
7676 // For a vector, get a mask such as 0x80... per scalar element
7678 SignMask = APInt::getSignBit(N0.getValueType().getScalarSizeInBits());
7679 SignMask = APInt::getSplat(IntVT.getSizeInBits(), SignMask);
7681 // For a scalar, just generate 0x80...
7682 SignMask = APInt::getSignBit(IntVT.getSizeInBits());
7684 Int = DAG.getNode(ISD::XOR, SDLoc(N0), IntVT, Int,
7685 DAG.getConstant(SignMask, IntVT));
7686 AddToWorklist(Int.getNode());
7687 return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Int);
7691 // (fneg (fmul c, x)) -> (fmul -c, x)
7692 if (N0.getOpcode() == ISD::FMUL) {
7693 ConstantFPSDNode *CFP1 = dyn_cast<ConstantFPSDNode>(N0.getOperand(1));
7695 APFloat CVal = CFP1->getValueAPF();
7697 if (Level >= AfterLegalizeDAG &&
7698 (TLI.isFPImmLegal(CVal, N->getValueType(0)) ||
7699 TLI.isOperationLegal(ISD::ConstantFP, N->getValueType(0))))
7701 ISD::FMUL, SDLoc(N), VT, N0.getOperand(0),
7702 DAG.getNode(ISD::FNEG, SDLoc(N), VT, N0.getOperand(1)));
7709 SDValue DAGCombiner::visitFMINNUM(SDNode *N) {
7710 SDValue N0 = N->getOperand(0);
7711 SDValue N1 = N->getOperand(1);
7712 const ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7713 const ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
7715 if (N0CFP && N1CFP) {
7716 const APFloat &C0 = N0CFP->getValueAPF();
7717 const APFloat &C1 = N1CFP->getValueAPF();
7718 return DAG.getConstantFP(minnum(C0, C1), N->getValueType(0));
7722 EVT VT = N->getValueType(0);
7723 // Canonicalize to constant on RHS.
7724 return DAG.getNode(ISD::FMINNUM, SDLoc(N), VT, N1, N0);
7730 SDValue DAGCombiner::visitFMAXNUM(SDNode *N) {
7731 SDValue N0 = N->getOperand(0);
7732 SDValue N1 = N->getOperand(1);
7733 const ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7734 const ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
7736 if (N0CFP && N1CFP) {
7737 const APFloat &C0 = N0CFP->getValueAPF();
7738 const APFloat &C1 = N1CFP->getValueAPF();
7739 return DAG.getConstantFP(maxnum(C0, C1), N->getValueType(0));
7743 EVT VT = N->getValueType(0);
7744 // Canonicalize to constant on RHS.
7745 return DAG.getNode(ISD::FMAXNUM, SDLoc(N), VT, N1, N0);
7751 SDValue DAGCombiner::visitFABS(SDNode *N) {
7752 SDValue N0 = N->getOperand(0);
7753 EVT VT = N->getValueType(0);
7755 if (VT.isVector()) {
7756 SDValue FoldedVOp = SimplifyVUnaryOp(N);
7757 if (FoldedVOp.getNode()) return FoldedVOp;
7760 // fold (fabs c1) -> fabs(c1)
7761 if (isa<ConstantFPSDNode>(N0))
7762 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
7764 // fold (fabs (fabs x)) -> (fabs x)
7765 if (N0.getOpcode() == ISD::FABS)
7766 return N->getOperand(0);
7768 // fold (fabs (fneg x)) -> (fabs x)
7769 // fold (fabs (fcopysign x, y)) -> (fabs x)
7770 if (N0.getOpcode() == ISD::FNEG || N0.getOpcode() == ISD::FCOPYSIGN)
7771 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0.getOperand(0));
7773 // Transform fabs(bitconvert(x)) -> bitconvert(x & ~sign) to avoid loading
7774 // constant pool values.
7775 if (!TLI.isFAbsFree(VT) &&
7776 N0.getOpcode() == ISD::BITCAST &&
7777 N0.getNode()->hasOneUse()) {
7778 SDValue Int = N0.getOperand(0);
7779 EVT IntVT = Int.getValueType();
7780 if (IntVT.isInteger() && !IntVT.isVector()) {
7782 if (N0.getValueType().isVector()) {
7783 // For a vector, get a mask such as 0x7f... per scalar element
7785 SignMask = ~APInt::getSignBit(N0.getValueType().getScalarSizeInBits());
7786 SignMask = APInt::getSplat(IntVT.getSizeInBits(), SignMask);
7788 // For a scalar, just generate 0x7f...
7789 SignMask = ~APInt::getSignBit(IntVT.getSizeInBits());
7791 Int = DAG.getNode(ISD::AND, SDLoc(N0), IntVT, Int,
7792 DAG.getConstant(SignMask, IntVT));
7793 AddToWorklist(Int.getNode());
7794 return DAG.getNode(ISD::BITCAST, SDLoc(N), N->getValueType(0), Int);
7801 SDValue DAGCombiner::visitBRCOND(SDNode *N) {
7802 SDValue Chain = N->getOperand(0);
7803 SDValue N1 = N->getOperand(1);
7804 SDValue N2 = N->getOperand(2);
7806 // If N is a constant we could fold this into a fallthrough or unconditional
7807 // branch. However that doesn't happen very often in normal code, because
7808 // Instcombine/SimplifyCFG should have handled the available opportunities.
7809 // If we did this folding here, it would be necessary to update the
7810 // MachineBasicBlock CFG, which is awkward.
7812 // fold a brcond with a setcc condition into a BR_CC node if BR_CC is legal
7814 if (N1.getOpcode() == ISD::SETCC &&
7815 TLI.isOperationLegalOrCustom(ISD::BR_CC,
7816 N1.getOperand(0).getValueType())) {
7817 return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other,
7818 Chain, N1.getOperand(2),
7819 N1.getOperand(0), N1.getOperand(1), N2);
7822 if ((N1.hasOneUse() && N1.getOpcode() == ISD::SRL) ||
7823 ((N1.getOpcode() == ISD::TRUNCATE && N1.hasOneUse()) &&
7824 (N1.getOperand(0).hasOneUse() &&
7825 N1.getOperand(0).getOpcode() == ISD::SRL))) {
7826 SDNode *Trunc = nullptr;
7827 if (N1.getOpcode() == ISD::TRUNCATE) {
7828 // Look pass the truncate.
7829 Trunc = N1.getNode();
7830 N1 = N1.getOperand(0);
7833 // Match this pattern so that we can generate simpler code:
7836 // %b = and i32 %a, 2
7837 // %c = srl i32 %b, 1
7838 // brcond i32 %c ...
7843 // %b = and i32 %a, 2
7844 // %c = setcc eq %b, 0
7847 // This applies only when the AND constant value has one bit set and the
7848 // SRL constant is equal to the log2 of the AND constant. The back-end is
7849 // smart enough to convert the result into a TEST/JMP sequence.
7850 SDValue Op0 = N1.getOperand(0);
7851 SDValue Op1 = N1.getOperand(1);
7853 if (Op0.getOpcode() == ISD::AND &&
7854 Op1.getOpcode() == ISD::Constant) {
7855 SDValue AndOp1 = Op0.getOperand(1);
7857 if (AndOp1.getOpcode() == ISD::Constant) {
7858 const APInt &AndConst = cast<ConstantSDNode>(AndOp1)->getAPIntValue();
7860 if (AndConst.isPowerOf2() &&
7861 cast<ConstantSDNode>(Op1)->getAPIntValue()==AndConst.logBase2()) {
7863 DAG.getSetCC(SDLoc(N),
7864 getSetCCResultType(Op0.getValueType()),
7865 Op0, DAG.getConstant(0, Op0.getValueType()),
7868 SDValue NewBRCond = DAG.getNode(ISD::BRCOND, SDLoc(N),
7869 MVT::Other, Chain, SetCC, N2);
7870 // Don't add the new BRCond into the worklist or else SimplifySelectCC
7871 // will convert it back to (X & C1) >> C2.
7872 CombineTo(N, NewBRCond, false);
7873 // Truncate is dead.
7875 deleteAndRecombine(Trunc);
7876 // Replace the uses of SRL with SETCC
7877 WorklistRemover DeadNodes(*this);
7878 DAG.ReplaceAllUsesOfValueWith(N1, SetCC);
7879 deleteAndRecombine(N1.getNode());
7880 return SDValue(N, 0); // Return N so it doesn't get rechecked!
7886 // Restore N1 if the above transformation doesn't match.
7887 N1 = N->getOperand(1);
7890 // Transform br(xor(x, y)) -> br(x != y)
7891 // Transform br(xor(xor(x,y), 1)) -> br (x == y)
7892 if (N1.hasOneUse() && N1.getOpcode() == ISD::XOR) {
7893 SDNode *TheXor = N1.getNode();
7894 SDValue Op0 = TheXor->getOperand(0);
7895 SDValue Op1 = TheXor->getOperand(1);
7896 if (Op0.getOpcode() == Op1.getOpcode()) {
7897 // Avoid missing important xor optimizations.
7898 SDValue Tmp = visitXOR(TheXor);
7899 if (Tmp.getNode()) {
7900 if (Tmp.getNode() != TheXor) {
7901 DEBUG(dbgs() << "\nReplacing.8 ";
7903 dbgs() << "\nWith: ";
7904 Tmp.getNode()->dump(&DAG);
7906 WorklistRemover DeadNodes(*this);
7907 DAG.ReplaceAllUsesOfValueWith(N1, Tmp);
7908 deleteAndRecombine(TheXor);
7909 return DAG.getNode(ISD::BRCOND, SDLoc(N),
7910 MVT::Other, Chain, Tmp, N2);
7913 // visitXOR has changed XOR's operands or replaced the XOR completely,
7915 return SDValue(N, 0);
7919 if (Op0.getOpcode() != ISD::SETCC && Op1.getOpcode() != ISD::SETCC) {
7921 if (ConstantSDNode *RHSCI = dyn_cast<ConstantSDNode>(Op0))
7922 if (RHSCI->getAPIntValue() == 1 && Op0.hasOneUse() &&
7923 Op0.getOpcode() == ISD::XOR) {
7924 TheXor = Op0.getNode();
7928 EVT SetCCVT = N1.getValueType();
7930 SetCCVT = getSetCCResultType(SetCCVT);
7931 SDValue SetCC = DAG.getSetCC(SDLoc(TheXor),
7934 Equal ? ISD::SETEQ : ISD::SETNE);
7935 // Replace the uses of XOR with SETCC
7936 WorklistRemover DeadNodes(*this);
7937 DAG.ReplaceAllUsesOfValueWith(N1, SetCC);
7938 deleteAndRecombine(N1.getNode());
7939 return DAG.getNode(ISD::BRCOND, SDLoc(N),
7940 MVT::Other, Chain, SetCC, N2);
7947 // Operand List for BR_CC: Chain, CondCC, CondLHS, CondRHS, DestBB.
7949 SDValue DAGCombiner::visitBR_CC(SDNode *N) {
7950 CondCodeSDNode *CC = cast<CondCodeSDNode>(N->getOperand(1));
7951 SDValue CondLHS = N->getOperand(2), CondRHS = N->getOperand(3);
7953 // If N is a constant we could fold this into a fallthrough or unconditional
7954 // branch. However that doesn't happen very often in normal code, because
7955 // Instcombine/SimplifyCFG should have handled the available opportunities.
7956 // If we did this folding here, it would be necessary to update the
7957 // MachineBasicBlock CFG, which is awkward.
7959 // Use SimplifySetCC to simplify SETCC's.
7960 SDValue Simp = SimplifySetCC(getSetCCResultType(CondLHS.getValueType()),
7961 CondLHS, CondRHS, CC->get(), SDLoc(N),
7963 if (Simp.getNode()) AddToWorklist(Simp.getNode());
7965 // fold to a simpler setcc
7966 if (Simp.getNode() && Simp.getOpcode() == ISD::SETCC)
7967 return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other,
7968 N->getOperand(0), Simp.getOperand(2),
7969 Simp.getOperand(0), Simp.getOperand(1),
7975 /// Return true if 'Use' is a load or a store that uses N as its base pointer
7976 /// and that N may be folded in the load / store addressing mode.
7977 static bool canFoldInAddressingMode(SDNode *N, SDNode *Use,
7979 const TargetLowering &TLI) {
7981 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Use)) {
7982 if (LD->isIndexed() || LD->getBasePtr().getNode() != N)
7984 VT = Use->getValueType(0);
7985 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(Use)) {
7986 if (ST->isIndexed() || ST->getBasePtr().getNode() != N)
7988 VT = ST->getValue().getValueType();
7992 TargetLowering::AddrMode AM;
7993 if (N->getOpcode() == ISD::ADD) {
7994 ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1));
7997 AM.BaseOffs = Offset->getSExtValue();
8001 } else if (N->getOpcode() == ISD::SUB) {
8002 ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1));
8005 AM.BaseOffs = -Offset->getSExtValue();
8012 return TLI.isLegalAddressingMode(AM, VT.getTypeForEVT(*DAG.getContext()));
8015 /// Try turning a load/store into a pre-indexed load/store when the base
8016 /// pointer is an add or subtract and it has other uses besides the load/store.
8017 /// After the transformation, the new indexed load/store has effectively folded
8018 /// the add/subtract in and all of its other uses are redirected to the
8020 bool DAGCombiner::CombineToPreIndexedLoadStore(SDNode *N) {
8021 if (Level < AfterLegalizeDAG)
8027 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
8028 if (LD->isIndexed())
8030 VT = LD->getMemoryVT();
8031 if (!TLI.isIndexedLoadLegal(ISD::PRE_INC, VT) &&
8032 !TLI.isIndexedLoadLegal(ISD::PRE_DEC, VT))
8034 Ptr = LD->getBasePtr();
8035 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
8036 if (ST->isIndexed())
8038 VT = ST->getMemoryVT();
8039 if (!TLI.isIndexedStoreLegal(ISD::PRE_INC, VT) &&
8040 !TLI.isIndexedStoreLegal(ISD::PRE_DEC, VT))
8042 Ptr = ST->getBasePtr();
8048 // If the pointer is not an add/sub, or if it doesn't have multiple uses, bail
8049 // out. There is no reason to make this a preinc/predec.
8050 if ((Ptr.getOpcode() != ISD::ADD && Ptr.getOpcode() != ISD::SUB) ||
8051 Ptr.getNode()->hasOneUse())
8054 // Ask the target to do addressing mode selection.
8057 ISD::MemIndexedMode AM = ISD::UNINDEXED;
8058 if (!TLI.getPreIndexedAddressParts(N, BasePtr, Offset, AM, DAG))
8061 // Backends without true r+i pre-indexed forms may need to pass a
8062 // constant base with a variable offset so that constant coercion
8063 // will work with the patterns in canonical form.
8064 bool Swapped = false;
8065 if (isa<ConstantSDNode>(BasePtr)) {
8066 std::swap(BasePtr, Offset);
8070 // Don't create a indexed load / store with zero offset.
8071 if (isa<ConstantSDNode>(Offset) &&
8072 cast<ConstantSDNode>(Offset)->isNullValue())
8075 // Try turning it into a pre-indexed load / store except when:
8076 // 1) The new base ptr is a frame index.
8077 // 2) If N is a store and the new base ptr is either the same as or is a
8078 // predecessor of the value being stored.
8079 // 3) Another use of old base ptr is a predecessor of N. If ptr is folded
8080 // that would create a cycle.
8081 // 4) All uses are load / store ops that use it as old base ptr.
8083 // Check #1. Preinc'ing a frame index would require copying the stack pointer
8084 // (plus the implicit offset) to a register to preinc anyway.
8085 if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr))
8090 SDValue Val = cast<StoreSDNode>(N)->getValue();
8091 if (Val == BasePtr || BasePtr.getNode()->isPredecessorOf(Val.getNode()))
8095 // If the offset is a constant, there may be other adds of constants that
8096 // can be folded with this one. We should do this to avoid having to keep
8097 // a copy of the original base pointer.
8098 SmallVector<SDNode *, 16> OtherUses;
8099 if (isa<ConstantSDNode>(Offset))
8100 for (SDNode *Use : BasePtr.getNode()->uses()) {
8101 if (Use == Ptr.getNode())
8104 if (Use->isPredecessorOf(N))
8107 if (Use->getOpcode() != ISD::ADD && Use->getOpcode() != ISD::SUB) {
8112 SDValue Op0 = Use->getOperand(0), Op1 = Use->getOperand(1);
8113 if (Op1.getNode() == BasePtr.getNode())
8114 std::swap(Op0, Op1);
8115 assert(Op0.getNode() == BasePtr.getNode() &&
8116 "Use of ADD/SUB but not an operand");
8118 if (!isa<ConstantSDNode>(Op1)) {
8123 // FIXME: In some cases, we can be smarter about this.
8124 if (Op1.getValueType() != Offset.getValueType()) {
8129 OtherUses.push_back(Use);
8133 std::swap(BasePtr, Offset);
8135 // Now check for #3 and #4.
8136 bool RealUse = false;
8138 // Caches for hasPredecessorHelper
8139 SmallPtrSet<const SDNode *, 32> Visited;
8140 SmallVector<const SDNode *, 16> Worklist;
8142 for (SDNode *Use : Ptr.getNode()->uses()) {
8145 if (N->hasPredecessorHelper(Use, Visited, Worklist))
8148 // If Ptr may be folded in addressing mode of other use, then it's
8149 // not profitable to do this transformation.
8150 if (!canFoldInAddressingMode(Ptr.getNode(), Use, DAG, TLI))
8159 Result = DAG.getIndexedLoad(SDValue(N,0), SDLoc(N),
8160 BasePtr, Offset, AM);
8162 Result = DAG.getIndexedStore(SDValue(N,0), SDLoc(N),
8163 BasePtr, Offset, AM);
8166 DEBUG(dbgs() << "\nReplacing.4 ";
8168 dbgs() << "\nWith: ";
8169 Result.getNode()->dump(&DAG);
8171 WorklistRemover DeadNodes(*this);
8173 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0));
8174 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2));
8176 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1));
8179 // Finally, since the node is now dead, remove it from the graph.
8180 deleteAndRecombine(N);
8183 std::swap(BasePtr, Offset);
8185 // Replace other uses of BasePtr that can be updated to use Ptr
8186 for (unsigned i = 0, e = OtherUses.size(); i != e; ++i) {
8187 unsigned OffsetIdx = 1;
8188 if (OtherUses[i]->getOperand(OffsetIdx).getNode() == BasePtr.getNode())
8190 assert(OtherUses[i]->getOperand(!OffsetIdx).getNode() ==
8191 BasePtr.getNode() && "Expected BasePtr operand");
8193 // We need to replace ptr0 in the following expression:
8194 // x0 * offset0 + y0 * ptr0 = t0
8196 // x1 * offset1 + y1 * ptr0 = t1 (the indexed load/store)
8198 // where x0, x1, y0 and y1 in {-1, 1} are given by the types of the
8199 // indexed load/store and the expresion that needs to be re-written.
8201 // Therefore, we have:
8202 // t0 = (x0 * offset0 - x1 * y0 * y1 *offset1) + (y0 * y1) * t1
8204 ConstantSDNode *CN =
8205 cast<ConstantSDNode>(OtherUses[i]->getOperand(OffsetIdx));
8207 APInt Offset0 = CN->getAPIntValue();
8208 APInt Offset1 = cast<ConstantSDNode>(Offset)->getAPIntValue();
8210 X0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 1) ? -1 : 1;
8211 Y0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 0) ? -1 : 1;
8212 X1 = (AM == ISD::PRE_DEC && !Swapped) ? -1 : 1;
8213 Y1 = (AM == ISD::PRE_DEC && Swapped) ? -1 : 1;
8215 unsigned Opcode = (Y0 * Y1 < 0) ? ISD::SUB : ISD::ADD;
8217 APInt CNV = Offset0;
8218 if (X0 < 0) CNV = -CNV;
8219 if (X1 * Y0 * Y1 < 0) CNV = CNV + Offset1;
8220 else CNV = CNV - Offset1;
8222 // We can now generate the new expression.
8223 SDValue NewOp1 = DAG.getConstant(CNV, CN->getValueType(0));
8224 SDValue NewOp2 = Result.getValue(isLoad ? 1 : 0);
8226 SDValue NewUse = DAG.getNode(Opcode,
8227 SDLoc(OtherUses[i]),
8228 OtherUses[i]->getValueType(0), NewOp1, NewOp2);
8229 DAG.ReplaceAllUsesOfValueWith(SDValue(OtherUses[i], 0), NewUse);
8230 deleteAndRecombine(OtherUses[i]);
8233 // Replace the uses of Ptr with uses of the updated base value.
8234 DAG.ReplaceAllUsesOfValueWith(Ptr, Result.getValue(isLoad ? 1 : 0));
8235 deleteAndRecombine(Ptr.getNode());
8240 /// Try to combine a load/store with a add/sub of the base pointer node into a
8241 /// post-indexed load/store. The transformation folded the add/subtract into the
8242 /// new indexed load/store effectively and all of its uses are redirected to the
8244 bool DAGCombiner::CombineToPostIndexedLoadStore(SDNode *N) {
8245 if (Level < AfterLegalizeDAG)
8251 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
8252 if (LD->isIndexed())
8254 VT = LD->getMemoryVT();
8255 if (!TLI.isIndexedLoadLegal(ISD::POST_INC, VT) &&
8256 !TLI.isIndexedLoadLegal(ISD::POST_DEC, VT))
8258 Ptr = LD->getBasePtr();
8259 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
8260 if (ST->isIndexed())
8262 VT = ST->getMemoryVT();
8263 if (!TLI.isIndexedStoreLegal(ISD::POST_INC, VT) &&
8264 !TLI.isIndexedStoreLegal(ISD::POST_DEC, VT))
8266 Ptr = ST->getBasePtr();
8272 if (Ptr.getNode()->hasOneUse())
8275 for (SDNode *Op : Ptr.getNode()->uses()) {
8277 (Op->getOpcode() != ISD::ADD && Op->getOpcode() != ISD::SUB))
8282 ISD::MemIndexedMode AM = ISD::UNINDEXED;
8283 if (TLI.getPostIndexedAddressParts(N, Op, BasePtr, Offset, AM, DAG)) {
8284 // Don't create a indexed load / store with zero offset.
8285 if (isa<ConstantSDNode>(Offset) &&
8286 cast<ConstantSDNode>(Offset)->isNullValue())
8289 // Try turning it into a post-indexed load / store except when
8290 // 1) All uses are load / store ops that use it as base ptr (and
8291 // it may be folded as addressing mmode).
8292 // 2) Op must be independent of N, i.e. Op is neither a predecessor
8293 // nor a successor of N. Otherwise, if Op is folded that would
8296 if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr))
8300 bool TryNext = false;
8301 for (SDNode *Use : BasePtr.getNode()->uses()) {
8302 if (Use == Ptr.getNode())
8305 // If all the uses are load / store addresses, then don't do the
8307 if (Use->getOpcode() == ISD::ADD || Use->getOpcode() == ISD::SUB){
8308 bool RealUse = false;
8309 for (SDNode *UseUse : Use->uses()) {
8310 if (!canFoldInAddressingMode(Use, UseUse, DAG, TLI))
8325 if (!Op->isPredecessorOf(N) && !N->isPredecessorOf(Op)) {
8326 SDValue Result = isLoad
8327 ? DAG.getIndexedLoad(SDValue(N,0), SDLoc(N),
8328 BasePtr, Offset, AM)
8329 : DAG.getIndexedStore(SDValue(N,0), SDLoc(N),
8330 BasePtr, Offset, AM);
8333 DEBUG(dbgs() << "\nReplacing.5 ";
8335 dbgs() << "\nWith: ";
8336 Result.getNode()->dump(&DAG);
8338 WorklistRemover DeadNodes(*this);
8340 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0));
8341 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2));
8343 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1));
8346 // Finally, since the node is now dead, remove it from the graph.
8347 deleteAndRecombine(N);
8349 // Replace the uses of Use with uses of the updated base value.
8350 DAG.ReplaceAllUsesOfValueWith(SDValue(Op, 0),
8351 Result.getValue(isLoad ? 1 : 0));
8352 deleteAndRecombine(Op);
8361 /// \brief Return the base-pointer arithmetic from an indexed \p LD.
8362 SDValue DAGCombiner::SplitIndexingFromLoad(LoadSDNode *LD) {
8363 ISD::MemIndexedMode AM = LD->getAddressingMode();
8364 assert(AM != ISD::UNINDEXED);
8365 SDValue BP = LD->getOperand(1);
8366 SDValue Inc = LD->getOperand(2);
8368 // Some backends use TargetConstants for load offsets, but don't expect
8369 // TargetConstants in general ADD nodes. We can convert these constants into
8370 // regular Constants (if the constant is not opaque).
8371 assert((Inc.getOpcode() != ISD::TargetConstant ||
8372 !cast<ConstantSDNode>(Inc)->isOpaque()) &&
8373 "Cannot split out indexing using opaque target constants");
8374 if (Inc.getOpcode() == ISD::TargetConstant) {
8375 ConstantSDNode *ConstInc = cast<ConstantSDNode>(Inc);
8376 Inc = DAG.getConstant(*ConstInc->getConstantIntValue(),
8377 ConstInc->getValueType(0));
8381 (AM == ISD::PRE_INC || AM == ISD::POST_INC ? ISD::ADD : ISD::SUB);
8382 return DAG.getNode(Opc, SDLoc(LD), BP.getSimpleValueType(), BP, Inc);
8385 SDValue DAGCombiner::visitLOAD(SDNode *N) {
8386 LoadSDNode *LD = cast<LoadSDNode>(N);
8387 SDValue Chain = LD->getChain();
8388 SDValue Ptr = LD->getBasePtr();
8390 // If load is not volatile and there are no uses of the loaded value (and
8391 // the updated indexed value in case of indexed loads), change uses of the
8392 // chain value into uses of the chain input (i.e. delete the dead load).
8393 if (!LD->isVolatile()) {
8394 if (N->getValueType(1) == MVT::Other) {
8396 if (!N->hasAnyUseOfValue(0)) {
8397 // It's not safe to use the two value CombineTo variant here. e.g.
8398 // v1, chain2 = load chain1, loc
8399 // v2, chain3 = load chain2, loc
8401 // Now we replace use of chain2 with chain1. This makes the second load
8402 // isomorphic to the one we are deleting, and thus makes this load live.
8403 DEBUG(dbgs() << "\nReplacing.6 ";
8405 dbgs() << "\nWith chain: ";
8406 Chain.getNode()->dump(&DAG);
8408 WorklistRemover DeadNodes(*this);
8409 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain);
8412 deleteAndRecombine(N);
8414 return SDValue(N, 0); // Return N so it doesn't get rechecked!
8418 assert(N->getValueType(2) == MVT::Other && "Malformed indexed loads?");
8420 // If this load has an opaque TargetConstant offset, then we cannot split
8421 // the indexing into an add/sub directly (that TargetConstant may not be
8422 // valid for a different type of node, and we cannot convert an opaque
8423 // target constant into a regular constant).
8424 bool HasOTCInc = LD->getOperand(2).getOpcode() == ISD::TargetConstant &&
8425 cast<ConstantSDNode>(LD->getOperand(2))->isOpaque();
8427 if (!N->hasAnyUseOfValue(0) &&
8428 ((MaySplitLoadIndex && !HasOTCInc) || !N->hasAnyUseOfValue(1))) {
8429 SDValue Undef = DAG.getUNDEF(N->getValueType(0));
8431 if (N->hasAnyUseOfValue(1) && MaySplitLoadIndex && !HasOTCInc) {
8432 Index = SplitIndexingFromLoad(LD);
8433 // Try to fold the base pointer arithmetic into subsequent loads and
8435 AddUsersToWorklist(N);
8437 Index = DAG.getUNDEF(N->getValueType(1));
8438 DEBUG(dbgs() << "\nReplacing.7 ";
8440 dbgs() << "\nWith: ";
8441 Undef.getNode()->dump(&DAG);
8442 dbgs() << " and 2 other values\n");
8443 WorklistRemover DeadNodes(*this);
8444 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Undef);
8445 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Index);
8446 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 2), Chain);
8447 deleteAndRecombine(N);
8448 return SDValue(N, 0); // Return N so it doesn't get rechecked!
8453 // If this load is directly stored, replace the load value with the stored
8455 // TODO: Handle store large -> read small portion.
8456 // TODO: Handle TRUNCSTORE/LOADEXT
8457 if (ISD::isNormalLoad(N) && !LD->isVolatile()) {
8458 if (ISD::isNON_TRUNCStore(Chain.getNode())) {
8459 StoreSDNode *PrevST = cast<StoreSDNode>(Chain);
8460 if (PrevST->getBasePtr() == Ptr &&
8461 PrevST->getValue().getValueType() == N->getValueType(0))
8462 return CombineTo(N, Chain.getOperand(1), Chain);
8466 // Try to infer better alignment information than the load already has.
8467 if (OptLevel != CodeGenOpt::None && LD->isUnindexed()) {
8468 if (unsigned Align = DAG.InferPtrAlignment(Ptr)) {
8469 if (Align > LD->getMemOperand()->getBaseAlignment()) {
8471 DAG.getExtLoad(LD->getExtensionType(), SDLoc(N),
8472 LD->getValueType(0),
8473 Chain, Ptr, LD->getPointerInfo(),
8475 LD->isVolatile(), LD->isNonTemporal(),
8476 LD->isInvariant(), Align, LD->getAAInfo());
8477 return CombineTo(N, NewLoad, SDValue(NewLoad.getNode(), 1), true);
8482 bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA
8483 : DAG.getSubtarget().useAA();
8485 if (CombinerAAOnlyFunc.getNumOccurrences() &&
8486 CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
8489 if (UseAA && LD->isUnindexed()) {
8490 // Walk up chain skipping non-aliasing memory nodes.
8491 SDValue BetterChain = FindBetterChain(N, Chain);
8493 // If there is a better chain.
8494 if (Chain != BetterChain) {
8497 // Replace the chain to void dependency.
8498 if (LD->getExtensionType() == ISD::NON_EXTLOAD) {
8499 ReplLoad = DAG.getLoad(N->getValueType(0), SDLoc(LD),
8500 BetterChain, Ptr, LD->getMemOperand());
8502 ReplLoad = DAG.getExtLoad(LD->getExtensionType(), SDLoc(LD),
8503 LD->getValueType(0),
8504 BetterChain, Ptr, LD->getMemoryVT(),
8505 LD->getMemOperand());
8508 // Create token factor to keep old chain connected.
8509 SDValue Token = DAG.getNode(ISD::TokenFactor, SDLoc(N),
8510 MVT::Other, Chain, ReplLoad.getValue(1));
8512 // Make sure the new and old chains are cleaned up.
8513 AddToWorklist(Token.getNode());
8515 // Replace uses with load result and token factor. Don't add users
8517 return CombineTo(N, ReplLoad.getValue(0), Token, false);
8521 // Try transforming N to an indexed load.
8522 if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
8523 return SDValue(N, 0);
8525 // Try to slice up N to more direct loads if the slices are mapped to
8526 // different register banks or pairing can take place.
8528 return SDValue(N, 0);
8534 /// \brief Helper structure used to slice a load in smaller loads.
8535 /// Basically a slice is obtained from the following sequence:
8536 /// Origin = load Ty1, Base
8537 /// Shift = srl Ty1 Origin, CstTy Amount
8538 /// Inst = trunc Shift to Ty2
8540 /// Then, it will be rewriten into:
8541 /// Slice = load SliceTy, Base + SliceOffset
8542 /// [Inst = zext Slice to Ty2], only if SliceTy <> Ty2
8544 /// SliceTy is deduced from the number of bits that are actually used to
8546 struct LoadedSlice {
8547 /// \brief Helper structure used to compute the cost of a slice.
8549 /// Are we optimizing for code size.
8554 unsigned CrossRegisterBanksCopies;
8558 Cost(bool ForCodeSize = false)
8559 : ForCodeSize(ForCodeSize), Loads(0), Truncates(0),
8560 CrossRegisterBanksCopies(0), ZExts(0), Shift(0) {}
8562 /// \brief Get the cost of one isolated slice.
8563 Cost(const LoadedSlice &LS, bool ForCodeSize = false)
8564 : ForCodeSize(ForCodeSize), Loads(1), Truncates(0),
8565 CrossRegisterBanksCopies(0), ZExts(0), Shift(0) {
8566 EVT TruncType = LS.Inst->getValueType(0);
8567 EVT LoadedType = LS.getLoadedType();
8568 if (TruncType != LoadedType &&
8569 !LS.DAG->getTargetLoweringInfo().isZExtFree(LoadedType, TruncType))
8573 /// \brief Account for slicing gain in the current cost.
8574 /// Slicing provide a few gains like removing a shift or a
8575 /// truncate. This method allows to grow the cost of the original
8576 /// load with the gain from this slice.
8577 void addSliceGain(const LoadedSlice &LS) {
8578 // Each slice saves a truncate.
8579 const TargetLowering &TLI = LS.DAG->getTargetLoweringInfo();
8580 if (!TLI.isTruncateFree(LS.Inst->getValueType(0),
8581 LS.Inst->getOperand(0).getValueType()))
8583 // If there is a shift amount, this slice gets rid of it.
8586 // If this slice can merge a cross register bank copy, account for it.
8587 if (LS.canMergeExpensiveCrossRegisterBankCopy())
8588 ++CrossRegisterBanksCopies;
8591 Cost &operator+=(const Cost &RHS) {
8593 Truncates += RHS.Truncates;
8594 CrossRegisterBanksCopies += RHS.CrossRegisterBanksCopies;
8600 bool operator==(const Cost &RHS) const {
8601 return Loads == RHS.Loads && Truncates == RHS.Truncates &&
8602 CrossRegisterBanksCopies == RHS.CrossRegisterBanksCopies &&
8603 ZExts == RHS.ZExts && Shift == RHS.Shift;
8606 bool operator!=(const Cost &RHS) const { return !(*this == RHS); }
8608 bool operator<(const Cost &RHS) const {
8609 // Assume cross register banks copies are as expensive as loads.
8610 // FIXME: Do we want some more target hooks?
8611 unsigned ExpensiveOpsLHS = Loads + CrossRegisterBanksCopies;
8612 unsigned ExpensiveOpsRHS = RHS.Loads + RHS.CrossRegisterBanksCopies;
8613 // Unless we are optimizing for code size, consider the
8614 // expensive operation first.
8615 if (!ForCodeSize && ExpensiveOpsLHS != ExpensiveOpsRHS)
8616 return ExpensiveOpsLHS < ExpensiveOpsRHS;
8617 return (Truncates + ZExts + Shift + ExpensiveOpsLHS) <
8618 (RHS.Truncates + RHS.ZExts + RHS.Shift + ExpensiveOpsRHS);
8621 bool operator>(const Cost &RHS) const { return RHS < *this; }
8623 bool operator<=(const Cost &RHS) const { return !(RHS < *this); }
8625 bool operator>=(const Cost &RHS) const { return !(*this < RHS); }
8627 // The last instruction that represent the slice. This should be a
8628 // truncate instruction.
8630 // The original load instruction.
8632 // The right shift amount in bits from the original load.
8634 // The DAG from which Origin came from.
8635 // This is used to get some contextual information about legal types, etc.
8638 LoadedSlice(SDNode *Inst = nullptr, LoadSDNode *Origin = nullptr,
8639 unsigned Shift = 0, SelectionDAG *DAG = nullptr)
8640 : Inst(Inst), Origin(Origin), Shift(Shift), DAG(DAG) {}
8642 LoadedSlice(const LoadedSlice &LS)
8643 : Inst(LS.Inst), Origin(LS.Origin), Shift(LS.Shift), DAG(LS.DAG) {}
8645 /// \brief Get the bits used in a chunk of bits \p BitWidth large.
8646 /// \return Result is \p BitWidth and has used bits set to 1 and
8647 /// not used bits set to 0.
8648 APInt getUsedBits() const {
8649 // Reproduce the trunc(lshr) sequence:
8650 // - Start from the truncated value.
8651 // - Zero extend to the desired bit width.
8653 assert(Origin && "No original load to compare against.");
8654 unsigned BitWidth = Origin->getValueSizeInBits(0);
8655 assert(Inst && "This slice is not bound to an instruction");
8656 assert(Inst->getValueSizeInBits(0) <= BitWidth &&
8657 "Extracted slice is bigger than the whole type!");
8658 APInt UsedBits(Inst->getValueSizeInBits(0), 0);
8659 UsedBits.setAllBits();
8660 UsedBits = UsedBits.zext(BitWidth);
8665 /// \brief Get the size of the slice to be loaded in bytes.
8666 unsigned getLoadedSize() const {
8667 unsigned SliceSize = getUsedBits().countPopulation();
8668 assert(!(SliceSize & 0x7) && "Size is not a multiple of a byte.");
8669 return SliceSize / 8;
8672 /// \brief Get the type that will be loaded for this slice.
8673 /// Note: This may not be the final type for the slice.
8674 EVT getLoadedType() const {
8675 assert(DAG && "Missing context");
8676 LLVMContext &Ctxt = *DAG->getContext();
8677 return EVT::getIntegerVT(Ctxt, getLoadedSize() * 8);
8680 /// \brief Get the alignment of the load used for this slice.
8681 unsigned getAlignment() const {
8682 unsigned Alignment = Origin->getAlignment();
8683 unsigned Offset = getOffsetFromBase();
8685 Alignment = MinAlign(Alignment, Alignment + Offset);
8689 /// \brief Check if this slice can be rewritten with legal operations.
8690 bool isLegal() const {
8691 // An invalid slice is not legal.
8692 if (!Origin || !Inst || !DAG)
8695 // Offsets are for indexed load only, we do not handle that.
8696 if (Origin->getOffset().getOpcode() != ISD::UNDEF)
8699 const TargetLowering &TLI = DAG->getTargetLoweringInfo();
8701 // Check that the type is legal.
8702 EVT SliceType = getLoadedType();
8703 if (!TLI.isTypeLegal(SliceType))
8706 // Check that the load is legal for this type.
8707 if (!TLI.isOperationLegal(ISD::LOAD, SliceType))
8710 // Check that the offset can be computed.
8711 // 1. Check its type.
8712 EVT PtrType = Origin->getBasePtr().getValueType();
8713 if (PtrType == MVT::Untyped || PtrType.isExtended())
8716 // 2. Check that it fits in the immediate.
8717 if (!TLI.isLegalAddImmediate(getOffsetFromBase()))
8720 // 3. Check that the computation is legal.
8721 if (!TLI.isOperationLegal(ISD::ADD, PtrType))
8724 // Check that the zext is legal if it needs one.
8725 EVT TruncateType = Inst->getValueType(0);
8726 if (TruncateType != SliceType &&
8727 !TLI.isOperationLegal(ISD::ZERO_EXTEND, TruncateType))
8733 /// \brief Get the offset in bytes of this slice in the original chunk of
8735 /// \pre DAG != nullptr.
8736 uint64_t getOffsetFromBase() const {
8737 assert(DAG && "Missing context.");
8739 DAG->getTargetLoweringInfo().getDataLayout()->isBigEndian();
8740 assert(!(Shift & 0x7) && "Shifts not aligned on Bytes are not supported.");
8741 uint64_t Offset = Shift / 8;
8742 unsigned TySizeInBytes = Origin->getValueSizeInBits(0) / 8;
8743 assert(!(Origin->getValueSizeInBits(0) & 0x7) &&
8744 "The size of the original loaded type is not a multiple of a"
8746 // If Offset is bigger than TySizeInBytes, it means we are loading all
8747 // zeros. This should have been optimized before in the process.
8748 assert(TySizeInBytes > Offset &&
8749 "Invalid shift amount for given loaded size");
8751 Offset = TySizeInBytes - Offset - getLoadedSize();
8755 /// \brief Generate the sequence of instructions to load the slice
8756 /// represented by this object and redirect the uses of this slice to
8757 /// this new sequence of instructions.
8758 /// \pre this->Inst && this->Origin are valid Instructions and this
8759 /// object passed the legal check: LoadedSlice::isLegal returned true.
8760 /// \return The last instruction of the sequence used to load the slice.
8761 SDValue loadSlice() const {
8762 assert(Inst && Origin && "Unable to replace a non-existing slice.");
8763 const SDValue &OldBaseAddr = Origin->getBasePtr();
8764 SDValue BaseAddr = OldBaseAddr;
8765 // Get the offset in that chunk of bytes w.r.t. the endianess.
8766 int64_t Offset = static_cast<int64_t>(getOffsetFromBase());
8767 assert(Offset >= 0 && "Offset too big to fit in int64_t!");
8769 // BaseAddr = BaseAddr + Offset.
8770 EVT ArithType = BaseAddr.getValueType();
8771 BaseAddr = DAG->getNode(ISD::ADD, SDLoc(Origin), ArithType, BaseAddr,
8772 DAG->getConstant(Offset, ArithType));
8775 // Create the type of the loaded slice according to its size.
8776 EVT SliceType = getLoadedType();
8778 // Create the load for the slice.
8779 SDValue LastInst = DAG->getLoad(
8780 SliceType, SDLoc(Origin), Origin->getChain(), BaseAddr,
8781 Origin->getPointerInfo().getWithOffset(Offset), Origin->isVolatile(),
8782 Origin->isNonTemporal(), Origin->isInvariant(), getAlignment());
8783 // If the final type is not the same as the loaded type, this means that
8784 // we have to pad with zero. Create a zero extend for that.
8785 EVT FinalType = Inst->getValueType(0);
8786 if (SliceType != FinalType)
8788 DAG->getNode(ISD::ZERO_EXTEND, SDLoc(LastInst), FinalType, LastInst);
8792 /// \brief Check if this slice can be merged with an expensive cross register
8793 /// bank copy. E.g.,
8795 /// f = bitcast i32 i to float
8796 bool canMergeExpensiveCrossRegisterBankCopy() const {
8797 if (!Inst || !Inst->hasOneUse())
8799 SDNode *Use = *Inst->use_begin();
8800 if (Use->getOpcode() != ISD::BITCAST)
8802 assert(DAG && "Missing context");
8803 const TargetLowering &TLI = DAG->getTargetLoweringInfo();
8804 EVT ResVT = Use->getValueType(0);
8805 const TargetRegisterClass *ResRC = TLI.getRegClassFor(ResVT.getSimpleVT());
8806 const TargetRegisterClass *ArgRC =
8807 TLI.getRegClassFor(Use->getOperand(0).getValueType().getSimpleVT());
8808 if (ArgRC == ResRC || !TLI.isOperationLegal(ISD::LOAD, ResVT))
8811 // At this point, we know that we perform a cross-register-bank copy.
8812 // Check if it is expensive.
8813 const TargetRegisterInfo *TRI = DAG->getSubtarget().getRegisterInfo();
8814 // Assume bitcasts are cheap, unless both register classes do not
8815 // explicitly share a common sub class.
8816 if (!TRI || TRI->getCommonSubClass(ArgRC, ResRC))
8819 // Check if it will be merged with the load.
8820 // 1. Check the alignment constraint.
8821 unsigned RequiredAlignment = TLI.getDataLayout()->getABITypeAlignment(
8822 ResVT.getTypeForEVT(*DAG->getContext()));
8824 if (RequiredAlignment > getAlignment())
8827 // 2. Check that the load is a legal operation for that type.
8828 if (!TLI.isOperationLegal(ISD::LOAD, ResVT))
8831 // 3. Check that we do not have a zext in the way.
8832 if (Inst->getValueType(0) != getLoadedType())
8840 /// \brief Check that all bits set in \p UsedBits form a dense region, i.e.,
8841 /// \p UsedBits looks like 0..0 1..1 0..0.
8842 static bool areUsedBitsDense(const APInt &UsedBits) {
8843 // If all the bits are one, this is dense!
8844 if (UsedBits.isAllOnesValue())
8847 // Get rid of the unused bits on the right.
8848 APInt NarrowedUsedBits = UsedBits.lshr(UsedBits.countTrailingZeros());
8849 // Get rid of the unused bits on the left.
8850 if (NarrowedUsedBits.countLeadingZeros())
8851 NarrowedUsedBits = NarrowedUsedBits.trunc(NarrowedUsedBits.getActiveBits());
8852 // Check that the chunk of bits is completely used.
8853 return NarrowedUsedBits.isAllOnesValue();
8856 /// \brief Check whether or not \p First and \p Second are next to each other
8857 /// in memory. This means that there is no hole between the bits loaded
8858 /// by \p First and the bits loaded by \p Second.
8859 static bool areSlicesNextToEachOther(const LoadedSlice &First,
8860 const LoadedSlice &Second) {
8861 assert(First.Origin == Second.Origin && First.Origin &&
8862 "Unable to match different memory origins.");
8863 APInt UsedBits = First.getUsedBits();
8864 assert((UsedBits & Second.getUsedBits()) == 0 &&
8865 "Slices are not supposed to overlap.");
8866 UsedBits |= Second.getUsedBits();
8867 return areUsedBitsDense(UsedBits);
8870 /// \brief Adjust the \p GlobalLSCost according to the target
8871 /// paring capabilities and the layout of the slices.
8872 /// \pre \p GlobalLSCost should account for at least as many loads as
8873 /// there is in the slices in \p LoadedSlices.
8874 static void adjustCostForPairing(SmallVectorImpl<LoadedSlice> &LoadedSlices,
8875 LoadedSlice::Cost &GlobalLSCost) {
8876 unsigned NumberOfSlices = LoadedSlices.size();
8877 // If there is less than 2 elements, no pairing is possible.
8878 if (NumberOfSlices < 2)
8881 // Sort the slices so that elements that are likely to be next to each
8882 // other in memory are next to each other in the list.
8883 std::sort(LoadedSlices.begin(), LoadedSlices.end(),
8884 [](const LoadedSlice &LHS, const LoadedSlice &RHS) {
8885 assert(LHS.Origin == RHS.Origin && "Different bases not implemented.");
8886 return LHS.getOffsetFromBase() < RHS.getOffsetFromBase();
8888 const TargetLowering &TLI = LoadedSlices[0].DAG->getTargetLoweringInfo();
8889 // First (resp. Second) is the first (resp. Second) potentially candidate
8890 // to be placed in a paired load.
8891 const LoadedSlice *First = nullptr;
8892 const LoadedSlice *Second = nullptr;
8893 for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice,
8894 // Set the beginning of the pair.
8897 Second = &LoadedSlices[CurrSlice];
8899 // If First is NULL, it means we start a new pair.
8900 // Get to the next slice.
8904 EVT LoadedType = First->getLoadedType();
8906 // If the types of the slices are different, we cannot pair them.
8907 if (LoadedType != Second->getLoadedType())
8910 // Check if the target supplies paired loads for this type.
8911 unsigned RequiredAlignment = 0;
8912 if (!TLI.hasPairedLoad(LoadedType, RequiredAlignment)) {
8913 // move to the next pair, this type is hopeless.
8917 // Check if we meet the alignment requirement.
8918 if (RequiredAlignment > First->getAlignment())
8921 // Check that both loads are next to each other in memory.
8922 if (!areSlicesNextToEachOther(*First, *Second))
8925 assert(GlobalLSCost.Loads > 0 && "We save more loads than we created!");
8926 --GlobalLSCost.Loads;
8927 // Move to the next pair.
8932 /// \brief Check the profitability of all involved LoadedSlice.
8933 /// Currently, it is considered profitable if there is exactly two
8934 /// involved slices (1) which are (2) next to each other in memory, and
8935 /// whose cost (\see LoadedSlice::Cost) is smaller than the original load (3).
8937 /// Note: The order of the elements in \p LoadedSlices may be modified, but not
8938 /// the elements themselves.
8940 /// FIXME: When the cost model will be mature enough, we can relax
8941 /// constraints (1) and (2).
8942 static bool isSlicingProfitable(SmallVectorImpl<LoadedSlice> &LoadedSlices,
8943 const APInt &UsedBits, bool ForCodeSize) {
8944 unsigned NumberOfSlices = LoadedSlices.size();
8945 if (StressLoadSlicing)
8946 return NumberOfSlices > 1;
8949 if (NumberOfSlices != 2)
8953 if (!areUsedBitsDense(UsedBits))
8957 LoadedSlice::Cost OrigCost(ForCodeSize), GlobalSlicingCost(ForCodeSize);
8958 // The original code has one big load.
8960 for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice) {
8961 const LoadedSlice &LS = LoadedSlices[CurrSlice];
8962 // Accumulate the cost of all the slices.
8963 LoadedSlice::Cost SliceCost(LS, ForCodeSize);
8964 GlobalSlicingCost += SliceCost;
8966 // Account as cost in the original configuration the gain obtained
8967 // with the current slices.
8968 OrigCost.addSliceGain(LS);
8971 // If the target supports paired load, adjust the cost accordingly.
8972 adjustCostForPairing(LoadedSlices, GlobalSlicingCost);
8973 return OrigCost > GlobalSlicingCost;
8976 /// \brief If the given load, \p LI, is used only by trunc or trunc(lshr)
8977 /// operations, split it in the various pieces being extracted.
8979 /// This sort of thing is introduced by SROA.
8980 /// This slicing takes care not to insert overlapping loads.
8981 /// \pre LI is a simple load (i.e., not an atomic or volatile load).
8982 bool DAGCombiner::SliceUpLoad(SDNode *N) {
8983 if (Level < AfterLegalizeDAG)
8986 LoadSDNode *LD = cast<LoadSDNode>(N);
8987 if (LD->isVolatile() || !ISD::isNormalLoad(LD) ||
8988 !LD->getValueType(0).isInteger())
8991 // Keep track of already used bits to detect overlapping values.
8992 // In that case, we will just abort the transformation.
8993 APInt UsedBits(LD->getValueSizeInBits(0), 0);
8995 SmallVector<LoadedSlice, 4> LoadedSlices;
8997 // Check if this load is used as several smaller chunks of bits.
8998 // Basically, look for uses in trunc or trunc(lshr) and record a new chain
8999 // of computation for each trunc.
9000 for (SDNode::use_iterator UI = LD->use_begin(), UIEnd = LD->use_end();
9001 UI != UIEnd; ++UI) {
9002 // Skip the uses of the chain.
9003 if (UI.getUse().getResNo() != 0)
9009 // Check if this is a trunc(lshr).
9010 if (User->getOpcode() == ISD::SRL && User->hasOneUse() &&
9011 isa<ConstantSDNode>(User->getOperand(1))) {
9012 Shift = cast<ConstantSDNode>(User->getOperand(1))->getZExtValue();
9013 User = *User->use_begin();
9016 // At this point, User is a Truncate, iff we encountered, trunc or
9018 if (User->getOpcode() != ISD::TRUNCATE)
9021 // The width of the type must be a power of 2 and greater than 8-bits.
9022 // Otherwise the load cannot be represented in LLVM IR.
9023 // Moreover, if we shifted with a non-8-bits multiple, the slice
9024 // will be across several bytes. We do not support that.
9025 unsigned Width = User->getValueSizeInBits(0);
9026 if (Width < 8 || !isPowerOf2_32(Width) || (Shift & 0x7))
9029 // Build the slice for this chain of computations.
9030 LoadedSlice LS(User, LD, Shift, &DAG);
9031 APInt CurrentUsedBits = LS.getUsedBits();
9033 // Check if this slice overlaps with another.
9034 if ((CurrentUsedBits & UsedBits) != 0)
9036 // Update the bits used globally.
9037 UsedBits |= CurrentUsedBits;
9039 // Check if the new slice would be legal.
9043 // Record the slice.
9044 LoadedSlices.push_back(LS);
9047 // Abort slicing if it does not seem to be profitable.
9048 if (!isSlicingProfitable(LoadedSlices, UsedBits, ForCodeSize))
9053 // Rewrite each chain to use an independent load.
9054 // By construction, each chain can be represented by a unique load.
9056 // Prepare the argument for the new token factor for all the slices.
9057 SmallVector<SDValue, 8> ArgChains;
9058 for (SmallVectorImpl<LoadedSlice>::const_iterator
9059 LSIt = LoadedSlices.begin(),
9060 LSItEnd = LoadedSlices.end();
9061 LSIt != LSItEnd; ++LSIt) {
9062 SDValue SliceInst = LSIt->loadSlice();
9063 CombineTo(LSIt->Inst, SliceInst, true);
9064 if (SliceInst.getNode()->getOpcode() != ISD::LOAD)
9065 SliceInst = SliceInst.getOperand(0);
9066 assert(SliceInst->getOpcode() == ISD::LOAD &&
9067 "It takes more than a zext to get to the loaded slice!!");
9068 ArgChains.push_back(SliceInst.getValue(1));
9071 SDValue Chain = DAG.getNode(ISD::TokenFactor, SDLoc(LD), MVT::Other,
9073 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain);
9077 /// Check to see if V is (and load (ptr), imm), where the load is having
9078 /// specific bytes cleared out. If so, return the byte size being masked out
9079 /// and the shift amount.
9080 static std::pair<unsigned, unsigned>
9081 CheckForMaskedLoad(SDValue V, SDValue Ptr, SDValue Chain) {
9082 std::pair<unsigned, unsigned> Result(0, 0);
9084 // Check for the structure we're looking for.
9085 if (V->getOpcode() != ISD::AND ||
9086 !isa<ConstantSDNode>(V->getOperand(1)) ||
9087 !ISD::isNormalLoad(V->getOperand(0).getNode()))
9090 // Check the chain and pointer.
9091 LoadSDNode *LD = cast<LoadSDNode>(V->getOperand(0));
9092 if (LD->getBasePtr() != Ptr) return Result; // Not from same pointer.
9094 // The store should be chained directly to the load or be an operand of a
9096 if (LD == Chain.getNode())
9098 else if (Chain->getOpcode() != ISD::TokenFactor)
9099 return Result; // Fail.
9102 for (unsigned i = 0, e = Chain->getNumOperands(); i != e; ++i)
9103 if (Chain->getOperand(i).getNode() == LD) {
9107 if (!isOk) return Result;
9110 // This only handles simple types.
9111 if (V.getValueType() != MVT::i16 &&
9112 V.getValueType() != MVT::i32 &&
9113 V.getValueType() != MVT::i64)
9116 // Check the constant mask. Invert it so that the bits being masked out are
9117 // 0 and the bits being kept are 1. Use getSExtValue so that leading bits
9118 // follow the sign bit for uniformity.
9119 uint64_t NotMask = ~cast<ConstantSDNode>(V->getOperand(1))->getSExtValue();
9120 unsigned NotMaskLZ = countLeadingZeros(NotMask);
9121 if (NotMaskLZ & 7) return Result; // Must be multiple of a byte.
9122 unsigned NotMaskTZ = countTrailingZeros(NotMask);
9123 if (NotMaskTZ & 7) return Result; // Must be multiple of a byte.
9124 if (NotMaskLZ == 64) return Result; // All zero mask.
9126 // See if we have a continuous run of bits. If so, we have 0*1+0*
9127 if (CountTrailingOnes_64(NotMask >> NotMaskTZ)+NotMaskTZ+NotMaskLZ != 64)
9130 // Adjust NotMaskLZ down to be from the actual size of the int instead of i64.
9131 if (V.getValueType() != MVT::i64 && NotMaskLZ)
9132 NotMaskLZ -= 64-V.getValueSizeInBits();
9134 unsigned MaskedBytes = (V.getValueSizeInBits()-NotMaskLZ-NotMaskTZ)/8;
9135 switch (MaskedBytes) {
9139 default: return Result; // All one mask, or 5-byte mask.
9142 // Verify that the first bit starts at a multiple of mask so that the access
9143 // is aligned the same as the access width.
9144 if (NotMaskTZ && NotMaskTZ/8 % MaskedBytes) return Result;
9146 Result.first = MaskedBytes;
9147 Result.second = NotMaskTZ/8;
9152 /// Check to see if IVal is something that provides a value as specified by
9153 /// MaskInfo. If so, replace the specified store with a narrower store of
9156 ShrinkLoadReplaceStoreWithStore(const std::pair<unsigned, unsigned> &MaskInfo,
9157 SDValue IVal, StoreSDNode *St,
9159 unsigned NumBytes = MaskInfo.first;
9160 unsigned ByteShift = MaskInfo.second;
9161 SelectionDAG &DAG = DC->getDAG();
9163 // Check to see if IVal is all zeros in the part being masked in by the 'or'
9164 // that uses this. If not, this is not a replacement.
9165 APInt Mask = ~APInt::getBitsSet(IVal.getValueSizeInBits(),
9166 ByteShift*8, (ByteShift+NumBytes)*8);
9167 if (!DAG.MaskedValueIsZero(IVal, Mask)) return nullptr;
9169 // Check that it is legal on the target to do this. It is legal if the new
9170 // VT we're shrinking to (i8/i16/i32) is legal or we're still before type
9172 MVT VT = MVT::getIntegerVT(NumBytes*8);
9173 if (!DC->isTypeLegal(VT))
9176 // Okay, we can do this! Replace the 'St' store with a store of IVal that is
9177 // shifted by ByteShift and truncated down to NumBytes.
9179 IVal = DAG.getNode(ISD::SRL, SDLoc(IVal), IVal.getValueType(), IVal,
9180 DAG.getConstant(ByteShift*8,
9181 DC->getShiftAmountTy(IVal.getValueType())));
9183 // Figure out the offset for the store and the alignment of the access.
9185 unsigned NewAlign = St->getAlignment();
9187 if (DAG.getTargetLoweringInfo().isLittleEndian())
9188 StOffset = ByteShift;
9190 StOffset = IVal.getValueType().getStoreSize() - ByteShift - NumBytes;
9192 SDValue Ptr = St->getBasePtr();
9194 Ptr = DAG.getNode(ISD::ADD, SDLoc(IVal), Ptr.getValueType(),
9195 Ptr, DAG.getConstant(StOffset, Ptr.getValueType()));
9196 NewAlign = MinAlign(NewAlign, StOffset);
9199 // Truncate down to the new size.
9200 IVal = DAG.getNode(ISD::TRUNCATE, SDLoc(IVal), VT, IVal);
9203 return DAG.getStore(St->getChain(), SDLoc(St), IVal, Ptr,
9204 St->getPointerInfo().getWithOffset(StOffset),
9205 false, false, NewAlign).getNode();
9209 /// Look for sequence of load / op / store where op is one of 'or', 'xor', and
9210 /// 'and' of immediates. If 'op' is only touching some of the loaded bits, try
9211 /// narrowing the load and store if it would end up being a win for performance
9213 SDValue DAGCombiner::ReduceLoadOpStoreWidth(SDNode *N) {
9214 StoreSDNode *ST = cast<StoreSDNode>(N);
9215 if (ST->isVolatile())
9218 SDValue Chain = ST->getChain();
9219 SDValue Value = ST->getValue();
9220 SDValue Ptr = ST->getBasePtr();
9221 EVT VT = Value.getValueType();
9223 if (ST->isTruncatingStore() || VT.isVector() || !Value.hasOneUse())
9226 unsigned Opc = Value.getOpcode();
9228 // If this is "store (or X, Y), P" and X is "(and (load P), cst)", where cst
9229 // is a byte mask indicating a consecutive number of bytes, check to see if
9230 // Y is known to provide just those bytes. If so, we try to replace the
9231 // load + replace + store sequence with a single (narrower) store, which makes
9233 if (Opc == ISD::OR) {
9234 std::pair<unsigned, unsigned> MaskedLoad;
9235 MaskedLoad = CheckForMaskedLoad(Value.getOperand(0), Ptr, Chain);
9236 if (MaskedLoad.first)
9237 if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad,
9238 Value.getOperand(1), ST,this))
9239 return SDValue(NewST, 0);
9241 // Or is commutative, so try swapping X and Y.
9242 MaskedLoad = CheckForMaskedLoad(Value.getOperand(1), Ptr, Chain);
9243 if (MaskedLoad.first)
9244 if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad,
9245 Value.getOperand(0), ST,this))
9246 return SDValue(NewST, 0);
9249 if ((Opc != ISD::OR && Opc != ISD::XOR && Opc != ISD::AND) ||
9250 Value.getOperand(1).getOpcode() != ISD::Constant)
9253 SDValue N0 = Value.getOperand(0);
9254 if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
9255 Chain == SDValue(N0.getNode(), 1)) {
9256 LoadSDNode *LD = cast<LoadSDNode>(N0);
9257 if (LD->getBasePtr() != Ptr ||
9258 LD->getPointerInfo().getAddrSpace() !=
9259 ST->getPointerInfo().getAddrSpace())
9262 // Find the type to narrow it the load / op / store to.
9263 SDValue N1 = Value.getOperand(1);
9264 unsigned BitWidth = N1.getValueSizeInBits();
9265 APInt Imm = cast<ConstantSDNode>(N1)->getAPIntValue();
9266 if (Opc == ISD::AND)
9267 Imm ^= APInt::getAllOnesValue(BitWidth);
9268 if (Imm == 0 || Imm.isAllOnesValue())
9270 unsigned ShAmt = Imm.countTrailingZeros();
9271 unsigned MSB = BitWidth - Imm.countLeadingZeros() - 1;
9272 unsigned NewBW = NextPowerOf2(MSB - ShAmt);
9273 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW);
9274 while (NewBW < BitWidth &&
9275 !(TLI.isOperationLegalOrCustom(Opc, NewVT) &&
9276 TLI.isNarrowingProfitable(VT, NewVT))) {
9277 NewBW = NextPowerOf2(NewBW);
9278 NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW);
9280 if (NewBW >= BitWidth)
9283 // If the lsb changed does not start at the type bitwidth boundary,
9284 // start at the previous one.
9286 ShAmt = (((ShAmt + NewBW - 1) / NewBW) * NewBW) - NewBW;
9287 APInt Mask = APInt::getBitsSet(BitWidth, ShAmt,
9288 std::min(BitWidth, ShAmt + NewBW));
9289 if ((Imm & Mask) == Imm) {
9290 APInt NewImm = (Imm & Mask).lshr(ShAmt).trunc(NewBW);
9291 if (Opc == ISD::AND)
9292 NewImm ^= APInt::getAllOnesValue(NewBW);
9293 uint64_t PtrOff = ShAmt / 8;
9294 // For big endian targets, we need to adjust the offset to the pointer to
9295 // load the correct bytes.
9296 if (TLI.isBigEndian())
9297 PtrOff = (BitWidth + 7 - NewBW) / 8 - PtrOff;
9299 unsigned NewAlign = MinAlign(LD->getAlignment(), PtrOff);
9300 Type *NewVTTy = NewVT.getTypeForEVT(*DAG.getContext());
9301 if (NewAlign < TLI.getDataLayout()->getABITypeAlignment(NewVTTy))
9304 SDValue NewPtr = DAG.getNode(ISD::ADD, SDLoc(LD),
9305 Ptr.getValueType(), Ptr,
9306 DAG.getConstant(PtrOff, Ptr.getValueType()));
9307 SDValue NewLD = DAG.getLoad(NewVT, SDLoc(N0),
9308 LD->getChain(), NewPtr,
9309 LD->getPointerInfo().getWithOffset(PtrOff),
9310 LD->isVolatile(), LD->isNonTemporal(),
9311 LD->isInvariant(), NewAlign,
9313 SDValue NewVal = DAG.getNode(Opc, SDLoc(Value), NewVT, NewLD,
9314 DAG.getConstant(NewImm, NewVT));
9315 SDValue NewST = DAG.getStore(Chain, SDLoc(N),
9317 ST->getPointerInfo().getWithOffset(PtrOff),
9318 false, false, NewAlign);
9320 AddToWorklist(NewPtr.getNode());
9321 AddToWorklist(NewLD.getNode());
9322 AddToWorklist(NewVal.getNode());
9323 WorklistRemover DeadNodes(*this);
9324 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLD.getValue(1));
9333 /// For a given floating point load / store pair, if the load value isn't used
9334 /// by any other operations, then consider transforming the pair to integer
9335 /// load / store operations if the target deems the transformation profitable.
9336 SDValue DAGCombiner::TransformFPLoadStorePair(SDNode *N) {
9337 StoreSDNode *ST = cast<StoreSDNode>(N);
9338 SDValue Chain = ST->getChain();
9339 SDValue Value = ST->getValue();
9340 if (ISD::isNormalStore(ST) && ISD::isNormalLoad(Value.getNode()) &&
9341 Value.hasOneUse() &&
9342 Chain == SDValue(Value.getNode(), 1)) {
9343 LoadSDNode *LD = cast<LoadSDNode>(Value);
9344 EVT VT = LD->getMemoryVT();
9345 if (!VT.isFloatingPoint() ||
9346 VT != ST->getMemoryVT() ||
9347 LD->isNonTemporal() ||
9348 ST->isNonTemporal() ||
9349 LD->getPointerInfo().getAddrSpace() != 0 ||
9350 ST->getPointerInfo().getAddrSpace() != 0)
9353 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), VT.getSizeInBits());
9354 if (!TLI.isOperationLegal(ISD::LOAD, IntVT) ||
9355 !TLI.isOperationLegal(ISD::STORE, IntVT) ||
9356 !TLI.isDesirableToTransformToIntegerOp(ISD::LOAD, VT) ||
9357 !TLI.isDesirableToTransformToIntegerOp(ISD::STORE, VT))
9360 unsigned LDAlign = LD->getAlignment();
9361 unsigned STAlign = ST->getAlignment();
9362 Type *IntVTTy = IntVT.getTypeForEVT(*DAG.getContext());
9363 unsigned ABIAlign = TLI.getDataLayout()->getABITypeAlignment(IntVTTy);
9364 if (LDAlign < ABIAlign || STAlign < ABIAlign)
9367 SDValue NewLD = DAG.getLoad(IntVT, SDLoc(Value),
9368 LD->getChain(), LD->getBasePtr(),
9369 LD->getPointerInfo(),
9370 false, false, false, LDAlign);
9372 SDValue NewST = DAG.getStore(NewLD.getValue(1), SDLoc(N),
9373 NewLD, ST->getBasePtr(),
9374 ST->getPointerInfo(),
9375 false, false, STAlign);
9377 AddToWorklist(NewLD.getNode());
9378 AddToWorklist(NewST.getNode());
9379 WorklistRemover DeadNodes(*this);
9380 DAG.ReplaceAllUsesOfValueWith(Value.getValue(1), NewLD.getValue(1));
9388 /// Helper struct to parse and store a memory address as base + index + offset.
9389 /// We ignore sign extensions when it is safe to do so.
9390 /// The following two expressions are not equivalent. To differentiate we need
9391 /// to store whether there was a sign extension involved in the index
9393 /// (load (i64 add (i64 copyfromreg %c)
9394 /// (i64 signextend (add (i8 load %index)
9398 /// (load (i64 add (i64 copyfromreg %c)
9399 /// (i64 signextend (i32 add (i32 signextend (i8 load %index))
9401 struct BaseIndexOffset {
9405 bool IsIndexSignExt;
9407 BaseIndexOffset() : Offset(0), IsIndexSignExt(false) {}
9409 BaseIndexOffset(SDValue Base, SDValue Index, int64_t Offset,
9410 bool IsIndexSignExt) :
9411 Base(Base), Index(Index), Offset(Offset), IsIndexSignExt(IsIndexSignExt) {}
9413 bool equalBaseIndex(const BaseIndexOffset &Other) {
9414 return Other.Base == Base && Other.Index == Index &&
9415 Other.IsIndexSignExt == IsIndexSignExt;
9418 /// Parses tree in Ptr for base, index, offset addresses.
9419 static BaseIndexOffset match(SDValue Ptr) {
9420 bool IsIndexSignExt = false;
9422 // We only can pattern match BASE + INDEX + OFFSET. If Ptr is not an ADD
9423 // instruction, then it could be just the BASE or everything else we don't
9424 // know how to handle. Just use Ptr as BASE and give up.
9425 if (Ptr->getOpcode() != ISD::ADD)
9426 return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
9428 // We know that we have at least an ADD instruction. Try to pattern match
9429 // the simple case of BASE + OFFSET.
9430 if (isa<ConstantSDNode>(Ptr->getOperand(1))) {
9431 int64_t Offset = cast<ConstantSDNode>(Ptr->getOperand(1))->getSExtValue();
9432 return BaseIndexOffset(Ptr->getOperand(0), SDValue(), Offset,
9436 // Inside a loop the current BASE pointer is calculated using an ADD and a
9437 // MUL instruction. In this case Ptr is the actual BASE pointer.
9438 // (i64 add (i64 %array_ptr)
9439 // (i64 mul (i64 %induction_var)
9440 // (i64 %element_size)))
9441 if (Ptr->getOperand(1)->getOpcode() == ISD::MUL)
9442 return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
9444 // Look at Base + Index + Offset cases.
9445 SDValue Base = Ptr->getOperand(0);
9446 SDValue IndexOffset = Ptr->getOperand(1);
9448 // Skip signextends.
9449 if (IndexOffset->getOpcode() == ISD::SIGN_EXTEND) {
9450 IndexOffset = IndexOffset->getOperand(0);
9451 IsIndexSignExt = true;
9454 // Either the case of Base + Index (no offset) or something else.
9455 if (IndexOffset->getOpcode() != ISD::ADD)
9456 return BaseIndexOffset(Base, IndexOffset, 0, IsIndexSignExt);
9458 // Now we have the case of Base + Index + offset.
9459 SDValue Index = IndexOffset->getOperand(0);
9460 SDValue Offset = IndexOffset->getOperand(1);
9462 if (!isa<ConstantSDNode>(Offset))
9463 return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
9465 // Ignore signextends.
9466 if (Index->getOpcode() == ISD::SIGN_EXTEND) {
9467 Index = Index->getOperand(0);
9468 IsIndexSignExt = true;
9469 } else IsIndexSignExt = false;
9471 int64_t Off = cast<ConstantSDNode>(Offset)->getSExtValue();
9472 return BaseIndexOffset(Base, Index, Off, IsIndexSignExt);
9476 /// Holds a pointer to an LSBaseSDNode as well as information on where it
9477 /// is located in a sequence of memory operations connected by a chain.
9479 MemOpLink (LSBaseSDNode *N, int64_t Offset, unsigned Seq):
9480 MemNode(N), OffsetFromBase(Offset), SequenceNum(Seq) { }
9481 // Ptr to the mem node.
9482 LSBaseSDNode *MemNode;
9483 // Offset from the base ptr.
9484 int64_t OffsetFromBase;
9485 // What is the sequence number of this mem node.
9486 // Lowest mem operand in the DAG starts at zero.
9487 unsigned SequenceNum;
9490 bool DAGCombiner::MergeConsecutiveStores(StoreSDNode* St) {
9491 EVT MemVT = St->getMemoryVT();
9492 int64_t ElementSizeBytes = MemVT.getSizeInBits()/8;
9493 bool NoVectors = DAG.getMachineFunction().getFunction()->getAttributes().
9494 hasAttribute(AttributeSet::FunctionIndex, Attribute::NoImplicitFloat);
9496 // Don't merge vectors into wider inputs.
9497 if (MemVT.isVector() || !MemVT.isSimple())
9500 // Perform an early exit check. Do not bother looking at stored values that
9501 // are not constants or loads.
9502 SDValue StoredVal = St->getValue();
9503 bool IsLoadSrc = isa<LoadSDNode>(StoredVal);
9504 if (!isa<ConstantSDNode>(StoredVal) && !isa<ConstantFPSDNode>(StoredVal) &&
9508 // Only look at ends of store sequences.
9509 SDValue Chain = SDValue(St, 0);
9510 if (Chain->hasOneUse() && Chain->use_begin()->getOpcode() == ISD::STORE)
9513 // This holds the base pointer, index, and the offset in bytes from the base
9515 BaseIndexOffset BasePtr = BaseIndexOffset::match(St->getBasePtr());
9517 // We must have a base and an offset.
9518 if (!BasePtr.Base.getNode())
9521 // Do not handle stores to undef base pointers.
9522 if (BasePtr.Base.getOpcode() == ISD::UNDEF)
9525 // Save the LoadSDNodes that we find in the chain.
9526 // We need to make sure that these nodes do not interfere with
9527 // any of the store nodes.
9528 SmallVector<LSBaseSDNode*, 8> AliasLoadNodes;
9530 // Save the StoreSDNodes that we find in the chain.
9531 SmallVector<MemOpLink, 8> StoreNodes;
9533 // Walk up the chain and look for nodes with offsets from the same
9534 // base pointer. Stop when reaching an instruction with a different kind
9535 // or instruction which has a different base pointer.
9537 StoreSDNode *Index = St;
9539 // If the chain has more than one use, then we can't reorder the mem ops.
9540 if (Index != St && !SDValue(Index, 0)->hasOneUse())
9543 // Find the base pointer and offset for this memory node.
9544 BaseIndexOffset Ptr = BaseIndexOffset::match(Index->getBasePtr());
9546 // Check that the base pointer is the same as the original one.
9547 if (!Ptr.equalBaseIndex(BasePtr))
9550 // Check that the alignment is the same.
9551 if (Index->getAlignment() != St->getAlignment())
9554 // The memory operands must not be volatile.
9555 if (Index->isVolatile() || Index->isIndexed())
9559 if (StoreSDNode *St = dyn_cast<StoreSDNode>(Index))
9560 if (St->isTruncatingStore())
9563 // The stored memory type must be the same.
9564 if (Index->getMemoryVT() != MemVT)
9567 // We do not allow unaligned stores because we want to prevent overriding
9569 if (Index->getAlignment()*8 != MemVT.getSizeInBits())
9572 // We found a potential memory operand to merge.
9573 StoreNodes.push_back(MemOpLink(Index, Ptr.Offset, Seq++));
9575 // Find the next memory operand in the chain. If the next operand in the
9576 // chain is a store then move up and continue the scan with the next
9577 // memory operand. If the next operand is a load save it and use alias
9578 // information to check if it interferes with anything.
9579 SDNode *NextInChain = Index->getChain().getNode();
9581 if (StoreSDNode *STn = dyn_cast<StoreSDNode>(NextInChain)) {
9582 // We found a store node. Use it for the next iteration.
9585 } else if (LoadSDNode *Ldn = dyn_cast<LoadSDNode>(NextInChain)) {
9586 if (Ldn->isVolatile()) {
9591 // Save the load node for later. Continue the scan.
9592 AliasLoadNodes.push_back(Ldn);
9593 NextInChain = Ldn->getChain().getNode();
9602 // Check if there is anything to merge.
9603 if (StoreNodes.size() < 2)
9606 // Sort the memory operands according to their distance from the base pointer.
9607 std::sort(StoreNodes.begin(), StoreNodes.end(),
9608 [](MemOpLink LHS, MemOpLink RHS) {
9609 return LHS.OffsetFromBase < RHS.OffsetFromBase ||
9610 (LHS.OffsetFromBase == RHS.OffsetFromBase &&
9611 LHS.SequenceNum > RHS.SequenceNum);
9614 // Scan the memory operations on the chain and find the first non-consecutive
9615 // store memory address.
9616 unsigned LastConsecutiveStore = 0;
9617 int64_t StartAddress = StoreNodes[0].OffsetFromBase;
9618 for (unsigned i = 0, e = StoreNodes.size(); i < e; ++i) {
9620 // Check that the addresses are consecutive starting from the second
9621 // element in the list of stores.
9623 int64_t CurrAddress = StoreNodes[i].OffsetFromBase;
9624 if (CurrAddress - StartAddress != (ElementSizeBytes * i))
9629 // Check if this store interferes with any of the loads that we found.
9630 for (unsigned ld = 0, lde = AliasLoadNodes.size(); ld < lde; ++ld)
9631 if (isAlias(AliasLoadNodes[ld], StoreNodes[i].MemNode)) {
9635 // We found a load that alias with this store. Stop the sequence.
9639 // Mark this node as useful.
9640 LastConsecutiveStore = i;
9643 // The node with the lowest store address.
9644 LSBaseSDNode *FirstInChain = StoreNodes[0].MemNode;
9646 // Store the constants into memory as one consecutive store.
9648 unsigned LastLegalType = 0;
9649 unsigned LastLegalVectorType = 0;
9650 bool NonZero = false;
9651 for (unsigned i=0; i<LastConsecutiveStore+1; ++i) {
9652 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
9653 SDValue StoredVal = St->getValue();
9655 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(StoredVal)) {
9656 NonZero |= !C->isNullValue();
9657 } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(StoredVal)) {
9658 NonZero |= !C->getConstantFPValue()->isNullValue();
9664 // Find a legal type for the constant store.
9665 unsigned StoreBW = (i+1) * ElementSizeBytes * 8;
9666 EVT StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
9667 if (TLI.isTypeLegal(StoreTy))
9668 LastLegalType = i+1;
9669 // Or check whether a truncstore is legal.
9670 else if (TLI.getTypeAction(*DAG.getContext(), StoreTy) ==
9671 TargetLowering::TypePromoteInteger) {
9672 EVT LegalizedStoredValueTy =
9673 TLI.getTypeToTransformTo(*DAG.getContext(), StoredVal.getValueType());
9674 if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy))
9675 LastLegalType = i+1;
9678 // Find a legal type for the vector store.
9679 EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT, i+1);
9680 if (TLI.isTypeLegal(Ty))
9681 LastLegalVectorType = i + 1;
9684 // We only use vectors if the constant is known to be zero and the
9685 // function is not marked with the noimplicitfloat attribute.
9686 if (NonZero || NoVectors)
9687 LastLegalVectorType = 0;
9689 // Check if we found a legal integer type to store.
9690 if (LastLegalType == 0 && LastLegalVectorType == 0)
9693 bool UseVector = (LastLegalVectorType > LastLegalType) && !NoVectors;
9694 unsigned NumElem = UseVector ? LastLegalVectorType : LastLegalType;
9696 // Make sure we have something to merge.
9700 unsigned EarliestNodeUsed = 0;
9701 for (unsigned i=0; i < NumElem; ++i) {
9702 // Find a chain for the new wide-store operand. Notice that some
9703 // of the store nodes that we found may not be selected for inclusion
9704 // in the wide store. The chain we use needs to be the chain of the
9705 // earliest store node which is *used* and replaced by the wide store.
9706 if (StoreNodes[i].SequenceNum > StoreNodes[EarliestNodeUsed].SequenceNum)
9707 EarliestNodeUsed = i;
9710 // The earliest Node in the DAG.
9711 LSBaseSDNode *EarliestOp = StoreNodes[EarliestNodeUsed].MemNode;
9712 SDLoc DL(StoreNodes[0].MemNode);
9716 // Find a legal type for the vector store.
9717 EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT, NumElem);
9718 assert(TLI.isTypeLegal(Ty) && "Illegal vector store");
9719 StoredVal = DAG.getConstant(0, Ty);
9721 unsigned StoreBW = NumElem * ElementSizeBytes * 8;
9722 APInt StoreInt(StoreBW, 0);
9724 // Construct a single integer constant which is made of the smaller
9726 bool IsLE = TLI.isLittleEndian();
9727 for (unsigned i = 0; i < NumElem ; ++i) {
9728 unsigned Idx = IsLE ?(NumElem - 1 - i) : i;
9729 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[Idx].MemNode);
9730 SDValue Val = St->getValue();
9731 StoreInt<<=ElementSizeBytes*8;
9732 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Val)) {
9733 StoreInt|=C->getAPIntValue().zext(StoreBW);
9734 } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Val)) {
9735 StoreInt|= C->getValueAPF().bitcastToAPInt().zext(StoreBW);
9737 assert(false && "Invalid constant element type");
9741 // Create the new Load and Store operations.
9742 EVT StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
9743 StoredVal = DAG.getConstant(StoreInt, StoreTy);
9746 SDValue NewStore = DAG.getStore(EarliestOp->getChain(), DL, StoredVal,
9747 FirstInChain->getBasePtr(),
9748 FirstInChain->getPointerInfo(),
9750 FirstInChain->getAlignment());
9752 // Replace the first store with the new store
9753 CombineTo(EarliestOp, NewStore);
9754 // Erase all other stores.
9755 for (unsigned i = 0; i < NumElem ; ++i) {
9756 if (StoreNodes[i].MemNode == EarliestOp)
9758 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
9759 // ReplaceAllUsesWith will replace all uses that existed when it was
9760 // called, but graph optimizations may cause new ones to appear. For
9761 // example, the case in pr14333 looks like
9763 // St's chain -> St -> another store -> X
9765 // And the only difference from St to the other store is the chain.
9766 // When we change it's chain to be St's chain they become identical,
9767 // get CSEed and the net result is that X is now a use of St.
9768 // Since we know that St is redundant, just iterate.
9769 while (!St->use_empty())
9770 DAG.ReplaceAllUsesWith(SDValue(St, 0), St->getChain());
9771 deleteAndRecombine(St);
9777 // Below we handle the case of multiple consecutive stores that
9778 // come from multiple consecutive loads. We merge them into a single
9779 // wide load and a single wide store.
9781 // Look for load nodes which are used by the stored values.
9782 SmallVector<MemOpLink, 8> LoadNodes;
9784 // Find acceptable loads. Loads need to have the same chain (token factor),
9785 // must not be zext, volatile, indexed, and they must be consecutive.
9786 BaseIndexOffset LdBasePtr;
9787 for (unsigned i=0; i<LastConsecutiveStore+1; ++i) {
9788 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
9789 LoadSDNode *Ld = dyn_cast<LoadSDNode>(St->getValue());
9792 // Loads must only have one use.
9793 if (!Ld->hasNUsesOfValue(1, 0))
9796 // Check that the alignment is the same as the stores.
9797 if (Ld->getAlignment() != St->getAlignment())
9800 // The memory operands must not be volatile.
9801 if (Ld->isVolatile() || Ld->isIndexed())
9804 // We do not accept ext loads.
9805 if (Ld->getExtensionType() != ISD::NON_EXTLOAD)
9808 // The stored memory type must be the same.
9809 if (Ld->getMemoryVT() != MemVT)
9812 BaseIndexOffset LdPtr = BaseIndexOffset::match(Ld->getBasePtr());
9813 // If this is not the first ptr that we check.
9814 if (LdBasePtr.Base.getNode()) {
9815 // The base ptr must be the same.
9816 if (!LdPtr.equalBaseIndex(LdBasePtr))
9819 // Check that all other base pointers are the same as this one.
9823 // We found a potential memory operand to merge.
9824 LoadNodes.push_back(MemOpLink(Ld, LdPtr.Offset, 0));
9827 if (LoadNodes.size() < 2)
9830 // If we have load/store pair instructions and we only have two values,
9832 unsigned RequiredAlignment;
9833 if (LoadNodes.size() == 2 && TLI.hasPairedLoad(MemVT, RequiredAlignment) &&
9834 St->getAlignment() >= RequiredAlignment)
9837 // Scan the memory operations on the chain and find the first non-consecutive
9838 // load memory address. These variables hold the index in the store node
9840 unsigned LastConsecutiveLoad = 0;
9841 // This variable refers to the size and not index in the array.
9842 unsigned LastLegalVectorType = 0;
9843 unsigned LastLegalIntegerType = 0;
9844 StartAddress = LoadNodes[0].OffsetFromBase;
9845 SDValue FirstChain = LoadNodes[0].MemNode->getChain();
9846 for (unsigned i = 1; i < LoadNodes.size(); ++i) {
9847 // All loads much share the same chain.
9848 if (LoadNodes[i].MemNode->getChain() != FirstChain)
9851 int64_t CurrAddress = LoadNodes[i].OffsetFromBase;
9852 if (CurrAddress - StartAddress != (ElementSizeBytes * i))
9854 LastConsecutiveLoad = i;
9856 // Find a legal type for the vector store.
9857 EVT StoreTy = EVT::getVectorVT(*DAG.getContext(), MemVT, i+1);
9858 if (TLI.isTypeLegal(StoreTy))
9859 LastLegalVectorType = i + 1;
9861 // Find a legal type for the integer store.
9862 unsigned StoreBW = (i+1) * ElementSizeBytes * 8;
9863 StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
9864 if (TLI.isTypeLegal(StoreTy))
9865 LastLegalIntegerType = i + 1;
9866 // Or check whether a truncstore and extload is legal.
9867 else if (TLI.getTypeAction(*DAG.getContext(), StoreTy) ==
9868 TargetLowering::TypePromoteInteger) {
9869 EVT LegalizedStoredValueTy =
9870 TLI.getTypeToTransformTo(*DAG.getContext(), StoreTy);
9871 if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy) &&
9872 TLI.isLoadExtLegal(ISD::ZEXTLOAD, StoreTy) &&
9873 TLI.isLoadExtLegal(ISD::SEXTLOAD, StoreTy) &&
9874 TLI.isLoadExtLegal(ISD::EXTLOAD, StoreTy))
9875 LastLegalIntegerType = i+1;
9879 // Only use vector types if the vector type is larger than the integer type.
9880 // If they are the same, use integers.
9881 bool UseVectorTy = LastLegalVectorType > LastLegalIntegerType && !NoVectors;
9882 unsigned LastLegalType = std::max(LastLegalVectorType, LastLegalIntegerType);
9884 // We add +1 here because the LastXXX variables refer to location while
9885 // the NumElem refers to array/index size.
9886 unsigned NumElem = std::min(LastConsecutiveStore, LastConsecutiveLoad) + 1;
9887 NumElem = std::min(LastLegalType, NumElem);
9892 // The earliest Node in the DAG.
9893 unsigned EarliestNodeUsed = 0;
9894 LSBaseSDNode *EarliestOp = StoreNodes[EarliestNodeUsed].MemNode;
9895 for (unsigned i=1; i<NumElem; ++i) {
9896 // Find a chain for the new wide-store operand. Notice that some
9897 // of the store nodes that we found may not be selected for inclusion
9898 // in the wide store. The chain we use needs to be the chain of the
9899 // earliest store node which is *used* and replaced by the wide store.
9900 if (StoreNodes[i].SequenceNum > StoreNodes[EarliestNodeUsed].SequenceNum)
9901 EarliestNodeUsed = i;
9904 // Find if it is better to use vectors or integers to load and store
9908 JointMemOpVT = EVT::getVectorVT(*DAG.getContext(), MemVT, NumElem);
9910 unsigned StoreBW = NumElem * ElementSizeBytes * 8;
9911 JointMemOpVT = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
9914 SDLoc LoadDL(LoadNodes[0].MemNode);
9915 SDLoc StoreDL(StoreNodes[0].MemNode);
9917 LoadSDNode *FirstLoad = cast<LoadSDNode>(LoadNodes[0].MemNode);
9918 SDValue NewLoad = DAG.getLoad(JointMemOpVT, LoadDL,
9919 FirstLoad->getChain(),
9920 FirstLoad->getBasePtr(),
9921 FirstLoad->getPointerInfo(),
9922 false, false, false,
9923 FirstLoad->getAlignment());
9925 SDValue NewStore = DAG.getStore(EarliestOp->getChain(), StoreDL, NewLoad,
9926 FirstInChain->getBasePtr(),
9927 FirstInChain->getPointerInfo(), false, false,
9928 FirstInChain->getAlignment());
9930 // Replace one of the loads with the new load.
9931 LoadSDNode *Ld = cast<LoadSDNode>(LoadNodes[0].MemNode);
9932 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1),
9933 SDValue(NewLoad.getNode(), 1));
9935 // Remove the rest of the load chains.
9936 for (unsigned i = 1; i < NumElem ; ++i) {
9937 // Replace all chain users of the old load nodes with the chain of the new
9939 LoadSDNode *Ld = cast<LoadSDNode>(LoadNodes[i].MemNode);
9940 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), Ld->getChain());
9943 // Replace the first store with the new store.
9944 CombineTo(EarliestOp, NewStore);
9945 // Erase all other stores.
9946 for (unsigned i = 0; i < NumElem ; ++i) {
9947 // Remove all Store nodes.
9948 if (StoreNodes[i].MemNode == EarliestOp)
9950 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
9951 DAG.ReplaceAllUsesOfValueWith(SDValue(St, 0), St->getChain());
9952 deleteAndRecombine(St);
9958 SDValue DAGCombiner::visitSTORE(SDNode *N) {
9959 StoreSDNode *ST = cast<StoreSDNode>(N);
9960 SDValue Chain = ST->getChain();
9961 SDValue Value = ST->getValue();
9962 SDValue Ptr = ST->getBasePtr();
9964 // If this is a store of a bit convert, store the input value if the
9965 // resultant store does not need a higher alignment than the original.
9966 if (Value.getOpcode() == ISD::BITCAST && !ST->isTruncatingStore() &&
9967 ST->isUnindexed()) {
9968 unsigned OrigAlign = ST->getAlignment();
9969 EVT SVT = Value.getOperand(0).getValueType();
9970 unsigned Align = TLI.getDataLayout()->
9971 getABITypeAlignment(SVT.getTypeForEVT(*DAG.getContext()));
9972 if (Align <= OrigAlign &&
9973 ((!LegalOperations && !ST->isVolatile()) ||
9974 TLI.isOperationLegalOrCustom(ISD::STORE, SVT)))
9975 return DAG.getStore(Chain, SDLoc(N), Value.getOperand(0),
9976 Ptr, ST->getPointerInfo(), ST->isVolatile(),
9977 ST->isNonTemporal(), OrigAlign,
9981 // Turn 'store undef, Ptr' -> nothing.
9982 if (Value.getOpcode() == ISD::UNDEF && ST->isUnindexed())
9985 // Turn 'store float 1.0, Ptr' -> 'store int 0x12345678, Ptr'
9986 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Value)) {
9987 // NOTE: If the original store is volatile, this transform must not increase
9988 // the number of stores. For example, on x86-32 an f64 can be stored in one
9989 // processor operation but an i64 (which is not legal) requires two. So the
9990 // transform should not be done in this case.
9991 if (Value.getOpcode() != ISD::TargetConstantFP) {
9993 switch (CFP->getSimpleValueType(0).SimpleTy) {
9994 default: llvm_unreachable("Unknown FP type");
9995 case MVT::f16: // We don't do this for these yet.
10001 if ((isTypeLegal(MVT::i32) && !LegalOperations && !ST->isVolatile()) ||
10002 TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) {
10003 Tmp = DAG.getConstant((uint32_t)CFP->getValueAPF().
10004 bitcastToAPInt().getZExtValue(), MVT::i32);
10005 return DAG.getStore(Chain, SDLoc(N), Tmp,
10006 Ptr, ST->getMemOperand());
10010 if ((TLI.isTypeLegal(MVT::i64) && !LegalOperations &&
10011 !ST->isVolatile()) ||
10012 TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i64)) {
10013 Tmp = DAG.getConstant(CFP->getValueAPF().bitcastToAPInt().
10014 getZExtValue(), MVT::i64);
10015 return DAG.getStore(Chain, SDLoc(N), Tmp,
10016 Ptr, ST->getMemOperand());
10019 if (!ST->isVolatile() &&
10020 TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) {
10021 // Many FP stores are not made apparent until after legalize, e.g. for
10022 // argument passing. Since this is so common, custom legalize the
10023 // 64-bit integer store into two 32-bit stores.
10024 uint64_t Val = CFP->getValueAPF().bitcastToAPInt().getZExtValue();
10025 SDValue Lo = DAG.getConstant(Val & 0xFFFFFFFF, MVT::i32);
10026 SDValue Hi = DAG.getConstant(Val >> 32, MVT::i32);
10027 if (TLI.isBigEndian()) std::swap(Lo, Hi);
10029 unsigned Alignment = ST->getAlignment();
10030 bool isVolatile = ST->isVolatile();
10031 bool isNonTemporal = ST->isNonTemporal();
10032 AAMDNodes AAInfo = ST->getAAInfo();
10034 SDValue St0 = DAG.getStore(Chain, SDLoc(ST), Lo,
10035 Ptr, ST->getPointerInfo(),
10036 isVolatile, isNonTemporal,
10037 ST->getAlignment(), AAInfo);
10038 Ptr = DAG.getNode(ISD::ADD, SDLoc(N), Ptr.getValueType(), Ptr,
10039 DAG.getConstant(4, Ptr.getValueType()));
10040 Alignment = MinAlign(Alignment, 4U);
10041 SDValue St1 = DAG.getStore(Chain, SDLoc(ST), Hi,
10042 Ptr, ST->getPointerInfo().getWithOffset(4),
10043 isVolatile, isNonTemporal,
10044 Alignment, AAInfo);
10045 return DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other,
10054 // Try to infer better alignment information than the store already has.
10055 if (OptLevel != CodeGenOpt::None && ST->isUnindexed()) {
10056 if (unsigned Align = DAG.InferPtrAlignment(Ptr)) {
10057 if (Align > ST->getAlignment())
10058 return DAG.getTruncStore(Chain, SDLoc(N), Value,
10059 Ptr, ST->getPointerInfo(), ST->getMemoryVT(),
10060 ST->isVolatile(), ST->isNonTemporal(), Align,
10065 // Try transforming a pair floating point load / store ops to integer
10066 // load / store ops.
10067 SDValue NewST = TransformFPLoadStorePair(N);
10068 if (NewST.getNode())
10071 bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA
10072 : DAG.getSubtarget().useAA();
10074 if (CombinerAAOnlyFunc.getNumOccurrences() &&
10075 CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
10078 if (UseAA && ST->isUnindexed()) {
10079 // Walk up chain skipping non-aliasing memory nodes.
10080 SDValue BetterChain = FindBetterChain(N, Chain);
10082 // If there is a better chain.
10083 if (Chain != BetterChain) {
10086 // Replace the chain to avoid dependency.
10087 if (ST->isTruncatingStore()) {
10088 ReplStore = DAG.getTruncStore(BetterChain, SDLoc(N), Value, Ptr,
10089 ST->getMemoryVT(), ST->getMemOperand());
10091 ReplStore = DAG.getStore(BetterChain, SDLoc(N), Value, Ptr,
10092 ST->getMemOperand());
10095 // Create token to keep both nodes around.
10096 SDValue Token = DAG.getNode(ISD::TokenFactor, SDLoc(N),
10097 MVT::Other, Chain, ReplStore);
10099 // Make sure the new and old chains are cleaned up.
10100 AddToWorklist(Token.getNode());
10102 // Don't add users to work list.
10103 return CombineTo(N, Token, false);
10107 // Try transforming N to an indexed store.
10108 if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
10109 return SDValue(N, 0);
10111 // FIXME: is there such a thing as a truncating indexed store?
10112 if (ST->isTruncatingStore() && ST->isUnindexed() &&
10113 Value.getValueType().isInteger()) {
10114 // See if we can simplify the input to this truncstore with knowledge that
10115 // only the low bits are being used. For example:
10116 // "truncstore (or (shl x, 8), y), i8" -> "truncstore y, i8"
10118 GetDemandedBits(Value,
10119 APInt::getLowBitsSet(
10120 Value.getValueType().getScalarType().getSizeInBits(),
10121 ST->getMemoryVT().getScalarType().getSizeInBits()));
10122 AddToWorklist(Value.getNode());
10123 if (Shorter.getNode())
10124 return DAG.getTruncStore(Chain, SDLoc(N), Shorter,
10125 Ptr, ST->getMemoryVT(), ST->getMemOperand());
10127 // Otherwise, see if we can simplify the operation with
10128 // SimplifyDemandedBits, which only works if the value has a single use.
10129 if (SimplifyDemandedBits(Value,
10130 APInt::getLowBitsSet(
10131 Value.getValueType().getScalarType().getSizeInBits(),
10132 ST->getMemoryVT().getScalarType().getSizeInBits())))
10133 return SDValue(N, 0);
10136 // If this is a load followed by a store to the same location, then the store
10138 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Value)) {
10139 if (Ld->getBasePtr() == Ptr && ST->getMemoryVT() == Ld->getMemoryVT() &&
10140 ST->isUnindexed() && !ST->isVolatile() &&
10141 // There can't be any side effects between the load and store, such as
10142 // a call or store.
10143 Chain.reachesChainWithoutSideEffects(SDValue(Ld, 1))) {
10144 // The store is dead, remove it.
10149 // If this is a store followed by a store with the same value to the same
10150 // location, then the store is dead/noop.
10151 if (StoreSDNode *ST1 = dyn_cast<StoreSDNode>(Chain)) {
10152 if (ST1->getBasePtr() == Ptr && ST->getMemoryVT() == ST1->getMemoryVT() &&
10153 ST1->getValue() == Value && ST->isUnindexed() && !ST->isVolatile() &&
10154 ST1->isUnindexed() && !ST1->isVolatile()) {
10155 // The store is dead, remove it.
10160 // If this is an FP_ROUND or TRUNC followed by a store, fold this into a
10161 // truncating store. We can do this even if this is already a truncstore.
10162 if ((Value.getOpcode() == ISD::FP_ROUND || Value.getOpcode() == ISD::TRUNCATE)
10163 && Value.getNode()->hasOneUse() && ST->isUnindexed() &&
10164 TLI.isTruncStoreLegal(Value.getOperand(0).getValueType(),
10165 ST->getMemoryVT())) {
10166 return DAG.getTruncStore(Chain, SDLoc(N), Value.getOperand(0),
10167 Ptr, ST->getMemoryVT(), ST->getMemOperand());
10170 // Only perform this optimization before the types are legal, because we
10171 // don't want to perform this optimization on every DAGCombine invocation.
10173 bool EverChanged = false;
10176 // There can be multiple store sequences on the same chain.
10177 // Keep trying to merge store sequences until we are unable to do so
10178 // or until we merge the last store on the chain.
10179 bool Changed = MergeConsecutiveStores(ST);
10180 EverChanged |= Changed;
10181 if (!Changed) break;
10182 } while (ST->getOpcode() != ISD::DELETED_NODE);
10185 return SDValue(N, 0);
10188 return ReduceLoadOpStoreWidth(N);
10191 SDValue DAGCombiner::visitINSERT_VECTOR_ELT(SDNode *N) {
10192 SDValue InVec = N->getOperand(0);
10193 SDValue InVal = N->getOperand(1);
10194 SDValue EltNo = N->getOperand(2);
10197 // If the inserted element is an UNDEF, just use the input vector.
10198 if (InVal.getOpcode() == ISD::UNDEF)
10201 EVT VT = InVec.getValueType();
10203 // If we can't generate a legal BUILD_VECTOR, exit
10204 if (LegalOperations && !TLI.isOperationLegal(ISD::BUILD_VECTOR, VT))
10207 // Check that we know which element is being inserted
10208 if (!isa<ConstantSDNode>(EltNo))
10210 unsigned Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
10212 // Canonicalize insert_vector_elt dag nodes.
10214 // (insert_vector_elt (insert_vector_elt A, Idx0), Idx1)
10215 // -> (insert_vector_elt (insert_vector_elt A, Idx1), Idx0)
10217 // Do this only if the child insert_vector node has one use; also
10218 // do this only if indices are both constants and Idx1 < Idx0.
10219 if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT && InVec.hasOneUse()
10220 && isa<ConstantSDNode>(InVec.getOperand(2))) {
10221 unsigned OtherElt =
10222 cast<ConstantSDNode>(InVec.getOperand(2))->getZExtValue();
10223 if (Elt < OtherElt) {
10225 SDValue NewOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, SDLoc(N), VT,
10226 InVec.getOperand(0), InVal, EltNo);
10227 AddToWorklist(NewOp.getNode());
10228 return DAG.getNode(ISD::INSERT_VECTOR_ELT, SDLoc(InVec.getNode()),
10229 VT, NewOp, InVec.getOperand(1), InVec.getOperand(2));
10233 // Check that the operand is a BUILD_VECTOR (or UNDEF, which can essentially
10234 // be converted to a BUILD_VECTOR). Fill in the Ops vector with the
10235 // vector elements.
10236 SmallVector<SDValue, 8> Ops;
10237 // Do not combine these two vectors if the output vector will not replace
10238 // the input vector.
10239 if (InVec.getOpcode() == ISD::BUILD_VECTOR && InVec.hasOneUse()) {
10240 Ops.append(InVec.getNode()->op_begin(),
10241 InVec.getNode()->op_end());
10242 } else if (InVec.getOpcode() == ISD::UNDEF) {
10243 unsigned NElts = VT.getVectorNumElements();
10244 Ops.append(NElts, DAG.getUNDEF(InVal.getValueType()));
10249 // Insert the element
10250 if (Elt < Ops.size()) {
10251 // All the operands of BUILD_VECTOR must have the same type;
10252 // we enforce that here.
10253 EVT OpVT = Ops[0].getValueType();
10254 if (InVal.getValueType() != OpVT)
10255 InVal = OpVT.bitsGT(InVal.getValueType()) ?
10256 DAG.getNode(ISD::ANY_EXTEND, dl, OpVT, InVal) :
10257 DAG.getNode(ISD::TRUNCATE, dl, OpVT, InVal);
10261 // Return the new vector
10262 return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
10265 SDValue DAGCombiner::ReplaceExtractVectorEltOfLoadWithNarrowedLoad(
10266 SDNode *EVE, EVT InVecVT, SDValue EltNo, LoadSDNode *OriginalLoad) {
10267 EVT ResultVT = EVE->getValueType(0);
10268 EVT VecEltVT = InVecVT.getVectorElementType();
10269 unsigned Align = OriginalLoad->getAlignment();
10270 unsigned NewAlign = TLI.getDataLayout()->getABITypeAlignment(
10271 VecEltVT.getTypeForEVT(*DAG.getContext()));
10273 if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, VecEltVT))
10278 SDValue NewPtr = OriginalLoad->getBasePtr();
10280 EVT PtrType = NewPtr.getValueType();
10281 MachinePointerInfo MPI;
10282 if (auto *ConstEltNo = dyn_cast<ConstantSDNode>(EltNo)) {
10283 int Elt = ConstEltNo->getZExtValue();
10284 unsigned PtrOff = VecEltVT.getSizeInBits() * Elt / 8;
10285 if (TLI.isBigEndian())
10286 PtrOff = InVecVT.getSizeInBits() / 8 - PtrOff;
10287 Offset = DAG.getConstant(PtrOff, PtrType);
10288 MPI = OriginalLoad->getPointerInfo().getWithOffset(PtrOff);
10290 Offset = DAG.getNode(
10291 ISD::MUL, SDLoc(EVE), EltNo.getValueType(), EltNo,
10292 DAG.getConstant(VecEltVT.getStoreSize(), EltNo.getValueType()));
10293 if (TLI.isBigEndian())
10294 Offset = DAG.getNode(
10295 ISD::SUB, SDLoc(EVE), EltNo.getValueType(),
10296 DAG.getConstant(InVecVT.getStoreSize(), EltNo.getValueType()), Offset);
10297 MPI = OriginalLoad->getPointerInfo();
10299 NewPtr = DAG.getNode(ISD::ADD, SDLoc(EVE), PtrType, NewPtr, Offset);
10301 // The replacement we need to do here is a little tricky: we need to
10302 // replace an extractelement of a load with a load.
10303 // Use ReplaceAllUsesOfValuesWith to do the replacement.
10304 // Note that this replacement assumes that the extractvalue is the only
10305 // use of the load; that's okay because we don't want to perform this
10306 // transformation in other cases anyway.
10309 if (ResultVT.bitsGT(VecEltVT)) {
10310 // If the result type of vextract is wider than the load, then issue an
10311 // extending load instead.
10312 ISD::LoadExtType ExtType = TLI.isLoadExtLegal(ISD::ZEXTLOAD, VecEltVT)
10315 Load = DAG.getExtLoad(
10316 ExtType, SDLoc(EVE), ResultVT, OriginalLoad->getChain(), NewPtr, MPI,
10317 VecEltVT, OriginalLoad->isVolatile(), OriginalLoad->isNonTemporal(),
10318 OriginalLoad->isInvariant(), Align, OriginalLoad->getAAInfo());
10319 Chain = Load.getValue(1);
10321 Load = DAG.getLoad(
10322 VecEltVT, SDLoc(EVE), OriginalLoad->getChain(), NewPtr, MPI,
10323 OriginalLoad->isVolatile(), OriginalLoad->isNonTemporal(),
10324 OriginalLoad->isInvariant(), Align, OriginalLoad->getAAInfo());
10325 Chain = Load.getValue(1);
10326 if (ResultVT.bitsLT(VecEltVT))
10327 Load = DAG.getNode(ISD::TRUNCATE, SDLoc(EVE), ResultVT, Load);
10329 Load = DAG.getNode(ISD::BITCAST, SDLoc(EVE), ResultVT, Load);
10331 WorklistRemover DeadNodes(*this);
10332 SDValue From[] = { SDValue(EVE, 0), SDValue(OriginalLoad, 1) };
10333 SDValue To[] = { Load, Chain };
10334 DAG.ReplaceAllUsesOfValuesWith(From, To, 2);
10335 // Since we're explicitly calling ReplaceAllUses, add the new node to the
10336 // worklist explicitly as well.
10337 AddToWorklist(Load.getNode());
10338 AddUsersToWorklist(Load.getNode()); // Add users too
10339 // Make sure to revisit this node to clean it up; it will usually be dead.
10340 AddToWorklist(EVE);
10342 return SDValue(EVE, 0);
10345 SDValue DAGCombiner::visitEXTRACT_VECTOR_ELT(SDNode *N) {
10346 // (vextract (scalar_to_vector val, 0) -> val
10347 SDValue InVec = N->getOperand(0);
10348 EVT VT = InVec.getValueType();
10349 EVT NVT = N->getValueType(0);
10351 if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR) {
10352 // Check if the result type doesn't match the inserted element type. A
10353 // SCALAR_TO_VECTOR may truncate the inserted element and the
10354 // EXTRACT_VECTOR_ELT may widen the extracted vector.
10355 SDValue InOp = InVec.getOperand(0);
10356 if (InOp.getValueType() != NVT) {
10357 assert(InOp.getValueType().isInteger() && NVT.isInteger());
10358 return DAG.getSExtOrTrunc(InOp, SDLoc(InVec), NVT);
10363 SDValue EltNo = N->getOperand(1);
10364 bool ConstEltNo = isa<ConstantSDNode>(EltNo);
10366 // Transform: (EXTRACT_VECTOR_ELT( VECTOR_SHUFFLE )) -> EXTRACT_VECTOR_ELT.
10367 // We only perform this optimization before the op legalization phase because
10368 // we may introduce new vector instructions which are not backed by TD
10369 // patterns. For example on AVX, extracting elements from a wide vector
10370 // without using extract_subvector. However, if we can find an underlying
10371 // scalar value, then we can always use that.
10372 if (InVec.getOpcode() == ISD::VECTOR_SHUFFLE
10374 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
10375 int NumElem = VT.getVectorNumElements();
10376 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(InVec);
10377 // Find the new index to extract from.
10378 int OrigElt = SVOp->getMaskElt(Elt);
10380 // Extracting an undef index is undef.
10382 return DAG.getUNDEF(NVT);
10384 // Select the right vector half to extract from.
10386 if (OrigElt < NumElem) {
10387 SVInVec = InVec->getOperand(0);
10389 SVInVec = InVec->getOperand(1);
10390 OrigElt -= NumElem;
10393 if (SVInVec.getOpcode() == ISD::BUILD_VECTOR) {
10394 SDValue InOp = SVInVec.getOperand(OrigElt);
10395 if (InOp.getValueType() != NVT) {
10396 assert(InOp.getValueType().isInteger() && NVT.isInteger());
10397 InOp = DAG.getSExtOrTrunc(InOp, SDLoc(SVInVec), NVT);
10403 // FIXME: We should handle recursing on other vector shuffles and
10404 // scalar_to_vector here as well.
10406 if (!LegalOperations) {
10407 EVT IndexTy = TLI.getVectorIdxTy();
10408 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SDLoc(N), NVT,
10409 SVInVec, DAG.getConstant(OrigElt, IndexTy));
10413 bool BCNumEltsChanged = false;
10414 EVT ExtVT = VT.getVectorElementType();
10417 // If the result of load has to be truncated, then it's not necessarily
10419 if (NVT.bitsLT(LVT) && !TLI.isTruncateFree(LVT, NVT))
10422 if (InVec.getOpcode() == ISD::BITCAST) {
10423 // Don't duplicate a load with other uses.
10424 if (!InVec.hasOneUse())
10427 EVT BCVT = InVec.getOperand(0).getValueType();
10428 if (!BCVT.isVector() || ExtVT.bitsGT(BCVT.getVectorElementType()))
10430 if (VT.getVectorNumElements() != BCVT.getVectorNumElements())
10431 BCNumEltsChanged = true;
10432 InVec = InVec.getOperand(0);
10433 ExtVT = BCVT.getVectorElementType();
10436 // (vextract (vN[if]M load $addr), i) -> ([if]M load $addr + i * size)
10437 if (!LegalOperations && !ConstEltNo && InVec.hasOneUse() &&
10438 ISD::isNormalLoad(InVec.getNode()) &&
10439 !N->getOperand(1)->hasPredecessor(InVec.getNode())) {
10440 SDValue Index = N->getOperand(1);
10441 if (LoadSDNode *OrigLoad = dyn_cast<LoadSDNode>(InVec))
10442 return ReplaceExtractVectorEltOfLoadWithNarrowedLoad(N, VT, Index,
10446 // Perform only after legalization to ensure build_vector / vector_shuffle
10447 // optimizations have already been done.
10448 if (!LegalOperations) return SDValue();
10450 // (vextract (v4f32 load $addr), c) -> (f32 load $addr+c*size)
10451 // (vextract (v4f32 s2v (f32 load $addr)), c) -> (f32 load $addr+c*size)
10452 // (vextract (v4f32 shuffle (load $addr), <1,u,u,u>), 0) -> (f32 load $addr)
10455 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
10457 LoadSDNode *LN0 = nullptr;
10458 const ShuffleVectorSDNode *SVN = nullptr;
10459 if (ISD::isNormalLoad(InVec.getNode())) {
10460 LN0 = cast<LoadSDNode>(InVec);
10461 } else if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR &&
10462 InVec.getOperand(0).getValueType() == ExtVT &&
10463 ISD::isNormalLoad(InVec.getOperand(0).getNode())) {
10464 // Don't duplicate a load with other uses.
10465 if (!InVec.hasOneUse())
10468 LN0 = cast<LoadSDNode>(InVec.getOperand(0));
10469 } else if ((SVN = dyn_cast<ShuffleVectorSDNode>(InVec))) {
10470 // (vextract (vector_shuffle (load $addr), v2, <1, u, u, u>), 1)
10472 // (load $addr+1*size)
10474 // Don't duplicate a load with other uses.
10475 if (!InVec.hasOneUse())
10478 // If the bit convert changed the number of elements, it is unsafe
10479 // to examine the mask.
10480 if (BCNumEltsChanged)
10483 // Select the input vector, guarding against out of range extract vector.
10484 unsigned NumElems = VT.getVectorNumElements();
10485 int Idx = (Elt > (int)NumElems) ? -1 : SVN->getMaskElt(Elt);
10486 InVec = (Idx < (int)NumElems) ? InVec.getOperand(0) : InVec.getOperand(1);
10488 if (InVec.getOpcode() == ISD::BITCAST) {
10489 // Don't duplicate a load with other uses.
10490 if (!InVec.hasOneUse())
10493 InVec = InVec.getOperand(0);
10495 if (ISD::isNormalLoad(InVec.getNode())) {
10496 LN0 = cast<LoadSDNode>(InVec);
10497 Elt = (Idx < (int)NumElems) ? Idx : Idx - (int)NumElems;
10498 EltNo = DAG.getConstant(Elt, EltNo.getValueType());
10502 // Make sure we found a non-volatile load and the extractelement is
10504 if (!LN0 || !LN0->hasNUsesOfValue(1,0) || LN0->isVolatile())
10507 // If Idx was -1 above, Elt is going to be -1, so just return undef.
10509 return DAG.getUNDEF(LVT);
10511 return ReplaceExtractVectorEltOfLoadWithNarrowedLoad(N, VT, EltNo, LN0);
10517 // Simplify (build_vec (ext )) to (bitcast (build_vec ))
10518 SDValue DAGCombiner::reduceBuildVecExtToExtBuildVec(SDNode *N) {
10519 // We perform this optimization post type-legalization because
10520 // the type-legalizer often scalarizes integer-promoted vectors.
10521 // Performing this optimization before may create bit-casts which
10522 // will be type-legalized to complex code sequences.
10523 // We perform this optimization only before the operation legalizer because we
10524 // may introduce illegal operations.
10525 if (Level != AfterLegalizeVectorOps && Level != AfterLegalizeTypes)
10528 unsigned NumInScalars = N->getNumOperands();
10530 EVT VT = N->getValueType(0);
10532 // Check to see if this is a BUILD_VECTOR of a bunch of values
10533 // which come from any_extend or zero_extend nodes. If so, we can create
10534 // a new BUILD_VECTOR using bit-casts which may enable other BUILD_VECTOR
10535 // optimizations. We do not handle sign-extend because we can't fill the sign
10537 EVT SourceType = MVT::Other;
10538 bool AllAnyExt = true;
10540 for (unsigned i = 0; i != NumInScalars; ++i) {
10541 SDValue In = N->getOperand(i);
10542 // Ignore undef inputs.
10543 if (In.getOpcode() == ISD::UNDEF) continue;
10545 bool AnyExt = In.getOpcode() == ISD::ANY_EXTEND;
10546 bool ZeroExt = In.getOpcode() == ISD::ZERO_EXTEND;
10548 // Abort if the element is not an extension.
10549 if (!ZeroExt && !AnyExt) {
10550 SourceType = MVT::Other;
10554 // The input is a ZeroExt or AnyExt. Check the original type.
10555 EVT InTy = In.getOperand(0).getValueType();
10557 // Check that all of the widened source types are the same.
10558 if (SourceType == MVT::Other)
10561 else if (InTy != SourceType) {
10562 // Multiple income types. Abort.
10563 SourceType = MVT::Other;
10567 // Check if all of the extends are ANY_EXTENDs.
10568 AllAnyExt &= AnyExt;
10571 // In order to have valid types, all of the inputs must be extended from the
10572 // same source type and all of the inputs must be any or zero extend.
10573 // Scalar sizes must be a power of two.
10574 EVT OutScalarTy = VT.getScalarType();
10575 bool ValidTypes = SourceType != MVT::Other &&
10576 isPowerOf2_32(OutScalarTy.getSizeInBits()) &&
10577 isPowerOf2_32(SourceType.getSizeInBits());
10579 // Create a new simpler BUILD_VECTOR sequence which other optimizations can
10580 // turn into a single shuffle instruction.
10584 bool isLE = TLI.isLittleEndian();
10585 unsigned ElemRatio = OutScalarTy.getSizeInBits()/SourceType.getSizeInBits();
10586 assert(ElemRatio > 1 && "Invalid element size ratio");
10587 SDValue Filler = AllAnyExt ? DAG.getUNDEF(SourceType):
10588 DAG.getConstant(0, SourceType);
10590 unsigned NewBVElems = ElemRatio * VT.getVectorNumElements();
10591 SmallVector<SDValue, 8> Ops(NewBVElems, Filler);
10593 // Populate the new build_vector
10594 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
10595 SDValue Cast = N->getOperand(i);
10596 assert((Cast.getOpcode() == ISD::ANY_EXTEND ||
10597 Cast.getOpcode() == ISD::ZERO_EXTEND ||
10598 Cast.getOpcode() == ISD::UNDEF) && "Invalid cast opcode");
10600 if (Cast.getOpcode() == ISD::UNDEF)
10601 In = DAG.getUNDEF(SourceType);
10603 In = Cast->getOperand(0);
10604 unsigned Index = isLE ? (i * ElemRatio) :
10605 (i * ElemRatio + (ElemRatio - 1));
10607 assert(Index < Ops.size() && "Invalid index");
10611 // The type of the new BUILD_VECTOR node.
10612 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), SourceType, NewBVElems);
10613 assert(VecVT.getSizeInBits() == VT.getSizeInBits() &&
10614 "Invalid vector size");
10615 // Check if the new vector type is legal.
10616 if (!isTypeLegal(VecVT)) return SDValue();
10618 // Make the new BUILD_VECTOR.
10619 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, VecVT, Ops);
10621 // The new BUILD_VECTOR node has the potential to be further optimized.
10622 AddToWorklist(BV.getNode());
10623 // Bitcast to the desired type.
10624 return DAG.getNode(ISD::BITCAST, dl, VT, BV);
10627 SDValue DAGCombiner::reduceBuildVecConvertToConvertBuildVec(SDNode *N) {
10628 EVT VT = N->getValueType(0);
10630 unsigned NumInScalars = N->getNumOperands();
10633 EVT SrcVT = MVT::Other;
10634 unsigned Opcode = ISD::DELETED_NODE;
10635 unsigned NumDefs = 0;
10637 for (unsigned i = 0; i != NumInScalars; ++i) {
10638 SDValue In = N->getOperand(i);
10639 unsigned Opc = In.getOpcode();
10641 if (Opc == ISD::UNDEF)
10644 // If all scalar values are floats and converted from integers.
10645 if (Opcode == ISD::DELETED_NODE &&
10646 (Opc == ISD::UINT_TO_FP || Opc == ISD::SINT_TO_FP)) {
10653 EVT InVT = In.getOperand(0).getValueType();
10655 // If all scalar values are typed differently, bail out. It's chosen to
10656 // simplify BUILD_VECTOR of integer types.
10657 if (SrcVT == MVT::Other)
10664 // If the vector has just one element defined, it's not worth to fold it into
10665 // a vectorized one.
10669 assert((Opcode == ISD::UINT_TO_FP || Opcode == ISD::SINT_TO_FP)
10670 && "Should only handle conversion from integer to float.");
10671 assert(SrcVT != MVT::Other && "Cannot determine source type!");
10673 EVT NVT = EVT::getVectorVT(*DAG.getContext(), SrcVT, NumInScalars);
10675 if (!TLI.isOperationLegalOrCustom(Opcode, NVT))
10678 SmallVector<SDValue, 8> Opnds;
10679 for (unsigned i = 0; i != NumInScalars; ++i) {
10680 SDValue In = N->getOperand(i);
10682 if (In.getOpcode() == ISD::UNDEF)
10683 Opnds.push_back(DAG.getUNDEF(SrcVT));
10685 Opnds.push_back(In.getOperand(0));
10687 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, NVT, Opnds);
10688 AddToWorklist(BV.getNode());
10690 return DAG.getNode(Opcode, dl, VT, BV);
10693 SDValue DAGCombiner::visitBUILD_VECTOR(SDNode *N) {
10694 unsigned NumInScalars = N->getNumOperands();
10696 EVT VT = N->getValueType(0);
10698 // A vector built entirely of undefs is undef.
10699 if (ISD::allOperandsUndef(N))
10700 return DAG.getUNDEF(VT);
10702 SDValue V = reduceBuildVecExtToExtBuildVec(N);
10706 V = reduceBuildVecConvertToConvertBuildVec(N);
10710 // Check to see if this is a BUILD_VECTOR of a bunch of EXTRACT_VECTOR_ELT
10711 // operations. If so, and if the EXTRACT_VECTOR_ELT vector inputs come from
10712 // at most two distinct vectors, turn this into a shuffle node.
10714 // Only type-legal BUILD_VECTOR nodes are converted to shuffle nodes.
10715 if (!isTypeLegal(VT))
10718 // May only combine to shuffle after legalize if shuffle is legal.
10719 if (LegalOperations && !TLI.isOperationLegal(ISD::VECTOR_SHUFFLE, VT))
10722 SDValue VecIn1, VecIn2;
10723 bool UsesZeroVector = false;
10724 for (unsigned i = 0; i != NumInScalars; ++i) {
10725 SDValue Op = N->getOperand(i);
10726 // Ignore undef inputs.
10727 if (Op.getOpcode() == ISD::UNDEF) continue;
10729 // See if we can combine this build_vector into a blend with a zero vector.
10730 if (!VecIn2.getNode() && ((Op.getOpcode() == ISD::Constant &&
10731 cast<ConstantSDNode>(Op.getNode())->isNullValue()) ||
10732 (Op.getOpcode() == ISD::ConstantFP &&
10733 cast<ConstantFPSDNode>(Op.getNode())->getValueAPF().isZero()))) {
10734 UsesZeroVector = true;
10738 // If this input is something other than a EXTRACT_VECTOR_ELT with a
10739 // constant index, bail out.
10740 if (Op.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
10741 !isa<ConstantSDNode>(Op.getOperand(1))) {
10742 VecIn1 = VecIn2 = SDValue(nullptr, 0);
10746 // We allow up to two distinct input vectors.
10747 SDValue ExtractedFromVec = Op.getOperand(0);
10748 if (ExtractedFromVec == VecIn1 || ExtractedFromVec == VecIn2)
10751 if (!VecIn1.getNode()) {
10752 VecIn1 = ExtractedFromVec;
10753 } else if (!VecIn2.getNode() && !UsesZeroVector) {
10754 VecIn2 = ExtractedFromVec;
10756 // Too many inputs.
10757 VecIn1 = VecIn2 = SDValue(nullptr, 0);
10762 // If everything is good, we can make a shuffle operation.
10763 if (VecIn1.getNode()) {
10764 SmallVector<int, 8> Mask;
10765 for (unsigned i = 0; i != NumInScalars; ++i) {
10766 unsigned Opcode = N->getOperand(i).getOpcode();
10767 if (Opcode == ISD::UNDEF) {
10768 Mask.push_back(-1);
10772 // Operands can also be zero.
10773 if (Opcode != ISD::EXTRACT_VECTOR_ELT) {
10774 assert(UsesZeroVector &&
10775 (Opcode == ISD::Constant || Opcode == ISD::ConstantFP) &&
10776 "Unexpected node found!");
10777 Mask.push_back(NumInScalars+i);
10781 // If extracting from the first vector, just use the index directly.
10782 SDValue Extract = N->getOperand(i);
10783 SDValue ExtVal = Extract.getOperand(1);
10784 unsigned ExtIndex = cast<ConstantSDNode>(ExtVal)->getZExtValue();
10785 if (Extract.getOperand(0) == VecIn1) {
10786 Mask.push_back(ExtIndex);
10790 // Otherwise, use InIdx + VecSize
10791 Mask.push_back(NumInScalars+ExtIndex);
10794 // Avoid introducing illegal shuffles with zero.
10795 if (UsesZeroVector && !TLI.isVectorClearMaskLegal(Mask, VT))
10798 // We can't generate a shuffle node with mismatched input and output types.
10799 // Attempt to transform a single input vector to the correct type.
10800 if ((VT != VecIn1.getValueType())) {
10801 // We don't support shuffeling between TWO values of different types.
10802 if (VecIn2.getNode())
10805 // If the input vector type has a different base type to the output
10806 // vector type, bail out.
10807 if (VecIn1.getValueType().getVectorElementType() !=
10808 VT.getVectorElementType())
10811 // If the input vector is too small, widen it.
10812 // We only support widening of vectors which are half the size of the
10813 // output registers. For example XMM->YMM widening on X86 with AVX.
10814 EVT VecInT = VecIn1.getValueType();
10815 if (VecInT.getSizeInBits() * 2 == VT.getSizeInBits()) {
10816 // Widen the input vector by adding undef values.
10817 VecIn1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
10818 VecIn1, DAG.getUNDEF(VecIn1.getValueType()));
10819 } else if (VecInT.getSizeInBits() == VT.getSizeInBits() * 2) {
10820 // If the input vector is too large, try to split it.
10821 if (!TLI.isExtractSubvectorCheap(VT, VT.getVectorNumElements()))
10824 // Try to replace VecIn1 with two extract_subvectors
10825 // No need to update the masks, they should still be correct.
10826 VecIn2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, VecIn1,
10827 DAG.getConstant(VT.getVectorNumElements(), TLI.getVectorIdxTy()));
10828 VecIn1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, VecIn1,
10829 DAG.getConstant(0, TLI.getVectorIdxTy()));
10830 UsesZeroVector = false;
10835 if (UsesZeroVector)
10836 VecIn2 = VT.isInteger() ? DAG.getConstant(0, VT) :
10837 DAG.getConstantFP(0.0, VT);
10839 // If VecIn2 is unused then change it to undef.
10840 VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(VT);
10842 // Check that we were able to transform all incoming values to the same
10844 if (VecIn2.getValueType() != VecIn1.getValueType() ||
10845 VecIn1.getValueType() != VT)
10848 // Return the new VECTOR_SHUFFLE node.
10852 return DAG.getVectorShuffle(VT, dl, Ops[0], Ops[1], &Mask[0]);
10858 SDValue DAGCombiner::visitCONCAT_VECTORS(SDNode *N) {
10859 // TODO: Check to see if this is a CONCAT_VECTORS of a bunch of
10860 // EXTRACT_SUBVECTOR operations. If so, and if the EXTRACT_SUBVECTOR vector
10861 // inputs come from at most two distinct vectors, turn this into a shuffle
10864 // If we only have one input vector, we don't need to do any concatenation.
10865 if (N->getNumOperands() == 1)
10866 return N->getOperand(0);
10868 // Check if all of the operands are undefs.
10869 EVT VT = N->getValueType(0);
10870 if (ISD::allOperandsUndef(N))
10871 return DAG.getUNDEF(VT);
10873 // Optimize concat_vectors where one of the vectors is undef.
10874 if (N->getNumOperands() == 2 &&
10875 N->getOperand(1)->getOpcode() == ISD::UNDEF) {
10876 SDValue In = N->getOperand(0);
10877 assert(In.getValueType().isVector() && "Must concat vectors");
10879 // Transform: concat_vectors(scalar, undef) -> scalar_to_vector(sclr).
10880 if (In->getOpcode() == ISD::BITCAST &&
10881 !In->getOperand(0)->getValueType(0).isVector()) {
10882 SDValue Scalar = In->getOperand(0);
10883 EVT SclTy = Scalar->getValueType(0);
10885 if (!SclTy.isFloatingPoint() && !SclTy.isInteger())
10888 EVT NVT = EVT::getVectorVT(*DAG.getContext(), SclTy,
10889 VT.getSizeInBits() / SclTy.getSizeInBits());
10890 if (!TLI.isTypeLegal(NVT) || !TLI.isTypeLegal(Scalar.getValueType()))
10893 SDLoc dl = SDLoc(N);
10894 SDValue Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, NVT, Scalar);
10895 return DAG.getNode(ISD::BITCAST, dl, VT, Res);
10899 // fold (concat_vectors (BUILD_VECTOR A, B, ...), (BUILD_VECTOR C, D, ...))
10900 // -> (BUILD_VECTOR A, B, ..., C, D, ...)
10901 if (N->getNumOperands() == 2 &&
10902 N->getOperand(0).getOpcode() == ISD::BUILD_VECTOR &&
10903 N->getOperand(1).getOpcode() == ISD::BUILD_VECTOR) {
10904 EVT VT = N->getValueType(0);
10905 SDValue N0 = N->getOperand(0);
10906 SDValue N1 = N->getOperand(1);
10907 SmallVector<SDValue, 8> Opnds;
10908 unsigned BuildVecNumElts = N0.getNumOperands();
10910 EVT SclTy0 = N0.getOperand(0)->getValueType(0);
10911 EVT SclTy1 = N1.getOperand(0)->getValueType(0);
10912 if (SclTy0.isFloatingPoint()) {
10913 for (unsigned i = 0; i != BuildVecNumElts; ++i)
10914 Opnds.push_back(N0.getOperand(i));
10915 for (unsigned i = 0; i != BuildVecNumElts; ++i)
10916 Opnds.push_back(N1.getOperand(i));
10918 // If BUILD_VECTOR are from built from integer, they may have different
10919 // operand types. Get the smaller type and truncate all operands to it.
10920 EVT MinTy = SclTy0.bitsLE(SclTy1) ? SclTy0 : SclTy1;
10921 for (unsigned i = 0; i != BuildVecNumElts; ++i)
10922 Opnds.push_back(DAG.getNode(ISD::TRUNCATE, SDLoc(N), MinTy,
10923 N0.getOperand(i)));
10924 for (unsigned i = 0; i != BuildVecNumElts; ++i)
10925 Opnds.push_back(DAG.getNode(ISD::TRUNCATE, SDLoc(N), MinTy,
10926 N1.getOperand(i)));
10929 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, Opnds);
10932 // Type legalization of vectors and DAG canonicalization of SHUFFLE_VECTOR
10933 // nodes often generate nop CONCAT_VECTOR nodes.
10934 // Scan the CONCAT_VECTOR operands and look for a CONCAT operations that
10935 // place the incoming vectors at the exact same location.
10936 SDValue SingleSource = SDValue();
10937 unsigned PartNumElem = N->getOperand(0).getValueType().getVectorNumElements();
10939 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
10940 SDValue Op = N->getOperand(i);
10942 if (Op.getOpcode() == ISD::UNDEF)
10945 // Check if this is the identity extract:
10946 if (Op.getOpcode() != ISD::EXTRACT_SUBVECTOR)
10949 // Find the single incoming vector for the extract_subvector.
10950 if (SingleSource.getNode()) {
10951 if (Op.getOperand(0) != SingleSource)
10954 SingleSource = Op.getOperand(0);
10956 // Check the source type is the same as the type of the result.
10957 // If not, this concat may extend the vector, so we can not
10958 // optimize it away.
10959 if (SingleSource.getValueType() != N->getValueType(0))
10963 unsigned IdentityIndex = i * PartNumElem;
10964 ConstantSDNode *CS = dyn_cast<ConstantSDNode>(Op.getOperand(1));
10965 // The extract index must be constant.
10969 // Check that we are reading from the identity index.
10970 if (CS->getZExtValue() != IdentityIndex)
10974 if (SingleSource.getNode())
10975 return SingleSource;
10980 SDValue DAGCombiner::visitEXTRACT_SUBVECTOR(SDNode* N) {
10981 EVT NVT = N->getValueType(0);
10982 SDValue V = N->getOperand(0);
10984 if (V->getOpcode() == ISD::CONCAT_VECTORS) {
10986 // (extract_subvec (concat V1, V2, ...), i)
10989 // Only operand 0 is checked as 'concat' assumes all inputs of the same
10991 if (V->getOperand(0).getValueType() != NVT)
10993 unsigned Idx = dyn_cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
10994 unsigned NumElems = NVT.getVectorNumElements();
10995 assert((Idx % NumElems) == 0 &&
10996 "IDX in concat is not a multiple of the result vector length.");
10997 return V->getOperand(Idx / NumElems);
11001 if (V->getOpcode() == ISD::BITCAST)
11002 V = V.getOperand(0);
11004 if (V->getOpcode() == ISD::INSERT_SUBVECTOR) {
11006 // Handle only simple case where vector being inserted and vector
11007 // being extracted are of same type, and are half size of larger vectors.
11008 EVT BigVT = V->getOperand(0).getValueType();
11009 EVT SmallVT = V->getOperand(1).getValueType();
11010 if (!NVT.bitsEq(SmallVT) || NVT.getSizeInBits()*2 != BigVT.getSizeInBits())
11013 // Only handle cases where both indexes are constants with the same type.
11014 ConstantSDNode *ExtIdx = dyn_cast<ConstantSDNode>(N->getOperand(1));
11015 ConstantSDNode *InsIdx = dyn_cast<ConstantSDNode>(V->getOperand(2));
11017 if (InsIdx && ExtIdx &&
11018 InsIdx->getValueType(0).getSizeInBits() <= 64 &&
11019 ExtIdx->getValueType(0).getSizeInBits() <= 64) {
11021 // (extract_subvec (insert_subvec V1, V2, InsIdx), ExtIdx)
11023 // indices are equal or bit offsets are equal => V1
11024 // otherwise => (extract_subvec V1, ExtIdx)
11025 if (InsIdx->getZExtValue() * SmallVT.getScalarType().getSizeInBits() ==
11026 ExtIdx->getZExtValue() * NVT.getScalarType().getSizeInBits())
11027 return DAG.getNode(ISD::BITCAST, dl, NVT, V->getOperand(1));
11028 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, NVT,
11029 DAG.getNode(ISD::BITCAST, dl,
11030 N->getOperand(0).getValueType(),
11031 V->getOperand(0)), N->getOperand(1));
11038 static SDValue simplifyShuffleOperandRecursively(SmallBitVector &UsedElements,
11039 SDValue V, SelectionDAG &DAG) {
11041 EVT VT = V.getValueType();
11043 switch (V.getOpcode()) {
11047 case ISD::CONCAT_VECTORS: {
11048 EVT OpVT = V->getOperand(0).getValueType();
11049 int OpSize = OpVT.getVectorNumElements();
11050 SmallBitVector OpUsedElements(OpSize, false);
11051 bool FoundSimplification = false;
11052 SmallVector<SDValue, 4> NewOps;
11053 NewOps.reserve(V->getNumOperands());
11054 for (int i = 0, NumOps = V->getNumOperands(); i < NumOps; ++i) {
11055 SDValue Op = V->getOperand(i);
11056 bool OpUsed = false;
11057 for (int j = 0; j < OpSize; ++j)
11058 if (UsedElements[i * OpSize + j]) {
11059 OpUsedElements[j] = true;
11063 OpUsed ? simplifyShuffleOperandRecursively(OpUsedElements, Op, DAG)
11064 : DAG.getUNDEF(OpVT));
11065 FoundSimplification |= Op == NewOps.back();
11066 OpUsedElements.reset();
11068 if (FoundSimplification)
11069 V = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, NewOps);
11073 case ISD::INSERT_SUBVECTOR: {
11074 SDValue BaseV = V->getOperand(0);
11075 SDValue SubV = V->getOperand(1);
11076 auto *IdxN = dyn_cast<ConstantSDNode>(V->getOperand(2));
11080 int SubSize = SubV.getValueType().getVectorNumElements();
11081 int Idx = IdxN->getZExtValue();
11082 bool SubVectorUsed = false;
11083 SmallBitVector SubUsedElements(SubSize, false);
11084 for (int i = 0; i < SubSize; ++i)
11085 if (UsedElements[i + Idx]) {
11086 SubVectorUsed = true;
11087 SubUsedElements[i] = true;
11088 UsedElements[i + Idx] = false;
11091 // Now recurse on both the base and sub vectors.
11092 SDValue SimplifiedSubV =
11094 ? simplifyShuffleOperandRecursively(SubUsedElements, SubV, DAG)
11095 : DAG.getUNDEF(SubV.getValueType());
11096 SDValue SimplifiedBaseV = simplifyShuffleOperandRecursively(UsedElements, BaseV, DAG);
11097 if (SimplifiedSubV != SubV || SimplifiedBaseV != BaseV)
11098 V = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT,
11099 SimplifiedBaseV, SimplifiedSubV, V->getOperand(2));
11105 static SDValue simplifyShuffleOperands(ShuffleVectorSDNode *SVN, SDValue N0,
11106 SDValue N1, SelectionDAG &DAG) {
11107 EVT VT = SVN->getValueType(0);
11108 int NumElts = VT.getVectorNumElements();
11109 SmallBitVector N0UsedElements(NumElts, false), N1UsedElements(NumElts, false);
11110 for (int M : SVN->getMask())
11111 if (M >= 0 && M < NumElts)
11112 N0UsedElements[M] = true;
11113 else if (M >= NumElts)
11114 N1UsedElements[M - NumElts] = true;
11116 SDValue S0 = simplifyShuffleOperandRecursively(N0UsedElements, N0, DAG);
11117 SDValue S1 = simplifyShuffleOperandRecursively(N1UsedElements, N1, DAG);
11118 if (S0 == N0 && S1 == N1)
11121 return DAG.getVectorShuffle(VT, SDLoc(SVN), S0, S1, SVN->getMask());
11124 // Tries to turn a shuffle of two CONCAT_VECTORS into a single concat.
11125 static SDValue partitionShuffleOfConcats(SDNode *N, SelectionDAG &DAG) {
11126 EVT VT = N->getValueType(0);
11127 unsigned NumElts = VT.getVectorNumElements();
11129 SDValue N0 = N->getOperand(0);
11130 SDValue N1 = N->getOperand(1);
11131 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
11133 SmallVector<SDValue, 4> Ops;
11134 EVT ConcatVT = N0.getOperand(0).getValueType();
11135 unsigned NumElemsPerConcat = ConcatVT.getVectorNumElements();
11136 unsigned NumConcats = NumElts / NumElemsPerConcat;
11138 // Look at every vector that's inserted. We're looking for exact
11139 // subvector-sized copies from a concatenated vector
11140 for (unsigned I = 0; I != NumConcats; ++I) {
11141 // Make sure we're dealing with a copy.
11142 unsigned Begin = I * NumElemsPerConcat;
11143 bool AllUndef = true, NoUndef = true;
11144 for (unsigned J = Begin; J != Begin + NumElemsPerConcat; ++J) {
11145 if (SVN->getMaskElt(J) >= 0)
11152 if (SVN->getMaskElt(Begin) % NumElemsPerConcat != 0)
11155 for (unsigned J = 1; J != NumElemsPerConcat; ++J)
11156 if (SVN->getMaskElt(Begin + J - 1) + 1 != SVN->getMaskElt(Begin + J))
11159 unsigned FirstElt = SVN->getMaskElt(Begin) / NumElemsPerConcat;
11160 if (FirstElt < N0.getNumOperands())
11161 Ops.push_back(N0.getOperand(FirstElt));
11163 Ops.push_back(N1.getOperand(FirstElt - N0.getNumOperands()));
11165 } else if (AllUndef) {
11166 Ops.push_back(DAG.getUNDEF(N0.getOperand(0).getValueType()));
11167 } else { // Mixed with general masks and undefs, can't do optimization.
11172 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Ops);
11175 SDValue DAGCombiner::visitVECTOR_SHUFFLE(SDNode *N) {
11176 EVT VT = N->getValueType(0);
11177 unsigned NumElts = VT.getVectorNumElements();
11179 SDValue N0 = N->getOperand(0);
11180 SDValue N1 = N->getOperand(1);
11182 assert(N0.getValueType() == VT && "Vector shuffle must be normalized in DAG");
11184 // Canonicalize shuffle undef, undef -> undef
11185 if (N0.getOpcode() == ISD::UNDEF && N1.getOpcode() == ISD::UNDEF)
11186 return DAG.getUNDEF(VT);
11188 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
11190 // Canonicalize shuffle v, v -> v, undef
11192 SmallVector<int, 8> NewMask;
11193 for (unsigned i = 0; i != NumElts; ++i) {
11194 int Idx = SVN->getMaskElt(i);
11195 if (Idx >= (int)NumElts) Idx -= NumElts;
11196 NewMask.push_back(Idx);
11198 return DAG.getVectorShuffle(VT, SDLoc(N), N0, DAG.getUNDEF(VT),
11202 // Canonicalize shuffle undef, v -> v, undef. Commute the shuffle mask.
11203 if (N0.getOpcode() == ISD::UNDEF) {
11204 SmallVector<int, 8> NewMask;
11205 for (unsigned i = 0; i != NumElts; ++i) {
11206 int Idx = SVN->getMaskElt(i);
11208 if (Idx >= (int)NumElts)
11211 Idx = -1; // remove reference to lhs
11213 NewMask.push_back(Idx);
11215 return DAG.getVectorShuffle(VT, SDLoc(N), N1, DAG.getUNDEF(VT),
11219 // Remove references to rhs if it is undef
11220 if (N1.getOpcode() == ISD::UNDEF) {
11221 bool Changed = false;
11222 SmallVector<int, 8> NewMask;
11223 for (unsigned i = 0; i != NumElts; ++i) {
11224 int Idx = SVN->getMaskElt(i);
11225 if (Idx >= (int)NumElts) {
11229 NewMask.push_back(Idx);
11232 return DAG.getVectorShuffle(VT, SDLoc(N), N0, N1, &NewMask[0]);
11235 // If it is a splat, check if the argument vector is another splat or a
11236 // build_vector with all scalar elements the same.
11237 if (SVN->isSplat() && SVN->getSplatIndex() < (int)NumElts) {
11238 SDNode *V = N0.getNode();
11240 // If this is a bit convert that changes the element type of the vector but
11241 // not the number of vector elements, look through it. Be careful not to
11242 // look though conversions that change things like v4f32 to v2f64.
11243 if (V->getOpcode() == ISD::BITCAST) {
11244 SDValue ConvInput = V->getOperand(0);
11245 if (ConvInput.getValueType().isVector() &&
11246 ConvInput.getValueType().getVectorNumElements() == NumElts)
11247 V = ConvInput.getNode();
11250 if (V->getOpcode() == ISD::BUILD_VECTOR) {
11251 assert(V->getNumOperands() == NumElts &&
11252 "BUILD_VECTOR has wrong number of operands");
11254 bool AllSame = true;
11255 for (unsigned i = 0; i != NumElts; ++i) {
11256 if (V->getOperand(i).getOpcode() != ISD::UNDEF) {
11257 Base = V->getOperand(i);
11261 // Splat of <u, u, u, u>, return <u, u, u, u>
11262 if (!Base.getNode())
11264 for (unsigned i = 0; i != NumElts; ++i) {
11265 if (V->getOperand(i) != Base) {
11270 // Splat of <x, x, x, x>, return <x, x, x, x>
11276 // There are various patterns used to build up a vector from smaller vectors,
11277 // subvectors, or elements. Scan chains of these and replace unused insertions
11278 // or components with undef.
11279 if (SDValue S = simplifyShuffleOperands(SVN, N0, N1, DAG))
11282 if (N0.getOpcode() == ISD::CONCAT_VECTORS &&
11283 Level < AfterLegalizeVectorOps &&
11284 (N1.getOpcode() == ISD::UNDEF ||
11285 (N1.getOpcode() == ISD::CONCAT_VECTORS &&
11286 N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType()))) {
11287 SDValue V = partitionShuffleOfConcats(N, DAG);
11293 // Canonicalize shuffles according to rules:
11294 // shuffle(A, shuffle(A, B)) -> shuffle(shuffle(A,B), A)
11295 // shuffle(B, shuffle(A, B)) -> shuffle(shuffle(A,B), B)
11296 // shuffle(B, shuffle(A, Undef)) -> shuffle(shuffle(A, Undef), B)
11297 if (N1.getOpcode() == ISD::VECTOR_SHUFFLE &&
11298 N0.getOpcode() != ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG &&
11299 TLI.isTypeLegal(VT)) {
11300 // The incoming shuffle must be of the same type as the result of the
11301 // current shuffle.
11302 assert(N1->getOperand(0).getValueType() == VT &&
11303 "Shuffle types don't match");
11305 SDValue SV0 = N1->getOperand(0);
11306 SDValue SV1 = N1->getOperand(1);
11307 bool HasSameOp0 = N0 == SV0;
11308 bool IsSV1Undef = SV1.getOpcode() == ISD::UNDEF;
11309 if (HasSameOp0 || IsSV1Undef || N0 == SV1)
11310 // Commute the operands of this shuffle so that next rule
11312 return DAG.getCommutedVectorShuffle(*SVN);
11315 // Try to fold according to rules:
11316 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, B, M2)
11317 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, C, M2)
11318 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(B, C, M2)
11319 // Don't try to fold shuffles with illegal type.
11320 if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG &&
11321 TLI.isTypeLegal(VT)) {
11322 ShuffleVectorSDNode *OtherSV = cast<ShuffleVectorSDNode>(N0);
11324 // The incoming shuffle must be of the same type as the result of the
11325 // current shuffle.
11326 assert(OtherSV->getOperand(0).getValueType() == VT &&
11327 "Shuffle types don't match");
11330 SmallVector<int, 4> Mask;
11331 // Compute the combined shuffle mask for a shuffle with SV0 as the first
11332 // operand, and SV1 as the second operand.
11333 for (unsigned i = 0; i != NumElts; ++i) {
11334 int Idx = SVN->getMaskElt(i);
11336 // Propagate Undef.
11337 Mask.push_back(Idx);
11341 SDValue CurrentVec;
11342 if (Idx < (int)NumElts) {
11343 // This shuffle index refers to the inner shuffle N0. Lookup the inner
11344 // shuffle mask to identify which vector is actually referenced.
11345 Idx = OtherSV->getMaskElt(Idx);
11347 // Propagate Undef.
11348 Mask.push_back(Idx);
11352 CurrentVec = (Idx < (int) NumElts) ? OtherSV->getOperand(0)
11353 : OtherSV->getOperand(1);
11355 // This shuffle index references an element within N1.
11359 // Simple case where 'CurrentVec' is UNDEF.
11360 if (CurrentVec.getOpcode() == ISD::UNDEF) {
11361 Mask.push_back(-1);
11365 // Canonicalize the shuffle index. We don't know yet if CurrentVec
11366 // will be the first or second operand of the combined shuffle.
11367 Idx = Idx % NumElts;
11368 if (!SV0.getNode() || SV0 == CurrentVec) {
11369 // Ok. CurrentVec is the left hand side.
11370 // Update the mask accordingly.
11372 Mask.push_back(Idx);
11376 // Bail out if we cannot convert the shuffle pair into a single shuffle.
11377 if (SV1.getNode() && SV1 != CurrentVec)
11380 // Ok. CurrentVec is the right hand side.
11381 // Update the mask accordingly.
11383 Mask.push_back(Idx + NumElts);
11386 // Check if all indices in Mask are Undef. In case, propagate Undef.
11387 bool isUndefMask = true;
11388 for (unsigned i = 0; i != NumElts && isUndefMask; ++i)
11389 isUndefMask &= Mask[i] < 0;
11392 return DAG.getUNDEF(VT);
11394 if (!SV0.getNode())
11395 SV0 = DAG.getUNDEF(VT);
11396 if (!SV1.getNode())
11397 SV1 = DAG.getUNDEF(VT);
11399 // Avoid introducing shuffles with illegal mask.
11400 if (!TLI.isShuffleMaskLegal(Mask, VT)) {
11401 // Compute the commuted shuffle mask and test again.
11402 for (unsigned i = 0; i != NumElts; ++i) {
11406 else if (idx < (int)NumElts)
11407 Mask[i] = idx + NumElts;
11409 Mask[i] = idx - NumElts;
11412 if (!TLI.isShuffleMaskLegal(Mask, VT))
11415 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(B, A, M2)
11416 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(C, A, M2)
11417 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(C, B, M2)
11418 std::swap(SV0, SV1);
11421 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, B, M2)
11422 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, C, M2)
11423 // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(B, C, M2)
11424 return DAG.getVectorShuffle(VT, SDLoc(N), SV0, SV1, &Mask[0]);
11430 SDValue DAGCombiner::visitINSERT_SUBVECTOR(SDNode *N) {
11431 SDValue N0 = N->getOperand(0);
11432 SDValue N2 = N->getOperand(2);
11434 // If the input vector is a concatenation, and the insert replaces
11435 // one of the halves, we can optimize into a single concat_vectors.
11436 if (N0.getOpcode() == ISD::CONCAT_VECTORS &&
11437 N0->getNumOperands() == 2 && N2.getOpcode() == ISD::Constant) {
11438 APInt InsIdx = cast<ConstantSDNode>(N2)->getAPIntValue();
11439 EVT VT = N->getValueType(0);
11441 // Lower half: fold (insert_subvector (concat_vectors X, Y), Z) ->
11442 // (concat_vectors Z, Y)
11444 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
11445 N->getOperand(1), N0.getOperand(1));
11447 // Upper half: fold (insert_subvector (concat_vectors X, Y), Z) ->
11448 // (concat_vectors X, Z)
11449 if (InsIdx == VT.getVectorNumElements()/2)
11450 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
11451 N0.getOperand(0), N->getOperand(1));
11457 /// Returns a vector_shuffle if it able to transform an AND to a vector_shuffle
11458 /// with the destination vector and a zero vector.
11459 /// e.g. AND V, <0xffffffff, 0, 0xffffffff, 0>. ==>
11460 /// vector_shuffle V, Zero, <0, 4, 2, 4>
11461 SDValue DAGCombiner::XformToShuffleWithZero(SDNode *N) {
11462 EVT VT = N->getValueType(0);
11464 SDValue LHS = N->getOperand(0);
11465 SDValue RHS = N->getOperand(1);
11466 if (N->getOpcode() == ISD::AND) {
11467 if (RHS.getOpcode() == ISD::BITCAST)
11468 RHS = RHS.getOperand(0);
11469 if (RHS.getOpcode() == ISD::BUILD_VECTOR) {
11470 SmallVector<int, 8> Indices;
11471 unsigned NumElts = RHS.getNumOperands();
11472 for (unsigned i = 0; i != NumElts; ++i) {
11473 SDValue Elt = RHS.getOperand(i);
11474 if (!isa<ConstantSDNode>(Elt))
11477 if (cast<ConstantSDNode>(Elt)->isAllOnesValue())
11478 Indices.push_back(i);
11479 else if (cast<ConstantSDNode>(Elt)->isNullValue())
11480 Indices.push_back(NumElts+i);
11485 // Let's see if the target supports this vector_shuffle.
11486 EVT RVT = RHS.getValueType();
11487 if (!TLI.isVectorClearMaskLegal(Indices, RVT))
11490 // Return the new VECTOR_SHUFFLE node.
11491 EVT EltVT = RVT.getVectorElementType();
11492 SmallVector<SDValue,8> ZeroOps(RVT.getVectorNumElements(),
11493 DAG.getConstant(0, EltVT));
11494 SDValue Zero = DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), RVT, ZeroOps);
11495 LHS = DAG.getNode(ISD::BITCAST, dl, RVT, LHS);
11496 SDValue Shuf = DAG.getVectorShuffle(RVT, dl, LHS, Zero, &Indices[0]);
11497 return DAG.getNode(ISD::BITCAST, dl, VT, Shuf);
11504 /// Visit a binary vector operation, like ADD.
11505 SDValue DAGCombiner::SimplifyVBinOp(SDNode *N) {
11506 assert(N->getValueType(0).isVector() &&
11507 "SimplifyVBinOp only works on vectors!");
11509 SDValue LHS = N->getOperand(0);
11510 SDValue RHS = N->getOperand(1);
11511 SDValue Shuffle = XformToShuffleWithZero(N);
11512 if (Shuffle.getNode()) return Shuffle;
11514 // If the LHS and RHS are BUILD_VECTOR nodes, see if we can constant fold
11516 if (LHS.getOpcode() == ISD::BUILD_VECTOR &&
11517 RHS.getOpcode() == ISD::BUILD_VECTOR) {
11518 // Check if both vectors are constants. If not bail out.
11519 if (!(cast<BuildVectorSDNode>(LHS)->isConstant() &&
11520 cast<BuildVectorSDNode>(RHS)->isConstant()))
11523 SmallVector<SDValue, 8> Ops;
11524 for (unsigned i = 0, e = LHS.getNumOperands(); i != e; ++i) {
11525 SDValue LHSOp = LHS.getOperand(i);
11526 SDValue RHSOp = RHS.getOperand(i);
11528 // Can't fold divide by zero.
11529 if (N->getOpcode() == ISD::SDIV || N->getOpcode() == ISD::UDIV ||
11530 N->getOpcode() == ISD::FDIV) {
11531 if ((RHSOp.getOpcode() == ISD::Constant &&
11532 cast<ConstantSDNode>(RHSOp.getNode())->isNullValue()) ||
11533 (RHSOp.getOpcode() == ISD::ConstantFP &&
11534 cast<ConstantFPSDNode>(RHSOp.getNode())->getValueAPF().isZero()))
11538 EVT VT = LHSOp.getValueType();
11539 EVT RVT = RHSOp.getValueType();
11541 // Integer BUILD_VECTOR operands may have types larger than the element
11542 // size (e.g., when the element type is not legal). Prior to type
11543 // legalization, the types may not match between the two BUILD_VECTORS.
11544 // Truncate one of the operands to make them match.
11545 if (RVT.getSizeInBits() > VT.getSizeInBits()) {
11546 RHSOp = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, RHSOp);
11548 LHSOp = DAG.getNode(ISD::TRUNCATE, SDLoc(N), RVT, LHSOp);
11552 SDValue FoldOp = DAG.getNode(N->getOpcode(), SDLoc(LHS), VT,
11554 if (FoldOp.getOpcode() != ISD::UNDEF &&
11555 FoldOp.getOpcode() != ISD::Constant &&
11556 FoldOp.getOpcode() != ISD::ConstantFP)
11558 Ops.push_back(FoldOp);
11559 AddToWorklist(FoldOp.getNode());
11562 if (Ops.size() == LHS.getNumOperands())
11563 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), LHS.getValueType(), Ops);
11566 // Type legalization might introduce new shuffles in the DAG.
11567 // Fold (VBinOp (shuffle (A, Undef, Mask)), (shuffle (B, Undef, Mask)))
11568 // -> (shuffle (VBinOp (A, B)), Undef, Mask).
11569 if (LegalTypes && isa<ShuffleVectorSDNode>(LHS) &&
11570 isa<ShuffleVectorSDNode>(RHS) && LHS.hasOneUse() && RHS.hasOneUse() &&
11571 LHS.getOperand(1).getOpcode() == ISD::UNDEF &&
11572 RHS.getOperand(1).getOpcode() == ISD::UNDEF) {
11573 ShuffleVectorSDNode *SVN0 = cast<ShuffleVectorSDNode>(LHS);
11574 ShuffleVectorSDNode *SVN1 = cast<ShuffleVectorSDNode>(RHS);
11576 if (SVN0->getMask().equals(SVN1->getMask())) {
11577 EVT VT = N->getValueType(0);
11578 SDValue UndefVector = LHS.getOperand(1);
11579 SDValue NewBinOp = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
11580 LHS.getOperand(0), RHS.getOperand(0));
11581 AddUsersToWorklist(N);
11582 return DAG.getVectorShuffle(VT, SDLoc(N), NewBinOp, UndefVector,
11583 &SVN0->getMask()[0]);
11590 /// Visit a binary vector operation, like FABS/FNEG.
11591 SDValue DAGCombiner::SimplifyVUnaryOp(SDNode *N) {
11592 assert(N->getValueType(0).isVector() &&
11593 "SimplifyVUnaryOp only works on vectors!");
11595 SDValue N0 = N->getOperand(0);
11597 if (N0.getOpcode() != ISD::BUILD_VECTOR)
11600 // Operand is a BUILD_VECTOR node, see if we can constant fold it.
11601 SmallVector<SDValue, 8> Ops;
11602 for (unsigned i = 0, e = N0.getNumOperands(); i != e; ++i) {
11603 SDValue Op = N0.getOperand(i);
11604 if (Op.getOpcode() != ISD::UNDEF &&
11605 Op.getOpcode() != ISD::ConstantFP)
11607 EVT EltVT = Op.getValueType();
11608 SDValue FoldOp = DAG.getNode(N->getOpcode(), SDLoc(N0), EltVT, Op);
11609 if (FoldOp.getOpcode() != ISD::UNDEF &&
11610 FoldOp.getOpcode() != ISD::ConstantFP)
11612 Ops.push_back(FoldOp);
11613 AddToWorklist(FoldOp.getNode());
11616 if (Ops.size() != N0.getNumOperands())
11619 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), N0.getValueType(), Ops);
11622 SDValue DAGCombiner::SimplifySelect(SDLoc DL, SDValue N0,
11623 SDValue N1, SDValue N2){
11624 assert(N0.getOpcode() ==ISD::SETCC && "First argument must be a SetCC node!");
11626 SDValue SCC = SimplifySelectCC(DL, N0.getOperand(0), N0.getOperand(1), N1, N2,
11627 cast<CondCodeSDNode>(N0.getOperand(2))->get());
11629 // If we got a simplified select_cc node back from SimplifySelectCC, then
11630 // break it down into a new SETCC node, and a new SELECT node, and then return
11631 // the SELECT node, since we were called with a SELECT node.
11632 if (SCC.getNode()) {
11633 // Check to see if we got a select_cc back (to turn into setcc/select).
11634 // Otherwise, just return whatever node we got back, like fabs.
11635 if (SCC.getOpcode() == ISD::SELECT_CC) {
11636 SDValue SETCC = DAG.getNode(ISD::SETCC, SDLoc(N0),
11638 SCC.getOperand(0), SCC.getOperand(1),
11639 SCC.getOperand(4));
11640 AddToWorklist(SETCC.getNode());
11641 return DAG.getSelect(SDLoc(SCC), SCC.getValueType(), SETCC,
11642 SCC.getOperand(2), SCC.getOperand(3));
11650 /// Given a SELECT or a SELECT_CC node, where LHS and RHS are the two values
11651 /// being selected between, see if we can simplify the select. Callers of this
11652 /// should assume that TheSelect is deleted if this returns true. As such, they
11653 /// should return the appropriate thing (e.g. the node) back to the top-level of
11654 /// the DAG combiner loop to avoid it being looked at.
11655 bool DAGCombiner::SimplifySelectOps(SDNode *TheSelect, SDValue LHS,
11658 // Cannot simplify select with vector condition
11659 if (TheSelect->getOperand(0).getValueType().isVector()) return false;
11661 // If this is a select from two identical things, try to pull the operation
11662 // through the select.
11663 if (LHS.getOpcode() != RHS.getOpcode() ||
11664 !LHS.hasOneUse() || !RHS.hasOneUse())
11667 // If this is a load and the token chain is identical, replace the select
11668 // of two loads with a load through a select of the address to load from.
11669 // This triggers in things like "select bool X, 10.0, 123.0" after the FP
11670 // constants have been dropped into the constant pool.
11671 if (LHS.getOpcode() == ISD::LOAD) {
11672 LoadSDNode *LLD = cast<LoadSDNode>(LHS);
11673 LoadSDNode *RLD = cast<LoadSDNode>(RHS);
11675 // Token chains must be identical.
11676 if (LHS.getOperand(0) != RHS.getOperand(0) ||
11677 // Do not let this transformation reduce the number of volatile loads.
11678 LLD->isVolatile() || RLD->isVolatile() ||
11679 // If this is an EXTLOAD, the VT's must match.
11680 LLD->getMemoryVT() != RLD->getMemoryVT() ||
11681 // If this is an EXTLOAD, the kind of extension must match.
11682 (LLD->getExtensionType() != RLD->getExtensionType() &&
11683 // The only exception is if one of the extensions is anyext.
11684 LLD->getExtensionType() != ISD::EXTLOAD &&
11685 RLD->getExtensionType() != ISD::EXTLOAD) ||
11686 // FIXME: this discards src value information. This is
11687 // over-conservative. It would be beneficial to be able to remember
11688 // both potential memory locations. Since we are discarding
11689 // src value info, don't do the transformation if the memory
11690 // locations are not in the default address space.
11691 LLD->getPointerInfo().getAddrSpace() != 0 ||
11692 RLD->getPointerInfo().getAddrSpace() != 0 ||
11693 !TLI.isOperationLegalOrCustom(TheSelect->getOpcode(),
11694 LLD->getBasePtr().getValueType()))
11697 // Check that the select condition doesn't reach either load. If so,
11698 // folding this will induce a cycle into the DAG. If not, this is safe to
11699 // xform, so create a select of the addresses.
11701 if (TheSelect->getOpcode() == ISD::SELECT) {
11702 SDNode *CondNode = TheSelect->getOperand(0).getNode();
11703 if ((LLD->hasAnyUseOfValue(1) && LLD->isPredecessorOf(CondNode)) ||
11704 (RLD->hasAnyUseOfValue(1) && RLD->isPredecessorOf(CondNode)))
11706 // The loads must not depend on one another.
11707 if (LLD->isPredecessorOf(RLD) ||
11708 RLD->isPredecessorOf(LLD))
11710 Addr = DAG.getSelect(SDLoc(TheSelect),
11711 LLD->getBasePtr().getValueType(),
11712 TheSelect->getOperand(0), LLD->getBasePtr(),
11713 RLD->getBasePtr());
11714 } else { // Otherwise SELECT_CC
11715 SDNode *CondLHS = TheSelect->getOperand(0).getNode();
11716 SDNode *CondRHS = TheSelect->getOperand(1).getNode();
11718 if ((LLD->hasAnyUseOfValue(1) &&
11719 (LLD->isPredecessorOf(CondLHS) || LLD->isPredecessorOf(CondRHS))) ||
11720 (RLD->hasAnyUseOfValue(1) &&
11721 (RLD->isPredecessorOf(CondLHS) || RLD->isPredecessorOf(CondRHS))))
11724 Addr = DAG.getNode(ISD::SELECT_CC, SDLoc(TheSelect),
11725 LLD->getBasePtr().getValueType(),
11726 TheSelect->getOperand(0),
11727 TheSelect->getOperand(1),
11728 LLD->getBasePtr(), RLD->getBasePtr(),
11729 TheSelect->getOperand(4));
11733 // It is safe to replace the two loads if they have different alignments,
11734 // but the new load must be the minimum (most restrictive) alignment of the
11736 bool isInvariant = LLD->isInvariant() & RLD->isInvariant();
11737 unsigned Alignment = std::min(LLD->getAlignment(), RLD->getAlignment());
11738 if (LLD->getExtensionType() == ISD::NON_EXTLOAD) {
11739 Load = DAG.getLoad(TheSelect->getValueType(0),
11741 // FIXME: Discards pointer and AA info.
11742 LLD->getChain(), Addr, MachinePointerInfo(),
11743 LLD->isVolatile(), LLD->isNonTemporal(),
11744 isInvariant, Alignment);
11746 Load = DAG.getExtLoad(LLD->getExtensionType() == ISD::EXTLOAD ?
11747 RLD->getExtensionType() : LLD->getExtensionType(),
11749 TheSelect->getValueType(0),
11750 // FIXME: Discards pointer and AA info.
11751 LLD->getChain(), Addr, MachinePointerInfo(),
11752 LLD->getMemoryVT(), LLD->isVolatile(),
11753 LLD->isNonTemporal(), isInvariant, Alignment);
11756 // Users of the select now use the result of the load.
11757 CombineTo(TheSelect, Load);
11759 // Users of the old loads now use the new load's chain. We know the
11760 // old-load value is dead now.
11761 CombineTo(LHS.getNode(), Load.getValue(0), Load.getValue(1));
11762 CombineTo(RHS.getNode(), Load.getValue(0), Load.getValue(1));
11769 /// Simplify an expression of the form (N0 cond N1) ? N2 : N3
11770 /// where 'cond' is the comparison specified by CC.
11771 SDValue DAGCombiner::SimplifySelectCC(SDLoc DL, SDValue N0, SDValue N1,
11772 SDValue N2, SDValue N3,
11773 ISD::CondCode CC, bool NotExtCompare) {
11774 // (x ? y : y) -> y.
11775 if (N2 == N3) return N2;
11777 EVT VT = N2.getValueType();
11778 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
11779 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2.getNode());
11780 ConstantSDNode *N3C = dyn_cast<ConstantSDNode>(N3.getNode());
11782 // Determine if the condition we're dealing with is constant
11783 SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()),
11784 N0, N1, CC, DL, false);
11785 if (SCC.getNode()) AddToWorklist(SCC.getNode());
11786 ConstantSDNode *SCCC = dyn_cast_or_null<ConstantSDNode>(SCC.getNode());
11788 // fold select_cc true, x, y -> x
11789 if (SCCC && !SCCC->isNullValue())
11791 // fold select_cc false, x, y -> y
11792 if (SCCC && SCCC->isNullValue())
11795 // Check to see if we can simplify the select into an fabs node
11796 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N1)) {
11797 // Allow either -0.0 or 0.0
11798 if (CFP->getValueAPF().isZero()) {
11799 // select (setg[te] X, +/-0.0), X, fneg(X) -> fabs
11800 if ((CC == ISD::SETGE || CC == ISD::SETGT) &&
11801 N0 == N2 && N3.getOpcode() == ISD::FNEG &&
11802 N2 == N3.getOperand(0))
11803 return DAG.getNode(ISD::FABS, DL, VT, N0);
11805 // select (setl[te] X, +/-0.0), fneg(X), X -> fabs
11806 if ((CC == ISD::SETLT || CC == ISD::SETLE) &&
11807 N0 == N3 && N2.getOpcode() == ISD::FNEG &&
11808 N2.getOperand(0) == N3)
11809 return DAG.getNode(ISD::FABS, DL, VT, N3);
11813 // Turn "(a cond b) ? 1.0f : 2.0f" into "load (tmp + ((a cond b) ? 0 : 4)"
11814 // where "tmp" is a constant pool entry containing an array with 1.0 and 2.0
11815 // in it. This is a win when the constant is not otherwise available because
11816 // it replaces two constant pool loads with one. We only do this if the FP
11817 // type is known to be legal, because if it isn't, then we are before legalize
11818 // types an we want the other legalization to happen first (e.g. to avoid
11819 // messing with soft float) and if the ConstantFP is not legal, because if
11820 // it is legal, we may not need to store the FP constant in a constant pool.
11821 if (ConstantFPSDNode *TV = dyn_cast<ConstantFPSDNode>(N2))
11822 if (ConstantFPSDNode *FV = dyn_cast<ConstantFPSDNode>(N3)) {
11823 if (TLI.isTypeLegal(N2.getValueType()) &&
11824 (TLI.getOperationAction(ISD::ConstantFP, N2.getValueType()) !=
11825 TargetLowering::Legal &&
11826 !TLI.isFPImmLegal(TV->getValueAPF(), TV->getValueType(0)) &&
11827 !TLI.isFPImmLegal(FV->getValueAPF(), FV->getValueType(0))) &&
11828 // If both constants have multiple uses, then we won't need to do an
11829 // extra load, they are likely around in registers for other users.
11830 (TV->hasOneUse() || FV->hasOneUse())) {
11831 Constant *Elts[] = {
11832 const_cast<ConstantFP*>(FV->getConstantFPValue()),
11833 const_cast<ConstantFP*>(TV->getConstantFPValue())
11835 Type *FPTy = Elts[0]->getType();
11836 const DataLayout &TD = *TLI.getDataLayout();
11838 // Create a ConstantArray of the two constants.
11839 Constant *CA = ConstantArray::get(ArrayType::get(FPTy, 2), Elts);
11840 SDValue CPIdx = DAG.getConstantPool(CA, TLI.getPointerTy(),
11841 TD.getPrefTypeAlignment(FPTy));
11842 unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
11844 // Get the offsets to the 0 and 1 element of the array so that we can
11845 // select between them.
11846 SDValue Zero = DAG.getIntPtrConstant(0);
11847 unsigned EltSize = (unsigned)TD.getTypeAllocSize(Elts[0]->getType());
11848 SDValue One = DAG.getIntPtrConstant(EltSize);
11850 SDValue Cond = DAG.getSetCC(DL,
11851 getSetCCResultType(N0.getValueType()),
11853 AddToWorklist(Cond.getNode());
11854 SDValue CstOffset = DAG.getSelect(DL, Zero.getValueType(),
11856 AddToWorklist(CstOffset.getNode());
11857 CPIdx = DAG.getNode(ISD::ADD, DL, CPIdx.getValueType(), CPIdx,
11859 AddToWorklist(CPIdx.getNode());
11860 return DAG.getLoad(TV->getValueType(0), DL, DAG.getEntryNode(), CPIdx,
11861 MachinePointerInfo::getConstantPool(), false,
11862 false, false, Alignment);
11867 // Check to see if we can perform the "gzip trick", transforming
11868 // (select_cc setlt X, 0, A, 0) -> (and (sra X, (sub size(X), 1), A)
11869 if (N1C && N3C && N3C->isNullValue() && CC == ISD::SETLT &&
11870 (N1C->isNullValue() || // (a < 0) ? b : 0
11871 (N1C->getAPIntValue() == 1 && N0 == N2))) { // (a < 1) ? a : 0
11872 EVT XType = N0.getValueType();
11873 EVT AType = N2.getValueType();
11874 if (XType.bitsGE(AType)) {
11875 // and (sra X, size(X)-1, A) -> "and (srl X, C2), A" iff A is a
11876 // single-bit constant.
11877 if (N2C && ((N2C->getAPIntValue() & (N2C->getAPIntValue()-1)) == 0)) {
11878 unsigned ShCtV = N2C->getAPIntValue().logBase2();
11879 ShCtV = XType.getSizeInBits()-ShCtV-1;
11880 SDValue ShCt = DAG.getConstant(ShCtV,
11881 getShiftAmountTy(N0.getValueType()));
11882 SDValue Shift = DAG.getNode(ISD::SRL, SDLoc(N0),
11884 AddToWorklist(Shift.getNode());
11886 if (XType.bitsGT(AType)) {
11887 Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift);
11888 AddToWorklist(Shift.getNode());
11891 return DAG.getNode(ISD::AND, DL, AType, Shift, N2);
11894 SDValue Shift = DAG.getNode(ISD::SRA, SDLoc(N0),
11896 DAG.getConstant(XType.getSizeInBits()-1,
11897 getShiftAmountTy(N0.getValueType())));
11898 AddToWorklist(Shift.getNode());
11900 if (XType.bitsGT(AType)) {
11901 Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift);
11902 AddToWorklist(Shift.getNode());
11905 return DAG.getNode(ISD::AND, DL, AType, Shift, N2);
11909 // fold (select_cc seteq (and x, y), 0, 0, A) -> (and (shr (shl x)) A)
11910 // where y is has a single bit set.
11911 // A plaintext description would be, we can turn the SELECT_CC into an AND
11912 // when the condition can be materialized as an all-ones register. Any
11913 // single bit-test can be materialized as an all-ones register with
11914 // shift-left and shift-right-arith.
11915 if (CC == ISD::SETEQ && N0->getOpcode() == ISD::AND &&
11916 N0->getValueType(0) == VT &&
11917 N1C && N1C->isNullValue() &&
11918 N2C && N2C->isNullValue()) {
11919 SDValue AndLHS = N0->getOperand(0);
11920 ConstantSDNode *ConstAndRHS = dyn_cast<ConstantSDNode>(N0->getOperand(1));
11921 if (ConstAndRHS && ConstAndRHS->getAPIntValue().countPopulation() == 1) {
11922 // Shift the tested bit over the sign bit.
11923 APInt AndMask = ConstAndRHS->getAPIntValue();
11925 DAG.getConstant(AndMask.countLeadingZeros(),
11926 getShiftAmountTy(AndLHS.getValueType()));
11927 SDValue Shl = DAG.getNode(ISD::SHL, SDLoc(N0), VT, AndLHS, ShlAmt);
11929 // Now arithmetic right shift it all the way over, so the result is either
11930 // all-ones, or zero.
11932 DAG.getConstant(AndMask.getBitWidth()-1,
11933 getShiftAmountTy(Shl.getValueType()));
11934 SDValue Shr = DAG.getNode(ISD::SRA, SDLoc(N0), VT, Shl, ShrAmt);
11936 return DAG.getNode(ISD::AND, DL, VT, Shr, N3);
11940 // fold select C, 16, 0 -> shl C, 4
11941 if (N2C && N3C && N3C->isNullValue() && N2C->getAPIntValue().isPowerOf2() &&
11942 TLI.getBooleanContents(N0.getValueType()) ==
11943 TargetLowering::ZeroOrOneBooleanContent) {
11945 // If the caller doesn't want us to simplify this into a zext of a compare,
11947 if (NotExtCompare && N2C->getAPIntValue() == 1)
11950 // Get a SetCC of the condition
11951 // NOTE: Don't create a SETCC if it's not legal on this target.
11952 if (!LegalOperations ||
11953 TLI.isOperationLegal(ISD::SETCC,
11954 LegalTypes ? getSetCCResultType(N0.getValueType()) : MVT::i1)) {
11956 // cast from setcc result type to select result type
11958 SCC = DAG.getSetCC(DL, getSetCCResultType(N0.getValueType()),
11960 if (N2.getValueType().bitsLT(SCC.getValueType()))
11961 Temp = DAG.getZeroExtendInReg(SCC, SDLoc(N2),
11962 N2.getValueType());
11964 Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2),
11965 N2.getValueType(), SCC);
11967 SCC = DAG.getSetCC(SDLoc(N0), MVT::i1, N0, N1, CC);
11968 Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2),
11969 N2.getValueType(), SCC);
11972 AddToWorklist(SCC.getNode());
11973 AddToWorklist(Temp.getNode());
11975 if (N2C->getAPIntValue() == 1)
11978 // shl setcc result by log2 n2c
11979 return DAG.getNode(
11980 ISD::SHL, DL, N2.getValueType(), Temp,
11981 DAG.getConstant(N2C->getAPIntValue().logBase2(),
11982 getShiftAmountTy(Temp.getValueType())));
11986 // Check to see if this is the equivalent of setcc
11987 // FIXME: Turn all of these into setcc if setcc if setcc is legal
11988 // otherwise, go ahead with the folds.
11989 if (0 && N3C && N3C->isNullValue() && N2C && (N2C->getAPIntValue() == 1ULL)) {
11990 EVT XType = N0.getValueType();
11991 if (!LegalOperations ||
11992 TLI.isOperationLegal(ISD::SETCC, getSetCCResultType(XType))) {
11993 SDValue Res = DAG.getSetCC(DL, getSetCCResultType(XType), N0, N1, CC);
11994 if (Res.getValueType() != VT)
11995 Res = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, Res);
11999 // fold (seteq X, 0) -> (srl (ctlz X, log2(size(X))))
12000 if (N1C && N1C->isNullValue() && CC == ISD::SETEQ &&
12001 (!LegalOperations ||
12002 TLI.isOperationLegal(ISD::CTLZ, XType))) {
12003 SDValue Ctlz = DAG.getNode(ISD::CTLZ, SDLoc(N0), XType, N0);
12004 return DAG.getNode(ISD::SRL, DL, XType, Ctlz,
12005 DAG.getConstant(Log2_32(XType.getSizeInBits()),
12006 getShiftAmountTy(Ctlz.getValueType())));
12008 // fold (setgt X, 0) -> (srl (and (-X, ~X), size(X)-1))
12009 if (N1C && N1C->isNullValue() && CC == ISD::SETGT) {
12010 SDValue NegN0 = DAG.getNode(ISD::SUB, SDLoc(N0),
12011 XType, DAG.getConstant(0, XType), N0);
12012 SDValue NotN0 = DAG.getNOT(SDLoc(N0), N0, XType);
12013 return DAG.getNode(ISD::SRL, DL, XType,
12014 DAG.getNode(ISD::AND, DL, XType, NegN0, NotN0),
12015 DAG.getConstant(XType.getSizeInBits()-1,
12016 getShiftAmountTy(XType)));
12018 // fold (setgt X, -1) -> (xor (srl (X, size(X)-1), 1))
12019 if (N1C && N1C->isAllOnesValue() && CC == ISD::SETGT) {
12020 SDValue Sign = DAG.getNode(ISD::SRL, SDLoc(N0), XType, N0,
12021 DAG.getConstant(XType.getSizeInBits()-1,
12022 getShiftAmountTy(N0.getValueType())));
12023 return DAG.getNode(ISD::XOR, DL, XType, Sign, DAG.getConstant(1, XType));
12027 // Check to see if this is an integer abs.
12028 // select_cc setg[te] X, 0, X, -X ->
12029 // select_cc setgt X, -1, X, -X ->
12030 // select_cc setl[te] X, 0, -X, X ->
12031 // select_cc setlt X, 1, -X, X ->
12032 // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
12034 ConstantSDNode *SubC = nullptr;
12035 if (((N1C->isNullValue() && (CC == ISD::SETGT || CC == ISD::SETGE)) ||
12036 (N1C->isAllOnesValue() && CC == ISD::SETGT)) &&
12037 N0 == N2 && N3.getOpcode() == ISD::SUB && N0 == N3.getOperand(1))
12038 SubC = dyn_cast<ConstantSDNode>(N3.getOperand(0));
12039 else if (((N1C->isNullValue() && (CC == ISD::SETLT || CC == ISD::SETLE)) ||
12040 (N1C->isOne() && CC == ISD::SETLT)) &&
12041 N0 == N3 && N2.getOpcode() == ISD::SUB && N0 == N2.getOperand(1))
12042 SubC = dyn_cast<ConstantSDNode>(N2.getOperand(0));
12044 EVT XType = N0.getValueType();
12045 if (SubC && SubC->isNullValue() && XType.isInteger()) {
12046 SDValue Shift = DAG.getNode(ISD::SRA, SDLoc(N0), XType,
12048 DAG.getConstant(XType.getSizeInBits()-1,
12049 getShiftAmountTy(N0.getValueType())));
12050 SDValue Add = DAG.getNode(ISD::ADD, SDLoc(N0),
12052 AddToWorklist(Shift.getNode());
12053 AddToWorklist(Add.getNode());
12054 return DAG.getNode(ISD::XOR, DL, XType, Add, Shift);
12061 /// This is a stub for TargetLowering::SimplifySetCC.
12062 SDValue DAGCombiner::SimplifySetCC(EVT VT, SDValue N0,
12063 SDValue N1, ISD::CondCode Cond,
12064 SDLoc DL, bool foldBooleans) {
12065 TargetLowering::DAGCombinerInfo
12066 DagCombineInfo(DAG, Level, false, this);
12067 return TLI.SimplifySetCC(VT, N0, N1, Cond, foldBooleans, DagCombineInfo, DL);
12070 /// Given an ISD::SDIV node expressing a divide by constant, return
12071 /// a DAG expression to select that will generate the same value by multiplying
12072 /// by a magic number.
12073 /// Ref: "Hacker's Delight" or "The PowerPC Compiler Writer's Guide".
12074 SDValue DAGCombiner::BuildSDIV(SDNode *N) {
12075 ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1));
12079 // Avoid division by zero.
12080 if (!C->getAPIntValue())
12083 std::vector<SDNode*> Built;
12085 TLI.BuildSDIV(N, C->getAPIntValue(), DAG, LegalOperations, &Built);
12087 for (SDNode *N : Built)
12092 /// Given an ISD::SDIV node expressing a divide by constant power of 2, return a
12093 /// DAG expression that will generate the same value by right shifting.
12094 SDValue DAGCombiner::BuildSDIVPow2(SDNode *N) {
12095 ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1));
12099 // Avoid division by zero.
12100 if (!C->getAPIntValue())
12103 std::vector<SDNode *> Built;
12104 SDValue S = TLI.BuildSDIVPow2(N, C->getAPIntValue(), DAG, &Built);
12106 for (SDNode *N : Built)
12111 /// Given an ISD::UDIV node expressing a divide by constant, return a DAG
12112 /// expression that will generate the same value by multiplying by a magic
12114 /// Ref: "Hacker's Delight" or "The PowerPC Compiler Writer's Guide".
12115 SDValue DAGCombiner::BuildUDIV(SDNode *N) {
12116 ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1));
12120 // Avoid division by zero.
12121 if (!C->getAPIntValue())
12124 std::vector<SDNode*> Built;
12126 TLI.BuildUDIV(N, C->getAPIntValue(), DAG, LegalOperations, &Built);
12128 for (SDNode *N : Built)
12133 SDValue DAGCombiner::BuildReciprocalEstimate(SDValue Op) {
12134 if (Level >= AfterLegalizeDAG)
12137 // Expose the DAG combiner to the target combiner implementations.
12138 TargetLowering::DAGCombinerInfo DCI(DAG, Level, false, this);
12140 unsigned Iterations = 0;
12141 if (SDValue Est = TLI.getRecipEstimate(Op, DCI, Iterations)) {
12143 // Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i)
12144 // For the reciprocal, we need to find the zero of the function:
12145 // F(X) = A X - 1 [which has a zero at X = 1/A]
12147 // X_{i+1} = X_i (2 - A X_i) = X_i + X_i (1 - A X_i) [this second form
12148 // does not require additional intermediate precision]
12149 EVT VT = Op.getValueType();
12151 SDValue FPOne = DAG.getConstantFP(1.0, VT);
12153 AddToWorklist(Est.getNode());
12155 // Newton iterations: Est = Est + Est (1 - Arg * Est)
12156 for (unsigned i = 0; i < Iterations; ++i) {
12157 SDValue NewEst = DAG.getNode(ISD::FMUL, DL, VT, Op, Est);
12158 AddToWorklist(NewEst.getNode());
12160 NewEst = DAG.getNode(ISD::FSUB, DL, VT, FPOne, NewEst);
12161 AddToWorklist(NewEst.getNode());
12163 NewEst = DAG.getNode(ISD::FMUL, DL, VT, Est, NewEst);
12164 AddToWorklist(NewEst.getNode());
12166 Est = DAG.getNode(ISD::FADD, DL, VT, Est, NewEst);
12167 AddToWorklist(Est.getNode());
12176 /// Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i)
12177 /// For the reciprocal sqrt, we need to find the zero of the function:
12178 /// F(X) = 1/X^2 - A [which has a zero at X = 1/sqrt(A)]
12180 /// X_{i+1} = X_i (1.5 - A X_i^2 / 2)
12181 /// As a result, we precompute A/2 prior to the iteration loop.
12182 SDValue DAGCombiner::BuildRsqrtNROneConst(SDValue Arg, SDValue Est,
12183 unsigned Iterations) {
12184 EVT VT = Arg.getValueType();
12186 SDValue ThreeHalves = DAG.getConstantFP(1.5, VT);
12188 // We now need 0.5 * Arg which we can write as (1.5 * Arg - Arg) so that
12189 // this entire sequence requires only one FP constant.
12190 SDValue HalfArg = DAG.getNode(ISD::FMUL, DL, VT, ThreeHalves, Arg);
12191 AddToWorklist(HalfArg.getNode());
12193 HalfArg = DAG.getNode(ISD::FSUB, DL, VT, HalfArg, Arg);
12194 AddToWorklist(HalfArg.getNode());
12196 // Newton iterations: Est = Est * (1.5 - HalfArg * Est * Est)
12197 for (unsigned i = 0; i < Iterations; ++i) {
12198 SDValue NewEst = DAG.getNode(ISD::FMUL, DL, VT, Est, Est);
12199 AddToWorklist(NewEst.getNode());
12201 NewEst = DAG.getNode(ISD::FMUL, DL, VT, HalfArg, NewEst);
12202 AddToWorklist(NewEst.getNode());
12204 NewEst = DAG.getNode(ISD::FSUB, DL, VT, ThreeHalves, NewEst);
12205 AddToWorklist(NewEst.getNode());
12207 Est = DAG.getNode(ISD::FMUL, DL, VT, Est, NewEst);
12208 AddToWorklist(Est.getNode());
12213 /// Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i)
12214 /// For the reciprocal sqrt, we need to find the zero of the function:
12215 /// F(X) = 1/X^2 - A [which has a zero at X = 1/sqrt(A)]
12217 /// X_{i+1} = (-0.5 * X_i) * (A * X_i * X_i + (-3.0))
12218 SDValue DAGCombiner::BuildRsqrtNRTwoConst(SDValue Arg, SDValue Est,
12219 unsigned Iterations) {
12220 EVT VT = Arg.getValueType();
12222 SDValue MinusThree = DAG.getConstantFP(-3.0, VT);
12223 SDValue MinusHalf = DAG.getConstantFP(-0.5, VT);
12225 // Newton iterations: Est = -0.5 * Est * (-3.0 + Arg * Est * Est)
12226 for (unsigned i = 0; i < Iterations; ++i) {
12227 SDValue HalfEst = DAG.getNode(ISD::FMUL, DL, VT, Est, MinusHalf);
12228 AddToWorklist(HalfEst.getNode());
12230 Est = DAG.getNode(ISD::FMUL, DL, VT, Est, Est);
12231 AddToWorklist(Est.getNode());
12233 Est = DAG.getNode(ISD::FMUL, DL, VT, Est, Arg);
12234 AddToWorklist(Est.getNode());
12236 Est = DAG.getNode(ISD::FADD, DL, VT, Est, MinusThree);
12237 AddToWorklist(Est.getNode());
12239 Est = DAG.getNode(ISD::FMUL, DL, VT, Est, HalfEst);
12240 AddToWorklist(Est.getNode());
12245 SDValue DAGCombiner::BuildRsqrtEstimate(SDValue Op) {
12246 if (Level >= AfterLegalizeDAG)
12249 // Expose the DAG combiner to the target combiner implementations.
12250 TargetLowering::DAGCombinerInfo DCI(DAG, Level, false, this);
12251 unsigned Iterations = 0;
12252 bool UseOneConstNR = false;
12253 if (SDValue Est = TLI.getRsqrtEstimate(Op, DCI, Iterations, UseOneConstNR)) {
12254 AddToWorklist(Est.getNode());
12256 Est = UseOneConstNR ?
12257 BuildRsqrtNROneConst(Op, Est, Iterations) :
12258 BuildRsqrtNRTwoConst(Op, Est, Iterations);
12266 /// Return true if base is a frame index, which is known not to alias with
12267 /// anything but itself. Provides base object and offset as results.
12268 static bool FindBaseOffset(SDValue Ptr, SDValue &Base, int64_t &Offset,
12269 const GlobalValue *&GV, const void *&CV) {
12270 // Assume it is a primitive operation.
12271 Base = Ptr; Offset = 0; GV = nullptr; CV = nullptr;
12273 // If it's an adding a simple constant then integrate the offset.
12274 if (Base.getOpcode() == ISD::ADD) {
12275 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Base.getOperand(1))) {
12276 Base = Base.getOperand(0);
12277 Offset += C->getZExtValue();
12281 // Return the underlying GlobalValue, and update the Offset. Return false
12282 // for GlobalAddressSDNode since the same GlobalAddress may be represented
12283 // by multiple nodes with different offsets.
12284 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Base)) {
12285 GV = G->getGlobal();
12286 Offset += G->getOffset();
12290 // Return the underlying Constant value, and update the Offset. Return false
12291 // for ConstantSDNodes since the same constant pool entry may be represented
12292 // by multiple nodes with different offsets.
12293 if (ConstantPoolSDNode *C = dyn_cast<ConstantPoolSDNode>(Base)) {
12294 CV = C->isMachineConstantPoolEntry() ? (const void *)C->getMachineCPVal()
12295 : (const void *)C->getConstVal();
12296 Offset += C->getOffset();
12299 // If it's any of the following then it can't alias with anything but itself.
12300 return isa<FrameIndexSDNode>(Base);
12303 /// Return true if there is any possibility that the two addresses overlap.
12304 bool DAGCombiner::isAlias(LSBaseSDNode *Op0, LSBaseSDNode *Op1) const {
12305 // If they are the same then they must be aliases.
12306 if (Op0->getBasePtr() == Op1->getBasePtr()) return true;
12308 // If they are both volatile then they cannot be reordered.
12309 if (Op0->isVolatile() && Op1->isVolatile()) return true;
12311 // Gather base node and offset information.
12312 SDValue Base1, Base2;
12313 int64_t Offset1, Offset2;
12314 const GlobalValue *GV1, *GV2;
12315 const void *CV1, *CV2;
12316 bool isFrameIndex1 = FindBaseOffset(Op0->getBasePtr(),
12317 Base1, Offset1, GV1, CV1);
12318 bool isFrameIndex2 = FindBaseOffset(Op1->getBasePtr(),
12319 Base2, Offset2, GV2, CV2);
12321 // If they have a same base address then check to see if they overlap.
12322 if (Base1 == Base2 || (GV1 && (GV1 == GV2)) || (CV1 && (CV1 == CV2)))
12323 return !((Offset1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= Offset2 ||
12324 (Offset2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= Offset1);
12326 // It is possible for different frame indices to alias each other, mostly
12327 // when tail call optimization reuses return address slots for arguments.
12328 // To catch this case, look up the actual index of frame indices to compute
12329 // the real alias relationship.
12330 if (isFrameIndex1 && isFrameIndex2) {
12331 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
12332 Offset1 += MFI->getObjectOffset(cast<FrameIndexSDNode>(Base1)->getIndex());
12333 Offset2 += MFI->getObjectOffset(cast<FrameIndexSDNode>(Base2)->getIndex());
12334 return !((Offset1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= Offset2 ||
12335 (Offset2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= Offset1);
12338 // Otherwise, if we know what the bases are, and they aren't identical, then
12339 // we know they cannot alias.
12340 if ((isFrameIndex1 || CV1 || GV1) && (isFrameIndex2 || CV2 || GV2))
12343 // If we know required SrcValue1 and SrcValue2 have relatively large alignment
12344 // compared to the size and offset of the access, we may be able to prove they
12345 // do not alias. This check is conservative for now to catch cases created by
12346 // splitting vector types.
12347 if ((Op0->getOriginalAlignment() == Op1->getOriginalAlignment()) &&
12348 (Op0->getSrcValueOffset() != Op1->getSrcValueOffset()) &&
12349 (Op0->getMemoryVT().getSizeInBits() >> 3 ==
12350 Op1->getMemoryVT().getSizeInBits() >> 3) &&
12351 (Op0->getOriginalAlignment() > Op0->getMemoryVT().getSizeInBits()) >> 3) {
12352 int64_t OffAlign1 = Op0->getSrcValueOffset() % Op0->getOriginalAlignment();
12353 int64_t OffAlign2 = Op1->getSrcValueOffset() % Op1->getOriginalAlignment();
12355 // There is no overlap between these relatively aligned accesses of similar
12356 // size, return no alias.
12357 if ((OffAlign1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= OffAlign2 ||
12358 (OffAlign2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= OffAlign1)
12362 bool UseAA = CombinerGlobalAA.getNumOccurrences() > 0
12364 : DAG.getSubtarget().useAA();
12366 if (CombinerAAOnlyFunc.getNumOccurrences() &&
12367 CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
12371 Op0->getMemOperand()->getValue() && Op1->getMemOperand()->getValue()) {
12372 // Use alias analysis information.
12373 int64_t MinOffset = std::min(Op0->getSrcValueOffset(),
12374 Op1->getSrcValueOffset());
12375 int64_t Overlap1 = (Op0->getMemoryVT().getSizeInBits() >> 3) +
12376 Op0->getSrcValueOffset() - MinOffset;
12377 int64_t Overlap2 = (Op1->getMemoryVT().getSizeInBits() >> 3) +
12378 Op1->getSrcValueOffset() - MinOffset;
12379 AliasAnalysis::AliasResult AAResult =
12380 AA.alias(AliasAnalysis::Location(Op0->getMemOperand()->getValue(),
12382 UseTBAA ? Op0->getAAInfo() : AAMDNodes()),
12383 AliasAnalysis::Location(Op1->getMemOperand()->getValue(),
12385 UseTBAA ? Op1->getAAInfo() : AAMDNodes()));
12386 if (AAResult == AliasAnalysis::NoAlias)
12390 // Otherwise we have to assume they alias.
12394 /// Walk up chain skipping non-aliasing memory nodes,
12395 /// looking for aliasing nodes and adding them to the Aliases vector.
12396 void DAGCombiner::GatherAllAliases(SDNode *N, SDValue OriginalChain,
12397 SmallVectorImpl<SDValue> &Aliases) {
12398 SmallVector<SDValue, 8> Chains; // List of chains to visit.
12399 SmallPtrSet<SDNode *, 16> Visited; // Visited node set.
12401 // Get alias information for node.
12402 bool IsLoad = isa<LoadSDNode>(N) && !cast<LSBaseSDNode>(N)->isVolatile();
12405 Chains.push_back(OriginalChain);
12406 unsigned Depth = 0;
12408 // Look at each chain and determine if it is an alias. If so, add it to the
12409 // aliases list. If not, then continue up the chain looking for the next
12411 while (!Chains.empty()) {
12412 SDValue Chain = Chains.back();
12415 // For TokenFactor nodes, look at each operand and only continue up the
12416 // chain until we find two aliases. If we've seen two aliases, assume we'll
12417 // find more and revert to original chain since the xform is unlikely to be
12420 // FIXME: The depth check could be made to return the last non-aliasing
12421 // chain we found before we hit a tokenfactor rather than the original
12423 if (Depth > 6 || Aliases.size() == 2) {
12425 Aliases.push_back(OriginalChain);
12429 // Don't bother if we've been before.
12430 if (!Visited.insert(Chain.getNode()).second)
12433 switch (Chain.getOpcode()) {
12434 case ISD::EntryToken:
12435 // Entry token is ideal chain operand, but handled in FindBetterChain.
12440 // Get alias information for Chain.
12441 bool IsOpLoad = isa<LoadSDNode>(Chain.getNode()) &&
12442 !cast<LSBaseSDNode>(Chain.getNode())->isVolatile();
12444 // If chain is alias then stop here.
12445 if (!(IsLoad && IsOpLoad) &&
12446 isAlias(cast<LSBaseSDNode>(N), cast<LSBaseSDNode>(Chain.getNode()))) {
12447 Aliases.push_back(Chain);
12449 // Look further up the chain.
12450 Chains.push_back(Chain.getOperand(0));
12456 case ISD::TokenFactor:
12457 // We have to check each of the operands of the token factor for "small"
12458 // token factors, so we queue them up. Adding the operands to the queue
12459 // (stack) in reverse order maintains the original order and increases the
12460 // likelihood that getNode will find a matching token factor (CSE.)
12461 if (Chain.getNumOperands() > 16) {
12462 Aliases.push_back(Chain);
12465 for (unsigned n = Chain.getNumOperands(); n;)
12466 Chains.push_back(Chain.getOperand(--n));
12471 // For all other instructions we will just have to take what we can get.
12472 Aliases.push_back(Chain);
12477 // We need to be careful here to also search for aliases through the
12478 // value operand of a store, etc. Consider the following situation:
12480 // L1 = load Token1, %52
12481 // S1 = store Token1, L1, %51
12482 // L2 = load Token1, %52+8
12483 // S2 = store Token1, L2, %51+8
12484 // Token2 = Token(S1, S2)
12485 // L3 = load Token2, %53
12486 // S3 = store Token2, L3, %52
12487 // L4 = load Token2, %53+8
12488 // S4 = store Token2, L4, %52+8
12489 // If we search for aliases of S3 (which loads address %52), and we look
12490 // only through the chain, then we'll miss the trivial dependence on L1
12491 // (which also loads from %52). We then might change all loads and
12492 // stores to use Token1 as their chain operand, which could result in
12493 // copying %53 into %52 before copying %52 into %51 (which should
12496 // The problem is, however, that searching for such data dependencies
12497 // can become expensive, and the cost is not directly related to the
12498 // chain depth. Instead, we'll rule out such configurations here by
12499 // insisting that we've visited all chain users (except for users
12500 // of the original chain, which is not necessary). When doing this,
12501 // we need to look through nodes we don't care about (otherwise, things
12502 // like register copies will interfere with trivial cases).
12504 SmallVector<const SDNode *, 16> Worklist;
12505 for (const SDNode *N : Visited)
12506 if (N != OriginalChain.getNode())
12507 Worklist.push_back(N);
12509 while (!Worklist.empty()) {
12510 const SDNode *M = Worklist.pop_back_val();
12512 // We have already visited M, and want to make sure we've visited any uses
12513 // of M that we care about. For uses that we've not visisted, and don't
12514 // care about, queue them to the worklist.
12516 for (SDNode::use_iterator UI = M->use_begin(),
12517 UIE = M->use_end(); UI != UIE; ++UI)
12518 if (UI.getUse().getValueType() == MVT::Other &&
12519 Visited.insert(*UI).second) {
12520 if (isa<MemIntrinsicSDNode>(*UI) || isa<MemSDNode>(*UI)) {
12521 // We've not visited this use, and we care about it (it could have an
12522 // ordering dependency with the original node).
12524 Aliases.push_back(OriginalChain);
12528 // We've not visited this use, but we don't care about it. Mark it as
12529 // visited and enqueue it to the worklist.
12530 Worklist.push_back(*UI);
12535 /// Walk up chain skipping non-aliasing memory nodes, looking for a better chain
12536 /// (aliasing node.)
12537 SDValue DAGCombiner::FindBetterChain(SDNode *N, SDValue OldChain) {
12538 SmallVector<SDValue, 8> Aliases; // Ops for replacing token factor.
12540 // Accumulate all the aliases to this node.
12541 GatherAllAliases(N, OldChain, Aliases);
12543 // If no operands then chain to entry token.
12544 if (Aliases.size() == 0)
12545 return DAG.getEntryNode();
12547 // If a single operand then chain to it. We don't need to revisit it.
12548 if (Aliases.size() == 1)
12551 // Construct a custom tailored token factor.
12552 return DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other, Aliases);
12555 /// This is the entry point for the file.
12556 void SelectionDAG::Combine(CombineLevel Level, AliasAnalysis &AA,
12557 CodeGenOpt::Level OptLevel) {
12558 /// This is the main entry point to this class.
12559 DAGCombiner(*this, AA, OptLevel).Run(Level);