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);
307 SDValue XformToShuffleWithZero(SDNode *N);
308 SDValue ReassociateOps(unsigned Opc, SDLoc DL, SDValue LHS, SDValue RHS);
310 SDValue visitShiftByConstant(SDNode *N, ConstantSDNode *Amt);
312 bool SimplifySelectOps(SDNode *SELECT, SDValue LHS, SDValue RHS);
313 SDValue SimplifyBinOpWithSameOpcodeHands(SDNode *N);
314 SDValue SimplifySelect(SDLoc DL, SDValue N0, SDValue N1, SDValue N2);
315 SDValue SimplifySelectCC(SDLoc DL, SDValue N0, SDValue N1, SDValue N2,
316 SDValue N3, ISD::CondCode CC,
317 bool NotExtCompare = false);
318 SDValue SimplifySetCC(EVT VT, SDValue N0, SDValue N1, ISD::CondCode Cond,
319 SDLoc DL, bool foldBooleans = true);
321 bool isSetCCEquivalent(SDValue N, SDValue &LHS, SDValue &RHS,
323 bool isOneUseSetCC(SDValue N) const;
325 SDValue SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp,
327 SDValue CombineConsecutiveLoads(SDNode *N, EVT VT);
328 SDValue ConstantFoldBITCASTofBUILD_VECTOR(SDNode *, EVT);
329 SDValue BuildSDIV(SDNode *N);
330 SDValue BuildSDIVPow2(SDNode *N);
331 SDValue BuildUDIV(SDNode *N);
332 SDValue BuildReciprocalEstimate(SDValue Op);
333 SDValue BuildRsqrtEstimate(SDValue Op);
334 SDValue BuildRsqrtNROneConst(SDValue Op, SDValue Est, unsigned Iterations);
335 SDValue BuildRsqrtNRTwoConst(SDValue Op, SDValue Est, unsigned Iterations);
336 SDValue MatchBSwapHWordLow(SDNode *N, SDValue N0, SDValue N1,
337 bool DemandHighBits = true);
338 SDValue MatchBSwapHWord(SDNode *N, SDValue N0, SDValue N1);
339 SDNode *MatchRotatePosNeg(SDValue Shifted, SDValue Pos, SDValue Neg,
340 SDValue InnerPos, SDValue InnerNeg,
341 unsigned PosOpcode, unsigned NegOpcode,
343 SDNode *MatchRotate(SDValue LHS, SDValue RHS, SDLoc DL);
344 SDValue ReduceLoadWidth(SDNode *N);
345 SDValue ReduceLoadOpStoreWidth(SDNode *N);
346 SDValue TransformFPLoadStorePair(SDNode *N);
347 SDValue reduceBuildVecExtToExtBuildVec(SDNode *N);
348 SDValue reduceBuildVecConvertToConvertBuildVec(SDNode *N);
350 SDValue GetDemandedBits(SDValue V, const APInt &Mask);
352 /// Walk up chain skipping non-aliasing memory nodes,
353 /// looking for aliasing nodes and adding them to the Aliases vector.
354 void GatherAllAliases(SDNode *N, SDValue OriginalChain,
355 SmallVectorImpl<SDValue> &Aliases);
357 /// Return true if there is any possibility that the two addresses overlap.
358 bool isAlias(LSBaseSDNode *Op0, LSBaseSDNode *Op1) const;
360 /// Walk up chain skipping non-aliasing memory nodes, looking for a better
361 /// chain (aliasing node.)
362 SDValue FindBetterChain(SDNode *N, SDValue Chain);
364 /// Merge consecutive store operations into a wide store.
365 /// This optimization uses wide integers or vectors when possible.
366 /// \return True if some memory operations were changed.
367 bool MergeConsecutiveStores(StoreSDNode *N);
369 /// \brief Try to transform a truncation where C is a constant:
370 /// (trunc (and X, C)) -> (and (trunc X), (trunc C))
372 /// \p N needs to be a truncation and its first operand an AND. Other
373 /// requirements are checked by the function (e.g. that trunc is
374 /// single-use) and if missed an empty SDValue is returned.
375 SDValue distributeTruncateThroughAnd(SDNode *N);
378 DAGCombiner(SelectionDAG &D, AliasAnalysis &A, CodeGenOpt::Level OL)
379 : DAG(D), TLI(D.getTargetLoweringInfo()), Level(BeforeLegalizeTypes),
380 OptLevel(OL), LegalOperations(false), LegalTypes(false), AA(A) {
381 AttributeSet FnAttrs =
382 DAG.getMachineFunction().getFunction()->getAttributes();
384 FnAttrs.hasAttribute(AttributeSet::FunctionIndex,
385 Attribute::OptimizeForSize) ||
386 FnAttrs.hasAttribute(AttributeSet::FunctionIndex, Attribute::MinSize);
389 /// Runs the dag combiner on all nodes in the work list
390 void Run(CombineLevel AtLevel);
392 SelectionDAG &getDAG() const { return DAG; }
394 /// Returns a type large enough to hold any valid shift amount - before type
395 /// legalization these can be huge.
396 EVT getShiftAmountTy(EVT LHSTy) {
397 assert(LHSTy.isInteger() && "Shift amount is not an integer type!");
398 if (LHSTy.isVector())
400 return LegalTypes ? TLI.getScalarShiftAmountTy(LHSTy)
401 : TLI.getPointerTy();
404 /// This method returns true if we are running before type legalization or
405 /// if the specified VT is legal.
406 bool isTypeLegal(const EVT &VT) {
407 if (!LegalTypes) return true;
408 return TLI.isTypeLegal(VT);
411 /// Convenience wrapper around TargetLowering::getSetCCResultType
412 EVT getSetCCResultType(EVT VT) const {
413 return TLI.getSetCCResultType(*DAG.getContext(), VT);
420 /// This class is a DAGUpdateListener that removes any deleted
421 /// nodes from the worklist.
422 class WorklistRemover : public SelectionDAG::DAGUpdateListener {
425 explicit WorklistRemover(DAGCombiner &dc)
426 : SelectionDAG::DAGUpdateListener(dc.getDAG()), DC(dc) {}
428 void NodeDeleted(SDNode *N, SDNode *E) override {
429 DC.removeFromWorklist(N);
434 //===----------------------------------------------------------------------===//
435 // TargetLowering::DAGCombinerInfo implementation
436 //===----------------------------------------------------------------------===//
438 void TargetLowering::DAGCombinerInfo::AddToWorklist(SDNode *N) {
439 ((DAGCombiner*)DC)->AddToWorklist(N);
442 void TargetLowering::DAGCombinerInfo::RemoveFromWorklist(SDNode *N) {
443 ((DAGCombiner*)DC)->removeFromWorklist(N);
446 SDValue TargetLowering::DAGCombinerInfo::
447 CombineTo(SDNode *N, const std::vector<SDValue> &To, bool AddTo) {
448 return ((DAGCombiner*)DC)->CombineTo(N, &To[0], To.size(), AddTo);
451 SDValue TargetLowering::DAGCombinerInfo::
452 CombineTo(SDNode *N, SDValue Res, bool AddTo) {
453 return ((DAGCombiner*)DC)->CombineTo(N, Res, AddTo);
457 SDValue TargetLowering::DAGCombinerInfo::
458 CombineTo(SDNode *N, SDValue Res0, SDValue Res1, bool AddTo) {
459 return ((DAGCombiner*)DC)->CombineTo(N, Res0, Res1, AddTo);
462 void TargetLowering::DAGCombinerInfo::
463 CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) {
464 return ((DAGCombiner*)DC)->CommitTargetLoweringOpt(TLO);
467 //===----------------------------------------------------------------------===//
469 //===----------------------------------------------------------------------===//
471 void DAGCombiner::deleteAndRecombine(SDNode *N) {
472 removeFromWorklist(N);
474 // If the operands of this node are only used by the node, they will now be
475 // dead. Make sure to re-visit them and recursively delete dead nodes.
476 for (const SDValue &Op : N->ops())
477 // For an operand generating multiple values, one of the values may
478 // become dead allowing further simplification (e.g. split index
479 // arithmetic from an indexed load).
480 if (Op->hasOneUse() || Op->getNumValues() > 1)
481 AddToWorklist(Op.getNode());
486 /// Return 1 if we can compute the negated form of the specified expression for
487 /// the same cost as the expression itself, or 2 if we can compute the negated
488 /// form more cheaply than the expression itself.
489 static char isNegatibleForFree(SDValue Op, bool LegalOperations,
490 const TargetLowering &TLI,
491 const TargetOptions *Options,
492 unsigned Depth = 0) {
493 // fneg is removable even if it has multiple uses.
494 if (Op.getOpcode() == ISD::FNEG) return 2;
496 // Don't allow anything with multiple uses.
497 if (!Op.hasOneUse()) return 0;
499 // Don't recurse exponentially.
500 if (Depth > 6) return 0;
502 switch (Op.getOpcode()) {
503 default: return false;
504 case ISD::ConstantFP:
505 // Don't invert constant FP values after legalize. The negated constant
506 // isn't necessarily legal.
507 return LegalOperations ? 0 : 1;
509 // FIXME: determine better conditions for this xform.
510 if (!Options->UnsafeFPMath) return 0;
512 // After operation legalization, it might not be legal to create new FSUBs.
513 if (LegalOperations &&
514 !TLI.isOperationLegalOrCustom(ISD::FSUB, Op.getValueType()))
517 // fold (fneg (fadd A, B)) -> (fsub (fneg A), B)
518 if (char V = isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI,
521 // fold (fneg (fadd A, B)) -> (fsub (fneg B), A)
522 return isNegatibleForFree(Op.getOperand(1), LegalOperations, TLI, Options,
525 // We can't turn -(A-B) into B-A when we honor signed zeros.
526 if (!Options->UnsafeFPMath) return 0;
528 // fold (fneg (fsub A, B)) -> (fsub B, A)
533 if (Options->HonorSignDependentRoundingFPMath()) return 0;
535 // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y) or (fmul X, (fneg Y))
536 if (char V = isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI,
540 return isNegatibleForFree(Op.getOperand(1), LegalOperations, TLI, Options,
546 return isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI, Options,
551 /// If isNegatibleForFree returns true, return the newly negated expression.
552 static SDValue GetNegatedExpression(SDValue Op, SelectionDAG &DAG,
553 bool LegalOperations, unsigned Depth = 0) {
554 const TargetOptions &Options = DAG.getTarget().Options;
555 // fneg is removable even if it has multiple uses.
556 if (Op.getOpcode() == ISD::FNEG) return Op.getOperand(0);
558 // Don't allow anything with multiple uses.
559 assert(Op.hasOneUse() && "Unknown reuse!");
561 assert(Depth <= 6 && "GetNegatedExpression doesn't match isNegatibleForFree");
562 switch (Op.getOpcode()) {
563 default: llvm_unreachable("Unknown code");
564 case ISD::ConstantFP: {
565 APFloat V = cast<ConstantFPSDNode>(Op)->getValueAPF();
567 return DAG.getConstantFP(V, Op.getValueType());
570 // FIXME: determine better conditions for this xform.
571 assert(Options.UnsafeFPMath);
573 // fold (fneg (fadd A, B)) -> (fsub (fneg A), B)
574 if (isNegatibleForFree(Op.getOperand(0), LegalOperations,
575 DAG.getTargetLoweringInfo(), &Options, Depth+1))
576 return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
577 GetNegatedExpression(Op.getOperand(0), DAG,
578 LegalOperations, Depth+1),
580 // fold (fneg (fadd A, B)) -> (fsub (fneg B), A)
581 return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
582 GetNegatedExpression(Op.getOperand(1), DAG,
583 LegalOperations, Depth+1),
586 // We can't turn -(A-B) into B-A when we honor signed zeros.
587 assert(Options.UnsafeFPMath);
589 // fold (fneg (fsub 0, B)) -> B
590 if (ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(Op.getOperand(0)))
591 if (N0CFP->getValueAPF().isZero())
592 return Op.getOperand(1);
594 // fold (fneg (fsub A, B)) -> (fsub B, A)
595 return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
596 Op.getOperand(1), Op.getOperand(0));
600 assert(!Options.HonorSignDependentRoundingFPMath());
602 // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y)
603 if (isNegatibleForFree(Op.getOperand(0), LegalOperations,
604 DAG.getTargetLoweringInfo(), &Options, Depth+1))
605 return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
606 GetNegatedExpression(Op.getOperand(0), DAG,
607 LegalOperations, Depth+1),
610 // fold (fneg (fmul X, Y)) -> (fmul X, (fneg Y))
611 return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
613 GetNegatedExpression(Op.getOperand(1), DAG,
614 LegalOperations, Depth+1));
618 return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
619 GetNegatedExpression(Op.getOperand(0), DAG,
620 LegalOperations, Depth+1));
622 return DAG.getNode(ISD::FP_ROUND, SDLoc(Op), Op.getValueType(),
623 GetNegatedExpression(Op.getOperand(0), DAG,
624 LegalOperations, Depth+1),
629 // Return true if this node is a setcc, or is a select_cc
630 // that selects between the target values used for true and false, making it
631 // equivalent to a setcc. Also, set the incoming LHS, RHS, and CC references to
632 // the appropriate nodes based on the type of node we are checking. This
633 // simplifies life a bit for the callers.
634 bool DAGCombiner::isSetCCEquivalent(SDValue N, SDValue &LHS, SDValue &RHS,
636 if (N.getOpcode() == ISD::SETCC) {
637 LHS = N.getOperand(0);
638 RHS = N.getOperand(1);
639 CC = N.getOperand(2);
643 if (N.getOpcode() != ISD::SELECT_CC ||
644 !TLI.isConstTrueVal(N.getOperand(2).getNode()) ||
645 !TLI.isConstFalseVal(N.getOperand(3).getNode()))
648 LHS = N.getOperand(0);
649 RHS = N.getOperand(1);
650 CC = N.getOperand(4);
654 /// Return true if this is a SetCC-equivalent operation with only one use.
655 /// If this is true, it allows the users to invert the operation for free when
656 /// it is profitable to do so.
657 bool DAGCombiner::isOneUseSetCC(SDValue N) const {
659 if (isSetCCEquivalent(N, N0, N1, N2) && N.getNode()->hasOneUse())
664 /// Returns true if N is a BUILD_VECTOR node whose
665 /// elements are all the same constant or undefined.
666 static bool isConstantSplatVector(SDNode *N, APInt& SplatValue) {
667 BuildVectorSDNode *C = dyn_cast<BuildVectorSDNode>(N);
672 unsigned SplatBitSize;
674 EVT EltVT = N->getValueType(0).getVectorElementType();
675 return (C->isConstantSplat(SplatValue, SplatUndef, SplatBitSize,
677 EltVT.getSizeInBits() >= SplatBitSize);
680 // \brief Returns the SDNode if it is a constant BuildVector or constant.
681 static SDNode *isConstantBuildVectorOrConstantInt(SDValue N) {
682 if (isa<ConstantSDNode>(N))
684 BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N);
685 if (BV && BV->isConstant())
690 // \brief Returns the SDNode if it is a constant splat BuildVector or constant
692 static ConstantSDNode *isConstOrConstSplat(SDValue N) {
693 if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N))
696 if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) {
697 BitVector UndefElements;
698 ConstantSDNode *CN = BV->getConstantSplatNode(&UndefElements);
700 // BuildVectors can truncate their operands. Ignore that case here.
701 // FIXME: We blindly ignore splats which include undef which is overly
703 if (CN && UndefElements.none() &&
704 CN->getValueType(0) == N.getValueType().getScalarType())
711 // \brief Returns the SDNode if it is a constant splat BuildVector or constant
713 static ConstantFPSDNode *isConstOrConstSplatFP(SDValue N) {
714 if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(N))
717 if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) {
718 BitVector UndefElements;
719 ConstantFPSDNode *CN = BV->getConstantFPSplatNode(&UndefElements);
721 if (CN && UndefElements.none())
728 SDValue DAGCombiner::ReassociateOps(unsigned Opc, SDLoc DL,
729 SDValue N0, SDValue N1) {
730 EVT VT = N0.getValueType();
731 if (N0.getOpcode() == Opc) {
732 if (SDNode *L = isConstantBuildVectorOrConstantInt(N0.getOperand(1))) {
733 if (SDNode *R = isConstantBuildVectorOrConstantInt(N1)) {
734 // reassoc. (op (op x, c1), c2) -> (op x, (op c1, c2))
735 SDValue OpNode = DAG.FoldConstantArithmetic(Opc, VT, L, R);
736 if (!OpNode.getNode())
738 return DAG.getNode(Opc, DL, VT, N0.getOperand(0), OpNode);
740 if (N0.hasOneUse()) {
741 // reassoc. (op (op x, c1), y) -> (op (op x, y), c1) iff x+c1 has one
743 SDValue OpNode = DAG.getNode(Opc, SDLoc(N0), VT, N0.getOperand(0), N1);
744 if (!OpNode.getNode())
746 AddToWorklist(OpNode.getNode());
747 return DAG.getNode(Opc, DL, VT, OpNode, N0.getOperand(1));
752 if (N1.getOpcode() == Opc) {
753 if (SDNode *R = isConstantBuildVectorOrConstantInt(N1.getOperand(1))) {
754 if (SDNode *L = isConstantBuildVectorOrConstantInt(N0)) {
755 // reassoc. (op c2, (op x, c1)) -> (op x, (op c1, c2))
756 SDValue OpNode = DAG.FoldConstantArithmetic(Opc, VT, R, L);
757 if (!OpNode.getNode())
759 return DAG.getNode(Opc, DL, VT, N1.getOperand(0), OpNode);
761 if (N1.hasOneUse()) {
762 // reassoc. (op y, (op x, c1)) -> (op (op x, y), c1) iff x+c1 has one
764 SDValue OpNode = DAG.getNode(Opc, SDLoc(N0), VT, N1.getOperand(0), N0);
765 if (!OpNode.getNode())
767 AddToWorklist(OpNode.getNode());
768 return DAG.getNode(Opc, DL, VT, OpNode, N1.getOperand(1));
776 SDValue DAGCombiner::CombineTo(SDNode *N, const SDValue *To, unsigned NumTo,
778 assert(N->getNumValues() == NumTo && "Broken CombineTo call!");
780 DEBUG(dbgs() << "\nReplacing.1 ";
782 dbgs() << "\nWith: ";
783 To[0].getNode()->dump(&DAG);
784 dbgs() << " and " << NumTo-1 << " other values\n";
785 for (unsigned i = 0, e = NumTo; i != e; ++i)
786 assert((!To[i].getNode() ||
787 N->getValueType(i) == To[i].getValueType()) &&
788 "Cannot combine value to value of different type!"));
789 WorklistRemover DeadNodes(*this);
790 DAG.ReplaceAllUsesWith(N, To);
792 // Push the new nodes and any users onto the worklist
793 for (unsigned i = 0, e = NumTo; i != e; ++i) {
794 if (To[i].getNode()) {
795 AddToWorklist(To[i].getNode());
796 AddUsersToWorklist(To[i].getNode());
801 // Finally, if the node is now dead, remove it from the graph. The node
802 // may not be dead if the replacement process recursively simplified to
803 // something else needing this node.
805 deleteAndRecombine(N);
806 return SDValue(N, 0);
810 CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) {
811 // Replace all uses. If any nodes become isomorphic to other nodes and
812 // are deleted, make sure to remove them from our worklist.
813 WorklistRemover DeadNodes(*this);
814 DAG.ReplaceAllUsesOfValueWith(TLO.Old, TLO.New);
816 // Push the new node and any (possibly new) users onto the worklist.
817 AddToWorklist(TLO.New.getNode());
818 AddUsersToWorklist(TLO.New.getNode());
820 // Finally, if the node is now dead, remove it from the graph. The node
821 // may not be dead if the replacement process recursively simplified to
822 // something else needing this node.
823 if (TLO.Old.getNode()->use_empty())
824 deleteAndRecombine(TLO.Old.getNode());
827 /// Check the specified integer node value to see if it can be simplified or if
828 /// things it uses can be simplified by bit propagation. If so, return true.
829 bool DAGCombiner::SimplifyDemandedBits(SDValue Op, const APInt &Demanded) {
830 TargetLowering::TargetLoweringOpt TLO(DAG, LegalTypes, LegalOperations);
831 APInt KnownZero, KnownOne;
832 if (!TLI.SimplifyDemandedBits(Op, Demanded, KnownZero, KnownOne, TLO))
836 AddToWorklist(Op.getNode());
838 // Replace the old value with the new one.
840 DEBUG(dbgs() << "\nReplacing.2 ";
841 TLO.Old.getNode()->dump(&DAG);
842 dbgs() << "\nWith: ";
843 TLO.New.getNode()->dump(&DAG);
846 CommitTargetLoweringOpt(TLO);
850 void DAGCombiner::ReplaceLoadWithPromotedLoad(SDNode *Load, SDNode *ExtLoad) {
852 EVT VT = Load->getValueType(0);
853 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, dl, VT, SDValue(ExtLoad, 0));
855 DEBUG(dbgs() << "\nReplacing.9 ";
857 dbgs() << "\nWith: ";
858 Trunc.getNode()->dump(&DAG);
860 WorklistRemover DeadNodes(*this);
861 DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 0), Trunc);
862 DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 1), SDValue(ExtLoad, 1));
863 deleteAndRecombine(Load);
864 AddToWorklist(Trunc.getNode());
867 SDValue DAGCombiner::PromoteOperand(SDValue Op, EVT PVT, bool &Replace) {
870 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Op)) {
871 EVT MemVT = LD->getMemoryVT();
872 ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD)
873 ? (TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT) ? ISD::ZEXTLOAD
875 : LD->getExtensionType();
877 return DAG.getExtLoad(ExtType, dl, PVT,
878 LD->getChain(), LD->getBasePtr(),
879 MemVT, LD->getMemOperand());
882 unsigned Opc = Op.getOpcode();
885 case ISD::AssertSext:
886 return DAG.getNode(ISD::AssertSext, dl, PVT,
887 SExtPromoteOperand(Op.getOperand(0), PVT),
889 case ISD::AssertZext:
890 return DAG.getNode(ISD::AssertZext, dl, PVT,
891 ZExtPromoteOperand(Op.getOperand(0), PVT),
893 case ISD::Constant: {
895 Op.getValueType().isByteSized() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
896 return DAG.getNode(ExtOpc, dl, PVT, Op);
900 if (!TLI.isOperationLegal(ISD::ANY_EXTEND, PVT))
902 return DAG.getNode(ISD::ANY_EXTEND, dl, PVT, Op);
905 SDValue DAGCombiner::SExtPromoteOperand(SDValue Op, EVT PVT) {
906 if (!TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, PVT))
908 EVT OldVT = Op.getValueType();
910 bool Replace = false;
911 SDValue NewOp = PromoteOperand(Op, PVT, Replace);
912 if (!NewOp.getNode())
914 AddToWorklist(NewOp.getNode());
917 ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode());
918 return DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, NewOp.getValueType(), NewOp,
919 DAG.getValueType(OldVT));
922 SDValue DAGCombiner::ZExtPromoteOperand(SDValue Op, EVT PVT) {
923 EVT OldVT = Op.getValueType();
925 bool Replace = false;
926 SDValue NewOp = PromoteOperand(Op, PVT, Replace);
927 if (!NewOp.getNode())
929 AddToWorklist(NewOp.getNode());
932 ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode());
933 return DAG.getZeroExtendInReg(NewOp, dl, OldVT);
936 /// Promote the specified integer binary operation if the target indicates it is
937 /// beneficial. e.g. On x86, it's usually better to promote i16 operations to
938 /// i32 since i16 instructions are longer.
939 SDValue DAGCombiner::PromoteIntBinOp(SDValue Op) {
940 if (!LegalOperations)
943 EVT VT = Op.getValueType();
944 if (VT.isVector() || !VT.isInteger())
947 // If operation type is 'undesirable', e.g. i16 on x86, consider
949 unsigned Opc = Op.getOpcode();
950 if (TLI.isTypeDesirableForOp(Opc, VT))
954 // Consult target whether it is a good idea to promote this operation and
955 // what's the right type to promote it to.
956 if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
957 assert(PVT != VT && "Don't know what type to promote to!");
959 bool Replace0 = false;
960 SDValue N0 = Op.getOperand(0);
961 SDValue NN0 = PromoteOperand(N0, PVT, Replace0);
965 bool Replace1 = false;
966 SDValue N1 = Op.getOperand(1);
971 NN1 = PromoteOperand(N1, PVT, Replace1);
976 AddToWorklist(NN0.getNode());
978 AddToWorklist(NN1.getNode());
981 ReplaceLoadWithPromotedLoad(N0.getNode(), NN0.getNode());
983 ReplaceLoadWithPromotedLoad(N1.getNode(), NN1.getNode());
985 DEBUG(dbgs() << "\nPromoting ";
986 Op.getNode()->dump(&DAG));
988 return DAG.getNode(ISD::TRUNCATE, dl, VT,
989 DAG.getNode(Opc, dl, PVT, NN0, NN1));
994 /// Promote the specified integer shift operation if the target indicates it is
995 /// beneficial. e.g. On x86, it's usually better to promote i16 operations to
996 /// i32 since i16 instructions are longer.
997 SDValue DAGCombiner::PromoteIntShiftOp(SDValue Op) {
998 if (!LegalOperations)
1001 EVT VT = Op.getValueType();
1002 if (VT.isVector() || !VT.isInteger())
1005 // If operation type is 'undesirable', e.g. i16 on x86, consider
1007 unsigned Opc = Op.getOpcode();
1008 if (TLI.isTypeDesirableForOp(Opc, VT))
1012 // Consult target whether it is a good idea to promote this operation and
1013 // what's the right type to promote it to.
1014 if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1015 assert(PVT != VT && "Don't know what type to promote to!");
1017 bool Replace = false;
1018 SDValue N0 = Op.getOperand(0);
1019 if (Opc == ISD::SRA)
1020 N0 = SExtPromoteOperand(Op.getOperand(0), PVT);
1021 else if (Opc == ISD::SRL)
1022 N0 = ZExtPromoteOperand(Op.getOperand(0), PVT);
1024 N0 = PromoteOperand(N0, PVT, Replace);
1028 AddToWorklist(N0.getNode());
1030 ReplaceLoadWithPromotedLoad(Op.getOperand(0).getNode(), N0.getNode());
1032 DEBUG(dbgs() << "\nPromoting ";
1033 Op.getNode()->dump(&DAG));
1035 return DAG.getNode(ISD::TRUNCATE, dl, VT,
1036 DAG.getNode(Opc, dl, PVT, N0, Op.getOperand(1)));
1041 SDValue DAGCombiner::PromoteExtend(SDValue Op) {
1042 if (!LegalOperations)
1045 EVT VT = Op.getValueType();
1046 if (VT.isVector() || !VT.isInteger())
1049 // If operation type is 'undesirable', e.g. i16 on x86, consider
1051 unsigned Opc = Op.getOpcode();
1052 if (TLI.isTypeDesirableForOp(Opc, VT))
1056 // Consult target whether it is a good idea to promote this operation and
1057 // what's the right type to promote it to.
1058 if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1059 assert(PVT != VT && "Don't know what type to promote to!");
1060 // fold (aext (aext x)) -> (aext x)
1061 // fold (aext (zext x)) -> (zext x)
1062 // fold (aext (sext x)) -> (sext x)
1063 DEBUG(dbgs() << "\nPromoting ";
1064 Op.getNode()->dump(&DAG));
1065 return DAG.getNode(Op.getOpcode(), SDLoc(Op), VT, Op.getOperand(0));
1070 bool DAGCombiner::PromoteLoad(SDValue Op) {
1071 if (!LegalOperations)
1074 EVT VT = Op.getValueType();
1075 if (VT.isVector() || !VT.isInteger())
1078 // If operation type is 'undesirable', e.g. i16 on x86, consider
1080 unsigned Opc = Op.getOpcode();
1081 if (TLI.isTypeDesirableForOp(Opc, VT))
1085 // Consult target whether it is a good idea to promote this operation and
1086 // what's the right type to promote it to.
1087 if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1088 assert(PVT != VT && "Don't know what type to promote to!");
1091 SDNode *N = Op.getNode();
1092 LoadSDNode *LD = cast<LoadSDNode>(N);
1093 EVT MemVT = LD->getMemoryVT();
1094 ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD)
1095 ? (TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT) ? ISD::ZEXTLOAD
1097 : LD->getExtensionType();
1098 SDValue NewLD = DAG.getExtLoad(ExtType, dl, PVT,
1099 LD->getChain(), LD->getBasePtr(),
1100 MemVT, LD->getMemOperand());
1101 SDValue Result = DAG.getNode(ISD::TRUNCATE, dl, VT, NewLD);
1103 DEBUG(dbgs() << "\nPromoting ";
1106 Result.getNode()->dump(&DAG);
1108 WorklistRemover DeadNodes(*this);
1109 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result);
1110 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), NewLD.getValue(1));
1111 deleteAndRecombine(N);
1112 AddToWorklist(Result.getNode());
1118 /// \brief Recursively delete a node which has no uses and any operands for
1119 /// which it is the only use.
1121 /// Note that this both deletes the nodes and removes them from the worklist.
1122 /// It also adds any nodes who have had a user deleted to the worklist as they
1123 /// may now have only one use and subject to other combines.
1124 bool DAGCombiner::recursivelyDeleteUnusedNodes(SDNode *N) {
1125 if (!N->use_empty())
1128 SmallSetVector<SDNode *, 16> Nodes;
1131 N = Nodes.pop_back_val();
1135 if (N->use_empty()) {
1136 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1137 Nodes.insert(N->getOperand(i).getNode());
1139 removeFromWorklist(N);
1144 } while (!Nodes.empty());
1148 //===----------------------------------------------------------------------===//
1149 // Main DAG Combiner implementation
1150 //===----------------------------------------------------------------------===//
1152 void DAGCombiner::Run(CombineLevel AtLevel) {
1153 // set the instance variables, so that the various visit routines may use it.
1155 LegalOperations = Level >= AfterLegalizeVectorOps;
1156 LegalTypes = Level >= AfterLegalizeTypes;
1158 // Early exit if this basic block is in an optnone function.
1159 AttributeSet FnAttrs =
1160 DAG.getMachineFunction().getFunction()->getAttributes();
1161 if (FnAttrs.hasAttribute(AttributeSet::FunctionIndex,
1162 Attribute::OptimizeNone))
1165 // Add all the dag nodes to the worklist.
1166 for (SelectionDAG::allnodes_iterator I = DAG.allnodes_begin(),
1167 E = DAG.allnodes_end(); I != E; ++I)
1170 // Create a dummy node (which is not added to allnodes), that adds a reference
1171 // to the root node, preventing it from being deleted, and tracking any
1172 // changes of the root.
1173 HandleSDNode Dummy(DAG.getRoot());
1175 // while the worklist isn't empty, find a node and
1176 // try and combine it.
1177 while (!WorklistMap.empty()) {
1179 // The Worklist holds the SDNodes in order, but it may contain null entries.
1181 N = Worklist.pop_back_val();
1184 bool GoodWorklistEntry = WorklistMap.erase(N);
1185 (void)GoodWorklistEntry;
1186 assert(GoodWorklistEntry &&
1187 "Found a worklist entry without a corresponding map entry!");
1189 // If N has no uses, it is dead. Make sure to revisit all N's operands once
1190 // N is deleted from the DAG, since they too may now be dead or may have a
1191 // reduced number of uses, allowing other xforms.
1192 if (recursivelyDeleteUnusedNodes(N))
1195 WorklistRemover DeadNodes(*this);
1197 // If this combine is running after legalizing the DAG, re-legalize any
1198 // nodes pulled off the worklist.
1199 if (Level == AfterLegalizeDAG) {
1200 SmallSetVector<SDNode *, 16> UpdatedNodes;
1201 bool NIsValid = DAG.LegalizeOp(N, UpdatedNodes);
1203 for (SDNode *LN : UpdatedNodes) {
1205 AddUsersToWorklist(LN);
1211 DEBUG(dbgs() << "\nCombining: "; N->dump(&DAG));
1213 // Add any operands of the new node which have not yet been combined to the
1214 // worklist as well. Because the worklist uniques things already, this
1215 // won't repeatedly process the same operand.
1216 CombinedNodes.insert(N);
1217 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1218 if (!CombinedNodes.count(N->getOperand(i).getNode()))
1219 AddToWorklist(N->getOperand(i).getNode());
1221 SDValue RV = combine(N);
1228 // If we get back the same node we passed in, rather than a new node or
1229 // zero, we know that the node must have defined multiple values and
1230 // CombineTo was used. Since CombineTo takes care of the worklist
1231 // mechanics for us, we have no work to do in this case.
1232 if (RV.getNode() == N)
1235 assert(N->getOpcode() != ISD::DELETED_NODE &&
1236 RV.getNode()->getOpcode() != ISD::DELETED_NODE &&
1237 "Node was deleted but visit returned new node!");
1239 DEBUG(dbgs() << " ... into: ";
1240 RV.getNode()->dump(&DAG));
1242 // Transfer debug value.
1243 DAG.TransferDbgValues(SDValue(N, 0), RV);
1244 if (N->getNumValues() == RV.getNode()->getNumValues())
1245 DAG.ReplaceAllUsesWith(N, RV.getNode());
1247 assert(N->getValueType(0) == RV.getValueType() &&
1248 N->getNumValues() == 1 && "Type mismatch");
1250 DAG.ReplaceAllUsesWith(N, &OpV);
1253 // Push the new node and any users onto the worklist
1254 AddToWorklist(RV.getNode());
1255 AddUsersToWorklist(RV.getNode());
1257 // Finally, if the node is now dead, remove it from the graph. The node
1258 // may not be dead if the replacement process recursively simplified to
1259 // something else needing this node. This will also take care of adding any
1260 // operands which have lost a user to the worklist.
1261 recursivelyDeleteUnusedNodes(N);
1264 // If the root changed (e.g. it was a dead load, update the root).
1265 DAG.setRoot(Dummy.getValue());
1266 DAG.RemoveDeadNodes();
1269 SDValue DAGCombiner::visit(SDNode *N) {
1270 switch (N->getOpcode()) {
1272 case ISD::TokenFactor: return visitTokenFactor(N);
1273 case ISD::MERGE_VALUES: return visitMERGE_VALUES(N);
1274 case ISD::ADD: return visitADD(N);
1275 case ISD::SUB: return visitSUB(N);
1276 case ISD::ADDC: return visitADDC(N);
1277 case ISD::SUBC: return visitSUBC(N);
1278 case ISD::ADDE: return visitADDE(N);
1279 case ISD::SUBE: return visitSUBE(N);
1280 case ISD::MUL: return visitMUL(N);
1281 case ISD::SDIV: return visitSDIV(N);
1282 case ISD::UDIV: return visitUDIV(N);
1283 case ISD::SREM: return visitSREM(N);
1284 case ISD::UREM: return visitUREM(N);
1285 case ISD::MULHU: return visitMULHU(N);
1286 case ISD::MULHS: return visitMULHS(N);
1287 case ISD::SMUL_LOHI: return visitSMUL_LOHI(N);
1288 case ISD::UMUL_LOHI: return visitUMUL_LOHI(N);
1289 case ISD::SMULO: return visitSMULO(N);
1290 case ISD::UMULO: return visitUMULO(N);
1291 case ISD::SDIVREM: return visitSDIVREM(N);
1292 case ISD::UDIVREM: return visitUDIVREM(N);
1293 case ISD::AND: return visitAND(N);
1294 case ISD::OR: return visitOR(N);
1295 case ISD::XOR: return visitXOR(N);
1296 case ISD::SHL: return visitSHL(N);
1297 case ISD::SRA: return visitSRA(N);
1298 case ISD::SRL: return visitSRL(N);
1300 case ISD::ROTL: return visitRotate(N);
1301 case ISD::CTLZ: return visitCTLZ(N);
1302 case ISD::CTLZ_ZERO_UNDEF: return visitCTLZ_ZERO_UNDEF(N);
1303 case ISD::CTTZ: return visitCTTZ(N);
1304 case ISD::CTTZ_ZERO_UNDEF: return visitCTTZ_ZERO_UNDEF(N);
1305 case ISD::CTPOP: return visitCTPOP(N);
1306 case ISD::SELECT: return visitSELECT(N);
1307 case ISD::VSELECT: return visitVSELECT(N);
1308 case ISD::SELECT_CC: return visitSELECT_CC(N);
1309 case ISD::SETCC: return visitSETCC(N);
1310 case ISD::SIGN_EXTEND: return visitSIGN_EXTEND(N);
1311 case ISD::ZERO_EXTEND: return visitZERO_EXTEND(N);
1312 case ISD::ANY_EXTEND: return visitANY_EXTEND(N);
1313 case ISD::SIGN_EXTEND_INREG: return visitSIGN_EXTEND_INREG(N);
1314 case ISD::TRUNCATE: return visitTRUNCATE(N);
1315 case ISD::BITCAST: return visitBITCAST(N);
1316 case ISD::BUILD_PAIR: return visitBUILD_PAIR(N);
1317 case ISD::FADD: return visitFADD(N);
1318 case ISD::FSUB: return visitFSUB(N);
1319 case ISD::FMUL: return visitFMUL(N);
1320 case ISD::FMA: return visitFMA(N);
1321 case ISD::FDIV: return visitFDIV(N);
1322 case ISD::FREM: return visitFREM(N);
1323 case ISD::FSQRT: return visitFSQRT(N);
1324 case ISD::FCOPYSIGN: return visitFCOPYSIGN(N);
1325 case ISD::SINT_TO_FP: return visitSINT_TO_FP(N);
1326 case ISD::UINT_TO_FP: return visitUINT_TO_FP(N);
1327 case ISD::FP_TO_SINT: return visitFP_TO_SINT(N);
1328 case ISD::FP_TO_UINT: return visitFP_TO_UINT(N);
1329 case ISD::FP_ROUND: return visitFP_ROUND(N);
1330 case ISD::FP_ROUND_INREG: return visitFP_ROUND_INREG(N);
1331 case ISD::FP_EXTEND: return visitFP_EXTEND(N);
1332 case ISD::FNEG: return visitFNEG(N);
1333 case ISD::FABS: return visitFABS(N);
1334 case ISD::FFLOOR: return visitFFLOOR(N);
1335 case ISD::FMINNUM: return visitFMINNUM(N);
1336 case ISD::FMAXNUM: return visitFMAXNUM(N);
1337 case ISD::FCEIL: return visitFCEIL(N);
1338 case ISD::FTRUNC: return visitFTRUNC(N);
1339 case ISD::BRCOND: return visitBRCOND(N);
1340 case ISD::BR_CC: return visitBR_CC(N);
1341 case ISD::LOAD: return visitLOAD(N);
1342 case ISD::STORE: return visitSTORE(N);
1343 case ISD::INSERT_VECTOR_ELT: return visitINSERT_VECTOR_ELT(N);
1344 case ISD::EXTRACT_VECTOR_ELT: return visitEXTRACT_VECTOR_ELT(N);
1345 case ISD::BUILD_VECTOR: return visitBUILD_VECTOR(N);
1346 case ISD::CONCAT_VECTORS: return visitCONCAT_VECTORS(N);
1347 case ISD::EXTRACT_SUBVECTOR: return visitEXTRACT_SUBVECTOR(N);
1348 case ISD::VECTOR_SHUFFLE: return visitVECTOR_SHUFFLE(N);
1349 case ISD::INSERT_SUBVECTOR: return visitINSERT_SUBVECTOR(N);
1354 SDValue DAGCombiner::combine(SDNode *N) {
1355 SDValue RV = visit(N);
1357 // If nothing happened, try a target-specific DAG combine.
1358 if (!RV.getNode()) {
1359 assert(N->getOpcode() != ISD::DELETED_NODE &&
1360 "Node was deleted but visit returned NULL!");
1362 if (N->getOpcode() >= ISD::BUILTIN_OP_END ||
1363 TLI.hasTargetDAGCombine((ISD::NodeType)N->getOpcode())) {
1365 // Expose the DAG combiner to the target combiner impls.
1366 TargetLowering::DAGCombinerInfo
1367 DagCombineInfo(DAG, Level, false, this);
1369 RV = TLI.PerformDAGCombine(N, DagCombineInfo);
1373 // If nothing happened still, try promoting the operation.
1374 if (!RV.getNode()) {
1375 switch (N->getOpcode()) {
1383 RV = PromoteIntBinOp(SDValue(N, 0));
1388 RV = PromoteIntShiftOp(SDValue(N, 0));
1390 case ISD::SIGN_EXTEND:
1391 case ISD::ZERO_EXTEND:
1392 case ISD::ANY_EXTEND:
1393 RV = PromoteExtend(SDValue(N, 0));
1396 if (PromoteLoad(SDValue(N, 0)))
1402 // If N is a commutative binary node, try commuting it to enable more
1404 if (!RV.getNode() && SelectionDAG::isCommutativeBinOp(N->getOpcode()) &&
1405 N->getNumValues() == 1) {
1406 SDValue N0 = N->getOperand(0);
1407 SDValue N1 = N->getOperand(1);
1409 // Constant operands are canonicalized to RHS.
1410 if (isa<ConstantSDNode>(N0) || !isa<ConstantSDNode>(N1)) {
1411 SDValue Ops[] = {N1, N0};
1413 if (const BinaryWithFlagsSDNode *BinNode =
1414 dyn_cast<BinaryWithFlagsSDNode>(N)) {
1415 CSENode = DAG.getNodeIfExists(
1416 N->getOpcode(), N->getVTList(), Ops, BinNode->hasNoUnsignedWrap(),
1417 BinNode->hasNoSignedWrap(), BinNode->isExact());
1419 CSENode = DAG.getNodeIfExists(N->getOpcode(), N->getVTList(), Ops);
1422 return SDValue(CSENode, 0);
1429 /// Given a node, return its input chain if it has one, otherwise return a null
1431 static SDValue getInputChainForNode(SDNode *N) {
1432 if (unsigned NumOps = N->getNumOperands()) {
1433 if (N->getOperand(0).getValueType() == MVT::Other)
1434 return N->getOperand(0);
1435 if (N->getOperand(NumOps-1).getValueType() == MVT::Other)
1436 return N->getOperand(NumOps-1);
1437 for (unsigned i = 1; i < NumOps-1; ++i)
1438 if (N->getOperand(i).getValueType() == MVT::Other)
1439 return N->getOperand(i);
1444 SDValue DAGCombiner::visitTokenFactor(SDNode *N) {
1445 // If N has two operands, where one has an input chain equal to the other,
1446 // the 'other' chain is redundant.
1447 if (N->getNumOperands() == 2) {
1448 if (getInputChainForNode(N->getOperand(0).getNode()) == N->getOperand(1))
1449 return N->getOperand(0);
1450 if (getInputChainForNode(N->getOperand(1).getNode()) == N->getOperand(0))
1451 return N->getOperand(1);
1454 SmallVector<SDNode *, 8> TFs; // List of token factors to visit.
1455 SmallVector<SDValue, 8> Ops; // Ops for replacing token factor.
1456 SmallPtrSet<SDNode*, 16> SeenOps;
1457 bool Changed = false; // If we should replace this token factor.
1459 // Start out with this token factor.
1462 // Iterate through token factors. The TFs grows when new token factors are
1464 for (unsigned i = 0; i < TFs.size(); ++i) {
1465 SDNode *TF = TFs[i];
1467 // Check each of the operands.
1468 for (unsigned i = 0, ie = TF->getNumOperands(); i != ie; ++i) {
1469 SDValue Op = TF->getOperand(i);
1471 switch (Op.getOpcode()) {
1472 case ISD::EntryToken:
1473 // Entry tokens don't need to be added to the list. They are
1478 case ISD::TokenFactor:
1479 if (Op.hasOneUse() &&
1480 std::find(TFs.begin(), TFs.end(), Op.getNode()) == TFs.end()) {
1481 // Queue up for processing.
1482 TFs.push_back(Op.getNode());
1483 // Clean up in case the token factor is removed.
1484 AddToWorklist(Op.getNode());
1491 // Only add if it isn't already in the list.
1492 if (SeenOps.insert(Op.getNode()))
1503 // If we've change things around then replace token factor.
1506 // The entry token is the only possible outcome.
1507 Result = DAG.getEntryNode();
1509 // New and improved token factor.
1510 Result = DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other, Ops);
1513 // Don't add users to work list.
1514 return CombineTo(N, Result, false);
1520 /// MERGE_VALUES can always be eliminated.
1521 SDValue DAGCombiner::visitMERGE_VALUES(SDNode *N) {
1522 WorklistRemover DeadNodes(*this);
1523 // Replacing results may cause a different MERGE_VALUES to suddenly
1524 // be CSE'd with N, and carry its uses with it. Iterate until no
1525 // uses remain, to ensure that the node can be safely deleted.
1526 // First add the users of this node to the work list so that they
1527 // can be tried again once they have new operands.
1528 AddUsersToWorklist(N);
1530 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1531 DAG.ReplaceAllUsesOfValueWith(SDValue(N, i), N->getOperand(i));
1532 } while (!N->use_empty());
1533 deleteAndRecombine(N);
1534 return SDValue(N, 0); // Return N so it doesn't get rechecked!
1537 SDValue DAGCombiner::visitADD(SDNode *N) {
1538 SDValue N0 = N->getOperand(0);
1539 SDValue N1 = N->getOperand(1);
1540 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1541 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1542 EVT VT = N0.getValueType();
1545 if (VT.isVector()) {
1546 SDValue FoldedVOp = SimplifyVBinOp(N);
1547 if (FoldedVOp.getNode()) return FoldedVOp;
1549 // fold (add x, 0) -> x, vector edition
1550 if (ISD::isBuildVectorAllZeros(N1.getNode()))
1552 if (ISD::isBuildVectorAllZeros(N0.getNode()))
1556 // fold (add x, undef) -> undef
1557 if (N0.getOpcode() == ISD::UNDEF)
1559 if (N1.getOpcode() == ISD::UNDEF)
1561 // fold (add c1, c2) -> c1+c2
1563 return DAG.FoldConstantArithmetic(ISD::ADD, VT, N0C, N1C);
1564 // canonicalize constant to RHS
1566 return DAG.getNode(ISD::ADD, SDLoc(N), VT, N1, N0);
1567 // fold (add x, 0) -> x
1568 if (N1C && N1C->isNullValue())
1570 // fold (add Sym, c) -> Sym+c
1571 if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N0))
1572 if (!LegalOperations && TLI.isOffsetFoldingLegal(GA) && N1C &&
1573 GA->getOpcode() == ISD::GlobalAddress)
1574 return DAG.getGlobalAddress(GA->getGlobal(), SDLoc(N1C), VT,
1576 (uint64_t)N1C->getSExtValue());
1577 // fold ((c1-A)+c2) -> (c1+c2)-A
1578 if (N1C && N0.getOpcode() == ISD::SUB)
1579 if (ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getOperand(0)))
1580 return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1581 DAG.getConstant(N1C->getAPIntValue()+
1582 N0C->getAPIntValue(), VT),
1585 SDValue RADD = ReassociateOps(ISD::ADD, SDLoc(N), N0, N1);
1588 // fold ((0-A) + B) -> B-A
1589 if (N0.getOpcode() == ISD::SUB && isa<ConstantSDNode>(N0.getOperand(0)) &&
1590 cast<ConstantSDNode>(N0.getOperand(0))->isNullValue())
1591 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1, N0.getOperand(1));
1592 // fold (A + (0-B)) -> A-B
1593 if (N1.getOpcode() == ISD::SUB && isa<ConstantSDNode>(N1.getOperand(0)) &&
1594 cast<ConstantSDNode>(N1.getOperand(0))->isNullValue())
1595 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, N1.getOperand(1));
1596 // fold (A+(B-A)) -> B
1597 if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(1))
1598 return N1.getOperand(0);
1599 // fold ((B-A)+A) -> B
1600 if (N0.getOpcode() == ISD::SUB && N1 == N0.getOperand(1))
1601 return N0.getOperand(0);
1602 // fold (A+(B-(A+C))) to (B-C)
1603 if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD &&
1604 N0 == N1.getOperand(1).getOperand(0))
1605 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1.getOperand(0),
1606 N1.getOperand(1).getOperand(1));
1607 // fold (A+(B-(C+A))) to (B-C)
1608 if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD &&
1609 N0 == N1.getOperand(1).getOperand(1))
1610 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1.getOperand(0),
1611 N1.getOperand(1).getOperand(0));
1612 // fold (A+((B-A)+or-C)) to (B+or-C)
1613 if ((N1.getOpcode() == ISD::SUB || N1.getOpcode() == ISD::ADD) &&
1614 N1.getOperand(0).getOpcode() == ISD::SUB &&
1615 N0 == N1.getOperand(0).getOperand(1))
1616 return DAG.getNode(N1.getOpcode(), SDLoc(N), VT,
1617 N1.getOperand(0).getOperand(0), N1.getOperand(1));
1619 // fold (A-B)+(C-D) to (A+C)-(B+D) when A or C is constant
1620 if (N0.getOpcode() == ISD::SUB && N1.getOpcode() == ISD::SUB) {
1621 SDValue N00 = N0.getOperand(0);
1622 SDValue N01 = N0.getOperand(1);
1623 SDValue N10 = N1.getOperand(0);
1624 SDValue N11 = N1.getOperand(1);
1626 if (isa<ConstantSDNode>(N00) || isa<ConstantSDNode>(N10))
1627 return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1628 DAG.getNode(ISD::ADD, SDLoc(N0), VT, N00, N10),
1629 DAG.getNode(ISD::ADD, SDLoc(N1), VT, N01, N11));
1632 if (!VT.isVector() && SimplifyDemandedBits(SDValue(N, 0)))
1633 return SDValue(N, 0);
1635 // fold (a+b) -> (a|b) iff a and b share no bits.
1636 if (VT.isInteger() && !VT.isVector()) {
1637 APInt LHSZero, LHSOne;
1638 APInt RHSZero, RHSOne;
1639 DAG.computeKnownBits(N0, LHSZero, LHSOne);
1641 if (LHSZero.getBoolValue()) {
1642 DAG.computeKnownBits(N1, RHSZero, RHSOne);
1644 // If all possibly-set bits on the LHS are clear on the RHS, return an OR.
1645 // If all possibly-set bits on the RHS are clear on the LHS, return an OR.
1646 if ((RHSZero & ~LHSZero) == ~LHSZero || (LHSZero & ~RHSZero) == ~RHSZero){
1647 if (!LegalOperations || TLI.isOperationLegal(ISD::OR, VT))
1648 return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N1);
1653 // fold (add x, shl(0 - y, n)) -> sub(x, shl(y, n))
1654 if (N1.getOpcode() == ISD::SHL &&
1655 N1.getOperand(0).getOpcode() == ISD::SUB)
1656 if (ConstantSDNode *C =
1657 dyn_cast<ConstantSDNode>(N1.getOperand(0).getOperand(0)))
1658 if (C->getAPIntValue() == 0)
1659 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N0,
1660 DAG.getNode(ISD::SHL, SDLoc(N), VT,
1661 N1.getOperand(0).getOperand(1),
1663 if (N0.getOpcode() == ISD::SHL &&
1664 N0.getOperand(0).getOpcode() == ISD::SUB)
1665 if (ConstantSDNode *C =
1666 dyn_cast<ConstantSDNode>(N0.getOperand(0).getOperand(0)))
1667 if (C->getAPIntValue() == 0)
1668 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1,
1669 DAG.getNode(ISD::SHL, SDLoc(N), VT,
1670 N0.getOperand(0).getOperand(1),
1673 if (N1.getOpcode() == ISD::AND) {
1674 SDValue AndOp0 = N1.getOperand(0);
1675 ConstantSDNode *AndOp1 = dyn_cast<ConstantSDNode>(N1->getOperand(1));
1676 unsigned NumSignBits = DAG.ComputeNumSignBits(AndOp0);
1677 unsigned DestBits = VT.getScalarType().getSizeInBits();
1679 // (add z, (and (sbbl x, x), 1)) -> (sub z, (sbbl x, x))
1680 // and similar xforms where the inner op is either ~0 or 0.
1681 if (NumSignBits == DestBits && AndOp1 && AndOp1->isOne()) {
1683 return DAG.getNode(ISD::SUB, DL, VT, N->getOperand(0), AndOp0);
1687 // add (sext i1), X -> sub X, (zext i1)
1688 if (N0.getOpcode() == ISD::SIGN_EXTEND &&
1689 N0.getOperand(0).getValueType() == MVT::i1 &&
1690 !TLI.isOperationLegal(ISD::SIGN_EXTEND, MVT::i1)) {
1692 SDValue ZExt = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0));
1693 return DAG.getNode(ISD::SUB, DL, VT, N1, ZExt);
1696 // add X, (sextinreg Y i1) -> sub X, (and Y 1)
1697 if (N1.getOpcode() == ISD::SIGN_EXTEND_INREG) {
1698 VTSDNode *TN = cast<VTSDNode>(N1.getOperand(1));
1699 if (TN->getVT() == MVT::i1) {
1701 SDValue ZExt = DAG.getNode(ISD::AND, DL, VT, N1.getOperand(0),
1702 DAG.getConstant(1, VT));
1703 return DAG.getNode(ISD::SUB, DL, VT, N0, ZExt);
1710 SDValue DAGCombiner::visitADDC(SDNode *N) {
1711 SDValue N0 = N->getOperand(0);
1712 SDValue N1 = N->getOperand(1);
1713 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1714 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1715 EVT VT = N0.getValueType();
1717 // If the flag result is dead, turn this into an ADD.
1718 if (!N->hasAnyUseOfValue(1))
1719 return CombineTo(N, DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, N1),
1720 DAG.getNode(ISD::CARRY_FALSE,
1721 SDLoc(N), MVT::Glue));
1723 // canonicalize constant to RHS.
1725 return DAG.getNode(ISD::ADDC, SDLoc(N), N->getVTList(), N1, N0);
1727 // fold (addc x, 0) -> x + no carry out
1728 if (N1C && N1C->isNullValue())
1729 return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE,
1730 SDLoc(N), MVT::Glue));
1732 // fold (addc a, b) -> (or a, b), CARRY_FALSE iff a and b share no bits.
1733 APInt LHSZero, LHSOne;
1734 APInt RHSZero, RHSOne;
1735 DAG.computeKnownBits(N0, LHSZero, LHSOne);
1737 if (LHSZero.getBoolValue()) {
1738 DAG.computeKnownBits(N1, RHSZero, RHSOne);
1740 // If all possibly-set bits on the LHS are clear on the RHS, return an OR.
1741 // If all possibly-set bits on the RHS are clear on the LHS, return an OR.
1742 if ((RHSZero & ~LHSZero) == ~LHSZero || (LHSZero & ~RHSZero) == ~RHSZero)
1743 return CombineTo(N, DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N1),
1744 DAG.getNode(ISD::CARRY_FALSE,
1745 SDLoc(N), MVT::Glue));
1751 SDValue DAGCombiner::visitADDE(SDNode *N) {
1752 SDValue N0 = N->getOperand(0);
1753 SDValue N1 = N->getOperand(1);
1754 SDValue CarryIn = N->getOperand(2);
1755 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1756 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1758 // canonicalize constant to RHS
1760 return DAG.getNode(ISD::ADDE, SDLoc(N), N->getVTList(),
1763 // fold (adde x, y, false) -> (addc x, y)
1764 if (CarryIn.getOpcode() == ISD::CARRY_FALSE)
1765 return DAG.getNode(ISD::ADDC, SDLoc(N), N->getVTList(), N0, N1);
1770 // Since it may not be valid to emit a fold to zero for vector initializers
1771 // check if we can before folding.
1772 static SDValue tryFoldToZero(SDLoc DL, const TargetLowering &TLI, EVT VT,
1774 bool LegalOperations, bool LegalTypes) {
1776 return DAG.getConstant(0, VT);
1777 if (!LegalOperations || TLI.isOperationLegal(ISD::BUILD_VECTOR, VT))
1778 return DAG.getConstant(0, VT);
1782 SDValue DAGCombiner::visitSUB(SDNode *N) {
1783 SDValue N0 = N->getOperand(0);
1784 SDValue N1 = N->getOperand(1);
1785 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getNode());
1786 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
1787 ConstantSDNode *N1C1 = N1.getOpcode() != ISD::ADD ? nullptr :
1788 dyn_cast<ConstantSDNode>(N1.getOperand(1).getNode());
1789 EVT VT = N0.getValueType();
1792 if (VT.isVector()) {
1793 SDValue FoldedVOp = SimplifyVBinOp(N);
1794 if (FoldedVOp.getNode()) return FoldedVOp;
1796 // fold (sub x, 0) -> x, vector edition
1797 if (ISD::isBuildVectorAllZeros(N1.getNode()))
1801 // fold (sub x, x) -> 0
1802 // FIXME: Refactor this and xor and other similar operations together.
1804 return tryFoldToZero(SDLoc(N), TLI, VT, DAG, LegalOperations, LegalTypes);
1805 // fold (sub c1, c2) -> c1-c2
1807 return DAG.FoldConstantArithmetic(ISD::SUB, VT, N0C, N1C);
1808 // fold (sub x, c) -> (add x, -c)
1810 return DAG.getNode(ISD::ADD, SDLoc(N), VT, N0,
1811 DAG.getConstant(-N1C->getAPIntValue(), VT));
1812 // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1)
1813 if (N0C && N0C->isAllOnesValue())
1814 return DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0);
1815 // fold A-(A-B) -> B
1816 if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(0))
1817 return N1.getOperand(1);
1818 // fold (A+B)-A -> B
1819 if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1)
1820 return N0.getOperand(1);
1821 // fold (A+B)-B -> A
1822 if (N0.getOpcode() == ISD::ADD && N0.getOperand(1) == N1)
1823 return N0.getOperand(0);
1824 // fold C2-(A+C1) -> (C2-C1)-A
1825 if (N1.getOpcode() == ISD::ADD && N0C && N1C1) {
1826 SDValue NewC = DAG.getConstant(N0C->getAPIntValue() - N1C1->getAPIntValue(),
1828 return DAG.getNode(ISD::SUB, SDLoc(N), VT, NewC,
1831 // fold ((A+(B+or-C))-B) -> A+or-C
1832 if (N0.getOpcode() == ISD::ADD &&
1833 (N0.getOperand(1).getOpcode() == ISD::SUB ||
1834 N0.getOperand(1).getOpcode() == ISD::ADD) &&
1835 N0.getOperand(1).getOperand(0) == N1)
1836 return DAG.getNode(N0.getOperand(1).getOpcode(), SDLoc(N), VT,
1837 N0.getOperand(0), N0.getOperand(1).getOperand(1));
1838 // fold ((A+(C+B))-B) -> A+C
1839 if (N0.getOpcode() == ISD::ADD &&
1840 N0.getOperand(1).getOpcode() == ISD::ADD &&
1841 N0.getOperand(1).getOperand(1) == N1)
1842 return DAG.getNode(ISD::ADD, SDLoc(N), VT,
1843 N0.getOperand(0), N0.getOperand(1).getOperand(0));
1844 // fold ((A-(B-C))-C) -> A-B
1845 if (N0.getOpcode() == ISD::SUB &&
1846 N0.getOperand(1).getOpcode() == ISD::SUB &&
1847 N0.getOperand(1).getOperand(1) == N1)
1848 return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1849 N0.getOperand(0), N0.getOperand(1).getOperand(0));
1851 // If either operand of a sub is undef, the result is undef
1852 if (N0.getOpcode() == ISD::UNDEF)
1854 if (N1.getOpcode() == ISD::UNDEF)
1857 // If the relocation model supports it, consider symbol offsets.
1858 if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N0))
1859 if (!LegalOperations && TLI.isOffsetFoldingLegal(GA)) {
1860 // fold (sub Sym, c) -> Sym-c
1861 if (N1C && GA->getOpcode() == ISD::GlobalAddress)
1862 return DAG.getGlobalAddress(GA->getGlobal(), SDLoc(N1C), VT,
1864 (uint64_t)N1C->getSExtValue());
1865 // fold (sub Sym+c1, Sym+c2) -> c1-c2
1866 if (GlobalAddressSDNode *GB = dyn_cast<GlobalAddressSDNode>(N1))
1867 if (GA->getGlobal() == GB->getGlobal())
1868 return DAG.getConstant((uint64_t)GA->getOffset() - GB->getOffset(),
1872 // sub X, (sextinreg Y i1) -> add X, (and Y 1)
1873 if (N1.getOpcode() == ISD::SIGN_EXTEND_INREG) {
1874 VTSDNode *TN = cast<VTSDNode>(N1.getOperand(1));
1875 if (TN->getVT() == MVT::i1) {
1877 SDValue ZExt = DAG.getNode(ISD::AND, DL, VT, N1.getOperand(0),
1878 DAG.getConstant(1, VT));
1879 return DAG.getNode(ISD::ADD, DL, VT, N0, ZExt);
1886 SDValue DAGCombiner::visitSUBC(SDNode *N) {
1887 SDValue N0 = N->getOperand(0);
1888 SDValue N1 = N->getOperand(1);
1889 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1890 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1891 EVT VT = N0.getValueType();
1893 // If the flag result is dead, turn this into an SUB.
1894 if (!N->hasAnyUseOfValue(1))
1895 return CombineTo(N, DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, N1),
1896 DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
1899 // fold (subc x, x) -> 0 + no borrow
1901 return CombineTo(N, DAG.getConstant(0, VT),
1902 DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
1905 // fold (subc x, 0) -> x + no borrow
1906 if (N1C && N1C->isNullValue())
1907 return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
1910 // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1) + no borrow
1911 if (N0C && N0C->isAllOnesValue())
1912 return CombineTo(N, DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0),
1913 DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
1919 SDValue DAGCombiner::visitSUBE(SDNode *N) {
1920 SDValue N0 = N->getOperand(0);
1921 SDValue N1 = N->getOperand(1);
1922 SDValue CarryIn = N->getOperand(2);
1924 // fold (sube x, y, false) -> (subc x, y)
1925 if (CarryIn.getOpcode() == ISD::CARRY_FALSE)
1926 return DAG.getNode(ISD::SUBC, SDLoc(N), N->getVTList(), N0, N1);
1931 SDValue DAGCombiner::visitMUL(SDNode *N) {
1932 SDValue N0 = N->getOperand(0);
1933 SDValue N1 = N->getOperand(1);
1934 EVT VT = N0.getValueType();
1936 // fold (mul x, undef) -> 0
1937 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
1938 return DAG.getConstant(0, VT);
1940 bool N0IsConst = false;
1941 bool N1IsConst = false;
1942 APInt ConstValue0, ConstValue1;
1944 if (VT.isVector()) {
1945 SDValue FoldedVOp = SimplifyVBinOp(N);
1946 if (FoldedVOp.getNode()) return FoldedVOp;
1948 N0IsConst = isConstantSplatVector(N0.getNode(), ConstValue0);
1949 N1IsConst = isConstantSplatVector(N1.getNode(), ConstValue1);
1951 N0IsConst = dyn_cast<ConstantSDNode>(N0) != nullptr;
1952 ConstValue0 = N0IsConst ? (dyn_cast<ConstantSDNode>(N0))->getAPIntValue()
1954 N1IsConst = dyn_cast<ConstantSDNode>(N1) != nullptr;
1955 ConstValue1 = N1IsConst ? (dyn_cast<ConstantSDNode>(N1))->getAPIntValue()
1959 // fold (mul c1, c2) -> c1*c2
1960 if (N0IsConst && N1IsConst)
1961 return DAG.FoldConstantArithmetic(ISD::MUL, VT, N0.getNode(), N1.getNode());
1963 // canonicalize constant to RHS
1964 if (N0IsConst && !N1IsConst)
1965 return DAG.getNode(ISD::MUL, SDLoc(N), VT, N1, N0);
1966 // fold (mul x, 0) -> 0
1967 if (N1IsConst && ConstValue1 == 0)
1969 // We require a splat of the entire scalar bit width for non-contiguous
1972 ConstValue1.getBitWidth() == VT.getScalarType().getSizeInBits();
1973 // fold (mul x, 1) -> x
1974 if (N1IsConst && ConstValue1 == 1 && IsFullSplat)
1976 // fold (mul x, -1) -> 0-x
1977 if (N1IsConst && ConstValue1.isAllOnesValue())
1978 return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1979 DAG.getConstant(0, VT), N0);
1980 // fold (mul x, (1 << c)) -> x << c
1981 if (N1IsConst && ConstValue1.isPowerOf2() && IsFullSplat)
1982 return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0,
1983 DAG.getConstant(ConstValue1.logBase2(),
1984 getShiftAmountTy(N0.getValueType())));
1985 // fold (mul x, -(1 << c)) -> -(x << c) or (-x) << c
1986 if (N1IsConst && (-ConstValue1).isPowerOf2() && IsFullSplat) {
1987 unsigned Log2Val = (-ConstValue1).logBase2();
1988 // FIXME: If the input is something that is easily negated (e.g. a
1989 // single-use add), we should put the negate there.
1990 return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1991 DAG.getConstant(0, VT),
1992 DAG.getNode(ISD::SHL, SDLoc(N), VT, N0,
1993 DAG.getConstant(Log2Val,
1994 getShiftAmountTy(N0.getValueType()))));
1998 // (mul (shl X, c1), c2) -> (mul X, c2 << c1)
1999 if (N1IsConst && N0.getOpcode() == ISD::SHL &&
2000 (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
2001 isa<ConstantSDNode>(N0.getOperand(1)))) {
2002 SDValue C3 = DAG.getNode(ISD::SHL, SDLoc(N), VT,
2003 N1, N0.getOperand(1));
2004 AddToWorklist(C3.getNode());
2005 return DAG.getNode(ISD::MUL, SDLoc(N), VT,
2006 N0.getOperand(0), C3);
2009 // Change (mul (shl X, C), Y) -> (shl (mul X, Y), C) when the shift has one
2012 SDValue Sh(nullptr,0), Y(nullptr,0);
2013 // Check for both (mul (shl X, C), Y) and (mul Y, (shl X, C)).
2014 if (N0.getOpcode() == ISD::SHL &&
2015 (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
2016 isa<ConstantSDNode>(N0.getOperand(1))) &&
2017 N0.getNode()->hasOneUse()) {
2019 } else if (N1.getOpcode() == ISD::SHL &&
2020 isa<ConstantSDNode>(N1.getOperand(1)) &&
2021 N1.getNode()->hasOneUse()) {
2026 SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT,
2027 Sh.getOperand(0), Y);
2028 return DAG.getNode(ISD::SHL, SDLoc(N), VT,
2029 Mul, Sh.getOperand(1));
2033 // fold (mul (add x, c1), c2) -> (add (mul x, c2), c1*c2)
2034 if (N1IsConst && N0.getOpcode() == ISD::ADD && N0.getNode()->hasOneUse() &&
2035 (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
2036 isa<ConstantSDNode>(N0.getOperand(1))))
2037 return DAG.getNode(ISD::ADD, SDLoc(N), VT,
2038 DAG.getNode(ISD::MUL, SDLoc(N0), VT,
2039 N0.getOperand(0), N1),
2040 DAG.getNode(ISD::MUL, SDLoc(N1), VT,
2041 N0.getOperand(1), N1));
2044 SDValue RMUL = ReassociateOps(ISD::MUL, SDLoc(N), N0, N1);
2051 SDValue DAGCombiner::visitSDIV(SDNode *N) {
2052 SDValue N0 = N->getOperand(0);
2053 SDValue N1 = N->getOperand(1);
2054 ConstantSDNode *N0C = isConstOrConstSplat(N0);
2055 ConstantSDNode *N1C = isConstOrConstSplat(N1);
2056 EVT VT = N->getValueType(0);
2059 if (VT.isVector()) {
2060 SDValue FoldedVOp = SimplifyVBinOp(N);
2061 if (FoldedVOp.getNode()) return FoldedVOp;
2064 // fold (sdiv c1, c2) -> c1/c2
2065 if (N0C && N1C && !N1C->isNullValue())
2066 return DAG.FoldConstantArithmetic(ISD::SDIV, VT, N0C, N1C);
2067 // fold (sdiv X, 1) -> X
2068 if (N1C && N1C->getAPIntValue() == 1LL)
2070 // fold (sdiv X, -1) -> 0-X
2071 if (N1C && N1C->isAllOnesValue())
2072 return DAG.getNode(ISD::SUB, SDLoc(N), VT,
2073 DAG.getConstant(0, VT), N0);
2074 // If we know the sign bits of both operands are zero, strength reduce to a
2075 // udiv instead. Handles (X&15) /s 4 -> X&15 >> 2
2076 if (!VT.isVector()) {
2077 if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
2078 return DAG.getNode(ISD::UDIV, SDLoc(N), N1.getValueType(),
2082 // fold (sdiv X, pow2) -> simple ops after legalize
2083 if (N1C && !N1C->isNullValue() && (N1C->getAPIntValue().isPowerOf2() ||
2084 (-N1C->getAPIntValue()).isPowerOf2())) {
2085 // If dividing by powers of two is cheap, then don't perform the following
2087 if (TLI.isPow2SDivCheap())
2090 // Target-specific implementation of sdiv x, pow2.
2091 SDValue Res = BuildSDIVPow2(N);
2095 unsigned lg2 = N1C->getAPIntValue().countTrailingZeros();
2097 // Splat the sign bit into the register
2099 DAG.getNode(ISD::SRA, SDLoc(N), VT, N0,
2100 DAG.getConstant(VT.getScalarSizeInBits() - 1,
2101 getShiftAmountTy(N0.getValueType())));
2102 AddToWorklist(SGN.getNode());
2104 // Add (N0 < 0) ? abs2 - 1 : 0;
2106 DAG.getNode(ISD::SRL, SDLoc(N), VT, SGN,
2107 DAG.getConstant(VT.getScalarSizeInBits() - lg2,
2108 getShiftAmountTy(SGN.getValueType())));
2109 SDValue ADD = DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, SRL);
2110 AddToWorklist(SRL.getNode());
2111 AddToWorklist(ADD.getNode()); // Divide by pow2
2112 SDValue SRA = DAG.getNode(ISD::SRA, SDLoc(N), VT, ADD,
2113 DAG.getConstant(lg2, getShiftAmountTy(ADD.getValueType())));
2115 // If we're dividing by a positive value, we're done. Otherwise, we must
2116 // negate the result.
2117 if (N1C->getAPIntValue().isNonNegative())
2120 AddToWorklist(SRA.getNode());
2121 return DAG.getNode(ISD::SUB, SDLoc(N), VT, DAG.getConstant(0, VT), SRA);
2124 // if integer divide is expensive and we satisfy the requirements, emit an
2125 // alternate sequence.
2126 if (N1C && !TLI.isIntDivCheap()) {
2127 SDValue Op = BuildSDIV(N);
2128 if (Op.getNode()) return Op;
2132 if (N0.getOpcode() == ISD::UNDEF)
2133 return DAG.getConstant(0, VT);
2134 // X / undef -> undef
2135 if (N1.getOpcode() == ISD::UNDEF)
2141 SDValue DAGCombiner::visitUDIV(SDNode *N) {
2142 SDValue N0 = N->getOperand(0);
2143 SDValue N1 = N->getOperand(1);
2144 ConstantSDNode *N0C = isConstOrConstSplat(N0);
2145 ConstantSDNode *N1C = isConstOrConstSplat(N1);
2146 EVT VT = N->getValueType(0);
2149 if (VT.isVector()) {
2150 SDValue FoldedVOp = SimplifyVBinOp(N);
2151 if (FoldedVOp.getNode()) return FoldedVOp;
2154 // fold (udiv c1, c2) -> c1/c2
2155 if (N0C && N1C && !N1C->isNullValue())
2156 return DAG.FoldConstantArithmetic(ISD::UDIV, VT, N0C, N1C);
2157 // fold (udiv x, (1 << c)) -> x >>u c
2158 if (N1C && N1C->getAPIntValue().isPowerOf2())
2159 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0,
2160 DAG.getConstant(N1C->getAPIntValue().logBase2(),
2161 getShiftAmountTy(N0.getValueType())));
2162 // fold (udiv x, (shl c, y)) -> x >>u (log2(c)+y) iff c is power of 2
2163 if (N1.getOpcode() == ISD::SHL) {
2164 if (ConstantSDNode *SHC = dyn_cast<ConstantSDNode>(N1.getOperand(0))) {
2165 if (SHC->getAPIntValue().isPowerOf2()) {
2166 EVT ADDVT = N1.getOperand(1).getValueType();
2167 SDValue Add = DAG.getNode(ISD::ADD, SDLoc(N), ADDVT,
2169 DAG.getConstant(SHC->getAPIntValue()
2172 AddToWorklist(Add.getNode());
2173 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, Add);
2177 // fold (udiv x, c) -> alternate
2178 if (N1C && !TLI.isIntDivCheap()) {
2179 SDValue Op = BuildUDIV(N);
2180 if (Op.getNode()) return Op;
2184 if (N0.getOpcode() == ISD::UNDEF)
2185 return DAG.getConstant(0, VT);
2186 // X / undef -> undef
2187 if (N1.getOpcode() == ISD::UNDEF)
2193 SDValue DAGCombiner::visitSREM(SDNode *N) {
2194 SDValue N0 = N->getOperand(0);
2195 SDValue N1 = N->getOperand(1);
2196 ConstantSDNode *N0C = isConstOrConstSplat(N0);
2197 ConstantSDNode *N1C = isConstOrConstSplat(N1);
2198 EVT VT = N->getValueType(0);
2200 // fold (srem c1, c2) -> c1%c2
2201 if (N0C && N1C && !N1C->isNullValue())
2202 return DAG.FoldConstantArithmetic(ISD::SREM, VT, N0C, N1C);
2203 // If we know the sign bits of both operands are zero, strength reduce to a
2204 // urem instead. Handles (X & 0x0FFFFFFF) %s 16 -> X&15
2205 if (!VT.isVector()) {
2206 if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
2207 return DAG.getNode(ISD::UREM, SDLoc(N), VT, N0, N1);
2210 // If X/C can be simplified by the division-by-constant logic, lower
2211 // X%C to the equivalent of X-X/C*C.
2212 if (N1C && !N1C->isNullValue()) {
2213 SDValue Div = DAG.getNode(ISD::SDIV, SDLoc(N), VT, N0, N1);
2214 AddToWorklist(Div.getNode());
2215 SDValue OptimizedDiv = combine(Div.getNode());
2216 if (OptimizedDiv.getNode() && OptimizedDiv.getNode() != Div.getNode()) {
2217 SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT,
2219 SDValue Sub = DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, Mul);
2220 AddToWorklist(Mul.getNode());
2226 if (N0.getOpcode() == ISD::UNDEF)
2227 return DAG.getConstant(0, VT);
2228 // X % undef -> undef
2229 if (N1.getOpcode() == ISD::UNDEF)
2235 SDValue DAGCombiner::visitUREM(SDNode *N) {
2236 SDValue N0 = N->getOperand(0);
2237 SDValue N1 = N->getOperand(1);
2238 ConstantSDNode *N0C = isConstOrConstSplat(N0);
2239 ConstantSDNode *N1C = isConstOrConstSplat(N1);
2240 EVT VT = N->getValueType(0);
2242 // fold (urem c1, c2) -> c1%c2
2243 if (N0C && N1C && !N1C->isNullValue())
2244 return DAG.FoldConstantArithmetic(ISD::UREM, VT, N0C, N1C);
2245 // fold (urem x, pow2) -> (and x, pow2-1)
2246 if (N1C && !N1C->isNullValue() && N1C->getAPIntValue().isPowerOf2())
2247 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0,
2248 DAG.getConstant(N1C->getAPIntValue()-1,VT));
2249 // fold (urem x, (shl pow2, y)) -> (and x, (add (shl pow2, y), -1))
2250 if (N1.getOpcode() == ISD::SHL) {
2251 if (ConstantSDNode *SHC = dyn_cast<ConstantSDNode>(N1.getOperand(0))) {
2252 if (SHC->getAPIntValue().isPowerOf2()) {
2254 DAG.getNode(ISD::ADD, SDLoc(N), VT, N1,
2255 DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()),
2257 AddToWorklist(Add.getNode());
2258 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, Add);
2263 // If X/C can be simplified by the division-by-constant logic, lower
2264 // X%C to the equivalent of X-X/C*C.
2265 if (N1C && !N1C->isNullValue()) {
2266 SDValue Div = DAG.getNode(ISD::UDIV, SDLoc(N), VT, N0, N1);
2267 AddToWorklist(Div.getNode());
2268 SDValue OptimizedDiv = combine(Div.getNode());
2269 if (OptimizedDiv.getNode() && OptimizedDiv.getNode() != Div.getNode()) {
2270 SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT,
2272 SDValue Sub = DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, Mul);
2273 AddToWorklist(Mul.getNode());
2279 if (N0.getOpcode() == ISD::UNDEF)
2280 return DAG.getConstant(0, VT);
2281 // X % undef -> undef
2282 if (N1.getOpcode() == ISD::UNDEF)
2288 SDValue DAGCombiner::visitMULHS(SDNode *N) {
2289 SDValue N0 = N->getOperand(0);
2290 SDValue N1 = N->getOperand(1);
2291 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2292 EVT VT = N->getValueType(0);
2295 // fold (mulhs x, 0) -> 0
2296 if (N1C && N1C->isNullValue())
2298 // fold (mulhs x, 1) -> (sra x, size(x)-1)
2299 if (N1C && N1C->getAPIntValue() == 1)
2300 return DAG.getNode(ISD::SRA, SDLoc(N), N0.getValueType(), N0,
2301 DAG.getConstant(N0.getValueType().getSizeInBits() - 1,
2302 getShiftAmountTy(N0.getValueType())));
2303 // fold (mulhs x, undef) -> 0
2304 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2305 return DAG.getConstant(0, VT);
2307 // If the type twice as wide is legal, transform the mulhs to a wider multiply
2309 if (VT.isSimple() && !VT.isVector()) {
2310 MVT Simple = VT.getSimpleVT();
2311 unsigned SimpleSize = Simple.getSizeInBits();
2312 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2313 if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2314 N0 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N0);
2315 N1 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N1);
2316 N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1);
2317 N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1,
2318 DAG.getConstant(SimpleSize, getShiftAmountTy(N1.getValueType())));
2319 return DAG.getNode(ISD::TRUNCATE, DL, VT, N1);
2326 SDValue DAGCombiner::visitMULHU(SDNode *N) {
2327 SDValue N0 = N->getOperand(0);
2328 SDValue N1 = N->getOperand(1);
2329 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2330 EVT VT = N->getValueType(0);
2333 // fold (mulhu x, 0) -> 0
2334 if (N1C && N1C->isNullValue())
2336 // fold (mulhu x, 1) -> 0
2337 if (N1C && N1C->getAPIntValue() == 1)
2338 return DAG.getConstant(0, N0.getValueType());
2339 // fold (mulhu x, undef) -> 0
2340 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2341 return DAG.getConstant(0, VT);
2343 // If the type twice as wide is legal, transform the mulhu to a wider multiply
2345 if (VT.isSimple() && !VT.isVector()) {
2346 MVT Simple = VT.getSimpleVT();
2347 unsigned SimpleSize = Simple.getSizeInBits();
2348 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2349 if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2350 N0 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N0);
2351 N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N1);
2352 N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1);
2353 N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1,
2354 DAG.getConstant(SimpleSize, getShiftAmountTy(N1.getValueType())));
2355 return DAG.getNode(ISD::TRUNCATE, DL, VT, N1);
2362 /// Perform optimizations common to nodes that compute two values. LoOp and HiOp
2363 /// give the opcodes for the two computations that are being performed. Return
2364 /// true if a simplification was made.
2365 SDValue DAGCombiner::SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp,
2367 // If the high half is not needed, just compute the low half.
2368 bool HiExists = N->hasAnyUseOfValue(1);
2370 (!LegalOperations ||
2371 TLI.isOperationLegalOrCustom(LoOp, N->getValueType(0)))) {
2372 SDValue Res = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0), N->ops());
2373 return CombineTo(N, Res, Res);
2376 // If the low half is not needed, just compute the high half.
2377 bool LoExists = N->hasAnyUseOfValue(0);
2379 (!LegalOperations ||
2380 TLI.isOperationLegal(HiOp, N->getValueType(1)))) {
2381 SDValue Res = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1), N->ops());
2382 return CombineTo(N, Res, Res);
2385 // If both halves are used, return as it is.
2386 if (LoExists && HiExists)
2389 // If the two computed results can be simplified separately, separate them.
2391 SDValue Lo = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0), N->ops());
2392 AddToWorklist(Lo.getNode());
2393 SDValue LoOpt = combine(Lo.getNode());
2394 if (LoOpt.getNode() && LoOpt.getNode() != Lo.getNode() &&
2395 (!LegalOperations ||
2396 TLI.isOperationLegal(LoOpt.getOpcode(), LoOpt.getValueType())))
2397 return CombineTo(N, LoOpt, LoOpt);
2401 SDValue Hi = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1), N->ops());
2402 AddToWorklist(Hi.getNode());
2403 SDValue HiOpt = combine(Hi.getNode());
2404 if (HiOpt.getNode() && HiOpt != Hi &&
2405 (!LegalOperations ||
2406 TLI.isOperationLegal(HiOpt.getOpcode(), HiOpt.getValueType())))
2407 return CombineTo(N, HiOpt, HiOpt);
2413 SDValue DAGCombiner::visitSMUL_LOHI(SDNode *N) {
2414 SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHS);
2415 if (Res.getNode()) return Res;
2417 EVT VT = N->getValueType(0);
2420 // If the type twice as wide is legal, transform the mulhu to a wider multiply
2422 if (VT.isSimple() && !VT.isVector()) {
2423 MVT Simple = VT.getSimpleVT();
2424 unsigned SimpleSize = Simple.getSizeInBits();
2425 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2426 if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2427 SDValue Lo = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(0));
2428 SDValue Hi = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(1));
2429 Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi);
2430 // Compute the high part as N1.
2431 Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo,
2432 DAG.getConstant(SimpleSize, getShiftAmountTy(Lo.getValueType())));
2433 Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi);
2434 // Compute the low part as N0.
2435 Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo);
2436 return CombineTo(N, Lo, Hi);
2443 SDValue DAGCombiner::visitUMUL_LOHI(SDNode *N) {
2444 SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHU);
2445 if (Res.getNode()) return Res;
2447 EVT VT = N->getValueType(0);
2450 // If the type twice as wide is legal, transform the mulhu to a wider multiply
2452 if (VT.isSimple() && !VT.isVector()) {
2453 MVT Simple = VT.getSimpleVT();
2454 unsigned SimpleSize = Simple.getSizeInBits();
2455 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2456 if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2457 SDValue Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(0));
2458 SDValue Hi = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(1));
2459 Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi);
2460 // Compute the high part as N1.
2461 Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo,
2462 DAG.getConstant(SimpleSize, getShiftAmountTy(Lo.getValueType())));
2463 Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi);
2464 // Compute the low part as N0.
2465 Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo);
2466 return CombineTo(N, Lo, Hi);
2473 SDValue DAGCombiner::visitSMULO(SDNode *N) {
2474 // (smulo x, 2) -> (saddo x, x)
2475 if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1)))
2476 if (C2->getAPIntValue() == 2)
2477 return DAG.getNode(ISD::SADDO, SDLoc(N), N->getVTList(),
2478 N->getOperand(0), N->getOperand(0));
2483 SDValue DAGCombiner::visitUMULO(SDNode *N) {
2484 // (umulo x, 2) -> (uaddo x, x)
2485 if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1)))
2486 if (C2->getAPIntValue() == 2)
2487 return DAG.getNode(ISD::UADDO, SDLoc(N), N->getVTList(),
2488 N->getOperand(0), N->getOperand(0));
2493 SDValue DAGCombiner::visitSDIVREM(SDNode *N) {
2494 SDValue Res = SimplifyNodeWithTwoResults(N, ISD::SDIV, ISD::SREM);
2495 if (Res.getNode()) return Res;
2500 SDValue DAGCombiner::visitUDIVREM(SDNode *N) {
2501 SDValue Res = SimplifyNodeWithTwoResults(N, ISD::UDIV, ISD::UREM);
2502 if (Res.getNode()) return Res;
2507 /// If this is a binary operator with two operands of the same opcode, try to
2509 SDValue DAGCombiner::SimplifyBinOpWithSameOpcodeHands(SDNode *N) {
2510 SDValue N0 = N->getOperand(0), N1 = N->getOperand(1);
2511 EVT VT = N0.getValueType();
2512 assert(N0.getOpcode() == N1.getOpcode() && "Bad input!");
2514 // Bail early if none of these transforms apply.
2515 if (N0.getNode()->getNumOperands() == 0) return SDValue();
2517 // For each of OP in AND/OR/XOR:
2518 // fold (OP (zext x), (zext y)) -> (zext (OP x, y))
2519 // fold (OP (sext x), (sext y)) -> (sext (OP x, y))
2520 // fold (OP (aext x), (aext y)) -> (aext (OP x, y))
2521 // fold (OP (trunc x), (trunc y)) -> (trunc (OP x, y)) (if trunc isn't free)
2523 // do not sink logical op inside of a vector extend, since it may combine
2525 EVT Op0VT = N0.getOperand(0).getValueType();
2526 if ((N0.getOpcode() == ISD::ZERO_EXTEND ||
2527 N0.getOpcode() == ISD::SIGN_EXTEND ||
2528 // Avoid infinite looping with PromoteIntBinOp.
2529 (N0.getOpcode() == ISD::ANY_EXTEND &&
2530 (!LegalTypes || TLI.isTypeDesirableForOp(N->getOpcode(), Op0VT))) ||
2531 (N0.getOpcode() == ISD::TRUNCATE &&
2532 (!TLI.isZExtFree(VT, Op0VT) ||
2533 !TLI.isTruncateFree(Op0VT, VT)) &&
2534 TLI.isTypeLegal(Op0VT))) &&
2536 Op0VT == N1.getOperand(0).getValueType() &&
2537 (!LegalOperations || TLI.isOperationLegal(N->getOpcode(), Op0VT))) {
2538 SDValue ORNode = DAG.getNode(N->getOpcode(), SDLoc(N0),
2539 N0.getOperand(0).getValueType(),
2540 N0.getOperand(0), N1.getOperand(0));
2541 AddToWorklist(ORNode.getNode());
2542 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, ORNode);
2545 // For each of OP in SHL/SRL/SRA/AND...
2546 // fold (and (OP x, z), (OP y, z)) -> (OP (and x, y), z)
2547 // fold (or (OP x, z), (OP y, z)) -> (OP (or x, y), z)
2548 // fold (xor (OP x, z), (OP y, z)) -> (OP (xor x, y), z)
2549 if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL ||
2550 N0.getOpcode() == ISD::SRA || N0.getOpcode() == ISD::AND) &&
2551 N0.getOperand(1) == N1.getOperand(1)) {
2552 SDValue ORNode = DAG.getNode(N->getOpcode(), SDLoc(N0),
2553 N0.getOperand(0).getValueType(),
2554 N0.getOperand(0), N1.getOperand(0));
2555 AddToWorklist(ORNode.getNode());
2556 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
2557 ORNode, N0.getOperand(1));
2560 // Simplify xor/and/or (bitcast(A), bitcast(B)) -> bitcast(op (A,B))
2561 // Only perform this optimization after type legalization and before
2562 // LegalizeVectorOprs. LegalizeVectorOprs promotes vector operations by
2563 // adding bitcasts. For example (xor v4i32) is promoted to (v2i64), and
2564 // we don't want to undo this promotion.
2565 // We also handle SCALAR_TO_VECTOR because xor/or/and operations are cheaper
2567 if ((N0.getOpcode() == ISD::BITCAST ||
2568 N0.getOpcode() == ISD::SCALAR_TO_VECTOR) &&
2569 Level == AfterLegalizeTypes) {
2570 SDValue In0 = N0.getOperand(0);
2571 SDValue In1 = N1.getOperand(0);
2572 EVT In0Ty = In0.getValueType();
2573 EVT In1Ty = In1.getValueType();
2575 // If both incoming values are integers, and the original types are the
2577 if (In0Ty.isInteger() && In1Ty.isInteger() && In0Ty == In1Ty) {
2578 SDValue Op = DAG.getNode(N->getOpcode(), DL, In0Ty, In0, In1);
2579 SDValue BC = DAG.getNode(N0.getOpcode(), DL, VT, Op);
2580 AddToWorklist(Op.getNode());
2585 // Xor/and/or are indifferent to the swizzle operation (shuffle of one value).
2586 // Simplify xor/and/or (shuff(A), shuff(B)) -> shuff(op (A,B))
2587 // If both shuffles use the same mask, and both shuffle within a single
2588 // vector, then it is worthwhile to move the swizzle after the operation.
2589 // The type-legalizer generates this pattern when loading illegal
2590 // vector types from memory. In many cases this allows additional shuffle
2592 // There are other cases where moving the shuffle after the xor/and/or
2593 // is profitable even if shuffles don't perform a swizzle.
2594 // If both shuffles use the same mask, and both shuffles have the same first
2595 // or second operand, then it might still be profitable to move the shuffle
2596 // after the xor/and/or operation.
2597 if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG) {
2598 ShuffleVectorSDNode *SVN0 = cast<ShuffleVectorSDNode>(N0);
2599 ShuffleVectorSDNode *SVN1 = cast<ShuffleVectorSDNode>(N1);
2601 assert(N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType() &&
2602 "Inputs to shuffles are not the same type");
2604 // Check that both shuffles use the same mask. The masks are known to be of
2605 // the same length because the result vector type is the same.
2606 // Check also that shuffles have only one use to avoid introducing extra
2608 if (SVN0->hasOneUse() && SVN1->hasOneUse() &&
2609 SVN0->getMask().equals(SVN1->getMask())) {
2610 SDValue ShOp = N0->getOperand(1);
2612 // Don't try to fold this node if it requires introducing a
2613 // build vector of all zeros that might be illegal at this stage.
2614 if (N->getOpcode() == ISD::XOR && ShOp.getOpcode() != ISD::UNDEF) {
2616 ShOp = DAG.getConstant(0, VT);
2621 // (AND (shuf (A, C), shuf (B, C)) -> shuf (AND (A, B), C)
2622 // (OR (shuf (A, C), shuf (B, C)) -> shuf (OR (A, B), C)
2623 // (XOR (shuf (A, C), shuf (B, C)) -> shuf (XOR (A, B), V_0)
2624 if (N0.getOperand(1) == N1.getOperand(1) && ShOp.getNode()) {
2625 SDValue NewNode = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
2626 N0->getOperand(0), N1->getOperand(0));
2627 AddToWorklist(NewNode.getNode());
2628 return DAG.getVectorShuffle(VT, SDLoc(N), NewNode, ShOp,
2629 &SVN0->getMask()[0]);
2632 // Don't try to fold this node if it requires introducing a
2633 // build vector of all zeros that might be illegal at this stage.
2634 ShOp = N0->getOperand(0);
2635 if (N->getOpcode() == ISD::XOR && ShOp.getOpcode() != ISD::UNDEF) {
2637 ShOp = DAG.getConstant(0, VT);
2642 // (AND (shuf (C, A), shuf (C, B)) -> shuf (C, AND (A, B))
2643 // (OR (shuf (C, A), shuf (C, B)) -> shuf (C, OR (A, B))
2644 // (XOR (shuf (C, A), shuf (C, B)) -> shuf (V_0, XOR (A, B))
2645 if (N0->getOperand(0) == N1->getOperand(0) && ShOp.getNode()) {
2646 SDValue NewNode = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
2647 N0->getOperand(1), N1->getOperand(1));
2648 AddToWorklist(NewNode.getNode());
2649 return DAG.getVectorShuffle(VT, SDLoc(N), ShOp, NewNode,
2650 &SVN0->getMask()[0]);
2658 SDValue DAGCombiner::visitAND(SDNode *N) {
2659 SDValue N0 = N->getOperand(0);
2660 SDValue N1 = N->getOperand(1);
2661 SDValue LL, LR, RL, RR, CC0, CC1;
2662 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
2663 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2664 EVT VT = N1.getValueType();
2665 unsigned BitWidth = VT.getScalarType().getSizeInBits();
2668 if (VT.isVector()) {
2669 SDValue FoldedVOp = SimplifyVBinOp(N);
2670 if (FoldedVOp.getNode()) return FoldedVOp;
2672 // fold (and x, 0) -> 0, vector edition
2673 if (ISD::isBuildVectorAllZeros(N0.getNode()))
2674 // do not return N0, because undef node may exist in N0
2675 return DAG.getConstant(
2676 APInt::getNullValue(
2677 N0.getValueType().getScalarType().getSizeInBits()),
2679 if (ISD::isBuildVectorAllZeros(N1.getNode()))
2680 // do not return N1, because undef node may exist in N1
2681 return DAG.getConstant(
2682 APInt::getNullValue(
2683 N1.getValueType().getScalarType().getSizeInBits()),
2686 // fold (and x, -1) -> x, vector edition
2687 if (ISD::isBuildVectorAllOnes(N0.getNode()))
2689 if (ISD::isBuildVectorAllOnes(N1.getNode()))
2693 // fold (and x, undef) -> 0
2694 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2695 return DAG.getConstant(0, VT);
2696 // fold (and c1, c2) -> c1&c2
2698 return DAG.FoldConstantArithmetic(ISD::AND, VT, N0C, N1C);
2699 // canonicalize constant to RHS
2701 return DAG.getNode(ISD::AND, SDLoc(N), VT, N1, N0);
2702 // fold (and x, -1) -> x
2703 if (N1C && N1C->isAllOnesValue())
2705 // if (and x, c) is known to be zero, return 0
2706 if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0),
2707 APInt::getAllOnesValue(BitWidth)))
2708 return DAG.getConstant(0, VT);
2710 SDValue RAND = ReassociateOps(ISD::AND, SDLoc(N), N0, N1);
2713 // fold (and (or x, C), D) -> D if (C & D) == D
2714 if (N1C && N0.getOpcode() == ISD::OR)
2715 if (ConstantSDNode *ORI = dyn_cast<ConstantSDNode>(N0.getOperand(1)))
2716 if ((ORI->getAPIntValue() & N1C->getAPIntValue()) == N1C->getAPIntValue())
2718 // fold (and (any_ext V), c) -> (zero_ext V) if 'and' only clears top bits.
2719 if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
2720 SDValue N0Op0 = N0.getOperand(0);
2721 APInt Mask = ~N1C->getAPIntValue();
2722 Mask = Mask.trunc(N0Op0.getValueSizeInBits());
2723 if (DAG.MaskedValueIsZero(N0Op0, Mask)) {
2724 SDValue Zext = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N),
2725 N0.getValueType(), N0Op0);
2727 // Replace uses of the AND with uses of the Zero extend node.
2730 // We actually want to replace all uses of the any_extend with the
2731 // zero_extend, to avoid duplicating things. This will later cause this
2732 // AND to be folded.
2733 CombineTo(N0.getNode(), Zext);
2734 return SDValue(N, 0); // Return N so it doesn't get rechecked!
2737 // similarly fold (and (X (load ([non_ext|any_ext|zero_ext] V))), c) ->
2738 // (X (load ([non_ext|zero_ext] V))) if 'and' only clears top bits which must
2739 // already be zero by virtue of the width of the base type of the load.
2741 // the 'X' node here can either be nothing or an extract_vector_elt to catch
2743 if ((N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
2744 N0.getOperand(0).getOpcode() == ISD::LOAD) ||
2745 N0.getOpcode() == ISD::LOAD) {
2746 LoadSDNode *Load = cast<LoadSDNode>( (N0.getOpcode() == ISD::LOAD) ?
2747 N0 : N0.getOperand(0) );
2749 // Get the constant (if applicable) the zero'th operand is being ANDed with.
2750 // This can be a pure constant or a vector splat, in which case we treat the
2751 // vector as a scalar and use the splat value.
2752 APInt Constant = APInt::getNullValue(1);
2753 if (const ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
2754 Constant = C->getAPIntValue();
2755 } else if (BuildVectorSDNode *Vector = dyn_cast<BuildVectorSDNode>(N1)) {
2756 APInt SplatValue, SplatUndef;
2757 unsigned SplatBitSize;
2759 bool IsSplat = Vector->isConstantSplat(SplatValue, SplatUndef,
2760 SplatBitSize, HasAnyUndefs);
2762 // Undef bits can contribute to a possible optimisation if set, so
2764 SplatValue |= SplatUndef;
2766 // The splat value may be something like "0x00FFFFFF", which means 0 for
2767 // the first vector value and FF for the rest, repeating. We need a mask
2768 // that will apply equally to all members of the vector, so AND all the
2769 // lanes of the constant together.
2770 EVT VT = Vector->getValueType(0);
2771 unsigned BitWidth = VT.getVectorElementType().getSizeInBits();
2773 // If the splat value has been compressed to a bitlength lower
2774 // than the size of the vector lane, we need to re-expand it to
2776 if (BitWidth > SplatBitSize)
2777 for (SplatValue = SplatValue.zextOrTrunc(BitWidth);
2778 SplatBitSize < BitWidth;
2779 SplatBitSize = SplatBitSize * 2)
2780 SplatValue |= SplatValue.shl(SplatBitSize);
2782 Constant = APInt::getAllOnesValue(BitWidth);
2783 for (unsigned i = 0, n = SplatBitSize/BitWidth; i < n; ++i)
2784 Constant &= SplatValue.lshr(i*BitWidth).zextOrTrunc(BitWidth);
2788 // If we want to change an EXTLOAD to a ZEXTLOAD, ensure a ZEXTLOAD is
2789 // actually legal and isn't going to get expanded, else this is a false
2791 bool CanZextLoadProfitably = TLI.isLoadExtLegal(ISD::ZEXTLOAD,
2792 Load->getMemoryVT());
2794 // Resize the constant to the same size as the original memory access before
2795 // extension. If it is still the AllOnesValue then this AND is completely
2798 Constant.zextOrTrunc(Load->getMemoryVT().getScalarType().getSizeInBits());
2801 switch (Load->getExtensionType()) {
2802 default: B = false; break;
2803 case ISD::EXTLOAD: B = CanZextLoadProfitably; break;
2805 case ISD::NON_EXTLOAD: B = true; break;
2808 if (B && Constant.isAllOnesValue()) {
2809 // If the load type was an EXTLOAD, convert to ZEXTLOAD in order to
2810 // preserve semantics once we get rid of the AND.
2811 SDValue NewLoad(Load, 0);
2812 if (Load->getExtensionType() == ISD::EXTLOAD) {
2813 NewLoad = DAG.getLoad(Load->getAddressingMode(), ISD::ZEXTLOAD,
2814 Load->getValueType(0), SDLoc(Load),
2815 Load->getChain(), Load->getBasePtr(),
2816 Load->getOffset(), Load->getMemoryVT(),
2817 Load->getMemOperand());
2818 // Replace uses of the EXTLOAD with the new ZEXTLOAD.
2819 if (Load->getNumValues() == 3) {
2820 // PRE/POST_INC loads have 3 values.
2821 SDValue To[] = { NewLoad.getValue(0), NewLoad.getValue(1),
2822 NewLoad.getValue(2) };
2823 CombineTo(Load, To, 3, true);
2825 CombineTo(Load, NewLoad.getValue(0), NewLoad.getValue(1));
2829 // Fold the AND away, taking care not to fold to the old load node if we
2831 CombineTo(N, (N0.getNode() == Load) ? NewLoad : N0);
2833 return SDValue(N, 0); // Return N so it doesn't get rechecked!
2836 // fold (and (setcc x), (setcc y)) -> (setcc (and x, y))
2837 if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){
2838 ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get();
2839 ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get();
2841 if (LR == RR && isa<ConstantSDNode>(LR) && Op0 == Op1 &&
2842 LL.getValueType().isInteger()) {
2843 // fold (and (seteq X, 0), (seteq Y, 0)) -> (seteq (or X, Y), 0)
2844 if (cast<ConstantSDNode>(LR)->isNullValue() && Op1 == ISD::SETEQ) {
2845 SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(N0),
2846 LR.getValueType(), LL, RL);
2847 AddToWorklist(ORNode.getNode());
2848 return DAG.getSetCC(SDLoc(N), VT, ORNode, LR, Op1);
2850 // fold (and (seteq X, -1), (seteq Y, -1)) -> (seteq (and X, Y), -1)
2851 if (cast<ConstantSDNode>(LR)->isAllOnesValue() && Op1 == ISD::SETEQ) {
2852 SDValue ANDNode = DAG.getNode(ISD::AND, SDLoc(N0),
2853 LR.getValueType(), LL, RL);
2854 AddToWorklist(ANDNode.getNode());
2855 return DAG.getSetCC(SDLoc(N), VT, ANDNode, LR, Op1);
2857 // fold (and (setgt X, -1), (setgt Y, -1)) -> (setgt (or X, Y), -1)
2858 if (cast<ConstantSDNode>(LR)->isAllOnesValue() && Op1 == ISD::SETGT) {
2859 SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(N0),
2860 LR.getValueType(), LL, RL);
2861 AddToWorklist(ORNode.getNode());
2862 return DAG.getSetCC(SDLoc(N), VT, ORNode, LR, Op1);
2865 // Simplify (and (setne X, 0), (setne X, -1)) -> (setuge (add X, 1), 2)
2866 if (LL == RL && isa<ConstantSDNode>(LR) && isa<ConstantSDNode>(RR) &&
2867 Op0 == Op1 && LL.getValueType().isInteger() &&
2868 Op0 == ISD::SETNE && ((cast<ConstantSDNode>(LR)->isNullValue() &&
2869 cast<ConstantSDNode>(RR)->isAllOnesValue()) ||
2870 (cast<ConstantSDNode>(LR)->isAllOnesValue() &&
2871 cast<ConstantSDNode>(RR)->isNullValue()))) {
2872 SDValue ADDNode = DAG.getNode(ISD::ADD, SDLoc(N0), LL.getValueType(),
2873 LL, DAG.getConstant(1, LL.getValueType()));
2874 AddToWorklist(ADDNode.getNode());
2875 return DAG.getSetCC(SDLoc(N), VT, ADDNode,
2876 DAG.getConstant(2, LL.getValueType()), ISD::SETUGE);
2878 // canonicalize equivalent to ll == rl
2879 if (LL == RR && LR == RL) {
2880 Op1 = ISD::getSetCCSwappedOperands(Op1);
2883 if (LL == RL && LR == RR) {
2884 bool isInteger = LL.getValueType().isInteger();
2885 ISD::CondCode Result = ISD::getSetCCAndOperation(Op0, Op1, isInteger);
2886 if (Result != ISD::SETCC_INVALID &&
2887 (!LegalOperations ||
2888 (TLI.isCondCodeLegal(Result, LL.getSimpleValueType()) &&
2889 TLI.isOperationLegal(ISD::SETCC,
2890 getSetCCResultType(N0.getSimpleValueType())))))
2891 return DAG.getSetCC(SDLoc(N), N0.getValueType(),
2896 // Simplify: (and (op x...), (op y...)) -> (op (and x, y))
2897 if (N0.getOpcode() == N1.getOpcode()) {
2898 SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
2899 if (Tmp.getNode()) return Tmp;
2902 // fold (and (sign_extend_inreg x, i16 to i32), 1) -> (and x, 1)
2903 // fold (and (sra)) -> (and (srl)) when possible.
2904 if (!VT.isVector() &&
2905 SimplifyDemandedBits(SDValue(N, 0)))
2906 return SDValue(N, 0);
2908 // fold (zext_inreg (extload x)) -> (zextload x)
2909 if (ISD::isEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode())) {
2910 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
2911 EVT MemVT = LN0->getMemoryVT();
2912 // If we zero all the possible extended bits, then we can turn this into
2913 // a zextload if we are running before legalize or the operation is legal.
2914 unsigned BitWidth = N1.getValueType().getScalarType().getSizeInBits();
2915 if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth,
2916 BitWidth - MemVT.getScalarType().getSizeInBits())) &&
2917 ((!LegalOperations && !LN0->isVolatile()) ||
2918 TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT))) {
2919 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N0), VT,
2920 LN0->getChain(), LN0->getBasePtr(),
2921 MemVT, LN0->getMemOperand());
2923 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
2924 return SDValue(N, 0); // Return N so it doesn't get rechecked!
2927 // fold (zext_inreg (sextload x)) -> (zextload x) iff load has one use
2928 if (ISD::isSEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
2930 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
2931 EVT MemVT = LN0->getMemoryVT();
2932 // If we zero all the possible extended bits, then we can turn this into
2933 // a zextload if we are running before legalize or the operation is legal.
2934 unsigned BitWidth = N1.getValueType().getScalarType().getSizeInBits();
2935 if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth,
2936 BitWidth - MemVT.getScalarType().getSizeInBits())) &&
2937 ((!LegalOperations && !LN0->isVolatile()) ||
2938 TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT))) {
2939 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N0), VT,
2940 LN0->getChain(), LN0->getBasePtr(),
2941 MemVT, LN0->getMemOperand());
2943 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
2944 return SDValue(N, 0); // Return N so it doesn't get rechecked!
2948 // fold (and (load x), 255) -> (zextload x, i8)
2949 // fold (and (extload x, i16), 255) -> (zextload x, i8)
2950 // fold (and (any_ext (extload x, i16)), 255) -> (zextload x, i8)
2951 if (N1C && (N0.getOpcode() == ISD::LOAD ||
2952 (N0.getOpcode() == ISD::ANY_EXTEND &&
2953 N0.getOperand(0).getOpcode() == ISD::LOAD))) {
2954 bool HasAnyExt = N0.getOpcode() == ISD::ANY_EXTEND;
2955 LoadSDNode *LN0 = HasAnyExt
2956 ? cast<LoadSDNode>(N0.getOperand(0))
2957 : cast<LoadSDNode>(N0);
2958 if (LN0->getExtensionType() != ISD::SEXTLOAD &&
2959 LN0->isUnindexed() && N0.hasOneUse() && SDValue(LN0, 0).hasOneUse()) {
2960 uint32_t ActiveBits = N1C->getAPIntValue().getActiveBits();
2961 if (ActiveBits > 0 && APIntOps::isMask(ActiveBits, N1C->getAPIntValue())){
2962 EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), ActiveBits);
2963 EVT LoadedVT = LN0->getMemoryVT();
2965 if (ExtVT == LoadedVT &&
2966 (!LegalOperations || TLI.isLoadExtLegal(ISD::ZEXTLOAD, ExtVT))) {
2967 EVT LoadResultTy = HasAnyExt ? LN0->getValueType(0) : VT;
2970 DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), LoadResultTy,
2971 LN0->getChain(), LN0->getBasePtr(), ExtVT,
2972 LN0->getMemOperand());
2974 CombineTo(LN0, NewLoad, NewLoad.getValue(1));
2975 return SDValue(N, 0); // Return N so it doesn't get rechecked!
2978 // Do not change the width of a volatile load.
2979 // Do not generate loads of non-round integer types since these can
2980 // be expensive (and would be wrong if the type is not byte sized).
2981 if (!LN0->isVolatile() && LoadedVT.bitsGT(ExtVT) && ExtVT.isRound() &&
2982 (!LegalOperations || TLI.isLoadExtLegal(ISD::ZEXTLOAD, ExtVT))) {
2983 EVT PtrType = LN0->getOperand(1).getValueType();
2985 unsigned Alignment = LN0->getAlignment();
2986 SDValue NewPtr = LN0->getBasePtr();
2988 // For big endian targets, we need to add an offset to the pointer
2989 // to load the correct bytes. For little endian systems, we merely
2990 // need to read fewer bytes from the same pointer.
2991 if (TLI.isBigEndian()) {
2992 unsigned LVTStoreBytes = LoadedVT.getStoreSize();
2993 unsigned EVTStoreBytes = ExtVT.getStoreSize();
2994 unsigned PtrOff = LVTStoreBytes - EVTStoreBytes;
2995 NewPtr = DAG.getNode(ISD::ADD, SDLoc(LN0), PtrType,
2996 NewPtr, DAG.getConstant(PtrOff, PtrType));
2997 Alignment = MinAlign(Alignment, PtrOff);
3000 AddToWorklist(NewPtr.getNode());
3002 EVT LoadResultTy = HasAnyExt ? LN0->getValueType(0) : VT;
3004 DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), LoadResultTy,
3005 LN0->getChain(), NewPtr,
3006 LN0->getPointerInfo(),
3007 ExtVT, LN0->isVolatile(), LN0->isNonTemporal(),
3008 LN0->isInvariant(), Alignment, LN0->getAAInfo());
3010 CombineTo(LN0, Load, Load.getValue(1));
3011 return SDValue(N, 0); // Return N so it doesn't get rechecked!
3017 if (N0.getOpcode() == ISD::ADD && N1.getOpcode() == ISD::SRL &&
3018 VT.getSizeInBits() <= 64) {
3019 if (ConstantSDNode *ADDI = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
3020 APInt ADDC = ADDI->getAPIntValue();
3021 if (!TLI.isLegalAddImmediate(ADDC.getSExtValue())) {
3022 // Look for (and (add x, c1), (lshr y, c2)). If C1 wasn't a legal
3023 // immediate for an add, but it is legal if its top c2 bits are set,
3024 // transform the ADD so the immediate doesn't need to be materialized
3026 if (ConstantSDNode *SRLI = dyn_cast<ConstantSDNode>(N1.getOperand(1))) {
3027 APInt Mask = APInt::getHighBitsSet(VT.getSizeInBits(),
3028 SRLI->getZExtValue());
3029 if (DAG.MaskedValueIsZero(N0.getOperand(1), Mask)) {
3031 if (TLI.isLegalAddImmediate(ADDC.getSExtValue())) {
3033 DAG.getNode(ISD::ADD, SDLoc(N0), VT,
3034 N0.getOperand(0), DAG.getConstant(ADDC, VT));
3035 CombineTo(N0.getNode(), NewAdd);
3036 return SDValue(N, 0); // Return N so it doesn't get rechecked!
3044 // fold (and (or (srl N, 8), (shl N, 8)), 0xffff) -> (srl (bswap N), const)
3045 if (N1C && N1C->getAPIntValue() == 0xffff && N0.getOpcode() == ISD::OR) {
3046 SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0),
3047 N0.getOperand(1), false);
3048 if (BSwap.getNode())
3055 /// Match (a >> 8) | (a << 8) as (bswap a) >> 16.
3056 SDValue DAGCombiner::MatchBSwapHWordLow(SDNode *N, SDValue N0, SDValue N1,
3057 bool DemandHighBits) {
3058 if (!LegalOperations)
3061 EVT VT = N->getValueType(0);
3062 if (VT != MVT::i64 && VT != MVT::i32 && VT != MVT::i16)
3064 if (!TLI.isOperationLegal(ISD::BSWAP, VT))
3067 // Recognize (and (shl a, 8), 0xff), (and (srl a, 8), 0xff00)
3068 bool LookPassAnd0 = false;
3069 bool LookPassAnd1 = false;
3070 if (N0.getOpcode() == ISD::AND && N0.getOperand(0).getOpcode() == ISD::SRL)
3072 if (N1.getOpcode() == ISD::AND && N1.getOperand(0).getOpcode() == ISD::SHL)
3074 if (N0.getOpcode() == ISD::AND) {
3075 if (!N0.getNode()->hasOneUse())
3077 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3078 if (!N01C || N01C->getZExtValue() != 0xFF00)
3080 N0 = N0.getOperand(0);
3081 LookPassAnd0 = true;
3084 if (N1.getOpcode() == ISD::AND) {
3085 if (!N1.getNode()->hasOneUse())
3087 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
3088 if (!N11C || N11C->getZExtValue() != 0xFF)
3090 N1 = N1.getOperand(0);
3091 LookPassAnd1 = true;
3094 if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
3096 if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
3098 if (!N0.getNode()->hasOneUse() ||
3099 !N1.getNode()->hasOneUse())
3102 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3103 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
3106 if (N01C->getZExtValue() != 8 || N11C->getZExtValue() != 8)
3109 // Look for (shl (and a, 0xff), 8), (srl (and a, 0xff00), 8)
3110 SDValue N00 = N0->getOperand(0);
3111 if (!LookPassAnd0 && N00.getOpcode() == ISD::AND) {
3112 if (!N00.getNode()->hasOneUse())
3114 ConstantSDNode *N001C = dyn_cast<ConstantSDNode>(N00.getOperand(1));
3115 if (!N001C || N001C->getZExtValue() != 0xFF)
3117 N00 = N00.getOperand(0);
3118 LookPassAnd0 = true;
3121 SDValue N10 = N1->getOperand(0);
3122 if (!LookPassAnd1 && N10.getOpcode() == ISD::AND) {
3123 if (!N10.getNode()->hasOneUse())
3125 ConstantSDNode *N101C = dyn_cast<ConstantSDNode>(N10.getOperand(1));
3126 if (!N101C || N101C->getZExtValue() != 0xFF00)
3128 N10 = N10.getOperand(0);
3129 LookPassAnd1 = true;
3135 // Make sure everything beyond the low halfword gets set to zero since the SRL
3136 // 16 will clear the top bits.
3137 unsigned OpSizeInBits = VT.getSizeInBits();
3138 if (DemandHighBits && OpSizeInBits > 16) {
3139 // If the left-shift isn't masked out then the only way this is a bswap is
3140 // if all bits beyond the low 8 are 0. In that case the entire pattern
3141 // reduces to a left shift anyway: leave it for other parts of the combiner.
3145 // However, if the right shift isn't masked out then it might be because
3146 // it's not needed. See if we can spot that too.
3147 if (!LookPassAnd1 &&
3148 !DAG.MaskedValueIsZero(
3149 N10, APInt::getHighBitsSet(OpSizeInBits, OpSizeInBits - 16)))
3153 SDValue Res = DAG.getNode(ISD::BSWAP, SDLoc(N), VT, N00);
3154 if (OpSizeInBits > 16)
3155 Res = DAG.getNode(ISD::SRL, SDLoc(N), VT, Res,
3156 DAG.getConstant(OpSizeInBits-16, getShiftAmountTy(VT)));
3160 /// Return true if the specified node is an element that makes up a 32-bit
3161 /// packed halfword byteswap.
3162 /// ((x & 0x000000ff) << 8) |
3163 /// ((x & 0x0000ff00) >> 8) |
3164 /// ((x & 0x00ff0000) << 8) |
3165 /// ((x & 0xff000000) >> 8)
3166 static bool isBSwapHWordElement(SDValue N, MutableArrayRef<SDNode *> Parts) {
3167 if (!N.getNode()->hasOneUse())
3170 unsigned Opc = N.getOpcode();
3171 if (Opc != ISD::AND && Opc != ISD::SHL && Opc != ISD::SRL)
3174 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3179 switch (N1C->getZExtValue()) {
3182 case 0xFF: Num = 0; break;
3183 case 0xFF00: Num = 1; break;
3184 case 0xFF0000: Num = 2; break;
3185 case 0xFF000000: Num = 3; break;
3188 // Look for (x & 0xff) << 8 as well as ((x << 8) & 0xff00).
3189 SDValue N0 = N.getOperand(0);
3190 if (Opc == ISD::AND) {
3191 if (Num == 0 || Num == 2) {
3193 // (x >> 8) & 0xff0000
3194 if (N0.getOpcode() != ISD::SRL)
3196 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3197 if (!C || C->getZExtValue() != 8)
3200 // (x << 8) & 0xff00
3201 // (x << 8) & 0xff000000
3202 if (N0.getOpcode() != ISD::SHL)
3204 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3205 if (!C || C->getZExtValue() != 8)
3208 } else if (Opc == ISD::SHL) {
3210 // (x & 0xff0000) << 8
3211 if (Num != 0 && Num != 2)
3213 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3214 if (!C || C->getZExtValue() != 8)
3216 } else { // Opc == ISD::SRL
3217 // (x & 0xff00) >> 8
3218 // (x & 0xff000000) >> 8
3219 if (Num != 1 && Num != 3)
3221 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3222 if (!C || C->getZExtValue() != 8)
3229 Parts[Num] = N0.getOperand(0).getNode();
3233 /// Match a 32-bit packed halfword bswap. That is
3234 /// ((x & 0x000000ff) << 8) |
3235 /// ((x & 0x0000ff00) >> 8) |
3236 /// ((x & 0x00ff0000) << 8) |
3237 /// ((x & 0xff000000) >> 8)
3238 /// => (rotl (bswap x), 16)
3239 SDValue DAGCombiner::MatchBSwapHWord(SDNode *N, SDValue N0, SDValue N1) {
3240 if (!LegalOperations)
3243 EVT VT = N->getValueType(0);
3246 if (!TLI.isOperationLegal(ISD::BSWAP, VT))
3250 // (or (or (and), (and)), (or (and), (and)))
3251 // (or (or (or (and), (and)), (and)), (and))
3252 if (N0.getOpcode() != ISD::OR)
3254 SDValue N00 = N0.getOperand(0);
3255 SDValue N01 = N0.getOperand(1);
3256 SDNode *Parts[4] = {};
3258 if (N1.getOpcode() == ISD::OR &&
3259 N00.getNumOperands() == 2 && N01.getNumOperands() == 2) {
3260 // (or (or (and), (and)), (or (and), (and)))
3261 SDValue N000 = N00.getOperand(0);
3262 if (!isBSwapHWordElement(N000, Parts))
3265 SDValue N001 = N00.getOperand(1);
3266 if (!isBSwapHWordElement(N001, Parts))
3268 SDValue N010 = N01.getOperand(0);
3269 if (!isBSwapHWordElement(N010, Parts))
3271 SDValue N011 = N01.getOperand(1);
3272 if (!isBSwapHWordElement(N011, Parts))
3275 // (or (or (or (and), (and)), (and)), (and))
3276 if (!isBSwapHWordElement(N1, Parts))
3278 if (!isBSwapHWordElement(N01, Parts))
3280 if (N00.getOpcode() != ISD::OR)
3282 SDValue N000 = N00.getOperand(0);
3283 if (!isBSwapHWordElement(N000, Parts))
3285 SDValue N001 = N00.getOperand(1);
3286 if (!isBSwapHWordElement(N001, Parts))
3290 // Make sure the parts are all coming from the same node.
3291 if (Parts[0] != Parts[1] || Parts[0] != Parts[2] || Parts[0] != Parts[3])
3294 SDValue BSwap = DAG.getNode(ISD::BSWAP, SDLoc(N), VT,
3295 SDValue(Parts[0],0));
3297 // Result of the bswap should be rotated by 16. If it's not legal, then
3298 // do (x << 16) | (x >> 16).
3299 SDValue ShAmt = DAG.getConstant(16, getShiftAmountTy(VT));
3300 if (TLI.isOperationLegalOrCustom(ISD::ROTL, VT))
3301 return DAG.getNode(ISD::ROTL, SDLoc(N), VT, BSwap, ShAmt);
3302 if (TLI.isOperationLegalOrCustom(ISD::ROTR, VT))
3303 return DAG.getNode(ISD::ROTR, SDLoc(N), VT, BSwap, ShAmt);
3304 return DAG.getNode(ISD::OR, SDLoc(N), VT,
3305 DAG.getNode(ISD::SHL, SDLoc(N), VT, BSwap, ShAmt),
3306 DAG.getNode(ISD::SRL, SDLoc(N), VT, BSwap, ShAmt));
3309 SDValue DAGCombiner::visitOR(SDNode *N) {
3310 SDValue N0 = N->getOperand(0);
3311 SDValue N1 = N->getOperand(1);
3312 SDValue LL, LR, RL, RR, CC0, CC1;
3313 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
3314 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
3315 EVT VT = N1.getValueType();
3318 if (VT.isVector()) {
3319 SDValue FoldedVOp = SimplifyVBinOp(N);
3320 if (FoldedVOp.getNode()) return FoldedVOp;
3322 // fold (or x, 0) -> x, vector edition
3323 if (ISD::isBuildVectorAllZeros(N0.getNode()))
3325 if (ISD::isBuildVectorAllZeros(N1.getNode()))
3328 // fold (or x, -1) -> -1, vector edition
3329 if (ISD::isBuildVectorAllOnes(N0.getNode()))
3330 // do not return N0, because undef node may exist in N0
3331 return DAG.getConstant(
3332 APInt::getAllOnesValue(
3333 N0.getValueType().getScalarType().getSizeInBits()),
3335 if (ISD::isBuildVectorAllOnes(N1.getNode()))
3336 // do not return N1, because undef node may exist in N1
3337 return DAG.getConstant(
3338 APInt::getAllOnesValue(
3339 N1.getValueType().getScalarType().getSizeInBits()),
3342 // fold (or (shuf A, V_0, MA), (shuf B, V_0, MB)) -> (shuf A, B, Mask1)
3343 // fold (or (shuf A, V_0, MA), (shuf B, V_0, MB)) -> (shuf B, A, Mask2)
3344 // Do this only if the resulting shuffle is legal.
3345 if (isa<ShuffleVectorSDNode>(N0) &&
3346 isa<ShuffleVectorSDNode>(N1) &&
3347 // Avoid folding a node with illegal type.
3348 TLI.isTypeLegal(VT) &&
3349 N0->getOperand(1) == N1->getOperand(1) &&
3350 ISD::isBuildVectorAllZeros(N0.getOperand(1).getNode())) {
3351 bool CanFold = true;
3352 unsigned NumElts = VT.getVectorNumElements();
3353 const ShuffleVectorSDNode *SV0 = cast<ShuffleVectorSDNode>(N0);
3354 const ShuffleVectorSDNode *SV1 = cast<ShuffleVectorSDNode>(N1);
3355 // We construct two shuffle masks:
3356 // - Mask1 is a shuffle mask for a shuffle with N0 as the first operand
3357 // and N1 as the second operand.
3358 // - Mask2 is a shuffle mask for a shuffle with N1 as the first operand
3359 // and N0 as the second operand.
3360 // We do this because OR is commutable and therefore there might be
3361 // two ways to fold this node into a shuffle.
3362 SmallVector<int,4> Mask1;
3363 SmallVector<int,4> Mask2;
3365 for (unsigned i = 0; i != NumElts && CanFold; ++i) {
3366 int M0 = SV0->getMaskElt(i);
3367 int M1 = SV1->getMaskElt(i);
3369 // Both shuffle indexes are undef. Propagate Undef.
3370 if (M0 < 0 && M1 < 0) {
3371 Mask1.push_back(M0);
3372 Mask2.push_back(M0);
3376 if (M0 < 0 || M1 < 0 ||
3377 (M0 < (int)NumElts && M1 < (int)NumElts) ||
3378 (M0 >= (int)NumElts && M1 >= (int)NumElts)) {
3383 Mask1.push_back(M0 < (int)NumElts ? M0 : M1 + NumElts);
3384 Mask2.push_back(M1 < (int)NumElts ? M1 : M0 + NumElts);
3388 // Fold this sequence only if the resulting shuffle is 'legal'.
3389 if (TLI.isShuffleMaskLegal(Mask1, VT))
3390 return DAG.getVectorShuffle(VT, SDLoc(N), N0->getOperand(0),
3391 N1->getOperand(0), &Mask1[0]);
3392 if (TLI.isShuffleMaskLegal(Mask2, VT))
3393 return DAG.getVectorShuffle(VT, SDLoc(N), N1->getOperand(0),
3394 N0->getOperand(0), &Mask2[0]);
3399 // fold (or x, undef) -> -1
3400 if (!LegalOperations &&
3401 (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)) {
3402 EVT EltVT = VT.isVector() ? VT.getVectorElementType() : VT;
3403 return DAG.getConstant(APInt::getAllOnesValue(EltVT.getSizeInBits()), VT);
3405 // fold (or c1, c2) -> c1|c2
3407 return DAG.FoldConstantArithmetic(ISD::OR, VT, N0C, N1C);
3408 // canonicalize constant to RHS
3410 return DAG.getNode(ISD::OR, SDLoc(N), VT, N1, N0);
3411 // fold (or x, 0) -> x
3412 if (N1C && N1C->isNullValue())
3414 // fold (or x, -1) -> -1
3415 if (N1C && N1C->isAllOnesValue())
3417 // fold (or x, c) -> c iff (x & ~c) == 0
3418 if (N1C && DAG.MaskedValueIsZero(N0, ~N1C->getAPIntValue()))
3421 // Recognize halfword bswaps as (bswap + rotl 16) or (bswap + shl 16)
3422 SDValue BSwap = MatchBSwapHWord(N, N0, N1);
3423 if (BSwap.getNode())
3425 BSwap = MatchBSwapHWordLow(N, N0, N1);
3426 if (BSwap.getNode())
3430 SDValue ROR = ReassociateOps(ISD::OR, SDLoc(N), N0, N1);
3433 // Canonicalize (or (and X, c1), c2) -> (and (or X, c2), c1|c2)
3434 // iff (c1 & c2) == 0.
3435 if (N1C && N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() &&
3436 isa<ConstantSDNode>(N0.getOperand(1))) {
3437 ConstantSDNode *C1 = cast<ConstantSDNode>(N0.getOperand(1));
3438 if ((C1->getAPIntValue() & N1C->getAPIntValue()) != 0) {
3439 SDValue COR = DAG.FoldConstantArithmetic(ISD::OR, VT, N1C, C1);
3442 return DAG.getNode(ISD::AND, SDLoc(N), VT,
3443 DAG.getNode(ISD::OR, SDLoc(N0), VT,
3444 N0.getOperand(0), N1), COR);
3447 // fold (or (setcc x), (setcc y)) -> (setcc (or x, y))
3448 if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){
3449 ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get();
3450 ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get();
3452 if (LR == RR && isa<ConstantSDNode>(LR) && Op0 == Op1 &&
3453 LL.getValueType().isInteger()) {
3454 // fold (or (setne X, 0), (setne Y, 0)) -> (setne (or X, Y), 0)
3455 // fold (or (setlt X, 0), (setlt Y, 0)) -> (setne (or X, Y), 0)
3456 if (cast<ConstantSDNode>(LR)->isNullValue() &&
3457 (Op1 == ISD::SETNE || Op1 == ISD::SETLT)) {
3458 SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(LR),
3459 LR.getValueType(), LL, RL);
3460 AddToWorklist(ORNode.getNode());
3461 return DAG.getSetCC(SDLoc(N), VT, ORNode, LR, Op1);
3463 // fold (or (setne X, -1), (setne Y, -1)) -> (setne (and X, Y), -1)
3464 // fold (or (setgt X, -1), (setgt Y -1)) -> (setgt (and X, Y), -1)
3465 if (cast<ConstantSDNode>(LR)->isAllOnesValue() &&
3466 (Op1 == ISD::SETNE || Op1 == ISD::SETGT)) {
3467 SDValue ANDNode = DAG.getNode(ISD::AND, SDLoc(LR),
3468 LR.getValueType(), LL, RL);
3469 AddToWorklist(ANDNode.getNode());
3470 return DAG.getSetCC(SDLoc(N), VT, ANDNode, LR, Op1);
3473 // canonicalize equivalent to ll == rl
3474 if (LL == RR && LR == RL) {
3475 Op1 = ISD::getSetCCSwappedOperands(Op1);
3478 if (LL == RL && LR == RR) {
3479 bool isInteger = LL.getValueType().isInteger();
3480 ISD::CondCode Result = ISD::getSetCCOrOperation(Op0, Op1, isInteger);
3481 if (Result != ISD::SETCC_INVALID &&
3482 (!LegalOperations ||
3483 (TLI.isCondCodeLegal(Result, LL.getSimpleValueType()) &&
3484 TLI.isOperationLegal(ISD::SETCC,
3485 getSetCCResultType(N0.getValueType())))))
3486 return DAG.getSetCC(SDLoc(N), N0.getValueType(),
3491 // Simplify: (or (op x...), (op y...)) -> (op (or x, y))
3492 if (N0.getOpcode() == N1.getOpcode()) {
3493 SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
3494 if (Tmp.getNode()) return Tmp;
3497 // (or (and X, C1), (and Y, C2)) -> (and (or X, Y), C3) if possible.
3498 if (N0.getOpcode() == ISD::AND &&
3499 N1.getOpcode() == ISD::AND &&
3500 N0.getOperand(1).getOpcode() == ISD::Constant &&
3501 N1.getOperand(1).getOpcode() == ISD::Constant &&
3502 // Don't increase # computations.
3503 (N0.getNode()->hasOneUse() || N1.getNode()->hasOneUse())) {
3504 // We can only do this xform if we know that bits from X that are set in C2
3505 // but not in C1 are already zero. Likewise for Y.
3506 const APInt &LHSMask =
3507 cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
3508 const APInt &RHSMask =
3509 cast<ConstantSDNode>(N1.getOperand(1))->getAPIntValue();
3511 if (DAG.MaskedValueIsZero(N0.getOperand(0), RHSMask&~LHSMask) &&
3512 DAG.MaskedValueIsZero(N1.getOperand(0), LHSMask&~RHSMask)) {
3513 SDValue X = DAG.getNode(ISD::OR, SDLoc(N0), VT,
3514 N0.getOperand(0), N1.getOperand(0));
3515 return DAG.getNode(ISD::AND, SDLoc(N), VT, X,
3516 DAG.getConstant(LHSMask | RHSMask, VT));
3520 // See if this is some rotate idiom.
3521 if (SDNode *Rot = MatchRotate(N0, N1, SDLoc(N)))
3522 return SDValue(Rot, 0);
3524 // Simplify the operands using demanded-bits information.
3525 if (!VT.isVector() &&
3526 SimplifyDemandedBits(SDValue(N, 0)))
3527 return SDValue(N, 0);
3532 /// Match "(X shl/srl V1) & V2" where V2 may not be present.
3533 static bool MatchRotateHalf(SDValue Op, SDValue &Shift, SDValue &Mask) {
3534 if (Op.getOpcode() == ISD::AND) {
3535 if (isa<ConstantSDNode>(Op.getOperand(1))) {
3536 Mask = Op.getOperand(1);
3537 Op = Op.getOperand(0);
3543 if (Op.getOpcode() == ISD::SRL || Op.getOpcode() == ISD::SHL) {
3551 // Return true if we can prove that, whenever Neg and Pos are both in the
3552 // range [0, OpSize), Neg == (Pos == 0 ? 0 : OpSize - Pos). This means that
3553 // for two opposing shifts shift1 and shift2 and a value X with OpBits bits:
3555 // (or (shift1 X, Neg), (shift2 X, Pos))
3557 // reduces to a rotate in direction shift2 by Pos or (equivalently) a rotate
3558 // in direction shift1 by Neg. The range [0, OpSize) means that we only need
3559 // to consider shift amounts with defined behavior.
3560 static bool matchRotateSub(SDValue Pos, SDValue Neg, unsigned OpSize) {
3561 // If OpSize is a power of 2 then:
3563 // (a) (Pos == 0 ? 0 : OpSize - Pos) == (OpSize - Pos) & (OpSize - 1)
3564 // (b) Neg == Neg & (OpSize - 1) whenever Neg is in [0, OpSize).
3566 // So if OpSize is a power of 2 and Neg is (and Neg', OpSize-1), we check
3567 // for the stronger condition:
3569 // Neg & (OpSize - 1) == (OpSize - Pos) & (OpSize - 1) [A]
3571 // for all Neg and Pos. Since Neg & (OpSize - 1) == Neg' & (OpSize - 1)
3572 // we can just replace Neg with Neg' for the rest of the function.
3574 // In other cases we check for the even stronger condition:
3576 // Neg == OpSize - Pos [B]
3578 // for all Neg and Pos. Note that the (or ...) then invokes undefined
3579 // behavior if Pos == 0 (and consequently Neg == OpSize).
3581 // We could actually use [A] whenever OpSize is a power of 2, but the
3582 // only extra cases that it would match are those uninteresting ones
3583 // where Neg and Pos are never in range at the same time. E.g. for
3584 // OpSize == 32, using [A] would allow a Neg of the form (sub 64, Pos)
3585 // as well as (sub 32, Pos), but:
3587 // (or (shift1 X, (sub 64, Pos)), (shift2 X, Pos))
3589 // always invokes undefined behavior for 32-bit X.
3591 // Below, Mask == OpSize - 1 when using [A] and is all-ones otherwise.
3592 unsigned MaskLoBits = 0;
3593 if (Neg.getOpcode() == ISD::AND &&
3594 isPowerOf2_64(OpSize) &&
3595 Neg.getOperand(1).getOpcode() == ISD::Constant &&
3596 cast<ConstantSDNode>(Neg.getOperand(1))->getAPIntValue() == OpSize - 1) {
3597 Neg = Neg.getOperand(0);
3598 MaskLoBits = Log2_64(OpSize);
3601 // Check whether Neg has the form (sub NegC, NegOp1) for some NegC and NegOp1.
3602 if (Neg.getOpcode() != ISD::SUB)
3604 ConstantSDNode *NegC = dyn_cast<ConstantSDNode>(Neg.getOperand(0));
3607 SDValue NegOp1 = Neg.getOperand(1);
3609 // On the RHS of [A], if Pos is Pos' & (OpSize - 1), just replace Pos with
3610 // Pos'. The truncation is redundant for the purpose of the equality.
3612 Pos.getOpcode() == ISD::AND &&
3613 Pos.getOperand(1).getOpcode() == ISD::Constant &&
3614 cast<ConstantSDNode>(Pos.getOperand(1))->getAPIntValue() == OpSize - 1)
3615 Pos = Pos.getOperand(0);
3617 // The condition we need is now:
3619 // (NegC - NegOp1) & Mask == (OpSize - Pos) & Mask
3621 // If NegOp1 == Pos then we need:
3623 // OpSize & Mask == NegC & Mask
3625 // (because "x & Mask" is a truncation and distributes through subtraction).
3628 Width = NegC->getAPIntValue();
3629 // Check for cases where Pos has the form (add NegOp1, PosC) for some PosC.
3630 // Then the condition we want to prove becomes:
3632 // (NegC - NegOp1) & Mask == (OpSize - (NegOp1 + PosC)) & Mask
3634 // which, again because "x & Mask" is a truncation, becomes:
3636 // NegC & Mask == (OpSize - PosC) & Mask
3637 // OpSize & Mask == (NegC + PosC) & Mask
3638 else if (Pos.getOpcode() == ISD::ADD &&
3639 Pos.getOperand(0) == NegOp1 &&
3640 Pos.getOperand(1).getOpcode() == ISD::Constant)
3641 Width = (cast<ConstantSDNode>(Pos.getOperand(1))->getAPIntValue() +
3642 NegC->getAPIntValue());
3646 // Now we just need to check that OpSize & Mask == Width & Mask.
3648 // Opsize & Mask is 0 since Mask is Opsize - 1.
3649 return Width.getLoBits(MaskLoBits) == 0;
3650 return Width == OpSize;
3653 // A subroutine of MatchRotate used once we have found an OR of two opposite
3654 // shifts of Shifted. If Neg == <operand size> - Pos then the OR reduces
3655 // to both (PosOpcode Shifted, Pos) and (NegOpcode Shifted, Neg), with the
3656 // former being preferred if supported. InnerPos and InnerNeg are Pos and
3657 // Neg with outer conversions stripped away.
3658 SDNode *DAGCombiner::MatchRotatePosNeg(SDValue Shifted, SDValue Pos,
3659 SDValue Neg, SDValue InnerPos,
3660 SDValue InnerNeg, unsigned PosOpcode,
3661 unsigned NegOpcode, SDLoc DL) {
3662 // fold (or (shl x, (*ext y)),
3663 // (srl x, (*ext (sub 32, y)))) ->
3664 // (rotl x, y) or (rotr x, (sub 32, y))
3666 // fold (or (shl x, (*ext (sub 32, y))),
3667 // (srl x, (*ext y))) ->
3668 // (rotr x, y) or (rotl x, (sub 32, y))
3669 EVT VT = Shifted.getValueType();
3670 if (matchRotateSub(InnerPos, InnerNeg, VT.getSizeInBits())) {
3671 bool HasPos = TLI.isOperationLegalOrCustom(PosOpcode, VT);
3672 return DAG.getNode(HasPos ? PosOpcode : NegOpcode, DL, VT, Shifted,
3673 HasPos ? Pos : Neg).getNode();
3679 // MatchRotate - Handle an 'or' of two operands. If this is one of the many
3680 // idioms for rotate, and if the target supports rotation instructions, generate
3682 SDNode *DAGCombiner::MatchRotate(SDValue LHS, SDValue RHS, SDLoc DL) {
3683 // Must be a legal type. Expanded 'n promoted things won't work with rotates.
3684 EVT VT = LHS.getValueType();
3685 if (!TLI.isTypeLegal(VT)) return nullptr;
3687 // The target must have at least one rotate flavor.
3688 bool HasROTL = TLI.isOperationLegalOrCustom(ISD::ROTL, VT);
3689 bool HasROTR = TLI.isOperationLegalOrCustom(ISD::ROTR, VT);
3690 if (!HasROTL && !HasROTR) return nullptr;
3692 // Match "(X shl/srl V1) & V2" where V2 may not be present.
3693 SDValue LHSShift; // The shift.
3694 SDValue LHSMask; // AND value if any.
3695 if (!MatchRotateHalf(LHS, LHSShift, LHSMask))
3696 return nullptr; // Not part of a rotate.
3698 SDValue RHSShift; // The shift.
3699 SDValue RHSMask; // AND value if any.
3700 if (!MatchRotateHalf(RHS, RHSShift, RHSMask))
3701 return nullptr; // Not part of a rotate.
3703 if (LHSShift.getOperand(0) != RHSShift.getOperand(0))
3704 return nullptr; // Not shifting the same value.
3706 if (LHSShift.getOpcode() == RHSShift.getOpcode())
3707 return nullptr; // Shifts must disagree.
3709 // Canonicalize shl to left side in a shl/srl pair.
3710 if (RHSShift.getOpcode() == ISD::SHL) {
3711 std::swap(LHS, RHS);
3712 std::swap(LHSShift, RHSShift);
3713 std::swap(LHSMask , RHSMask );
3716 unsigned OpSizeInBits = VT.getSizeInBits();
3717 SDValue LHSShiftArg = LHSShift.getOperand(0);
3718 SDValue LHSShiftAmt = LHSShift.getOperand(1);
3719 SDValue RHSShiftArg = RHSShift.getOperand(0);
3720 SDValue RHSShiftAmt = RHSShift.getOperand(1);
3722 // fold (or (shl x, C1), (srl x, C2)) -> (rotl x, C1)
3723 // fold (or (shl x, C1), (srl x, C2)) -> (rotr x, C2)
3724 if (LHSShiftAmt.getOpcode() == ISD::Constant &&
3725 RHSShiftAmt.getOpcode() == ISD::Constant) {
3726 uint64_t LShVal = cast<ConstantSDNode>(LHSShiftAmt)->getZExtValue();
3727 uint64_t RShVal = cast<ConstantSDNode>(RHSShiftAmt)->getZExtValue();
3728 if ((LShVal + RShVal) != OpSizeInBits)
3731 SDValue Rot = DAG.getNode(HasROTL ? ISD::ROTL : ISD::ROTR, DL, VT,
3732 LHSShiftArg, HasROTL ? LHSShiftAmt : RHSShiftAmt);
3734 // If there is an AND of either shifted operand, apply it to the result.
3735 if (LHSMask.getNode() || RHSMask.getNode()) {
3736 APInt Mask = APInt::getAllOnesValue(OpSizeInBits);
3738 if (LHSMask.getNode()) {
3739 APInt RHSBits = APInt::getLowBitsSet(OpSizeInBits, LShVal);
3740 Mask &= cast<ConstantSDNode>(LHSMask)->getAPIntValue() | RHSBits;
3742 if (RHSMask.getNode()) {
3743 APInt LHSBits = APInt::getHighBitsSet(OpSizeInBits, RShVal);
3744 Mask &= cast<ConstantSDNode>(RHSMask)->getAPIntValue() | LHSBits;
3747 Rot = DAG.getNode(ISD::AND, DL, VT, Rot, DAG.getConstant(Mask, VT));
3750 return Rot.getNode();
3753 // If there is a mask here, and we have a variable shift, we can't be sure
3754 // that we're masking out the right stuff.
3755 if (LHSMask.getNode() || RHSMask.getNode())
3758 // If the shift amount is sign/zext/any-extended just peel it off.
3759 SDValue LExtOp0 = LHSShiftAmt;
3760 SDValue RExtOp0 = RHSShiftAmt;
3761 if ((LHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND ||
3762 LHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND ||
3763 LHSShiftAmt.getOpcode() == ISD::ANY_EXTEND ||
3764 LHSShiftAmt.getOpcode() == ISD::TRUNCATE) &&
3765 (RHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND ||
3766 RHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND ||
3767 RHSShiftAmt.getOpcode() == ISD::ANY_EXTEND ||
3768 RHSShiftAmt.getOpcode() == ISD::TRUNCATE)) {
3769 LExtOp0 = LHSShiftAmt.getOperand(0);
3770 RExtOp0 = RHSShiftAmt.getOperand(0);
3773 SDNode *TryL = MatchRotatePosNeg(LHSShiftArg, LHSShiftAmt, RHSShiftAmt,
3774 LExtOp0, RExtOp0, ISD::ROTL, ISD::ROTR, DL);
3778 SDNode *TryR = MatchRotatePosNeg(RHSShiftArg, RHSShiftAmt, LHSShiftAmt,
3779 RExtOp0, LExtOp0, ISD::ROTR, ISD::ROTL, DL);
3786 SDValue DAGCombiner::visitXOR(SDNode *N) {
3787 SDValue N0 = N->getOperand(0);
3788 SDValue N1 = N->getOperand(1);
3789 SDValue LHS, RHS, CC;
3790 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
3791 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
3792 EVT VT = N0.getValueType();
3795 if (VT.isVector()) {
3796 SDValue FoldedVOp = SimplifyVBinOp(N);
3797 if (FoldedVOp.getNode()) return FoldedVOp;
3799 // fold (xor x, 0) -> x, vector edition
3800 if (ISD::isBuildVectorAllZeros(N0.getNode()))
3802 if (ISD::isBuildVectorAllZeros(N1.getNode()))
3806 // fold (xor undef, undef) -> 0. This is a common idiom (misuse).
3807 if (N0.getOpcode() == ISD::UNDEF && N1.getOpcode() == ISD::UNDEF)
3808 return DAG.getConstant(0, VT);
3809 // fold (xor x, undef) -> undef
3810 if (N0.getOpcode() == ISD::UNDEF)
3812 if (N1.getOpcode() == ISD::UNDEF)
3814 // fold (xor c1, c2) -> c1^c2
3816 return DAG.FoldConstantArithmetic(ISD::XOR, VT, N0C, N1C);
3817 // canonicalize constant to RHS
3819 return DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0);
3820 // fold (xor x, 0) -> x
3821 if (N1C && N1C->isNullValue())
3824 SDValue RXOR = ReassociateOps(ISD::XOR, SDLoc(N), N0, N1);
3828 // fold !(x cc y) -> (x !cc y)
3829 if (N1C && N1C->getAPIntValue().isAllOnesValue() &&
3830 isSetCCEquivalent(N0, LHS, RHS, CC)) {
3831 bool isInt = LHS.getValueType().isInteger();
3832 ISD::CondCode NotCC = ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(),
3835 if (!LegalOperations ||
3836 TLI.isCondCodeLegal(NotCC, LHS.getSimpleValueType())) {
3837 switch (N0.getOpcode()) {
3839 llvm_unreachable("Unhandled SetCC Equivalent!");
3841 return DAG.getSetCC(SDLoc(N), VT, LHS, RHS, NotCC);
3842 case ISD::SELECT_CC:
3843 return DAG.getSelectCC(SDLoc(N), LHS, RHS, N0.getOperand(2),
3844 N0.getOperand(3), NotCC);
3849 // fold (not (zext (setcc x, y))) -> (zext (not (setcc x, y)))
3850 if (N1C && N1C->getAPIntValue() == 1 && N0.getOpcode() == ISD::ZERO_EXTEND &&
3851 N0.getNode()->hasOneUse() &&
3852 isSetCCEquivalent(N0.getOperand(0), LHS, RHS, CC)){
3853 SDValue V = N0.getOperand(0);
3854 V = DAG.getNode(ISD::XOR, SDLoc(N0), V.getValueType(), V,
3855 DAG.getConstant(1, V.getValueType()));
3856 AddToWorklist(V.getNode());
3857 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, V);
3860 // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are setcc
3861 if (N1C && N1C->getAPIntValue() == 1 && VT == MVT::i1 &&
3862 (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
3863 SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
3864 if (isOneUseSetCC(RHS) || isOneUseSetCC(LHS)) {
3865 unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
3866 LHS = DAG.getNode(ISD::XOR, SDLoc(LHS), VT, LHS, N1); // LHS = ~LHS
3867 RHS = DAG.getNode(ISD::XOR, SDLoc(RHS), VT, RHS, N1); // RHS = ~RHS
3868 AddToWorklist(LHS.getNode()); AddToWorklist(RHS.getNode());
3869 return DAG.getNode(NewOpcode, SDLoc(N), VT, LHS, RHS);
3872 // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are constants
3873 if (N1C && N1C->isAllOnesValue() &&
3874 (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
3875 SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
3876 if (isa<ConstantSDNode>(RHS) || isa<ConstantSDNode>(LHS)) {
3877 unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
3878 LHS = DAG.getNode(ISD::XOR, SDLoc(LHS), VT, LHS, N1); // LHS = ~LHS
3879 RHS = DAG.getNode(ISD::XOR, SDLoc(RHS), VT, RHS, N1); // RHS = ~RHS
3880 AddToWorklist(LHS.getNode()); AddToWorklist(RHS.getNode());
3881 return DAG.getNode(NewOpcode, SDLoc(N), VT, LHS, RHS);
3884 // fold (xor (and x, y), y) -> (and (not x), y)
3885 if (N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() &&
3886 N0->getOperand(1) == N1) {
3887 SDValue X = N0->getOperand(0);
3888 SDValue NotX = DAG.getNOT(SDLoc(X), X, VT);
3889 AddToWorklist(NotX.getNode());
3890 return DAG.getNode(ISD::AND, SDLoc(N), VT, NotX, N1);
3892 // fold (xor (xor x, c1), c2) -> (xor x, (xor c1, c2))
3893 if (N1C && N0.getOpcode() == ISD::XOR) {
3894 ConstantSDNode *N00C = dyn_cast<ConstantSDNode>(N0.getOperand(0));
3895 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3897 return DAG.getNode(ISD::XOR, SDLoc(N), VT, N0.getOperand(1),
3898 DAG.getConstant(N1C->getAPIntValue() ^
3899 N00C->getAPIntValue(), VT));
3901 return DAG.getNode(ISD::XOR, SDLoc(N), VT, N0.getOperand(0),
3902 DAG.getConstant(N1C->getAPIntValue() ^
3903 N01C->getAPIntValue(), VT));
3905 // fold (xor x, x) -> 0
3907 return tryFoldToZero(SDLoc(N), TLI, VT, DAG, LegalOperations, LegalTypes);
3909 // Simplify: xor (op x...), (op y...) -> (op (xor x, y))
3910 if (N0.getOpcode() == N1.getOpcode()) {
3911 SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
3912 if (Tmp.getNode()) return Tmp;
3915 // Simplify the expression using non-local knowledge.
3916 if (!VT.isVector() &&
3917 SimplifyDemandedBits(SDValue(N, 0)))
3918 return SDValue(N, 0);
3923 /// Handle transforms common to the three shifts, when the shift amount is a
3925 SDValue DAGCombiner::visitShiftByConstant(SDNode *N, ConstantSDNode *Amt) {
3926 // We can't and shouldn't fold opaque constants.
3927 if (Amt->isOpaque())
3930 SDNode *LHS = N->getOperand(0).getNode();
3931 if (!LHS->hasOneUse()) return SDValue();
3933 // We want to pull some binops through shifts, so that we have (and (shift))
3934 // instead of (shift (and)), likewise for add, or, xor, etc. This sort of
3935 // thing happens with address calculations, so it's important to canonicalize
3937 bool HighBitSet = false; // Can we transform this if the high bit is set?
3939 switch (LHS->getOpcode()) {
3940 default: return SDValue();
3943 HighBitSet = false; // We can only transform sra if the high bit is clear.
3946 HighBitSet = true; // We can only transform sra if the high bit is set.
3949 if (N->getOpcode() != ISD::SHL)
3950 return SDValue(); // only shl(add) not sr[al](add).
3951 HighBitSet = false; // We can only transform sra if the high bit is clear.
3955 // We require the RHS of the binop to be a constant and not opaque as well.
3956 ConstantSDNode *BinOpCst = dyn_cast<ConstantSDNode>(LHS->getOperand(1));
3957 if (!BinOpCst || BinOpCst->isOpaque()) return SDValue();
3959 // FIXME: disable this unless the input to the binop is a shift by a constant.
3960 // If it is not a shift, it pessimizes some common cases like:
3962 // void foo(int *X, int i) { X[i & 1235] = 1; }
3963 // int bar(int *X, int i) { return X[i & 255]; }
3964 SDNode *BinOpLHSVal = LHS->getOperand(0).getNode();
3965 if ((BinOpLHSVal->getOpcode() != ISD::SHL &&
3966 BinOpLHSVal->getOpcode() != ISD::SRA &&
3967 BinOpLHSVal->getOpcode() != ISD::SRL) ||
3968 !isa<ConstantSDNode>(BinOpLHSVal->getOperand(1)))
3971 EVT VT = N->getValueType(0);
3973 // If this is a signed shift right, and the high bit is modified by the
3974 // logical operation, do not perform the transformation. The highBitSet
3975 // boolean indicates the value of the high bit of the constant which would
3976 // cause it to be modified for this operation.
3977 if (N->getOpcode() == ISD::SRA) {
3978 bool BinOpRHSSignSet = BinOpCst->getAPIntValue().isNegative();
3979 if (BinOpRHSSignSet != HighBitSet)
3983 if (!TLI.isDesirableToCommuteWithShift(LHS))
3986 // Fold the constants, shifting the binop RHS by the shift amount.
3987 SDValue NewRHS = DAG.getNode(N->getOpcode(), SDLoc(LHS->getOperand(1)),
3989 LHS->getOperand(1), N->getOperand(1));
3990 assert(isa<ConstantSDNode>(NewRHS) && "Folding was not successful!");
3992 // Create the new shift.
3993 SDValue NewShift = DAG.getNode(N->getOpcode(),
3994 SDLoc(LHS->getOperand(0)),
3995 VT, LHS->getOperand(0), N->getOperand(1));
3997 // Create the new binop.
3998 return DAG.getNode(LHS->getOpcode(), SDLoc(N), VT, NewShift, NewRHS);
4001 SDValue DAGCombiner::distributeTruncateThroughAnd(SDNode *N) {
4002 assert(N->getOpcode() == ISD::TRUNCATE);
4003 assert(N->getOperand(0).getOpcode() == ISD::AND);
4005 // (truncate:TruncVT (and N00, N01C)) -> (and (truncate:TruncVT N00), TruncC)
4006 if (N->hasOneUse() && N->getOperand(0).hasOneUse()) {
4007 SDValue N01 = N->getOperand(0).getOperand(1);
4009 if (ConstantSDNode *N01C = isConstOrConstSplat(N01)) {
4010 EVT TruncVT = N->getValueType(0);
4011 SDValue N00 = N->getOperand(0).getOperand(0);
4012 APInt TruncC = N01C->getAPIntValue();
4013 TruncC = TruncC.trunc(TruncVT.getScalarSizeInBits());
4015 return DAG.getNode(ISD::AND, SDLoc(N), TruncVT,
4016 DAG.getNode(ISD::TRUNCATE, SDLoc(N), TruncVT, N00),
4017 DAG.getConstant(TruncC, TruncVT));
4024 SDValue DAGCombiner::visitRotate(SDNode *N) {
4025 // fold (rot* x, (trunc (and y, c))) -> (rot* x, (and (trunc y), (trunc c))).
4026 if (N->getOperand(1).getOpcode() == ISD::TRUNCATE &&
4027 N->getOperand(1).getOperand(0).getOpcode() == ISD::AND) {
4028 SDValue NewOp1 = distributeTruncateThroughAnd(N->getOperand(1).getNode());
4029 if (NewOp1.getNode())
4030 return DAG.getNode(N->getOpcode(), SDLoc(N), N->getValueType(0),
4031 N->getOperand(0), NewOp1);
4036 SDValue DAGCombiner::visitSHL(SDNode *N) {
4037 SDValue N0 = N->getOperand(0);
4038 SDValue N1 = N->getOperand(1);
4039 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
4040 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4041 EVT VT = N0.getValueType();
4042 unsigned OpSizeInBits = VT.getScalarSizeInBits();
4045 if (VT.isVector()) {
4046 SDValue FoldedVOp = SimplifyVBinOp(N);
4047 if (FoldedVOp.getNode()) return FoldedVOp;
4049 BuildVectorSDNode *N1CV = dyn_cast<BuildVectorSDNode>(N1);
4050 // If setcc produces all-one true value then:
4051 // (shl (and (setcc) N01CV) N1CV) -> (and (setcc) N01CV<<N1CV)
4052 if (N1CV && N1CV->isConstant()) {
4053 if (N0.getOpcode() == ISD::AND) {
4054 SDValue N00 = N0->getOperand(0);
4055 SDValue N01 = N0->getOperand(1);
4056 BuildVectorSDNode *N01CV = dyn_cast<BuildVectorSDNode>(N01);
4058 if (N01CV && N01CV->isConstant() && N00.getOpcode() == ISD::SETCC &&
4059 TLI.getBooleanContents(N00.getOperand(0).getValueType()) ==
4060 TargetLowering::ZeroOrNegativeOneBooleanContent) {
4061 SDValue C = DAG.FoldConstantArithmetic(ISD::SHL, VT, N01CV, N1CV);
4063 return DAG.getNode(ISD::AND, SDLoc(N), VT, N00, C);
4066 N1C = isConstOrConstSplat(N1);
4071 // fold (shl c1, c2) -> c1<<c2
4073 return DAG.FoldConstantArithmetic(ISD::SHL, VT, N0C, N1C);
4074 // fold (shl 0, x) -> 0
4075 if (N0C && N0C->isNullValue())
4077 // fold (shl x, c >= size(x)) -> undef
4078 if (N1C && N1C->getZExtValue() >= OpSizeInBits)
4079 return DAG.getUNDEF(VT);
4080 // fold (shl x, 0) -> x
4081 if (N1C && N1C->isNullValue())
4083 // fold (shl undef, x) -> 0
4084 if (N0.getOpcode() == ISD::UNDEF)
4085 return DAG.getConstant(0, VT);
4086 // if (shl x, c) is known to be zero, return 0
4087 if (DAG.MaskedValueIsZero(SDValue(N, 0),
4088 APInt::getAllOnesValue(OpSizeInBits)))
4089 return DAG.getConstant(0, VT);
4090 // fold (shl x, (trunc (and y, c))) -> (shl x, (and (trunc y), (trunc c))).
4091 if (N1.getOpcode() == ISD::TRUNCATE &&
4092 N1.getOperand(0).getOpcode() == ISD::AND) {
4093 SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode());
4094 if (NewOp1.getNode())
4095 return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0, NewOp1);
4098 if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
4099 return SDValue(N, 0);
4101 // fold (shl (shl x, c1), c2) -> 0 or (shl x, (add c1, c2))
4102 if (N1C && N0.getOpcode() == ISD::SHL) {
4103 if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) {
4104 uint64_t c1 = N0C1->getZExtValue();
4105 uint64_t c2 = N1C->getZExtValue();
4106 if (c1 + c2 >= OpSizeInBits)
4107 return DAG.getConstant(0, VT);
4108 return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0.getOperand(0),
4109 DAG.getConstant(c1 + c2, N1.getValueType()));
4113 // fold (shl (ext (shl x, c1)), c2) -> (ext (shl x, (add c1, c2)))
4114 // For this to be valid, the second form must not preserve any of the bits
4115 // that are shifted out by the inner shift in the first form. This means
4116 // the outer shift size must be >= the number of bits added by the ext.
4117 // As a corollary, we don't care what kind of ext it is.
4118 if (N1C && (N0.getOpcode() == ISD::ZERO_EXTEND ||
4119 N0.getOpcode() == ISD::ANY_EXTEND ||
4120 N0.getOpcode() == ISD::SIGN_EXTEND) &&
4121 N0.getOperand(0).getOpcode() == ISD::SHL) {
4122 SDValue N0Op0 = N0.getOperand(0);
4123 if (ConstantSDNode *N0Op0C1 = isConstOrConstSplat(N0Op0.getOperand(1))) {
4124 uint64_t c1 = N0Op0C1->getZExtValue();
4125 uint64_t c2 = N1C->getZExtValue();
4126 EVT InnerShiftVT = N0Op0.getValueType();
4127 uint64_t InnerShiftSize = InnerShiftVT.getScalarSizeInBits();
4128 if (c2 >= OpSizeInBits - InnerShiftSize) {
4129 if (c1 + c2 >= OpSizeInBits)
4130 return DAG.getConstant(0, VT);
4131 return DAG.getNode(ISD::SHL, SDLoc(N0), VT,
4132 DAG.getNode(N0.getOpcode(), SDLoc(N0), VT,
4133 N0Op0->getOperand(0)),
4134 DAG.getConstant(c1 + c2, N1.getValueType()));
4139 // fold (shl (zext (srl x, C)), C) -> (zext (shl (srl x, C), C))
4140 // Only fold this if the inner zext has no other uses to avoid increasing
4141 // the total number of instructions.
4142 if (N1C && N0.getOpcode() == ISD::ZERO_EXTEND && N0.hasOneUse() &&
4143 N0.getOperand(0).getOpcode() == ISD::SRL) {
4144 SDValue N0Op0 = N0.getOperand(0);
4145 if (ConstantSDNode *N0Op0C1 = isConstOrConstSplat(N0Op0.getOperand(1))) {
4146 uint64_t c1 = N0Op0C1->getZExtValue();
4147 if (c1 < VT.getScalarSizeInBits()) {
4148 uint64_t c2 = N1C->getZExtValue();
4150 SDValue NewOp0 = N0.getOperand(0);
4151 EVT CountVT = NewOp0.getOperand(1).getValueType();
4152 SDValue NewSHL = DAG.getNode(ISD::SHL, SDLoc(N), NewOp0.getValueType(),
4153 NewOp0, DAG.getConstant(c2, CountVT));
4154 AddToWorklist(NewSHL.getNode());
4155 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N0), VT, NewSHL);
4161 // fold (shl (srl x, c1), c2) -> (and (shl x, (sub c2, c1), MASK) or
4162 // (and (srl x, (sub c1, c2), MASK)
4163 // Only fold this if the inner shift has no other uses -- if it does, folding
4164 // this will increase the total number of instructions.
4165 if (N1C && N0.getOpcode() == ISD::SRL && N0.hasOneUse()) {
4166 if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) {
4167 uint64_t c1 = N0C1->getZExtValue();
4168 if (c1 < OpSizeInBits) {
4169 uint64_t c2 = N1C->getZExtValue();
4170 APInt Mask = APInt::getHighBitsSet(OpSizeInBits, OpSizeInBits - c1);
4173 Mask = Mask.shl(c2 - c1);
4174 Shift = DAG.getNode(ISD::SHL, SDLoc(N), VT, N0.getOperand(0),
4175 DAG.getConstant(c2 - c1, N1.getValueType()));
4177 Mask = Mask.lshr(c1 - c2);
4178 Shift = DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0),
4179 DAG.getConstant(c1 - c2, N1.getValueType()));
4181 return DAG.getNode(ISD::AND, SDLoc(N0), VT, Shift,
4182 DAG.getConstant(Mask, VT));
4186 // fold (shl (sra x, c1), c1) -> (and x, (shl -1, c1))
4187 if (N1C && N0.getOpcode() == ISD::SRA && N1 == N0.getOperand(1)) {
4188 unsigned BitSize = VT.getScalarSizeInBits();
4189 SDValue HiBitsMask =
4190 DAG.getConstant(APInt::getHighBitsSet(BitSize,
4191 BitSize - N1C->getZExtValue()), VT);
4192 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0.getOperand(0),
4196 // fold (shl (add x, c1), c2) -> (add (shl x, c2), c1 << c2)
4197 // Variant of version done on multiply, except mul by a power of 2 is turned
4200 if (N1C && N0.getOpcode() == ISD::ADD && N0.getNode()->hasOneUse() &&
4201 (isa<ConstantSDNode>(N0.getOperand(1)) ||
4202 isConstantSplatVector(N0.getOperand(1).getNode(), Val))) {
4203 SDValue Shl0 = DAG.getNode(ISD::SHL, SDLoc(N0), VT, N0.getOperand(0), N1);
4204 SDValue Shl1 = DAG.getNode(ISD::SHL, SDLoc(N1), VT, N0.getOperand(1), N1);
4205 return DAG.getNode(ISD::ADD, SDLoc(N), VT, Shl0, Shl1);
4209 SDValue NewSHL = visitShiftByConstant(N, N1C);
4210 if (NewSHL.getNode())
4217 SDValue DAGCombiner::visitSRA(SDNode *N) {
4218 SDValue N0 = N->getOperand(0);
4219 SDValue N1 = N->getOperand(1);
4220 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
4221 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4222 EVT VT = N0.getValueType();
4223 unsigned OpSizeInBits = VT.getScalarType().getSizeInBits();
4226 if (VT.isVector()) {
4227 SDValue FoldedVOp = SimplifyVBinOp(N);
4228 if (FoldedVOp.getNode()) return FoldedVOp;
4230 N1C = isConstOrConstSplat(N1);
4233 // fold (sra c1, c2) -> (sra c1, c2)
4235 return DAG.FoldConstantArithmetic(ISD::SRA, VT, N0C, N1C);
4236 // fold (sra 0, x) -> 0
4237 if (N0C && N0C->isNullValue())
4239 // fold (sra -1, x) -> -1
4240 if (N0C && N0C->isAllOnesValue())
4242 // fold (sra x, (setge c, size(x))) -> undef
4243 if (N1C && N1C->getZExtValue() >= OpSizeInBits)
4244 return DAG.getUNDEF(VT);
4245 // fold (sra x, 0) -> x
4246 if (N1C && N1C->isNullValue())
4248 // fold (sra (shl x, c1), c1) -> sext_inreg for some c1 and target supports
4250 if (N1C && N0.getOpcode() == ISD::SHL && N1 == N0.getOperand(1)) {
4251 unsigned LowBits = OpSizeInBits - (unsigned)N1C->getZExtValue();
4252 EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), LowBits);
4254 ExtVT = EVT::getVectorVT(*DAG.getContext(),
4255 ExtVT, VT.getVectorNumElements());
4256 if ((!LegalOperations ||
4257 TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, ExtVT)))
4258 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
4259 N0.getOperand(0), DAG.getValueType(ExtVT));
4262 // fold (sra (sra x, c1), c2) -> (sra x, (add c1, c2))
4263 if (N1C && N0.getOpcode() == ISD::SRA) {
4264 if (ConstantSDNode *C1 = isConstOrConstSplat(N0.getOperand(1))) {
4265 unsigned Sum = N1C->getZExtValue() + C1->getZExtValue();
4266 if (Sum >= OpSizeInBits)
4267 Sum = OpSizeInBits - 1;
4268 return DAG.getNode(ISD::SRA, SDLoc(N), VT, N0.getOperand(0),
4269 DAG.getConstant(Sum, N1.getValueType()));
4273 // fold (sra (shl X, m), (sub result_size, n))
4274 // -> (sign_extend (trunc (shl X, (sub (sub result_size, n), m)))) for
4275 // result_size - n != m.
4276 // If truncate is free for the target sext(shl) is likely to result in better
4278 if (N0.getOpcode() == ISD::SHL && N1C) {
4279 // Get the two constanst of the shifts, CN0 = m, CN = n.
4280 const ConstantSDNode *N01C = isConstOrConstSplat(N0.getOperand(1));
4282 LLVMContext &Ctx = *DAG.getContext();
4283 // Determine what the truncate's result bitsize and type would be.
4284 EVT TruncVT = EVT::getIntegerVT(Ctx, OpSizeInBits - N1C->getZExtValue());
4287 TruncVT = EVT::getVectorVT(Ctx, TruncVT, VT.getVectorNumElements());
4289 // Determine the residual right-shift amount.
4290 signed ShiftAmt = N1C->getZExtValue() - N01C->getZExtValue();
4292 // If the shift is not a no-op (in which case this should be just a sign
4293 // extend already), the truncated to type is legal, sign_extend is legal
4294 // on that type, and the truncate to that type is both legal and free,
4295 // perform the transform.
4296 if ((ShiftAmt > 0) &&
4297 TLI.isOperationLegalOrCustom(ISD::SIGN_EXTEND, TruncVT) &&
4298 TLI.isOperationLegalOrCustom(ISD::TRUNCATE, VT) &&
4299 TLI.isTruncateFree(VT, TruncVT)) {
4301 SDValue Amt = DAG.getConstant(ShiftAmt,
4302 getShiftAmountTy(N0.getOperand(0).getValueType()));
4303 SDValue Shift = DAG.getNode(ISD::SRL, SDLoc(N0), VT,
4304 N0.getOperand(0), Amt);
4305 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0), TruncVT,
4307 return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N),
4308 N->getValueType(0), Trunc);
4313 // fold (sra x, (trunc (and y, c))) -> (sra x, (and (trunc y), (trunc c))).
4314 if (N1.getOpcode() == ISD::TRUNCATE &&
4315 N1.getOperand(0).getOpcode() == ISD::AND) {
4316 SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode());
4317 if (NewOp1.getNode())
4318 return DAG.getNode(ISD::SRA, SDLoc(N), VT, N0, NewOp1);
4321 // fold (sra (trunc (srl x, c1)), c2) -> (trunc (sra x, c1 + c2))
4322 // if c1 is equal to the number of bits the trunc removes
4323 if (N0.getOpcode() == ISD::TRUNCATE &&
4324 (N0.getOperand(0).getOpcode() == ISD::SRL ||
4325 N0.getOperand(0).getOpcode() == ISD::SRA) &&
4326 N0.getOperand(0).hasOneUse() &&
4327 N0.getOperand(0).getOperand(1).hasOneUse() &&
4329 SDValue N0Op0 = N0.getOperand(0);
4330 if (ConstantSDNode *LargeShift = isConstOrConstSplat(N0Op0.getOperand(1))) {
4331 unsigned LargeShiftVal = LargeShift->getZExtValue();
4332 EVT LargeVT = N0Op0.getValueType();
4334 if (LargeVT.getScalarSizeInBits() - OpSizeInBits == LargeShiftVal) {
4336 DAG.getConstant(LargeShiftVal + N1C->getZExtValue(),
4337 getShiftAmountTy(N0Op0.getOperand(0).getValueType()));
4338 SDValue SRA = DAG.getNode(ISD::SRA, SDLoc(N), LargeVT,
4339 N0Op0.getOperand(0), Amt);
4340 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, SRA);
4345 // Simplify, based on bits shifted out of the LHS.
4346 if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
4347 return SDValue(N, 0);
4350 // If the sign bit is known to be zero, switch this to a SRL.
4351 if (DAG.SignBitIsZero(N0))
4352 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, N1);
4355 SDValue NewSRA = visitShiftByConstant(N, N1C);
4356 if (NewSRA.getNode())
4363 SDValue DAGCombiner::visitSRL(SDNode *N) {
4364 SDValue N0 = N->getOperand(0);
4365 SDValue N1 = N->getOperand(1);
4366 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
4367 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4368 EVT VT = N0.getValueType();
4369 unsigned OpSizeInBits = VT.getScalarType().getSizeInBits();
4372 if (VT.isVector()) {
4373 SDValue FoldedVOp = SimplifyVBinOp(N);
4374 if (FoldedVOp.getNode()) return FoldedVOp;
4376 N1C = isConstOrConstSplat(N1);
4379 // fold (srl c1, c2) -> c1 >>u c2
4381 return DAG.FoldConstantArithmetic(ISD::SRL, VT, N0C, N1C);
4382 // fold (srl 0, x) -> 0
4383 if (N0C && N0C->isNullValue())
4385 // fold (srl x, c >= size(x)) -> undef
4386 if (N1C && N1C->getZExtValue() >= OpSizeInBits)
4387 return DAG.getUNDEF(VT);
4388 // fold (srl x, 0) -> x
4389 if (N1C && N1C->isNullValue())
4391 // if (srl x, c) is known to be zero, return 0
4392 if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0),
4393 APInt::getAllOnesValue(OpSizeInBits)))
4394 return DAG.getConstant(0, VT);
4396 // fold (srl (srl x, c1), c2) -> 0 or (srl x, (add c1, c2))
4397 if (N1C && N0.getOpcode() == ISD::SRL) {
4398 if (ConstantSDNode *N01C = isConstOrConstSplat(N0.getOperand(1))) {
4399 uint64_t c1 = N01C->getZExtValue();
4400 uint64_t c2 = N1C->getZExtValue();
4401 if (c1 + c2 >= OpSizeInBits)
4402 return DAG.getConstant(0, VT);
4403 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0),
4404 DAG.getConstant(c1 + c2, N1.getValueType()));
4408 // fold (srl (trunc (srl x, c1)), c2) -> 0 or (trunc (srl x, (add c1, c2)))
4409 if (N1C && N0.getOpcode() == ISD::TRUNCATE &&
4410 N0.getOperand(0).getOpcode() == ISD::SRL &&
4411 isa<ConstantSDNode>(N0.getOperand(0)->getOperand(1))) {
4413 cast<ConstantSDNode>(N0.getOperand(0)->getOperand(1))->getZExtValue();
4414 uint64_t c2 = N1C->getZExtValue();
4415 EVT InnerShiftVT = N0.getOperand(0).getValueType();
4416 EVT ShiftCountVT = N0.getOperand(0)->getOperand(1).getValueType();
4417 uint64_t InnerShiftSize = InnerShiftVT.getScalarType().getSizeInBits();
4418 // This is only valid if the OpSizeInBits + c1 = size of inner shift.
4419 if (c1 + OpSizeInBits == InnerShiftSize) {
4420 if (c1 + c2 >= InnerShiftSize)
4421 return DAG.getConstant(0, VT);
4422 return DAG.getNode(ISD::TRUNCATE, SDLoc(N0), VT,
4423 DAG.getNode(ISD::SRL, SDLoc(N0), InnerShiftVT,
4424 N0.getOperand(0)->getOperand(0),
4425 DAG.getConstant(c1 + c2, ShiftCountVT)));
4429 // fold (srl (shl x, c), c) -> (and x, cst2)
4430 if (N1C && N0.getOpcode() == ISD::SHL && N0.getOperand(1) == N1) {
4431 unsigned BitSize = N0.getScalarValueSizeInBits();
4432 if (BitSize <= 64) {
4433 uint64_t ShAmt = N1C->getZExtValue() + 64 - BitSize;
4434 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0.getOperand(0),
4435 DAG.getConstant(~0ULL >> ShAmt, VT));
4439 // fold (srl (anyextend x), c) -> (and (anyextend (srl x, c)), mask)
4440 if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
4441 // Shifting in all undef bits?
4442 EVT SmallVT = N0.getOperand(0).getValueType();
4443 unsigned BitSize = SmallVT.getScalarSizeInBits();
4444 if (N1C->getZExtValue() >= BitSize)
4445 return DAG.getUNDEF(VT);
4447 if (!LegalTypes || TLI.isTypeDesirableForOp(ISD::SRL, SmallVT)) {
4448 uint64_t ShiftAmt = N1C->getZExtValue();
4449 SDValue SmallShift = DAG.getNode(ISD::SRL, SDLoc(N0), SmallVT,
4451 DAG.getConstant(ShiftAmt, getShiftAmountTy(SmallVT)));
4452 AddToWorklist(SmallShift.getNode());
4453 APInt Mask = APInt::getAllOnesValue(OpSizeInBits).lshr(ShiftAmt);
4454 return DAG.getNode(ISD::AND, SDLoc(N), VT,
4455 DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, SmallShift),
4456 DAG.getConstant(Mask, VT));
4460 // fold (srl (sra X, Y), 31) -> (srl X, 31). This srl only looks at the sign
4461 // bit, which is unmodified by sra.
4462 if (N1C && N1C->getZExtValue() + 1 == OpSizeInBits) {
4463 if (N0.getOpcode() == ISD::SRA)
4464 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0), N1);
4467 // fold (srl (ctlz x), "5") -> x iff x has one bit set (the low bit).
4468 if (N1C && N0.getOpcode() == ISD::CTLZ &&
4469 N1C->getAPIntValue() == Log2_32(OpSizeInBits)) {
4470 APInt KnownZero, KnownOne;
4471 DAG.computeKnownBits(N0.getOperand(0), KnownZero, KnownOne);
4473 // If any of the input bits are KnownOne, then the input couldn't be all
4474 // zeros, thus the result of the srl will always be zero.
4475 if (KnownOne.getBoolValue()) return DAG.getConstant(0, VT);
4477 // If all of the bits input the to ctlz node are known to be zero, then
4478 // the result of the ctlz is "32" and the result of the shift is one.
4479 APInt UnknownBits = ~KnownZero;
4480 if (UnknownBits == 0) return DAG.getConstant(1, VT);
4482 // Otherwise, check to see if there is exactly one bit input to the ctlz.
4483 if ((UnknownBits & (UnknownBits - 1)) == 0) {
4484 // Okay, we know that only that the single bit specified by UnknownBits
4485 // could be set on input to the CTLZ node. If this bit is set, the SRL
4486 // will return 0, if it is clear, it returns 1. Change the CTLZ/SRL pair
4487 // to an SRL/XOR pair, which is likely to simplify more.
4488 unsigned ShAmt = UnknownBits.countTrailingZeros();
4489 SDValue Op = N0.getOperand(0);
4492 Op = DAG.getNode(ISD::SRL, SDLoc(N0), VT, Op,
4493 DAG.getConstant(ShAmt, getShiftAmountTy(Op.getValueType())));
4494 AddToWorklist(Op.getNode());
4497 return DAG.getNode(ISD::XOR, SDLoc(N), VT,
4498 Op, DAG.getConstant(1, VT));
4502 // fold (srl x, (trunc (and y, c))) -> (srl x, (and (trunc y), (trunc c))).
4503 if (N1.getOpcode() == ISD::TRUNCATE &&
4504 N1.getOperand(0).getOpcode() == ISD::AND) {
4505 SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode());
4506 if (NewOp1.getNode())
4507 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, NewOp1);
4510 // fold operands of srl based on knowledge that the low bits are not
4512 if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
4513 return SDValue(N, 0);
4516 SDValue NewSRL = visitShiftByConstant(N, N1C);
4517 if (NewSRL.getNode())
4521 // Attempt to convert a srl of a load into a narrower zero-extending load.
4522 SDValue NarrowLoad = ReduceLoadWidth(N);
4523 if (NarrowLoad.getNode())
4526 // Here is a common situation. We want to optimize:
4529 // %b = and i32 %a, 2
4530 // %c = srl i32 %b, 1
4531 // brcond i32 %c ...
4537 // %c = setcc eq %b, 0
4540 // However when after the source operand of SRL is optimized into AND, the SRL
4541 // itself may not be optimized further. Look for it and add the BRCOND into
4543 if (N->hasOneUse()) {
4544 SDNode *Use = *N->use_begin();
4545 if (Use->getOpcode() == ISD::BRCOND)
4547 else if (Use->getOpcode() == ISD::TRUNCATE && Use->hasOneUse()) {
4548 // Also look pass the truncate.
4549 Use = *Use->use_begin();
4550 if (Use->getOpcode() == ISD::BRCOND)
4558 SDValue DAGCombiner::visitCTLZ(SDNode *N) {
4559 SDValue N0 = N->getOperand(0);
4560 EVT VT = N->getValueType(0);
4562 // fold (ctlz c1) -> c2
4563 if (isa<ConstantSDNode>(N0))
4564 return DAG.getNode(ISD::CTLZ, SDLoc(N), VT, N0);
4568 SDValue DAGCombiner::visitCTLZ_ZERO_UNDEF(SDNode *N) {
4569 SDValue N0 = N->getOperand(0);
4570 EVT VT = N->getValueType(0);
4572 // fold (ctlz_zero_undef c1) -> c2
4573 if (isa<ConstantSDNode>(N0))
4574 return DAG.getNode(ISD::CTLZ_ZERO_UNDEF, SDLoc(N), VT, N0);
4578 SDValue DAGCombiner::visitCTTZ(SDNode *N) {
4579 SDValue N0 = N->getOperand(0);
4580 EVT VT = N->getValueType(0);
4582 // fold (cttz c1) -> c2
4583 if (isa<ConstantSDNode>(N0))
4584 return DAG.getNode(ISD::CTTZ, SDLoc(N), VT, N0);
4588 SDValue DAGCombiner::visitCTTZ_ZERO_UNDEF(SDNode *N) {
4589 SDValue N0 = N->getOperand(0);
4590 EVT VT = N->getValueType(0);
4592 // fold (cttz_zero_undef c1) -> c2
4593 if (isa<ConstantSDNode>(N0))
4594 return DAG.getNode(ISD::CTTZ_ZERO_UNDEF, SDLoc(N), VT, N0);
4598 SDValue DAGCombiner::visitCTPOP(SDNode *N) {
4599 SDValue N0 = N->getOperand(0);
4600 EVT VT = N->getValueType(0);
4602 // fold (ctpop c1) -> c2
4603 if (isa<ConstantSDNode>(N0))
4604 return DAG.getNode(ISD::CTPOP, SDLoc(N), VT, N0);
4608 SDValue DAGCombiner::visitSELECT(SDNode *N) {
4609 SDValue N0 = N->getOperand(0);
4610 SDValue N1 = N->getOperand(1);
4611 SDValue N2 = N->getOperand(2);
4612 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
4613 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4614 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2);
4615 EVT VT = N->getValueType(0);
4616 EVT VT0 = N0.getValueType();
4618 // fold (select C, X, X) -> X
4621 // fold (select true, X, Y) -> X
4622 if (N0C && !N0C->isNullValue())
4624 // fold (select false, X, Y) -> Y
4625 if (N0C && N0C->isNullValue())
4627 // fold (select C, 1, X) -> (or C, X)
4628 if (VT == MVT::i1 && N1C && N1C->getAPIntValue() == 1)
4629 return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N2);
4630 // fold (select C, 0, 1) -> (xor C, 1)
4631 // We can't do this reliably if integer based booleans have different contents
4632 // to floating point based booleans. This is because we can't tell whether we
4633 // have an integer-based boolean or a floating-point-based boolean unless we
4634 // can find the SETCC that produced it and inspect its operands. This is
4635 // fairly easy if C is the SETCC node, but it can potentially be
4636 // undiscoverable (or not reasonably discoverable). For example, it could be
4637 // in another basic block or it could require searching a complicated
4639 if (VT.isInteger() &&
4640 (VT0 == MVT::i1 || (VT0.isInteger() &&
4641 TLI.getBooleanContents(false, false) ==
4642 TLI.getBooleanContents(false, true) &&
4643 TLI.getBooleanContents(false, false) ==
4644 TargetLowering::ZeroOrOneBooleanContent)) &&
4645 N1C && N2C && N1C->isNullValue() && N2C->getAPIntValue() == 1) {
4648 return DAG.getNode(ISD::XOR, SDLoc(N), VT0,
4649 N0, DAG.getConstant(1, VT0));
4650 XORNode = DAG.getNode(ISD::XOR, SDLoc(N0), VT0,
4651 N0, DAG.getConstant(1, VT0));
4652 AddToWorklist(XORNode.getNode());
4654 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, XORNode);
4655 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, XORNode);
4657 // fold (select C, 0, X) -> (and (not C), X)
4658 if (VT == VT0 && VT == MVT::i1 && N1C && N1C->isNullValue()) {
4659 SDValue NOTNode = DAG.getNOT(SDLoc(N0), N0, VT);
4660 AddToWorklist(NOTNode.getNode());
4661 return DAG.getNode(ISD::AND, SDLoc(N), VT, NOTNode, N2);
4663 // fold (select C, X, 1) -> (or (not C), X)
4664 if (VT == VT0 && VT == MVT::i1 && N2C && N2C->getAPIntValue() == 1) {
4665 SDValue NOTNode = DAG.getNOT(SDLoc(N0), N0, VT);
4666 AddToWorklist(NOTNode.getNode());
4667 return DAG.getNode(ISD::OR, SDLoc(N), VT, NOTNode, N1);
4669 // fold (select C, X, 0) -> (and C, X)
4670 if (VT == MVT::i1 && N2C && N2C->isNullValue())
4671 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, N1);
4672 // fold (select X, X, Y) -> (or X, Y)
4673 // fold (select X, 1, Y) -> (or X, Y)
4674 if (VT == MVT::i1 && (N0 == N1 || (N1C && N1C->getAPIntValue() == 1)))
4675 return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N2);
4676 // fold (select X, Y, X) -> (and X, Y)
4677 // fold (select X, Y, 0) -> (and X, Y)
4678 if (VT == MVT::i1 && (N0 == N2 || (N2C && N2C->getAPIntValue() == 0)))
4679 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, N1);
4681 // If we can fold this based on the true/false value, do so.
4682 if (SimplifySelectOps(N, N1, N2))
4683 return SDValue(N, 0); // Don't revisit N.
4685 // fold selects based on a setcc into other things, such as min/max/abs
4686 if (N0.getOpcode() == ISD::SETCC) {
4687 if ((!LegalOperations &&
4688 TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT)) ||
4689 TLI.isOperationLegal(ISD::SELECT_CC, VT))
4690 return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT,
4691 N0.getOperand(0), N0.getOperand(1),
4692 N1, N2, N0.getOperand(2));
4693 return SimplifySelect(SDLoc(N), N0, N1, N2);
4700 std::pair<SDValue, SDValue> SplitVSETCC(const SDNode *N, SelectionDAG &DAG) {
4703 std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(N->getValueType(0));
4705 // Split the inputs.
4706 SDValue Lo, Hi, LL, LH, RL, RH;
4707 std::tie(LL, LH) = DAG.SplitVectorOperand(N, 0);
4708 std::tie(RL, RH) = DAG.SplitVectorOperand(N, 1);
4710 Lo = DAG.getNode(N->getOpcode(), DL, LoVT, LL, RL, N->getOperand(2));
4711 Hi = DAG.getNode(N->getOpcode(), DL, HiVT, LH, RH, N->getOperand(2));
4713 return std::make_pair(Lo, Hi);
4716 // This function assumes all the vselect's arguments are CONCAT_VECTOR
4717 // nodes and that the condition is a BV of ConstantSDNodes (or undefs).
4718 static SDValue ConvertSelectToConcatVector(SDNode *N, SelectionDAG &DAG) {
4720 SDValue Cond = N->getOperand(0);
4721 SDValue LHS = N->getOperand(1);
4722 SDValue RHS = N->getOperand(2);
4723 EVT VT = N->getValueType(0);
4724 int NumElems = VT.getVectorNumElements();
4725 assert(LHS.getOpcode() == ISD::CONCAT_VECTORS &&
4726 RHS.getOpcode() == ISD::CONCAT_VECTORS &&
4727 Cond.getOpcode() == ISD::BUILD_VECTOR);
4729 // CONCAT_VECTOR can take an arbitrary number of arguments. We only care about
4730 // binary ones here.
4731 if (LHS->getNumOperands() != 2 || RHS->getNumOperands() != 2)
4734 // We're sure we have an even number of elements due to the
4735 // concat_vectors we have as arguments to vselect.
4736 // Skip BV elements until we find one that's not an UNDEF
4737 // After we find an UNDEF element, keep looping until we get to half the
4738 // length of the BV and see if all the non-undef nodes are the same.
4739 ConstantSDNode *BottomHalf = nullptr;
4740 for (int i = 0; i < NumElems / 2; ++i) {
4741 if (Cond->getOperand(i)->getOpcode() == ISD::UNDEF)
4744 if (BottomHalf == nullptr)
4745 BottomHalf = cast<ConstantSDNode>(Cond.getOperand(i));
4746 else if (Cond->getOperand(i).getNode() != BottomHalf)
4750 // Do the same for the second half of the BuildVector
4751 ConstantSDNode *TopHalf = nullptr;
4752 for (int i = NumElems / 2; i < NumElems; ++i) {
4753 if (Cond->getOperand(i)->getOpcode() == ISD::UNDEF)
4756 if (TopHalf == nullptr)
4757 TopHalf = cast<ConstantSDNode>(Cond.getOperand(i));
4758 else if (Cond->getOperand(i).getNode() != TopHalf)
4762 assert(TopHalf && BottomHalf &&
4763 "One half of the selector was all UNDEFs and the other was all the "
4764 "same value. This should have been addressed before this function.");
4766 ISD::CONCAT_VECTORS, dl, VT,
4767 BottomHalf->isNullValue() ? RHS->getOperand(0) : LHS->getOperand(0),
4768 TopHalf->isNullValue() ? RHS->getOperand(1) : LHS->getOperand(1));
4771 SDValue DAGCombiner::visitVSELECT(SDNode *N) {
4772 SDValue N0 = N->getOperand(0);
4773 SDValue N1 = N->getOperand(1);
4774 SDValue N2 = N->getOperand(2);
4777 // Canonicalize integer abs.
4778 // vselect (setg[te] X, 0), X, -X ->
4779 // vselect (setgt X, -1), X, -X ->
4780 // vselect (setl[te] X, 0), -X, X ->
4781 // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
4782 if (N0.getOpcode() == ISD::SETCC) {
4783 SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
4784 ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
4786 bool RHSIsAllZeros = ISD::isBuildVectorAllZeros(RHS.getNode());
4788 if (((RHSIsAllZeros && (CC == ISD::SETGT || CC == ISD::SETGE)) ||
4789 (ISD::isBuildVectorAllOnes(RHS.getNode()) && CC == ISD::SETGT)) &&
4790 N1 == LHS && N2.getOpcode() == ISD::SUB && N1 == N2.getOperand(1))
4791 isAbs = ISD::isBuildVectorAllZeros(N2.getOperand(0).getNode());
4792 else if ((RHSIsAllZeros && (CC == ISD::SETLT || CC == ISD::SETLE)) &&
4793 N2 == LHS && N1.getOpcode() == ISD::SUB && N2 == N1.getOperand(1))
4794 isAbs = ISD::isBuildVectorAllZeros(N1.getOperand(0).getNode());
4797 EVT VT = LHS.getValueType();
4798 SDValue Shift = DAG.getNode(
4799 ISD::SRA, DL, VT, LHS,
4800 DAG.getConstant(VT.getScalarType().getSizeInBits() - 1, VT));
4801 SDValue Add = DAG.getNode(ISD::ADD, DL, VT, LHS, Shift);
4802 AddToWorklist(Shift.getNode());
4803 AddToWorklist(Add.getNode());
4804 return DAG.getNode(ISD::XOR, DL, VT, Add, Shift);
4808 // If the VSELECT result requires splitting and the mask is provided by a
4809 // SETCC, then split both nodes and its operands before legalization. This
4810 // prevents the type legalizer from unrolling SETCC into scalar comparisons
4811 // and enables future optimizations (e.g. min/max pattern matching on X86).
4812 if (N0.getOpcode() == ISD::SETCC) {
4813 EVT VT = N->getValueType(0);
4815 // Check if any splitting is required.
4816 if (TLI.getTypeAction(*DAG.getContext(), VT) !=
4817 TargetLowering::TypeSplitVector)
4820 SDValue Lo, Hi, CCLo, CCHi, LL, LH, RL, RH;
4821 std::tie(CCLo, CCHi) = SplitVSETCC(N0.getNode(), DAG);
4822 std::tie(LL, LH) = DAG.SplitVectorOperand(N, 1);
4823 std::tie(RL, RH) = DAG.SplitVectorOperand(N, 2);
4825 Lo = DAG.getNode(N->getOpcode(), DL, LL.getValueType(), CCLo, LL, RL);
4826 Hi = DAG.getNode(N->getOpcode(), DL, LH.getValueType(), CCHi, LH, RH);
4828 // Add the new VSELECT nodes to the work list in case they need to be split
4830 AddToWorklist(Lo.getNode());
4831 AddToWorklist(Hi.getNode());
4833 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
4836 // Fold (vselect (build_vector all_ones), N1, N2) -> N1
4837 if (ISD::isBuildVectorAllOnes(N0.getNode()))
4839 // Fold (vselect (build_vector all_zeros), N1, N2) -> N2
4840 if (ISD::isBuildVectorAllZeros(N0.getNode()))
4843 // The ConvertSelectToConcatVector function is assuming both the above
4844 // checks for (vselect (build_vector all{ones,zeros) ...) have been made
4846 if (N1.getOpcode() == ISD::CONCAT_VECTORS &&
4847 N2.getOpcode() == ISD::CONCAT_VECTORS &&
4848 ISD::isBuildVectorOfConstantSDNodes(N0.getNode())) {
4849 SDValue CV = ConvertSelectToConcatVector(N, DAG);
4857 SDValue DAGCombiner::visitSELECT_CC(SDNode *N) {
4858 SDValue N0 = N->getOperand(0);
4859 SDValue N1 = N->getOperand(1);
4860 SDValue N2 = N->getOperand(2);
4861 SDValue N3 = N->getOperand(3);
4862 SDValue N4 = N->getOperand(4);
4863 ISD::CondCode CC = cast<CondCodeSDNode>(N4)->get();
4865 // fold select_cc lhs, rhs, x, x, cc -> x
4869 // Determine if the condition we're dealing with is constant
4870 SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()),
4871 N0, N1, CC, SDLoc(N), false);
4872 if (SCC.getNode()) {
4873 AddToWorklist(SCC.getNode());
4875 if (ConstantSDNode *SCCC = dyn_cast<ConstantSDNode>(SCC.getNode())) {
4876 if (!SCCC->isNullValue())
4877 return N2; // cond always true -> true val
4879 return N3; // cond always false -> false val
4882 // Fold to a simpler select_cc
4883 if (SCC.getOpcode() == ISD::SETCC)
4884 return DAG.getNode(ISD::SELECT_CC, SDLoc(N), N2.getValueType(),
4885 SCC.getOperand(0), SCC.getOperand(1), N2, N3,
4889 // If we can fold this based on the true/false value, do so.
4890 if (SimplifySelectOps(N, N2, N3))
4891 return SDValue(N, 0); // Don't revisit N.
4893 // fold select_cc into other things, such as min/max/abs
4894 return SimplifySelectCC(SDLoc(N), N0, N1, N2, N3, CC);
4897 SDValue DAGCombiner::visitSETCC(SDNode *N) {
4898 return SimplifySetCC(N->getValueType(0), N->getOperand(0), N->getOperand(1),
4899 cast<CondCodeSDNode>(N->getOperand(2))->get(),
4903 // tryToFoldExtendOfConstant - Try to fold a sext/zext/aext
4904 // dag node into a ConstantSDNode or a build_vector of constants.
4905 // This function is called by the DAGCombiner when visiting sext/zext/aext
4906 // dag nodes (see for example method DAGCombiner::visitSIGN_EXTEND).
4907 // Vector extends are not folded if operations are legal; this is to
4908 // avoid introducing illegal build_vector dag nodes.
4909 static SDNode *tryToFoldExtendOfConstant(SDNode *N, const TargetLowering &TLI,
4910 SelectionDAG &DAG, bool LegalTypes,
4911 bool LegalOperations) {
4912 unsigned Opcode = N->getOpcode();
4913 SDValue N0 = N->getOperand(0);
4914 EVT VT = N->getValueType(0);
4916 assert((Opcode == ISD::SIGN_EXTEND || Opcode == ISD::ZERO_EXTEND ||
4917 Opcode == ISD::ANY_EXTEND) && "Expected EXTEND dag node in input!");
4919 // fold (sext c1) -> c1
4920 // fold (zext c1) -> c1
4921 // fold (aext c1) -> c1
4922 if (isa<ConstantSDNode>(N0))
4923 return DAG.getNode(Opcode, SDLoc(N), VT, N0).getNode();
4925 // fold (sext (build_vector AllConstants) -> (build_vector AllConstants)
4926 // fold (zext (build_vector AllConstants) -> (build_vector AllConstants)
4927 // fold (aext (build_vector AllConstants) -> (build_vector AllConstants)
4928 EVT SVT = VT.getScalarType();
4929 if (!(VT.isVector() &&
4930 (!LegalTypes || (!LegalOperations && TLI.isTypeLegal(SVT))) &&
4931 ISD::isBuildVectorOfConstantSDNodes(N0.getNode())))
4934 // We can fold this node into a build_vector.
4935 unsigned VTBits = SVT.getSizeInBits();
4936 unsigned EVTBits = N0->getValueType(0).getScalarType().getSizeInBits();
4937 unsigned ShAmt = VTBits - EVTBits;
4938 SmallVector<SDValue, 8> Elts;
4939 unsigned NumElts = N0->getNumOperands();
4942 for (unsigned i=0; i != NumElts; ++i) {
4943 SDValue Op = N0->getOperand(i);
4944 if (Op->getOpcode() == ISD::UNDEF) {
4945 Elts.push_back(DAG.getUNDEF(SVT));
4949 ConstantSDNode *CurrentND = cast<ConstantSDNode>(Op);
4950 const APInt &C = APInt(VTBits, CurrentND->getAPIntValue().getZExtValue());
4951 if (Opcode == ISD::SIGN_EXTEND)
4952 Elts.push_back(DAG.getConstant(C.shl(ShAmt).ashr(ShAmt).getZExtValue(),
4955 Elts.push_back(DAG.getConstant(C.shl(ShAmt).lshr(ShAmt).getZExtValue(),
4959 return DAG.getNode(ISD::BUILD_VECTOR, DL, VT, Elts).getNode();
4962 // ExtendUsesToFormExtLoad - Trying to extend uses of a load to enable this:
4963 // "fold ({s|z|a}ext (load x)) -> ({s|z|a}ext (truncate ({s|z|a}extload x)))"
4964 // transformation. Returns true if extension are possible and the above
4965 // mentioned transformation is profitable.
4966 static bool ExtendUsesToFormExtLoad(SDNode *N, SDValue N0,
4968 SmallVectorImpl<SDNode *> &ExtendNodes,
4969 const TargetLowering &TLI) {
4970 bool HasCopyToRegUses = false;
4971 bool isTruncFree = TLI.isTruncateFree(N->getValueType(0), N0.getValueType());
4972 for (SDNode::use_iterator UI = N0.getNode()->use_begin(),
4973 UE = N0.getNode()->use_end();
4978 if (UI.getUse().getResNo() != N0.getResNo())
4980 // FIXME: Only extend SETCC N, N and SETCC N, c for now.
4981 if (ExtOpc != ISD::ANY_EXTEND && User->getOpcode() == ISD::SETCC) {
4982 ISD::CondCode CC = cast<CondCodeSDNode>(User->getOperand(2))->get();
4983 if (ExtOpc == ISD::ZERO_EXTEND && ISD::isSignedIntSetCC(CC))
4984 // Sign bits will be lost after a zext.
4987 for (unsigned i = 0; i != 2; ++i) {
4988 SDValue UseOp = User->getOperand(i);
4991 if (!isa<ConstantSDNode>(UseOp))
4996 ExtendNodes.push_back(User);
4999 // If truncates aren't free and there are users we can't
5000 // extend, it isn't worthwhile.
5003 // Remember if this value is live-out.
5004 if (User->getOpcode() == ISD::CopyToReg)
5005 HasCopyToRegUses = true;
5008 if (HasCopyToRegUses) {
5009 bool BothLiveOut = false;
5010 for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
5012 SDUse &Use = UI.getUse();
5013 if (Use.getResNo() == 0 && Use.getUser()->getOpcode() == ISD::CopyToReg) {
5019 // Both unextended and extended values are live out. There had better be
5020 // a good reason for the transformation.
5021 return ExtendNodes.size();
5026 void DAGCombiner::ExtendSetCCUses(const SmallVectorImpl<SDNode *> &SetCCs,
5027 SDValue Trunc, SDValue ExtLoad, SDLoc DL,
5028 ISD::NodeType ExtType) {
5029 // Extend SetCC uses if necessary.
5030 for (unsigned i = 0, e = SetCCs.size(); i != e; ++i) {
5031 SDNode *SetCC = SetCCs[i];
5032 SmallVector<SDValue, 4> Ops;
5034 for (unsigned j = 0; j != 2; ++j) {
5035 SDValue SOp = SetCC->getOperand(j);
5037 Ops.push_back(ExtLoad);
5039 Ops.push_back(DAG.getNode(ExtType, DL, ExtLoad->getValueType(0), SOp));
5042 Ops.push_back(SetCC->getOperand(2));
5043 CombineTo(SetCC, DAG.getNode(ISD::SETCC, DL, SetCC->getValueType(0), Ops));
5047 SDValue DAGCombiner::visitSIGN_EXTEND(SDNode *N) {
5048 SDValue N0 = N->getOperand(0);
5049 EVT VT = N->getValueType(0);
5051 if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
5053 return SDValue(Res, 0);
5055 // fold (sext (sext x)) -> (sext x)
5056 // fold (sext (aext x)) -> (sext x)
5057 if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
5058 return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT,
5061 if (N0.getOpcode() == ISD::TRUNCATE) {
5062 // fold (sext (truncate (load x))) -> (sext (smaller load x))
5063 // fold (sext (truncate (srl (load x), c))) -> (sext (smaller load (x+c/n)))
5064 SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
5065 if (NarrowLoad.getNode()) {
5066 SDNode* oye = N0.getNode()->getOperand(0).getNode();
5067 if (NarrowLoad.getNode() != N0.getNode()) {
5068 CombineTo(N0.getNode(), NarrowLoad);
5069 // CombineTo deleted the truncate, if needed, but not what's under it.
5072 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5075 // See if the value being truncated is already sign extended. If so, just
5076 // eliminate the trunc/sext pair.
5077 SDValue Op = N0.getOperand(0);
5078 unsigned OpBits = Op.getValueType().getScalarType().getSizeInBits();
5079 unsigned MidBits = N0.getValueType().getScalarType().getSizeInBits();
5080 unsigned DestBits = VT.getScalarType().getSizeInBits();
5081 unsigned NumSignBits = DAG.ComputeNumSignBits(Op);
5083 if (OpBits == DestBits) {
5084 // Op is i32, Mid is i8, and Dest is i32. If Op has more than 24 sign
5085 // bits, it is already ready.
5086 if (NumSignBits > DestBits-MidBits)
5088 } else if (OpBits < DestBits) {
5089 // Op is i32, Mid is i8, and Dest is i64. If Op has more than 24 sign
5090 // bits, just sext from i32.
5091 if (NumSignBits > OpBits-MidBits)
5092 return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, Op);
5094 // Op is i64, Mid is i8, and Dest is i32. If Op has more than 56 sign
5095 // bits, just truncate to i32.
5096 if (NumSignBits > OpBits-MidBits)
5097 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
5100 // fold (sext (truncate x)) -> (sextinreg x).
5101 if (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG,
5102 N0.getValueType())) {
5103 if (OpBits < DestBits)
5104 Op = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N0), VT, Op);
5105 else if (OpBits > DestBits)
5106 Op = DAG.getNode(ISD::TRUNCATE, SDLoc(N0), VT, Op);
5107 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, Op,
5108 DAG.getValueType(N0.getValueType()));
5112 // fold (sext (load x)) -> (sext (truncate (sextload x)))
5113 // None of the supported targets knows how to perform load and sign extend
5114 // on vectors in one instruction. We only perform this transformation on
5116 if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() &&
5117 ISD::isUNINDEXEDLoad(N0.getNode()) &&
5118 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
5119 TLI.isLoadExtLegal(ISD::SEXTLOAD, N0.getValueType()))) {
5120 bool DoXform = true;
5121 SmallVector<SDNode*, 4> SetCCs;
5122 if (!N0.hasOneUse())
5123 DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::SIGN_EXTEND, SetCCs, TLI);
5125 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5126 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
5128 LN0->getBasePtr(), N0.getValueType(),
5129 LN0->getMemOperand());
5130 CombineTo(N, ExtLoad);
5131 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
5132 N0.getValueType(), ExtLoad);
5133 CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
5134 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
5136 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5140 // fold (sext (sextload x)) -> (sext (truncate (sextload x)))
5141 // fold (sext ( extload x)) -> (sext (truncate (sextload x)))
5142 if ((ISD::isSEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) &&
5143 ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) {
5144 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5145 EVT MemVT = LN0->getMemoryVT();
5146 if ((!LegalOperations && !LN0->isVolatile()) ||
5147 TLI.isLoadExtLegal(ISD::SEXTLOAD, MemVT)) {
5148 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
5150 LN0->getBasePtr(), MemVT,
5151 LN0->getMemOperand());
5152 CombineTo(N, ExtLoad);
5153 CombineTo(N0.getNode(),
5154 DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
5155 N0.getValueType(), ExtLoad),
5156 ExtLoad.getValue(1));
5157 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5161 // fold (sext (and/or/xor (load x), cst)) ->
5162 // (and/or/xor (sextload x), (sext cst))
5163 if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR ||
5164 N0.getOpcode() == ISD::XOR) &&
5165 isa<LoadSDNode>(N0.getOperand(0)) &&
5166 N0.getOperand(1).getOpcode() == ISD::Constant &&
5167 TLI.isLoadExtLegal(ISD::SEXTLOAD, N0.getValueType()) &&
5168 (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) {
5169 LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0));
5170 if (LN0->getExtensionType() != ISD::ZEXTLOAD && LN0->isUnindexed()) {
5171 bool DoXform = true;
5172 SmallVector<SDNode*, 4> SetCCs;
5173 if (!N0.hasOneUse())
5174 DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0), ISD::SIGN_EXTEND,
5177 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(LN0), VT,
5178 LN0->getChain(), LN0->getBasePtr(),
5180 LN0->getMemOperand());
5181 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
5182 Mask = Mask.sext(VT.getSizeInBits());
5183 SDValue And = DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
5184 ExtLoad, DAG.getConstant(Mask, VT));
5185 SDValue Trunc = DAG.getNode(ISD::TRUNCATE,
5186 SDLoc(N0.getOperand(0)),
5187 N0.getOperand(0).getValueType(), ExtLoad);
5189 CombineTo(N0.getOperand(0).getNode(), Trunc, ExtLoad.getValue(1));
5190 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
5192 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5197 if (N0.getOpcode() == ISD::SETCC) {
5198 EVT N0VT = N0.getOperand(0).getValueType();
5199 // sext(setcc) -> sext_in_reg(vsetcc) for vectors.
5200 // Only do this before legalize for now.
5201 if (VT.isVector() && !LegalOperations &&
5202 TLI.getBooleanContents(N0VT) ==
5203 TargetLowering::ZeroOrNegativeOneBooleanContent) {
5204 // On some architectures (such as SSE/NEON/etc) the SETCC result type is
5205 // of the same size as the compared operands. Only optimize sext(setcc())
5206 // if this is the case.
5207 EVT SVT = getSetCCResultType(N0VT);
5209 // We know that the # elements of the results is the same as the
5210 // # elements of the compare (and the # elements of the compare result
5211 // for that matter). Check to see that they are the same size. If so,
5212 // we know that the element size of the sext'd result matches the
5213 // element size of the compare operands.
5214 if (VT.getSizeInBits() == SVT.getSizeInBits())
5215 return DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
5217 cast<CondCodeSDNode>(N0.getOperand(2))->get());
5219 // If the desired elements are smaller or larger than the source
5220 // elements we can use a matching integer vector type and then
5221 // truncate/sign extend
5222 EVT MatchingVectorType = N0VT.changeVectorElementTypeToInteger();
5223 if (SVT == MatchingVectorType) {
5224 SDValue VsetCC = DAG.getSetCC(SDLoc(N), MatchingVectorType,
5225 N0.getOperand(0), N0.getOperand(1),
5226 cast<CondCodeSDNode>(N0.getOperand(2))->get());
5227 return DAG.getSExtOrTrunc(VsetCC, SDLoc(N), VT);
5231 // sext(setcc x, y, cc) -> (select (setcc x, y, cc), -1, 0)
5232 unsigned ElementWidth = VT.getScalarType().getSizeInBits();
5234 DAG.getConstant(APInt::getAllOnesValue(ElementWidth), VT);
5236 SimplifySelectCC(SDLoc(N), N0.getOperand(0), N0.getOperand(1),
5237 NegOne, DAG.getConstant(0, VT),
5238 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
5239 if (SCC.getNode()) return SCC;
5241 if (!VT.isVector()) {
5242 EVT SetCCVT = getSetCCResultType(N0.getOperand(0).getValueType());
5243 if (!LegalOperations || TLI.isOperationLegal(ISD::SETCC, SetCCVT)) {
5245 ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
5246 SDValue SetCC = DAG.getSetCC(DL, SetCCVT,
5247 N0.getOperand(0), N0.getOperand(1), CC);
5248 return DAG.getSelect(DL, VT, SetCC,
5249 NegOne, DAG.getConstant(0, VT));
5254 // fold (sext x) -> (zext x) if the sign bit is known zero.
5255 if ((!LegalOperations || TLI.isOperationLegal(ISD::ZERO_EXTEND, VT)) &&
5256 DAG.SignBitIsZero(N0))
5257 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, N0);
5262 // isTruncateOf - If N is a truncate of some other value, return true, record
5263 // the value being truncated in Op and which of Op's bits are zero in KnownZero.
5264 // This function computes KnownZero to avoid a duplicated call to
5265 // computeKnownBits in the caller.
5266 static bool isTruncateOf(SelectionDAG &DAG, SDValue N, SDValue &Op,
5269 if (N->getOpcode() == ISD::TRUNCATE) {
5270 Op = N->getOperand(0);
5271 DAG.computeKnownBits(Op, KnownZero, KnownOne);
5275 if (N->getOpcode() != ISD::SETCC || N->getValueType(0) != MVT::i1 ||
5276 cast<CondCodeSDNode>(N->getOperand(2))->get() != ISD::SETNE)
5279 SDValue Op0 = N->getOperand(0);
5280 SDValue Op1 = N->getOperand(1);
5281 assert(Op0.getValueType() == Op1.getValueType());
5283 ConstantSDNode *COp0 = dyn_cast<ConstantSDNode>(Op0);
5284 ConstantSDNode *COp1 = dyn_cast<ConstantSDNode>(Op1);
5285 if (COp0 && COp0->isNullValue())
5287 else if (COp1 && COp1->isNullValue())
5292 DAG.computeKnownBits(Op, KnownZero, KnownOne);
5294 if (!(KnownZero | APInt(Op.getValueSizeInBits(), 1)).isAllOnesValue())
5300 SDValue DAGCombiner::visitZERO_EXTEND(SDNode *N) {
5301 SDValue N0 = N->getOperand(0);
5302 EVT VT = N->getValueType(0);
5304 if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
5306 return SDValue(Res, 0);
5308 // fold (zext (zext x)) -> (zext x)
5309 // fold (zext (aext x)) -> (zext x)
5310 if (N0.getOpcode() == ISD::ZERO_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
5311 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT,
5314 // fold (zext (truncate x)) -> (zext x) or
5315 // (zext (truncate x)) -> (truncate x)
5316 // This is valid when the truncated bits of x are already zero.
5317 // FIXME: We should extend this to work for vectors too.
5320 if (!VT.isVector() && isTruncateOf(DAG, N0, Op, KnownZero)) {
5321 APInt TruncatedBits =
5322 (Op.getValueSizeInBits() == N0.getValueSizeInBits()) ?
5323 APInt(Op.getValueSizeInBits(), 0) :
5324 APInt::getBitsSet(Op.getValueSizeInBits(),
5325 N0.getValueSizeInBits(),
5326 std::min(Op.getValueSizeInBits(),
5327 VT.getSizeInBits()));
5328 if (TruncatedBits == (KnownZero & TruncatedBits)) {
5329 if (VT.bitsGT(Op.getValueType()))
5330 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, Op);
5331 if (VT.bitsLT(Op.getValueType()))
5332 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
5338 // fold (zext (truncate (load x))) -> (zext (smaller load x))
5339 // fold (zext (truncate (srl (load x), c))) -> (zext (small load (x+c/n)))
5340 if (N0.getOpcode() == ISD::TRUNCATE) {
5341 SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
5342 if (NarrowLoad.getNode()) {
5343 SDNode* oye = N0.getNode()->getOperand(0).getNode();
5344 if (NarrowLoad.getNode() != N0.getNode()) {
5345 CombineTo(N0.getNode(), NarrowLoad);
5346 // CombineTo deleted the truncate, if needed, but not what's under it.
5349 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5353 // fold (zext (truncate x)) -> (and x, mask)
5354 if (N0.getOpcode() == ISD::TRUNCATE &&
5355 (!LegalOperations || TLI.isOperationLegal(ISD::AND, VT))) {
5357 // fold (zext (truncate (load x))) -> (zext (smaller load x))
5358 // fold (zext (truncate (srl (load x), c))) -> (zext (smaller load (x+c/n)))
5359 SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
5360 if (NarrowLoad.getNode()) {
5361 SDNode* oye = N0.getNode()->getOperand(0).getNode();
5362 if (NarrowLoad.getNode() != N0.getNode()) {
5363 CombineTo(N0.getNode(), NarrowLoad);
5364 // CombineTo deleted the truncate, if needed, but not what's under it.
5367 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5370 SDValue Op = N0.getOperand(0);
5371 if (Op.getValueType().bitsLT(VT)) {
5372 Op = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, Op);
5373 AddToWorklist(Op.getNode());
5374 } else if (Op.getValueType().bitsGT(VT)) {
5375 Op = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
5376 AddToWorklist(Op.getNode());
5378 return DAG.getZeroExtendInReg(Op, SDLoc(N),
5379 N0.getValueType().getScalarType());
5382 // Fold (zext (and (trunc x), cst)) -> (and x, cst),
5383 // if either of the casts is not free.
5384 if (N0.getOpcode() == ISD::AND &&
5385 N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
5386 N0.getOperand(1).getOpcode() == ISD::Constant &&
5387 (!TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(),
5388 N0.getValueType()) ||
5389 !TLI.isZExtFree(N0.getValueType(), VT))) {
5390 SDValue X = N0.getOperand(0).getOperand(0);
5391 if (X.getValueType().bitsLT(VT)) {
5392 X = DAG.getNode(ISD::ANY_EXTEND, SDLoc(X), VT, X);
5393 } else if (X.getValueType().bitsGT(VT)) {
5394 X = DAG.getNode(ISD::TRUNCATE, SDLoc(X), VT, X);
5396 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
5397 Mask = Mask.zext(VT.getSizeInBits());
5398 return DAG.getNode(ISD::AND, SDLoc(N), VT,
5399 X, DAG.getConstant(Mask, VT));
5402 // fold (zext (load x)) -> (zext (truncate (zextload x)))
5403 // None of the supported targets knows how to perform load and vector_zext
5404 // on vectors in one instruction. We only perform this transformation on
5406 if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() &&
5407 ISD::isUNINDEXEDLoad(N0.getNode()) &&
5408 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
5409 TLI.isLoadExtLegal(ISD::ZEXTLOAD, N0.getValueType()))) {
5410 bool DoXform = true;
5411 SmallVector<SDNode*, 4> SetCCs;
5412 if (!N0.hasOneUse())
5413 DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ZERO_EXTEND, SetCCs, TLI);
5415 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5416 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT,
5418 LN0->getBasePtr(), N0.getValueType(),
5419 LN0->getMemOperand());
5420 CombineTo(N, ExtLoad);
5421 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
5422 N0.getValueType(), ExtLoad);
5423 CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
5425 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
5427 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5431 // fold (zext (and/or/xor (load x), cst)) ->
5432 // (and/or/xor (zextload x), (zext cst))
5433 if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR ||
5434 N0.getOpcode() == ISD::XOR) &&
5435 isa<LoadSDNode>(N0.getOperand(0)) &&
5436 N0.getOperand(1).getOpcode() == ISD::Constant &&
5437 TLI.isLoadExtLegal(ISD::ZEXTLOAD, N0.getValueType()) &&
5438 (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) {
5439 LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0));
5440 if (LN0->getExtensionType() != ISD::SEXTLOAD && LN0->isUnindexed()) {
5441 bool DoXform = true;
5442 SmallVector<SDNode*, 4> SetCCs;
5443 if (!N0.hasOneUse())
5444 DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0), ISD::ZERO_EXTEND,
5447 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), VT,
5448 LN0->getChain(), LN0->getBasePtr(),
5450 LN0->getMemOperand());
5451 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
5452 Mask = Mask.zext(VT.getSizeInBits());
5453 SDValue And = DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
5454 ExtLoad, DAG.getConstant(Mask, VT));
5455 SDValue Trunc = DAG.getNode(ISD::TRUNCATE,
5456 SDLoc(N0.getOperand(0)),
5457 N0.getOperand(0).getValueType(), ExtLoad);
5459 CombineTo(N0.getOperand(0).getNode(), Trunc, ExtLoad.getValue(1));
5460 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
5462 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5467 // fold (zext (zextload x)) -> (zext (truncate (zextload x)))
5468 // fold (zext ( extload x)) -> (zext (truncate (zextload x)))
5469 if ((ISD::isZEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) &&
5470 ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) {
5471 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5472 EVT MemVT = LN0->getMemoryVT();
5473 if ((!LegalOperations && !LN0->isVolatile()) ||
5474 TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT)) {
5475 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT,
5477 LN0->getBasePtr(), MemVT,
5478 LN0->getMemOperand());
5479 CombineTo(N, ExtLoad);
5480 CombineTo(N0.getNode(),
5481 DAG.getNode(ISD::TRUNCATE, SDLoc(N0), N0.getValueType(),
5483 ExtLoad.getValue(1));
5484 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5488 if (N0.getOpcode() == ISD::SETCC) {
5489 if (!LegalOperations && VT.isVector() &&
5490 N0.getValueType().getVectorElementType() == MVT::i1) {
5491 EVT N0VT = N0.getOperand(0).getValueType();
5492 if (getSetCCResultType(N0VT) == N0.getValueType())
5495 // zext(setcc) -> (and (vsetcc), (1, 1, ...) for vectors.
5496 // Only do this before legalize for now.
5497 EVT EltVT = VT.getVectorElementType();
5498 SmallVector<SDValue,8> OneOps(VT.getVectorNumElements(),
5499 DAG.getConstant(1, EltVT));
5500 if (VT.getSizeInBits() == N0VT.getSizeInBits())
5501 // We know that the # elements of the results is the same as the
5502 // # elements of the compare (and the # elements of the compare result
5503 // for that matter). Check to see that they are the same size. If so,
5504 // we know that the element size of the sext'd result matches the
5505 // element size of the compare operands.
5506 return DAG.getNode(ISD::AND, SDLoc(N), VT,
5507 DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
5509 cast<CondCodeSDNode>(N0.getOperand(2))->get()),
5510 DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT,
5513 // If the desired elements are smaller or larger than the source
5514 // elements we can use a matching integer vector type and then
5515 // truncate/sign extend
5516 EVT MatchingElementType =
5517 EVT::getIntegerVT(*DAG.getContext(),
5518 N0VT.getScalarType().getSizeInBits());
5519 EVT MatchingVectorType =
5520 EVT::getVectorVT(*DAG.getContext(), MatchingElementType,
5521 N0VT.getVectorNumElements());
5523 DAG.getSetCC(SDLoc(N), MatchingVectorType, N0.getOperand(0),
5525 cast<CondCodeSDNode>(N0.getOperand(2))->get());
5526 return DAG.getNode(ISD::AND, SDLoc(N), VT,
5527 DAG.getSExtOrTrunc(VsetCC, SDLoc(N), VT),
5528 DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, OneOps));
5531 // zext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
5533 SimplifySelectCC(SDLoc(N), N0.getOperand(0), N0.getOperand(1),
5534 DAG.getConstant(1, VT), DAG.getConstant(0, VT),
5535 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
5536 if (SCC.getNode()) return SCC;
5539 // (zext (shl (zext x), cst)) -> (shl (zext x), cst)
5540 if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL) &&
5541 isa<ConstantSDNode>(N0.getOperand(1)) &&
5542 N0.getOperand(0).getOpcode() == ISD::ZERO_EXTEND &&
5544 SDValue ShAmt = N0.getOperand(1);
5545 unsigned ShAmtVal = cast<ConstantSDNode>(ShAmt)->getZExtValue();
5546 if (N0.getOpcode() == ISD::SHL) {
5547 SDValue InnerZExt = N0.getOperand(0);
5548 // If the original shl may be shifting out bits, do not perform this
5550 unsigned KnownZeroBits = InnerZExt.getValueType().getSizeInBits() -
5551 InnerZExt.getOperand(0).getValueType().getSizeInBits();
5552 if (ShAmtVal > KnownZeroBits)
5558 // Ensure that the shift amount is wide enough for the shifted value.
5559 if (VT.getSizeInBits() >= 256)
5560 ShAmt = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, ShAmt);
5562 return DAG.getNode(N0.getOpcode(), DL, VT,
5563 DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0)),
5570 SDValue DAGCombiner::visitANY_EXTEND(SDNode *N) {
5571 SDValue N0 = N->getOperand(0);
5572 EVT VT = N->getValueType(0);
5574 if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
5576 return SDValue(Res, 0);
5578 // fold (aext (aext x)) -> (aext x)
5579 // fold (aext (zext x)) -> (zext x)
5580 // fold (aext (sext x)) -> (sext x)
5581 if (N0.getOpcode() == ISD::ANY_EXTEND ||
5582 N0.getOpcode() == ISD::ZERO_EXTEND ||
5583 N0.getOpcode() == ISD::SIGN_EXTEND)
5584 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, N0.getOperand(0));
5586 // fold (aext (truncate (load x))) -> (aext (smaller load x))
5587 // fold (aext (truncate (srl (load x), c))) -> (aext (small load (x+c/n)))
5588 if (N0.getOpcode() == ISD::TRUNCATE) {
5589 SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
5590 if (NarrowLoad.getNode()) {
5591 SDNode* oye = N0.getNode()->getOperand(0).getNode();
5592 if (NarrowLoad.getNode() != N0.getNode()) {
5593 CombineTo(N0.getNode(), NarrowLoad);
5594 // CombineTo deleted the truncate, if needed, but not what's under it.
5597 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5601 // fold (aext (truncate x))
5602 if (N0.getOpcode() == ISD::TRUNCATE) {
5603 SDValue TruncOp = N0.getOperand(0);
5604 if (TruncOp.getValueType() == VT)
5605 return TruncOp; // x iff x size == zext size.
5606 if (TruncOp.getValueType().bitsGT(VT))
5607 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, TruncOp);
5608 return DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, TruncOp);
5611 // Fold (aext (and (trunc x), cst)) -> (and x, cst)
5612 // if the trunc is not free.
5613 if (N0.getOpcode() == ISD::AND &&
5614 N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
5615 N0.getOperand(1).getOpcode() == ISD::Constant &&
5616 !TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(),
5617 N0.getValueType())) {
5618 SDValue X = N0.getOperand(0).getOperand(0);
5619 if (X.getValueType().bitsLT(VT)) {
5620 X = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, X);
5621 } else if (X.getValueType().bitsGT(VT)) {
5622 X = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, X);
5624 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
5625 Mask = Mask.zext(VT.getSizeInBits());
5626 return DAG.getNode(ISD::AND, SDLoc(N), VT,
5627 X, DAG.getConstant(Mask, VT));
5630 // fold (aext (load x)) -> (aext (truncate (extload x)))
5631 // None of the supported targets knows how to perform load and any_ext
5632 // on vectors in one instruction. We only perform this transformation on
5634 if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() &&
5635 ISD::isUNINDEXEDLoad(N0.getNode()) &&
5636 TLI.isLoadExtLegal(ISD::EXTLOAD, N0.getValueType())) {
5637 bool DoXform = true;
5638 SmallVector<SDNode*, 4> SetCCs;
5639 if (!N0.hasOneUse())
5640 DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ANY_EXTEND, SetCCs, TLI);
5642 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5643 SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT,
5645 LN0->getBasePtr(), N0.getValueType(),
5646 LN0->getMemOperand());
5647 CombineTo(N, ExtLoad);
5648 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
5649 N0.getValueType(), ExtLoad);
5650 CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
5651 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
5653 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5657 // fold (aext (zextload x)) -> (aext (truncate (zextload x)))
5658 // fold (aext (sextload x)) -> (aext (truncate (sextload x)))
5659 // fold (aext ( extload x)) -> (aext (truncate (extload x)))
5660 if (N0.getOpcode() == ISD::LOAD &&
5661 !ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
5663 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5664 ISD::LoadExtType ExtType = LN0->getExtensionType();
5665 EVT MemVT = LN0->getMemoryVT();
5666 if (!LegalOperations || TLI.isLoadExtLegal(ExtType, MemVT)) {
5667 SDValue ExtLoad = DAG.getExtLoad(ExtType, SDLoc(N),
5668 VT, LN0->getChain(), LN0->getBasePtr(),
5669 MemVT, LN0->getMemOperand());
5670 CombineTo(N, ExtLoad);
5671 CombineTo(N0.getNode(),
5672 DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
5673 N0.getValueType(), ExtLoad),
5674 ExtLoad.getValue(1));
5675 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5679 if (N0.getOpcode() == ISD::SETCC) {
5681 // aext(setcc) -> vsetcc
5682 // aext(setcc) -> truncate(vsetcc)
5683 // aext(setcc) -> aext(vsetcc)
5684 // Only do this before legalize for now.
5685 if (VT.isVector() && !LegalOperations) {
5686 EVT N0VT = N0.getOperand(0).getValueType();
5687 // We know that the # elements of the results is the same as the
5688 // # elements of the compare (and the # elements of the compare result
5689 // for that matter). Check to see that they are the same size. If so,
5690 // we know that the element size of the sext'd result matches the
5691 // element size of the compare operands.
5692 if (VT.getSizeInBits() == N0VT.getSizeInBits())
5693 return DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
5695 cast<CondCodeSDNode>(N0.getOperand(2))->get());
5696 // If the desired elements are smaller or larger than the source
5697 // elements we can use a matching integer vector type and then
5698 // truncate/any extend
5700 EVT MatchingVectorType = N0VT.changeVectorElementTypeToInteger();
5702 DAG.getSetCC(SDLoc(N), MatchingVectorType, N0.getOperand(0),
5704 cast<CondCodeSDNode>(N0.getOperand(2))->get());
5705 return DAG.getAnyExtOrTrunc(VsetCC, SDLoc(N), VT);
5709 // aext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
5711 SimplifySelectCC(SDLoc(N), N0.getOperand(0), N0.getOperand(1),
5712 DAG.getConstant(1, VT), DAG.getConstant(0, VT),
5713 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
5721 /// See if the specified operand can be simplified with the knowledge that only
5722 /// the bits specified by Mask are used. If so, return the simpler operand,
5723 /// otherwise return a null SDValue.
5724 SDValue DAGCombiner::GetDemandedBits(SDValue V, const APInt &Mask) {
5725 switch (V.getOpcode()) {
5727 case ISD::Constant: {
5728 const ConstantSDNode *CV = cast<ConstantSDNode>(V.getNode());
5729 assert(CV && "Const value should be ConstSDNode.");
5730 const APInt &CVal = CV->getAPIntValue();
5731 APInt NewVal = CVal & Mask;
5733 return DAG.getConstant(NewVal, V.getValueType());
5738 // If the LHS or RHS don't contribute bits to the or, drop them.
5739 if (DAG.MaskedValueIsZero(V.getOperand(0), Mask))
5740 return V.getOperand(1);
5741 if (DAG.MaskedValueIsZero(V.getOperand(1), Mask))
5742 return V.getOperand(0);
5745 // Only look at single-use SRLs.
5746 if (!V.getNode()->hasOneUse())
5748 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(V.getOperand(1))) {
5749 // See if we can recursively simplify the LHS.
5750 unsigned Amt = RHSC->getZExtValue();
5752 // Watch out for shift count overflow though.
5753 if (Amt >= Mask.getBitWidth()) break;
5754 APInt NewMask = Mask << Amt;
5755 SDValue SimplifyLHS = GetDemandedBits(V.getOperand(0), NewMask);
5756 if (SimplifyLHS.getNode())
5757 return DAG.getNode(ISD::SRL, SDLoc(V), V.getValueType(),
5758 SimplifyLHS, V.getOperand(1));
5764 /// If the result of a wider load is shifted to right of N bits and then
5765 /// truncated to a narrower type and where N is a multiple of number of bits of
5766 /// the narrower type, transform it to a narrower load from address + N / num of
5767 /// bits of new type. If the result is to be extended, also fold the extension
5768 /// to form a extending load.
5769 SDValue DAGCombiner::ReduceLoadWidth(SDNode *N) {
5770 unsigned Opc = N->getOpcode();
5772 ISD::LoadExtType ExtType = ISD::NON_EXTLOAD;
5773 SDValue N0 = N->getOperand(0);
5774 EVT VT = N->getValueType(0);
5777 // This transformation isn't valid for vector loads.
5781 // Special case: SIGN_EXTEND_INREG is basically truncating to ExtVT then
5783 if (Opc == ISD::SIGN_EXTEND_INREG) {
5784 ExtType = ISD::SEXTLOAD;
5785 ExtVT = cast<VTSDNode>(N->getOperand(1))->getVT();
5786 } else if (Opc == ISD::SRL) {
5787 // Another special-case: SRL is basically zero-extending a narrower value.
5788 ExtType = ISD::ZEXTLOAD;
5790 ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1));
5791 if (!N01) return SDValue();
5792 ExtVT = EVT::getIntegerVT(*DAG.getContext(),
5793 VT.getSizeInBits() - N01->getZExtValue());
5795 if (LegalOperations && !TLI.isLoadExtLegal(ExtType, ExtVT))
5798 unsigned EVTBits = ExtVT.getSizeInBits();
5800 // Do not generate loads of non-round integer types since these can
5801 // be expensive (and would be wrong if the type is not byte sized).
5802 if (!ExtVT.isRound())
5806 if (N0.getOpcode() == ISD::SRL && N0.hasOneUse()) {
5807 if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
5808 ShAmt = N01->getZExtValue();
5809 // Is the shift amount a multiple of size of VT?
5810 if ((ShAmt & (EVTBits-1)) == 0) {
5811 N0 = N0.getOperand(0);
5812 // Is the load width a multiple of size of VT?
5813 if ((N0.getValueType().getSizeInBits() & (EVTBits-1)) != 0)
5817 // At this point, we must have a load or else we can't do the transform.
5818 if (!isa<LoadSDNode>(N0)) return SDValue();
5820 // Because a SRL must be assumed to *need* to zero-extend the high bits
5821 // (as opposed to anyext the high bits), we can't combine the zextload
5822 // lowering of SRL and an sextload.
5823 if (cast<LoadSDNode>(N0)->getExtensionType() == ISD::SEXTLOAD)
5826 // If the shift amount is larger than the input type then we're not
5827 // accessing any of the loaded bytes. If the load was a zextload/extload
5828 // then the result of the shift+trunc is zero/undef (handled elsewhere).
5829 if (ShAmt >= cast<LoadSDNode>(N0)->getMemoryVT().getSizeInBits())
5834 // If the load is shifted left (and the result isn't shifted back right),
5835 // we can fold the truncate through the shift.
5836 unsigned ShLeftAmt = 0;
5837 if (ShAmt == 0 && N0.getOpcode() == ISD::SHL && N0.hasOneUse() &&
5838 ExtVT == VT && TLI.isNarrowingProfitable(N0.getValueType(), VT)) {
5839 if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
5840 ShLeftAmt = N01->getZExtValue();
5841 N0 = N0.getOperand(0);
5845 // If we haven't found a load, we can't narrow it. Don't transform one with
5846 // multiple uses, this would require adding a new load.
5847 if (!isa<LoadSDNode>(N0) || !N0.hasOneUse())
5850 // Don't change the width of a volatile load.
5851 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5852 if (LN0->isVolatile())
5855 // Verify that we are actually reducing a load width here.
5856 if (LN0->getMemoryVT().getSizeInBits() < EVTBits)
5859 // For the transform to be legal, the load must produce only two values
5860 // (the value loaded and the chain). Don't transform a pre-increment
5861 // load, for example, which produces an extra value. Otherwise the
5862 // transformation is not equivalent, and the downstream logic to replace
5863 // uses gets things wrong.
5864 if (LN0->getNumValues() > 2)
5867 // If the load that we're shrinking is an extload and we're not just
5868 // discarding the extension we can't simply shrink the load. Bail.
5869 // TODO: It would be possible to merge the extensions in some cases.
5870 if (LN0->getExtensionType() != ISD::NON_EXTLOAD &&
5871 LN0->getMemoryVT().getSizeInBits() < ExtVT.getSizeInBits() + ShAmt)
5874 EVT PtrType = N0.getOperand(1).getValueType();
5876 if (PtrType == MVT::Untyped || PtrType.isExtended())
5877 // It's not possible to generate a constant of extended or untyped type.
5880 // For big endian targets, we need to adjust the offset to the pointer to
5881 // load the correct bytes.
5882 if (TLI.isBigEndian()) {
5883 unsigned LVTStoreBits = LN0->getMemoryVT().getStoreSizeInBits();
5884 unsigned EVTStoreBits = ExtVT.getStoreSizeInBits();
5885 ShAmt = LVTStoreBits - EVTStoreBits - ShAmt;
5888 uint64_t PtrOff = ShAmt / 8;
5889 unsigned NewAlign = MinAlign(LN0->getAlignment(), PtrOff);
5890 SDValue NewPtr = DAG.getNode(ISD::ADD, SDLoc(LN0),
5891 PtrType, LN0->getBasePtr(),
5892 DAG.getConstant(PtrOff, PtrType));
5893 AddToWorklist(NewPtr.getNode());
5896 if (ExtType == ISD::NON_EXTLOAD)
5897 Load = DAG.getLoad(VT, SDLoc(N0), LN0->getChain(), NewPtr,
5898 LN0->getPointerInfo().getWithOffset(PtrOff),
5899 LN0->isVolatile(), LN0->isNonTemporal(),
5900 LN0->isInvariant(), NewAlign, LN0->getAAInfo());
5902 Load = DAG.getExtLoad(ExtType, SDLoc(N0), VT, LN0->getChain(),NewPtr,
5903 LN0->getPointerInfo().getWithOffset(PtrOff),
5904 ExtVT, LN0->isVolatile(), LN0->isNonTemporal(),
5905 LN0->isInvariant(), NewAlign, LN0->getAAInfo());
5907 // Replace the old load's chain with the new load's chain.
5908 WorklistRemover DeadNodes(*this);
5909 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1));
5911 // Shift the result left, if we've swallowed a left shift.
5912 SDValue Result = Load;
5913 if (ShLeftAmt != 0) {
5914 EVT ShImmTy = getShiftAmountTy(Result.getValueType());
5915 if (!isUIntN(ShImmTy.getSizeInBits(), ShLeftAmt))
5917 // If the shift amount is as large as the result size (but, presumably,
5918 // no larger than the source) then the useful bits of the result are
5919 // zero; we can't simply return the shortened shift, because the result
5920 // of that operation is undefined.
5921 if (ShLeftAmt >= VT.getSizeInBits())
5922 Result = DAG.getConstant(0, VT);
5924 Result = DAG.getNode(ISD::SHL, SDLoc(N0), VT,
5925 Result, DAG.getConstant(ShLeftAmt, ShImmTy));
5928 // Return the new loaded value.
5932 SDValue DAGCombiner::visitSIGN_EXTEND_INREG(SDNode *N) {
5933 SDValue N0 = N->getOperand(0);
5934 SDValue N1 = N->getOperand(1);
5935 EVT VT = N->getValueType(0);
5936 EVT EVT = cast<VTSDNode>(N1)->getVT();
5937 unsigned VTBits = VT.getScalarType().getSizeInBits();
5938 unsigned EVTBits = EVT.getScalarType().getSizeInBits();
5940 // fold (sext_in_reg c1) -> c1
5941 if (isa<ConstantSDNode>(N0) || N0.getOpcode() == ISD::UNDEF)
5942 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, N0, N1);
5944 // If the input is already sign extended, just drop the extension.
5945 if (DAG.ComputeNumSignBits(N0) >= VTBits-EVTBits+1)
5948 // fold (sext_in_reg (sext_in_reg x, VT2), VT1) -> (sext_in_reg x, minVT) pt2
5949 if (N0.getOpcode() == ISD::SIGN_EXTEND_INREG &&
5950 EVT.bitsLT(cast<VTSDNode>(N0.getOperand(1))->getVT()))
5951 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
5952 N0.getOperand(0), N1);
5954 // fold (sext_in_reg (sext x)) -> (sext x)
5955 // fold (sext_in_reg (aext x)) -> (sext x)
5956 // if x is small enough.
5957 if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND) {
5958 SDValue N00 = N0.getOperand(0);
5959 if (N00.getValueType().getScalarType().getSizeInBits() <= EVTBits &&
5960 (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND, VT)))
5961 return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, N00, N1);
5964 // fold (sext_in_reg x) -> (zext_in_reg x) if the sign bit is known zero.
5965 if (DAG.MaskedValueIsZero(N0, APInt::getBitsSet(VTBits, EVTBits-1, EVTBits)))
5966 return DAG.getZeroExtendInReg(N0, SDLoc(N), EVT);
5968 // fold operands of sext_in_reg based on knowledge that the top bits are not
5970 if (SimplifyDemandedBits(SDValue(N, 0)))
5971 return SDValue(N, 0);
5973 // fold (sext_in_reg (load x)) -> (smaller sextload x)
5974 // fold (sext_in_reg (srl (load x), c)) -> (smaller sextload (x+c/evtbits))
5975 SDValue NarrowLoad = ReduceLoadWidth(N);
5976 if (NarrowLoad.getNode())
5979 // fold (sext_in_reg (srl X, 24), i8) -> (sra X, 24)
5980 // fold (sext_in_reg (srl X, 23), i8) -> (sra X, 23) iff possible.
5981 // We already fold "(sext_in_reg (srl X, 25), i8) -> srl X, 25" above.
5982 if (N0.getOpcode() == ISD::SRL) {
5983 if (ConstantSDNode *ShAmt = dyn_cast<ConstantSDNode>(N0.getOperand(1)))
5984 if (ShAmt->getZExtValue()+EVTBits <= VTBits) {
5985 // We can turn this into an SRA iff the input to the SRL is already sign
5987 unsigned InSignBits = DAG.ComputeNumSignBits(N0.getOperand(0));
5988 if (VTBits-(ShAmt->getZExtValue()+EVTBits) < InSignBits)
5989 return DAG.getNode(ISD::SRA, SDLoc(N), VT,
5990 N0.getOperand(0), N0.getOperand(1));
5994 // fold (sext_inreg (extload x)) -> (sextload x)
5995 if (ISD::isEXTLoad(N0.getNode()) &&
5996 ISD::isUNINDEXEDLoad(N0.getNode()) &&
5997 EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
5998 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
5999 TLI.isLoadExtLegal(ISD::SEXTLOAD, EVT))) {
6000 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6001 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
6003 LN0->getBasePtr(), EVT,
6004 LN0->getMemOperand());
6005 CombineTo(N, ExtLoad);
6006 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
6007 AddToWorklist(ExtLoad.getNode());
6008 return SDValue(N, 0); // Return N so it doesn't get rechecked!
6010 // fold (sext_inreg (zextload x)) -> (sextload x) iff load has one use
6011 if (ISD::isZEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
6013 EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
6014 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
6015 TLI.isLoadExtLegal(ISD::SEXTLOAD, EVT))) {
6016 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6017 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
6019 LN0->getBasePtr(), EVT,
6020 LN0->getMemOperand());
6021 CombineTo(N, ExtLoad);
6022 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
6023 return SDValue(N, 0); // Return N so it doesn't get rechecked!
6026 // Form (sext_inreg (bswap >> 16)) or (sext_inreg (rotl (bswap) 16))
6027 if (EVTBits <= 16 && N0.getOpcode() == ISD::OR) {
6028 SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0),
6029 N0.getOperand(1), false);
6030 if (BSwap.getNode())
6031 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
6035 // Fold a sext_inreg of a build_vector of ConstantSDNodes or undefs
6036 // into a build_vector.
6037 if (ISD::isBuildVectorOfConstantSDNodes(N0.getNode())) {
6038 SmallVector<SDValue, 8> Elts;
6039 unsigned NumElts = N0->getNumOperands();
6040 unsigned ShAmt = VTBits - EVTBits;
6042 for (unsigned i = 0; i != NumElts; ++i) {
6043 SDValue Op = N0->getOperand(i);
6044 if (Op->getOpcode() == ISD::UNDEF) {
6049 ConstantSDNode *CurrentND = cast<ConstantSDNode>(Op);
6050 const APInt &C = APInt(VTBits, CurrentND->getAPIntValue().getZExtValue());
6051 Elts.push_back(DAG.getConstant(C.shl(ShAmt).ashr(ShAmt).getZExtValue(),
6052 Op.getValueType()));
6055 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, Elts);
6061 SDValue DAGCombiner::visitTRUNCATE(SDNode *N) {
6062 SDValue N0 = N->getOperand(0);
6063 EVT VT = N->getValueType(0);
6064 bool isLE = TLI.isLittleEndian();
6067 if (N0.getValueType() == N->getValueType(0))
6069 // fold (truncate c1) -> c1
6070 if (isa<ConstantSDNode>(N0))
6071 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0);
6072 // fold (truncate (truncate x)) -> (truncate x)
6073 if (N0.getOpcode() == ISD::TRUNCATE)
6074 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0));
6075 // fold (truncate (ext x)) -> (ext x) or (truncate x) or x
6076 if (N0.getOpcode() == ISD::ZERO_EXTEND ||
6077 N0.getOpcode() == ISD::SIGN_EXTEND ||
6078 N0.getOpcode() == ISD::ANY_EXTEND) {
6079 if (N0.getOperand(0).getValueType().bitsLT(VT))
6080 // if the source is smaller than the dest, we still need an extend
6081 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
6083 if (N0.getOperand(0).getValueType().bitsGT(VT))
6084 // if the source is larger than the dest, than we just need the truncate
6085 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0));
6086 // if the source and dest are the same type, we can drop both the extend
6087 // and the truncate.
6088 return N0.getOperand(0);
6091 // Fold extract-and-trunc into a narrow extract. For example:
6092 // i64 x = EXTRACT_VECTOR_ELT(v2i64 val, i32 1)
6093 // i32 y = TRUNCATE(i64 x)
6095 // v16i8 b = BITCAST (v2i64 val)
6096 // i8 x = EXTRACT_VECTOR_ELT(v16i8 b, i32 8)
6098 // Note: We only run this optimization after type legalization (which often
6099 // creates this pattern) and before operation legalization after which
6100 // we need to be more careful about the vector instructions that we generate.
6101 if (N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
6102 LegalTypes && !LegalOperations && N0->hasOneUse() && VT != MVT::i1) {
6104 EVT VecTy = N0.getOperand(0).getValueType();
6105 EVT ExTy = N0.getValueType();
6106 EVT TrTy = N->getValueType(0);
6108 unsigned NumElem = VecTy.getVectorNumElements();
6109 unsigned SizeRatio = ExTy.getSizeInBits()/TrTy.getSizeInBits();
6111 EVT NVT = EVT::getVectorVT(*DAG.getContext(), TrTy, SizeRatio * NumElem);
6112 assert(NVT.getSizeInBits() == VecTy.getSizeInBits() && "Invalid Size");
6114 SDValue EltNo = N0->getOperand(1);
6115 if (isa<ConstantSDNode>(EltNo) && isTypeLegal(NVT)) {
6116 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
6117 EVT IndexTy = TLI.getVectorIdxTy();
6118 int Index = isLE ? (Elt*SizeRatio) : (Elt*SizeRatio + (SizeRatio-1));
6120 SDValue V = DAG.getNode(ISD::BITCAST, SDLoc(N),
6121 NVT, N0.getOperand(0));
6123 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT,
6125 DAG.getConstant(Index, IndexTy));
6129 // trunc (select c, a, b) -> select c, (trunc a), (trunc b)
6130 if (N0.getOpcode() == ISD::SELECT) {
6131 EVT SrcVT = N0.getValueType();
6132 if ((!LegalOperations || TLI.isOperationLegal(ISD::SELECT, SrcVT)) &&
6133 TLI.isTruncateFree(SrcVT, VT)) {
6135 SDValue Cond = N0.getOperand(0);
6136 SDValue TruncOp0 = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(1));
6137 SDValue TruncOp1 = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(2));
6138 return DAG.getNode(ISD::SELECT, SDLoc(N), VT, Cond, TruncOp0, TruncOp1);
6142 // Fold a series of buildvector, bitcast, and truncate if possible.
6144 // (2xi32 trunc (bitcast ((4xi32)buildvector x, x, y, y) 2xi64)) to
6145 // (2xi32 (buildvector x, y)).
6146 if (Level == AfterLegalizeVectorOps && VT.isVector() &&
6147 N0.getOpcode() == ISD::BITCAST && N0.hasOneUse() &&
6148 N0.getOperand(0).getOpcode() == ISD::BUILD_VECTOR &&
6149 N0.getOperand(0).hasOneUse()) {
6151 SDValue BuildVect = N0.getOperand(0);
6152 EVT BuildVectEltTy = BuildVect.getValueType().getVectorElementType();
6153 EVT TruncVecEltTy = VT.getVectorElementType();
6155 // Check that the element types match.
6156 if (BuildVectEltTy == TruncVecEltTy) {
6157 // Now we only need to compute the offset of the truncated elements.
6158 unsigned BuildVecNumElts = BuildVect.getNumOperands();
6159 unsigned TruncVecNumElts = VT.getVectorNumElements();
6160 unsigned TruncEltOffset = BuildVecNumElts / TruncVecNumElts;
6162 assert((BuildVecNumElts % TruncVecNumElts) == 0 &&
6163 "Invalid number of elements");
6165 SmallVector<SDValue, 8> Opnds;
6166 for (unsigned i = 0, e = BuildVecNumElts; i != e; i += TruncEltOffset)
6167 Opnds.push_back(BuildVect.getOperand(i));
6169 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, Opnds);
6173 // See if we can simplify the input to this truncate through knowledge that
6174 // only the low bits are being used.
6175 // For example "trunc (or (shl x, 8), y)" // -> trunc y
6176 // Currently we only perform this optimization on scalars because vectors
6177 // may have different active low bits.
6178 if (!VT.isVector()) {
6180 GetDemandedBits(N0, APInt::getLowBitsSet(N0.getValueSizeInBits(),
6181 VT.getSizeInBits()));
6182 if (Shorter.getNode())
6183 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Shorter);
6185 // fold (truncate (load x)) -> (smaller load x)
6186 // fold (truncate (srl (load x), c)) -> (smaller load (x+c/evtbits))
6187 if (!LegalTypes || TLI.isTypeDesirableForOp(N0.getOpcode(), VT)) {
6188 SDValue Reduced = ReduceLoadWidth(N);
6189 if (Reduced.getNode())
6191 // Handle the case where the load remains an extending load even
6192 // after truncation.
6193 if (N0.hasOneUse() && ISD::isUNINDEXEDLoad(N0.getNode())) {
6194 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6195 if (!LN0->isVolatile() &&
6196 LN0->getMemoryVT().getStoreSizeInBits() < VT.getSizeInBits()) {
6197 SDValue NewLoad = DAG.getExtLoad(LN0->getExtensionType(), SDLoc(LN0),
6198 VT, LN0->getChain(), LN0->getBasePtr(),
6200 LN0->getMemOperand());
6201 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLoad.getValue(1));
6206 // fold (trunc (concat ... x ...)) -> (concat ..., (trunc x), ...)),
6207 // where ... are all 'undef'.
6208 if (N0.getOpcode() == ISD::CONCAT_VECTORS && !LegalTypes) {
6209 SmallVector<EVT, 8> VTs;
6212 unsigned NumDefs = 0;
6214 for (unsigned i = 0, e = N0.getNumOperands(); i != e; ++i) {
6215 SDValue X = N0.getOperand(i);
6216 if (X.getOpcode() != ISD::UNDEF) {
6221 // Stop if more than one members are non-undef.
6224 VTs.push_back(EVT::getVectorVT(*DAG.getContext(),
6225 VT.getVectorElementType(),
6226 X.getValueType().getVectorNumElements()));
6230 return DAG.getUNDEF(VT);
6233 assert(V.getNode() && "The single defined operand is empty!");
6234 SmallVector<SDValue, 8> Opnds;
6235 for (unsigned i = 0, e = VTs.size(); i != e; ++i) {
6237 Opnds.push_back(DAG.getUNDEF(VTs[i]));
6240 SDValue NV = DAG.getNode(ISD::TRUNCATE, SDLoc(V), VTs[i], V);
6241 AddToWorklist(NV.getNode());
6242 Opnds.push_back(NV);
6244 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Opnds);
6248 // Simplify the operands using demanded-bits information.
6249 if (!VT.isVector() &&
6250 SimplifyDemandedBits(SDValue(N, 0)))
6251 return SDValue(N, 0);
6256 static SDNode *getBuildPairElt(SDNode *N, unsigned i) {
6257 SDValue Elt = N->getOperand(i);
6258 if (Elt.getOpcode() != ISD::MERGE_VALUES)
6259 return Elt.getNode();
6260 return Elt.getOperand(Elt.getResNo()).getNode();
6263 /// build_pair (load, load) -> load
6264 /// if load locations are consecutive.
6265 SDValue DAGCombiner::CombineConsecutiveLoads(SDNode *N, EVT VT) {
6266 assert(N->getOpcode() == ISD::BUILD_PAIR);
6268 LoadSDNode *LD1 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 0));
6269 LoadSDNode *LD2 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 1));
6270 if (!LD1 || !LD2 || !ISD::isNON_EXTLoad(LD1) || !LD1->hasOneUse() ||
6271 LD1->getAddressSpace() != LD2->getAddressSpace())
6273 EVT LD1VT = LD1->getValueType(0);
6275 if (ISD::isNON_EXTLoad(LD2) &&
6277 // If both are volatile this would reduce the number of volatile loads.
6278 // If one is volatile it might be ok, but play conservative and bail out.
6279 !LD1->isVolatile() &&
6280 !LD2->isVolatile() &&
6281 DAG.isConsecutiveLoad(LD2, LD1, LD1VT.getSizeInBits()/8, 1)) {
6282 unsigned Align = LD1->getAlignment();
6283 unsigned NewAlign = TLI.getDataLayout()->
6284 getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
6286 if (NewAlign <= Align &&
6287 (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT)))
6288 return DAG.getLoad(VT, SDLoc(N), LD1->getChain(),
6289 LD1->getBasePtr(), LD1->getPointerInfo(),
6290 false, false, false, Align);
6296 SDValue DAGCombiner::visitBITCAST(SDNode *N) {
6297 SDValue N0 = N->getOperand(0);
6298 EVT VT = N->getValueType(0);
6300 // If the input is a BUILD_VECTOR with all constant elements, fold this now.
6301 // Only do this before legalize, since afterward the target may be depending
6302 // on the bitconvert.
6303 // First check to see if this is all constant.
6305 N0.getOpcode() == ISD::BUILD_VECTOR && N0.getNode()->hasOneUse() &&
6307 bool isSimple = cast<BuildVectorSDNode>(N0)->isConstant();
6309 EVT DestEltVT = N->getValueType(0).getVectorElementType();
6310 assert(!DestEltVT.isVector() &&
6311 "Element type of vector ValueType must not be vector!");
6313 return ConstantFoldBITCASTofBUILD_VECTOR(N0.getNode(), DestEltVT);
6316 // If the input is a constant, let getNode fold it.
6317 if (isa<ConstantSDNode>(N0) || isa<ConstantFPSDNode>(N0)) {
6318 SDValue Res = DAG.getNode(ISD::BITCAST, SDLoc(N), VT, N0);
6319 if (Res.getNode() != N) {
6320 if (!LegalOperations ||
6321 TLI.isOperationLegal(Res.getNode()->getOpcode(), VT))
6324 // Folding it resulted in an illegal node, and it's too late to
6325 // do that. Clean up the old node and forego the transformation.
6326 // Ideally this won't happen very often, because instcombine
6327 // and the earlier dagcombine runs (where illegal nodes are
6328 // permitted) should have folded most of them already.
6329 deleteAndRecombine(Res.getNode());
6333 // (conv (conv x, t1), t2) -> (conv x, t2)
6334 if (N0.getOpcode() == ISD::BITCAST)
6335 return DAG.getNode(ISD::BITCAST, SDLoc(N), VT,
6338 // fold (conv (load x)) -> (load (conv*)x)
6339 // If the resultant load doesn't need a higher alignment than the original!
6340 if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
6341 // Do not change the width of a volatile load.
6342 !cast<LoadSDNode>(N0)->isVolatile() &&
6343 // Do not remove the cast if the types differ in endian layout.
6344 TLI.hasBigEndianPartOrdering(N0.getValueType()) ==
6345 TLI.hasBigEndianPartOrdering(VT) &&
6346 (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT)) &&
6347 TLI.isLoadBitCastBeneficial(N0.getValueType(), VT)) {
6348 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6349 unsigned Align = TLI.getDataLayout()->
6350 getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
6351 unsigned OrigAlign = LN0->getAlignment();
6353 if (Align <= OrigAlign) {
6354 SDValue Load = DAG.getLoad(VT, SDLoc(N), LN0->getChain(),
6355 LN0->getBasePtr(), LN0->getPointerInfo(),
6356 LN0->isVolatile(), LN0->isNonTemporal(),
6357 LN0->isInvariant(), OrigAlign,
6359 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1));
6364 // fold (bitconvert (fneg x)) -> (xor (bitconvert x), signbit)
6365 // fold (bitconvert (fabs x)) -> (and (bitconvert x), (not signbit))
6366 // This often reduces constant pool loads.
6367 if (((N0.getOpcode() == ISD::FNEG && !TLI.isFNegFree(N0.getValueType())) ||
6368 (N0.getOpcode() == ISD::FABS && !TLI.isFAbsFree(N0.getValueType()))) &&
6369 N0.getNode()->hasOneUse() && VT.isInteger() &&
6370 !VT.isVector() && !N0.getValueType().isVector()) {
6371 SDValue NewConv = DAG.getNode(ISD::BITCAST, SDLoc(N0), VT,
6373 AddToWorklist(NewConv.getNode());
6375 APInt SignBit = APInt::getSignBit(VT.getSizeInBits());
6376 if (N0.getOpcode() == ISD::FNEG)
6377 return DAG.getNode(ISD::XOR, SDLoc(N), VT,
6378 NewConv, DAG.getConstant(SignBit, VT));
6379 assert(N0.getOpcode() == ISD::FABS);
6380 return DAG.getNode(ISD::AND, SDLoc(N), VT,
6381 NewConv, DAG.getConstant(~SignBit, VT));
6384 // fold (bitconvert (fcopysign cst, x)) ->
6385 // (or (and (bitconvert x), sign), (and cst, (not sign)))
6386 // Note that we don't handle (copysign x, cst) because this can always be
6387 // folded to an fneg or fabs.
6388 if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse() &&
6389 isa<ConstantFPSDNode>(N0.getOperand(0)) &&
6390 VT.isInteger() && !VT.isVector()) {
6391 unsigned OrigXWidth = N0.getOperand(1).getValueType().getSizeInBits();
6392 EVT IntXVT = EVT::getIntegerVT(*DAG.getContext(), OrigXWidth);
6393 if (isTypeLegal(IntXVT)) {
6394 SDValue X = DAG.getNode(ISD::BITCAST, SDLoc(N0),
6395 IntXVT, N0.getOperand(1));
6396 AddToWorklist(X.getNode());
6398 // If X has a different width than the result/lhs, sext it or truncate it.
6399 unsigned VTWidth = VT.getSizeInBits();
6400 if (OrigXWidth < VTWidth) {
6401 X = DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, X);
6402 AddToWorklist(X.getNode());
6403 } else if (OrigXWidth > VTWidth) {
6404 // To get the sign bit in the right place, we have to shift it right
6405 // before truncating.
6406 X = DAG.getNode(ISD::SRL, SDLoc(X),
6407 X.getValueType(), X,
6408 DAG.getConstant(OrigXWidth-VTWidth, X.getValueType()));
6409 AddToWorklist(X.getNode());
6410 X = DAG.getNode(ISD::TRUNCATE, SDLoc(X), VT, X);
6411 AddToWorklist(X.getNode());
6414 APInt SignBit = APInt::getSignBit(VT.getSizeInBits());
6415 X = DAG.getNode(ISD::AND, SDLoc(X), VT,
6416 X, DAG.getConstant(SignBit, VT));
6417 AddToWorklist(X.getNode());
6419 SDValue Cst = DAG.getNode(ISD::BITCAST, SDLoc(N0),
6420 VT, N0.getOperand(0));
6421 Cst = DAG.getNode(ISD::AND, SDLoc(Cst), VT,
6422 Cst, DAG.getConstant(~SignBit, VT));
6423 AddToWorklist(Cst.getNode());
6425 return DAG.getNode(ISD::OR, SDLoc(N), VT, X, Cst);
6429 // bitconvert(build_pair(ld, ld)) -> ld iff load locations are consecutive.
6430 if (N0.getOpcode() == ISD::BUILD_PAIR) {
6431 SDValue CombineLD = CombineConsecutiveLoads(N0.getNode(), VT);
6432 if (CombineLD.getNode())
6439 SDValue DAGCombiner::visitBUILD_PAIR(SDNode *N) {
6440 EVT VT = N->getValueType(0);
6441 return CombineConsecutiveLoads(N, VT);
6444 /// We know that BV is a build_vector node with Constant, ConstantFP or Undef
6445 /// operands. DstEltVT indicates the destination element value type.
6446 SDValue DAGCombiner::
6447 ConstantFoldBITCASTofBUILD_VECTOR(SDNode *BV, EVT DstEltVT) {
6448 EVT SrcEltVT = BV->getValueType(0).getVectorElementType();
6450 // If this is already the right type, we're done.
6451 if (SrcEltVT == DstEltVT) return SDValue(BV, 0);
6453 unsigned SrcBitSize = SrcEltVT.getSizeInBits();
6454 unsigned DstBitSize = DstEltVT.getSizeInBits();
6456 // If this is a conversion of N elements of one type to N elements of another
6457 // type, convert each element. This handles FP<->INT cases.
6458 if (SrcBitSize == DstBitSize) {
6459 EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT,
6460 BV->getValueType(0).getVectorNumElements());
6462 // Due to the FP element handling below calling this routine recursively,
6463 // we can end up with a scalar-to-vector node here.
6464 if (BV->getOpcode() == ISD::SCALAR_TO_VECTOR)
6465 return DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(BV), VT,
6466 DAG.getNode(ISD::BITCAST, SDLoc(BV),
6467 DstEltVT, BV->getOperand(0)));
6469 SmallVector<SDValue, 8> Ops;
6470 for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) {
6471 SDValue Op = BV->getOperand(i);
6472 // If the vector element type is not legal, the BUILD_VECTOR operands
6473 // are promoted and implicitly truncated. Make that explicit here.
6474 if (Op.getValueType() != SrcEltVT)
6475 Op = DAG.getNode(ISD::TRUNCATE, SDLoc(BV), SrcEltVT, Op);
6476 Ops.push_back(DAG.getNode(ISD::BITCAST, SDLoc(BV),
6478 AddToWorklist(Ops.back().getNode());
6480 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(BV), VT, Ops);
6483 // Otherwise, we're growing or shrinking the elements. To avoid having to
6484 // handle annoying details of growing/shrinking FP values, we convert them to
6486 if (SrcEltVT.isFloatingPoint()) {
6487 // Convert the input float vector to a int vector where the elements are the
6489 assert((SrcEltVT == MVT::f32 || SrcEltVT == MVT::f64) && "Unknown FP VT!");
6490 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), SrcEltVT.getSizeInBits());
6491 BV = ConstantFoldBITCASTofBUILD_VECTOR(BV, IntVT).getNode();
6495 // Now we know the input is an integer vector. If the output is a FP type,
6496 // convert to integer first, then to FP of the right size.
6497 if (DstEltVT.isFloatingPoint()) {
6498 assert((DstEltVT == MVT::f32 || DstEltVT == MVT::f64) && "Unknown FP VT!");
6499 EVT TmpVT = EVT::getIntegerVT(*DAG.getContext(), DstEltVT.getSizeInBits());
6500 SDNode *Tmp = ConstantFoldBITCASTofBUILD_VECTOR(BV, TmpVT).getNode();
6502 // Next, convert to FP elements of the same size.
6503 return ConstantFoldBITCASTofBUILD_VECTOR(Tmp, DstEltVT);
6506 // Okay, we know the src/dst types are both integers of differing types.
6507 // Handling growing first.
6508 assert(SrcEltVT.isInteger() && DstEltVT.isInteger());
6509 if (SrcBitSize < DstBitSize) {
6510 unsigned NumInputsPerOutput = DstBitSize/SrcBitSize;
6512 SmallVector<SDValue, 8> Ops;
6513 for (unsigned i = 0, e = BV->getNumOperands(); i != e;
6514 i += NumInputsPerOutput) {
6515 bool isLE = TLI.isLittleEndian();
6516 APInt NewBits = APInt(DstBitSize, 0);
6517 bool EltIsUndef = true;
6518 for (unsigned j = 0; j != NumInputsPerOutput; ++j) {
6519 // Shift the previously computed bits over.
6520 NewBits <<= SrcBitSize;
6521 SDValue Op = BV->getOperand(i+ (isLE ? (NumInputsPerOutput-j-1) : j));
6522 if (Op.getOpcode() == ISD::UNDEF) continue;
6525 NewBits |= cast<ConstantSDNode>(Op)->getAPIntValue().
6526 zextOrTrunc(SrcBitSize).zext(DstBitSize);
6530 Ops.push_back(DAG.getUNDEF(DstEltVT));
6532 Ops.push_back(DAG.getConstant(NewBits, DstEltVT));
6535 EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT, Ops.size());
6536 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(BV), VT, Ops);
6539 // Finally, this must be the case where we are shrinking elements: each input
6540 // turns into multiple outputs.
6541 bool isS2V = ISD::isScalarToVector(BV);
6542 unsigned NumOutputsPerInput = SrcBitSize/DstBitSize;
6543 EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT,
6544 NumOutputsPerInput*BV->getNumOperands());
6545 SmallVector<SDValue, 8> Ops;
6547 for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) {
6548 if (BV->getOperand(i).getOpcode() == ISD::UNDEF) {
6549 for (unsigned j = 0; j != NumOutputsPerInput; ++j)
6550 Ops.push_back(DAG.getUNDEF(DstEltVT));
6554 APInt OpVal = cast<ConstantSDNode>(BV->getOperand(i))->
6555 getAPIntValue().zextOrTrunc(SrcBitSize);
6557 for (unsigned j = 0; j != NumOutputsPerInput; ++j) {
6558 APInt ThisVal = OpVal.trunc(DstBitSize);
6559 Ops.push_back(DAG.getConstant(ThisVal, DstEltVT));
6560 if (isS2V && i == 0 && j == 0 && ThisVal.zext(SrcBitSize) == OpVal)
6561 // Simply turn this into a SCALAR_TO_VECTOR of the new type.
6562 return DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(BV), VT,
6564 OpVal = OpVal.lshr(DstBitSize);
6567 // For big endian targets, swap the order of the pieces of each element.
6568 if (TLI.isBigEndian())
6569 std::reverse(Ops.end()-NumOutputsPerInput, Ops.end());
6572 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(BV), VT, Ops);
6575 SDValue DAGCombiner::visitFADD(SDNode *N) {
6576 SDValue N0 = N->getOperand(0);
6577 SDValue N1 = N->getOperand(1);
6578 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6579 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6580 EVT VT = N->getValueType(0);
6581 const TargetOptions &Options = DAG.getTarget().Options;
6584 if (VT.isVector()) {
6585 SDValue FoldedVOp = SimplifyVBinOp(N);
6586 if (FoldedVOp.getNode()) return FoldedVOp;
6589 // fold (fadd c1, c2) -> c1 + c2
6591 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N1);
6593 // canonicalize constant to RHS
6594 if (N0CFP && !N1CFP)
6595 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N1, N0);
6597 // fold (fadd A, (fneg B)) -> (fsub A, B)
6598 if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) &&
6599 isNegatibleForFree(N1, LegalOperations, TLI, &Options) == 2)
6600 return DAG.getNode(ISD::FSUB, SDLoc(N), VT, N0,
6601 GetNegatedExpression(N1, DAG, LegalOperations));
6603 // fold (fadd (fneg A), B) -> (fsub B, A)
6604 if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) &&
6605 isNegatibleForFree(N0, LegalOperations, TLI, &Options) == 2)
6606 return DAG.getNode(ISD::FSUB, SDLoc(N), VT, N1,
6607 GetNegatedExpression(N0, DAG, LegalOperations));
6609 // If 'unsafe math' is enabled, fold lots of things.
6610 if (Options.UnsafeFPMath) {
6611 // No FP constant should be created after legalization as Instruction
6612 // Selection pass has a hard time dealing with FP constants.
6613 bool AllowNewConst = (Level < AfterLegalizeDAG);
6615 // fold (fadd A, 0) -> A
6616 if (N1CFP && N1CFP->getValueAPF().isZero())
6619 // fold (fadd (fadd x, c1), c2) -> (fadd x, (fadd c1, c2))
6620 if (N1CFP && N0.getOpcode() == ISD::FADD && N0.getNode()->hasOneUse() &&
6621 isa<ConstantFPSDNode>(N0.getOperand(1)))
6622 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0.getOperand(0),
6623 DAG.getNode(ISD::FADD, SDLoc(N), VT,
6624 N0.getOperand(1), N1));
6626 // If allowed, fold (fadd (fneg x), x) -> 0.0
6627 if (AllowNewConst && N0.getOpcode() == ISD::FNEG && N0.getOperand(0) == N1)
6628 return DAG.getConstantFP(0.0, VT);
6630 // If allowed, fold (fadd x, (fneg x)) -> 0.0
6631 if (AllowNewConst && N1.getOpcode() == ISD::FNEG && N1.getOperand(0) == N0)
6632 return DAG.getConstantFP(0.0, VT);
6634 // We can fold chains of FADD's of the same value into multiplications.
6635 // This transform is not safe in general because we are reducing the number
6636 // of rounding steps.
6637 if (TLI.isOperationLegalOrCustom(ISD::FMUL, VT) && !N0CFP && !N1CFP) {
6638 if (N0.getOpcode() == ISD::FMUL) {
6639 ConstantFPSDNode *CFP00 = dyn_cast<ConstantFPSDNode>(N0.getOperand(0));
6640 ConstantFPSDNode *CFP01 = dyn_cast<ConstantFPSDNode>(N0.getOperand(1));
6642 // (fadd (fmul x, c), x) -> (fmul x, c+1)
6643 if (CFP01 && !CFP00 && N0.getOperand(0) == N1) {
6644 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6646 DAG.getConstantFP(1.0, VT));
6647 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N1, NewCFP);
6650 // (fadd (fmul x, c), (fadd x, x)) -> (fmul x, c+2)
6651 if (CFP01 && !CFP00 && N1.getOpcode() == ISD::FADD &&
6652 N1.getOperand(0) == N1.getOperand(1) &&
6653 N0.getOperand(0) == N1.getOperand(0)) {
6654 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6656 DAG.getConstantFP(2.0, VT));
6657 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6658 N0.getOperand(0), NewCFP);
6662 if (N1.getOpcode() == ISD::FMUL) {
6663 ConstantFPSDNode *CFP10 = dyn_cast<ConstantFPSDNode>(N1.getOperand(0));
6664 ConstantFPSDNode *CFP11 = dyn_cast<ConstantFPSDNode>(N1.getOperand(1));
6666 // (fadd x, (fmul x, c)) -> (fmul x, c+1)
6667 if (CFP11 && !CFP10 && N1.getOperand(0) == N0) {
6668 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6670 DAG.getConstantFP(1.0, VT));
6671 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0, NewCFP);
6674 // (fadd (fadd x, x), (fmul x, c)) -> (fmul x, c+2)
6675 if (CFP11 && !CFP10 && N0.getOpcode() == ISD::FADD &&
6676 N0.getOperand(0) == N0.getOperand(1) &&
6677 N1.getOperand(0) == N0.getOperand(0)) {
6678 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6680 DAG.getConstantFP(2.0, VT));
6681 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N1.getOperand(0), NewCFP);
6685 if (N0.getOpcode() == ISD::FADD && AllowNewConst) {
6686 ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N0.getOperand(0));
6687 // (fadd (fadd x, x), x) -> (fmul x, 3.0)
6688 if (!CFP && N0.getOperand(0) == N0.getOperand(1) &&
6689 (N0.getOperand(0) == N1))
6690 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6691 N1, DAG.getConstantFP(3.0, VT));
6694 if (N1.getOpcode() == ISD::FADD && AllowNewConst) {
6695 ConstantFPSDNode *CFP10 = dyn_cast<ConstantFPSDNode>(N1.getOperand(0));
6696 // (fadd x, (fadd x, x)) -> (fmul x, 3.0)
6697 if (!CFP10 && N1.getOperand(0) == N1.getOperand(1) &&
6698 N1.getOperand(0) == N0)
6699 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6700 N0, DAG.getConstantFP(3.0, VT));
6703 // (fadd (fadd x, x), (fadd x, x)) -> (fmul x, 4.0)
6704 if (AllowNewConst &&
6705 N0.getOpcode() == ISD::FADD && N1.getOpcode() == ISD::FADD &&
6706 N0.getOperand(0) == N0.getOperand(1) &&
6707 N1.getOperand(0) == N1.getOperand(1) &&
6708 N0.getOperand(0) == N1.getOperand(0))
6709 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6710 N0.getOperand(0), DAG.getConstantFP(4.0, VT));
6712 } // enable-unsafe-fp-math
6714 // FADD -> FMA combines:
6715 if ((Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath) &&
6716 TLI.isFMAFasterThanFMulAndFAdd(VT) &&
6717 (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT))) {
6719 // fold (fadd (fmul x, y), z) -> (fma x, y, z)
6720 if (N0.getOpcode() == ISD::FMUL &&
6721 (N0->hasOneUse() || TLI.enableAggressiveFMAFusion(VT)))
6722 return DAG.getNode(ISD::FMA, SDLoc(N), VT,
6723 N0.getOperand(0), N0.getOperand(1), N1);
6725 // fold (fadd x, (fmul y, z)) -> (fma y, z, x)
6726 // Note: Commutes FADD operands.
6727 if (N1.getOpcode() == ISD::FMUL &&
6728 (N1->hasOneUse() || TLI.enableAggressiveFMAFusion(VT)))
6729 return DAG.getNode(ISD::FMA, SDLoc(N), VT,
6730 N1.getOperand(0), N1.getOperand(1), N0);
6736 SDValue DAGCombiner::visitFSUB(SDNode *N) {
6737 SDValue N0 = N->getOperand(0);
6738 SDValue N1 = N->getOperand(1);
6739 ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0);
6740 ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1);
6741 EVT VT = N->getValueType(0);
6743 const TargetOptions &Options = DAG.getTarget().Options;
6746 if (VT.isVector()) {
6747 SDValue FoldedVOp = SimplifyVBinOp(N);
6748 if (FoldedVOp.getNode()) return FoldedVOp;
6751 // fold (fsub c1, c2) -> c1-c2
6753 return DAG.getNode(ISD::FSUB, SDLoc(N), VT, N0, N1);
6755 // fold (fsub A, (fneg B)) -> (fadd A, B)
6756 if (isNegatibleForFree(N1, LegalOperations, TLI, &Options))
6757 return DAG.getNode(ISD::FADD, dl, VT, N0,
6758 GetNegatedExpression(N1, DAG, LegalOperations));
6760 // If 'unsafe math' is enabled, fold lots of things.
6761 if (Options.UnsafeFPMath) {
6763 if (N1CFP && N1CFP->getValueAPF().isZero())
6766 // (fsub 0, B) -> -B
6767 if (N0CFP && N0CFP->getValueAPF().isZero()) {
6768 if (isNegatibleForFree(N1, LegalOperations, TLI, &Options))
6769 return GetNegatedExpression(N1, DAG, LegalOperations);
6770 if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
6771 return DAG.getNode(ISD::FNEG, dl, VT, N1);
6774 // (fsub x, x) -> 0.0
6776 return DAG.getConstantFP(0.0f, VT);
6778 // (fsub x, (fadd x, y)) -> (fneg y)
6779 // (fsub x, (fadd y, x)) -> (fneg y)
6780 if (N1.getOpcode() == ISD::FADD) {
6781 SDValue N10 = N1->getOperand(0);
6782 SDValue N11 = N1->getOperand(1);
6784 if (N10 == N0 && isNegatibleForFree(N11, LegalOperations, TLI, &Options))
6785 return GetNegatedExpression(N11, DAG, LegalOperations);
6787 if (N11 == N0 && isNegatibleForFree(N10, LegalOperations, TLI, &Options))
6788 return GetNegatedExpression(N10, DAG, LegalOperations);
6792 // FSUB -> FMA combines:
6793 if ((Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath) &&
6794 TLI.isFMAFasterThanFMulAndFAdd(VT) &&
6795 (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT))) {
6797 // fold (fsub (fmul x, y), z) -> (fma x, y, (fneg z))
6798 if (N0.getOpcode() == ISD::FMUL &&
6799 (N0->hasOneUse() || TLI.enableAggressiveFMAFusion(VT)))
6800 return DAG.getNode(ISD::FMA, dl, VT,
6801 N0.getOperand(0), N0.getOperand(1),
6802 DAG.getNode(ISD::FNEG, dl, VT, N1));
6804 // fold (fsub x, (fmul y, z)) -> (fma (fneg y), z, x)
6805 // Note: Commutes FSUB operands.
6806 if (N1.getOpcode() == ISD::FMUL &&
6807 (N1->hasOneUse() || TLI.enableAggressiveFMAFusion(VT)))
6808 return DAG.getNode(ISD::FMA, dl, VT,
6809 DAG.getNode(ISD::FNEG, dl, VT,
6811 N1.getOperand(1), N0);
6813 // fold (fsub (fneg (fmul, x, y)), z) -> (fma (fneg x), y, (fneg z))
6814 if (N0.getOpcode() == ISD::FNEG &&
6815 N0.getOperand(0).getOpcode() == ISD::FMUL &&
6816 ((N0->hasOneUse() && N0.getOperand(0).hasOneUse()) ||
6817 TLI.enableAggressiveFMAFusion(VT))) {
6818 SDValue N00 = N0.getOperand(0).getOperand(0);
6819 SDValue N01 = N0.getOperand(0).getOperand(1);
6820 return DAG.getNode(ISD::FMA, dl, VT,
6821 DAG.getNode(ISD::FNEG, dl, VT, N00), N01,
6822 DAG.getNode(ISD::FNEG, dl, VT, N1));
6829 SDValue DAGCombiner::visitFMUL(SDNode *N) {
6830 SDValue N0 = N->getOperand(0);
6831 SDValue N1 = N->getOperand(1);
6832 ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0);
6833 ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1);
6834 EVT VT = N->getValueType(0);
6835 const TargetOptions &Options = DAG.getTarget().Options;
6838 if (VT.isVector()) {
6839 // This just handles C1 * C2 for vectors. Other vector folds are below.
6840 SDValue FoldedVOp = SimplifyVBinOp(N);
6841 if (FoldedVOp.getNode())
6843 // Canonicalize vector constant to RHS.
6844 if (N0.getOpcode() == ISD::BUILD_VECTOR &&
6845 N1.getOpcode() != ISD::BUILD_VECTOR)
6846 if (auto *BV0 = dyn_cast<BuildVectorSDNode>(N0))
6847 if (BV0->isConstant())
6848 return DAG.getNode(N->getOpcode(), SDLoc(N), VT, N1, N0);
6851 // fold (fmul c1, c2) -> c1*c2
6853 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0, N1);
6855 // canonicalize constant to RHS
6856 if (N0CFP && !N1CFP)
6857 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N1, N0);
6859 // fold (fmul A, 1.0) -> A
6860 if (N1CFP && N1CFP->isExactlyValue(1.0))
6863 if (Options.UnsafeFPMath) {
6864 // fold (fmul A, 0) -> 0
6865 if (N1CFP && N1CFP->getValueAPF().isZero())
6868 // fold (fmul (fmul x, c1), c2) -> (fmul x, (fmul c1, c2))
6869 if (N0.getOpcode() == ISD::FMUL) {
6870 // Fold scalars or any vector constants (not just splats).
6871 // This fold is done in general by InstCombine, but extra fmul insts
6872 // may have been generated during lowering.
6873 SDValue N01 = N0.getOperand(1);
6874 auto *BV1 = dyn_cast<BuildVectorSDNode>(N1);
6875 auto *BV01 = dyn_cast<BuildVectorSDNode>(N01);
6876 if ((N1CFP && isConstOrConstSplatFP(N01)) ||
6877 (BV1 && BV01 && BV1->isConstant() && BV01->isConstant())) {
6879 SDValue MulConsts = DAG.getNode(ISD::FMUL, SL, VT, N01, N1);
6880 return DAG.getNode(ISD::FMUL, SL, VT, N0.getOperand(0), MulConsts);
6884 // fold (fmul (fadd x, x), c) -> (fmul x, (fmul 2.0, c))
6885 // Undo the fmul 2.0, x -> fadd x, x transformation, since if it occurs
6886 // during an early run of DAGCombiner can prevent folding with fmuls
6887 // inserted during lowering.
6888 if (N0.getOpcode() == ISD::FADD && N0.getOperand(0) == N0.getOperand(1)) {
6890 const SDValue Two = DAG.getConstantFP(2.0, VT);
6891 SDValue MulConsts = DAG.getNode(ISD::FMUL, SL, VT, Two, N1);
6892 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0.getOperand(0), MulConsts);
6896 // fold (fmul X, 2.0) -> (fadd X, X)
6897 if (N1CFP && N1CFP->isExactlyValue(+2.0))
6898 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N0);
6900 // fold (fmul X, -1.0) -> (fneg X)
6901 if (N1CFP && N1CFP->isExactlyValue(-1.0))
6902 if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
6903 return DAG.getNode(ISD::FNEG, SDLoc(N), VT, N0);
6905 // fold (fmul (fneg X), (fneg Y)) -> (fmul X, Y)
6906 if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI, &Options)) {
6907 if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI, &Options)) {
6908 // Both can be negated for free, check to see if at least one is cheaper
6910 if (LHSNeg == 2 || RHSNeg == 2)
6911 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6912 GetNegatedExpression(N0, DAG, LegalOperations),
6913 GetNegatedExpression(N1, DAG, LegalOperations));
6920 SDValue DAGCombiner::visitFMA(SDNode *N) {
6921 SDValue N0 = N->getOperand(0);
6922 SDValue N1 = N->getOperand(1);
6923 SDValue N2 = N->getOperand(2);
6924 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6925 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6926 EVT VT = N->getValueType(0);
6928 const TargetOptions &Options = DAG.getTarget().Options;
6930 // Constant fold FMA.
6931 if (isa<ConstantFPSDNode>(N0) &&
6932 isa<ConstantFPSDNode>(N1) &&
6933 isa<ConstantFPSDNode>(N2)) {
6934 return DAG.getNode(ISD::FMA, dl, VT, N0, N1, N2);
6937 if (Options.UnsafeFPMath) {
6938 if (N0CFP && N0CFP->isZero())
6940 if (N1CFP && N1CFP->isZero())
6943 if (N0CFP && N0CFP->isExactlyValue(1.0))
6944 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N1, N2);
6945 if (N1CFP && N1CFP->isExactlyValue(1.0))
6946 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N2);
6948 // Canonicalize (fma c, x, y) -> (fma x, c, y)
6949 if (N0CFP && !N1CFP)
6950 return DAG.getNode(ISD::FMA, SDLoc(N), VT, N1, N0, N2);
6952 // (fma x, c1, (fmul x, c2)) -> (fmul x, c1+c2)
6953 if (Options.UnsafeFPMath && N1CFP &&
6954 N2.getOpcode() == ISD::FMUL &&
6955 N0 == N2.getOperand(0) &&
6956 N2.getOperand(1).getOpcode() == ISD::ConstantFP) {
6957 return DAG.getNode(ISD::FMUL, dl, VT, N0,
6958 DAG.getNode(ISD::FADD, dl, VT, N1, N2.getOperand(1)));
6962 // (fma (fmul x, c1), c2, y) -> (fma x, c1*c2, y)
6963 if (Options.UnsafeFPMath &&
6964 N0.getOpcode() == ISD::FMUL && N1CFP &&
6965 N0.getOperand(1).getOpcode() == ISD::ConstantFP) {
6966 return DAG.getNode(ISD::FMA, dl, VT,
6968 DAG.getNode(ISD::FMUL, dl, VT, N1, N0.getOperand(1)),
6972 // (fma x, 1, y) -> (fadd x, y)
6973 // (fma x, -1, y) -> (fadd (fneg x), y)
6975 if (N1CFP->isExactlyValue(1.0))
6976 return DAG.getNode(ISD::FADD, dl, VT, N0, N2);
6978 if (N1CFP->isExactlyValue(-1.0) &&
6979 (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))) {
6980 SDValue RHSNeg = DAG.getNode(ISD::FNEG, dl, VT, N0);
6981 AddToWorklist(RHSNeg.getNode());
6982 return DAG.getNode(ISD::FADD, dl, VT, N2, RHSNeg);
6986 // (fma x, c, x) -> (fmul x, (c+1))
6987 if (Options.UnsafeFPMath && N1CFP && N0 == N2)
6988 return DAG.getNode(ISD::FMUL, dl, VT, N0,
6989 DAG.getNode(ISD::FADD, dl, VT,
6990 N1, DAG.getConstantFP(1.0, VT)));
6992 // (fma x, c, (fneg x)) -> (fmul x, (c-1))
6993 if (Options.UnsafeFPMath && N1CFP &&
6994 N2.getOpcode() == ISD::FNEG && N2.getOperand(0) == N0)
6995 return DAG.getNode(ISD::FMUL, dl, VT, N0,
6996 DAG.getNode(ISD::FADD, dl, VT,
6997 N1, DAG.getConstantFP(-1.0, VT)));
7003 SDValue DAGCombiner::visitFDIV(SDNode *N) {
7004 SDValue N0 = N->getOperand(0);
7005 SDValue N1 = N->getOperand(1);
7006 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7007 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
7008 EVT VT = N->getValueType(0);
7010 const TargetOptions &Options = DAG.getTarget().Options;
7013 if (VT.isVector()) {
7014 SDValue FoldedVOp = SimplifyVBinOp(N);
7015 if (FoldedVOp.getNode()) return FoldedVOp;
7018 // fold (fdiv c1, c2) -> c1/c2
7020 return DAG.getNode(ISD::FDIV, SDLoc(N), VT, N0, N1);
7022 if (Options.UnsafeFPMath) {
7023 // fold (fdiv X, c2) -> fmul X, 1/c2 if losing precision is acceptable.
7025 // Compute the reciprocal 1.0 / c2.
7026 APFloat N1APF = N1CFP->getValueAPF();
7027 APFloat Recip(N1APF.getSemantics(), 1); // 1.0
7028 APFloat::opStatus st = Recip.divide(N1APF, APFloat::rmNearestTiesToEven);
7029 // Only do the transform if the reciprocal is a legal fp immediate that
7030 // isn't too nasty (eg NaN, denormal, ...).
7031 if ((st == APFloat::opOK || st == APFloat::opInexact) && // Not too nasty
7032 (!LegalOperations ||
7033 // FIXME: custom lowering of ConstantFP might fail (see e.g. ARM
7034 // backend)... we should handle this gracefully after Legalize.
7035 // TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT) ||
7036 TLI.isOperationLegal(llvm::ISD::ConstantFP, VT) ||
7037 TLI.isFPImmLegal(Recip, VT)))
7038 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0,
7039 DAG.getConstantFP(Recip, VT));
7042 // If this FDIV is part of a reciprocal square root, it may be folded
7043 // into a target-specific square root estimate instruction.
7044 if (N1.getOpcode() == ISD::FSQRT) {
7045 if (SDValue RV = BuildRsqrtEstimate(N1.getOperand(0))) {
7046 return DAG.getNode(ISD::FMUL, DL, VT, N0, RV);
7048 } else if (N1.getOpcode() == ISD::FP_EXTEND &&
7049 N1.getOperand(0).getOpcode() == ISD::FSQRT) {
7050 if (SDValue RV = BuildRsqrtEstimate(N1.getOperand(0).getOperand(0))) {
7051 RV = DAG.getNode(ISD::FP_EXTEND, SDLoc(N1), VT, RV);
7052 AddToWorklist(RV.getNode());
7053 return DAG.getNode(ISD::FMUL, DL, VT, N0, RV);
7055 } else if (N1.getOpcode() == ISD::FP_ROUND &&
7056 N1.getOperand(0).getOpcode() == ISD::FSQRT) {
7057 if (SDValue RV = BuildRsqrtEstimate(N1.getOperand(0).getOperand(0))) {
7058 RV = DAG.getNode(ISD::FP_ROUND, SDLoc(N1), VT, RV, N1.getOperand(1));
7059 AddToWorklist(RV.getNode());
7060 return DAG.getNode(ISD::FMUL, DL, VT, N0, RV);
7062 } else if (N1.getOpcode() == ISD::FMUL) {
7063 // Look through an FMUL. Even though this won't remove the FDIV directly,
7064 // it's still worthwhile to get rid of the FSQRT if possible.
7067 if (N1.getOperand(0).getOpcode() == ISD::FSQRT) {
7068 SqrtOp = N1.getOperand(0);
7069 OtherOp = N1.getOperand(1);
7070 } else if (N1.getOperand(1).getOpcode() == ISD::FSQRT) {
7071 SqrtOp = N1.getOperand(1);
7072 OtherOp = N1.getOperand(0);
7074 if (SqrtOp.getNode()) {
7075 // We found a FSQRT, so try to make this fold:
7076 // x / (y * sqrt(z)) -> x * (rsqrt(z) / y)
7077 if (SDValue RV = BuildRsqrtEstimate(SqrtOp.getOperand(0))) {
7078 RV = DAG.getNode(ISD::FDIV, SDLoc(N1), VT, RV, OtherOp);
7079 AddToWorklist(RV.getNode());
7080 return DAG.getNode(ISD::FMUL, DL, VT, N0, RV);
7085 // Fold into a reciprocal estimate and multiply instead of a real divide.
7086 if (SDValue RV = BuildReciprocalEstimate(N1)) {
7087 AddToWorklist(RV.getNode());
7088 return DAG.getNode(ISD::FMUL, DL, VT, N0, RV);
7092 // (fdiv (fneg X), (fneg Y)) -> (fdiv X, Y)
7093 if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI, &Options)) {
7094 if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI, &Options)) {
7095 // Both can be negated for free, check to see if at least one is cheaper
7097 if (LHSNeg == 2 || RHSNeg == 2)
7098 return DAG.getNode(ISD::FDIV, SDLoc(N), VT,
7099 GetNegatedExpression(N0, DAG, LegalOperations),
7100 GetNegatedExpression(N1, DAG, LegalOperations));
7107 SDValue DAGCombiner::visitFREM(SDNode *N) {
7108 SDValue N0 = N->getOperand(0);
7109 SDValue N1 = N->getOperand(1);
7110 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7111 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
7112 EVT VT = N->getValueType(0);
7114 // fold (frem c1, c2) -> fmod(c1,c2)
7116 return DAG.getNode(ISD::FREM, SDLoc(N), VT, N0, N1);
7121 SDValue DAGCombiner::visitFSQRT(SDNode *N) {
7122 if (DAG.getTarget().Options.UnsafeFPMath) {
7123 // Compute this as X * (1/sqrt(X)) = X * (X ** -0.5)
7124 if (SDValue RV = BuildRsqrtEstimate(N->getOperand(0))) {
7125 EVT VT = RV.getValueType();
7126 RV = DAG.getNode(ISD::FMUL, SDLoc(N), VT, N->getOperand(0), RV);
7127 AddToWorklist(RV.getNode());
7129 // Unfortunately, RV is now NaN if the input was exactly 0.
7130 // Select out this case and force the answer to 0.
7131 SDValue Zero = DAG.getConstantFP(0.0, VT);
7133 DAG.getSetCC(SDLoc(N), TLI.getSetCCResultType(*DAG.getContext(), VT),
7134 N->getOperand(0), Zero, ISD::SETEQ);
7135 AddToWorklist(ZeroCmp.getNode());
7136 AddToWorklist(RV.getNode());
7138 RV = DAG.getNode(VT.isVector() ? ISD::VSELECT : ISD::SELECT,
7139 SDLoc(N), VT, ZeroCmp, Zero, RV);
7146 SDValue DAGCombiner::visitFCOPYSIGN(SDNode *N) {
7147 SDValue N0 = N->getOperand(0);
7148 SDValue N1 = N->getOperand(1);
7149 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7150 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
7151 EVT VT = N->getValueType(0);
7153 if (N0CFP && N1CFP) // Constant fold
7154 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, N0, N1);
7157 const APFloat& V = N1CFP->getValueAPF();
7158 // copysign(x, c1) -> fabs(x) iff ispos(c1)
7159 // copysign(x, c1) -> fneg(fabs(x)) iff isneg(c1)
7160 if (!V.isNegative()) {
7161 if (!LegalOperations || TLI.isOperationLegal(ISD::FABS, VT))
7162 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
7164 if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
7165 return DAG.getNode(ISD::FNEG, SDLoc(N), VT,
7166 DAG.getNode(ISD::FABS, SDLoc(N0), VT, N0));
7170 // copysign(fabs(x), y) -> copysign(x, y)
7171 // copysign(fneg(x), y) -> copysign(x, y)
7172 // copysign(copysign(x,z), y) -> copysign(x, y)
7173 if (N0.getOpcode() == ISD::FABS || N0.getOpcode() == ISD::FNEG ||
7174 N0.getOpcode() == ISD::FCOPYSIGN)
7175 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
7176 N0.getOperand(0), N1);
7178 // copysign(x, abs(y)) -> abs(x)
7179 if (N1.getOpcode() == ISD::FABS)
7180 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
7182 // copysign(x, copysign(y,z)) -> copysign(x, z)
7183 if (N1.getOpcode() == ISD::FCOPYSIGN)
7184 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
7185 N0, N1.getOperand(1));
7187 // copysign(x, fp_extend(y)) -> copysign(x, y)
7188 // copysign(x, fp_round(y)) -> copysign(x, y)
7189 if (N1.getOpcode() == ISD::FP_EXTEND || N1.getOpcode() == ISD::FP_ROUND)
7190 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
7191 N0, N1.getOperand(0));
7196 SDValue DAGCombiner::visitSINT_TO_FP(SDNode *N) {
7197 SDValue N0 = N->getOperand(0);
7198 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
7199 EVT VT = N->getValueType(0);
7200 EVT OpVT = N0.getValueType();
7202 // fold (sint_to_fp c1) -> c1fp
7204 // ...but only if the target supports immediate floating-point values
7205 (!LegalOperations ||
7206 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT)))
7207 return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0);
7209 // If the input is a legal type, and SINT_TO_FP is not legal on this target,
7210 // but UINT_TO_FP is legal on this target, try to convert.
7211 if (!TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT) &&
7212 TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT)) {
7213 // If the sign bit is known to be zero, we can change this to UINT_TO_FP.
7214 if (DAG.SignBitIsZero(N0))
7215 return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0);
7218 // The next optimizations are desirable only if SELECT_CC can be lowered.
7219 if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT) || !LegalOperations) {
7220 // fold (sint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc)
7221 if (N0.getOpcode() == ISD::SETCC && N0.getValueType() == MVT::i1 &&
7223 (!LegalOperations ||
7224 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
7226 { N0.getOperand(0), N0.getOperand(1),
7227 DAG.getConstantFP(-1.0, VT) , DAG.getConstantFP(0.0, VT),
7229 return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT, Ops);
7232 // fold (sint_to_fp (zext (setcc x, y, cc))) ->
7233 // (select_cc x, y, 1.0, 0.0,, cc)
7234 if (N0.getOpcode() == ISD::ZERO_EXTEND &&
7235 N0.getOperand(0).getOpcode() == ISD::SETCC &&!VT.isVector() &&
7236 (!LegalOperations ||
7237 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
7239 { N0.getOperand(0).getOperand(0), N0.getOperand(0).getOperand(1),
7240 DAG.getConstantFP(1.0, VT) , DAG.getConstantFP(0.0, VT),
7241 N0.getOperand(0).getOperand(2) };
7242 return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT, Ops);
7249 SDValue DAGCombiner::visitUINT_TO_FP(SDNode *N) {
7250 SDValue N0 = N->getOperand(0);
7251 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
7252 EVT VT = N->getValueType(0);
7253 EVT OpVT = N0.getValueType();
7255 // fold (uint_to_fp c1) -> c1fp
7257 // ...but only if the target supports immediate floating-point values
7258 (!LegalOperations ||
7259 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT)))
7260 return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0);
7262 // If the input is a legal type, and UINT_TO_FP is not legal on this target,
7263 // but SINT_TO_FP is legal on this target, try to convert.
7264 if (!TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT) &&
7265 TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT)) {
7266 // If the sign bit is known to be zero, we can change this to SINT_TO_FP.
7267 if (DAG.SignBitIsZero(N0))
7268 return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0);
7271 // The next optimizations are desirable only if SELECT_CC can be lowered.
7272 if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT) || !LegalOperations) {
7273 // fold (uint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc)
7275 if (N0.getOpcode() == ISD::SETCC && !VT.isVector() &&
7276 (!LegalOperations ||
7277 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
7279 { N0.getOperand(0), N0.getOperand(1),
7280 DAG.getConstantFP(1.0, VT), DAG.getConstantFP(0.0, VT),
7282 return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT, Ops);
7289 SDValue DAGCombiner::visitFP_TO_SINT(SDNode *N) {
7290 SDValue N0 = N->getOperand(0);
7291 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7292 EVT VT = N->getValueType(0);
7294 // fold (fp_to_sint c1fp) -> c1
7296 return DAG.getNode(ISD::FP_TO_SINT, SDLoc(N), VT, N0);
7301 SDValue DAGCombiner::visitFP_TO_UINT(SDNode *N) {
7302 SDValue N0 = N->getOperand(0);
7303 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7304 EVT VT = N->getValueType(0);
7306 // fold (fp_to_uint c1fp) -> c1
7308 return DAG.getNode(ISD::FP_TO_UINT, SDLoc(N), VT, N0);
7313 SDValue DAGCombiner::visitFP_ROUND(SDNode *N) {
7314 SDValue N0 = N->getOperand(0);
7315 SDValue N1 = N->getOperand(1);
7316 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7317 EVT VT = N->getValueType(0);
7319 // fold (fp_round c1fp) -> c1fp
7321 return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT, N0, N1);
7323 // fold (fp_round (fp_extend x)) -> x
7324 if (N0.getOpcode() == ISD::FP_EXTEND && VT == N0.getOperand(0).getValueType())
7325 return N0.getOperand(0);
7327 // fold (fp_round (fp_round x)) -> (fp_round x)
7328 if (N0.getOpcode() == ISD::FP_ROUND) {
7329 // This is a value preserving truncation if both round's are.
7330 bool IsTrunc = N->getConstantOperandVal(1) == 1 &&
7331 N0.getNode()->getConstantOperandVal(1) == 1;
7332 return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT, N0.getOperand(0),
7333 DAG.getIntPtrConstant(IsTrunc));
7336 // fold (fp_round (copysign X, Y)) -> (copysign (fp_round X), Y)
7337 if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse()) {
7338 SDValue Tmp = DAG.getNode(ISD::FP_ROUND, SDLoc(N0), VT,
7339 N0.getOperand(0), N1);
7340 AddToWorklist(Tmp.getNode());
7341 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
7342 Tmp, N0.getOperand(1));
7348 SDValue DAGCombiner::visitFP_ROUND_INREG(SDNode *N) {
7349 SDValue N0 = N->getOperand(0);
7350 EVT VT = N->getValueType(0);
7351 EVT EVT = cast<VTSDNode>(N->getOperand(1))->getVT();
7352 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7354 // fold (fp_round_inreg c1fp) -> c1fp
7355 if (N0CFP && isTypeLegal(EVT)) {
7356 SDValue Round = DAG.getConstantFP(*N0CFP->getConstantFPValue(), EVT);
7357 return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, Round);
7363 SDValue DAGCombiner::visitFP_EXTEND(SDNode *N) {
7364 SDValue N0 = N->getOperand(0);
7365 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7366 EVT VT = N->getValueType(0);
7368 // If this is fp_round(fpextend), don't fold it, allow ourselves to be folded.
7369 if (N->hasOneUse() &&
7370 N->use_begin()->getOpcode() == ISD::FP_ROUND)
7373 // fold (fp_extend c1fp) -> c1fp
7375 return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, N0);
7377 // Turn fp_extend(fp_round(X, 1)) -> x since the fp_round doesn't affect the
7379 if (N0.getOpcode() == ISD::FP_ROUND
7380 && N0.getNode()->getConstantOperandVal(1) == 1) {
7381 SDValue In = N0.getOperand(0);
7382 if (In.getValueType() == VT) return In;
7383 if (VT.bitsLT(In.getValueType()))
7384 return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT,
7385 In, N0.getOperand(1));
7386 return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, In);
7389 // fold (fpext (load x)) -> (fpext (fptrunc (extload x)))
7390 if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
7391 TLI.isLoadExtLegal(ISD::EXTLOAD, N0.getValueType())) {
7392 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
7393 SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT,
7395 LN0->getBasePtr(), N0.getValueType(),
7396 LN0->getMemOperand());
7397 CombineTo(N, ExtLoad);
7398 CombineTo(N0.getNode(),
7399 DAG.getNode(ISD::FP_ROUND, SDLoc(N0),
7400 N0.getValueType(), ExtLoad, DAG.getIntPtrConstant(1)),
7401 ExtLoad.getValue(1));
7402 return SDValue(N, 0); // Return N so it doesn't get rechecked!
7408 SDValue DAGCombiner::visitFCEIL(SDNode *N) {
7409 SDValue N0 = N->getOperand(0);
7410 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7411 EVT VT = N->getValueType(0);
7413 // fold (fceil c1) -> fceil(c1)
7415 return DAG.getNode(ISD::FCEIL, SDLoc(N), VT, N0);
7420 SDValue DAGCombiner::visitFTRUNC(SDNode *N) {
7421 SDValue N0 = N->getOperand(0);
7422 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7423 EVT VT = N->getValueType(0);
7425 // fold (ftrunc c1) -> ftrunc(c1)
7427 return DAG.getNode(ISD::FTRUNC, SDLoc(N), VT, N0);
7432 SDValue DAGCombiner::visitFFLOOR(SDNode *N) {
7433 SDValue N0 = N->getOperand(0);
7434 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7435 EVT VT = N->getValueType(0);
7437 // fold (ffloor c1) -> ffloor(c1)
7439 return DAG.getNode(ISD::FFLOOR, SDLoc(N), VT, N0);
7444 // FIXME: FNEG and FABS have a lot in common; refactor.
7445 SDValue DAGCombiner::visitFNEG(SDNode *N) {
7446 SDValue N0 = N->getOperand(0);
7447 EVT VT = N->getValueType(0);
7449 if (VT.isVector()) {
7450 SDValue FoldedVOp = SimplifyVUnaryOp(N);
7451 if (FoldedVOp.getNode()) return FoldedVOp;
7454 // Constant fold FNEG.
7455 if (isa<ConstantFPSDNode>(N0))
7456 return DAG.getNode(ISD::FNEG, SDLoc(N), VT, N->getOperand(0));
7458 if (isNegatibleForFree(N0, LegalOperations, DAG.getTargetLoweringInfo(),
7459 &DAG.getTarget().Options))
7460 return GetNegatedExpression(N0, DAG, LegalOperations);
7462 // Transform fneg(bitconvert(x)) -> bitconvert(x ^ sign) to avoid loading
7463 // constant pool values.
7464 if (!TLI.isFNegFree(VT) &&
7465 N0.getOpcode() == ISD::BITCAST &&
7466 N0.getNode()->hasOneUse()) {
7467 SDValue Int = N0.getOperand(0);
7468 EVT IntVT = Int.getValueType();
7469 if (IntVT.isInteger() && !IntVT.isVector()) {
7471 if (N0.getValueType().isVector()) {
7472 // For a vector, get a mask such as 0x80... per scalar element
7474 SignMask = APInt::getSignBit(N0.getValueType().getScalarSizeInBits());
7475 SignMask = APInt::getSplat(IntVT.getSizeInBits(), SignMask);
7477 // For a scalar, just generate 0x80...
7478 SignMask = APInt::getSignBit(IntVT.getSizeInBits());
7480 Int = DAG.getNode(ISD::XOR, SDLoc(N0), IntVT, Int,
7481 DAG.getConstant(SignMask, IntVT));
7482 AddToWorklist(Int.getNode());
7483 return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Int);
7487 // (fneg (fmul c, x)) -> (fmul -c, x)
7488 if (N0.getOpcode() == ISD::FMUL) {
7489 ConstantFPSDNode *CFP1 = dyn_cast<ConstantFPSDNode>(N0.getOperand(1));
7491 APFloat CVal = CFP1->getValueAPF();
7493 if (Level >= AfterLegalizeDAG &&
7494 (TLI.isFPImmLegal(CVal, N->getValueType(0)) ||
7495 TLI.isOperationLegal(ISD::ConstantFP, N->getValueType(0))))
7497 ISD::FMUL, SDLoc(N), VT, N0.getOperand(0),
7498 DAG.getNode(ISD::FNEG, SDLoc(N), VT, N0.getOperand(1)));
7505 SDValue DAGCombiner::visitFMINNUM(SDNode *N) {
7506 SDValue N0 = N->getOperand(0);
7507 SDValue N1 = N->getOperand(1);
7508 const ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7509 const ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
7511 if (N0CFP && N1CFP) {
7512 const APFloat &C0 = N0CFP->getValueAPF();
7513 const APFloat &C1 = N1CFP->getValueAPF();
7514 return DAG.getConstantFP(minnum(C0, C1), N->getValueType(0));
7518 EVT VT = N->getValueType(0);
7519 // Canonicalize to constant on RHS.
7520 return DAG.getNode(ISD::FMINNUM, SDLoc(N), VT, N1, N0);
7526 SDValue DAGCombiner::visitFMAXNUM(SDNode *N) {
7527 SDValue N0 = N->getOperand(0);
7528 SDValue N1 = N->getOperand(1);
7529 const ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7530 const ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
7532 if (N0CFP && N1CFP) {
7533 const APFloat &C0 = N0CFP->getValueAPF();
7534 const APFloat &C1 = N1CFP->getValueAPF();
7535 return DAG.getConstantFP(maxnum(C0, C1), N->getValueType(0));
7539 EVT VT = N->getValueType(0);
7540 // Canonicalize to constant on RHS.
7541 return DAG.getNode(ISD::FMAXNUM, SDLoc(N), VT, N1, N0);
7547 SDValue DAGCombiner::visitFABS(SDNode *N) {
7548 SDValue N0 = N->getOperand(0);
7549 EVT VT = N->getValueType(0);
7551 if (VT.isVector()) {
7552 SDValue FoldedVOp = SimplifyVUnaryOp(N);
7553 if (FoldedVOp.getNode()) return FoldedVOp;
7556 // fold (fabs c1) -> fabs(c1)
7557 if (isa<ConstantFPSDNode>(N0))
7558 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
7560 // fold (fabs (fabs x)) -> (fabs x)
7561 if (N0.getOpcode() == ISD::FABS)
7562 return N->getOperand(0);
7564 // fold (fabs (fneg x)) -> (fabs x)
7565 // fold (fabs (fcopysign x, y)) -> (fabs x)
7566 if (N0.getOpcode() == ISD::FNEG || N0.getOpcode() == ISD::FCOPYSIGN)
7567 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0.getOperand(0));
7569 // Transform fabs(bitconvert(x)) -> bitconvert(x & ~sign) to avoid loading
7570 // constant pool values.
7571 if (!TLI.isFAbsFree(VT) &&
7572 N0.getOpcode() == ISD::BITCAST &&
7573 N0.getNode()->hasOneUse()) {
7574 SDValue Int = N0.getOperand(0);
7575 EVT IntVT = Int.getValueType();
7576 if (IntVT.isInteger() && !IntVT.isVector()) {
7578 if (N0.getValueType().isVector()) {
7579 // For a vector, get a mask such as 0x7f... per scalar element
7581 SignMask = ~APInt::getSignBit(N0.getValueType().getScalarSizeInBits());
7582 SignMask = APInt::getSplat(IntVT.getSizeInBits(), SignMask);
7584 // For a scalar, just generate 0x7f...
7585 SignMask = ~APInt::getSignBit(IntVT.getSizeInBits());
7587 Int = DAG.getNode(ISD::AND, SDLoc(N0), IntVT, Int,
7588 DAG.getConstant(SignMask, IntVT));
7589 AddToWorklist(Int.getNode());
7590 return DAG.getNode(ISD::BITCAST, SDLoc(N), N->getValueType(0), Int);
7597 SDValue DAGCombiner::visitBRCOND(SDNode *N) {
7598 SDValue Chain = N->getOperand(0);
7599 SDValue N1 = N->getOperand(1);
7600 SDValue N2 = N->getOperand(2);
7602 // If N is a constant we could fold this into a fallthrough or unconditional
7603 // branch. However that doesn't happen very often in normal code, because
7604 // Instcombine/SimplifyCFG should have handled the available opportunities.
7605 // If we did this folding here, it would be necessary to update the
7606 // MachineBasicBlock CFG, which is awkward.
7608 // fold a brcond with a setcc condition into a BR_CC node if BR_CC is legal
7610 if (N1.getOpcode() == ISD::SETCC &&
7611 TLI.isOperationLegalOrCustom(ISD::BR_CC,
7612 N1.getOperand(0).getValueType())) {
7613 return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other,
7614 Chain, N1.getOperand(2),
7615 N1.getOperand(0), N1.getOperand(1), N2);
7618 if ((N1.hasOneUse() && N1.getOpcode() == ISD::SRL) ||
7619 ((N1.getOpcode() == ISD::TRUNCATE && N1.hasOneUse()) &&
7620 (N1.getOperand(0).hasOneUse() &&
7621 N1.getOperand(0).getOpcode() == ISD::SRL))) {
7622 SDNode *Trunc = nullptr;
7623 if (N1.getOpcode() == ISD::TRUNCATE) {
7624 // Look pass the truncate.
7625 Trunc = N1.getNode();
7626 N1 = N1.getOperand(0);
7629 // Match this pattern so that we can generate simpler code:
7632 // %b = and i32 %a, 2
7633 // %c = srl i32 %b, 1
7634 // brcond i32 %c ...
7639 // %b = and i32 %a, 2
7640 // %c = setcc eq %b, 0
7643 // This applies only when the AND constant value has one bit set and the
7644 // SRL constant is equal to the log2 of the AND constant. The back-end is
7645 // smart enough to convert the result into a TEST/JMP sequence.
7646 SDValue Op0 = N1.getOperand(0);
7647 SDValue Op1 = N1.getOperand(1);
7649 if (Op0.getOpcode() == ISD::AND &&
7650 Op1.getOpcode() == ISD::Constant) {
7651 SDValue AndOp1 = Op0.getOperand(1);
7653 if (AndOp1.getOpcode() == ISD::Constant) {
7654 const APInt &AndConst = cast<ConstantSDNode>(AndOp1)->getAPIntValue();
7656 if (AndConst.isPowerOf2() &&
7657 cast<ConstantSDNode>(Op1)->getAPIntValue()==AndConst.logBase2()) {
7659 DAG.getSetCC(SDLoc(N),
7660 getSetCCResultType(Op0.getValueType()),
7661 Op0, DAG.getConstant(0, Op0.getValueType()),
7664 SDValue NewBRCond = DAG.getNode(ISD::BRCOND, SDLoc(N),
7665 MVT::Other, Chain, SetCC, N2);
7666 // Don't add the new BRCond into the worklist or else SimplifySelectCC
7667 // will convert it back to (X & C1) >> C2.
7668 CombineTo(N, NewBRCond, false);
7669 // Truncate is dead.
7671 deleteAndRecombine(Trunc);
7672 // Replace the uses of SRL with SETCC
7673 WorklistRemover DeadNodes(*this);
7674 DAG.ReplaceAllUsesOfValueWith(N1, SetCC);
7675 deleteAndRecombine(N1.getNode());
7676 return SDValue(N, 0); // Return N so it doesn't get rechecked!
7682 // Restore N1 if the above transformation doesn't match.
7683 N1 = N->getOperand(1);
7686 // Transform br(xor(x, y)) -> br(x != y)
7687 // Transform br(xor(xor(x,y), 1)) -> br (x == y)
7688 if (N1.hasOneUse() && N1.getOpcode() == ISD::XOR) {
7689 SDNode *TheXor = N1.getNode();
7690 SDValue Op0 = TheXor->getOperand(0);
7691 SDValue Op1 = TheXor->getOperand(1);
7692 if (Op0.getOpcode() == Op1.getOpcode()) {
7693 // Avoid missing important xor optimizations.
7694 SDValue Tmp = visitXOR(TheXor);
7695 if (Tmp.getNode()) {
7696 if (Tmp.getNode() != TheXor) {
7697 DEBUG(dbgs() << "\nReplacing.8 ";
7699 dbgs() << "\nWith: ";
7700 Tmp.getNode()->dump(&DAG);
7702 WorklistRemover DeadNodes(*this);
7703 DAG.ReplaceAllUsesOfValueWith(N1, Tmp);
7704 deleteAndRecombine(TheXor);
7705 return DAG.getNode(ISD::BRCOND, SDLoc(N),
7706 MVT::Other, Chain, Tmp, N2);
7709 // visitXOR has changed XOR's operands or replaced the XOR completely,
7711 return SDValue(N, 0);
7715 if (Op0.getOpcode() != ISD::SETCC && Op1.getOpcode() != ISD::SETCC) {
7717 if (ConstantSDNode *RHSCI = dyn_cast<ConstantSDNode>(Op0))
7718 if (RHSCI->getAPIntValue() == 1 && Op0.hasOneUse() &&
7719 Op0.getOpcode() == ISD::XOR) {
7720 TheXor = Op0.getNode();
7724 EVT SetCCVT = N1.getValueType();
7726 SetCCVT = getSetCCResultType(SetCCVT);
7727 SDValue SetCC = DAG.getSetCC(SDLoc(TheXor),
7730 Equal ? ISD::SETEQ : ISD::SETNE);
7731 // Replace the uses of XOR with SETCC
7732 WorklistRemover DeadNodes(*this);
7733 DAG.ReplaceAllUsesOfValueWith(N1, SetCC);
7734 deleteAndRecombine(N1.getNode());
7735 return DAG.getNode(ISD::BRCOND, SDLoc(N),
7736 MVT::Other, Chain, SetCC, N2);
7743 // Operand List for BR_CC: Chain, CondCC, CondLHS, CondRHS, DestBB.
7745 SDValue DAGCombiner::visitBR_CC(SDNode *N) {
7746 CondCodeSDNode *CC = cast<CondCodeSDNode>(N->getOperand(1));
7747 SDValue CondLHS = N->getOperand(2), CondRHS = N->getOperand(3);
7749 // If N is a constant we could fold this into a fallthrough or unconditional
7750 // branch. However that doesn't happen very often in normal code, because
7751 // Instcombine/SimplifyCFG should have handled the available opportunities.
7752 // If we did this folding here, it would be necessary to update the
7753 // MachineBasicBlock CFG, which is awkward.
7755 // Use SimplifySetCC to simplify SETCC's.
7756 SDValue Simp = SimplifySetCC(getSetCCResultType(CondLHS.getValueType()),
7757 CondLHS, CondRHS, CC->get(), SDLoc(N),
7759 if (Simp.getNode()) AddToWorklist(Simp.getNode());
7761 // fold to a simpler setcc
7762 if (Simp.getNode() && Simp.getOpcode() == ISD::SETCC)
7763 return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other,
7764 N->getOperand(0), Simp.getOperand(2),
7765 Simp.getOperand(0), Simp.getOperand(1),
7771 /// Return true if 'Use' is a load or a store that uses N as its base pointer
7772 /// and that N may be folded in the load / store addressing mode.
7773 static bool canFoldInAddressingMode(SDNode *N, SDNode *Use,
7775 const TargetLowering &TLI) {
7777 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Use)) {
7778 if (LD->isIndexed() || LD->getBasePtr().getNode() != N)
7780 VT = Use->getValueType(0);
7781 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(Use)) {
7782 if (ST->isIndexed() || ST->getBasePtr().getNode() != N)
7784 VT = ST->getValue().getValueType();
7788 TargetLowering::AddrMode AM;
7789 if (N->getOpcode() == ISD::ADD) {
7790 ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1));
7793 AM.BaseOffs = Offset->getSExtValue();
7797 } else if (N->getOpcode() == ISD::SUB) {
7798 ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1));
7801 AM.BaseOffs = -Offset->getSExtValue();
7808 return TLI.isLegalAddressingMode(AM, VT.getTypeForEVT(*DAG.getContext()));
7811 /// Try turning a load/store into a pre-indexed load/store when the base
7812 /// pointer is an add or subtract and it has other uses besides the load/store.
7813 /// After the transformation, the new indexed load/store has effectively folded
7814 /// the add/subtract in and all of its other uses are redirected to the
7816 bool DAGCombiner::CombineToPreIndexedLoadStore(SDNode *N) {
7817 if (Level < AfterLegalizeDAG)
7823 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
7824 if (LD->isIndexed())
7826 VT = LD->getMemoryVT();
7827 if (!TLI.isIndexedLoadLegal(ISD::PRE_INC, VT) &&
7828 !TLI.isIndexedLoadLegal(ISD::PRE_DEC, VT))
7830 Ptr = LD->getBasePtr();
7831 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
7832 if (ST->isIndexed())
7834 VT = ST->getMemoryVT();
7835 if (!TLI.isIndexedStoreLegal(ISD::PRE_INC, VT) &&
7836 !TLI.isIndexedStoreLegal(ISD::PRE_DEC, VT))
7838 Ptr = ST->getBasePtr();
7844 // If the pointer is not an add/sub, or if it doesn't have multiple uses, bail
7845 // out. There is no reason to make this a preinc/predec.
7846 if ((Ptr.getOpcode() != ISD::ADD && Ptr.getOpcode() != ISD::SUB) ||
7847 Ptr.getNode()->hasOneUse())
7850 // Ask the target to do addressing mode selection.
7853 ISD::MemIndexedMode AM = ISD::UNINDEXED;
7854 if (!TLI.getPreIndexedAddressParts(N, BasePtr, Offset, AM, DAG))
7857 // Backends without true r+i pre-indexed forms may need to pass a
7858 // constant base with a variable offset so that constant coercion
7859 // will work with the patterns in canonical form.
7860 bool Swapped = false;
7861 if (isa<ConstantSDNode>(BasePtr)) {
7862 std::swap(BasePtr, Offset);
7866 // Don't create a indexed load / store with zero offset.
7867 if (isa<ConstantSDNode>(Offset) &&
7868 cast<ConstantSDNode>(Offset)->isNullValue())
7871 // Try turning it into a pre-indexed load / store except when:
7872 // 1) The new base ptr is a frame index.
7873 // 2) If N is a store and the new base ptr is either the same as or is a
7874 // predecessor of the value being stored.
7875 // 3) Another use of old base ptr is a predecessor of N. If ptr is folded
7876 // that would create a cycle.
7877 // 4) All uses are load / store ops that use it as old base ptr.
7879 // Check #1. Preinc'ing a frame index would require copying the stack pointer
7880 // (plus the implicit offset) to a register to preinc anyway.
7881 if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr))
7886 SDValue Val = cast<StoreSDNode>(N)->getValue();
7887 if (Val == BasePtr || BasePtr.getNode()->isPredecessorOf(Val.getNode()))
7891 // If the offset is a constant, there may be other adds of constants that
7892 // can be folded with this one. We should do this to avoid having to keep
7893 // a copy of the original base pointer.
7894 SmallVector<SDNode *, 16> OtherUses;
7895 if (isa<ConstantSDNode>(Offset))
7896 for (SDNode *Use : BasePtr.getNode()->uses()) {
7897 if (Use == Ptr.getNode())
7900 if (Use->isPredecessorOf(N))
7903 if (Use->getOpcode() != ISD::ADD && Use->getOpcode() != ISD::SUB) {
7908 SDValue Op0 = Use->getOperand(0), Op1 = Use->getOperand(1);
7909 if (Op1.getNode() == BasePtr.getNode())
7910 std::swap(Op0, Op1);
7911 assert(Op0.getNode() == BasePtr.getNode() &&
7912 "Use of ADD/SUB but not an operand");
7914 if (!isa<ConstantSDNode>(Op1)) {
7919 // FIXME: In some cases, we can be smarter about this.
7920 if (Op1.getValueType() != Offset.getValueType()) {
7925 OtherUses.push_back(Use);
7929 std::swap(BasePtr, Offset);
7931 // Now check for #3 and #4.
7932 bool RealUse = false;
7934 // Caches for hasPredecessorHelper
7935 SmallPtrSet<const SDNode *, 32> Visited;
7936 SmallVector<const SDNode *, 16> Worklist;
7938 for (SDNode *Use : Ptr.getNode()->uses()) {
7941 if (N->hasPredecessorHelper(Use, Visited, Worklist))
7944 // If Ptr may be folded in addressing mode of other use, then it's
7945 // not profitable to do this transformation.
7946 if (!canFoldInAddressingMode(Ptr.getNode(), Use, DAG, TLI))
7955 Result = DAG.getIndexedLoad(SDValue(N,0), SDLoc(N),
7956 BasePtr, Offset, AM);
7958 Result = DAG.getIndexedStore(SDValue(N,0), SDLoc(N),
7959 BasePtr, Offset, AM);
7962 DEBUG(dbgs() << "\nReplacing.4 ";
7964 dbgs() << "\nWith: ";
7965 Result.getNode()->dump(&DAG);
7967 WorklistRemover DeadNodes(*this);
7969 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0));
7970 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2));
7972 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1));
7975 // Finally, since the node is now dead, remove it from the graph.
7976 deleteAndRecombine(N);
7979 std::swap(BasePtr, Offset);
7981 // Replace other uses of BasePtr that can be updated to use Ptr
7982 for (unsigned i = 0, e = OtherUses.size(); i != e; ++i) {
7983 unsigned OffsetIdx = 1;
7984 if (OtherUses[i]->getOperand(OffsetIdx).getNode() == BasePtr.getNode())
7986 assert(OtherUses[i]->getOperand(!OffsetIdx).getNode() ==
7987 BasePtr.getNode() && "Expected BasePtr operand");
7989 // We need to replace ptr0 in the following expression:
7990 // x0 * offset0 + y0 * ptr0 = t0
7992 // x1 * offset1 + y1 * ptr0 = t1 (the indexed load/store)
7994 // where x0, x1, y0 and y1 in {-1, 1} are given by the types of the
7995 // indexed load/store and the expresion that needs to be re-written.
7997 // Therefore, we have:
7998 // t0 = (x0 * offset0 - x1 * y0 * y1 *offset1) + (y0 * y1) * t1
8000 ConstantSDNode *CN =
8001 cast<ConstantSDNode>(OtherUses[i]->getOperand(OffsetIdx));
8003 APInt Offset0 = CN->getAPIntValue();
8004 APInt Offset1 = cast<ConstantSDNode>(Offset)->getAPIntValue();
8006 X0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 1) ? -1 : 1;
8007 Y0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 0) ? -1 : 1;
8008 X1 = (AM == ISD::PRE_DEC && !Swapped) ? -1 : 1;
8009 Y1 = (AM == ISD::PRE_DEC && Swapped) ? -1 : 1;
8011 unsigned Opcode = (Y0 * Y1 < 0) ? ISD::SUB : ISD::ADD;
8013 APInt CNV = Offset0;
8014 if (X0 < 0) CNV = -CNV;
8015 if (X1 * Y0 * Y1 < 0) CNV = CNV + Offset1;
8016 else CNV = CNV - Offset1;
8018 // We can now generate the new expression.
8019 SDValue NewOp1 = DAG.getConstant(CNV, CN->getValueType(0));
8020 SDValue NewOp2 = Result.getValue(isLoad ? 1 : 0);
8022 SDValue NewUse = DAG.getNode(Opcode,
8023 SDLoc(OtherUses[i]),
8024 OtherUses[i]->getValueType(0), NewOp1, NewOp2);
8025 DAG.ReplaceAllUsesOfValueWith(SDValue(OtherUses[i], 0), NewUse);
8026 deleteAndRecombine(OtherUses[i]);
8029 // Replace the uses of Ptr with uses of the updated base value.
8030 DAG.ReplaceAllUsesOfValueWith(Ptr, Result.getValue(isLoad ? 1 : 0));
8031 deleteAndRecombine(Ptr.getNode());
8036 /// Try to combine a load/store with a add/sub of the base pointer node into a
8037 /// post-indexed load/store. The transformation folded the add/subtract into the
8038 /// new indexed load/store effectively and all of its uses are redirected to the
8040 bool DAGCombiner::CombineToPostIndexedLoadStore(SDNode *N) {
8041 if (Level < AfterLegalizeDAG)
8047 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
8048 if (LD->isIndexed())
8050 VT = LD->getMemoryVT();
8051 if (!TLI.isIndexedLoadLegal(ISD::POST_INC, VT) &&
8052 !TLI.isIndexedLoadLegal(ISD::POST_DEC, VT))
8054 Ptr = LD->getBasePtr();
8055 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
8056 if (ST->isIndexed())
8058 VT = ST->getMemoryVT();
8059 if (!TLI.isIndexedStoreLegal(ISD::POST_INC, VT) &&
8060 !TLI.isIndexedStoreLegal(ISD::POST_DEC, VT))
8062 Ptr = ST->getBasePtr();
8068 if (Ptr.getNode()->hasOneUse())
8071 for (SDNode *Op : Ptr.getNode()->uses()) {
8073 (Op->getOpcode() != ISD::ADD && Op->getOpcode() != ISD::SUB))
8078 ISD::MemIndexedMode AM = ISD::UNINDEXED;
8079 if (TLI.getPostIndexedAddressParts(N, Op, BasePtr, Offset, AM, DAG)) {
8080 // Don't create a indexed load / store with zero offset.
8081 if (isa<ConstantSDNode>(Offset) &&
8082 cast<ConstantSDNode>(Offset)->isNullValue())
8085 // Try turning it into a post-indexed load / store except when
8086 // 1) All uses are load / store ops that use it as base ptr (and
8087 // it may be folded as addressing mmode).
8088 // 2) Op must be independent of N, i.e. Op is neither a predecessor
8089 // nor a successor of N. Otherwise, if Op is folded that would
8092 if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr))
8096 bool TryNext = false;
8097 for (SDNode *Use : BasePtr.getNode()->uses()) {
8098 if (Use == Ptr.getNode())
8101 // If all the uses are load / store addresses, then don't do the
8103 if (Use->getOpcode() == ISD::ADD || Use->getOpcode() == ISD::SUB){
8104 bool RealUse = false;
8105 for (SDNode *UseUse : Use->uses()) {
8106 if (!canFoldInAddressingMode(Use, UseUse, DAG, TLI))
8121 if (!Op->isPredecessorOf(N) && !N->isPredecessorOf(Op)) {
8122 SDValue Result = isLoad
8123 ? DAG.getIndexedLoad(SDValue(N,0), SDLoc(N),
8124 BasePtr, Offset, AM)
8125 : DAG.getIndexedStore(SDValue(N,0), SDLoc(N),
8126 BasePtr, Offset, AM);
8129 DEBUG(dbgs() << "\nReplacing.5 ";
8131 dbgs() << "\nWith: ";
8132 Result.getNode()->dump(&DAG);
8134 WorklistRemover DeadNodes(*this);
8136 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0));
8137 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2));
8139 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1));
8142 // Finally, since the node is now dead, remove it from the graph.
8143 deleteAndRecombine(N);
8145 // Replace the uses of Use with uses of the updated base value.
8146 DAG.ReplaceAllUsesOfValueWith(SDValue(Op, 0),
8147 Result.getValue(isLoad ? 1 : 0));
8148 deleteAndRecombine(Op);
8157 /// \brief Return the base-pointer arithmetic from an indexed \p LD.
8158 SDValue DAGCombiner::SplitIndexingFromLoad(LoadSDNode *LD) {
8159 ISD::MemIndexedMode AM = LD->getAddressingMode();
8160 assert(AM != ISD::UNINDEXED);
8161 SDValue BP = LD->getOperand(1);
8162 SDValue Inc = LD->getOperand(2);
8164 // Some backends use TargetConstants for load offsets, but don't expect
8165 // TargetConstants in general ADD nodes. We can convert these constants into
8166 // regular Constants (if the constant is not opaque).
8167 assert((Inc.getOpcode() != ISD::TargetConstant ||
8168 !cast<ConstantSDNode>(Inc)->isOpaque()) &&
8169 "Cannot split out indexing using opaque target constants");
8170 if (Inc.getOpcode() == ISD::TargetConstant) {
8171 ConstantSDNode *ConstInc = cast<ConstantSDNode>(Inc);
8172 Inc = DAG.getConstant(*ConstInc->getConstantIntValue(),
8173 ConstInc->getValueType(0));
8177 (AM == ISD::PRE_INC || AM == ISD::POST_INC ? ISD::ADD : ISD::SUB);
8178 return DAG.getNode(Opc, SDLoc(LD), BP.getSimpleValueType(), BP, Inc);
8181 SDValue DAGCombiner::visitLOAD(SDNode *N) {
8182 LoadSDNode *LD = cast<LoadSDNode>(N);
8183 SDValue Chain = LD->getChain();
8184 SDValue Ptr = LD->getBasePtr();
8186 // If load is not volatile and there are no uses of the loaded value (and
8187 // the updated indexed value in case of indexed loads), change uses of the
8188 // chain value into uses of the chain input (i.e. delete the dead load).
8189 if (!LD->isVolatile()) {
8190 if (N->getValueType(1) == MVT::Other) {
8192 if (!N->hasAnyUseOfValue(0)) {
8193 // It's not safe to use the two value CombineTo variant here. e.g.
8194 // v1, chain2 = load chain1, loc
8195 // v2, chain3 = load chain2, loc
8197 // Now we replace use of chain2 with chain1. This makes the second load
8198 // isomorphic to the one we are deleting, and thus makes this load live.
8199 DEBUG(dbgs() << "\nReplacing.6 ";
8201 dbgs() << "\nWith chain: ";
8202 Chain.getNode()->dump(&DAG);
8204 WorklistRemover DeadNodes(*this);
8205 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain);
8208 deleteAndRecombine(N);
8210 return SDValue(N, 0); // Return N so it doesn't get rechecked!
8214 assert(N->getValueType(2) == MVT::Other && "Malformed indexed loads?");
8216 // If this load has an opaque TargetConstant offset, then we cannot split
8217 // the indexing into an add/sub directly (that TargetConstant may not be
8218 // valid for a different type of node, and we cannot convert an opaque
8219 // target constant into a regular constant).
8220 bool HasOTCInc = LD->getOperand(2).getOpcode() == ISD::TargetConstant &&
8221 cast<ConstantSDNode>(LD->getOperand(2))->isOpaque();
8223 if (!N->hasAnyUseOfValue(0) &&
8224 ((MaySplitLoadIndex && !HasOTCInc) || !N->hasAnyUseOfValue(1))) {
8225 SDValue Undef = DAG.getUNDEF(N->getValueType(0));
8227 if (N->hasAnyUseOfValue(1) && MaySplitLoadIndex && !HasOTCInc) {
8228 Index = SplitIndexingFromLoad(LD);
8229 // Try to fold the base pointer arithmetic into subsequent loads and
8231 AddUsersToWorklist(N);
8233 Index = DAG.getUNDEF(N->getValueType(1));
8234 DEBUG(dbgs() << "\nReplacing.7 ";
8236 dbgs() << "\nWith: ";
8237 Undef.getNode()->dump(&DAG);
8238 dbgs() << " and 2 other values\n");
8239 WorklistRemover DeadNodes(*this);
8240 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Undef);
8241 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Index);
8242 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 2), Chain);
8243 deleteAndRecombine(N);
8244 return SDValue(N, 0); // Return N so it doesn't get rechecked!
8249 // If this load is directly stored, replace the load value with the stored
8251 // TODO: Handle store large -> read small portion.
8252 // TODO: Handle TRUNCSTORE/LOADEXT
8253 if (ISD::isNormalLoad(N) && !LD->isVolatile()) {
8254 if (ISD::isNON_TRUNCStore(Chain.getNode())) {
8255 StoreSDNode *PrevST = cast<StoreSDNode>(Chain);
8256 if (PrevST->getBasePtr() == Ptr &&
8257 PrevST->getValue().getValueType() == N->getValueType(0))
8258 return CombineTo(N, Chain.getOperand(1), Chain);
8262 // Try to infer better alignment information than the load already has.
8263 if (OptLevel != CodeGenOpt::None && LD->isUnindexed()) {
8264 if (unsigned Align = DAG.InferPtrAlignment(Ptr)) {
8265 if (Align > LD->getMemOperand()->getBaseAlignment()) {
8267 DAG.getExtLoad(LD->getExtensionType(), SDLoc(N),
8268 LD->getValueType(0),
8269 Chain, Ptr, LD->getPointerInfo(),
8271 LD->isVolatile(), LD->isNonTemporal(),
8272 LD->isInvariant(), Align, LD->getAAInfo());
8273 return CombineTo(N, NewLoad, SDValue(NewLoad.getNode(), 1), true);
8278 bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA
8279 : DAG.getSubtarget().useAA();
8281 if (CombinerAAOnlyFunc.getNumOccurrences() &&
8282 CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
8285 if (UseAA && LD->isUnindexed()) {
8286 // Walk up chain skipping non-aliasing memory nodes.
8287 SDValue BetterChain = FindBetterChain(N, Chain);
8289 // If there is a better chain.
8290 if (Chain != BetterChain) {
8293 // Replace the chain to void dependency.
8294 if (LD->getExtensionType() == ISD::NON_EXTLOAD) {
8295 ReplLoad = DAG.getLoad(N->getValueType(0), SDLoc(LD),
8296 BetterChain, Ptr, LD->getMemOperand());
8298 ReplLoad = DAG.getExtLoad(LD->getExtensionType(), SDLoc(LD),
8299 LD->getValueType(0),
8300 BetterChain, Ptr, LD->getMemoryVT(),
8301 LD->getMemOperand());
8304 // Create token factor to keep old chain connected.
8305 SDValue Token = DAG.getNode(ISD::TokenFactor, SDLoc(N),
8306 MVT::Other, Chain, ReplLoad.getValue(1));
8308 // Make sure the new and old chains are cleaned up.
8309 AddToWorklist(Token.getNode());
8311 // Replace uses with load result and token factor. Don't add users
8313 return CombineTo(N, ReplLoad.getValue(0), Token, false);
8317 // Try transforming N to an indexed load.
8318 if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
8319 return SDValue(N, 0);
8321 // Try to slice up N to more direct loads if the slices are mapped to
8322 // different register banks or pairing can take place.
8324 return SDValue(N, 0);
8330 /// \brief Helper structure used to slice a load in smaller loads.
8331 /// Basically a slice is obtained from the following sequence:
8332 /// Origin = load Ty1, Base
8333 /// Shift = srl Ty1 Origin, CstTy Amount
8334 /// Inst = trunc Shift to Ty2
8336 /// Then, it will be rewriten into:
8337 /// Slice = load SliceTy, Base + SliceOffset
8338 /// [Inst = zext Slice to Ty2], only if SliceTy <> Ty2
8340 /// SliceTy is deduced from the number of bits that are actually used to
8342 struct LoadedSlice {
8343 /// \brief Helper structure used to compute the cost of a slice.
8345 /// Are we optimizing for code size.
8350 unsigned CrossRegisterBanksCopies;
8354 Cost(bool ForCodeSize = false)
8355 : ForCodeSize(ForCodeSize), Loads(0), Truncates(0),
8356 CrossRegisterBanksCopies(0), ZExts(0), Shift(0) {}
8358 /// \brief Get the cost of one isolated slice.
8359 Cost(const LoadedSlice &LS, bool ForCodeSize = false)
8360 : ForCodeSize(ForCodeSize), Loads(1), Truncates(0),
8361 CrossRegisterBanksCopies(0), ZExts(0), Shift(0) {
8362 EVT TruncType = LS.Inst->getValueType(0);
8363 EVT LoadedType = LS.getLoadedType();
8364 if (TruncType != LoadedType &&
8365 !LS.DAG->getTargetLoweringInfo().isZExtFree(LoadedType, TruncType))
8369 /// \brief Account for slicing gain in the current cost.
8370 /// Slicing provide a few gains like removing a shift or a
8371 /// truncate. This method allows to grow the cost of the original
8372 /// load with the gain from this slice.
8373 void addSliceGain(const LoadedSlice &LS) {
8374 // Each slice saves a truncate.
8375 const TargetLowering &TLI = LS.DAG->getTargetLoweringInfo();
8376 if (!TLI.isTruncateFree(LS.Inst->getValueType(0),
8377 LS.Inst->getOperand(0).getValueType()))
8379 // If there is a shift amount, this slice gets rid of it.
8382 // If this slice can merge a cross register bank copy, account for it.
8383 if (LS.canMergeExpensiveCrossRegisterBankCopy())
8384 ++CrossRegisterBanksCopies;
8387 Cost &operator+=(const Cost &RHS) {
8389 Truncates += RHS.Truncates;
8390 CrossRegisterBanksCopies += RHS.CrossRegisterBanksCopies;
8396 bool operator==(const Cost &RHS) const {
8397 return Loads == RHS.Loads && Truncates == RHS.Truncates &&
8398 CrossRegisterBanksCopies == RHS.CrossRegisterBanksCopies &&
8399 ZExts == RHS.ZExts && Shift == RHS.Shift;
8402 bool operator!=(const Cost &RHS) const { return !(*this == RHS); }
8404 bool operator<(const Cost &RHS) const {
8405 // Assume cross register banks copies are as expensive as loads.
8406 // FIXME: Do we want some more target hooks?
8407 unsigned ExpensiveOpsLHS = Loads + CrossRegisterBanksCopies;
8408 unsigned ExpensiveOpsRHS = RHS.Loads + RHS.CrossRegisterBanksCopies;
8409 // Unless we are optimizing for code size, consider the
8410 // expensive operation first.
8411 if (!ForCodeSize && ExpensiveOpsLHS != ExpensiveOpsRHS)
8412 return ExpensiveOpsLHS < ExpensiveOpsRHS;
8413 return (Truncates + ZExts + Shift + ExpensiveOpsLHS) <
8414 (RHS.Truncates + RHS.ZExts + RHS.Shift + ExpensiveOpsRHS);
8417 bool operator>(const Cost &RHS) const { return RHS < *this; }
8419 bool operator<=(const Cost &RHS) const { return !(RHS < *this); }
8421 bool operator>=(const Cost &RHS) const { return !(*this < RHS); }
8423 // The last instruction that represent the slice. This should be a
8424 // truncate instruction.
8426 // The original load instruction.
8428 // The right shift amount in bits from the original load.
8430 // The DAG from which Origin came from.
8431 // This is used to get some contextual information about legal types, etc.
8434 LoadedSlice(SDNode *Inst = nullptr, LoadSDNode *Origin = nullptr,
8435 unsigned Shift = 0, SelectionDAG *DAG = nullptr)
8436 : Inst(Inst), Origin(Origin), Shift(Shift), DAG(DAG) {}
8438 LoadedSlice(const LoadedSlice &LS)
8439 : Inst(LS.Inst), Origin(LS.Origin), Shift(LS.Shift), DAG(LS.DAG) {}
8441 /// \brief Get the bits used in a chunk of bits \p BitWidth large.
8442 /// \return Result is \p BitWidth and has used bits set to 1 and
8443 /// not used bits set to 0.
8444 APInt getUsedBits() const {
8445 // Reproduce the trunc(lshr) sequence:
8446 // - Start from the truncated value.
8447 // - Zero extend to the desired bit width.
8449 assert(Origin && "No original load to compare against.");
8450 unsigned BitWidth = Origin->getValueSizeInBits(0);
8451 assert(Inst && "This slice is not bound to an instruction");
8452 assert(Inst->getValueSizeInBits(0) <= BitWidth &&
8453 "Extracted slice is bigger than the whole type!");
8454 APInt UsedBits(Inst->getValueSizeInBits(0), 0);
8455 UsedBits.setAllBits();
8456 UsedBits = UsedBits.zext(BitWidth);
8461 /// \brief Get the size of the slice to be loaded in bytes.
8462 unsigned getLoadedSize() const {
8463 unsigned SliceSize = getUsedBits().countPopulation();
8464 assert(!(SliceSize & 0x7) && "Size is not a multiple of a byte.");
8465 return SliceSize / 8;
8468 /// \brief Get the type that will be loaded for this slice.
8469 /// Note: This may not be the final type for the slice.
8470 EVT getLoadedType() const {
8471 assert(DAG && "Missing context");
8472 LLVMContext &Ctxt = *DAG->getContext();
8473 return EVT::getIntegerVT(Ctxt, getLoadedSize() * 8);
8476 /// \brief Get the alignment of the load used for this slice.
8477 unsigned getAlignment() const {
8478 unsigned Alignment = Origin->getAlignment();
8479 unsigned Offset = getOffsetFromBase();
8481 Alignment = MinAlign(Alignment, Alignment + Offset);
8485 /// \brief Check if this slice can be rewritten with legal operations.
8486 bool isLegal() const {
8487 // An invalid slice is not legal.
8488 if (!Origin || !Inst || !DAG)
8491 // Offsets are for indexed load only, we do not handle that.
8492 if (Origin->getOffset().getOpcode() != ISD::UNDEF)
8495 const TargetLowering &TLI = DAG->getTargetLoweringInfo();
8497 // Check that the type is legal.
8498 EVT SliceType = getLoadedType();
8499 if (!TLI.isTypeLegal(SliceType))
8502 // Check that the load is legal for this type.
8503 if (!TLI.isOperationLegal(ISD::LOAD, SliceType))
8506 // Check that the offset can be computed.
8507 // 1. Check its type.
8508 EVT PtrType = Origin->getBasePtr().getValueType();
8509 if (PtrType == MVT::Untyped || PtrType.isExtended())
8512 // 2. Check that it fits in the immediate.
8513 if (!TLI.isLegalAddImmediate(getOffsetFromBase()))
8516 // 3. Check that the computation is legal.
8517 if (!TLI.isOperationLegal(ISD::ADD, PtrType))
8520 // Check that the zext is legal if it needs one.
8521 EVT TruncateType = Inst->getValueType(0);
8522 if (TruncateType != SliceType &&
8523 !TLI.isOperationLegal(ISD::ZERO_EXTEND, TruncateType))
8529 /// \brief Get the offset in bytes of this slice in the original chunk of
8531 /// \pre DAG != nullptr.
8532 uint64_t getOffsetFromBase() const {
8533 assert(DAG && "Missing context.");
8535 DAG->getTargetLoweringInfo().getDataLayout()->isBigEndian();
8536 assert(!(Shift & 0x7) && "Shifts not aligned on Bytes are not supported.");
8537 uint64_t Offset = Shift / 8;
8538 unsigned TySizeInBytes = Origin->getValueSizeInBits(0) / 8;
8539 assert(!(Origin->getValueSizeInBits(0) & 0x7) &&
8540 "The size of the original loaded type is not a multiple of a"
8542 // If Offset is bigger than TySizeInBytes, it means we are loading all
8543 // zeros. This should have been optimized before in the process.
8544 assert(TySizeInBytes > Offset &&
8545 "Invalid shift amount for given loaded size");
8547 Offset = TySizeInBytes - Offset - getLoadedSize();
8551 /// \brief Generate the sequence of instructions to load the slice
8552 /// represented by this object and redirect the uses of this slice to
8553 /// this new sequence of instructions.
8554 /// \pre this->Inst && this->Origin are valid Instructions and this
8555 /// object passed the legal check: LoadedSlice::isLegal returned true.
8556 /// \return The last instruction of the sequence used to load the slice.
8557 SDValue loadSlice() const {
8558 assert(Inst && Origin && "Unable to replace a non-existing slice.");
8559 const SDValue &OldBaseAddr = Origin->getBasePtr();
8560 SDValue BaseAddr = OldBaseAddr;
8561 // Get the offset in that chunk of bytes w.r.t. the endianess.
8562 int64_t Offset = static_cast<int64_t>(getOffsetFromBase());
8563 assert(Offset >= 0 && "Offset too big to fit in int64_t!");
8565 // BaseAddr = BaseAddr + Offset.
8566 EVT ArithType = BaseAddr.getValueType();
8567 BaseAddr = DAG->getNode(ISD::ADD, SDLoc(Origin), ArithType, BaseAddr,
8568 DAG->getConstant(Offset, ArithType));
8571 // Create the type of the loaded slice according to its size.
8572 EVT SliceType = getLoadedType();
8574 // Create the load for the slice.
8575 SDValue LastInst = DAG->getLoad(
8576 SliceType, SDLoc(Origin), Origin->getChain(), BaseAddr,
8577 Origin->getPointerInfo().getWithOffset(Offset), Origin->isVolatile(),
8578 Origin->isNonTemporal(), Origin->isInvariant(), getAlignment());
8579 // If the final type is not the same as the loaded type, this means that
8580 // we have to pad with zero. Create a zero extend for that.
8581 EVT FinalType = Inst->getValueType(0);
8582 if (SliceType != FinalType)
8584 DAG->getNode(ISD::ZERO_EXTEND, SDLoc(LastInst), FinalType, LastInst);
8588 /// \brief Check if this slice can be merged with an expensive cross register
8589 /// bank copy. E.g.,
8591 /// f = bitcast i32 i to float
8592 bool canMergeExpensiveCrossRegisterBankCopy() const {
8593 if (!Inst || !Inst->hasOneUse())
8595 SDNode *Use = *Inst->use_begin();
8596 if (Use->getOpcode() != ISD::BITCAST)
8598 assert(DAG && "Missing context");
8599 const TargetLowering &TLI = DAG->getTargetLoweringInfo();
8600 EVT ResVT = Use->getValueType(0);
8601 const TargetRegisterClass *ResRC = TLI.getRegClassFor(ResVT.getSimpleVT());
8602 const TargetRegisterClass *ArgRC =
8603 TLI.getRegClassFor(Use->getOperand(0).getValueType().getSimpleVT());
8604 if (ArgRC == ResRC || !TLI.isOperationLegal(ISD::LOAD, ResVT))
8607 // At this point, we know that we perform a cross-register-bank copy.
8608 // Check if it is expensive.
8609 const TargetRegisterInfo *TRI = DAG->getSubtarget().getRegisterInfo();
8610 // Assume bitcasts are cheap, unless both register classes do not
8611 // explicitly share a common sub class.
8612 if (!TRI || TRI->getCommonSubClass(ArgRC, ResRC))
8615 // Check if it will be merged with the load.
8616 // 1. Check the alignment constraint.
8617 unsigned RequiredAlignment = TLI.getDataLayout()->getABITypeAlignment(
8618 ResVT.getTypeForEVT(*DAG->getContext()));
8620 if (RequiredAlignment > getAlignment())
8623 // 2. Check that the load is a legal operation for that type.
8624 if (!TLI.isOperationLegal(ISD::LOAD, ResVT))
8627 // 3. Check that we do not have a zext in the way.
8628 if (Inst->getValueType(0) != getLoadedType())
8636 /// \brief Check that all bits set in \p UsedBits form a dense region, i.e.,
8637 /// \p UsedBits looks like 0..0 1..1 0..0.
8638 static bool areUsedBitsDense(const APInt &UsedBits) {
8639 // If all the bits are one, this is dense!
8640 if (UsedBits.isAllOnesValue())
8643 // Get rid of the unused bits on the right.
8644 APInt NarrowedUsedBits = UsedBits.lshr(UsedBits.countTrailingZeros());
8645 // Get rid of the unused bits on the left.
8646 if (NarrowedUsedBits.countLeadingZeros())
8647 NarrowedUsedBits = NarrowedUsedBits.trunc(NarrowedUsedBits.getActiveBits());
8648 // Check that the chunk of bits is completely used.
8649 return NarrowedUsedBits.isAllOnesValue();
8652 /// \brief Check whether or not \p First and \p Second are next to each other
8653 /// in memory. This means that there is no hole between the bits loaded
8654 /// by \p First and the bits loaded by \p Second.
8655 static bool areSlicesNextToEachOther(const LoadedSlice &First,
8656 const LoadedSlice &Second) {
8657 assert(First.Origin == Second.Origin && First.Origin &&
8658 "Unable to match different memory origins.");
8659 APInt UsedBits = First.getUsedBits();
8660 assert((UsedBits & Second.getUsedBits()) == 0 &&
8661 "Slices are not supposed to overlap.");
8662 UsedBits |= Second.getUsedBits();
8663 return areUsedBitsDense(UsedBits);
8666 /// \brief Adjust the \p GlobalLSCost according to the target
8667 /// paring capabilities and the layout of the slices.
8668 /// \pre \p GlobalLSCost should account for at least as many loads as
8669 /// there is in the slices in \p LoadedSlices.
8670 static void adjustCostForPairing(SmallVectorImpl<LoadedSlice> &LoadedSlices,
8671 LoadedSlice::Cost &GlobalLSCost) {
8672 unsigned NumberOfSlices = LoadedSlices.size();
8673 // If there is less than 2 elements, no pairing is possible.
8674 if (NumberOfSlices < 2)
8677 // Sort the slices so that elements that are likely to be next to each
8678 // other in memory are next to each other in the list.
8679 std::sort(LoadedSlices.begin(), LoadedSlices.end(),
8680 [](const LoadedSlice &LHS, const LoadedSlice &RHS) {
8681 assert(LHS.Origin == RHS.Origin && "Different bases not implemented.");
8682 return LHS.getOffsetFromBase() < RHS.getOffsetFromBase();
8684 const TargetLowering &TLI = LoadedSlices[0].DAG->getTargetLoweringInfo();
8685 // First (resp. Second) is the first (resp. Second) potentially candidate
8686 // to be placed in a paired load.
8687 const LoadedSlice *First = nullptr;
8688 const LoadedSlice *Second = nullptr;
8689 for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice,
8690 // Set the beginning of the pair.
8693 Second = &LoadedSlices[CurrSlice];
8695 // If First is NULL, it means we start a new pair.
8696 // Get to the next slice.
8700 EVT LoadedType = First->getLoadedType();
8702 // If the types of the slices are different, we cannot pair them.
8703 if (LoadedType != Second->getLoadedType())
8706 // Check if the target supplies paired loads for this type.
8707 unsigned RequiredAlignment = 0;
8708 if (!TLI.hasPairedLoad(LoadedType, RequiredAlignment)) {
8709 // move to the next pair, this type is hopeless.
8713 // Check if we meet the alignment requirement.
8714 if (RequiredAlignment > First->getAlignment())
8717 // Check that both loads are next to each other in memory.
8718 if (!areSlicesNextToEachOther(*First, *Second))
8721 assert(GlobalLSCost.Loads > 0 && "We save more loads than we created!");
8722 --GlobalLSCost.Loads;
8723 // Move to the next pair.
8728 /// \brief Check the profitability of all involved LoadedSlice.
8729 /// Currently, it is considered profitable if there is exactly two
8730 /// involved slices (1) which are (2) next to each other in memory, and
8731 /// whose cost (\see LoadedSlice::Cost) is smaller than the original load (3).
8733 /// Note: The order of the elements in \p LoadedSlices may be modified, but not
8734 /// the elements themselves.
8736 /// FIXME: When the cost model will be mature enough, we can relax
8737 /// constraints (1) and (2).
8738 static bool isSlicingProfitable(SmallVectorImpl<LoadedSlice> &LoadedSlices,
8739 const APInt &UsedBits, bool ForCodeSize) {
8740 unsigned NumberOfSlices = LoadedSlices.size();
8741 if (StressLoadSlicing)
8742 return NumberOfSlices > 1;
8745 if (NumberOfSlices != 2)
8749 if (!areUsedBitsDense(UsedBits))
8753 LoadedSlice::Cost OrigCost(ForCodeSize), GlobalSlicingCost(ForCodeSize);
8754 // The original code has one big load.
8756 for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice) {
8757 const LoadedSlice &LS = LoadedSlices[CurrSlice];
8758 // Accumulate the cost of all the slices.
8759 LoadedSlice::Cost SliceCost(LS, ForCodeSize);
8760 GlobalSlicingCost += SliceCost;
8762 // Account as cost in the original configuration the gain obtained
8763 // with the current slices.
8764 OrigCost.addSliceGain(LS);
8767 // If the target supports paired load, adjust the cost accordingly.
8768 adjustCostForPairing(LoadedSlices, GlobalSlicingCost);
8769 return OrigCost > GlobalSlicingCost;
8772 /// \brief If the given load, \p LI, is used only by trunc or trunc(lshr)
8773 /// operations, split it in the various pieces being extracted.
8775 /// This sort of thing is introduced by SROA.
8776 /// This slicing takes care not to insert overlapping loads.
8777 /// \pre LI is a simple load (i.e., not an atomic or volatile load).
8778 bool DAGCombiner::SliceUpLoad(SDNode *N) {
8779 if (Level < AfterLegalizeDAG)
8782 LoadSDNode *LD = cast<LoadSDNode>(N);
8783 if (LD->isVolatile() || !ISD::isNormalLoad(LD) ||
8784 !LD->getValueType(0).isInteger())
8787 // Keep track of already used bits to detect overlapping values.
8788 // In that case, we will just abort the transformation.
8789 APInt UsedBits(LD->getValueSizeInBits(0), 0);
8791 SmallVector<LoadedSlice, 4> LoadedSlices;
8793 // Check if this load is used as several smaller chunks of bits.
8794 // Basically, look for uses in trunc or trunc(lshr) and record a new chain
8795 // of computation for each trunc.
8796 for (SDNode::use_iterator UI = LD->use_begin(), UIEnd = LD->use_end();
8797 UI != UIEnd; ++UI) {
8798 // Skip the uses of the chain.
8799 if (UI.getUse().getResNo() != 0)
8805 // Check if this is a trunc(lshr).
8806 if (User->getOpcode() == ISD::SRL && User->hasOneUse() &&
8807 isa<ConstantSDNode>(User->getOperand(1))) {
8808 Shift = cast<ConstantSDNode>(User->getOperand(1))->getZExtValue();
8809 User = *User->use_begin();
8812 // At this point, User is a Truncate, iff we encountered, trunc or
8814 if (User->getOpcode() != ISD::TRUNCATE)
8817 // The width of the type must be a power of 2 and greater than 8-bits.
8818 // Otherwise the load cannot be represented in LLVM IR.
8819 // Moreover, if we shifted with a non-8-bits multiple, the slice
8820 // will be across several bytes. We do not support that.
8821 unsigned Width = User->getValueSizeInBits(0);
8822 if (Width < 8 || !isPowerOf2_32(Width) || (Shift & 0x7))
8825 // Build the slice for this chain of computations.
8826 LoadedSlice LS(User, LD, Shift, &DAG);
8827 APInt CurrentUsedBits = LS.getUsedBits();
8829 // Check if this slice overlaps with another.
8830 if ((CurrentUsedBits & UsedBits) != 0)
8832 // Update the bits used globally.
8833 UsedBits |= CurrentUsedBits;
8835 // Check if the new slice would be legal.
8839 // Record the slice.
8840 LoadedSlices.push_back(LS);
8843 // Abort slicing if it does not seem to be profitable.
8844 if (!isSlicingProfitable(LoadedSlices, UsedBits, ForCodeSize))
8849 // Rewrite each chain to use an independent load.
8850 // By construction, each chain can be represented by a unique load.
8852 // Prepare the argument for the new token factor for all the slices.
8853 SmallVector<SDValue, 8> ArgChains;
8854 for (SmallVectorImpl<LoadedSlice>::const_iterator
8855 LSIt = LoadedSlices.begin(),
8856 LSItEnd = LoadedSlices.end();
8857 LSIt != LSItEnd; ++LSIt) {
8858 SDValue SliceInst = LSIt->loadSlice();
8859 CombineTo(LSIt->Inst, SliceInst, true);
8860 if (SliceInst.getNode()->getOpcode() != ISD::LOAD)
8861 SliceInst = SliceInst.getOperand(0);
8862 assert(SliceInst->getOpcode() == ISD::LOAD &&
8863 "It takes more than a zext to get to the loaded slice!!");
8864 ArgChains.push_back(SliceInst.getValue(1));
8867 SDValue Chain = DAG.getNode(ISD::TokenFactor, SDLoc(LD), MVT::Other,
8869 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain);
8873 /// Check to see if V is (and load (ptr), imm), where the load is having
8874 /// specific bytes cleared out. If so, return the byte size being masked out
8875 /// and the shift amount.
8876 static std::pair<unsigned, unsigned>
8877 CheckForMaskedLoad(SDValue V, SDValue Ptr, SDValue Chain) {
8878 std::pair<unsigned, unsigned> Result(0, 0);
8880 // Check for the structure we're looking for.
8881 if (V->getOpcode() != ISD::AND ||
8882 !isa<ConstantSDNode>(V->getOperand(1)) ||
8883 !ISD::isNormalLoad(V->getOperand(0).getNode()))
8886 // Check the chain and pointer.
8887 LoadSDNode *LD = cast<LoadSDNode>(V->getOperand(0));
8888 if (LD->getBasePtr() != Ptr) return Result; // Not from same pointer.
8890 // The store should be chained directly to the load or be an operand of a
8892 if (LD == Chain.getNode())
8894 else if (Chain->getOpcode() != ISD::TokenFactor)
8895 return Result; // Fail.
8898 for (unsigned i = 0, e = Chain->getNumOperands(); i != e; ++i)
8899 if (Chain->getOperand(i).getNode() == LD) {
8903 if (!isOk) return Result;
8906 // This only handles simple types.
8907 if (V.getValueType() != MVT::i16 &&
8908 V.getValueType() != MVT::i32 &&
8909 V.getValueType() != MVT::i64)
8912 // Check the constant mask. Invert it so that the bits being masked out are
8913 // 0 and the bits being kept are 1. Use getSExtValue so that leading bits
8914 // follow the sign bit for uniformity.
8915 uint64_t NotMask = ~cast<ConstantSDNode>(V->getOperand(1))->getSExtValue();
8916 unsigned NotMaskLZ = countLeadingZeros(NotMask);
8917 if (NotMaskLZ & 7) return Result; // Must be multiple of a byte.
8918 unsigned NotMaskTZ = countTrailingZeros(NotMask);
8919 if (NotMaskTZ & 7) return Result; // Must be multiple of a byte.
8920 if (NotMaskLZ == 64) return Result; // All zero mask.
8922 // See if we have a continuous run of bits. If so, we have 0*1+0*
8923 if (CountTrailingOnes_64(NotMask >> NotMaskTZ)+NotMaskTZ+NotMaskLZ != 64)
8926 // Adjust NotMaskLZ down to be from the actual size of the int instead of i64.
8927 if (V.getValueType() != MVT::i64 && NotMaskLZ)
8928 NotMaskLZ -= 64-V.getValueSizeInBits();
8930 unsigned MaskedBytes = (V.getValueSizeInBits()-NotMaskLZ-NotMaskTZ)/8;
8931 switch (MaskedBytes) {
8935 default: return Result; // All one mask, or 5-byte mask.
8938 // Verify that the first bit starts at a multiple of mask so that the access
8939 // is aligned the same as the access width.
8940 if (NotMaskTZ && NotMaskTZ/8 % MaskedBytes) return Result;
8942 Result.first = MaskedBytes;
8943 Result.second = NotMaskTZ/8;
8948 /// Check to see if IVal is something that provides a value as specified by
8949 /// MaskInfo. If so, replace the specified store with a narrower store of
8952 ShrinkLoadReplaceStoreWithStore(const std::pair<unsigned, unsigned> &MaskInfo,
8953 SDValue IVal, StoreSDNode *St,
8955 unsigned NumBytes = MaskInfo.first;
8956 unsigned ByteShift = MaskInfo.second;
8957 SelectionDAG &DAG = DC->getDAG();
8959 // Check to see if IVal is all zeros in the part being masked in by the 'or'
8960 // that uses this. If not, this is not a replacement.
8961 APInt Mask = ~APInt::getBitsSet(IVal.getValueSizeInBits(),
8962 ByteShift*8, (ByteShift+NumBytes)*8);
8963 if (!DAG.MaskedValueIsZero(IVal, Mask)) return nullptr;
8965 // Check that it is legal on the target to do this. It is legal if the new
8966 // VT we're shrinking to (i8/i16/i32) is legal or we're still before type
8968 MVT VT = MVT::getIntegerVT(NumBytes*8);
8969 if (!DC->isTypeLegal(VT))
8972 // Okay, we can do this! Replace the 'St' store with a store of IVal that is
8973 // shifted by ByteShift and truncated down to NumBytes.
8975 IVal = DAG.getNode(ISD::SRL, SDLoc(IVal), IVal.getValueType(), IVal,
8976 DAG.getConstant(ByteShift*8,
8977 DC->getShiftAmountTy(IVal.getValueType())));
8979 // Figure out the offset for the store and the alignment of the access.
8981 unsigned NewAlign = St->getAlignment();
8983 if (DAG.getTargetLoweringInfo().isLittleEndian())
8984 StOffset = ByteShift;
8986 StOffset = IVal.getValueType().getStoreSize() - ByteShift - NumBytes;
8988 SDValue Ptr = St->getBasePtr();
8990 Ptr = DAG.getNode(ISD::ADD, SDLoc(IVal), Ptr.getValueType(),
8991 Ptr, DAG.getConstant(StOffset, Ptr.getValueType()));
8992 NewAlign = MinAlign(NewAlign, StOffset);
8995 // Truncate down to the new size.
8996 IVal = DAG.getNode(ISD::TRUNCATE, SDLoc(IVal), VT, IVal);
8999 return DAG.getStore(St->getChain(), SDLoc(St), IVal, Ptr,
9000 St->getPointerInfo().getWithOffset(StOffset),
9001 false, false, NewAlign).getNode();
9005 /// Look for sequence of load / op / store where op is one of 'or', 'xor', and
9006 /// 'and' of immediates. If 'op' is only touching some of the loaded bits, try
9007 /// narrowing the load and store if it would end up being a win for performance
9009 SDValue DAGCombiner::ReduceLoadOpStoreWidth(SDNode *N) {
9010 StoreSDNode *ST = cast<StoreSDNode>(N);
9011 if (ST->isVolatile())
9014 SDValue Chain = ST->getChain();
9015 SDValue Value = ST->getValue();
9016 SDValue Ptr = ST->getBasePtr();
9017 EVT VT = Value.getValueType();
9019 if (ST->isTruncatingStore() || VT.isVector() || !Value.hasOneUse())
9022 unsigned Opc = Value.getOpcode();
9024 // If this is "store (or X, Y), P" and X is "(and (load P), cst)", where cst
9025 // is a byte mask indicating a consecutive number of bytes, check to see if
9026 // Y is known to provide just those bytes. If so, we try to replace the
9027 // load + replace + store sequence with a single (narrower) store, which makes
9029 if (Opc == ISD::OR) {
9030 std::pair<unsigned, unsigned> MaskedLoad;
9031 MaskedLoad = CheckForMaskedLoad(Value.getOperand(0), Ptr, Chain);
9032 if (MaskedLoad.first)
9033 if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad,
9034 Value.getOperand(1), ST,this))
9035 return SDValue(NewST, 0);
9037 // Or is commutative, so try swapping X and Y.
9038 MaskedLoad = CheckForMaskedLoad(Value.getOperand(1), Ptr, Chain);
9039 if (MaskedLoad.first)
9040 if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad,
9041 Value.getOperand(0), ST,this))
9042 return SDValue(NewST, 0);
9045 if ((Opc != ISD::OR && Opc != ISD::XOR && Opc != ISD::AND) ||
9046 Value.getOperand(1).getOpcode() != ISD::Constant)
9049 SDValue N0 = Value.getOperand(0);
9050 if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
9051 Chain == SDValue(N0.getNode(), 1)) {
9052 LoadSDNode *LD = cast<LoadSDNode>(N0);
9053 if (LD->getBasePtr() != Ptr ||
9054 LD->getPointerInfo().getAddrSpace() !=
9055 ST->getPointerInfo().getAddrSpace())
9058 // Find the type to narrow it the load / op / store to.
9059 SDValue N1 = Value.getOperand(1);
9060 unsigned BitWidth = N1.getValueSizeInBits();
9061 APInt Imm = cast<ConstantSDNode>(N1)->getAPIntValue();
9062 if (Opc == ISD::AND)
9063 Imm ^= APInt::getAllOnesValue(BitWidth);
9064 if (Imm == 0 || Imm.isAllOnesValue())
9066 unsigned ShAmt = Imm.countTrailingZeros();
9067 unsigned MSB = BitWidth - Imm.countLeadingZeros() - 1;
9068 unsigned NewBW = NextPowerOf2(MSB - ShAmt);
9069 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW);
9070 while (NewBW < BitWidth &&
9071 !(TLI.isOperationLegalOrCustom(Opc, NewVT) &&
9072 TLI.isNarrowingProfitable(VT, NewVT))) {
9073 NewBW = NextPowerOf2(NewBW);
9074 NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW);
9076 if (NewBW >= BitWidth)
9079 // If the lsb changed does not start at the type bitwidth boundary,
9080 // start at the previous one.
9082 ShAmt = (((ShAmt + NewBW - 1) / NewBW) * NewBW) - NewBW;
9083 APInt Mask = APInt::getBitsSet(BitWidth, ShAmt,
9084 std::min(BitWidth, ShAmt + NewBW));
9085 if ((Imm & Mask) == Imm) {
9086 APInt NewImm = (Imm & Mask).lshr(ShAmt).trunc(NewBW);
9087 if (Opc == ISD::AND)
9088 NewImm ^= APInt::getAllOnesValue(NewBW);
9089 uint64_t PtrOff = ShAmt / 8;
9090 // For big endian targets, we need to adjust the offset to the pointer to
9091 // load the correct bytes.
9092 if (TLI.isBigEndian())
9093 PtrOff = (BitWidth + 7 - NewBW) / 8 - PtrOff;
9095 unsigned NewAlign = MinAlign(LD->getAlignment(), PtrOff);
9096 Type *NewVTTy = NewVT.getTypeForEVT(*DAG.getContext());
9097 if (NewAlign < TLI.getDataLayout()->getABITypeAlignment(NewVTTy))
9100 SDValue NewPtr = DAG.getNode(ISD::ADD, SDLoc(LD),
9101 Ptr.getValueType(), Ptr,
9102 DAG.getConstant(PtrOff, Ptr.getValueType()));
9103 SDValue NewLD = DAG.getLoad(NewVT, SDLoc(N0),
9104 LD->getChain(), NewPtr,
9105 LD->getPointerInfo().getWithOffset(PtrOff),
9106 LD->isVolatile(), LD->isNonTemporal(),
9107 LD->isInvariant(), NewAlign,
9109 SDValue NewVal = DAG.getNode(Opc, SDLoc(Value), NewVT, NewLD,
9110 DAG.getConstant(NewImm, NewVT));
9111 SDValue NewST = DAG.getStore(Chain, SDLoc(N),
9113 ST->getPointerInfo().getWithOffset(PtrOff),
9114 false, false, NewAlign);
9116 AddToWorklist(NewPtr.getNode());
9117 AddToWorklist(NewLD.getNode());
9118 AddToWorklist(NewVal.getNode());
9119 WorklistRemover DeadNodes(*this);
9120 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLD.getValue(1));
9129 /// For a given floating point load / store pair, if the load value isn't used
9130 /// by any other operations, then consider transforming the pair to integer
9131 /// load / store operations if the target deems the transformation profitable.
9132 SDValue DAGCombiner::TransformFPLoadStorePair(SDNode *N) {
9133 StoreSDNode *ST = cast<StoreSDNode>(N);
9134 SDValue Chain = ST->getChain();
9135 SDValue Value = ST->getValue();
9136 if (ISD::isNormalStore(ST) && ISD::isNormalLoad(Value.getNode()) &&
9137 Value.hasOneUse() &&
9138 Chain == SDValue(Value.getNode(), 1)) {
9139 LoadSDNode *LD = cast<LoadSDNode>(Value);
9140 EVT VT = LD->getMemoryVT();
9141 if (!VT.isFloatingPoint() ||
9142 VT != ST->getMemoryVT() ||
9143 LD->isNonTemporal() ||
9144 ST->isNonTemporal() ||
9145 LD->getPointerInfo().getAddrSpace() != 0 ||
9146 ST->getPointerInfo().getAddrSpace() != 0)
9149 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), VT.getSizeInBits());
9150 if (!TLI.isOperationLegal(ISD::LOAD, IntVT) ||
9151 !TLI.isOperationLegal(ISD::STORE, IntVT) ||
9152 !TLI.isDesirableToTransformToIntegerOp(ISD::LOAD, VT) ||
9153 !TLI.isDesirableToTransformToIntegerOp(ISD::STORE, VT))
9156 unsigned LDAlign = LD->getAlignment();
9157 unsigned STAlign = ST->getAlignment();
9158 Type *IntVTTy = IntVT.getTypeForEVT(*DAG.getContext());
9159 unsigned ABIAlign = TLI.getDataLayout()->getABITypeAlignment(IntVTTy);
9160 if (LDAlign < ABIAlign || STAlign < ABIAlign)
9163 SDValue NewLD = DAG.getLoad(IntVT, SDLoc(Value),
9164 LD->getChain(), LD->getBasePtr(),
9165 LD->getPointerInfo(),
9166 false, false, false, LDAlign);
9168 SDValue NewST = DAG.getStore(NewLD.getValue(1), SDLoc(N),
9169 NewLD, ST->getBasePtr(),
9170 ST->getPointerInfo(),
9171 false, false, STAlign);
9173 AddToWorklist(NewLD.getNode());
9174 AddToWorklist(NewST.getNode());
9175 WorklistRemover DeadNodes(*this);
9176 DAG.ReplaceAllUsesOfValueWith(Value.getValue(1), NewLD.getValue(1));
9184 /// Helper struct to parse and store a memory address as base + index + offset.
9185 /// We ignore sign extensions when it is safe to do so.
9186 /// The following two expressions are not equivalent. To differentiate we need
9187 /// to store whether there was a sign extension involved in the index
9189 /// (load (i64 add (i64 copyfromreg %c)
9190 /// (i64 signextend (add (i8 load %index)
9194 /// (load (i64 add (i64 copyfromreg %c)
9195 /// (i64 signextend (i32 add (i32 signextend (i8 load %index))
9197 struct BaseIndexOffset {
9201 bool IsIndexSignExt;
9203 BaseIndexOffset() : Offset(0), IsIndexSignExt(false) {}
9205 BaseIndexOffset(SDValue Base, SDValue Index, int64_t Offset,
9206 bool IsIndexSignExt) :
9207 Base(Base), Index(Index), Offset(Offset), IsIndexSignExt(IsIndexSignExt) {}
9209 bool equalBaseIndex(const BaseIndexOffset &Other) {
9210 return Other.Base == Base && Other.Index == Index &&
9211 Other.IsIndexSignExt == IsIndexSignExt;
9214 /// Parses tree in Ptr for base, index, offset addresses.
9215 static BaseIndexOffset match(SDValue Ptr) {
9216 bool IsIndexSignExt = false;
9218 // We only can pattern match BASE + INDEX + OFFSET. If Ptr is not an ADD
9219 // instruction, then it could be just the BASE or everything else we don't
9220 // know how to handle. Just use Ptr as BASE and give up.
9221 if (Ptr->getOpcode() != ISD::ADD)
9222 return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
9224 // We know that we have at least an ADD instruction. Try to pattern match
9225 // the simple case of BASE + OFFSET.
9226 if (isa<ConstantSDNode>(Ptr->getOperand(1))) {
9227 int64_t Offset = cast<ConstantSDNode>(Ptr->getOperand(1))->getSExtValue();
9228 return BaseIndexOffset(Ptr->getOperand(0), SDValue(), Offset,
9232 // Inside a loop the current BASE pointer is calculated using an ADD and a
9233 // MUL instruction. In this case Ptr is the actual BASE pointer.
9234 // (i64 add (i64 %array_ptr)
9235 // (i64 mul (i64 %induction_var)
9236 // (i64 %element_size)))
9237 if (Ptr->getOperand(1)->getOpcode() == ISD::MUL)
9238 return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
9240 // Look at Base + Index + Offset cases.
9241 SDValue Base = Ptr->getOperand(0);
9242 SDValue IndexOffset = Ptr->getOperand(1);
9244 // Skip signextends.
9245 if (IndexOffset->getOpcode() == ISD::SIGN_EXTEND) {
9246 IndexOffset = IndexOffset->getOperand(0);
9247 IsIndexSignExt = true;
9250 // Either the case of Base + Index (no offset) or something else.
9251 if (IndexOffset->getOpcode() != ISD::ADD)
9252 return BaseIndexOffset(Base, IndexOffset, 0, IsIndexSignExt);
9254 // Now we have the case of Base + Index + offset.
9255 SDValue Index = IndexOffset->getOperand(0);
9256 SDValue Offset = IndexOffset->getOperand(1);
9258 if (!isa<ConstantSDNode>(Offset))
9259 return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
9261 // Ignore signextends.
9262 if (Index->getOpcode() == ISD::SIGN_EXTEND) {
9263 Index = Index->getOperand(0);
9264 IsIndexSignExt = true;
9265 } else IsIndexSignExt = false;
9267 int64_t Off = cast<ConstantSDNode>(Offset)->getSExtValue();
9268 return BaseIndexOffset(Base, Index, Off, IsIndexSignExt);
9272 /// Holds a pointer to an LSBaseSDNode as well as information on where it
9273 /// is located in a sequence of memory operations connected by a chain.
9275 MemOpLink (LSBaseSDNode *N, int64_t Offset, unsigned Seq):
9276 MemNode(N), OffsetFromBase(Offset), SequenceNum(Seq) { }
9277 // Ptr to the mem node.
9278 LSBaseSDNode *MemNode;
9279 // Offset from the base ptr.
9280 int64_t OffsetFromBase;
9281 // What is the sequence number of this mem node.
9282 // Lowest mem operand in the DAG starts at zero.
9283 unsigned SequenceNum;
9286 bool DAGCombiner::MergeConsecutiveStores(StoreSDNode* St) {
9287 EVT MemVT = St->getMemoryVT();
9288 int64_t ElementSizeBytes = MemVT.getSizeInBits()/8;
9289 bool NoVectors = DAG.getMachineFunction().getFunction()->getAttributes().
9290 hasAttribute(AttributeSet::FunctionIndex, Attribute::NoImplicitFloat);
9292 // Don't merge vectors into wider inputs.
9293 if (MemVT.isVector() || !MemVT.isSimple())
9296 // Perform an early exit check. Do not bother looking at stored values that
9297 // are not constants or loads.
9298 SDValue StoredVal = St->getValue();
9299 bool IsLoadSrc = isa<LoadSDNode>(StoredVal);
9300 if (!isa<ConstantSDNode>(StoredVal) && !isa<ConstantFPSDNode>(StoredVal) &&
9304 // Only look at ends of store sequences.
9305 SDValue Chain = SDValue(St, 0);
9306 if (Chain->hasOneUse() && Chain->use_begin()->getOpcode() == ISD::STORE)
9309 // This holds the base pointer, index, and the offset in bytes from the base
9311 BaseIndexOffset BasePtr = BaseIndexOffset::match(St->getBasePtr());
9313 // We must have a base and an offset.
9314 if (!BasePtr.Base.getNode())
9317 // Do not handle stores to undef base pointers.
9318 if (BasePtr.Base.getOpcode() == ISD::UNDEF)
9321 // Save the LoadSDNodes that we find in the chain.
9322 // We need to make sure that these nodes do not interfere with
9323 // any of the store nodes.
9324 SmallVector<LSBaseSDNode*, 8> AliasLoadNodes;
9326 // Save the StoreSDNodes that we find in the chain.
9327 SmallVector<MemOpLink, 8> StoreNodes;
9329 // Walk up the chain and look for nodes with offsets from the same
9330 // base pointer. Stop when reaching an instruction with a different kind
9331 // or instruction which has a different base pointer.
9333 StoreSDNode *Index = St;
9335 // If the chain has more than one use, then we can't reorder the mem ops.
9336 if (Index != St && !SDValue(Index, 0)->hasOneUse())
9339 // Find the base pointer and offset for this memory node.
9340 BaseIndexOffset Ptr = BaseIndexOffset::match(Index->getBasePtr());
9342 // Check that the base pointer is the same as the original one.
9343 if (!Ptr.equalBaseIndex(BasePtr))
9346 // Check that the alignment is the same.
9347 if (Index->getAlignment() != St->getAlignment())
9350 // The memory operands must not be volatile.
9351 if (Index->isVolatile() || Index->isIndexed())
9355 if (StoreSDNode *St = dyn_cast<StoreSDNode>(Index))
9356 if (St->isTruncatingStore())
9359 // The stored memory type must be the same.
9360 if (Index->getMemoryVT() != MemVT)
9363 // We do not allow unaligned stores because we want to prevent overriding
9365 if (Index->getAlignment()*8 != MemVT.getSizeInBits())
9368 // We found a potential memory operand to merge.
9369 StoreNodes.push_back(MemOpLink(Index, Ptr.Offset, Seq++));
9371 // Find the next memory operand in the chain. If the next operand in the
9372 // chain is a store then move up and continue the scan with the next
9373 // memory operand. If the next operand is a load save it and use alias
9374 // information to check if it interferes with anything.
9375 SDNode *NextInChain = Index->getChain().getNode();
9377 if (StoreSDNode *STn = dyn_cast<StoreSDNode>(NextInChain)) {
9378 // We found a store node. Use it for the next iteration.
9381 } else if (LoadSDNode *Ldn = dyn_cast<LoadSDNode>(NextInChain)) {
9382 if (Ldn->isVolatile()) {
9387 // Save the load node for later. Continue the scan.
9388 AliasLoadNodes.push_back(Ldn);
9389 NextInChain = Ldn->getChain().getNode();
9398 // Check if there is anything to merge.
9399 if (StoreNodes.size() < 2)
9402 // Sort the memory operands according to their distance from the base pointer.
9403 std::sort(StoreNodes.begin(), StoreNodes.end(),
9404 [](MemOpLink LHS, MemOpLink RHS) {
9405 return LHS.OffsetFromBase < RHS.OffsetFromBase ||
9406 (LHS.OffsetFromBase == RHS.OffsetFromBase &&
9407 LHS.SequenceNum > RHS.SequenceNum);
9410 // Scan the memory operations on the chain and find the first non-consecutive
9411 // store memory address.
9412 unsigned LastConsecutiveStore = 0;
9413 int64_t StartAddress = StoreNodes[0].OffsetFromBase;
9414 for (unsigned i = 0, e = StoreNodes.size(); i < e; ++i) {
9416 // Check that the addresses are consecutive starting from the second
9417 // element in the list of stores.
9419 int64_t CurrAddress = StoreNodes[i].OffsetFromBase;
9420 if (CurrAddress - StartAddress != (ElementSizeBytes * i))
9425 // Check if this store interferes with any of the loads that we found.
9426 for (unsigned ld = 0, lde = AliasLoadNodes.size(); ld < lde; ++ld)
9427 if (isAlias(AliasLoadNodes[ld], StoreNodes[i].MemNode)) {
9431 // We found a load that alias with this store. Stop the sequence.
9435 // Mark this node as useful.
9436 LastConsecutiveStore = i;
9439 // The node with the lowest store address.
9440 LSBaseSDNode *FirstInChain = StoreNodes[0].MemNode;
9442 // Store the constants into memory as one consecutive store.
9444 unsigned LastLegalType = 0;
9445 unsigned LastLegalVectorType = 0;
9446 bool NonZero = false;
9447 for (unsigned i=0; i<LastConsecutiveStore+1; ++i) {
9448 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
9449 SDValue StoredVal = St->getValue();
9451 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(StoredVal)) {
9452 NonZero |= !C->isNullValue();
9453 } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(StoredVal)) {
9454 NonZero |= !C->getConstantFPValue()->isNullValue();
9460 // Find a legal type for the constant store.
9461 unsigned StoreBW = (i+1) * ElementSizeBytes * 8;
9462 EVT StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
9463 if (TLI.isTypeLegal(StoreTy))
9464 LastLegalType = i+1;
9465 // Or check whether a truncstore is legal.
9466 else if (TLI.getTypeAction(*DAG.getContext(), StoreTy) ==
9467 TargetLowering::TypePromoteInteger) {
9468 EVT LegalizedStoredValueTy =
9469 TLI.getTypeToTransformTo(*DAG.getContext(), StoredVal.getValueType());
9470 if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy))
9471 LastLegalType = i+1;
9474 // Find a legal type for the vector store.
9475 EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT, i+1);
9476 if (TLI.isTypeLegal(Ty))
9477 LastLegalVectorType = i + 1;
9480 // We only use vectors if the constant is known to be zero and the
9481 // function is not marked with the noimplicitfloat attribute.
9482 if (NonZero || NoVectors)
9483 LastLegalVectorType = 0;
9485 // Check if we found a legal integer type to store.
9486 if (LastLegalType == 0 && LastLegalVectorType == 0)
9489 bool UseVector = (LastLegalVectorType > LastLegalType) && !NoVectors;
9490 unsigned NumElem = UseVector ? LastLegalVectorType : LastLegalType;
9492 // Make sure we have something to merge.
9496 unsigned EarliestNodeUsed = 0;
9497 for (unsigned i=0; i < NumElem; ++i) {
9498 // Find a chain for the new wide-store operand. Notice that some
9499 // of the store nodes that we found may not be selected for inclusion
9500 // in the wide store. The chain we use needs to be the chain of the
9501 // earliest store node which is *used* and replaced by the wide store.
9502 if (StoreNodes[i].SequenceNum > StoreNodes[EarliestNodeUsed].SequenceNum)
9503 EarliestNodeUsed = i;
9506 // The earliest Node in the DAG.
9507 LSBaseSDNode *EarliestOp = StoreNodes[EarliestNodeUsed].MemNode;
9508 SDLoc DL(StoreNodes[0].MemNode);
9512 // Find a legal type for the vector store.
9513 EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT, NumElem);
9514 assert(TLI.isTypeLegal(Ty) && "Illegal vector store");
9515 StoredVal = DAG.getConstant(0, Ty);
9517 unsigned StoreBW = NumElem * ElementSizeBytes * 8;
9518 APInt StoreInt(StoreBW, 0);
9520 // Construct a single integer constant which is made of the smaller
9522 bool IsLE = TLI.isLittleEndian();
9523 for (unsigned i = 0; i < NumElem ; ++i) {
9524 unsigned Idx = IsLE ?(NumElem - 1 - i) : i;
9525 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[Idx].MemNode);
9526 SDValue Val = St->getValue();
9527 StoreInt<<=ElementSizeBytes*8;
9528 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Val)) {
9529 StoreInt|=C->getAPIntValue().zext(StoreBW);
9530 } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Val)) {
9531 StoreInt|= C->getValueAPF().bitcastToAPInt().zext(StoreBW);
9533 assert(false && "Invalid constant element type");
9537 // Create the new Load and Store operations.
9538 EVT StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
9539 StoredVal = DAG.getConstant(StoreInt, StoreTy);
9542 SDValue NewStore = DAG.getStore(EarliestOp->getChain(), DL, StoredVal,
9543 FirstInChain->getBasePtr(),
9544 FirstInChain->getPointerInfo(),
9546 FirstInChain->getAlignment());
9548 // Replace the first store with the new store
9549 CombineTo(EarliestOp, NewStore);
9550 // Erase all other stores.
9551 for (unsigned i = 0; i < NumElem ; ++i) {
9552 if (StoreNodes[i].MemNode == EarliestOp)
9554 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
9555 // ReplaceAllUsesWith will replace all uses that existed when it was
9556 // called, but graph optimizations may cause new ones to appear. For
9557 // example, the case in pr14333 looks like
9559 // St's chain -> St -> another store -> X
9561 // And the only difference from St to the other store is the chain.
9562 // When we change it's chain to be St's chain they become identical,
9563 // get CSEed and the net result is that X is now a use of St.
9564 // Since we know that St is redundant, just iterate.
9565 while (!St->use_empty())
9566 DAG.ReplaceAllUsesWith(SDValue(St, 0), St->getChain());
9567 deleteAndRecombine(St);
9573 // Below we handle the case of multiple consecutive stores that
9574 // come from multiple consecutive loads. We merge them into a single
9575 // wide load and a single wide store.
9577 // Look for load nodes which are used by the stored values.
9578 SmallVector<MemOpLink, 8> LoadNodes;
9580 // Find acceptable loads. Loads need to have the same chain (token factor),
9581 // must not be zext, volatile, indexed, and they must be consecutive.
9582 BaseIndexOffset LdBasePtr;
9583 for (unsigned i=0; i<LastConsecutiveStore+1; ++i) {
9584 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
9585 LoadSDNode *Ld = dyn_cast<LoadSDNode>(St->getValue());
9588 // Loads must only have one use.
9589 if (!Ld->hasNUsesOfValue(1, 0))
9592 // Check that the alignment is the same as the stores.
9593 if (Ld->getAlignment() != St->getAlignment())
9596 // The memory operands must not be volatile.
9597 if (Ld->isVolatile() || Ld->isIndexed())
9600 // We do not accept ext loads.
9601 if (Ld->getExtensionType() != ISD::NON_EXTLOAD)
9604 // The stored memory type must be the same.
9605 if (Ld->getMemoryVT() != MemVT)
9608 BaseIndexOffset LdPtr = BaseIndexOffset::match(Ld->getBasePtr());
9609 // If this is not the first ptr that we check.
9610 if (LdBasePtr.Base.getNode()) {
9611 // The base ptr must be the same.
9612 if (!LdPtr.equalBaseIndex(LdBasePtr))
9615 // Check that all other base pointers are the same as this one.
9619 // We found a potential memory operand to merge.
9620 LoadNodes.push_back(MemOpLink(Ld, LdPtr.Offset, 0));
9623 if (LoadNodes.size() < 2)
9626 // If we have load/store pair instructions and we only have two values,
9628 unsigned RequiredAlignment;
9629 if (LoadNodes.size() == 2 && TLI.hasPairedLoad(MemVT, RequiredAlignment) &&
9630 St->getAlignment() >= RequiredAlignment)
9633 // Scan the memory operations on the chain and find the first non-consecutive
9634 // load memory address. These variables hold the index in the store node
9636 unsigned LastConsecutiveLoad = 0;
9637 // This variable refers to the size and not index in the array.
9638 unsigned LastLegalVectorType = 0;
9639 unsigned LastLegalIntegerType = 0;
9640 StartAddress = LoadNodes[0].OffsetFromBase;
9641 SDValue FirstChain = LoadNodes[0].MemNode->getChain();
9642 for (unsigned i = 1; i < LoadNodes.size(); ++i) {
9643 // All loads much share the same chain.
9644 if (LoadNodes[i].MemNode->getChain() != FirstChain)
9647 int64_t CurrAddress = LoadNodes[i].OffsetFromBase;
9648 if (CurrAddress - StartAddress != (ElementSizeBytes * i))
9650 LastConsecutiveLoad = i;
9652 // Find a legal type for the vector store.
9653 EVT StoreTy = EVT::getVectorVT(*DAG.getContext(), MemVT, i+1);
9654 if (TLI.isTypeLegal(StoreTy))
9655 LastLegalVectorType = i + 1;
9657 // Find a legal type for the integer store.
9658 unsigned StoreBW = (i+1) * ElementSizeBytes * 8;
9659 StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
9660 if (TLI.isTypeLegal(StoreTy))
9661 LastLegalIntegerType = i + 1;
9662 // Or check whether a truncstore and extload is legal.
9663 else if (TLI.getTypeAction(*DAG.getContext(), StoreTy) ==
9664 TargetLowering::TypePromoteInteger) {
9665 EVT LegalizedStoredValueTy =
9666 TLI.getTypeToTransformTo(*DAG.getContext(), StoreTy);
9667 if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy) &&
9668 TLI.isLoadExtLegal(ISD::ZEXTLOAD, StoreTy) &&
9669 TLI.isLoadExtLegal(ISD::SEXTLOAD, StoreTy) &&
9670 TLI.isLoadExtLegal(ISD::EXTLOAD, StoreTy))
9671 LastLegalIntegerType = i+1;
9675 // Only use vector types if the vector type is larger than the integer type.
9676 // If they are the same, use integers.
9677 bool UseVectorTy = LastLegalVectorType > LastLegalIntegerType && !NoVectors;
9678 unsigned LastLegalType = std::max(LastLegalVectorType, LastLegalIntegerType);
9680 // We add +1 here because the LastXXX variables refer to location while
9681 // the NumElem refers to array/index size.
9682 unsigned NumElem = std::min(LastConsecutiveStore, LastConsecutiveLoad) + 1;
9683 NumElem = std::min(LastLegalType, NumElem);
9688 // The earliest Node in the DAG.
9689 unsigned EarliestNodeUsed = 0;
9690 LSBaseSDNode *EarliestOp = StoreNodes[EarliestNodeUsed].MemNode;
9691 for (unsigned i=1; i<NumElem; ++i) {
9692 // Find a chain for the new wide-store operand. Notice that some
9693 // of the store nodes that we found may not be selected for inclusion
9694 // in the wide store. The chain we use needs to be the chain of the
9695 // earliest store node which is *used* and replaced by the wide store.
9696 if (StoreNodes[i].SequenceNum > StoreNodes[EarliestNodeUsed].SequenceNum)
9697 EarliestNodeUsed = i;
9700 // Find if it is better to use vectors or integers to load and store
9704 JointMemOpVT = EVT::getVectorVT(*DAG.getContext(), MemVT, NumElem);
9706 unsigned StoreBW = NumElem * ElementSizeBytes * 8;
9707 JointMemOpVT = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
9710 SDLoc LoadDL(LoadNodes[0].MemNode);
9711 SDLoc StoreDL(StoreNodes[0].MemNode);
9713 LoadSDNode *FirstLoad = cast<LoadSDNode>(LoadNodes[0].MemNode);
9714 SDValue NewLoad = DAG.getLoad(JointMemOpVT, LoadDL,
9715 FirstLoad->getChain(),
9716 FirstLoad->getBasePtr(),
9717 FirstLoad->getPointerInfo(),
9718 false, false, false,
9719 FirstLoad->getAlignment());
9721 SDValue NewStore = DAG.getStore(EarliestOp->getChain(), StoreDL, NewLoad,
9722 FirstInChain->getBasePtr(),
9723 FirstInChain->getPointerInfo(), false, false,
9724 FirstInChain->getAlignment());
9726 // Replace one of the loads with the new load.
9727 LoadSDNode *Ld = cast<LoadSDNode>(LoadNodes[0].MemNode);
9728 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1),
9729 SDValue(NewLoad.getNode(), 1));
9731 // Remove the rest of the load chains.
9732 for (unsigned i = 1; i < NumElem ; ++i) {
9733 // Replace all chain users of the old load nodes with the chain of the new
9735 LoadSDNode *Ld = cast<LoadSDNode>(LoadNodes[i].MemNode);
9736 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), Ld->getChain());
9739 // Replace the first store with the new store.
9740 CombineTo(EarliestOp, NewStore);
9741 // Erase all other stores.
9742 for (unsigned i = 0; i < NumElem ; ++i) {
9743 // Remove all Store nodes.
9744 if (StoreNodes[i].MemNode == EarliestOp)
9746 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
9747 DAG.ReplaceAllUsesOfValueWith(SDValue(St, 0), St->getChain());
9748 deleteAndRecombine(St);
9754 SDValue DAGCombiner::visitSTORE(SDNode *N) {
9755 StoreSDNode *ST = cast<StoreSDNode>(N);
9756 SDValue Chain = ST->getChain();
9757 SDValue Value = ST->getValue();
9758 SDValue Ptr = ST->getBasePtr();
9760 // If this is a store of a bit convert, store the input value if the
9761 // resultant store does not need a higher alignment than the original.
9762 if (Value.getOpcode() == ISD::BITCAST && !ST->isTruncatingStore() &&
9763 ST->isUnindexed()) {
9764 unsigned OrigAlign = ST->getAlignment();
9765 EVT SVT = Value.getOperand(0).getValueType();
9766 unsigned Align = TLI.getDataLayout()->
9767 getABITypeAlignment(SVT.getTypeForEVT(*DAG.getContext()));
9768 if (Align <= OrigAlign &&
9769 ((!LegalOperations && !ST->isVolatile()) ||
9770 TLI.isOperationLegalOrCustom(ISD::STORE, SVT)))
9771 return DAG.getStore(Chain, SDLoc(N), Value.getOperand(0),
9772 Ptr, ST->getPointerInfo(), ST->isVolatile(),
9773 ST->isNonTemporal(), OrigAlign,
9777 // Turn 'store undef, Ptr' -> nothing.
9778 if (Value.getOpcode() == ISD::UNDEF && ST->isUnindexed())
9781 // Turn 'store float 1.0, Ptr' -> 'store int 0x12345678, Ptr'
9782 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Value)) {
9783 // NOTE: If the original store is volatile, this transform must not increase
9784 // the number of stores. For example, on x86-32 an f64 can be stored in one
9785 // processor operation but an i64 (which is not legal) requires two. So the
9786 // transform should not be done in this case.
9787 if (Value.getOpcode() != ISD::TargetConstantFP) {
9789 switch (CFP->getSimpleValueType(0).SimpleTy) {
9790 default: llvm_unreachable("Unknown FP type");
9791 case MVT::f16: // We don't do this for these yet.
9797 if ((isTypeLegal(MVT::i32) && !LegalOperations && !ST->isVolatile()) ||
9798 TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) {
9799 Tmp = DAG.getConstant((uint32_t)CFP->getValueAPF().
9800 bitcastToAPInt().getZExtValue(), MVT::i32);
9801 return DAG.getStore(Chain, SDLoc(N), Tmp,
9802 Ptr, ST->getMemOperand());
9806 if ((TLI.isTypeLegal(MVT::i64) && !LegalOperations &&
9807 !ST->isVolatile()) ||
9808 TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i64)) {
9809 Tmp = DAG.getConstant(CFP->getValueAPF().bitcastToAPInt().
9810 getZExtValue(), MVT::i64);
9811 return DAG.getStore(Chain, SDLoc(N), Tmp,
9812 Ptr, ST->getMemOperand());
9815 if (!ST->isVolatile() &&
9816 TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) {
9817 // Many FP stores are not made apparent until after legalize, e.g. for
9818 // argument passing. Since this is so common, custom legalize the
9819 // 64-bit integer store into two 32-bit stores.
9820 uint64_t Val = CFP->getValueAPF().bitcastToAPInt().getZExtValue();
9821 SDValue Lo = DAG.getConstant(Val & 0xFFFFFFFF, MVT::i32);
9822 SDValue Hi = DAG.getConstant(Val >> 32, MVT::i32);
9823 if (TLI.isBigEndian()) std::swap(Lo, Hi);
9825 unsigned Alignment = ST->getAlignment();
9826 bool isVolatile = ST->isVolatile();
9827 bool isNonTemporal = ST->isNonTemporal();
9828 AAMDNodes AAInfo = ST->getAAInfo();
9830 SDValue St0 = DAG.getStore(Chain, SDLoc(ST), Lo,
9831 Ptr, ST->getPointerInfo(),
9832 isVolatile, isNonTemporal,
9833 ST->getAlignment(), AAInfo);
9834 Ptr = DAG.getNode(ISD::ADD, SDLoc(N), Ptr.getValueType(), Ptr,
9835 DAG.getConstant(4, Ptr.getValueType()));
9836 Alignment = MinAlign(Alignment, 4U);
9837 SDValue St1 = DAG.getStore(Chain, SDLoc(ST), Hi,
9838 Ptr, ST->getPointerInfo().getWithOffset(4),
9839 isVolatile, isNonTemporal,
9841 return DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other,
9850 // Try to infer better alignment information than the store already has.
9851 if (OptLevel != CodeGenOpt::None && ST->isUnindexed()) {
9852 if (unsigned Align = DAG.InferPtrAlignment(Ptr)) {
9853 if (Align > ST->getAlignment())
9854 return DAG.getTruncStore(Chain, SDLoc(N), Value,
9855 Ptr, ST->getPointerInfo(), ST->getMemoryVT(),
9856 ST->isVolatile(), ST->isNonTemporal(), Align,
9861 // Try transforming a pair floating point load / store ops to integer
9862 // load / store ops.
9863 SDValue NewST = TransformFPLoadStorePair(N);
9864 if (NewST.getNode())
9867 bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA
9868 : DAG.getSubtarget().useAA();
9870 if (CombinerAAOnlyFunc.getNumOccurrences() &&
9871 CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
9874 if (UseAA && ST->isUnindexed()) {
9875 // Walk up chain skipping non-aliasing memory nodes.
9876 SDValue BetterChain = FindBetterChain(N, Chain);
9878 // If there is a better chain.
9879 if (Chain != BetterChain) {
9882 // Replace the chain to avoid dependency.
9883 if (ST->isTruncatingStore()) {
9884 ReplStore = DAG.getTruncStore(BetterChain, SDLoc(N), Value, Ptr,
9885 ST->getMemoryVT(), ST->getMemOperand());
9887 ReplStore = DAG.getStore(BetterChain, SDLoc(N), Value, Ptr,
9888 ST->getMemOperand());
9891 // Create token to keep both nodes around.
9892 SDValue Token = DAG.getNode(ISD::TokenFactor, SDLoc(N),
9893 MVT::Other, Chain, ReplStore);
9895 // Make sure the new and old chains are cleaned up.
9896 AddToWorklist(Token.getNode());
9898 // Don't add users to work list.
9899 return CombineTo(N, Token, false);
9903 // Try transforming N to an indexed store.
9904 if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
9905 return SDValue(N, 0);
9907 // FIXME: is there such a thing as a truncating indexed store?
9908 if (ST->isTruncatingStore() && ST->isUnindexed() &&
9909 Value.getValueType().isInteger()) {
9910 // See if we can simplify the input to this truncstore with knowledge that
9911 // only the low bits are being used. For example:
9912 // "truncstore (or (shl x, 8), y), i8" -> "truncstore y, i8"
9914 GetDemandedBits(Value,
9915 APInt::getLowBitsSet(
9916 Value.getValueType().getScalarType().getSizeInBits(),
9917 ST->getMemoryVT().getScalarType().getSizeInBits()));
9918 AddToWorklist(Value.getNode());
9919 if (Shorter.getNode())
9920 return DAG.getTruncStore(Chain, SDLoc(N), Shorter,
9921 Ptr, ST->getMemoryVT(), ST->getMemOperand());
9923 // Otherwise, see if we can simplify the operation with
9924 // SimplifyDemandedBits, which only works if the value has a single use.
9925 if (SimplifyDemandedBits(Value,
9926 APInt::getLowBitsSet(
9927 Value.getValueType().getScalarType().getSizeInBits(),
9928 ST->getMemoryVT().getScalarType().getSizeInBits())))
9929 return SDValue(N, 0);
9932 // If this is a load followed by a store to the same location, then the store
9934 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Value)) {
9935 if (Ld->getBasePtr() == Ptr && ST->getMemoryVT() == Ld->getMemoryVT() &&
9936 ST->isUnindexed() && !ST->isVolatile() &&
9937 // There can't be any side effects between the load and store, such as
9939 Chain.reachesChainWithoutSideEffects(SDValue(Ld, 1))) {
9940 // The store is dead, remove it.
9945 // If this is a store followed by a store with the same value to the same
9946 // location, then the store is dead/noop.
9947 if (StoreSDNode *ST1 = dyn_cast<StoreSDNode>(Chain)) {
9948 if (ST1->getBasePtr() == Ptr && ST->getMemoryVT() == ST1->getMemoryVT() &&
9949 ST1->getValue() == Value && ST->isUnindexed() && !ST->isVolatile() &&
9950 ST1->isUnindexed() && !ST1->isVolatile()) {
9951 // The store is dead, remove it.
9956 // If this is an FP_ROUND or TRUNC followed by a store, fold this into a
9957 // truncating store. We can do this even if this is already a truncstore.
9958 if ((Value.getOpcode() == ISD::FP_ROUND || Value.getOpcode() == ISD::TRUNCATE)
9959 && Value.getNode()->hasOneUse() && ST->isUnindexed() &&
9960 TLI.isTruncStoreLegal(Value.getOperand(0).getValueType(),
9961 ST->getMemoryVT())) {
9962 return DAG.getTruncStore(Chain, SDLoc(N), Value.getOperand(0),
9963 Ptr, ST->getMemoryVT(), ST->getMemOperand());
9966 // Only perform this optimization before the types are legal, because we
9967 // don't want to perform this optimization on every DAGCombine invocation.
9969 bool EverChanged = false;
9972 // There can be multiple store sequences on the same chain.
9973 // Keep trying to merge store sequences until we are unable to do so
9974 // or until we merge the last store on the chain.
9975 bool Changed = MergeConsecutiveStores(ST);
9976 EverChanged |= Changed;
9977 if (!Changed) break;
9978 } while (ST->getOpcode() != ISD::DELETED_NODE);
9981 return SDValue(N, 0);
9984 return ReduceLoadOpStoreWidth(N);
9987 SDValue DAGCombiner::visitINSERT_VECTOR_ELT(SDNode *N) {
9988 SDValue InVec = N->getOperand(0);
9989 SDValue InVal = N->getOperand(1);
9990 SDValue EltNo = N->getOperand(2);
9993 // If the inserted element is an UNDEF, just use the input vector.
9994 if (InVal.getOpcode() == ISD::UNDEF)
9997 EVT VT = InVec.getValueType();
9999 // If we can't generate a legal BUILD_VECTOR, exit
10000 if (LegalOperations && !TLI.isOperationLegal(ISD::BUILD_VECTOR, VT))
10003 // Check that we know which element is being inserted
10004 if (!isa<ConstantSDNode>(EltNo))
10006 unsigned Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
10008 // Canonicalize insert_vector_elt dag nodes.
10010 // (insert_vector_elt (insert_vector_elt A, Idx0), Idx1)
10011 // -> (insert_vector_elt (insert_vector_elt A, Idx1), Idx0)
10013 // Do this only if the child insert_vector node has one use; also
10014 // do this only if indices are both constants and Idx1 < Idx0.
10015 if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT && InVec.hasOneUse()
10016 && isa<ConstantSDNode>(InVec.getOperand(2))) {
10017 unsigned OtherElt =
10018 cast<ConstantSDNode>(InVec.getOperand(2))->getZExtValue();
10019 if (Elt < OtherElt) {
10021 SDValue NewOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, SDLoc(N), VT,
10022 InVec.getOperand(0), InVal, EltNo);
10023 AddToWorklist(NewOp.getNode());
10024 return DAG.getNode(ISD::INSERT_VECTOR_ELT, SDLoc(InVec.getNode()),
10025 VT, NewOp, InVec.getOperand(1), InVec.getOperand(2));
10029 // Check that the operand is a BUILD_VECTOR (or UNDEF, which can essentially
10030 // be converted to a BUILD_VECTOR). Fill in the Ops vector with the
10031 // vector elements.
10032 SmallVector<SDValue, 8> Ops;
10033 // Do not combine these two vectors if the output vector will not replace
10034 // the input vector.
10035 if (InVec.getOpcode() == ISD::BUILD_VECTOR && InVec.hasOneUse()) {
10036 Ops.append(InVec.getNode()->op_begin(),
10037 InVec.getNode()->op_end());
10038 } else if (InVec.getOpcode() == ISD::UNDEF) {
10039 unsigned NElts = VT.getVectorNumElements();
10040 Ops.append(NElts, DAG.getUNDEF(InVal.getValueType()));
10045 // Insert the element
10046 if (Elt < Ops.size()) {
10047 // All the operands of BUILD_VECTOR must have the same type;
10048 // we enforce that here.
10049 EVT OpVT = Ops[0].getValueType();
10050 if (InVal.getValueType() != OpVT)
10051 InVal = OpVT.bitsGT(InVal.getValueType()) ?
10052 DAG.getNode(ISD::ANY_EXTEND, dl, OpVT, InVal) :
10053 DAG.getNode(ISD::TRUNCATE, dl, OpVT, InVal);
10057 // Return the new vector
10058 return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
10061 SDValue DAGCombiner::ReplaceExtractVectorEltOfLoadWithNarrowedLoad(
10062 SDNode *EVE, EVT InVecVT, SDValue EltNo, LoadSDNode *OriginalLoad) {
10063 EVT ResultVT = EVE->getValueType(0);
10064 EVT VecEltVT = InVecVT.getVectorElementType();
10065 unsigned Align = OriginalLoad->getAlignment();
10066 unsigned NewAlign = TLI.getDataLayout()->getABITypeAlignment(
10067 VecEltVT.getTypeForEVT(*DAG.getContext()));
10069 if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, VecEltVT))
10074 SDValue NewPtr = OriginalLoad->getBasePtr();
10076 EVT PtrType = NewPtr.getValueType();
10077 MachinePointerInfo MPI;
10078 if (auto *ConstEltNo = dyn_cast<ConstantSDNode>(EltNo)) {
10079 int Elt = ConstEltNo->getZExtValue();
10080 unsigned PtrOff = VecEltVT.getSizeInBits() * Elt / 8;
10081 if (TLI.isBigEndian())
10082 PtrOff = InVecVT.getSizeInBits() / 8 - PtrOff;
10083 Offset = DAG.getConstant(PtrOff, PtrType);
10084 MPI = OriginalLoad->getPointerInfo().getWithOffset(PtrOff);
10086 Offset = DAG.getNode(
10087 ISD::MUL, SDLoc(EVE), EltNo.getValueType(), EltNo,
10088 DAG.getConstant(VecEltVT.getStoreSize(), EltNo.getValueType()));
10089 if (TLI.isBigEndian())
10090 Offset = DAG.getNode(
10091 ISD::SUB, SDLoc(EVE), EltNo.getValueType(),
10092 DAG.getConstant(InVecVT.getStoreSize(), EltNo.getValueType()), Offset);
10093 MPI = OriginalLoad->getPointerInfo();
10095 NewPtr = DAG.getNode(ISD::ADD, SDLoc(EVE), PtrType, NewPtr, Offset);
10097 // The replacement we need to do here is a little tricky: we need to
10098 // replace an extractelement of a load with a load.
10099 // Use ReplaceAllUsesOfValuesWith to do the replacement.
10100 // Note that this replacement assumes that the extractvalue is the only
10101 // use of the load; that's okay because we don't want to perform this
10102 // transformation in other cases anyway.
10105 if (ResultVT.bitsGT(VecEltVT)) {
10106 // If the result type of vextract is wider than the load, then issue an
10107 // extending load instead.
10108 ISD::LoadExtType ExtType = TLI.isLoadExtLegal(ISD::ZEXTLOAD, VecEltVT)
10111 Load = DAG.getExtLoad(
10112 ExtType, SDLoc(EVE), ResultVT, OriginalLoad->getChain(), NewPtr, MPI,
10113 VecEltVT, OriginalLoad->isVolatile(), OriginalLoad->isNonTemporal(),
10114 OriginalLoad->isInvariant(), Align, OriginalLoad->getAAInfo());
10115 Chain = Load.getValue(1);
10117 Load = DAG.getLoad(
10118 VecEltVT, SDLoc(EVE), OriginalLoad->getChain(), NewPtr, MPI,
10119 OriginalLoad->isVolatile(), OriginalLoad->isNonTemporal(),
10120 OriginalLoad->isInvariant(), Align, OriginalLoad->getAAInfo());
10121 Chain = Load.getValue(1);
10122 if (ResultVT.bitsLT(VecEltVT))
10123 Load = DAG.getNode(ISD::TRUNCATE, SDLoc(EVE), ResultVT, Load);
10125 Load = DAG.getNode(ISD::BITCAST, SDLoc(EVE), ResultVT, Load);
10127 WorklistRemover DeadNodes(*this);
10128 SDValue From[] = { SDValue(EVE, 0), SDValue(OriginalLoad, 1) };
10129 SDValue To[] = { Load, Chain };
10130 DAG.ReplaceAllUsesOfValuesWith(From, To, 2);
10131 // Since we're explicitly calling ReplaceAllUses, add the new node to the
10132 // worklist explicitly as well.
10133 AddToWorklist(Load.getNode());
10134 AddUsersToWorklist(Load.getNode()); // Add users too
10135 // Make sure to revisit this node to clean it up; it will usually be dead.
10136 AddToWorklist(EVE);
10138 return SDValue(EVE, 0);
10141 SDValue DAGCombiner::visitEXTRACT_VECTOR_ELT(SDNode *N) {
10142 // (vextract (scalar_to_vector val, 0) -> val
10143 SDValue InVec = N->getOperand(0);
10144 EVT VT = InVec.getValueType();
10145 EVT NVT = N->getValueType(0);
10147 if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR) {
10148 // Check if the result type doesn't match the inserted element type. A
10149 // SCALAR_TO_VECTOR may truncate the inserted element and the
10150 // EXTRACT_VECTOR_ELT may widen the extracted vector.
10151 SDValue InOp = InVec.getOperand(0);
10152 if (InOp.getValueType() != NVT) {
10153 assert(InOp.getValueType().isInteger() && NVT.isInteger());
10154 return DAG.getSExtOrTrunc(InOp, SDLoc(InVec), NVT);
10159 SDValue EltNo = N->getOperand(1);
10160 bool ConstEltNo = isa<ConstantSDNode>(EltNo);
10162 // Transform: (EXTRACT_VECTOR_ELT( VECTOR_SHUFFLE )) -> EXTRACT_VECTOR_ELT.
10163 // We only perform this optimization before the op legalization phase because
10164 // we may introduce new vector instructions which are not backed by TD
10165 // patterns. For example on AVX, extracting elements from a wide vector
10166 // without using extract_subvector. However, if we can find an underlying
10167 // scalar value, then we can always use that.
10168 if (InVec.getOpcode() == ISD::VECTOR_SHUFFLE
10170 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
10171 int NumElem = VT.getVectorNumElements();
10172 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(InVec);
10173 // Find the new index to extract from.
10174 int OrigElt = SVOp->getMaskElt(Elt);
10176 // Extracting an undef index is undef.
10178 return DAG.getUNDEF(NVT);
10180 // Select the right vector half to extract from.
10182 if (OrigElt < NumElem) {
10183 SVInVec = InVec->getOperand(0);
10185 SVInVec = InVec->getOperand(1);
10186 OrigElt -= NumElem;
10189 if (SVInVec.getOpcode() == ISD::BUILD_VECTOR) {
10190 SDValue InOp = SVInVec.getOperand(OrigElt);
10191 if (InOp.getValueType() != NVT) {
10192 assert(InOp.getValueType().isInteger() && NVT.isInteger());
10193 InOp = DAG.getSExtOrTrunc(InOp, SDLoc(SVInVec), NVT);
10199 // FIXME: We should handle recursing on other vector shuffles and
10200 // scalar_to_vector here as well.
10202 if (!LegalOperations) {
10203 EVT IndexTy = TLI.getVectorIdxTy();
10204 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SDLoc(N), NVT,
10205 SVInVec, DAG.getConstant(OrigElt, IndexTy));
10209 bool BCNumEltsChanged = false;
10210 EVT ExtVT = VT.getVectorElementType();
10213 // If the result of load has to be truncated, then it's not necessarily
10215 if (NVT.bitsLT(LVT) && !TLI.isTruncateFree(LVT, NVT))
10218 if (InVec.getOpcode() == ISD::BITCAST) {
10219 // Don't duplicate a load with other uses.
10220 if (!InVec.hasOneUse())
10223 EVT BCVT = InVec.getOperand(0).getValueType();
10224 if (!BCVT.isVector() || ExtVT.bitsGT(BCVT.getVectorElementType()))
10226 if (VT.getVectorNumElements() != BCVT.getVectorNumElements())
10227 BCNumEltsChanged = true;
10228 InVec = InVec.getOperand(0);
10229 ExtVT = BCVT.getVectorElementType();
10232 // (vextract (vN[if]M load $addr), i) -> ([if]M load $addr + i * size)
10233 if (!LegalOperations && !ConstEltNo && InVec.hasOneUse() &&
10234 ISD::isNormalLoad(InVec.getNode()) &&
10235 !N->getOperand(1)->hasPredecessor(InVec.getNode())) {
10236 SDValue Index = N->getOperand(1);
10237 if (LoadSDNode *OrigLoad = dyn_cast<LoadSDNode>(InVec))
10238 return ReplaceExtractVectorEltOfLoadWithNarrowedLoad(N, VT, Index,
10242 // Perform only after legalization to ensure build_vector / vector_shuffle
10243 // optimizations have already been done.
10244 if (!LegalOperations) return SDValue();
10246 // (vextract (v4f32 load $addr), c) -> (f32 load $addr+c*size)
10247 // (vextract (v4f32 s2v (f32 load $addr)), c) -> (f32 load $addr+c*size)
10248 // (vextract (v4f32 shuffle (load $addr), <1,u,u,u>), 0) -> (f32 load $addr)
10251 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
10253 LoadSDNode *LN0 = nullptr;
10254 const ShuffleVectorSDNode *SVN = nullptr;
10255 if (ISD::isNormalLoad(InVec.getNode())) {
10256 LN0 = cast<LoadSDNode>(InVec);
10257 } else if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR &&
10258 InVec.getOperand(0).getValueType() == ExtVT &&
10259 ISD::isNormalLoad(InVec.getOperand(0).getNode())) {
10260 // Don't duplicate a load with other uses.
10261 if (!InVec.hasOneUse())
10264 LN0 = cast<LoadSDNode>(InVec.getOperand(0));
10265 } else if ((SVN = dyn_cast<ShuffleVectorSDNode>(InVec))) {
10266 // (vextract (vector_shuffle (load $addr), v2, <1, u, u, u>), 1)
10268 // (load $addr+1*size)
10270 // Don't duplicate a load with other uses.
10271 if (!InVec.hasOneUse())
10274 // If the bit convert changed the number of elements, it is unsafe
10275 // to examine the mask.
10276 if (BCNumEltsChanged)
10279 // Select the input vector, guarding against out of range extract vector.
10280 unsigned NumElems = VT.getVectorNumElements();
10281 int Idx = (Elt > (int)NumElems) ? -1 : SVN->getMaskElt(Elt);
10282 InVec = (Idx < (int)NumElems) ? InVec.getOperand(0) : InVec.getOperand(1);
10284 if (InVec.getOpcode() == ISD::BITCAST) {
10285 // Don't duplicate a load with other uses.
10286 if (!InVec.hasOneUse())
10289 InVec = InVec.getOperand(0);
10291 if (ISD::isNormalLoad(InVec.getNode())) {
10292 LN0 = cast<LoadSDNode>(InVec);
10293 Elt = (Idx < (int)NumElems) ? Idx : Idx - (int)NumElems;
10294 EltNo = DAG.getConstant(Elt, EltNo.getValueType());
10298 // Make sure we found a non-volatile load and the extractelement is
10300 if (!LN0 || !LN0->hasNUsesOfValue(1,0) || LN0->isVolatile())
10303 // If Idx was -1 above, Elt is going to be -1, so just return undef.
10305 return DAG.getUNDEF(LVT);
10307 return ReplaceExtractVectorEltOfLoadWithNarrowedLoad(N, VT, EltNo, LN0);
10313 // Simplify (build_vec (ext )) to (bitcast (build_vec ))
10314 SDValue DAGCombiner::reduceBuildVecExtToExtBuildVec(SDNode *N) {
10315 // We perform this optimization post type-legalization because
10316 // the type-legalizer often scalarizes integer-promoted vectors.
10317 // Performing this optimization before may create bit-casts which
10318 // will be type-legalized to complex code sequences.
10319 // We perform this optimization only before the operation legalizer because we
10320 // may introduce illegal operations.
10321 if (Level != AfterLegalizeVectorOps && Level != AfterLegalizeTypes)
10324 unsigned NumInScalars = N->getNumOperands();
10326 EVT VT = N->getValueType(0);
10328 // Check to see if this is a BUILD_VECTOR of a bunch of values
10329 // which come from any_extend or zero_extend nodes. If so, we can create
10330 // a new BUILD_VECTOR using bit-casts which may enable other BUILD_VECTOR
10331 // optimizations. We do not handle sign-extend because we can't fill the sign
10333 EVT SourceType = MVT::Other;
10334 bool AllAnyExt = true;
10336 for (unsigned i = 0; i != NumInScalars; ++i) {
10337 SDValue In = N->getOperand(i);
10338 // Ignore undef inputs.
10339 if (In.getOpcode() == ISD::UNDEF) continue;
10341 bool AnyExt = In.getOpcode() == ISD::ANY_EXTEND;
10342 bool ZeroExt = In.getOpcode() == ISD::ZERO_EXTEND;
10344 // Abort if the element is not an extension.
10345 if (!ZeroExt && !AnyExt) {
10346 SourceType = MVT::Other;
10350 // The input is a ZeroExt or AnyExt. Check the original type.
10351 EVT InTy = In.getOperand(0).getValueType();
10353 // Check that all of the widened source types are the same.
10354 if (SourceType == MVT::Other)
10357 else if (InTy != SourceType) {
10358 // Multiple income types. Abort.
10359 SourceType = MVT::Other;
10363 // Check if all of the extends are ANY_EXTENDs.
10364 AllAnyExt &= AnyExt;
10367 // In order to have valid types, all of the inputs must be extended from the
10368 // same source type and all of the inputs must be any or zero extend.
10369 // Scalar sizes must be a power of two.
10370 EVT OutScalarTy = VT.getScalarType();
10371 bool ValidTypes = SourceType != MVT::Other &&
10372 isPowerOf2_32(OutScalarTy.getSizeInBits()) &&
10373 isPowerOf2_32(SourceType.getSizeInBits());
10375 // Create a new simpler BUILD_VECTOR sequence which other optimizations can
10376 // turn into a single shuffle instruction.
10380 bool isLE = TLI.isLittleEndian();
10381 unsigned ElemRatio = OutScalarTy.getSizeInBits()/SourceType.getSizeInBits();
10382 assert(ElemRatio > 1 && "Invalid element size ratio");
10383 SDValue Filler = AllAnyExt ? DAG.getUNDEF(SourceType):
10384 DAG.getConstant(0, SourceType);
10386 unsigned NewBVElems = ElemRatio * VT.getVectorNumElements();
10387 SmallVector<SDValue, 8> Ops(NewBVElems, Filler);
10389 // Populate the new build_vector
10390 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
10391 SDValue Cast = N->getOperand(i);
10392 assert((Cast.getOpcode() == ISD::ANY_EXTEND ||
10393 Cast.getOpcode() == ISD::ZERO_EXTEND ||
10394 Cast.getOpcode() == ISD::UNDEF) && "Invalid cast opcode");
10396 if (Cast.getOpcode() == ISD::UNDEF)
10397 In = DAG.getUNDEF(SourceType);
10399 In = Cast->getOperand(0);
10400 unsigned Index = isLE ? (i * ElemRatio) :
10401 (i * ElemRatio + (ElemRatio - 1));
10403 assert(Index < Ops.size() && "Invalid index");
10407 // The type of the new BUILD_VECTOR node.
10408 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), SourceType, NewBVElems);
10409 assert(VecVT.getSizeInBits() == VT.getSizeInBits() &&
10410 "Invalid vector size");
10411 // Check if the new vector type is legal.
10412 if (!isTypeLegal(VecVT)) return SDValue();
10414 // Make the new BUILD_VECTOR.
10415 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, VecVT, Ops);
10417 // The new BUILD_VECTOR node has the potential to be further optimized.
10418 AddToWorklist(BV.getNode());
10419 // Bitcast to the desired type.
10420 return DAG.getNode(ISD::BITCAST, dl, VT, BV);
10423 SDValue DAGCombiner::reduceBuildVecConvertToConvertBuildVec(SDNode *N) {
10424 EVT VT = N->getValueType(0);
10426 unsigned NumInScalars = N->getNumOperands();
10429 EVT SrcVT = MVT::Other;
10430 unsigned Opcode = ISD::DELETED_NODE;
10431 unsigned NumDefs = 0;
10433 for (unsigned i = 0; i != NumInScalars; ++i) {
10434 SDValue In = N->getOperand(i);
10435 unsigned Opc = In.getOpcode();
10437 if (Opc == ISD::UNDEF)
10440 // If all scalar values are floats and converted from integers.
10441 if (Opcode == ISD::DELETED_NODE &&
10442 (Opc == ISD::UINT_TO_FP || Opc == ISD::SINT_TO_FP)) {
10449 EVT InVT = In.getOperand(0).getValueType();
10451 // If all scalar values are typed differently, bail out. It's chosen to
10452 // simplify BUILD_VECTOR of integer types.
10453 if (SrcVT == MVT::Other)
10460 // If the vector has just one element defined, it's not worth to fold it into
10461 // a vectorized one.
10465 assert((Opcode == ISD::UINT_TO_FP || Opcode == ISD::SINT_TO_FP)
10466 && "Should only handle conversion from integer to float.");
10467 assert(SrcVT != MVT::Other && "Cannot determine source type!");
10469 EVT NVT = EVT::getVectorVT(*DAG.getContext(), SrcVT, NumInScalars);
10471 if (!TLI.isOperationLegalOrCustom(Opcode, NVT))
10474 SmallVector<SDValue, 8> Opnds;
10475 for (unsigned i = 0; i != NumInScalars; ++i) {
10476 SDValue In = N->getOperand(i);
10478 if (In.getOpcode() == ISD::UNDEF)
10479 Opnds.push_back(DAG.getUNDEF(SrcVT));
10481 Opnds.push_back(In.getOperand(0));
10483 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, NVT, Opnds);
10484 AddToWorklist(BV.getNode());
10486 return DAG.getNode(Opcode, dl, VT, BV);
10489 SDValue DAGCombiner::visitBUILD_VECTOR(SDNode *N) {
10490 unsigned NumInScalars = N->getNumOperands();
10492 EVT VT = N->getValueType(0);
10494 // A vector built entirely of undefs is undef.
10495 if (ISD::allOperandsUndef(N))
10496 return DAG.getUNDEF(VT);
10498 SDValue V = reduceBuildVecExtToExtBuildVec(N);
10502 V = reduceBuildVecConvertToConvertBuildVec(N);
10506 // Check to see if this is a BUILD_VECTOR of a bunch of EXTRACT_VECTOR_ELT
10507 // operations. If so, and if the EXTRACT_VECTOR_ELT vector inputs come from
10508 // at most two distinct vectors, turn this into a shuffle node.
10510 // Only type-legal BUILD_VECTOR nodes are converted to shuffle nodes.
10511 if (!isTypeLegal(VT))
10514 // May only combine to shuffle after legalize if shuffle is legal.
10515 if (LegalOperations && !TLI.isOperationLegal(ISD::VECTOR_SHUFFLE, VT))
10518 SDValue VecIn1, VecIn2;
10519 for (unsigned i = 0; i != NumInScalars; ++i) {
10520 // Ignore undef inputs.
10521 if (N->getOperand(i).getOpcode() == ISD::UNDEF) continue;
10523 // If this input is something other than a EXTRACT_VECTOR_ELT with a
10524 // constant index, bail out.
10525 if (N->getOperand(i).getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
10526 !isa<ConstantSDNode>(N->getOperand(i).getOperand(1))) {
10527 VecIn1 = VecIn2 = SDValue(nullptr, 0);
10531 // We allow up to two distinct input vectors.
10532 SDValue ExtractedFromVec = N->getOperand(i).getOperand(0);
10533 if (ExtractedFromVec == VecIn1 || ExtractedFromVec == VecIn2)
10536 if (!VecIn1.getNode()) {
10537 VecIn1 = ExtractedFromVec;
10538 } else if (!VecIn2.getNode()) {
10539 VecIn2 = ExtractedFromVec;
10541 // Too many inputs.
10542 VecIn1 = VecIn2 = SDValue(nullptr, 0);
10547 // If everything is good, we can make a shuffle operation.
10548 if (VecIn1.getNode()) {
10549 SmallVector<int, 8> Mask;
10550 for (unsigned i = 0; i != NumInScalars; ++i) {
10551 if (N->getOperand(i).getOpcode() == ISD::UNDEF) {
10552 Mask.push_back(-1);
10556 // If extracting from the first vector, just use the index directly.
10557 SDValue Extract = N->getOperand(i);
10558 SDValue ExtVal = Extract.getOperand(1);
10559 if (Extract.getOperand(0) == VecIn1) {
10560 unsigned ExtIndex = cast<ConstantSDNode>(ExtVal)->getZExtValue();
10561 if (ExtIndex > VT.getVectorNumElements())
10564 Mask.push_back(ExtIndex);
10568 // Otherwise, use InIdx + VecSize
10569 unsigned Idx = cast<ConstantSDNode>(ExtVal)->getZExtValue();
10570 Mask.push_back(Idx+NumInScalars);
10573 // We can't generate a shuffle node with mismatched input and output types.
10574 // Attempt to transform a single input vector to the correct type.
10575 if ((VT != VecIn1.getValueType())) {
10576 // We don't support shuffeling between TWO values of different types.
10577 if (VecIn2.getNode())
10580 // We only support widening of vectors which are half the size of the
10581 // output registers. For example XMM->YMM widening on X86 with AVX.
10582 if (VecIn1.getValueType().getSizeInBits()*2 != VT.getSizeInBits())
10585 // If the input vector type has a different base type to the output
10586 // vector type, bail out.
10587 if (VecIn1.getValueType().getVectorElementType() !=
10588 VT.getVectorElementType())
10591 // Widen the input vector by adding undef values.
10592 VecIn1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
10593 VecIn1, DAG.getUNDEF(VecIn1.getValueType()));
10596 // If VecIn2 is unused then change it to undef.
10597 VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(VT);
10599 // Check that we were able to transform all incoming values to the same
10601 if (VecIn2.getValueType() != VecIn1.getValueType() ||
10602 VecIn1.getValueType() != VT)
10605 // Return the new VECTOR_SHUFFLE node.
10609 return DAG.getVectorShuffle(VT, dl, Ops[0], Ops[1], &Mask[0]);
10615 SDValue DAGCombiner::visitCONCAT_VECTORS(SDNode *N) {
10616 // TODO: Check to see if this is a CONCAT_VECTORS of a bunch of
10617 // EXTRACT_SUBVECTOR operations. If so, and if the EXTRACT_SUBVECTOR vector
10618 // inputs come from at most two distinct vectors, turn this into a shuffle
10621 // If we only have one input vector, we don't need to do any concatenation.
10622 if (N->getNumOperands() == 1)
10623 return N->getOperand(0);
10625 // Check if all of the operands are undefs.
10626 EVT VT = N->getValueType(0);
10627 if (ISD::allOperandsUndef(N))
10628 return DAG.getUNDEF(VT);
10630 // Optimize concat_vectors where one of the vectors is undef.
10631 if (N->getNumOperands() == 2 &&
10632 N->getOperand(1)->getOpcode() == ISD::UNDEF) {
10633 SDValue In = N->getOperand(0);
10634 assert(In.getValueType().isVector() && "Must concat vectors");
10636 // Transform: concat_vectors(scalar, undef) -> scalar_to_vector(sclr).
10637 if (In->getOpcode() == ISD::BITCAST &&
10638 !In->getOperand(0)->getValueType(0).isVector()) {
10639 SDValue Scalar = In->getOperand(0);
10640 EVT SclTy = Scalar->getValueType(0);
10642 if (!SclTy.isFloatingPoint() && !SclTy.isInteger())
10645 EVT NVT = EVT::getVectorVT(*DAG.getContext(), SclTy,
10646 VT.getSizeInBits() / SclTy.getSizeInBits());
10647 if (!TLI.isTypeLegal(NVT) || !TLI.isTypeLegal(Scalar.getValueType()))
10650 SDLoc dl = SDLoc(N);
10651 SDValue Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, NVT, Scalar);
10652 return DAG.getNode(ISD::BITCAST, dl, VT, Res);
10656 // fold (concat_vectors (BUILD_VECTOR A, B, ...), (BUILD_VECTOR C, D, ...))
10657 // -> (BUILD_VECTOR A, B, ..., C, D, ...)
10658 if (N->getNumOperands() == 2 &&
10659 N->getOperand(0).getOpcode() == ISD::BUILD_VECTOR &&
10660 N->getOperand(1).getOpcode() == ISD::BUILD_VECTOR) {
10661 EVT VT = N->getValueType(0);
10662 SDValue N0 = N->getOperand(0);
10663 SDValue N1 = N->getOperand(1);
10664 SmallVector<SDValue, 8> Opnds;
10665 unsigned BuildVecNumElts = N0.getNumOperands();
10667 EVT SclTy0 = N0.getOperand(0)->getValueType(0);
10668 EVT SclTy1 = N1.getOperand(0)->getValueType(0);
10669 if (SclTy0.isFloatingPoint()) {
10670 for (unsigned i = 0; i != BuildVecNumElts; ++i)
10671 Opnds.push_back(N0.getOperand(i));
10672 for (unsigned i = 0; i != BuildVecNumElts; ++i)
10673 Opnds.push_back(N1.getOperand(i));
10675 // If BUILD_VECTOR are from built from integer, they may have different
10676 // operand types. Get the smaller type and truncate all operands to it.
10677 EVT MinTy = SclTy0.bitsLE(SclTy1) ? SclTy0 : SclTy1;
10678 for (unsigned i = 0; i != BuildVecNumElts; ++i)
10679 Opnds.push_back(DAG.getNode(ISD::TRUNCATE, SDLoc(N), MinTy,
10680 N0.getOperand(i)));
10681 for (unsigned i = 0; i != BuildVecNumElts; ++i)
10682 Opnds.push_back(DAG.getNode(ISD::TRUNCATE, SDLoc(N), MinTy,
10683 N1.getOperand(i)));
10686 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, Opnds);
10689 // Type legalization of vectors and DAG canonicalization of SHUFFLE_VECTOR
10690 // nodes often generate nop CONCAT_VECTOR nodes.
10691 // Scan the CONCAT_VECTOR operands and look for a CONCAT operations that
10692 // place the incoming vectors at the exact same location.
10693 SDValue SingleSource = SDValue();
10694 unsigned PartNumElem = N->getOperand(0).getValueType().getVectorNumElements();
10696 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
10697 SDValue Op = N->getOperand(i);
10699 if (Op.getOpcode() == ISD::UNDEF)
10702 // Check if this is the identity extract:
10703 if (Op.getOpcode() != ISD::EXTRACT_SUBVECTOR)
10706 // Find the single incoming vector for the extract_subvector.
10707 if (SingleSource.getNode()) {
10708 if (Op.getOperand(0) != SingleSource)
10711 SingleSource = Op.getOperand(0);
10713 // Check the source type is the same as the type of the result.
10714 // If not, this concat may extend the vector, so we can not
10715 // optimize it away.
10716 if (SingleSource.getValueType() != N->getValueType(0))
10720 unsigned IdentityIndex = i * PartNumElem;
10721 ConstantSDNode *CS = dyn_cast<ConstantSDNode>(Op.getOperand(1));
10722 // The extract index must be constant.
10726 // Check that we are reading from the identity index.
10727 if (CS->getZExtValue() != IdentityIndex)
10731 if (SingleSource.getNode())
10732 return SingleSource;
10737 SDValue DAGCombiner::visitEXTRACT_SUBVECTOR(SDNode* N) {
10738 EVT NVT = N->getValueType(0);
10739 SDValue V = N->getOperand(0);
10741 if (V->getOpcode() == ISD::CONCAT_VECTORS) {
10743 // (extract_subvec (concat V1, V2, ...), i)
10746 // Only operand 0 is checked as 'concat' assumes all inputs of the same
10748 if (V->getOperand(0).getValueType() != NVT)
10750 unsigned Idx = dyn_cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
10751 unsigned NumElems = NVT.getVectorNumElements();
10752 assert((Idx % NumElems) == 0 &&
10753 "IDX in concat is not a multiple of the result vector length.");
10754 return V->getOperand(Idx / NumElems);
10758 if (V->getOpcode() == ISD::BITCAST)
10759 V = V.getOperand(0);
10761 if (V->getOpcode() == ISD::INSERT_SUBVECTOR) {
10763 // Handle only simple case where vector being inserted and vector
10764 // being extracted are of same type, and are half size of larger vectors.
10765 EVT BigVT = V->getOperand(0).getValueType();
10766 EVT SmallVT = V->getOperand(1).getValueType();
10767 if (!NVT.bitsEq(SmallVT) || NVT.getSizeInBits()*2 != BigVT.getSizeInBits())
10770 // Only handle cases where both indexes are constants with the same type.
10771 ConstantSDNode *ExtIdx = dyn_cast<ConstantSDNode>(N->getOperand(1));
10772 ConstantSDNode *InsIdx = dyn_cast<ConstantSDNode>(V->getOperand(2));
10774 if (InsIdx && ExtIdx &&
10775 InsIdx->getValueType(0).getSizeInBits() <= 64 &&
10776 ExtIdx->getValueType(0).getSizeInBits() <= 64) {
10778 // (extract_subvec (insert_subvec V1, V2, InsIdx), ExtIdx)
10780 // indices are equal or bit offsets are equal => V1
10781 // otherwise => (extract_subvec V1, ExtIdx)
10782 if (InsIdx->getZExtValue() * SmallVT.getScalarType().getSizeInBits() ==
10783 ExtIdx->getZExtValue() * NVT.getScalarType().getSizeInBits())
10784 return DAG.getNode(ISD::BITCAST, dl, NVT, V->getOperand(1));
10785 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, NVT,
10786 DAG.getNode(ISD::BITCAST, dl,
10787 N->getOperand(0).getValueType(),
10788 V->getOperand(0)), N->getOperand(1));
10795 static SDValue simplifyShuffleOperandRecursively(SmallBitVector &UsedElements,
10796 SDValue V, SelectionDAG &DAG) {
10798 EVT VT = V.getValueType();
10800 switch (V.getOpcode()) {
10804 case ISD::CONCAT_VECTORS: {
10805 EVT OpVT = V->getOperand(0).getValueType();
10806 int OpSize = OpVT.getVectorNumElements();
10807 SmallBitVector OpUsedElements(OpSize, false);
10808 bool FoundSimplification = false;
10809 SmallVector<SDValue, 4> NewOps;
10810 NewOps.reserve(V->getNumOperands());
10811 for (int i = 0, NumOps = V->getNumOperands(); i < NumOps; ++i) {
10812 SDValue Op = V->getOperand(i);
10813 bool OpUsed = false;
10814 for (int j = 0; j < OpSize; ++j)
10815 if (UsedElements[i * OpSize + j]) {
10816 OpUsedElements[j] = true;
10820 OpUsed ? simplifyShuffleOperandRecursively(OpUsedElements, Op, DAG)
10821 : DAG.getUNDEF(OpVT));
10822 FoundSimplification |= Op == NewOps.back();
10823 OpUsedElements.reset();
10825 if (FoundSimplification)
10826 V = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, NewOps);
10830 case ISD::INSERT_SUBVECTOR: {
10831 SDValue BaseV = V->getOperand(0);
10832 SDValue SubV = V->getOperand(1);
10833 auto *IdxN = dyn_cast<ConstantSDNode>(V->getOperand(2));
10837 int SubSize = SubV.getValueType().getVectorNumElements();
10838 int Idx = IdxN->getZExtValue();
10839 bool SubVectorUsed = false;
10840 SmallBitVector SubUsedElements(SubSize, false);
10841 for (int i = 0; i < SubSize; ++i)
10842 if (UsedElements[i + Idx]) {
10843 SubVectorUsed = true;
10844 SubUsedElements[i] = true;
10845 UsedElements[i + Idx] = false;
10848 // Now recurse on both the base and sub vectors.
10849 SDValue SimplifiedSubV =
10851 ? simplifyShuffleOperandRecursively(SubUsedElements, SubV, DAG)
10852 : DAG.getUNDEF(SubV.getValueType());
10853 SDValue SimplifiedBaseV = simplifyShuffleOperandRecursively(UsedElements, BaseV, DAG);
10854 if (SimplifiedSubV != SubV || SimplifiedBaseV != BaseV)
10855 V = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT,
10856 SimplifiedBaseV, SimplifiedSubV, V->getOperand(2));
10862 static SDValue simplifyShuffleOperands(ShuffleVectorSDNode *SVN, SDValue N0,
10863 SDValue N1, SelectionDAG &DAG) {
10864 EVT VT = SVN->getValueType(0);
10865 int NumElts = VT.getVectorNumElements();
10866 SmallBitVector N0UsedElements(NumElts, false), N1UsedElements(NumElts, false);
10867 for (int M : SVN->getMask())
10868 if (M >= 0 && M < NumElts)
10869 N0UsedElements[M] = true;
10870 else if (M >= NumElts)
10871 N1UsedElements[M - NumElts] = true;
10873 SDValue S0 = simplifyShuffleOperandRecursively(N0UsedElements, N0, DAG);
10874 SDValue S1 = simplifyShuffleOperandRecursively(N1UsedElements, N1, DAG);
10875 if (S0 == N0 && S1 == N1)
10878 return DAG.getVectorShuffle(VT, SDLoc(SVN), S0, S1, SVN->getMask());
10881 // Tries to turn a shuffle of two CONCAT_VECTORS into a single concat.
10882 static SDValue partitionShuffleOfConcats(SDNode *N, SelectionDAG &DAG) {
10883 EVT VT = N->getValueType(0);
10884 unsigned NumElts = VT.getVectorNumElements();
10886 SDValue N0 = N->getOperand(0);
10887 SDValue N1 = N->getOperand(1);
10888 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
10890 SmallVector<SDValue, 4> Ops;
10891 EVT ConcatVT = N0.getOperand(0).getValueType();
10892 unsigned NumElemsPerConcat = ConcatVT.getVectorNumElements();
10893 unsigned NumConcats = NumElts / NumElemsPerConcat;
10895 // Look at every vector that's inserted. We're looking for exact
10896 // subvector-sized copies from a concatenated vector
10897 for (unsigned I = 0; I != NumConcats; ++I) {
10898 // Make sure we're dealing with a copy.
10899 unsigned Begin = I * NumElemsPerConcat;
10900 bool AllUndef = true, NoUndef = true;
10901 for (unsigned J = Begin; J != Begin + NumElemsPerConcat; ++J) {
10902 if (SVN->getMaskElt(J) >= 0)
10909 if (SVN->getMaskElt(Begin) % NumElemsPerConcat != 0)
10912 for (unsigned J = 1; J != NumElemsPerConcat; ++J)
10913 if (SVN->getMaskElt(Begin + J - 1) + 1 != SVN->getMaskElt(Begin + J))
10916 unsigned FirstElt = SVN->getMaskElt(Begin) / NumElemsPerConcat;
10917 if (FirstElt < N0.getNumOperands())
10918 Ops.push_back(N0.getOperand(FirstElt));
10920 Ops.push_back(N1.getOperand(FirstElt - N0.getNumOperands()));
10922 } else if (AllUndef) {
10923 Ops.push_back(DAG.getUNDEF(N0.getOperand(0).getValueType()));
10924 } else { // Mixed with general masks and undefs, can't do optimization.
10929 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Ops);
10932 SDValue DAGCombiner::visitVECTOR_SHUFFLE(SDNode *N) {
10933 EVT VT = N->getValueType(0);
10934 unsigned NumElts = VT.getVectorNumElements();
10936 SDValue N0 = N->getOperand(0);
10937 SDValue N1 = N->getOperand(1);
10939 assert(N0.getValueType() == VT && "Vector shuffle must be normalized in DAG");
10941 // Canonicalize shuffle undef, undef -> undef
10942 if (N0.getOpcode() == ISD::UNDEF && N1.getOpcode() == ISD::UNDEF)
10943 return DAG.getUNDEF(VT);
10945 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
10947 // Canonicalize shuffle v, v -> v, undef
10949 SmallVector<int, 8> NewMask;
10950 for (unsigned i = 0; i != NumElts; ++i) {
10951 int Idx = SVN->getMaskElt(i);
10952 if (Idx >= (int)NumElts) Idx -= NumElts;
10953 NewMask.push_back(Idx);
10955 return DAG.getVectorShuffle(VT, SDLoc(N), N0, DAG.getUNDEF(VT),
10959 // Canonicalize shuffle undef, v -> v, undef. Commute the shuffle mask.
10960 if (N0.getOpcode() == ISD::UNDEF) {
10961 SmallVector<int, 8> NewMask;
10962 for (unsigned i = 0; i != NumElts; ++i) {
10963 int Idx = SVN->getMaskElt(i);
10965 if (Idx >= (int)NumElts)
10968 Idx = -1; // remove reference to lhs
10970 NewMask.push_back(Idx);
10972 return DAG.getVectorShuffle(VT, SDLoc(N), N1, DAG.getUNDEF(VT),
10976 // Remove references to rhs if it is undef
10977 if (N1.getOpcode() == ISD::UNDEF) {
10978 bool Changed = false;
10979 SmallVector<int, 8> NewMask;
10980 for (unsigned i = 0; i != NumElts; ++i) {
10981 int Idx = SVN->getMaskElt(i);
10982 if (Idx >= (int)NumElts) {
10986 NewMask.push_back(Idx);
10989 return DAG.getVectorShuffle(VT, SDLoc(N), N0, N1, &NewMask[0]);
10992 // If it is a splat, check if the argument vector is another splat or a
10993 // build_vector with all scalar elements the same.
10994 if (SVN->isSplat() && SVN->getSplatIndex() < (int)NumElts) {
10995 SDNode *V = N0.getNode();
10997 // If this is a bit convert that changes the element type of the vector but
10998 // not the number of vector elements, look through it. Be careful not to
10999 // look though conversions that change things like v4f32 to v2f64.
11000 if (V->getOpcode() == ISD::BITCAST) {
11001 SDValue ConvInput = V->getOperand(0);
11002 if (ConvInput.getValueType().isVector() &&
11003 ConvInput.getValueType().getVectorNumElements() == NumElts)
11004 V = ConvInput.getNode();
11007 if (V->getOpcode() == ISD::BUILD_VECTOR) {
11008 assert(V->getNumOperands() == NumElts &&
11009 "BUILD_VECTOR has wrong number of operands");
11011 bool AllSame = true;
11012 for (unsigned i = 0; i != NumElts; ++i) {
11013 if (V->getOperand(i).getOpcode() != ISD::UNDEF) {
11014 Base = V->getOperand(i);
11018 // Splat of <u, u, u, u>, return <u, u, u, u>
11019 if (!Base.getNode())
11021 for (unsigned i = 0; i != NumElts; ++i) {
11022 if (V->getOperand(i) != Base) {
11027 // Splat of <x, x, x, x>, return <x, x, x, x>
11033 // There are various patterns used to build up a vector from smaller vectors,
11034 // subvectors, or elements. Scan chains of these and replace unused insertions
11035 // or components with undef.
11036 if (SDValue S = simplifyShuffleOperands(SVN, N0, N1, DAG))
11039 if (N0.getOpcode() == ISD::CONCAT_VECTORS &&
11040 Level < AfterLegalizeVectorOps &&
11041 (N1.getOpcode() == ISD::UNDEF ||
11042 (N1.getOpcode() == ISD::CONCAT_VECTORS &&
11043 N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType()))) {
11044 SDValue V = partitionShuffleOfConcats(N, DAG);
11050 // If this shuffle node is simply a swizzle of another shuffle node,
11051 // then try to simplify it.
11052 if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG &&
11053 N1.getOpcode() == ISD::UNDEF) {
11055 ShuffleVectorSDNode *OtherSV = cast<ShuffleVectorSDNode>(N0);
11057 // The incoming shuffle must be of the same type as the result of the
11058 // current shuffle.
11059 assert(OtherSV->getOperand(0).getValueType() == VT &&
11060 "Shuffle types don't match");
11062 SmallVector<int, 4> Mask;
11063 // Compute the combined shuffle mask.
11064 for (unsigned i = 0; i != NumElts; ++i) {
11065 int Idx = SVN->getMaskElt(i);
11066 assert(Idx < (int)NumElts && "Index references undef operand");
11067 // Next, this index comes from the first value, which is the incoming
11068 // shuffle. Adopt the incoming index.
11070 Idx = OtherSV->getMaskElt(Idx);
11071 Mask.push_back(Idx);
11074 // Check if all indices in Mask are Undef. In case, propagate Undef.
11075 bool isUndefMask = true;
11076 for (unsigned i = 0; i != NumElts && isUndefMask; ++i)
11077 isUndefMask &= Mask[i] < 0;
11080 return DAG.getUNDEF(VT);
11082 bool CommuteOperands = false;
11083 if (N0.getOperand(1).getOpcode() != ISD::UNDEF) {
11084 // To be valid, the combine shuffle mask should only reference elements
11085 // from one of the two vectors in input to the inner shufflevector.
11086 bool IsValidMask = true;
11087 for (unsigned i = 0; i != NumElts && IsValidMask; ++i)
11088 // See if the combined mask only reference undefs or elements coming
11089 // from the first shufflevector operand.
11090 IsValidMask = Mask[i] < 0 || (unsigned)Mask[i] < NumElts;
11092 if (!IsValidMask) {
11093 IsValidMask = true;
11094 for (unsigned i = 0; i != NumElts && IsValidMask; ++i)
11095 // Check that all the elements come from the second shuffle operand.
11096 IsValidMask = Mask[i] < 0 || (unsigned)Mask[i] >= NumElts;
11097 CommuteOperands = IsValidMask;
11100 // Early exit if the combined shuffle mask is not valid.
11105 // See if this pair of shuffles can be safely folded according to either
11106 // of the following rules:
11107 // shuffle(shuffle(x, y), undef) -> x
11108 // shuffle(shuffle(x, undef), undef) -> x
11109 // shuffle(shuffle(x, y), undef) -> y
11110 bool IsIdentityMask = true;
11111 unsigned BaseMaskIndex = CommuteOperands ? NumElts : 0;
11112 for (unsigned i = 0; i != NumElts && IsIdentityMask; ++i) {
11117 // The combined shuffle must map each index to itself.
11118 IsIdentityMask = (unsigned)Mask[i] == i + BaseMaskIndex;
11121 if (IsIdentityMask) {
11122 if (CommuteOperands)
11123 // optimize shuffle(shuffle(x, y), undef) -> y.
11124 return OtherSV->getOperand(1);
11126 // optimize shuffle(shuffle(x, undef), undef) -> x
11127 // optimize shuffle(shuffle(x, y), undef) -> x
11128 return OtherSV->getOperand(0);
11131 // It may still be beneficial to combine the two shuffles if the
11132 // resulting shuffle is legal.
11133 if (TLI.isTypeLegal(VT)) {
11134 if (!CommuteOperands) {
11135 if (TLI.isShuffleMaskLegal(Mask, VT))
11136 // shuffle(shuffle(x, undef, M1), undef, M2) -> shuffle(x, undef, M3).
11137 // shuffle(shuffle(x, y, M1), undef, M2) -> shuffle(x, undef, M3)
11138 return DAG.getVectorShuffle(VT, SDLoc(N), N0->getOperand(0), N1,
11141 // Compute the commuted shuffle mask.
11142 for (unsigned i = 0; i != NumElts; ++i) {
11146 else if (idx < (int)NumElts)
11147 Mask[i] = idx + NumElts;
11149 Mask[i] = idx - NumElts;
11152 if (TLI.isShuffleMaskLegal(Mask, VT))
11153 // shuffle(shuffle(x, y, M1), undef, M2) -> shuffle(y, undef, M3)
11154 return DAG.getVectorShuffle(VT, SDLoc(N), N0->getOperand(1), N1,
11160 // Canonicalize shuffles according to rules:
11161 // shuffle(A, shuffle(A, B)) -> shuffle(shuffle(A,B), A)
11162 // shuffle(B, shuffle(A, B)) -> shuffle(shuffle(A,B), B)
11163 // shuffle(B, shuffle(A, Undef)) -> shuffle(shuffle(A, Undef), B)
11164 if (N1.getOpcode() == ISD::VECTOR_SHUFFLE && N0.getOpcode() != ISD::UNDEF &&
11165 N0.getOpcode() != ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG &&
11166 TLI.isTypeLegal(VT)) {
11167 // The incoming shuffle must be of the same type as the result of the
11168 // current shuffle.
11169 assert(N1->getOperand(0).getValueType() == VT &&
11170 "Shuffle types don't match");
11172 SDValue SV0 = N1->getOperand(0);
11173 SDValue SV1 = N1->getOperand(1);
11174 bool HasSameOp0 = N0 == SV0;
11175 bool IsSV1Undef = SV1.getOpcode() == ISD::UNDEF;
11176 if (HasSameOp0 || IsSV1Undef || N0 == SV1)
11177 // Commute the operands of this shuffle so that next rule
11179 return DAG.getCommutedVectorShuffle(*SVN);
11182 // Try to fold according to rules:
11183 // shuffle(shuffle(A, B, M0), B, M1) -> shuffle(A, B, M2)
11184 // shuffle(shuffle(A, B, M0), A, M1) -> shuffle(A, B, M2)
11185 // shuffle(shuffle(A, Undef, M0), B, M1) -> shuffle(A, B, M2)
11186 // shuffle(shuffle(A, Undef, M0), A, M1) -> shuffle(A, Undef, M2)
11187 // Don't try to fold shuffles with illegal type.
11188 if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG &&
11189 N1.getOpcode() != ISD::UNDEF && TLI.isTypeLegal(VT)) {
11190 ShuffleVectorSDNode *OtherSV = cast<ShuffleVectorSDNode>(N0);
11192 // The incoming shuffle must be of the same type as the result of the
11193 // current shuffle.
11194 assert(OtherSV->getOperand(0).getValueType() == VT &&
11195 "Shuffle types don't match");
11197 SDValue SV0 = OtherSV->getOperand(0);
11198 SDValue SV1 = OtherSV->getOperand(1);
11199 bool HasSameOp0 = N1 == SV0;
11200 bool IsSV1Undef = SV1.getOpcode() == ISD::UNDEF;
11201 if (!HasSameOp0 && !IsSV1Undef && N1 != SV1)
11205 SmallVector<int, 4> Mask;
11206 // Compute the combined shuffle mask for a shuffle with SV0 as the first
11207 // operand, and SV1 as the second operand.
11208 for (unsigned i = 0; i != NumElts; ++i) {
11209 int Idx = SVN->getMaskElt(i);
11211 // Propagate Undef.
11212 Mask.push_back(Idx);
11216 if (Idx < (int)NumElts) {
11217 Idx = OtherSV->getMaskElt(Idx);
11218 if (IsSV1Undef && Idx >= (int) NumElts)
11219 Idx = -1; // Propagate Undef.
11221 Idx = HasSameOp0 ? Idx - NumElts : Idx;
11223 Mask.push_back(Idx);
11226 // Check if all indices in Mask are Undef. In case, propagate Undef.
11227 bool isUndefMask = true;
11228 for (unsigned i = 0; i != NumElts && isUndefMask; ++i)
11229 isUndefMask &= Mask[i] < 0;
11232 return DAG.getUNDEF(VT);
11234 // Avoid introducing shuffles with illegal mask.
11235 if (TLI.isShuffleMaskLegal(Mask, VT)) {
11237 // shuffle(shuffle(A, Undef, M0), B, M1) -> shuffle(A, B, M2)
11238 // shuffle(shuffle(A, Undef, M0), A, M1) -> shuffle(A, Undef, M2)
11239 return DAG.getVectorShuffle(VT, SDLoc(N), SV0, N1, &Mask[0]);
11240 return DAG.getVectorShuffle(VT, SDLoc(N), SV0, SV1, &Mask[0]);
11243 // Compute the commuted shuffle mask.
11244 for (unsigned i = 0; i != NumElts; ++i) {
11248 else if (idx < (int)NumElts)
11249 Mask[i] = idx + NumElts;
11251 Mask[i] = idx - NumElts;
11254 if (TLI.isShuffleMaskLegal(Mask, VT)) {
11256 // shuffle(shuffle(A, Undef, M0), B, M1) -> shuffle(B, A, M2)
11257 return DAG.getVectorShuffle(VT, SDLoc(N), N1, SV0, &Mask[0]);
11258 // shuffle(shuffle(A, B, M0), B, M1) -> shuffle(B, A, M2)
11259 // shuffle(shuffle(A, B, M0), A, M1) -> shuffle(B, A, M2)
11260 return DAG.getVectorShuffle(VT, SDLoc(N), SV1, SV0, &Mask[0]);
11267 SDValue DAGCombiner::visitINSERT_SUBVECTOR(SDNode *N) {
11268 SDValue N0 = N->getOperand(0);
11269 SDValue N2 = N->getOperand(2);
11271 // If the input vector is a concatenation, and the insert replaces
11272 // one of the halves, we can optimize into a single concat_vectors.
11273 if (N0.getOpcode() == ISD::CONCAT_VECTORS &&
11274 N0->getNumOperands() == 2 && N2.getOpcode() == ISD::Constant) {
11275 APInt InsIdx = cast<ConstantSDNode>(N2)->getAPIntValue();
11276 EVT VT = N->getValueType(0);
11278 // Lower half: fold (insert_subvector (concat_vectors X, Y), Z) ->
11279 // (concat_vectors Z, Y)
11281 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
11282 N->getOperand(1), N0.getOperand(1));
11284 // Upper half: fold (insert_subvector (concat_vectors X, Y), Z) ->
11285 // (concat_vectors X, Z)
11286 if (InsIdx == VT.getVectorNumElements()/2)
11287 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
11288 N0.getOperand(0), N->getOperand(1));
11294 /// Returns a vector_shuffle if it able to transform an AND to a vector_shuffle
11295 /// with the destination vector and a zero vector.
11296 /// e.g. AND V, <0xffffffff, 0, 0xffffffff, 0>. ==>
11297 /// vector_shuffle V, Zero, <0, 4, 2, 4>
11298 SDValue DAGCombiner::XformToShuffleWithZero(SDNode *N) {
11299 EVT VT = N->getValueType(0);
11301 SDValue LHS = N->getOperand(0);
11302 SDValue RHS = N->getOperand(1);
11303 if (N->getOpcode() == ISD::AND) {
11304 if (RHS.getOpcode() == ISD::BITCAST)
11305 RHS = RHS.getOperand(0);
11306 if (RHS.getOpcode() == ISD::BUILD_VECTOR) {
11307 SmallVector<int, 8> Indices;
11308 unsigned NumElts = RHS.getNumOperands();
11309 for (unsigned i = 0; i != NumElts; ++i) {
11310 SDValue Elt = RHS.getOperand(i);
11311 if (!isa<ConstantSDNode>(Elt))
11314 if (cast<ConstantSDNode>(Elt)->isAllOnesValue())
11315 Indices.push_back(i);
11316 else if (cast<ConstantSDNode>(Elt)->isNullValue())
11317 Indices.push_back(NumElts+i);
11322 // Let's see if the target supports this vector_shuffle.
11323 EVT RVT = RHS.getValueType();
11324 if (!TLI.isVectorClearMaskLegal(Indices, RVT))
11327 // Return the new VECTOR_SHUFFLE node.
11328 EVT EltVT = RVT.getVectorElementType();
11329 SmallVector<SDValue,8> ZeroOps(RVT.getVectorNumElements(),
11330 DAG.getConstant(0, EltVT));
11331 SDValue Zero = DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), RVT, ZeroOps);
11332 LHS = DAG.getNode(ISD::BITCAST, dl, RVT, LHS);
11333 SDValue Shuf = DAG.getVectorShuffle(RVT, dl, LHS, Zero, &Indices[0]);
11334 return DAG.getNode(ISD::BITCAST, dl, VT, Shuf);
11341 /// Visit a binary vector operation, like ADD.
11342 SDValue DAGCombiner::SimplifyVBinOp(SDNode *N) {
11343 assert(N->getValueType(0).isVector() &&
11344 "SimplifyVBinOp only works on vectors!");
11346 SDValue LHS = N->getOperand(0);
11347 SDValue RHS = N->getOperand(1);
11348 SDValue Shuffle = XformToShuffleWithZero(N);
11349 if (Shuffle.getNode()) return Shuffle;
11351 // If the LHS and RHS are BUILD_VECTOR nodes, see if we can constant fold
11353 if (LHS.getOpcode() == ISD::BUILD_VECTOR &&
11354 RHS.getOpcode() == ISD::BUILD_VECTOR) {
11355 // Check if both vectors are constants. If not bail out.
11356 if (!(cast<BuildVectorSDNode>(LHS)->isConstant() &&
11357 cast<BuildVectorSDNode>(RHS)->isConstant()))
11360 SmallVector<SDValue, 8> Ops;
11361 for (unsigned i = 0, e = LHS.getNumOperands(); i != e; ++i) {
11362 SDValue LHSOp = LHS.getOperand(i);
11363 SDValue RHSOp = RHS.getOperand(i);
11365 // Can't fold divide by zero.
11366 if (N->getOpcode() == ISD::SDIV || N->getOpcode() == ISD::UDIV ||
11367 N->getOpcode() == ISD::FDIV) {
11368 if ((RHSOp.getOpcode() == ISD::Constant &&
11369 cast<ConstantSDNode>(RHSOp.getNode())->isNullValue()) ||
11370 (RHSOp.getOpcode() == ISD::ConstantFP &&
11371 cast<ConstantFPSDNode>(RHSOp.getNode())->getValueAPF().isZero()))
11375 EVT VT = LHSOp.getValueType();
11376 EVT RVT = RHSOp.getValueType();
11378 // Integer BUILD_VECTOR operands may have types larger than the element
11379 // size (e.g., when the element type is not legal). Prior to type
11380 // legalization, the types may not match between the two BUILD_VECTORS.
11381 // Truncate one of the operands to make them match.
11382 if (RVT.getSizeInBits() > VT.getSizeInBits()) {
11383 RHSOp = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, RHSOp);
11385 LHSOp = DAG.getNode(ISD::TRUNCATE, SDLoc(N), RVT, LHSOp);
11389 SDValue FoldOp = DAG.getNode(N->getOpcode(), SDLoc(LHS), VT,
11391 if (FoldOp.getOpcode() != ISD::UNDEF &&
11392 FoldOp.getOpcode() != ISD::Constant &&
11393 FoldOp.getOpcode() != ISD::ConstantFP)
11395 Ops.push_back(FoldOp);
11396 AddToWorklist(FoldOp.getNode());
11399 if (Ops.size() == LHS.getNumOperands())
11400 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), LHS.getValueType(), Ops);
11403 // Type legalization might introduce new shuffles in the DAG.
11404 // Fold (VBinOp (shuffle (A, Undef, Mask)), (shuffle (B, Undef, Mask)))
11405 // -> (shuffle (VBinOp (A, B)), Undef, Mask).
11406 if (LegalTypes && isa<ShuffleVectorSDNode>(LHS) &&
11407 isa<ShuffleVectorSDNode>(RHS) && LHS.hasOneUse() && RHS.hasOneUse() &&
11408 LHS.getOperand(1).getOpcode() == ISD::UNDEF &&
11409 RHS.getOperand(1).getOpcode() == ISD::UNDEF) {
11410 ShuffleVectorSDNode *SVN0 = cast<ShuffleVectorSDNode>(LHS);
11411 ShuffleVectorSDNode *SVN1 = cast<ShuffleVectorSDNode>(RHS);
11413 if (SVN0->getMask().equals(SVN1->getMask())) {
11414 EVT VT = N->getValueType(0);
11415 SDValue UndefVector = LHS.getOperand(1);
11416 SDValue NewBinOp = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
11417 LHS.getOperand(0), RHS.getOperand(0));
11418 AddUsersToWorklist(N);
11419 return DAG.getVectorShuffle(VT, SDLoc(N), NewBinOp, UndefVector,
11420 &SVN0->getMask()[0]);
11427 /// Visit a binary vector operation, like FABS/FNEG.
11428 SDValue DAGCombiner::SimplifyVUnaryOp(SDNode *N) {
11429 assert(N->getValueType(0).isVector() &&
11430 "SimplifyVUnaryOp only works on vectors!");
11432 SDValue N0 = N->getOperand(0);
11434 if (N0.getOpcode() != ISD::BUILD_VECTOR)
11437 // Operand is a BUILD_VECTOR node, see if we can constant fold it.
11438 SmallVector<SDValue, 8> Ops;
11439 for (unsigned i = 0, e = N0.getNumOperands(); i != e; ++i) {
11440 SDValue Op = N0.getOperand(i);
11441 if (Op.getOpcode() != ISD::UNDEF &&
11442 Op.getOpcode() != ISD::ConstantFP)
11444 EVT EltVT = Op.getValueType();
11445 SDValue FoldOp = DAG.getNode(N->getOpcode(), SDLoc(N0), EltVT, Op);
11446 if (FoldOp.getOpcode() != ISD::UNDEF &&
11447 FoldOp.getOpcode() != ISD::ConstantFP)
11449 Ops.push_back(FoldOp);
11450 AddToWorklist(FoldOp.getNode());
11453 if (Ops.size() != N0.getNumOperands())
11456 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), N0.getValueType(), Ops);
11459 SDValue DAGCombiner::SimplifySelect(SDLoc DL, SDValue N0,
11460 SDValue N1, SDValue N2){
11461 assert(N0.getOpcode() ==ISD::SETCC && "First argument must be a SetCC node!");
11463 SDValue SCC = SimplifySelectCC(DL, N0.getOperand(0), N0.getOperand(1), N1, N2,
11464 cast<CondCodeSDNode>(N0.getOperand(2))->get());
11466 // If we got a simplified select_cc node back from SimplifySelectCC, then
11467 // break it down into a new SETCC node, and a new SELECT node, and then return
11468 // the SELECT node, since we were called with a SELECT node.
11469 if (SCC.getNode()) {
11470 // Check to see if we got a select_cc back (to turn into setcc/select).
11471 // Otherwise, just return whatever node we got back, like fabs.
11472 if (SCC.getOpcode() == ISD::SELECT_CC) {
11473 SDValue SETCC = DAG.getNode(ISD::SETCC, SDLoc(N0),
11475 SCC.getOperand(0), SCC.getOperand(1),
11476 SCC.getOperand(4));
11477 AddToWorklist(SETCC.getNode());
11478 return DAG.getSelect(SDLoc(SCC), SCC.getValueType(), SETCC,
11479 SCC.getOperand(2), SCC.getOperand(3));
11487 /// Given a SELECT or a SELECT_CC node, where LHS and RHS are the two values
11488 /// being selected between, see if we can simplify the select. Callers of this
11489 /// should assume that TheSelect is deleted if this returns true. As such, they
11490 /// should return the appropriate thing (e.g. the node) back to the top-level of
11491 /// the DAG combiner loop to avoid it being looked at.
11492 bool DAGCombiner::SimplifySelectOps(SDNode *TheSelect, SDValue LHS,
11495 // Cannot simplify select with vector condition
11496 if (TheSelect->getOperand(0).getValueType().isVector()) return false;
11498 // If this is a select from two identical things, try to pull the operation
11499 // through the select.
11500 if (LHS.getOpcode() != RHS.getOpcode() ||
11501 !LHS.hasOneUse() || !RHS.hasOneUse())
11504 // If this is a load and the token chain is identical, replace the select
11505 // of two loads with a load through a select of the address to load from.
11506 // This triggers in things like "select bool X, 10.0, 123.0" after the FP
11507 // constants have been dropped into the constant pool.
11508 if (LHS.getOpcode() == ISD::LOAD) {
11509 LoadSDNode *LLD = cast<LoadSDNode>(LHS);
11510 LoadSDNode *RLD = cast<LoadSDNode>(RHS);
11512 // Token chains must be identical.
11513 if (LHS.getOperand(0) != RHS.getOperand(0) ||
11514 // Do not let this transformation reduce the number of volatile loads.
11515 LLD->isVolatile() || RLD->isVolatile() ||
11516 // If this is an EXTLOAD, the VT's must match.
11517 LLD->getMemoryVT() != RLD->getMemoryVT() ||
11518 // If this is an EXTLOAD, the kind of extension must match.
11519 (LLD->getExtensionType() != RLD->getExtensionType() &&
11520 // The only exception is if one of the extensions is anyext.
11521 LLD->getExtensionType() != ISD::EXTLOAD &&
11522 RLD->getExtensionType() != ISD::EXTLOAD) ||
11523 // FIXME: this discards src value information. This is
11524 // over-conservative. It would be beneficial to be able to remember
11525 // both potential memory locations. Since we are discarding
11526 // src value info, don't do the transformation if the memory
11527 // locations are not in the default address space.
11528 LLD->getPointerInfo().getAddrSpace() != 0 ||
11529 RLD->getPointerInfo().getAddrSpace() != 0 ||
11530 !TLI.isOperationLegalOrCustom(TheSelect->getOpcode(),
11531 LLD->getBasePtr().getValueType()))
11534 // Check that the select condition doesn't reach either load. If so,
11535 // folding this will induce a cycle into the DAG. If not, this is safe to
11536 // xform, so create a select of the addresses.
11538 if (TheSelect->getOpcode() == ISD::SELECT) {
11539 SDNode *CondNode = TheSelect->getOperand(0).getNode();
11540 if ((LLD->hasAnyUseOfValue(1) && LLD->isPredecessorOf(CondNode)) ||
11541 (RLD->hasAnyUseOfValue(1) && RLD->isPredecessorOf(CondNode)))
11543 // The loads must not depend on one another.
11544 if (LLD->isPredecessorOf(RLD) ||
11545 RLD->isPredecessorOf(LLD))
11547 Addr = DAG.getSelect(SDLoc(TheSelect),
11548 LLD->getBasePtr().getValueType(),
11549 TheSelect->getOperand(0), LLD->getBasePtr(),
11550 RLD->getBasePtr());
11551 } else { // Otherwise SELECT_CC
11552 SDNode *CondLHS = TheSelect->getOperand(0).getNode();
11553 SDNode *CondRHS = TheSelect->getOperand(1).getNode();
11555 if ((LLD->hasAnyUseOfValue(1) &&
11556 (LLD->isPredecessorOf(CondLHS) || LLD->isPredecessorOf(CondRHS))) ||
11557 (RLD->hasAnyUseOfValue(1) &&
11558 (RLD->isPredecessorOf(CondLHS) || RLD->isPredecessorOf(CondRHS))))
11561 Addr = DAG.getNode(ISD::SELECT_CC, SDLoc(TheSelect),
11562 LLD->getBasePtr().getValueType(),
11563 TheSelect->getOperand(0),
11564 TheSelect->getOperand(1),
11565 LLD->getBasePtr(), RLD->getBasePtr(),
11566 TheSelect->getOperand(4));
11570 // It is safe to replace the two loads if they have different alignments,
11571 // but the new load must be the minimum (most restrictive) alignment of the
11573 bool isInvariant = LLD->isInvariant() & RLD->isInvariant();
11574 unsigned Alignment = std::min(LLD->getAlignment(), RLD->getAlignment());
11575 if (LLD->getExtensionType() == ISD::NON_EXTLOAD) {
11576 Load = DAG.getLoad(TheSelect->getValueType(0),
11578 // FIXME: Discards pointer and AA info.
11579 LLD->getChain(), Addr, MachinePointerInfo(),
11580 LLD->isVolatile(), LLD->isNonTemporal(),
11581 isInvariant, Alignment);
11583 Load = DAG.getExtLoad(LLD->getExtensionType() == ISD::EXTLOAD ?
11584 RLD->getExtensionType() : LLD->getExtensionType(),
11586 TheSelect->getValueType(0),
11587 // FIXME: Discards pointer and AA info.
11588 LLD->getChain(), Addr, MachinePointerInfo(),
11589 LLD->getMemoryVT(), LLD->isVolatile(),
11590 LLD->isNonTemporal(), isInvariant, Alignment);
11593 // Users of the select now use the result of the load.
11594 CombineTo(TheSelect, Load);
11596 // Users of the old loads now use the new load's chain. We know the
11597 // old-load value is dead now.
11598 CombineTo(LHS.getNode(), Load.getValue(0), Load.getValue(1));
11599 CombineTo(RHS.getNode(), Load.getValue(0), Load.getValue(1));
11606 /// Simplify an expression of the form (N0 cond N1) ? N2 : N3
11607 /// where 'cond' is the comparison specified by CC.
11608 SDValue DAGCombiner::SimplifySelectCC(SDLoc DL, SDValue N0, SDValue N1,
11609 SDValue N2, SDValue N3,
11610 ISD::CondCode CC, bool NotExtCompare) {
11611 // (x ? y : y) -> y.
11612 if (N2 == N3) return N2;
11614 EVT VT = N2.getValueType();
11615 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
11616 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2.getNode());
11617 ConstantSDNode *N3C = dyn_cast<ConstantSDNode>(N3.getNode());
11619 // Determine if the condition we're dealing with is constant
11620 SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()),
11621 N0, N1, CC, DL, false);
11622 if (SCC.getNode()) AddToWorklist(SCC.getNode());
11623 ConstantSDNode *SCCC = dyn_cast_or_null<ConstantSDNode>(SCC.getNode());
11625 // fold select_cc true, x, y -> x
11626 if (SCCC && !SCCC->isNullValue())
11628 // fold select_cc false, x, y -> y
11629 if (SCCC && SCCC->isNullValue())
11632 // Check to see if we can simplify the select into an fabs node
11633 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N1)) {
11634 // Allow either -0.0 or 0.0
11635 if (CFP->getValueAPF().isZero()) {
11636 // select (setg[te] X, +/-0.0), X, fneg(X) -> fabs
11637 if ((CC == ISD::SETGE || CC == ISD::SETGT) &&
11638 N0 == N2 && N3.getOpcode() == ISD::FNEG &&
11639 N2 == N3.getOperand(0))
11640 return DAG.getNode(ISD::FABS, DL, VT, N0);
11642 // select (setl[te] X, +/-0.0), fneg(X), X -> fabs
11643 if ((CC == ISD::SETLT || CC == ISD::SETLE) &&
11644 N0 == N3 && N2.getOpcode() == ISD::FNEG &&
11645 N2.getOperand(0) == N3)
11646 return DAG.getNode(ISD::FABS, DL, VT, N3);
11650 // Turn "(a cond b) ? 1.0f : 2.0f" into "load (tmp + ((a cond b) ? 0 : 4)"
11651 // where "tmp" is a constant pool entry containing an array with 1.0 and 2.0
11652 // in it. This is a win when the constant is not otherwise available because
11653 // it replaces two constant pool loads with one. We only do this if the FP
11654 // type is known to be legal, because if it isn't, then we are before legalize
11655 // types an we want the other legalization to happen first (e.g. to avoid
11656 // messing with soft float) and if the ConstantFP is not legal, because if
11657 // it is legal, we may not need to store the FP constant in a constant pool.
11658 if (ConstantFPSDNode *TV = dyn_cast<ConstantFPSDNode>(N2))
11659 if (ConstantFPSDNode *FV = dyn_cast<ConstantFPSDNode>(N3)) {
11660 if (TLI.isTypeLegal(N2.getValueType()) &&
11661 (TLI.getOperationAction(ISD::ConstantFP, N2.getValueType()) !=
11662 TargetLowering::Legal &&
11663 !TLI.isFPImmLegal(TV->getValueAPF(), TV->getValueType(0)) &&
11664 !TLI.isFPImmLegal(FV->getValueAPF(), FV->getValueType(0))) &&
11665 // If both constants have multiple uses, then we won't need to do an
11666 // extra load, they are likely around in registers for other users.
11667 (TV->hasOneUse() || FV->hasOneUse())) {
11668 Constant *Elts[] = {
11669 const_cast<ConstantFP*>(FV->getConstantFPValue()),
11670 const_cast<ConstantFP*>(TV->getConstantFPValue())
11672 Type *FPTy = Elts[0]->getType();
11673 const DataLayout &TD = *TLI.getDataLayout();
11675 // Create a ConstantArray of the two constants.
11676 Constant *CA = ConstantArray::get(ArrayType::get(FPTy, 2), Elts);
11677 SDValue CPIdx = DAG.getConstantPool(CA, TLI.getPointerTy(),
11678 TD.getPrefTypeAlignment(FPTy));
11679 unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
11681 // Get the offsets to the 0 and 1 element of the array so that we can
11682 // select between them.
11683 SDValue Zero = DAG.getIntPtrConstant(0);
11684 unsigned EltSize = (unsigned)TD.getTypeAllocSize(Elts[0]->getType());
11685 SDValue One = DAG.getIntPtrConstant(EltSize);
11687 SDValue Cond = DAG.getSetCC(DL,
11688 getSetCCResultType(N0.getValueType()),
11690 AddToWorklist(Cond.getNode());
11691 SDValue CstOffset = DAG.getSelect(DL, Zero.getValueType(),
11693 AddToWorklist(CstOffset.getNode());
11694 CPIdx = DAG.getNode(ISD::ADD, DL, CPIdx.getValueType(), CPIdx,
11696 AddToWorklist(CPIdx.getNode());
11697 return DAG.getLoad(TV->getValueType(0), DL, DAG.getEntryNode(), CPIdx,
11698 MachinePointerInfo::getConstantPool(), false,
11699 false, false, Alignment);
11704 // Check to see if we can perform the "gzip trick", transforming
11705 // (select_cc setlt X, 0, A, 0) -> (and (sra X, (sub size(X), 1), A)
11706 if (N1C && N3C && N3C->isNullValue() && CC == ISD::SETLT &&
11707 (N1C->isNullValue() || // (a < 0) ? b : 0
11708 (N1C->getAPIntValue() == 1 && N0 == N2))) { // (a < 1) ? a : 0
11709 EVT XType = N0.getValueType();
11710 EVT AType = N2.getValueType();
11711 if (XType.bitsGE(AType)) {
11712 // and (sra X, size(X)-1, A) -> "and (srl X, C2), A" iff A is a
11713 // single-bit constant.
11714 if (N2C && ((N2C->getAPIntValue() & (N2C->getAPIntValue()-1)) == 0)) {
11715 unsigned ShCtV = N2C->getAPIntValue().logBase2();
11716 ShCtV = XType.getSizeInBits()-ShCtV-1;
11717 SDValue ShCt = DAG.getConstant(ShCtV,
11718 getShiftAmountTy(N0.getValueType()));
11719 SDValue Shift = DAG.getNode(ISD::SRL, SDLoc(N0),
11721 AddToWorklist(Shift.getNode());
11723 if (XType.bitsGT(AType)) {
11724 Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift);
11725 AddToWorklist(Shift.getNode());
11728 return DAG.getNode(ISD::AND, DL, AType, Shift, N2);
11731 SDValue Shift = DAG.getNode(ISD::SRA, SDLoc(N0),
11733 DAG.getConstant(XType.getSizeInBits()-1,
11734 getShiftAmountTy(N0.getValueType())));
11735 AddToWorklist(Shift.getNode());
11737 if (XType.bitsGT(AType)) {
11738 Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift);
11739 AddToWorklist(Shift.getNode());
11742 return DAG.getNode(ISD::AND, DL, AType, Shift, N2);
11746 // fold (select_cc seteq (and x, y), 0, 0, A) -> (and (shr (shl x)) A)
11747 // where y is has a single bit set.
11748 // A plaintext description would be, we can turn the SELECT_CC into an AND
11749 // when the condition can be materialized as an all-ones register. Any
11750 // single bit-test can be materialized as an all-ones register with
11751 // shift-left and shift-right-arith.
11752 if (CC == ISD::SETEQ && N0->getOpcode() == ISD::AND &&
11753 N0->getValueType(0) == VT &&
11754 N1C && N1C->isNullValue() &&
11755 N2C && N2C->isNullValue()) {
11756 SDValue AndLHS = N0->getOperand(0);
11757 ConstantSDNode *ConstAndRHS = dyn_cast<ConstantSDNode>(N0->getOperand(1));
11758 if (ConstAndRHS && ConstAndRHS->getAPIntValue().countPopulation() == 1) {
11759 // Shift the tested bit over the sign bit.
11760 APInt AndMask = ConstAndRHS->getAPIntValue();
11762 DAG.getConstant(AndMask.countLeadingZeros(),
11763 getShiftAmountTy(AndLHS.getValueType()));
11764 SDValue Shl = DAG.getNode(ISD::SHL, SDLoc(N0), VT, AndLHS, ShlAmt);
11766 // Now arithmetic right shift it all the way over, so the result is either
11767 // all-ones, or zero.
11769 DAG.getConstant(AndMask.getBitWidth()-1,
11770 getShiftAmountTy(Shl.getValueType()));
11771 SDValue Shr = DAG.getNode(ISD::SRA, SDLoc(N0), VT, Shl, ShrAmt);
11773 return DAG.getNode(ISD::AND, DL, VT, Shr, N3);
11777 // fold select C, 16, 0 -> shl C, 4
11778 if (N2C && N3C && N3C->isNullValue() && N2C->getAPIntValue().isPowerOf2() &&
11779 TLI.getBooleanContents(N0.getValueType()) ==
11780 TargetLowering::ZeroOrOneBooleanContent) {
11782 // If the caller doesn't want us to simplify this into a zext of a compare,
11784 if (NotExtCompare && N2C->getAPIntValue() == 1)
11787 // Get a SetCC of the condition
11788 // NOTE: Don't create a SETCC if it's not legal on this target.
11789 if (!LegalOperations ||
11790 TLI.isOperationLegal(ISD::SETCC,
11791 LegalTypes ? getSetCCResultType(N0.getValueType()) : MVT::i1)) {
11793 // cast from setcc result type to select result type
11795 SCC = DAG.getSetCC(DL, getSetCCResultType(N0.getValueType()),
11797 if (N2.getValueType().bitsLT(SCC.getValueType()))
11798 Temp = DAG.getZeroExtendInReg(SCC, SDLoc(N2),
11799 N2.getValueType());
11801 Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2),
11802 N2.getValueType(), SCC);
11804 SCC = DAG.getSetCC(SDLoc(N0), MVT::i1, N0, N1, CC);
11805 Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2),
11806 N2.getValueType(), SCC);
11809 AddToWorklist(SCC.getNode());
11810 AddToWorklist(Temp.getNode());
11812 if (N2C->getAPIntValue() == 1)
11815 // shl setcc result by log2 n2c
11816 return DAG.getNode(
11817 ISD::SHL, DL, N2.getValueType(), Temp,
11818 DAG.getConstant(N2C->getAPIntValue().logBase2(),
11819 getShiftAmountTy(Temp.getValueType())));
11823 // Check to see if this is the equivalent of setcc
11824 // FIXME: Turn all of these into setcc if setcc if setcc is legal
11825 // otherwise, go ahead with the folds.
11826 if (0 && N3C && N3C->isNullValue() && N2C && (N2C->getAPIntValue() == 1ULL)) {
11827 EVT XType = N0.getValueType();
11828 if (!LegalOperations ||
11829 TLI.isOperationLegal(ISD::SETCC, getSetCCResultType(XType))) {
11830 SDValue Res = DAG.getSetCC(DL, getSetCCResultType(XType), N0, N1, CC);
11831 if (Res.getValueType() != VT)
11832 Res = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, Res);
11836 // fold (seteq X, 0) -> (srl (ctlz X, log2(size(X))))
11837 if (N1C && N1C->isNullValue() && CC == ISD::SETEQ &&
11838 (!LegalOperations ||
11839 TLI.isOperationLegal(ISD::CTLZ, XType))) {
11840 SDValue Ctlz = DAG.getNode(ISD::CTLZ, SDLoc(N0), XType, N0);
11841 return DAG.getNode(ISD::SRL, DL, XType, Ctlz,
11842 DAG.getConstant(Log2_32(XType.getSizeInBits()),
11843 getShiftAmountTy(Ctlz.getValueType())));
11845 // fold (setgt X, 0) -> (srl (and (-X, ~X), size(X)-1))
11846 if (N1C && N1C->isNullValue() && CC == ISD::SETGT) {
11847 SDValue NegN0 = DAG.getNode(ISD::SUB, SDLoc(N0),
11848 XType, DAG.getConstant(0, XType), N0);
11849 SDValue NotN0 = DAG.getNOT(SDLoc(N0), N0, XType);
11850 return DAG.getNode(ISD::SRL, DL, XType,
11851 DAG.getNode(ISD::AND, DL, XType, NegN0, NotN0),
11852 DAG.getConstant(XType.getSizeInBits()-1,
11853 getShiftAmountTy(XType)));
11855 // fold (setgt X, -1) -> (xor (srl (X, size(X)-1), 1))
11856 if (N1C && N1C->isAllOnesValue() && CC == ISD::SETGT) {
11857 SDValue Sign = DAG.getNode(ISD::SRL, SDLoc(N0), XType, N0,
11858 DAG.getConstant(XType.getSizeInBits()-1,
11859 getShiftAmountTy(N0.getValueType())));
11860 return DAG.getNode(ISD::XOR, DL, XType, Sign, DAG.getConstant(1, XType));
11864 // Check to see if this is an integer abs.
11865 // select_cc setg[te] X, 0, X, -X ->
11866 // select_cc setgt X, -1, X, -X ->
11867 // select_cc setl[te] X, 0, -X, X ->
11868 // select_cc setlt X, 1, -X, X ->
11869 // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
11871 ConstantSDNode *SubC = nullptr;
11872 if (((N1C->isNullValue() && (CC == ISD::SETGT || CC == ISD::SETGE)) ||
11873 (N1C->isAllOnesValue() && CC == ISD::SETGT)) &&
11874 N0 == N2 && N3.getOpcode() == ISD::SUB && N0 == N3.getOperand(1))
11875 SubC = dyn_cast<ConstantSDNode>(N3.getOperand(0));
11876 else if (((N1C->isNullValue() && (CC == ISD::SETLT || CC == ISD::SETLE)) ||
11877 (N1C->isOne() && CC == ISD::SETLT)) &&
11878 N0 == N3 && N2.getOpcode() == ISD::SUB && N0 == N2.getOperand(1))
11879 SubC = dyn_cast<ConstantSDNode>(N2.getOperand(0));
11881 EVT XType = N0.getValueType();
11882 if (SubC && SubC->isNullValue() && XType.isInteger()) {
11883 SDValue Shift = DAG.getNode(ISD::SRA, SDLoc(N0), XType,
11885 DAG.getConstant(XType.getSizeInBits()-1,
11886 getShiftAmountTy(N0.getValueType())));
11887 SDValue Add = DAG.getNode(ISD::ADD, SDLoc(N0),
11889 AddToWorklist(Shift.getNode());
11890 AddToWorklist(Add.getNode());
11891 return DAG.getNode(ISD::XOR, DL, XType, Add, Shift);
11898 /// This is a stub for TargetLowering::SimplifySetCC.
11899 SDValue DAGCombiner::SimplifySetCC(EVT VT, SDValue N0,
11900 SDValue N1, ISD::CondCode Cond,
11901 SDLoc DL, bool foldBooleans) {
11902 TargetLowering::DAGCombinerInfo
11903 DagCombineInfo(DAG, Level, false, this);
11904 return TLI.SimplifySetCC(VT, N0, N1, Cond, foldBooleans, DagCombineInfo, DL);
11907 /// Given an ISD::SDIV node expressing a divide by constant, return
11908 /// a DAG expression to select that will generate the same value by multiplying
11909 /// by a magic number.
11910 /// Ref: "Hacker's Delight" or "The PowerPC Compiler Writer's Guide".
11911 SDValue DAGCombiner::BuildSDIV(SDNode *N) {
11912 ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1));
11916 // Avoid division by zero.
11917 if (!C->getAPIntValue())
11920 std::vector<SDNode*> Built;
11922 TLI.BuildSDIV(N, C->getAPIntValue(), DAG, LegalOperations, &Built);
11924 for (SDNode *N : Built)
11929 /// Given an ISD::SDIV node expressing a divide by constant power of 2, return a
11930 /// DAG expression that will generate the same value by right shifting.
11931 SDValue DAGCombiner::BuildSDIVPow2(SDNode *N) {
11932 ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1));
11936 // Avoid division by zero.
11937 if (!C->getAPIntValue())
11940 std::vector<SDNode *> Built;
11941 SDValue S = TLI.BuildSDIVPow2(N, C->getAPIntValue(), DAG, &Built);
11943 for (SDNode *N : Built)
11948 /// Given an ISD::UDIV node expressing a divide by constant, return a DAG
11949 /// expression that will generate the same value by multiplying by a magic
11951 /// Ref: "Hacker's Delight" or "The PowerPC Compiler Writer's Guide".
11952 SDValue DAGCombiner::BuildUDIV(SDNode *N) {
11953 ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1));
11957 // Avoid division by zero.
11958 if (!C->getAPIntValue())
11961 std::vector<SDNode*> Built;
11963 TLI.BuildUDIV(N, C->getAPIntValue(), DAG, LegalOperations, &Built);
11965 for (SDNode *N : Built)
11970 SDValue DAGCombiner::BuildReciprocalEstimate(SDValue Op) {
11971 if (Level >= AfterLegalizeDAG)
11974 // Expose the DAG combiner to the target combiner implementations.
11975 TargetLowering::DAGCombinerInfo DCI(DAG, Level, false, this);
11977 unsigned Iterations = 0;
11978 if (SDValue Est = TLI.getRecipEstimate(Op, DCI, Iterations)) {
11980 // Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i)
11981 // For the reciprocal, we need to find the zero of the function:
11982 // F(X) = A X - 1 [which has a zero at X = 1/A]
11984 // X_{i+1} = X_i (2 - A X_i) = X_i + X_i (1 - A X_i) [this second form
11985 // does not require additional intermediate precision]
11986 EVT VT = Op.getValueType();
11988 SDValue FPOne = DAG.getConstantFP(1.0, VT);
11990 AddToWorklist(Est.getNode());
11992 // Newton iterations: Est = Est + Est (1 - Arg * Est)
11993 for (unsigned i = 0; i < Iterations; ++i) {
11994 SDValue NewEst = DAG.getNode(ISD::FMUL, DL, VT, Op, Est);
11995 AddToWorklist(NewEst.getNode());
11997 NewEst = DAG.getNode(ISD::FSUB, DL, VT, FPOne, NewEst);
11998 AddToWorklist(NewEst.getNode());
12000 NewEst = DAG.getNode(ISD::FMUL, DL, VT, Est, NewEst);
12001 AddToWorklist(NewEst.getNode());
12003 Est = DAG.getNode(ISD::FADD, DL, VT, Est, NewEst);
12004 AddToWorklist(Est.getNode());
12013 /// Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i)
12014 /// For the reciprocal sqrt, we need to find the zero of the function:
12015 /// F(X) = 1/X^2 - A [which has a zero at X = 1/sqrt(A)]
12017 /// X_{i+1} = X_i (1.5 - A X_i^2 / 2)
12018 /// As a result, we precompute A/2 prior to the iteration loop.
12019 SDValue DAGCombiner::BuildRsqrtNROneConst(SDValue Arg, SDValue Est,
12020 unsigned Iterations) {
12021 EVT VT = Arg.getValueType();
12023 SDValue ThreeHalves = DAG.getConstantFP(1.5, VT);
12025 // We now need 0.5 * Arg which we can write as (1.5 * Arg - Arg) so that
12026 // this entire sequence requires only one FP constant.
12027 SDValue HalfArg = DAG.getNode(ISD::FMUL, DL, VT, ThreeHalves, Arg);
12028 AddToWorklist(HalfArg.getNode());
12030 HalfArg = DAG.getNode(ISD::FSUB, DL, VT, HalfArg, Arg);
12031 AddToWorklist(HalfArg.getNode());
12033 // Newton iterations: Est = Est * (1.5 - HalfArg * Est * Est)
12034 for (unsigned i = 0; i < Iterations; ++i) {
12035 SDValue NewEst = DAG.getNode(ISD::FMUL, DL, VT, Est, Est);
12036 AddToWorklist(NewEst.getNode());
12038 NewEst = DAG.getNode(ISD::FMUL, DL, VT, HalfArg, NewEst);
12039 AddToWorklist(NewEst.getNode());
12041 NewEst = DAG.getNode(ISD::FSUB, DL, VT, ThreeHalves, NewEst);
12042 AddToWorklist(NewEst.getNode());
12044 Est = DAG.getNode(ISD::FMUL, DL, VT, Est, NewEst);
12045 AddToWorklist(Est.getNode());
12050 /// Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i)
12051 /// For the reciprocal sqrt, we need to find the zero of the function:
12052 /// F(X) = 1/X^2 - A [which has a zero at X = 1/sqrt(A)]
12054 /// X_{i+1} = (-0.5 * X_i) * (A * X_i * X_i + (-3.0))
12055 SDValue DAGCombiner::BuildRsqrtNRTwoConst(SDValue Arg, SDValue Est,
12056 unsigned Iterations) {
12057 EVT VT = Arg.getValueType();
12059 SDValue MinusThree = DAG.getConstantFP(-3.0, VT);
12060 SDValue MinusHalf = DAG.getConstantFP(-0.5, VT);
12062 // Newton iterations: Est = -0.5 * Est * (-3.0 + Arg * Est * Est)
12063 for (unsigned i = 0; i < Iterations; ++i) {
12064 SDValue HalfEst = DAG.getNode(ISD::FMUL, DL, VT, Est, MinusHalf);
12065 AddToWorklist(HalfEst.getNode());
12067 Est = DAG.getNode(ISD::FMUL, DL, VT, Est, Est);
12068 AddToWorklist(Est.getNode());
12070 Est = DAG.getNode(ISD::FMUL, DL, VT, Est, Arg);
12071 AddToWorklist(Est.getNode());
12073 Est = DAG.getNode(ISD::FADD, DL, VT, Est, MinusThree);
12074 AddToWorklist(Est.getNode());
12076 Est = DAG.getNode(ISD::FMUL, DL, VT, Est, HalfEst);
12077 AddToWorklist(Est.getNode());
12082 SDValue DAGCombiner::BuildRsqrtEstimate(SDValue Op) {
12083 if (Level >= AfterLegalizeDAG)
12086 // Expose the DAG combiner to the target combiner implementations.
12087 TargetLowering::DAGCombinerInfo DCI(DAG, Level, false, this);
12088 unsigned Iterations = 0;
12089 bool UseOneConstNR = false;
12090 if (SDValue Est = TLI.getRsqrtEstimate(Op, DCI, Iterations, UseOneConstNR)) {
12091 AddToWorklist(Est.getNode());
12093 Est = UseOneConstNR ?
12094 BuildRsqrtNROneConst(Op, Est, Iterations) :
12095 BuildRsqrtNRTwoConst(Op, Est, Iterations);
12103 /// Return true if base is a frame index, which is known not to alias with
12104 /// anything but itself. Provides base object and offset as results.
12105 static bool FindBaseOffset(SDValue Ptr, SDValue &Base, int64_t &Offset,
12106 const GlobalValue *&GV, const void *&CV) {
12107 // Assume it is a primitive operation.
12108 Base = Ptr; Offset = 0; GV = nullptr; CV = nullptr;
12110 // If it's an adding a simple constant then integrate the offset.
12111 if (Base.getOpcode() == ISD::ADD) {
12112 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Base.getOperand(1))) {
12113 Base = Base.getOperand(0);
12114 Offset += C->getZExtValue();
12118 // Return the underlying GlobalValue, and update the Offset. Return false
12119 // for GlobalAddressSDNode since the same GlobalAddress may be represented
12120 // by multiple nodes with different offsets.
12121 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Base)) {
12122 GV = G->getGlobal();
12123 Offset += G->getOffset();
12127 // Return the underlying Constant value, and update the Offset. Return false
12128 // for ConstantSDNodes since the same constant pool entry may be represented
12129 // by multiple nodes with different offsets.
12130 if (ConstantPoolSDNode *C = dyn_cast<ConstantPoolSDNode>(Base)) {
12131 CV = C->isMachineConstantPoolEntry() ? (const void *)C->getMachineCPVal()
12132 : (const void *)C->getConstVal();
12133 Offset += C->getOffset();
12136 // If it's any of the following then it can't alias with anything but itself.
12137 return isa<FrameIndexSDNode>(Base);
12140 /// Return true if there is any possibility that the two addresses overlap.
12141 bool DAGCombiner::isAlias(LSBaseSDNode *Op0, LSBaseSDNode *Op1) const {
12142 // If they are the same then they must be aliases.
12143 if (Op0->getBasePtr() == Op1->getBasePtr()) return true;
12145 // If they are both volatile then they cannot be reordered.
12146 if (Op0->isVolatile() && Op1->isVolatile()) return true;
12148 // Gather base node and offset information.
12149 SDValue Base1, Base2;
12150 int64_t Offset1, Offset2;
12151 const GlobalValue *GV1, *GV2;
12152 const void *CV1, *CV2;
12153 bool isFrameIndex1 = FindBaseOffset(Op0->getBasePtr(),
12154 Base1, Offset1, GV1, CV1);
12155 bool isFrameIndex2 = FindBaseOffset(Op1->getBasePtr(),
12156 Base2, Offset2, GV2, CV2);
12158 // If they have a same base address then check to see if they overlap.
12159 if (Base1 == Base2 || (GV1 && (GV1 == GV2)) || (CV1 && (CV1 == CV2)))
12160 return !((Offset1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= Offset2 ||
12161 (Offset2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= Offset1);
12163 // It is possible for different frame indices to alias each other, mostly
12164 // when tail call optimization reuses return address slots for arguments.
12165 // To catch this case, look up the actual index of frame indices to compute
12166 // the real alias relationship.
12167 if (isFrameIndex1 && isFrameIndex2) {
12168 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
12169 Offset1 += MFI->getObjectOffset(cast<FrameIndexSDNode>(Base1)->getIndex());
12170 Offset2 += MFI->getObjectOffset(cast<FrameIndexSDNode>(Base2)->getIndex());
12171 return !((Offset1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= Offset2 ||
12172 (Offset2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= Offset1);
12175 // Otherwise, if we know what the bases are, and they aren't identical, then
12176 // we know they cannot alias.
12177 if ((isFrameIndex1 || CV1 || GV1) && (isFrameIndex2 || CV2 || GV2))
12180 // If we know required SrcValue1 and SrcValue2 have relatively large alignment
12181 // compared to the size and offset of the access, we may be able to prove they
12182 // do not alias. This check is conservative for now to catch cases created by
12183 // splitting vector types.
12184 if ((Op0->getOriginalAlignment() == Op1->getOriginalAlignment()) &&
12185 (Op0->getSrcValueOffset() != Op1->getSrcValueOffset()) &&
12186 (Op0->getMemoryVT().getSizeInBits() >> 3 ==
12187 Op1->getMemoryVT().getSizeInBits() >> 3) &&
12188 (Op0->getOriginalAlignment() > Op0->getMemoryVT().getSizeInBits()) >> 3) {
12189 int64_t OffAlign1 = Op0->getSrcValueOffset() % Op0->getOriginalAlignment();
12190 int64_t OffAlign2 = Op1->getSrcValueOffset() % Op1->getOriginalAlignment();
12192 // There is no overlap between these relatively aligned accesses of similar
12193 // size, return no alias.
12194 if ((OffAlign1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= OffAlign2 ||
12195 (OffAlign2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= OffAlign1)
12199 bool UseAA = CombinerGlobalAA.getNumOccurrences() > 0
12201 : DAG.getSubtarget().useAA();
12203 if (CombinerAAOnlyFunc.getNumOccurrences() &&
12204 CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
12208 Op0->getMemOperand()->getValue() && Op1->getMemOperand()->getValue()) {
12209 // Use alias analysis information.
12210 int64_t MinOffset = std::min(Op0->getSrcValueOffset(),
12211 Op1->getSrcValueOffset());
12212 int64_t Overlap1 = (Op0->getMemoryVT().getSizeInBits() >> 3) +
12213 Op0->getSrcValueOffset() - MinOffset;
12214 int64_t Overlap2 = (Op1->getMemoryVT().getSizeInBits() >> 3) +
12215 Op1->getSrcValueOffset() - MinOffset;
12216 AliasAnalysis::AliasResult AAResult =
12217 AA.alias(AliasAnalysis::Location(Op0->getMemOperand()->getValue(),
12219 UseTBAA ? Op0->getAAInfo() : AAMDNodes()),
12220 AliasAnalysis::Location(Op1->getMemOperand()->getValue(),
12222 UseTBAA ? Op1->getAAInfo() : AAMDNodes()));
12223 if (AAResult == AliasAnalysis::NoAlias)
12227 // Otherwise we have to assume they alias.
12231 /// Walk up chain skipping non-aliasing memory nodes,
12232 /// looking for aliasing nodes and adding them to the Aliases vector.
12233 void DAGCombiner::GatherAllAliases(SDNode *N, SDValue OriginalChain,
12234 SmallVectorImpl<SDValue> &Aliases) {
12235 SmallVector<SDValue, 8> Chains; // List of chains to visit.
12236 SmallPtrSet<SDNode *, 16> Visited; // Visited node set.
12238 // Get alias information for node.
12239 bool IsLoad = isa<LoadSDNode>(N) && !cast<LSBaseSDNode>(N)->isVolatile();
12242 Chains.push_back(OriginalChain);
12243 unsigned Depth = 0;
12245 // Look at each chain and determine if it is an alias. If so, add it to the
12246 // aliases list. If not, then continue up the chain looking for the next
12248 while (!Chains.empty()) {
12249 SDValue Chain = Chains.back();
12252 // For TokenFactor nodes, look at each operand and only continue up the
12253 // chain until we find two aliases. If we've seen two aliases, assume we'll
12254 // find more and revert to original chain since the xform is unlikely to be
12257 // FIXME: The depth check could be made to return the last non-aliasing
12258 // chain we found before we hit a tokenfactor rather than the original
12260 if (Depth > 6 || Aliases.size() == 2) {
12262 Aliases.push_back(OriginalChain);
12266 // Don't bother if we've been before.
12267 if (!Visited.insert(Chain.getNode()))
12270 switch (Chain.getOpcode()) {
12271 case ISD::EntryToken:
12272 // Entry token is ideal chain operand, but handled in FindBetterChain.
12277 // Get alias information for Chain.
12278 bool IsOpLoad = isa<LoadSDNode>(Chain.getNode()) &&
12279 !cast<LSBaseSDNode>(Chain.getNode())->isVolatile();
12281 // If chain is alias then stop here.
12282 if (!(IsLoad && IsOpLoad) &&
12283 isAlias(cast<LSBaseSDNode>(N), cast<LSBaseSDNode>(Chain.getNode()))) {
12284 Aliases.push_back(Chain);
12286 // Look further up the chain.
12287 Chains.push_back(Chain.getOperand(0));
12293 case ISD::TokenFactor:
12294 // We have to check each of the operands of the token factor for "small"
12295 // token factors, so we queue them up. Adding the operands to the queue
12296 // (stack) in reverse order maintains the original order and increases the
12297 // likelihood that getNode will find a matching token factor (CSE.)
12298 if (Chain.getNumOperands() > 16) {
12299 Aliases.push_back(Chain);
12302 for (unsigned n = Chain.getNumOperands(); n;)
12303 Chains.push_back(Chain.getOperand(--n));
12308 // For all other instructions we will just have to take what we can get.
12309 Aliases.push_back(Chain);
12314 // We need to be careful here to also search for aliases through the
12315 // value operand of a store, etc. Consider the following situation:
12317 // L1 = load Token1, %52
12318 // S1 = store Token1, L1, %51
12319 // L2 = load Token1, %52+8
12320 // S2 = store Token1, L2, %51+8
12321 // Token2 = Token(S1, S2)
12322 // L3 = load Token2, %53
12323 // S3 = store Token2, L3, %52
12324 // L4 = load Token2, %53+8
12325 // S4 = store Token2, L4, %52+8
12326 // If we search for aliases of S3 (which loads address %52), and we look
12327 // only through the chain, then we'll miss the trivial dependence on L1
12328 // (which also loads from %52). We then might change all loads and
12329 // stores to use Token1 as their chain operand, which could result in
12330 // copying %53 into %52 before copying %52 into %51 (which should
12333 // The problem is, however, that searching for such data dependencies
12334 // can become expensive, and the cost is not directly related to the
12335 // chain depth. Instead, we'll rule out such configurations here by
12336 // insisting that we've visited all chain users (except for users
12337 // of the original chain, which is not necessary). When doing this,
12338 // we need to look through nodes we don't care about (otherwise, things
12339 // like register copies will interfere with trivial cases).
12341 SmallVector<const SDNode *, 16> Worklist;
12342 for (const SDNode *N : Visited)
12343 if (N != OriginalChain.getNode())
12344 Worklist.push_back(N);
12346 while (!Worklist.empty()) {
12347 const SDNode *M = Worklist.pop_back_val();
12349 // We have already visited M, and want to make sure we've visited any uses
12350 // of M that we care about. For uses that we've not visisted, and don't
12351 // care about, queue them to the worklist.
12353 for (SDNode::use_iterator UI = M->use_begin(),
12354 UIE = M->use_end(); UI != UIE; ++UI)
12355 if (UI.getUse().getValueType() == MVT::Other && Visited.insert(*UI)) {
12356 if (isa<MemIntrinsicSDNode>(*UI) || isa<MemSDNode>(*UI)) {
12357 // We've not visited this use, and we care about it (it could have an
12358 // ordering dependency with the original node).
12360 Aliases.push_back(OriginalChain);
12364 // We've not visited this use, but we don't care about it. Mark it as
12365 // visited and enqueue it to the worklist.
12366 Worklist.push_back(*UI);
12371 /// Walk up chain skipping non-aliasing memory nodes, looking for a better chain
12372 /// (aliasing node.)
12373 SDValue DAGCombiner::FindBetterChain(SDNode *N, SDValue OldChain) {
12374 SmallVector<SDValue, 8> Aliases; // Ops for replacing token factor.
12376 // Accumulate all the aliases to this node.
12377 GatherAllAliases(N, OldChain, Aliases);
12379 // If no operands then chain to entry token.
12380 if (Aliases.size() == 0)
12381 return DAG.getEntryNode();
12383 // If a single operand then chain to it. We don't need to revisit it.
12384 if (Aliases.size() == 1)
12387 // Construct a custom tailored token factor.
12388 return DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other, Aliases);
12391 /// This is the entry point for the file.
12392 void SelectionDAG::Combine(CombineLevel Level, AliasAnalysis &AA,
12393 CodeGenOpt::Level OptLevel) {
12394 /// This is the main entry point to this class.
12395 DAGCombiner(*this, AA, OptLevel).Run(Level);