1 //===-- DAGCombiner.cpp - Implement a DAG node combiner -------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This pass combines dag nodes to form fewer, simpler DAG nodes. It can be run
11 // both before and after the DAG is legalized.
13 // This pass is not a substitute for the LLVM IR instcombine pass. This pass is
14 // primarily intended to handle simplification opportunities that are implicit
15 // in the LLVM IR and exposed by the various codegen lowering phases.
17 //===----------------------------------------------------------------------===//
19 #define DEBUG_TYPE "dagcombine"
20 #include "llvm/CodeGen/SelectionDAG.h"
21 #include "llvm/ADT/SmallPtrSet.h"
22 #include "llvm/ADT/Statistic.h"
23 #include "llvm/Analysis/AliasAnalysis.h"
24 #include "llvm/CodeGen/MachineFrameInfo.h"
25 #include "llvm/CodeGen/MachineFunction.h"
26 #include "llvm/IR/DataLayout.h"
27 #include "llvm/IR/DerivedTypes.h"
28 #include "llvm/IR/Function.h"
29 #include "llvm/IR/LLVMContext.h"
30 #include "llvm/Support/CommandLine.h"
31 #include "llvm/Support/Debug.h"
32 #include "llvm/Support/ErrorHandling.h"
33 #include "llvm/Support/MathExtras.h"
34 #include "llvm/Support/raw_ostream.h"
35 #include "llvm/Target/TargetLowering.h"
36 #include "llvm/Target/TargetMachine.h"
37 #include "llvm/Target/TargetOptions.h"
38 #include "llvm/Target/TargetRegisterInfo.h"
39 #include "llvm/Target/TargetSubtargetInfo.h"
43 STATISTIC(NodesCombined , "Number of dag nodes combined");
44 STATISTIC(PreIndexedNodes , "Number of pre-indexed nodes created");
45 STATISTIC(PostIndexedNodes, "Number of post-indexed nodes created");
46 STATISTIC(OpsNarrowed , "Number of load/op/store narrowed");
47 STATISTIC(LdStFP2Int , "Number of fp load/store pairs transformed to int");
48 STATISTIC(SlicedLoads, "Number of load sliced");
52 CombinerAA("combiner-alias-analysis", cl::Hidden,
53 cl::desc("Enable DAG combiner alias-analysis heuristics"));
56 CombinerGlobalAA("combiner-global-alias-analysis", cl::Hidden,
57 cl::desc("Enable DAG combiner's use of IR alias analysis"));
59 // FIXME: Enable the use of TBAA. There are two known issues preventing this:
60 // 1. Stack coloring does not update TBAA when merging allocas
61 // 2. CGP inserts ptrtoint/inttoptr pairs when sinking address computations.
62 // Because BasicAA does not handle inttoptr, we'll often miss basic type
63 // punning idioms that we need to catch so we don't miscompile real-world
66 UseTBAA("combiner-use-tbaa", cl::Hidden, cl::init(false),
67 cl::desc("Enable DAG combiner's use of TBAA"));
70 static cl::opt<std::string>
71 CombinerAAOnlyFunc("combiner-aa-only-func", cl::Hidden,
72 cl::desc("Only use DAG-combiner alias analysis in this"
76 /// Hidden option to stress test load slicing, i.e., when this option
77 /// is enabled, load slicing bypasses most of its profitability guards.
79 StressLoadSlicing("combiner-stress-load-slicing", cl::Hidden,
80 cl::desc("Bypass the profitability model of load "
84 //------------------------------ DAGCombiner ---------------------------------//
88 const TargetLowering &TLI;
90 CodeGenOpt::Level OptLevel;
95 // Worklist of all of the nodes that need to be simplified.
97 // This has the semantics that when adding to the worklist,
98 // the item added must be next to be processed. It should
99 // also only appear once. The naive approach to this takes
102 // To reduce the insert/remove time to logarithmic, we use
103 // a set and a vector to maintain our worklist.
105 // The set contains the items on the worklist, but does not
106 // maintain the order they should be visited.
108 // The vector maintains the order nodes should be visited, but may
109 // contain duplicate or removed nodes. When choosing a node to
110 // visit, we pop off the order stack until we find an item that is
111 // also in the contents set. All operations are O(log N).
112 SmallPtrSet<SDNode*, 64> WorkListContents;
113 SmallVector<SDNode*, 64> WorkListOrder;
115 // AA - Used for DAG load/store alias analysis.
118 /// AddUsersToWorkList - When an instruction is simplified, add all users of
119 /// the instruction to the work lists because they might get more simplified
122 void AddUsersToWorkList(SDNode *N) {
123 for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
128 /// visit - call the node-specific routine that knows how to fold each
129 /// particular type of node.
130 SDValue visit(SDNode *N);
133 /// AddToWorkList - Add to the work list making sure its instance is at the
134 /// back (next to be processed.)
135 void AddToWorkList(SDNode *N) {
136 WorkListContents.insert(N);
137 WorkListOrder.push_back(N);
140 /// removeFromWorkList - remove all instances of N from the worklist.
142 void removeFromWorkList(SDNode *N) {
143 WorkListContents.erase(N);
146 SDValue CombineTo(SDNode *N, const SDValue *To, unsigned NumTo,
149 SDValue CombineTo(SDNode *N, SDValue Res, bool AddTo = true) {
150 return CombineTo(N, &Res, 1, AddTo);
153 SDValue CombineTo(SDNode *N, SDValue Res0, SDValue Res1,
155 SDValue To[] = { Res0, Res1 };
156 return CombineTo(N, To, 2, AddTo);
159 void CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO);
163 /// SimplifyDemandedBits - Check the specified integer node value to see if
164 /// it can be simplified or if things it uses can be simplified by bit
165 /// propagation. If so, return true.
166 bool SimplifyDemandedBits(SDValue Op) {
167 unsigned BitWidth = Op.getValueType().getScalarType().getSizeInBits();
168 APInt Demanded = APInt::getAllOnesValue(BitWidth);
169 return SimplifyDemandedBits(Op, Demanded);
172 bool SimplifyDemandedBits(SDValue Op, const APInt &Demanded);
174 bool CombineToPreIndexedLoadStore(SDNode *N);
175 bool CombineToPostIndexedLoadStore(SDNode *N);
176 bool SliceUpLoad(SDNode *N);
178 void ReplaceLoadWithPromotedLoad(SDNode *Load, SDNode *ExtLoad);
179 SDValue PromoteOperand(SDValue Op, EVT PVT, bool &Replace);
180 SDValue SExtPromoteOperand(SDValue Op, EVT PVT);
181 SDValue ZExtPromoteOperand(SDValue Op, EVT PVT);
182 SDValue PromoteIntBinOp(SDValue Op);
183 SDValue PromoteIntShiftOp(SDValue Op);
184 SDValue PromoteExtend(SDValue Op);
185 bool PromoteLoad(SDValue Op);
187 void ExtendSetCCUses(const SmallVectorImpl<SDNode *> &SetCCs,
188 SDValue Trunc, SDValue ExtLoad, SDLoc DL,
189 ISD::NodeType ExtType);
191 /// combine - call the node-specific routine that knows how to fold each
192 /// particular type of node. If that doesn't do anything, try the
193 /// target-specific DAG combines.
194 SDValue combine(SDNode *N);
196 // Visitation implementation - Implement dag node combining for different
197 // node types. The semantics are as follows:
199 // SDValue.getNode() == 0 - No change was made
200 // SDValue.getNode() == N - N was replaced, is dead and has been handled.
201 // otherwise - N should be replaced by the returned Operand.
203 SDValue visitTokenFactor(SDNode *N);
204 SDValue visitMERGE_VALUES(SDNode *N);
205 SDValue visitADD(SDNode *N);
206 SDValue visitSUB(SDNode *N);
207 SDValue visitADDC(SDNode *N);
208 SDValue visitSUBC(SDNode *N);
209 SDValue visitADDE(SDNode *N);
210 SDValue visitSUBE(SDNode *N);
211 SDValue visitMUL(SDNode *N);
212 SDValue visitSDIV(SDNode *N);
213 SDValue visitUDIV(SDNode *N);
214 SDValue visitSREM(SDNode *N);
215 SDValue visitUREM(SDNode *N);
216 SDValue visitMULHU(SDNode *N);
217 SDValue visitMULHS(SDNode *N);
218 SDValue visitSMUL_LOHI(SDNode *N);
219 SDValue visitUMUL_LOHI(SDNode *N);
220 SDValue visitSMULO(SDNode *N);
221 SDValue visitUMULO(SDNode *N);
222 SDValue visitSDIVREM(SDNode *N);
223 SDValue visitUDIVREM(SDNode *N);
224 SDValue visitAND(SDNode *N);
225 SDValue visitOR(SDNode *N);
226 SDValue visitXOR(SDNode *N);
227 SDValue SimplifyVBinOp(SDNode *N);
228 SDValue SimplifyVUnaryOp(SDNode *N);
229 SDValue visitSHL(SDNode *N);
230 SDValue visitSRA(SDNode *N);
231 SDValue visitSRL(SDNode *N);
232 SDValue visitCTLZ(SDNode *N);
233 SDValue visitCTLZ_ZERO_UNDEF(SDNode *N);
234 SDValue visitCTTZ(SDNode *N);
235 SDValue visitCTTZ_ZERO_UNDEF(SDNode *N);
236 SDValue visitCTPOP(SDNode *N);
237 SDValue visitSELECT(SDNode *N);
238 SDValue visitVSELECT(SDNode *N);
239 SDValue visitSELECT_CC(SDNode *N);
240 SDValue visitSETCC(SDNode *N);
241 SDValue visitSIGN_EXTEND(SDNode *N);
242 SDValue visitZERO_EXTEND(SDNode *N);
243 SDValue visitANY_EXTEND(SDNode *N);
244 SDValue visitSIGN_EXTEND_INREG(SDNode *N);
245 SDValue visitTRUNCATE(SDNode *N);
246 SDValue visitBITCAST(SDNode *N);
247 SDValue visitBUILD_PAIR(SDNode *N);
248 SDValue visitFADD(SDNode *N);
249 SDValue visitFSUB(SDNode *N);
250 SDValue visitFMUL(SDNode *N);
251 SDValue visitFMA(SDNode *N);
252 SDValue visitFDIV(SDNode *N);
253 SDValue visitFREM(SDNode *N);
254 SDValue visitFCOPYSIGN(SDNode *N);
255 SDValue visitSINT_TO_FP(SDNode *N);
256 SDValue visitUINT_TO_FP(SDNode *N);
257 SDValue visitFP_TO_SINT(SDNode *N);
258 SDValue visitFP_TO_UINT(SDNode *N);
259 SDValue visitFP_ROUND(SDNode *N);
260 SDValue visitFP_ROUND_INREG(SDNode *N);
261 SDValue visitFP_EXTEND(SDNode *N);
262 SDValue visitFNEG(SDNode *N);
263 SDValue visitFABS(SDNode *N);
264 SDValue visitFCEIL(SDNode *N);
265 SDValue visitFTRUNC(SDNode *N);
266 SDValue visitFFLOOR(SDNode *N);
267 SDValue visitBRCOND(SDNode *N);
268 SDValue visitBR_CC(SDNode *N);
269 SDValue visitLOAD(SDNode *N);
270 SDValue visitSTORE(SDNode *N);
271 SDValue visitINSERT_VECTOR_ELT(SDNode *N);
272 SDValue visitEXTRACT_VECTOR_ELT(SDNode *N);
273 SDValue visitBUILD_VECTOR(SDNode *N);
274 SDValue visitCONCAT_VECTORS(SDNode *N);
275 SDValue visitEXTRACT_SUBVECTOR(SDNode *N);
276 SDValue visitVECTOR_SHUFFLE(SDNode *N);
277 SDValue visitINSERT_SUBVECTOR(SDNode *N);
279 SDValue XformToShuffleWithZero(SDNode *N);
280 SDValue ReassociateOps(unsigned Opc, SDLoc DL, SDValue LHS, SDValue RHS);
282 SDValue visitShiftByConstant(SDNode *N, unsigned Amt);
284 bool SimplifySelectOps(SDNode *SELECT, SDValue LHS, SDValue RHS);
285 SDValue SimplifyBinOpWithSameOpcodeHands(SDNode *N);
286 SDValue SimplifySelect(SDLoc DL, SDValue N0, SDValue N1, SDValue N2);
287 SDValue SimplifySelectCC(SDLoc DL, SDValue N0, SDValue N1, SDValue N2,
288 SDValue N3, ISD::CondCode CC,
289 bool NotExtCompare = false);
290 SDValue SimplifySetCC(EVT VT, SDValue N0, SDValue N1, ISD::CondCode Cond,
291 SDLoc DL, bool foldBooleans = true);
292 SDValue SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp,
294 SDValue CombineConsecutiveLoads(SDNode *N, EVT VT);
295 SDValue ConstantFoldBITCASTofBUILD_VECTOR(SDNode *, EVT);
296 SDValue BuildSDIV(SDNode *N);
297 SDValue BuildUDIV(SDNode *N);
298 SDValue MatchBSwapHWordLow(SDNode *N, SDValue N0, SDValue N1,
299 bool DemandHighBits = true);
300 SDValue MatchBSwapHWord(SDNode *N, SDValue N0, SDValue N1);
301 SDNode *MatchRotatePosNeg(SDValue Shifted, SDValue Pos, SDValue Neg,
302 SDValue InnerPos, SDValue InnerNeg,
303 unsigned PosOpcode, unsigned NegOpcode,
305 SDNode *MatchRotate(SDValue LHS, SDValue RHS, SDLoc DL);
306 SDValue ReduceLoadWidth(SDNode *N);
307 SDValue ReduceLoadOpStoreWidth(SDNode *N);
308 SDValue TransformFPLoadStorePair(SDNode *N);
309 SDValue reduceBuildVecExtToExtBuildVec(SDNode *N);
310 SDValue reduceBuildVecConvertToConvertBuildVec(SDNode *N);
312 SDValue GetDemandedBits(SDValue V, const APInt &Mask);
314 /// GatherAllAliases - Walk up chain skipping non-aliasing memory nodes,
315 /// looking for aliasing nodes and adding them to the Aliases vector.
316 void GatherAllAliases(SDNode *N, SDValue OriginalChain,
317 SmallVectorImpl<SDValue> &Aliases);
319 /// isAlias - Return true if there is any possibility that the two addresses
321 bool isAlias(SDValue Ptr1, int64_t Size1, bool IsVolatile1,
322 const Value *SrcValue1, int SrcValueOffset1,
323 unsigned SrcValueAlign1,
324 const MDNode *TBAAInfo1,
325 SDValue Ptr2, int64_t Size2, bool IsVolatile2,
326 const Value *SrcValue2, int SrcValueOffset2,
327 unsigned SrcValueAlign2,
328 const MDNode *TBAAInfo2) const;
330 /// isAlias - Return true if there is any possibility that the two addresses
332 bool isAlias(LSBaseSDNode *Op0, LSBaseSDNode *Op1);
334 /// FindAliasInfo - Extracts the relevant alias information from the memory
335 /// node. Returns true if the operand was a load.
336 bool FindAliasInfo(SDNode *N,
337 SDValue &Ptr, int64_t &Size, bool &IsVolatile,
338 const Value *&SrcValue, int &SrcValueOffset,
339 unsigned &SrcValueAlignment,
340 const MDNode *&TBAAInfo) const;
342 /// FindBetterChain - Walk up chain skipping non-aliasing memory nodes,
343 /// looking for a better chain (aliasing node.)
344 SDValue FindBetterChain(SDNode *N, SDValue Chain);
346 /// Merge consecutive store operations into a wide store.
347 /// This optimization uses wide integers or vectors when possible.
348 /// \return True if some memory operations were changed.
349 bool MergeConsecutiveStores(StoreSDNode *N);
351 /// \brief Try to transform a truncation where C is a constant:
352 /// (trunc (and X, C)) -> (and (trunc X), (trunc C))
354 /// \p N needs to be a truncation and its first operand an AND. Other
355 /// requirements are checked by the function (e.g. that trunc is
356 /// single-use) and if missed an empty SDValue is returned.
357 SDValue distributeTruncateThroughAnd(SDNode *N);
360 DAGCombiner(SelectionDAG &D, AliasAnalysis &A, CodeGenOpt::Level OL)
361 : DAG(D), TLI(D.getTargetLoweringInfo()), Level(BeforeLegalizeTypes),
362 OptLevel(OL), LegalOperations(false), LegalTypes(false), AA(A) {
363 AttributeSet FnAttrs =
364 DAG.getMachineFunction().getFunction()->getAttributes();
366 FnAttrs.hasAttribute(AttributeSet::FunctionIndex,
367 Attribute::OptimizeForSize) ||
368 FnAttrs.hasAttribute(AttributeSet::FunctionIndex, Attribute::MinSize);
371 /// Run - runs the dag combiner on all nodes in the work list
372 void Run(CombineLevel AtLevel);
374 SelectionDAG &getDAG() const { return DAG; }
376 /// getShiftAmountTy - Returns a type large enough to hold any valid
377 /// shift amount - before type legalization these can be huge.
378 EVT getShiftAmountTy(EVT LHSTy) {
379 assert(LHSTy.isInteger() && "Shift amount is not an integer type!");
380 if (LHSTy.isVector())
382 return LegalTypes ? TLI.getScalarShiftAmountTy(LHSTy)
383 : TLI.getPointerTy();
386 /// isTypeLegal - This method returns true if we are running before type
387 /// legalization or if the specified VT is legal.
388 bool isTypeLegal(const EVT &VT) {
389 if (!LegalTypes) return true;
390 return TLI.isTypeLegal(VT);
393 /// getSetCCResultType - Convenience wrapper around
394 /// TargetLowering::getSetCCResultType
395 EVT getSetCCResultType(EVT VT) const {
396 return TLI.getSetCCResultType(*DAG.getContext(), VT);
403 /// WorkListRemover - This class is a DAGUpdateListener that removes any deleted
404 /// nodes from the worklist.
405 class WorkListRemover : public SelectionDAG::DAGUpdateListener {
408 explicit WorkListRemover(DAGCombiner &dc)
409 : SelectionDAG::DAGUpdateListener(dc.getDAG()), DC(dc) {}
411 virtual void NodeDeleted(SDNode *N, SDNode *E) {
412 DC.removeFromWorkList(N);
417 //===----------------------------------------------------------------------===//
418 // TargetLowering::DAGCombinerInfo implementation
419 //===----------------------------------------------------------------------===//
421 void TargetLowering::DAGCombinerInfo::AddToWorklist(SDNode *N) {
422 ((DAGCombiner*)DC)->AddToWorkList(N);
425 void TargetLowering::DAGCombinerInfo::RemoveFromWorklist(SDNode *N) {
426 ((DAGCombiner*)DC)->removeFromWorkList(N);
429 SDValue TargetLowering::DAGCombinerInfo::
430 CombineTo(SDNode *N, const std::vector<SDValue> &To, bool AddTo) {
431 return ((DAGCombiner*)DC)->CombineTo(N, &To[0], To.size(), AddTo);
434 SDValue TargetLowering::DAGCombinerInfo::
435 CombineTo(SDNode *N, SDValue Res, bool AddTo) {
436 return ((DAGCombiner*)DC)->CombineTo(N, Res, AddTo);
440 SDValue TargetLowering::DAGCombinerInfo::
441 CombineTo(SDNode *N, SDValue Res0, SDValue Res1, bool AddTo) {
442 return ((DAGCombiner*)DC)->CombineTo(N, Res0, Res1, AddTo);
445 void TargetLowering::DAGCombinerInfo::
446 CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) {
447 return ((DAGCombiner*)DC)->CommitTargetLoweringOpt(TLO);
450 //===----------------------------------------------------------------------===//
452 //===----------------------------------------------------------------------===//
454 /// isNegatibleForFree - Return 1 if we can compute the negated form of the
455 /// specified expression for the same cost as the expression itself, or 2 if we
456 /// can compute the negated form more cheaply than the expression itself.
457 static char isNegatibleForFree(SDValue Op, bool LegalOperations,
458 const TargetLowering &TLI,
459 const TargetOptions *Options,
460 unsigned Depth = 0) {
461 // fneg is removable even if it has multiple uses.
462 if (Op.getOpcode() == ISD::FNEG) return 2;
464 // Don't allow anything with multiple uses.
465 if (!Op.hasOneUse()) return 0;
467 // Don't recurse exponentially.
468 if (Depth > 6) return 0;
470 switch (Op.getOpcode()) {
471 default: return false;
472 case ISD::ConstantFP:
473 // Don't invert constant FP values after legalize. The negated constant
474 // isn't necessarily legal.
475 return LegalOperations ? 0 : 1;
477 // FIXME: determine better conditions for this xform.
478 if (!Options->UnsafeFPMath) return 0;
480 // After operation legalization, it might not be legal to create new FSUBs.
481 if (LegalOperations &&
482 !TLI.isOperationLegalOrCustom(ISD::FSUB, Op.getValueType()))
485 // fold (fneg (fadd A, B)) -> (fsub (fneg A), B)
486 if (char V = isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI,
489 // fold (fneg (fadd A, B)) -> (fsub (fneg B), A)
490 return isNegatibleForFree(Op.getOperand(1), LegalOperations, TLI, Options,
493 // We can't turn -(A-B) into B-A when we honor signed zeros.
494 if (!Options->UnsafeFPMath) return 0;
496 // fold (fneg (fsub A, B)) -> (fsub B, A)
501 if (Options->HonorSignDependentRoundingFPMath()) return 0;
503 // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y) or (fmul X, (fneg Y))
504 if (char V = isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI,
508 return isNegatibleForFree(Op.getOperand(1), LegalOperations, TLI, Options,
514 return isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI, Options,
519 /// GetNegatedExpression - If isNegatibleForFree returns true, this function
520 /// returns the newly negated expression.
521 static SDValue GetNegatedExpression(SDValue Op, SelectionDAG &DAG,
522 bool LegalOperations, unsigned Depth = 0) {
523 // fneg is removable even if it has multiple uses.
524 if (Op.getOpcode() == ISD::FNEG) return Op.getOperand(0);
526 // Don't allow anything with multiple uses.
527 assert(Op.hasOneUse() && "Unknown reuse!");
529 assert(Depth <= 6 && "GetNegatedExpression doesn't match isNegatibleForFree");
530 switch (Op.getOpcode()) {
531 default: llvm_unreachable("Unknown code");
532 case ISD::ConstantFP: {
533 APFloat V = cast<ConstantFPSDNode>(Op)->getValueAPF();
535 return DAG.getConstantFP(V, Op.getValueType());
538 // FIXME: determine better conditions for this xform.
539 assert(DAG.getTarget().Options.UnsafeFPMath);
541 // fold (fneg (fadd A, B)) -> (fsub (fneg A), B)
542 if (isNegatibleForFree(Op.getOperand(0), LegalOperations,
543 DAG.getTargetLoweringInfo(),
544 &DAG.getTarget().Options, Depth+1))
545 return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
546 GetNegatedExpression(Op.getOperand(0), DAG,
547 LegalOperations, Depth+1),
549 // fold (fneg (fadd A, B)) -> (fsub (fneg B), A)
550 return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
551 GetNegatedExpression(Op.getOperand(1), DAG,
552 LegalOperations, Depth+1),
555 // We can't turn -(A-B) into B-A when we honor signed zeros.
556 assert(DAG.getTarget().Options.UnsafeFPMath);
558 // fold (fneg (fsub 0, B)) -> B
559 if (ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(Op.getOperand(0)))
560 if (N0CFP->getValueAPF().isZero())
561 return Op.getOperand(1);
563 // fold (fneg (fsub A, B)) -> (fsub B, A)
564 return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
565 Op.getOperand(1), Op.getOperand(0));
569 assert(!DAG.getTarget().Options.HonorSignDependentRoundingFPMath());
571 // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y)
572 if (isNegatibleForFree(Op.getOperand(0), LegalOperations,
573 DAG.getTargetLoweringInfo(),
574 &DAG.getTarget().Options, Depth+1))
575 return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
576 GetNegatedExpression(Op.getOperand(0), DAG,
577 LegalOperations, Depth+1),
580 // fold (fneg (fmul X, Y)) -> (fmul X, (fneg Y))
581 return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
583 GetNegatedExpression(Op.getOperand(1), DAG,
584 LegalOperations, Depth+1));
588 return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
589 GetNegatedExpression(Op.getOperand(0), DAG,
590 LegalOperations, Depth+1));
592 return DAG.getNode(ISD::FP_ROUND, SDLoc(Op), Op.getValueType(),
593 GetNegatedExpression(Op.getOperand(0), DAG,
594 LegalOperations, Depth+1),
600 // isSetCCEquivalent - Return true if this node is a setcc, or is a select_cc
601 // that selects between the values 1 and 0, making it equivalent to a setcc.
602 // Also, set the incoming LHS, RHS, and CC references to the appropriate
603 // nodes based on the type of node we are checking. This simplifies life a
604 // bit for the callers.
605 static bool isSetCCEquivalent(SDValue N, SDValue &LHS, SDValue &RHS,
607 if (N.getOpcode() == ISD::SETCC) {
608 LHS = N.getOperand(0);
609 RHS = N.getOperand(1);
610 CC = N.getOperand(2);
613 if (N.getOpcode() == ISD::SELECT_CC &&
614 N.getOperand(2).getOpcode() == ISD::Constant &&
615 N.getOperand(3).getOpcode() == ISD::Constant &&
616 cast<ConstantSDNode>(N.getOperand(2))->getAPIntValue() == 1 &&
617 cast<ConstantSDNode>(N.getOperand(3))->isNullValue()) {
618 LHS = N.getOperand(0);
619 RHS = N.getOperand(1);
620 CC = N.getOperand(4);
626 // isOneUseSetCC - Return true if this is a SetCC-equivalent operation with only
627 // one use. If this is true, it allows the users to invert the operation for
628 // free when it is profitable to do so.
629 static bool isOneUseSetCC(SDValue N) {
631 if (isSetCCEquivalent(N, N0, N1, N2) && N.getNode()->hasOneUse())
636 // \brief Returns the SDNode if it is a constant BuildVector or constant int.
637 static SDNode *isConstantBuildVectorOrConstantInt(SDValue N) {
638 if (isa<ConstantSDNode>(N))
640 BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N);
641 if(BV && BV->isConstant())
646 SDValue DAGCombiner::ReassociateOps(unsigned Opc, SDLoc DL,
647 SDValue N0, SDValue N1) {
648 EVT VT = N0.getValueType();
649 if (N0.getOpcode() == Opc) {
650 if (SDNode *L = isConstantBuildVectorOrConstantInt(N0.getOperand(1))) {
651 if (SDNode *R = isConstantBuildVectorOrConstantInt(N1)) {
652 // reassoc. (op (op x, c1), c2) -> (op x, (op c1, c2))
653 SDValue OpNode = DAG.FoldConstantArithmetic(Opc, VT, L, R);
654 if (!OpNode.getNode())
656 return DAG.getNode(Opc, DL, VT, N0.getOperand(0), OpNode);
658 if (N0.hasOneUse()) {
659 // reassoc. (op (op x, c1), y) -> (op (op x, y), c1) iff x+c1 has one
661 SDValue OpNode = DAG.getNode(Opc, SDLoc(N0), VT, N0.getOperand(0), N1);
662 if (!OpNode.getNode())
664 AddToWorkList(OpNode.getNode());
665 return DAG.getNode(Opc, DL, VT, OpNode, N0.getOperand(1));
670 if (N1.getOpcode() == Opc) {
671 if (SDNode *R = isConstantBuildVectorOrConstantInt(N1.getOperand(1))) {
672 if (SDNode *L = isConstantBuildVectorOrConstantInt(N0)) {
673 // reassoc. (op c2, (op x, c1)) -> (op x, (op c1, c2))
674 SDValue OpNode = DAG.FoldConstantArithmetic(Opc, VT, R, L);
675 if (!OpNode.getNode())
677 return DAG.getNode(Opc, DL, VT, N1.getOperand(0), OpNode);
679 if (N1.hasOneUse()) {
680 // reassoc. (op y, (op x, c1)) -> (op (op x, y), c1) iff x+c1 has one
682 SDValue OpNode = DAG.getNode(Opc, SDLoc(N0), VT, N1.getOperand(0), N0);
683 if (!OpNode.getNode())
685 AddToWorkList(OpNode.getNode());
686 return DAG.getNode(Opc, DL, VT, OpNode, N1.getOperand(1));
694 SDValue DAGCombiner::CombineTo(SDNode *N, const SDValue *To, unsigned NumTo,
696 assert(N->getNumValues() == NumTo && "Broken CombineTo call!");
698 DEBUG(dbgs() << "\nReplacing.1 ";
700 dbgs() << "\nWith: ";
701 To[0].getNode()->dump(&DAG);
702 dbgs() << " and " << NumTo-1 << " other values\n";
703 for (unsigned i = 0, e = NumTo; i != e; ++i)
704 assert((!To[i].getNode() ||
705 N->getValueType(i) == To[i].getValueType()) &&
706 "Cannot combine value to value of different type!"));
707 WorkListRemover DeadNodes(*this);
708 DAG.ReplaceAllUsesWith(N, To);
710 // Push the new nodes and any users onto the worklist
711 for (unsigned i = 0, e = NumTo; i != e; ++i) {
712 if (To[i].getNode()) {
713 AddToWorkList(To[i].getNode());
714 AddUsersToWorkList(To[i].getNode());
719 // Finally, if the node is now dead, remove it from the graph. The node
720 // may not be dead if the replacement process recursively simplified to
721 // something else needing this node.
722 if (N->use_empty()) {
723 // Nodes can be reintroduced into the worklist. Make sure we do not
724 // process a node that has been replaced.
725 removeFromWorkList(N);
727 // Finally, since the node is now dead, remove it from the graph.
730 return SDValue(N, 0);
734 CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) {
735 // Replace all uses. If any nodes become isomorphic to other nodes and
736 // are deleted, make sure to remove them from our worklist.
737 WorkListRemover DeadNodes(*this);
738 DAG.ReplaceAllUsesOfValueWith(TLO.Old, TLO.New);
740 // Push the new node and any (possibly new) users onto the worklist.
741 AddToWorkList(TLO.New.getNode());
742 AddUsersToWorkList(TLO.New.getNode());
744 // Finally, if the node is now dead, remove it from the graph. The node
745 // may not be dead if the replacement process recursively simplified to
746 // something else needing this node.
747 if (TLO.Old.getNode()->use_empty()) {
748 removeFromWorkList(TLO.Old.getNode());
750 // If the operands of this node are only used by the node, they will now
751 // be dead. Make sure to visit them first to delete dead nodes early.
752 for (unsigned i = 0, e = TLO.Old.getNode()->getNumOperands(); i != e; ++i)
753 if (TLO.Old.getNode()->getOperand(i).getNode()->hasOneUse())
754 AddToWorkList(TLO.Old.getNode()->getOperand(i).getNode());
756 DAG.DeleteNode(TLO.Old.getNode());
760 /// SimplifyDemandedBits - Check the specified integer node value to see if
761 /// it can be simplified or if things it uses can be simplified by bit
762 /// propagation. If so, return true.
763 bool DAGCombiner::SimplifyDemandedBits(SDValue Op, const APInt &Demanded) {
764 TargetLowering::TargetLoweringOpt TLO(DAG, LegalTypes, LegalOperations);
765 APInt KnownZero, KnownOne;
766 if (!TLI.SimplifyDemandedBits(Op, Demanded, KnownZero, KnownOne, TLO))
770 AddToWorkList(Op.getNode());
772 // Replace the old value with the new one.
774 DEBUG(dbgs() << "\nReplacing.2 ";
775 TLO.Old.getNode()->dump(&DAG);
776 dbgs() << "\nWith: ";
777 TLO.New.getNode()->dump(&DAG);
780 CommitTargetLoweringOpt(TLO);
784 void DAGCombiner::ReplaceLoadWithPromotedLoad(SDNode *Load, SDNode *ExtLoad) {
786 EVT VT = Load->getValueType(0);
787 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, dl, VT, SDValue(ExtLoad, 0));
789 DEBUG(dbgs() << "\nReplacing.9 ";
791 dbgs() << "\nWith: ";
792 Trunc.getNode()->dump(&DAG);
794 WorkListRemover DeadNodes(*this);
795 DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 0), Trunc);
796 DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 1), SDValue(ExtLoad, 1));
797 removeFromWorkList(Load);
798 DAG.DeleteNode(Load);
799 AddToWorkList(Trunc.getNode());
802 SDValue DAGCombiner::PromoteOperand(SDValue Op, EVT PVT, bool &Replace) {
805 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Op)) {
806 EVT MemVT = LD->getMemoryVT();
807 ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD)
808 ? (TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT) ? ISD::ZEXTLOAD
810 : LD->getExtensionType();
812 return DAG.getExtLoad(ExtType, dl, PVT,
813 LD->getChain(), LD->getBasePtr(),
814 MemVT, LD->getMemOperand());
817 unsigned Opc = Op.getOpcode();
820 case ISD::AssertSext:
821 return DAG.getNode(ISD::AssertSext, dl, PVT,
822 SExtPromoteOperand(Op.getOperand(0), PVT),
824 case ISD::AssertZext:
825 return DAG.getNode(ISD::AssertZext, dl, PVT,
826 ZExtPromoteOperand(Op.getOperand(0), PVT),
828 case ISD::Constant: {
830 Op.getValueType().isByteSized() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
831 return DAG.getNode(ExtOpc, dl, PVT, Op);
835 if (!TLI.isOperationLegal(ISD::ANY_EXTEND, PVT))
837 return DAG.getNode(ISD::ANY_EXTEND, dl, PVT, Op);
840 SDValue DAGCombiner::SExtPromoteOperand(SDValue Op, EVT PVT) {
841 if (!TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, PVT))
843 EVT OldVT = Op.getValueType();
845 bool Replace = false;
846 SDValue NewOp = PromoteOperand(Op, PVT, Replace);
847 if (NewOp.getNode() == 0)
849 AddToWorkList(NewOp.getNode());
852 ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode());
853 return DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, NewOp.getValueType(), NewOp,
854 DAG.getValueType(OldVT));
857 SDValue DAGCombiner::ZExtPromoteOperand(SDValue Op, EVT PVT) {
858 EVT OldVT = Op.getValueType();
860 bool Replace = false;
861 SDValue NewOp = PromoteOperand(Op, PVT, Replace);
862 if (NewOp.getNode() == 0)
864 AddToWorkList(NewOp.getNode());
867 ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode());
868 return DAG.getZeroExtendInReg(NewOp, dl, OldVT);
871 /// PromoteIntBinOp - Promote the specified integer binary operation if the
872 /// target indicates it is beneficial. e.g. On x86, it's usually better to
873 /// promote i16 operations to i32 since i16 instructions are longer.
874 SDValue DAGCombiner::PromoteIntBinOp(SDValue Op) {
875 if (!LegalOperations)
878 EVT VT = Op.getValueType();
879 if (VT.isVector() || !VT.isInteger())
882 // If operation type is 'undesirable', e.g. i16 on x86, consider
884 unsigned Opc = Op.getOpcode();
885 if (TLI.isTypeDesirableForOp(Opc, VT))
889 // Consult target whether it is a good idea to promote this operation and
890 // what's the right type to promote it to.
891 if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
892 assert(PVT != VT && "Don't know what type to promote to!");
894 bool Replace0 = false;
895 SDValue N0 = Op.getOperand(0);
896 SDValue NN0 = PromoteOperand(N0, PVT, Replace0);
897 if (NN0.getNode() == 0)
900 bool Replace1 = false;
901 SDValue N1 = Op.getOperand(1);
906 NN1 = PromoteOperand(N1, PVT, Replace1);
907 if (NN1.getNode() == 0)
911 AddToWorkList(NN0.getNode());
913 AddToWorkList(NN1.getNode());
916 ReplaceLoadWithPromotedLoad(N0.getNode(), NN0.getNode());
918 ReplaceLoadWithPromotedLoad(N1.getNode(), NN1.getNode());
920 DEBUG(dbgs() << "\nPromoting ";
921 Op.getNode()->dump(&DAG));
923 return DAG.getNode(ISD::TRUNCATE, dl, VT,
924 DAG.getNode(Opc, dl, PVT, NN0, NN1));
929 /// PromoteIntShiftOp - Promote the specified integer shift operation if the
930 /// target indicates it is beneficial. e.g. On x86, it's usually better to
931 /// promote i16 operations to i32 since i16 instructions are longer.
932 SDValue DAGCombiner::PromoteIntShiftOp(SDValue Op) {
933 if (!LegalOperations)
936 EVT VT = Op.getValueType();
937 if (VT.isVector() || !VT.isInteger())
940 // If operation type is 'undesirable', e.g. i16 on x86, consider
942 unsigned Opc = Op.getOpcode();
943 if (TLI.isTypeDesirableForOp(Opc, VT))
947 // Consult target whether it is a good idea to promote this operation and
948 // what's the right type to promote it to.
949 if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
950 assert(PVT != VT && "Don't know what type to promote to!");
952 bool Replace = false;
953 SDValue N0 = Op.getOperand(0);
955 N0 = SExtPromoteOperand(Op.getOperand(0), PVT);
956 else if (Opc == ISD::SRL)
957 N0 = ZExtPromoteOperand(Op.getOperand(0), PVT);
959 N0 = PromoteOperand(N0, PVT, Replace);
960 if (N0.getNode() == 0)
963 AddToWorkList(N0.getNode());
965 ReplaceLoadWithPromotedLoad(Op.getOperand(0).getNode(), N0.getNode());
967 DEBUG(dbgs() << "\nPromoting ";
968 Op.getNode()->dump(&DAG));
970 return DAG.getNode(ISD::TRUNCATE, dl, VT,
971 DAG.getNode(Opc, dl, PVT, N0, Op.getOperand(1)));
976 SDValue DAGCombiner::PromoteExtend(SDValue Op) {
977 if (!LegalOperations)
980 EVT VT = Op.getValueType();
981 if (VT.isVector() || !VT.isInteger())
984 // If operation type is 'undesirable', e.g. i16 on x86, consider
986 unsigned Opc = Op.getOpcode();
987 if (TLI.isTypeDesirableForOp(Opc, VT))
991 // Consult target whether it is a good idea to promote this operation and
992 // what's the right type to promote it to.
993 if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
994 assert(PVT != VT && "Don't know what type to promote to!");
995 // fold (aext (aext x)) -> (aext x)
996 // fold (aext (zext x)) -> (zext x)
997 // fold (aext (sext x)) -> (sext x)
998 DEBUG(dbgs() << "\nPromoting ";
999 Op.getNode()->dump(&DAG));
1000 return DAG.getNode(Op.getOpcode(), SDLoc(Op), VT, Op.getOperand(0));
1005 bool DAGCombiner::PromoteLoad(SDValue Op) {
1006 if (!LegalOperations)
1009 EVT VT = Op.getValueType();
1010 if (VT.isVector() || !VT.isInteger())
1013 // If operation type is 'undesirable', e.g. i16 on x86, consider
1015 unsigned Opc = Op.getOpcode();
1016 if (TLI.isTypeDesirableForOp(Opc, VT))
1020 // Consult target whether it is a good idea to promote this operation and
1021 // what's the right type to promote it to.
1022 if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1023 assert(PVT != VT && "Don't know what type to promote to!");
1026 SDNode *N = Op.getNode();
1027 LoadSDNode *LD = cast<LoadSDNode>(N);
1028 EVT MemVT = LD->getMemoryVT();
1029 ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD)
1030 ? (TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT) ? ISD::ZEXTLOAD
1032 : LD->getExtensionType();
1033 SDValue NewLD = DAG.getExtLoad(ExtType, dl, PVT,
1034 LD->getChain(), LD->getBasePtr(),
1035 MemVT, LD->getMemOperand());
1036 SDValue Result = DAG.getNode(ISD::TRUNCATE, dl, VT, NewLD);
1038 DEBUG(dbgs() << "\nPromoting ";
1041 Result.getNode()->dump(&DAG);
1043 WorkListRemover DeadNodes(*this);
1044 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result);
1045 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), NewLD.getValue(1));
1046 removeFromWorkList(N);
1048 AddToWorkList(Result.getNode());
1055 //===----------------------------------------------------------------------===//
1056 // Main DAG Combiner implementation
1057 //===----------------------------------------------------------------------===//
1059 void DAGCombiner::Run(CombineLevel AtLevel) {
1060 // set the instance variables, so that the various visit routines may use it.
1062 LegalOperations = Level >= AfterLegalizeVectorOps;
1063 LegalTypes = Level >= AfterLegalizeTypes;
1065 // Add all the dag nodes to the worklist.
1066 for (SelectionDAG::allnodes_iterator I = DAG.allnodes_begin(),
1067 E = DAG.allnodes_end(); I != E; ++I)
1070 // Create a dummy node (which is not added to allnodes), that adds a reference
1071 // to the root node, preventing it from being deleted, and tracking any
1072 // changes of the root.
1073 HandleSDNode Dummy(DAG.getRoot());
1075 // The root of the dag may dangle to deleted nodes until the dag combiner is
1076 // done. Set it to null to avoid confusion.
1077 DAG.setRoot(SDValue());
1079 // while the worklist isn't empty, find a node and
1080 // try and combine it.
1081 while (!WorkListContents.empty()) {
1083 // The WorkListOrder holds the SDNodes in order, but it may contain
1085 // In order to avoid a linear scan, we use a set (O(log N)) to hold what the
1086 // worklist *should* contain, and check the node we want to visit is should
1087 // actually be visited.
1089 N = WorkListOrder.pop_back_val();
1090 } while (!WorkListContents.erase(N));
1092 // If N has no uses, it is dead. Make sure to revisit all N's operands once
1093 // N is deleted from the DAG, since they too may now be dead or may have a
1094 // reduced number of uses, allowing other xforms.
1095 if (N->use_empty() && N != &Dummy) {
1096 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1097 AddToWorkList(N->getOperand(i).getNode());
1103 SDValue RV = combine(N);
1105 if (RV.getNode() == 0)
1110 // If we get back the same node we passed in, rather than a new node or
1111 // zero, we know that the node must have defined multiple values and
1112 // CombineTo was used. Since CombineTo takes care of the worklist
1113 // mechanics for us, we have no work to do in this case.
1114 if (RV.getNode() == N)
1117 assert(N->getOpcode() != ISD::DELETED_NODE &&
1118 RV.getNode()->getOpcode() != ISD::DELETED_NODE &&
1119 "Node was deleted but visit returned new node!");
1121 DEBUG(dbgs() << "\nReplacing.3 ";
1123 dbgs() << "\nWith: ";
1124 RV.getNode()->dump(&DAG);
1127 // Transfer debug value.
1128 DAG.TransferDbgValues(SDValue(N, 0), RV);
1129 WorkListRemover DeadNodes(*this);
1130 if (N->getNumValues() == RV.getNode()->getNumValues())
1131 DAG.ReplaceAllUsesWith(N, RV.getNode());
1133 assert(N->getValueType(0) == RV.getValueType() &&
1134 N->getNumValues() == 1 && "Type mismatch");
1136 DAG.ReplaceAllUsesWith(N, &OpV);
1139 // Push the new node and any users onto the worklist
1140 AddToWorkList(RV.getNode());
1141 AddUsersToWorkList(RV.getNode());
1143 // Add any uses of the old node to the worklist in case this node is the
1144 // last one that uses them. They may become dead after this node is
1146 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1147 AddToWorkList(N->getOperand(i).getNode());
1149 // Finally, if the node is now dead, remove it from the graph. The node
1150 // may not be dead if the replacement process recursively simplified to
1151 // something else needing this node.
1152 if (N->use_empty()) {
1153 // Nodes can be reintroduced into the worklist. Make sure we do not
1154 // process a node that has been replaced.
1155 removeFromWorkList(N);
1157 // Finally, since the node is now dead, remove it from the graph.
1162 // If the root changed (e.g. it was a dead load, update the root).
1163 DAG.setRoot(Dummy.getValue());
1164 DAG.RemoveDeadNodes();
1167 SDValue DAGCombiner::visit(SDNode *N) {
1168 switch (N->getOpcode()) {
1170 case ISD::TokenFactor: return visitTokenFactor(N);
1171 case ISD::MERGE_VALUES: return visitMERGE_VALUES(N);
1172 case ISD::ADD: return visitADD(N);
1173 case ISD::SUB: return visitSUB(N);
1174 case ISD::ADDC: return visitADDC(N);
1175 case ISD::SUBC: return visitSUBC(N);
1176 case ISD::ADDE: return visitADDE(N);
1177 case ISD::SUBE: return visitSUBE(N);
1178 case ISD::MUL: return visitMUL(N);
1179 case ISD::SDIV: return visitSDIV(N);
1180 case ISD::UDIV: return visitUDIV(N);
1181 case ISD::SREM: return visitSREM(N);
1182 case ISD::UREM: return visitUREM(N);
1183 case ISD::MULHU: return visitMULHU(N);
1184 case ISD::MULHS: return visitMULHS(N);
1185 case ISD::SMUL_LOHI: return visitSMUL_LOHI(N);
1186 case ISD::UMUL_LOHI: return visitUMUL_LOHI(N);
1187 case ISD::SMULO: return visitSMULO(N);
1188 case ISD::UMULO: return visitUMULO(N);
1189 case ISD::SDIVREM: return visitSDIVREM(N);
1190 case ISD::UDIVREM: return visitUDIVREM(N);
1191 case ISD::AND: return visitAND(N);
1192 case ISD::OR: return visitOR(N);
1193 case ISD::XOR: return visitXOR(N);
1194 case ISD::SHL: return visitSHL(N);
1195 case ISD::SRA: return visitSRA(N);
1196 case ISD::SRL: return visitSRL(N);
1197 case ISD::CTLZ: return visitCTLZ(N);
1198 case ISD::CTLZ_ZERO_UNDEF: return visitCTLZ_ZERO_UNDEF(N);
1199 case ISD::CTTZ: return visitCTTZ(N);
1200 case ISD::CTTZ_ZERO_UNDEF: return visitCTTZ_ZERO_UNDEF(N);
1201 case ISD::CTPOP: return visitCTPOP(N);
1202 case ISD::SELECT: return visitSELECT(N);
1203 case ISD::VSELECT: return visitVSELECT(N);
1204 case ISD::SELECT_CC: return visitSELECT_CC(N);
1205 case ISD::SETCC: return visitSETCC(N);
1206 case ISD::SIGN_EXTEND: return visitSIGN_EXTEND(N);
1207 case ISD::ZERO_EXTEND: return visitZERO_EXTEND(N);
1208 case ISD::ANY_EXTEND: return visitANY_EXTEND(N);
1209 case ISD::SIGN_EXTEND_INREG: return visitSIGN_EXTEND_INREG(N);
1210 case ISD::TRUNCATE: return visitTRUNCATE(N);
1211 case ISD::BITCAST: return visitBITCAST(N);
1212 case ISD::BUILD_PAIR: return visitBUILD_PAIR(N);
1213 case ISD::FADD: return visitFADD(N);
1214 case ISD::FSUB: return visitFSUB(N);
1215 case ISD::FMUL: return visitFMUL(N);
1216 case ISD::FMA: return visitFMA(N);
1217 case ISD::FDIV: return visitFDIV(N);
1218 case ISD::FREM: return visitFREM(N);
1219 case ISD::FCOPYSIGN: return visitFCOPYSIGN(N);
1220 case ISD::SINT_TO_FP: return visitSINT_TO_FP(N);
1221 case ISD::UINT_TO_FP: return visitUINT_TO_FP(N);
1222 case ISD::FP_TO_SINT: return visitFP_TO_SINT(N);
1223 case ISD::FP_TO_UINT: return visitFP_TO_UINT(N);
1224 case ISD::FP_ROUND: return visitFP_ROUND(N);
1225 case ISD::FP_ROUND_INREG: return visitFP_ROUND_INREG(N);
1226 case ISD::FP_EXTEND: return visitFP_EXTEND(N);
1227 case ISD::FNEG: return visitFNEG(N);
1228 case ISD::FABS: return visitFABS(N);
1229 case ISD::FFLOOR: return visitFFLOOR(N);
1230 case ISD::FCEIL: return visitFCEIL(N);
1231 case ISD::FTRUNC: return visitFTRUNC(N);
1232 case ISD::BRCOND: return visitBRCOND(N);
1233 case ISD::BR_CC: return visitBR_CC(N);
1234 case ISD::LOAD: return visitLOAD(N);
1235 case ISD::STORE: return visitSTORE(N);
1236 case ISD::INSERT_VECTOR_ELT: return visitINSERT_VECTOR_ELT(N);
1237 case ISD::EXTRACT_VECTOR_ELT: return visitEXTRACT_VECTOR_ELT(N);
1238 case ISD::BUILD_VECTOR: return visitBUILD_VECTOR(N);
1239 case ISD::CONCAT_VECTORS: return visitCONCAT_VECTORS(N);
1240 case ISD::EXTRACT_SUBVECTOR: return visitEXTRACT_SUBVECTOR(N);
1241 case ISD::VECTOR_SHUFFLE: return visitVECTOR_SHUFFLE(N);
1242 case ISD::INSERT_SUBVECTOR: return visitINSERT_SUBVECTOR(N);
1247 SDValue DAGCombiner::combine(SDNode *N) {
1248 SDValue RV = visit(N);
1250 // If nothing happened, try a target-specific DAG combine.
1251 if (RV.getNode() == 0) {
1252 assert(N->getOpcode() != ISD::DELETED_NODE &&
1253 "Node was deleted but visit returned NULL!");
1255 if (N->getOpcode() >= ISD::BUILTIN_OP_END ||
1256 TLI.hasTargetDAGCombine((ISD::NodeType)N->getOpcode())) {
1258 // Expose the DAG combiner to the target combiner impls.
1259 TargetLowering::DAGCombinerInfo
1260 DagCombineInfo(DAG, Level, false, this);
1262 RV = TLI.PerformDAGCombine(N, DagCombineInfo);
1266 // If nothing happened still, try promoting the operation.
1267 if (RV.getNode() == 0) {
1268 switch (N->getOpcode()) {
1276 RV = PromoteIntBinOp(SDValue(N, 0));
1281 RV = PromoteIntShiftOp(SDValue(N, 0));
1283 case ISD::SIGN_EXTEND:
1284 case ISD::ZERO_EXTEND:
1285 case ISD::ANY_EXTEND:
1286 RV = PromoteExtend(SDValue(N, 0));
1289 if (PromoteLoad(SDValue(N, 0)))
1295 // If N is a commutative binary node, try commuting it to enable more
1297 if (RV.getNode() == 0 &&
1298 SelectionDAG::isCommutativeBinOp(N->getOpcode()) &&
1299 N->getNumValues() == 1) {
1300 SDValue N0 = N->getOperand(0);
1301 SDValue N1 = N->getOperand(1);
1303 // Constant operands are canonicalized to RHS.
1304 if (isa<ConstantSDNode>(N0) || !isa<ConstantSDNode>(N1)) {
1305 SDValue Ops[] = { N1, N0 };
1306 SDNode *CSENode = DAG.getNodeIfExists(N->getOpcode(), N->getVTList(),
1309 return SDValue(CSENode, 0);
1316 /// getInputChainForNode - Given a node, return its input chain if it has one,
1317 /// otherwise return a null sd operand.
1318 static SDValue getInputChainForNode(SDNode *N) {
1319 if (unsigned NumOps = N->getNumOperands()) {
1320 if (N->getOperand(0).getValueType() == MVT::Other)
1321 return N->getOperand(0);
1322 if (N->getOperand(NumOps-1).getValueType() == MVT::Other)
1323 return N->getOperand(NumOps-1);
1324 for (unsigned i = 1; i < NumOps-1; ++i)
1325 if (N->getOperand(i).getValueType() == MVT::Other)
1326 return N->getOperand(i);
1331 SDValue DAGCombiner::visitTokenFactor(SDNode *N) {
1332 // If N has two operands, where one has an input chain equal to the other,
1333 // the 'other' chain is redundant.
1334 if (N->getNumOperands() == 2) {
1335 if (getInputChainForNode(N->getOperand(0).getNode()) == N->getOperand(1))
1336 return N->getOperand(0);
1337 if (getInputChainForNode(N->getOperand(1).getNode()) == N->getOperand(0))
1338 return N->getOperand(1);
1341 SmallVector<SDNode *, 8> TFs; // List of token factors to visit.
1342 SmallVector<SDValue, 8> Ops; // Ops for replacing token factor.
1343 SmallPtrSet<SDNode*, 16> SeenOps;
1344 bool Changed = false; // If we should replace this token factor.
1346 // Start out with this token factor.
1349 // Iterate through token factors. The TFs grows when new token factors are
1351 for (unsigned i = 0; i < TFs.size(); ++i) {
1352 SDNode *TF = TFs[i];
1354 // Check each of the operands.
1355 for (unsigned i = 0, ie = TF->getNumOperands(); i != ie; ++i) {
1356 SDValue Op = TF->getOperand(i);
1358 switch (Op.getOpcode()) {
1359 case ISD::EntryToken:
1360 // Entry tokens don't need to be added to the list. They are
1365 case ISD::TokenFactor:
1366 if (Op.hasOneUse() &&
1367 std::find(TFs.begin(), TFs.end(), Op.getNode()) == TFs.end()) {
1368 // Queue up for processing.
1369 TFs.push_back(Op.getNode());
1370 // Clean up in case the token factor is removed.
1371 AddToWorkList(Op.getNode());
1378 // Only add if it isn't already in the list.
1379 if (SeenOps.insert(Op.getNode()))
1390 // If we've change things around then replace token factor.
1393 // The entry token is the only possible outcome.
1394 Result = DAG.getEntryNode();
1396 // New and improved token factor.
1397 Result = DAG.getNode(ISD::TokenFactor, SDLoc(N),
1398 MVT::Other, &Ops[0], Ops.size());
1401 // Don't add users to work list.
1402 return CombineTo(N, Result, false);
1408 /// MERGE_VALUES can always be eliminated.
1409 SDValue DAGCombiner::visitMERGE_VALUES(SDNode *N) {
1410 WorkListRemover DeadNodes(*this);
1411 // Replacing results may cause a different MERGE_VALUES to suddenly
1412 // be CSE'd with N, and carry its uses with it. Iterate until no
1413 // uses remain, to ensure that the node can be safely deleted.
1414 // First add the users of this node to the work list so that they
1415 // can be tried again once they have new operands.
1416 AddUsersToWorkList(N);
1418 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1419 DAG.ReplaceAllUsesOfValueWith(SDValue(N, i), N->getOperand(i));
1420 } while (!N->use_empty());
1421 removeFromWorkList(N);
1423 return SDValue(N, 0); // Return N so it doesn't get rechecked!
1427 SDValue combineShlAddConstant(SDLoc DL, SDValue N0, SDValue N1,
1428 SelectionDAG &DAG) {
1429 EVT VT = N0.getValueType();
1430 SDValue N00 = N0.getOperand(0);
1431 SDValue N01 = N0.getOperand(1);
1432 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N01);
1434 if (N01C && N00.getOpcode() == ISD::ADD && N00.getNode()->hasOneUse() &&
1435 isa<ConstantSDNode>(N00.getOperand(1))) {
1436 // fold (add (shl (add x, c1), c2), ) -> (add (add (shl x, c2), c1<<c2), )
1437 N0 = DAG.getNode(ISD::ADD, SDLoc(N0), VT,
1438 DAG.getNode(ISD::SHL, SDLoc(N00), VT,
1439 N00.getOperand(0), N01),
1440 DAG.getNode(ISD::SHL, SDLoc(N01), VT,
1441 N00.getOperand(1), N01));
1442 return DAG.getNode(ISD::ADD, DL, VT, N0, N1);
1448 SDValue DAGCombiner::visitADD(SDNode *N) {
1449 SDValue N0 = N->getOperand(0);
1450 SDValue N1 = N->getOperand(1);
1451 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1452 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1453 EVT VT = N0.getValueType();
1456 if (VT.isVector()) {
1457 SDValue FoldedVOp = SimplifyVBinOp(N);
1458 if (FoldedVOp.getNode()) return FoldedVOp;
1460 // fold (add x, 0) -> x, vector edition
1461 if (ISD::isBuildVectorAllZeros(N1.getNode()))
1463 if (ISD::isBuildVectorAllZeros(N0.getNode()))
1467 // fold (add x, undef) -> undef
1468 if (N0.getOpcode() == ISD::UNDEF)
1470 if (N1.getOpcode() == ISD::UNDEF)
1472 // fold (add c1, c2) -> c1+c2
1474 return DAG.FoldConstantArithmetic(ISD::ADD, VT, N0C, N1C);
1475 // canonicalize constant to RHS
1477 return DAG.getNode(ISD::ADD, SDLoc(N), VT, N1, N0);
1478 // fold (add x, 0) -> x
1479 if (N1C && N1C->isNullValue())
1481 // fold (add Sym, c) -> Sym+c
1482 if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N0))
1483 if (!LegalOperations && TLI.isOffsetFoldingLegal(GA) && N1C &&
1484 GA->getOpcode() == ISD::GlobalAddress)
1485 return DAG.getGlobalAddress(GA->getGlobal(), SDLoc(N1C), VT,
1487 (uint64_t)N1C->getSExtValue());
1488 // fold ((c1-A)+c2) -> (c1+c2)-A
1489 if (N1C && N0.getOpcode() == ISD::SUB)
1490 if (ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getOperand(0)))
1491 return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1492 DAG.getConstant(N1C->getAPIntValue()+
1493 N0C->getAPIntValue(), VT),
1496 SDValue RADD = ReassociateOps(ISD::ADD, SDLoc(N), N0, N1);
1497 if (RADD.getNode() != 0)
1499 // fold ((0-A) + B) -> B-A
1500 if (N0.getOpcode() == ISD::SUB && isa<ConstantSDNode>(N0.getOperand(0)) &&
1501 cast<ConstantSDNode>(N0.getOperand(0))->isNullValue())
1502 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1, N0.getOperand(1));
1503 // fold (A + (0-B)) -> A-B
1504 if (N1.getOpcode() == ISD::SUB && isa<ConstantSDNode>(N1.getOperand(0)) &&
1505 cast<ConstantSDNode>(N1.getOperand(0))->isNullValue())
1506 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, N1.getOperand(1));
1507 // fold (A+(B-A)) -> B
1508 if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(1))
1509 return N1.getOperand(0);
1510 // fold ((B-A)+A) -> B
1511 if (N0.getOpcode() == ISD::SUB && N1 == N0.getOperand(1))
1512 return N0.getOperand(0);
1513 // fold (A+(B-(A+C))) to (B-C)
1514 if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD &&
1515 N0 == N1.getOperand(1).getOperand(0))
1516 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1.getOperand(0),
1517 N1.getOperand(1).getOperand(1));
1518 // fold (A+(B-(C+A))) to (B-C)
1519 if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD &&
1520 N0 == N1.getOperand(1).getOperand(1))
1521 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1.getOperand(0),
1522 N1.getOperand(1).getOperand(0));
1523 // fold (A+((B-A)+or-C)) to (B+or-C)
1524 if ((N1.getOpcode() == ISD::SUB || N1.getOpcode() == ISD::ADD) &&
1525 N1.getOperand(0).getOpcode() == ISD::SUB &&
1526 N0 == N1.getOperand(0).getOperand(1))
1527 return DAG.getNode(N1.getOpcode(), SDLoc(N), VT,
1528 N1.getOperand(0).getOperand(0), N1.getOperand(1));
1530 // fold (A-B)+(C-D) to (A+C)-(B+D) when A or C is constant
1531 if (N0.getOpcode() == ISD::SUB && N1.getOpcode() == ISD::SUB) {
1532 SDValue N00 = N0.getOperand(0);
1533 SDValue N01 = N0.getOperand(1);
1534 SDValue N10 = N1.getOperand(0);
1535 SDValue N11 = N1.getOperand(1);
1537 if (isa<ConstantSDNode>(N00) || isa<ConstantSDNode>(N10))
1538 return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1539 DAG.getNode(ISD::ADD, SDLoc(N0), VT, N00, N10),
1540 DAG.getNode(ISD::ADD, SDLoc(N1), VT, N01, N11));
1543 if (!VT.isVector() && SimplifyDemandedBits(SDValue(N, 0)))
1544 return SDValue(N, 0);
1546 // fold (a+b) -> (a|b) iff a and b share no bits.
1547 if (VT.isInteger() && !VT.isVector()) {
1548 APInt LHSZero, LHSOne;
1549 APInt RHSZero, RHSOne;
1550 DAG.ComputeMaskedBits(N0, LHSZero, LHSOne);
1552 if (LHSZero.getBoolValue()) {
1553 DAG.ComputeMaskedBits(N1, RHSZero, RHSOne);
1555 // If all possibly-set bits on the LHS are clear on the RHS, return an OR.
1556 // If all possibly-set bits on the RHS are clear on the LHS, return an OR.
1557 if ((RHSZero & ~LHSZero) == ~LHSZero || (LHSZero & ~RHSZero) == ~RHSZero){
1558 if (!LegalOperations || TLI.isOperationLegal(ISD::OR, VT))
1559 return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N1);
1564 // fold (add (shl (add x, c1), c2), ) -> (add (add (shl x, c2), c1<<c2), )
1565 if (N0.getOpcode() == ISD::SHL && N0.getNode()->hasOneUse()) {
1566 SDValue Result = combineShlAddConstant(SDLoc(N), N0, N1, DAG);
1567 if (Result.getNode()) return Result;
1569 if (N1.getOpcode() == ISD::SHL && N1.getNode()->hasOneUse()) {
1570 SDValue Result = combineShlAddConstant(SDLoc(N), N1, N0, DAG);
1571 if (Result.getNode()) return Result;
1574 // fold (add x, shl(0 - y, n)) -> sub(x, shl(y, n))
1575 if (N1.getOpcode() == ISD::SHL &&
1576 N1.getOperand(0).getOpcode() == ISD::SUB)
1577 if (ConstantSDNode *C =
1578 dyn_cast<ConstantSDNode>(N1.getOperand(0).getOperand(0)))
1579 if (C->getAPIntValue() == 0)
1580 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N0,
1581 DAG.getNode(ISD::SHL, SDLoc(N), VT,
1582 N1.getOperand(0).getOperand(1),
1584 if (N0.getOpcode() == ISD::SHL &&
1585 N0.getOperand(0).getOpcode() == ISD::SUB)
1586 if (ConstantSDNode *C =
1587 dyn_cast<ConstantSDNode>(N0.getOperand(0).getOperand(0)))
1588 if (C->getAPIntValue() == 0)
1589 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1,
1590 DAG.getNode(ISD::SHL, SDLoc(N), VT,
1591 N0.getOperand(0).getOperand(1),
1594 if (N1.getOpcode() == ISD::AND) {
1595 SDValue AndOp0 = N1.getOperand(0);
1596 ConstantSDNode *AndOp1 = dyn_cast<ConstantSDNode>(N1->getOperand(1));
1597 unsigned NumSignBits = DAG.ComputeNumSignBits(AndOp0);
1598 unsigned DestBits = VT.getScalarType().getSizeInBits();
1600 // (add z, (and (sbbl x, x), 1)) -> (sub z, (sbbl x, x))
1601 // and similar xforms where the inner op is either ~0 or 0.
1602 if (NumSignBits == DestBits && AndOp1 && AndOp1->isOne()) {
1604 return DAG.getNode(ISD::SUB, DL, VT, N->getOperand(0), AndOp0);
1608 // add (sext i1), X -> sub X, (zext i1)
1609 if (N0.getOpcode() == ISD::SIGN_EXTEND &&
1610 N0.getOperand(0).getValueType() == MVT::i1 &&
1611 !TLI.isOperationLegal(ISD::SIGN_EXTEND, MVT::i1)) {
1613 SDValue ZExt = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0));
1614 return DAG.getNode(ISD::SUB, DL, VT, N1, ZExt);
1620 SDValue DAGCombiner::visitADDC(SDNode *N) {
1621 SDValue N0 = N->getOperand(0);
1622 SDValue N1 = N->getOperand(1);
1623 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1624 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1625 EVT VT = N0.getValueType();
1627 // If the flag result is dead, turn this into an ADD.
1628 if (!N->hasAnyUseOfValue(1))
1629 return CombineTo(N, DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, N1),
1630 DAG.getNode(ISD::CARRY_FALSE,
1631 SDLoc(N), MVT::Glue));
1633 // canonicalize constant to RHS.
1635 return DAG.getNode(ISD::ADDC, SDLoc(N), N->getVTList(), N1, N0);
1637 // fold (addc x, 0) -> x + no carry out
1638 if (N1C && N1C->isNullValue())
1639 return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE,
1640 SDLoc(N), MVT::Glue));
1642 // fold (addc a, b) -> (or a, b), CARRY_FALSE iff a and b share no bits.
1643 APInt LHSZero, LHSOne;
1644 APInt RHSZero, RHSOne;
1645 DAG.ComputeMaskedBits(N0, LHSZero, LHSOne);
1647 if (LHSZero.getBoolValue()) {
1648 DAG.ComputeMaskedBits(N1, RHSZero, RHSOne);
1650 // If all possibly-set bits on the LHS are clear on the RHS, return an OR.
1651 // If all possibly-set bits on the RHS are clear on the LHS, return an OR.
1652 if ((RHSZero & ~LHSZero) == ~LHSZero || (LHSZero & ~RHSZero) == ~RHSZero)
1653 return CombineTo(N, DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N1),
1654 DAG.getNode(ISD::CARRY_FALSE,
1655 SDLoc(N), MVT::Glue));
1661 SDValue DAGCombiner::visitADDE(SDNode *N) {
1662 SDValue N0 = N->getOperand(0);
1663 SDValue N1 = N->getOperand(1);
1664 SDValue CarryIn = N->getOperand(2);
1665 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1666 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1668 // canonicalize constant to RHS
1670 return DAG.getNode(ISD::ADDE, SDLoc(N), N->getVTList(),
1673 // fold (adde x, y, false) -> (addc x, y)
1674 if (CarryIn.getOpcode() == ISD::CARRY_FALSE)
1675 return DAG.getNode(ISD::ADDC, SDLoc(N), N->getVTList(), N0, N1);
1680 // Since it may not be valid to emit a fold to zero for vector initializers
1681 // check if we can before folding.
1682 static SDValue tryFoldToZero(SDLoc DL, const TargetLowering &TLI, EVT VT,
1684 bool LegalOperations, bool LegalTypes) {
1686 return DAG.getConstant(0, VT);
1687 if (!LegalOperations || TLI.isOperationLegal(ISD::BUILD_VECTOR, VT))
1688 return DAG.getConstant(0, VT);
1692 SDValue DAGCombiner::visitSUB(SDNode *N) {
1693 SDValue N0 = N->getOperand(0);
1694 SDValue N1 = N->getOperand(1);
1695 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getNode());
1696 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
1697 ConstantSDNode *N1C1 = N1.getOpcode() != ISD::ADD ? 0 :
1698 dyn_cast<ConstantSDNode>(N1.getOperand(1).getNode());
1699 EVT VT = N0.getValueType();
1702 if (VT.isVector()) {
1703 SDValue FoldedVOp = SimplifyVBinOp(N);
1704 if (FoldedVOp.getNode()) return FoldedVOp;
1706 // fold (sub x, 0) -> x, vector edition
1707 if (ISD::isBuildVectorAllZeros(N1.getNode()))
1711 // fold (sub x, x) -> 0
1712 // FIXME: Refactor this and xor and other similar operations together.
1714 return tryFoldToZero(SDLoc(N), TLI, VT, DAG, LegalOperations, LegalTypes);
1715 // fold (sub c1, c2) -> c1-c2
1717 return DAG.FoldConstantArithmetic(ISD::SUB, VT, N0C, N1C);
1718 // fold (sub x, c) -> (add x, -c)
1720 return DAG.getNode(ISD::ADD, SDLoc(N), VT, N0,
1721 DAG.getConstant(-N1C->getAPIntValue(), VT));
1722 // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1)
1723 if (N0C && N0C->isAllOnesValue())
1724 return DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0);
1725 // fold A-(A-B) -> B
1726 if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(0))
1727 return N1.getOperand(1);
1728 // fold (A+B)-A -> B
1729 if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1)
1730 return N0.getOperand(1);
1731 // fold (A+B)-B -> A
1732 if (N0.getOpcode() == ISD::ADD && N0.getOperand(1) == N1)
1733 return N0.getOperand(0);
1734 // fold C2-(A+C1) -> (C2-C1)-A
1735 if (N1.getOpcode() == ISD::ADD && N0C && N1C1) {
1736 SDValue NewC = DAG.getConstant(N0C->getAPIntValue() - N1C1->getAPIntValue(),
1738 return DAG.getNode(ISD::SUB, SDLoc(N), VT, NewC,
1741 // fold ((A+(B+or-C))-B) -> A+or-C
1742 if (N0.getOpcode() == ISD::ADD &&
1743 (N0.getOperand(1).getOpcode() == ISD::SUB ||
1744 N0.getOperand(1).getOpcode() == ISD::ADD) &&
1745 N0.getOperand(1).getOperand(0) == N1)
1746 return DAG.getNode(N0.getOperand(1).getOpcode(), SDLoc(N), VT,
1747 N0.getOperand(0), N0.getOperand(1).getOperand(1));
1748 // fold ((A+(C+B))-B) -> A+C
1749 if (N0.getOpcode() == ISD::ADD &&
1750 N0.getOperand(1).getOpcode() == ISD::ADD &&
1751 N0.getOperand(1).getOperand(1) == N1)
1752 return DAG.getNode(ISD::ADD, SDLoc(N), VT,
1753 N0.getOperand(0), N0.getOperand(1).getOperand(0));
1754 // fold ((A-(B-C))-C) -> A-B
1755 if (N0.getOpcode() == ISD::SUB &&
1756 N0.getOperand(1).getOpcode() == ISD::SUB &&
1757 N0.getOperand(1).getOperand(1) == N1)
1758 return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1759 N0.getOperand(0), N0.getOperand(1).getOperand(0));
1761 // If either operand of a sub is undef, the result is undef
1762 if (N0.getOpcode() == ISD::UNDEF)
1764 if (N1.getOpcode() == ISD::UNDEF)
1767 // If the relocation model supports it, consider symbol offsets.
1768 if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N0))
1769 if (!LegalOperations && TLI.isOffsetFoldingLegal(GA)) {
1770 // fold (sub Sym, c) -> Sym-c
1771 if (N1C && GA->getOpcode() == ISD::GlobalAddress)
1772 return DAG.getGlobalAddress(GA->getGlobal(), SDLoc(N1C), VT,
1774 (uint64_t)N1C->getSExtValue());
1775 // fold (sub Sym+c1, Sym+c2) -> c1-c2
1776 if (GlobalAddressSDNode *GB = dyn_cast<GlobalAddressSDNode>(N1))
1777 if (GA->getGlobal() == GB->getGlobal())
1778 return DAG.getConstant((uint64_t)GA->getOffset() - GB->getOffset(),
1785 SDValue DAGCombiner::visitSUBC(SDNode *N) {
1786 SDValue N0 = N->getOperand(0);
1787 SDValue N1 = N->getOperand(1);
1788 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1789 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1790 EVT VT = N0.getValueType();
1792 // If the flag result is dead, turn this into an SUB.
1793 if (!N->hasAnyUseOfValue(1))
1794 return CombineTo(N, DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, N1),
1795 DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
1798 // fold (subc x, x) -> 0 + no borrow
1800 return CombineTo(N, DAG.getConstant(0, VT),
1801 DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
1804 // fold (subc x, 0) -> x + no borrow
1805 if (N1C && N1C->isNullValue())
1806 return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
1809 // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1) + no borrow
1810 if (N0C && N0C->isAllOnesValue())
1811 return CombineTo(N, DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0),
1812 DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
1818 SDValue DAGCombiner::visitSUBE(SDNode *N) {
1819 SDValue N0 = N->getOperand(0);
1820 SDValue N1 = N->getOperand(1);
1821 SDValue CarryIn = N->getOperand(2);
1823 // fold (sube x, y, false) -> (subc x, y)
1824 if (CarryIn.getOpcode() == ISD::CARRY_FALSE)
1825 return DAG.getNode(ISD::SUBC, SDLoc(N), N->getVTList(), N0, N1);
1830 /// isConstantSplatVector - Returns true if N is a BUILD_VECTOR node whose
1831 /// elements are all the same constant or undefined.
1832 static bool isConstantSplatVector(SDNode *N, APInt& SplatValue) {
1833 BuildVectorSDNode *C = dyn_cast<BuildVectorSDNode>(N);
1838 unsigned SplatBitSize;
1840 EVT EltVT = N->getValueType(0).getVectorElementType();
1841 return (C->isConstantSplat(SplatValue, SplatUndef, SplatBitSize,
1843 EltVT.getSizeInBits() >= SplatBitSize);
1846 SDValue DAGCombiner::visitMUL(SDNode *N) {
1847 SDValue N0 = N->getOperand(0);
1848 SDValue N1 = N->getOperand(1);
1849 EVT VT = N0.getValueType();
1851 // fold (mul x, undef) -> 0
1852 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
1853 return DAG.getConstant(0, VT);
1855 bool N0IsConst = false;
1856 bool N1IsConst = false;
1857 APInt ConstValue0, ConstValue1;
1859 if (VT.isVector()) {
1860 SDValue FoldedVOp = SimplifyVBinOp(N);
1861 if (FoldedVOp.getNode()) return FoldedVOp;
1863 N0IsConst = isConstantSplatVector(N0.getNode(), ConstValue0);
1864 N1IsConst = isConstantSplatVector(N1.getNode(), ConstValue1);
1866 N0IsConst = dyn_cast<ConstantSDNode>(N0) != 0;
1867 ConstValue0 = N0IsConst ? (dyn_cast<ConstantSDNode>(N0))->getAPIntValue()
1869 N1IsConst = dyn_cast<ConstantSDNode>(N1) != 0;
1870 ConstValue1 = N1IsConst ? (dyn_cast<ConstantSDNode>(N1))->getAPIntValue()
1874 // fold (mul c1, c2) -> c1*c2
1875 if (N0IsConst && N1IsConst)
1876 return DAG.FoldConstantArithmetic(ISD::MUL, VT, N0.getNode(), N1.getNode());
1878 // canonicalize constant to RHS
1879 if (N0IsConst && !N1IsConst)
1880 return DAG.getNode(ISD::MUL, SDLoc(N), VT, N1, N0);
1881 // fold (mul x, 0) -> 0
1882 if (N1IsConst && ConstValue1 == 0)
1884 // We require a splat of the entire scalar bit width for non-contiguous
1887 ConstValue1.getBitWidth() == VT.getScalarType().getSizeInBits();
1888 // fold (mul x, 1) -> x
1889 if (N1IsConst && ConstValue1 == 1 && IsFullSplat)
1891 // fold (mul x, -1) -> 0-x
1892 if (N1IsConst && ConstValue1.isAllOnesValue())
1893 return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1894 DAG.getConstant(0, VT), N0);
1895 // fold (mul x, (1 << c)) -> x << c
1896 if (N1IsConst && ConstValue1.isPowerOf2() && IsFullSplat)
1897 return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0,
1898 DAG.getConstant(ConstValue1.logBase2(),
1899 getShiftAmountTy(N0.getValueType())));
1900 // fold (mul x, -(1 << c)) -> -(x << c) or (-x) << c
1901 if (N1IsConst && (-ConstValue1).isPowerOf2() && IsFullSplat) {
1902 unsigned Log2Val = (-ConstValue1).logBase2();
1903 // FIXME: If the input is something that is easily negated (e.g. a
1904 // single-use add), we should put the negate there.
1905 return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1906 DAG.getConstant(0, VT),
1907 DAG.getNode(ISD::SHL, SDLoc(N), VT, N0,
1908 DAG.getConstant(Log2Val,
1909 getShiftAmountTy(N0.getValueType()))));
1913 // (mul (shl X, c1), c2) -> (mul X, c2 << c1)
1914 if (N1IsConst && N0.getOpcode() == ISD::SHL &&
1915 (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
1916 isa<ConstantSDNode>(N0.getOperand(1)))) {
1917 SDValue C3 = DAG.getNode(ISD::SHL, SDLoc(N), VT,
1918 N1, N0.getOperand(1));
1919 AddToWorkList(C3.getNode());
1920 return DAG.getNode(ISD::MUL, SDLoc(N), VT,
1921 N0.getOperand(0), C3);
1924 // Change (mul (shl X, C), Y) -> (shl (mul X, Y), C) when the shift has one
1927 SDValue Sh(0,0), Y(0,0);
1928 // Check for both (mul (shl X, C), Y) and (mul Y, (shl X, C)).
1929 if (N0.getOpcode() == ISD::SHL &&
1930 (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
1931 isa<ConstantSDNode>(N0.getOperand(1))) &&
1932 N0.getNode()->hasOneUse()) {
1934 } else if (N1.getOpcode() == ISD::SHL &&
1935 isa<ConstantSDNode>(N1.getOperand(1)) &&
1936 N1.getNode()->hasOneUse()) {
1941 SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT,
1942 Sh.getOperand(0), Y);
1943 return DAG.getNode(ISD::SHL, SDLoc(N), VT,
1944 Mul, Sh.getOperand(1));
1948 // fold (mul (add x, c1), c2) -> (add (mul x, c2), c1*c2)
1949 if (N1IsConst && N0.getOpcode() == ISD::ADD && N0.getNode()->hasOneUse() &&
1950 (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
1951 isa<ConstantSDNode>(N0.getOperand(1))))
1952 return DAG.getNode(ISD::ADD, SDLoc(N), VT,
1953 DAG.getNode(ISD::MUL, SDLoc(N0), VT,
1954 N0.getOperand(0), N1),
1955 DAG.getNode(ISD::MUL, SDLoc(N1), VT,
1956 N0.getOperand(1), N1));
1959 SDValue RMUL = ReassociateOps(ISD::MUL, SDLoc(N), N0, N1);
1960 if (RMUL.getNode() != 0)
1966 SDValue DAGCombiner::visitSDIV(SDNode *N) {
1967 SDValue N0 = N->getOperand(0);
1968 SDValue N1 = N->getOperand(1);
1969 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getNode());
1970 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
1971 EVT VT = N->getValueType(0);
1974 if (VT.isVector()) {
1975 SDValue FoldedVOp = SimplifyVBinOp(N);
1976 if (FoldedVOp.getNode()) return FoldedVOp;
1979 // fold (sdiv c1, c2) -> c1/c2
1980 if (N0C && N1C && !N1C->isNullValue())
1981 return DAG.FoldConstantArithmetic(ISD::SDIV, VT, N0C, N1C);
1982 // fold (sdiv X, 1) -> X
1983 if (N1C && N1C->getAPIntValue() == 1LL)
1985 // fold (sdiv X, -1) -> 0-X
1986 if (N1C && N1C->isAllOnesValue())
1987 return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1988 DAG.getConstant(0, VT), N0);
1989 // If we know the sign bits of both operands are zero, strength reduce to a
1990 // udiv instead. Handles (X&15) /s 4 -> X&15 >> 2
1991 if (!VT.isVector()) {
1992 if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
1993 return DAG.getNode(ISD::UDIV, SDLoc(N), N1.getValueType(),
1996 // fold (sdiv X, pow2) -> simple ops after legalize
1997 if (N1C && !N1C->isNullValue() &&
1998 (N1C->getAPIntValue().isPowerOf2() ||
1999 (-N1C->getAPIntValue()).isPowerOf2())) {
2000 // If dividing by powers of two is cheap, then don't perform the following
2002 if (TLI.isPow2DivCheap())
2005 unsigned lg2 = N1C->getAPIntValue().countTrailingZeros();
2007 // Splat the sign bit into the register
2008 SDValue SGN = DAG.getNode(ISD::SRA, SDLoc(N), VT, N0,
2009 DAG.getConstant(VT.getSizeInBits()-1,
2010 getShiftAmountTy(N0.getValueType())));
2011 AddToWorkList(SGN.getNode());
2013 // Add (N0 < 0) ? abs2 - 1 : 0;
2014 SDValue SRL = DAG.getNode(ISD::SRL, SDLoc(N), VT, SGN,
2015 DAG.getConstant(VT.getSizeInBits() - lg2,
2016 getShiftAmountTy(SGN.getValueType())));
2017 SDValue ADD = DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, SRL);
2018 AddToWorkList(SRL.getNode());
2019 AddToWorkList(ADD.getNode()); // Divide by pow2
2020 SDValue SRA = DAG.getNode(ISD::SRA, SDLoc(N), VT, ADD,
2021 DAG.getConstant(lg2, getShiftAmountTy(ADD.getValueType())));
2023 // If we're dividing by a positive value, we're done. Otherwise, we must
2024 // negate the result.
2025 if (N1C->getAPIntValue().isNonNegative())
2028 AddToWorkList(SRA.getNode());
2029 return DAG.getNode(ISD::SUB, SDLoc(N), VT,
2030 DAG.getConstant(0, VT), SRA);
2033 // if integer divide is expensive and we satisfy the requirements, emit an
2034 // alternate sequence.
2035 if (N1C && !N1C->isNullValue() && !TLI.isIntDivCheap()) {
2036 SDValue Op = BuildSDIV(N);
2037 if (Op.getNode()) return Op;
2041 if (N0.getOpcode() == ISD::UNDEF)
2042 return DAG.getConstant(0, VT);
2043 // X / undef -> undef
2044 if (N1.getOpcode() == ISD::UNDEF)
2050 SDValue DAGCombiner::visitUDIV(SDNode *N) {
2051 SDValue N0 = N->getOperand(0);
2052 SDValue N1 = N->getOperand(1);
2053 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getNode());
2054 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
2055 EVT VT = N->getValueType(0);
2058 if (VT.isVector()) {
2059 SDValue FoldedVOp = SimplifyVBinOp(N);
2060 if (FoldedVOp.getNode()) return FoldedVOp;
2063 // fold (udiv c1, c2) -> c1/c2
2064 if (N0C && N1C && !N1C->isNullValue())
2065 return DAG.FoldConstantArithmetic(ISD::UDIV, VT, N0C, N1C);
2066 // fold (udiv x, (1 << c)) -> x >>u c
2067 if (N1C && N1C->getAPIntValue().isPowerOf2())
2068 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0,
2069 DAG.getConstant(N1C->getAPIntValue().logBase2(),
2070 getShiftAmountTy(N0.getValueType())));
2071 // fold (udiv x, (shl c, y)) -> x >>u (log2(c)+y) iff c is power of 2
2072 if (N1.getOpcode() == ISD::SHL) {
2073 if (ConstantSDNode *SHC = dyn_cast<ConstantSDNode>(N1.getOperand(0))) {
2074 if (SHC->getAPIntValue().isPowerOf2()) {
2075 EVT ADDVT = N1.getOperand(1).getValueType();
2076 SDValue Add = DAG.getNode(ISD::ADD, SDLoc(N), ADDVT,
2078 DAG.getConstant(SHC->getAPIntValue()
2081 AddToWorkList(Add.getNode());
2082 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, Add);
2086 // fold (udiv x, c) -> alternate
2087 if (N1C && !N1C->isNullValue() && !TLI.isIntDivCheap()) {
2088 SDValue Op = BuildUDIV(N);
2089 if (Op.getNode()) return Op;
2093 if (N0.getOpcode() == ISD::UNDEF)
2094 return DAG.getConstant(0, VT);
2095 // X / undef -> undef
2096 if (N1.getOpcode() == ISD::UNDEF)
2102 SDValue DAGCombiner::visitSREM(SDNode *N) {
2103 SDValue N0 = N->getOperand(0);
2104 SDValue N1 = N->getOperand(1);
2105 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
2106 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2107 EVT VT = N->getValueType(0);
2109 // fold (srem c1, c2) -> c1%c2
2110 if (N0C && N1C && !N1C->isNullValue())
2111 return DAG.FoldConstantArithmetic(ISD::SREM, VT, N0C, N1C);
2112 // If we know the sign bits of both operands are zero, strength reduce to a
2113 // urem instead. Handles (X & 0x0FFFFFFF) %s 16 -> X&15
2114 if (!VT.isVector()) {
2115 if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
2116 return DAG.getNode(ISD::UREM, SDLoc(N), VT, N0, N1);
2119 // If X/C can be simplified by the division-by-constant logic, lower
2120 // X%C to the equivalent of X-X/C*C.
2121 if (N1C && !N1C->isNullValue()) {
2122 SDValue Div = DAG.getNode(ISD::SDIV, SDLoc(N), VT, N0, N1);
2123 AddToWorkList(Div.getNode());
2124 SDValue OptimizedDiv = combine(Div.getNode());
2125 if (OptimizedDiv.getNode() && OptimizedDiv.getNode() != Div.getNode()) {
2126 SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT,
2128 SDValue Sub = DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, Mul);
2129 AddToWorkList(Mul.getNode());
2135 if (N0.getOpcode() == ISD::UNDEF)
2136 return DAG.getConstant(0, VT);
2137 // X % undef -> undef
2138 if (N1.getOpcode() == ISD::UNDEF)
2144 SDValue DAGCombiner::visitUREM(SDNode *N) {
2145 SDValue N0 = N->getOperand(0);
2146 SDValue N1 = N->getOperand(1);
2147 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
2148 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2149 EVT VT = N->getValueType(0);
2151 // fold (urem c1, c2) -> c1%c2
2152 if (N0C && N1C && !N1C->isNullValue())
2153 return DAG.FoldConstantArithmetic(ISD::UREM, VT, N0C, N1C);
2154 // fold (urem x, pow2) -> (and x, pow2-1)
2155 if (N1C && !N1C->isNullValue() && N1C->getAPIntValue().isPowerOf2())
2156 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0,
2157 DAG.getConstant(N1C->getAPIntValue()-1,VT));
2158 // fold (urem x, (shl pow2, y)) -> (and x, (add (shl pow2, y), -1))
2159 if (N1.getOpcode() == ISD::SHL) {
2160 if (ConstantSDNode *SHC = dyn_cast<ConstantSDNode>(N1.getOperand(0))) {
2161 if (SHC->getAPIntValue().isPowerOf2()) {
2163 DAG.getNode(ISD::ADD, SDLoc(N), VT, N1,
2164 DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()),
2166 AddToWorkList(Add.getNode());
2167 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, Add);
2172 // If X/C can be simplified by the division-by-constant logic, lower
2173 // X%C to the equivalent of X-X/C*C.
2174 if (N1C && !N1C->isNullValue()) {
2175 SDValue Div = DAG.getNode(ISD::UDIV, SDLoc(N), VT, N0, N1);
2176 AddToWorkList(Div.getNode());
2177 SDValue OptimizedDiv = combine(Div.getNode());
2178 if (OptimizedDiv.getNode() && OptimizedDiv.getNode() != Div.getNode()) {
2179 SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT,
2181 SDValue Sub = DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, Mul);
2182 AddToWorkList(Mul.getNode());
2188 if (N0.getOpcode() == ISD::UNDEF)
2189 return DAG.getConstant(0, VT);
2190 // X % undef -> undef
2191 if (N1.getOpcode() == ISD::UNDEF)
2197 SDValue DAGCombiner::visitMULHS(SDNode *N) {
2198 SDValue N0 = N->getOperand(0);
2199 SDValue N1 = N->getOperand(1);
2200 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2201 EVT VT = N->getValueType(0);
2204 // fold (mulhs x, 0) -> 0
2205 if (N1C && N1C->isNullValue())
2207 // fold (mulhs x, 1) -> (sra x, size(x)-1)
2208 if (N1C && N1C->getAPIntValue() == 1)
2209 return DAG.getNode(ISD::SRA, SDLoc(N), N0.getValueType(), N0,
2210 DAG.getConstant(N0.getValueType().getSizeInBits() - 1,
2211 getShiftAmountTy(N0.getValueType())));
2212 // fold (mulhs x, undef) -> 0
2213 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2214 return DAG.getConstant(0, VT);
2216 // If the type twice as wide is legal, transform the mulhs to a wider multiply
2218 if (VT.isSimple() && !VT.isVector()) {
2219 MVT Simple = VT.getSimpleVT();
2220 unsigned SimpleSize = Simple.getSizeInBits();
2221 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2222 if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2223 N0 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N0);
2224 N1 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N1);
2225 N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1);
2226 N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1,
2227 DAG.getConstant(SimpleSize, getShiftAmountTy(N1.getValueType())));
2228 return DAG.getNode(ISD::TRUNCATE, DL, VT, N1);
2235 SDValue DAGCombiner::visitMULHU(SDNode *N) {
2236 SDValue N0 = N->getOperand(0);
2237 SDValue N1 = N->getOperand(1);
2238 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2239 EVT VT = N->getValueType(0);
2242 // fold (mulhu x, 0) -> 0
2243 if (N1C && N1C->isNullValue())
2245 // fold (mulhu x, 1) -> 0
2246 if (N1C && N1C->getAPIntValue() == 1)
2247 return DAG.getConstant(0, N0.getValueType());
2248 // fold (mulhu x, undef) -> 0
2249 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2250 return DAG.getConstant(0, VT);
2252 // If the type twice as wide is legal, transform the mulhu to a wider multiply
2254 if (VT.isSimple() && !VT.isVector()) {
2255 MVT Simple = VT.getSimpleVT();
2256 unsigned SimpleSize = Simple.getSizeInBits();
2257 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2258 if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2259 N0 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N0);
2260 N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N1);
2261 N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1);
2262 N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1,
2263 DAG.getConstant(SimpleSize, getShiftAmountTy(N1.getValueType())));
2264 return DAG.getNode(ISD::TRUNCATE, DL, VT, N1);
2271 /// SimplifyNodeWithTwoResults - Perform optimizations common to nodes that
2272 /// compute two values. LoOp and HiOp give the opcodes for the two computations
2273 /// that are being performed. Return true if a simplification was made.
2275 SDValue DAGCombiner::SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp,
2277 // If the high half is not needed, just compute the low half.
2278 bool HiExists = N->hasAnyUseOfValue(1);
2280 (!LegalOperations ||
2281 TLI.isOperationLegalOrCustom(LoOp, N->getValueType(0)))) {
2282 SDValue Res = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0),
2283 N->op_begin(), N->getNumOperands());
2284 return CombineTo(N, Res, Res);
2287 // If the low half is not needed, just compute the high half.
2288 bool LoExists = N->hasAnyUseOfValue(0);
2290 (!LegalOperations ||
2291 TLI.isOperationLegal(HiOp, N->getValueType(1)))) {
2292 SDValue Res = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1),
2293 N->op_begin(), N->getNumOperands());
2294 return CombineTo(N, Res, Res);
2297 // If both halves are used, return as it is.
2298 if (LoExists && HiExists)
2301 // If the two computed results can be simplified separately, separate them.
2303 SDValue Lo = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0),
2304 N->op_begin(), N->getNumOperands());
2305 AddToWorkList(Lo.getNode());
2306 SDValue LoOpt = combine(Lo.getNode());
2307 if (LoOpt.getNode() && LoOpt.getNode() != Lo.getNode() &&
2308 (!LegalOperations ||
2309 TLI.isOperationLegal(LoOpt.getOpcode(), LoOpt.getValueType())))
2310 return CombineTo(N, LoOpt, LoOpt);
2314 SDValue Hi = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1),
2315 N->op_begin(), N->getNumOperands());
2316 AddToWorkList(Hi.getNode());
2317 SDValue HiOpt = combine(Hi.getNode());
2318 if (HiOpt.getNode() && HiOpt != Hi &&
2319 (!LegalOperations ||
2320 TLI.isOperationLegal(HiOpt.getOpcode(), HiOpt.getValueType())))
2321 return CombineTo(N, HiOpt, HiOpt);
2327 SDValue DAGCombiner::visitSMUL_LOHI(SDNode *N) {
2328 SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHS);
2329 if (Res.getNode()) return Res;
2331 EVT VT = N->getValueType(0);
2334 // If the type twice as wide is legal, transform the mulhu to a wider multiply
2336 if (VT.isSimple() && !VT.isVector()) {
2337 MVT Simple = VT.getSimpleVT();
2338 unsigned SimpleSize = Simple.getSizeInBits();
2339 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2340 if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2341 SDValue Lo = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(0));
2342 SDValue Hi = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(1));
2343 Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi);
2344 // Compute the high part as N1.
2345 Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo,
2346 DAG.getConstant(SimpleSize, getShiftAmountTy(Lo.getValueType())));
2347 Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi);
2348 // Compute the low part as N0.
2349 Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo);
2350 return CombineTo(N, Lo, Hi);
2357 SDValue DAGCombiner::visitUMUL_LOHI(SDNode *N) {
2358 SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHU);
2359 if (Res.getNode()) return Res;
2361 EVT VT = N->getValueType(0);
2364 // If the type twice as wide is legal, transform the mulhu to a wider multiply
2366 if (VT.isSimple() && !VT.isVector()) {
2367 MVT Simple = VT.getSimpleVT();
2368 unsigned SimpleSize = Simple.getSizeInBits();
2369 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2370 if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2371 SDValue Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(0));
2372 SDValue Hi = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(1));
2373 Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi);
2374 // Compute the high part as N1.
2375 Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo,
2376 DAG.getConstant(SimpleSize, getShiftAmountTy(Lo.getValueType())));
2377 Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi);
2378 // Compute the low part as N0.
2379 Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo);
2380 return CombineTo(N, Lo, Hi);
2387 SDValue DAGCombiner::visitSMULO(SDNode *N) {
2388 // (smulo x, 2) -> (saddo x, x)
2389 if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1)))
2390 if (C2->getAPIntValue() == 2)
2391 return DAG.getNode(ISD::SADDO, SDLoc(N), N->getVTList(),
2392 N->getOperand(0), N->getOperand(0));
2397 SDValue DAGCombiner::visitUMULO(SDNode *N) {
2398 // (umulo x, 2) -> (uaddo x, x)
2399 if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1)))
2400 if (C2->getAPIntValue() == 2)
2401 return DAG.getNode(ISD::UADDO, SDLoc(N), N->getVTList(),
2402 N->getOperand(0), N->getOperand(0));
2407 SDValue DAGCombiner::visitSDIVREM(SDNode *N) {
2408 SDValue Res = SimplifyNodeWithTwoResults(N, ISD::SDIV, ISD::SREM);
2409 if (Res.getNode()) return Res;
2414 SDValue DAGCombiner::visitUDIVREM(SDNode *N) {
2415 SDValue Res = SimplifyNodeWithTwoResults(N, ISD::UDIV, ISD::UREM);
2416 if (Res.getNode()) return Res;
2421 /// SimplifyBinOpWithSameOpcodeHands - If this is a binary operator with
2422 /// two operands of the same opcode, try to simplify it.
2423 SDValue DAGCombiner::SimplifyBinOpWithSameOpcodeHands(SDNode *N) {
2424 SDValue N0 = N->getOperand(0), N1 = N->getOperand(1);
2425 EVT VT = N0.getValueType();
2426 assert(N0.getOpcode() == N1.getOpcode() && "Bad input!");
2428 // Bail early if none of these transforms apply.
2429 if (N0.getNode()->getNumOperands() == 0) return SDValue();
2431 // For each of OP in AND/OR/XOR:
2432 // fold (OP (zext x), (zext y)) -> (zext (OP x, y))
2433 // fold (OP (sext x), (sext y)) -> (sext (OP x, y))
2434 // fold (OP (aext x), (aext y)) -> (aext (OP x, y))
2435 // fold (OP (trunc x), (trunc y)) -> (trunc (OP x, y)) (if trunc isn't free)
2437 // do not sink logical op inside of a vector extend, since it may combine
2439 EVT Op0VT = N0.getOperand(0).getValueType();
2440 if ((N0.getOpcode() == ISD::ZERO_EXTEND ||
2441 N0.getOpcode() == ISD::SIGN_EXTEND ||
2442 // Avoid infinite looping with PromoteIntBinOp.
2443 (N0.getOpcode() == ISD::ANY_EXTEND &&
2444 (!LegalTypes || TLI.isTypeDesirableForOp(N->getOpcode(), Op0VT))) ||
2445 (N0.getOpcode() == ISD::TRUNCATE &&
2446 (!TLI.isZExtFree(VT, Op0VT) ||
2447 !TLI.isTruncateFree(Op0VT, VT)) &&
2448 TLI.isTypeLegal(Op0VT))) &&
2450 Op0VT == N1.getOperand(0).getValueType() &&
2451 (!LegalOperations || TLI.isOperationLegal(N->getOpcode(), Op0VT))) {
2452 SDValue ORNode = DAG.getNode(N->getOpcode(), SDLoc(N0),
2453 N0.getOperand(0).getValueType(),
2454 N0.getOperand(0), N1.getOperand(0));
2455 AddToWorkList(ORNode.getNode());
2456 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, ORNode);
2459 // For each of OP in SHL/SRL/SRA/AND...
2460 // fold (and (OP x, z), (OP y, z)) -> (OP (and x, y), z)
2461 // fold (or (OP x, z), (OP y, z)) -> (OP (or x, y), z)
2462 // fold (xor (OP x, z), (OP y, z)) -> (OP (xor x, y), z)
2463 if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL ||
2464 N0.getOpcode() == ISD::SRA || N0.getOpcode() == ISD::AND) &&
2465 N0.getOperand(1) == N1.getOperand(1)) {
2466 SDValue ORNode = DAG.getNode(N->getOpcode(), SDLoc(N0),
2467 N0.getOperand(0).getValueType(),
2468 N0.getOperand(0), N1.getOperand(0));
2469 AddToWorkList(ORNode.getNode());
2470 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
2471 ORNode, N0.getOperand(1));
2474 // Simplify xor/and/or (bitcast(A), bitcast(B)) -> bitcast(op (A,B))
2475 // Only perform this optimization after type legalization and before
2476 // LegalizeVectorOprs. LegalizeVectorOprs promotes vector operations by
2477 // adding bitcasts. For example (xor v4i32) is promoted to (v2i64), and
2478 // we don't want to undo this promotion.
2479 // We also handle SCALAR_TO_VECTOR because xor/or/and operations are cheaper
2481 if ((N0.getOpcode() == ISD::BITCAST ||
2482 N0.getOpcode() == ISD::SCALAR_TO_VECTOR) &&
2483 Level == AfterLegalizeTypes) {
2484 SDValue In0 = N0.getOperand(0);
2485 SDValue In1 = N1.getOperand(0);
2486 EVT In0Ty = In0.getValueType();
2487 EVT In1Ty = In1.getValueType();
2489 // If both incoming values are integers, and the original types are the
2491 if (In0Ty.isInteger() && In1Ty.isInteger() && In0Ty == In1Ty) {
2492 SDValue Op = DAG.getNode(N->getOpcode(), DL, In0Ty, In0, In1);
2493 SDValue BC = DAG.getNode(N0.getOpcode(), DL, VT, Op);
2494 AddToWorkList(Op.getNode());
2499 // Xor/and/or are indifferent to the swizzle operation (shuffle of one value).
2500 // Simplify xor/and/or (shuff(A), shuff(B)) -> shuff(op (A,B))
2501 // If both shuffles use the same mask, and both shuffle within a single
2502 // vector, then it is worthwhile to move the swizzle after the operation.
2503 // The type-legalizer generates this pattern when loading illegal
2504 // vector types from memory. In many cases this allows additional shuffle
2506 if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG &&
2507 N0.getOperand(1).getOpcode() == ISD::UNDEF &&
2508 N1.getOperand(1).getOpcode() == ISD::UNDEF) {
2509 ShuffleVectorSDNode *SVN0 = cast<ShuffleVectorSDNode>(N0);
2510 ShuffleVectorSDNode *SVN1 = cast<ShuffleVectorSDNode>(N1);
2512 assert(N0.getOperand(0).getValueType() == N1.getOperand(1).getValueType() &&
2513 "Inputs to shuffles are not the same type");
2515 unsigned NumElts = VT.getVectorNumElements();
2517 // Check that both shuffles use the same mask. The masks are known to be of
2518 // the same length because the result vector type is the same.
2519 bool SameMask = true;
2520 for (unsigned i = 0; i != NumElts; ++i) {
2521 int Idx0 = SVN0->getMaskElt(i);
2522 int Idx1 = SVN1->getMaskElt(i);
2530 SDValue Op = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
2531 N0.getOperand(0), N1.getOperand(0));
2532 AddToWorkList(Op.getNode());
2533 return DAG.getVectorShuffle(VT, SDLoc(N), Op,
2534 DAG.getUNDEF(VT), &SVN0->getMask()[0]);
2541 SDValue DAGCombiner::visitAND(SDNode *N) {
2542 SDValue N0 = N->getOperand(0);
2543 SDValue N1 = N->getOperand(1);
2544 SDValue LL, LR, RL, RR, CC0, CC1;
2545 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
2546 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2547 EVT VT = N1.getValueType();
2548 unsigned BitWidth = VT.getScalarType().getSizeInBits();
2551 if (VT.isVector()) {
2552 SDValue FoldedVOp = SimplifyVBinOp(N);
2553 if (FoldedVOp.getNode()) return FoldedVOp;
2555 // fold (and x, 0) -> 0, vector edition
2556 if (ISD::isBuildVectorAllZeros(N0.getNode()))
2558 if (ISD::isBuildVectorAllZeros(N1.getNode()))
2561 // fold (and x, -1) -> x, vector edition
2562 if (ISD::isBuildVectorAllOnes(N0.getNode()))
2564 if (ISD::isBuildVectorAllOnes(N1.getNode()))
2568 // fold (and x, undef) -> 0
2569 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2570 return DAG.getConstant(0, VT);
2571 // fold (and c1, c2) -> c1&c2
2573 return DAG.FoldConstantArithmetic(ISD::AND, VT, N0C, N1C);
2574 // canonicalize constant to RHS
2576 return DAG.getNode(ISD::AND, SDLoc(N), VT, N1, N0);
2577 // fold (and x, -1) -> x
2578 if (N1C && N1C->isAllOnesValue())
2580 // if (and x, c) is known to be zero, return 0
2581 if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0),
2582 APInt::getAllOnesValue(BitWidth)))
2583 return DAG.getConstant(0, VT);
2585 SDValue RAND = ReassociateOps(ISD::AND, SDLoc(N), N0, N1);
2586 if (RAND.getNode() != 0)
2588 // fold (and (or x, C), D) -> D if (C & D) == D
2589 if (N1C && N0.getOpcode() == ISD::OR)
2590 if (ConstantSDNode *ORI = dyn_cast<ConstantSDNode>(N0.getOperand(1)))
2591 if ((ORI->getAPIntValue() & N1C->getAPIntValue()) == N1C->getAPIntValue())
2593 // fold (and (any_ext V), c) -> (zero_ext V) if 'and' only clears top bits.
2594 if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
2595 SDValue N0Op0 = N0.getOperand(0);
2596 APInt Mask = ~N1C->getAPIntValue();
2597 Mask = Mask.trunc(N0Op0.getValueSizeInBits());
2598 if (DAG.MaskedValueIsZero(N0Op0, Mask)) {
2599 SDValue Zext = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N),
2600 N0.getValueType(), N0Op0);
2602 // Replace uses of the AND with uses of the Zero extend node.
2605 // We actually want to replace all uses of the any_extend with the
2606 // zero_extend, to avoid duplicating things. This will later cause this
2607 // AND to be folded.
2608 CombineTo(N0.getNode(), Zext);
2609 return SDValue(N, 0); // Return N so it doesn't get rechecked!
2612 // similarly fold (and (X (load ([non_ext|any_ext|zero_ext] V))), c) ->
2613 // (X (load ([non_ext|zero_ext] V))) if 'and' only clears top bits which must
2614 // already be zero by virtue of the width of the base type of the load.
2616 // the 'X' node here can either be nothing or an extract_vector_elt to catch
2618 if ((N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
2619 N0.getOperand(0).getOpcode() == ISD::LOAD) ||
2620 N0.getOpcode() == ISD::LOAD) {
2621 LoadSDNode *Load = cast<LoadSDNode>( (N0.getOpcode() == ISD::LOAD) ?
2622 N0 : N0.getOperand(0) );
2624 // Get the constant (if applicable) the zero'th operand is being ANDed with.
2625 // This can be a pure constant or a vector splat, in which case we treat the
2626 // vector as a scalar and use the splat value.
2627 APInt Constant = APInt::getNullValue(1);
2628 if (const ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
2629 Constant = C->getAPIntValue();
2630 } else if (BuildVectorSDNode *Vector = dyn_cast<BuildVectorSDNode>(N1)) {
2631 APInt SplatValue, SplatUndef;
2632 unsigned SplatBitSize;
2634 bool IsSplat = Vector->isConstantSplat(SplatValue, SplatUndef,
2635 SplatBitSize, HasAnyUndefs);
2637 // Undef bits can contribute to a possible optimisation if set, so
2639 SplatValue |= SplatUndef;
2641 // The splat value may be something like "0x00FFFFFF", which means 0 for
2642 // the first vector value and FF for the rest, repeating. We need a mask
2643 // that will apply equally to all members of the vector, so AND all the
2644 // lanes of the constant together.
2645 EVT VT = Vector->getValueType(0);
2646 unsigned BitWidth = VT.getVectorElementType().getSizeInBits();
2648 // If the splat value has been compressed to a bitlength lower
2649 // than the size of the vector lane, we need to re-expand it to
2651 if (BitWidth > SplatBitSize)
2652 for (SplatValue = SplatValue.zextOrTrunc(BitWidth);
2653 SplatBitSize < BitWidth;
2654 SplatBitSize = SplatBitSize * 2)
2655 SplatValue |= SplatValue.shl(SplatBitSize);
2657 Constant = APInt::getAllOnesValue(BitWidth);
2658 for (unsigned i = 0, n = SplatBitSize/BitWidth; i < n; ++i)
2659 Constant &= SplatValue.lshr(i*BitWidth).zextOrTrunc(BitWidth);
2663 // If we want to change an EXTLOAD to a ZEXTLOAD, ensure a ZEXTLOAD is
2664 // actually legal and isn't going to get expanded, else this is a false
2666 bool CanZextLoadProfitably = TLI.isLoadExtLegal(ISD::ZEXTLOAD,
2667 Load->getMemoryVT());
2669 // Resize the constant to the same size as the original memory access before
2670 // extension. If it is still the AllOnesValue then this AND is completely
2673 Constant.zextOrTrunc(Load->getMemoryVT().getScalarType().getSizeInBits());
2676 switch (Load->getExtensionType()) {
2677 default: B = false; break;
2678 case ISD::EXTLOAD: B = CanZextLoadProfitably; break;
2680 case ISD::NON_EXTLOAD: B = true; break;
2683 if (B && Constant.isAllOnesValue()) {
2684 // If the load type was an EXTLOAD, convert to ZEXTLOAD in order to
2685 // preserve semantics once we get rid of the AND.
2686 SDValue NewLoad(Load, 0);
2687 if (Load->getExtensionType() == ISD::EXTLOAD) {
2688 NewLoad = DAG.getLoad(Load->getAddressingMode(), ISD::ZEXTLOAD,
2689 Load->getValueType(0), SDLoc(Load),
2690 Load->getChain(), Load->getBasePtr(),
2691 Load->getOffset(), Load->getMemoryVT(),
2692 Load->getMemOperand());
2693 // Replace uses of the EXTLOAD with the new ZEXTLOAD.
2694 if (Load->getNumValues() == 3) {
2695 // PRE/POST_INC loads have 3 values.
2696 SDValue To[] = { NewLoad.getValue(0), NewLoad.getValue(1),
2697 NewLoad.getValue(2) };
2698 CombineTo(Load, To, 3, true);
2700 CombineTo(Load, NewLoad.getValue(0), NewLoad.getValue(1));
2704 // Fold the AND away, taking care not to fold to the old load node if we
2706 CombineTo(N, (N0.getNode() == Load) ? NewLoad : N0);
2708 return SDValue(N, 0); // Return N so it doesn't get rechecked!
2711 // fold (and (setcc x), (setcc y)) -> (setcc (and x, y))
2712 if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){
2713 ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get();
2714 ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get();
2716 if (LR == RR && isa<ConstantSDNode>(LR) && Op0 == Op1 &&
2717 LL.getValueType().isInteger()) {
2718 // fold (and (seteq X, 0), (seteq Y, 0)) -> (seteq (or X, Y), 0)
2719 if (cast<ConstantSDNode>(LR)->isNullValue() && Op1 == ISD::SETEQ) {
2720 SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(N0),
2721 LR.getValueType(), LL, RL);
2722 AddToWorkList(ORNode.getNode());
2723 return DAG.getSetCC(SDLoc(N), VT, ORNode, LR, Op1);
2725 // fold (and (seteq X, -1), (seteq Y, -1)) -> (seteq (and X, Y), -1)
2726 if (cast<ConstantSDNode>(LR)->isAllOnesValue() && Op1 == ISD::SETEQ) {
2727 SDValue ANDNode = DAG.getNode(ISD::AND, SDLoc(N0),
2728 LR.getValueType(), LL, RL);
2729 AddToWorkList(ANDNode.getNode());
2730 return DAG.getSetCC(SDLoc(N), VT, ANDNode, LR, Op1);
2732 // fold (and (setgt X, -1), (setgt Y, -1)) -> (setgt (or X, Y), -1)
2733 if (cast<ConstantSDNode>(LR)->isAllOnesValue() && Op1 == ISD::SETGT) {
2734 SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(N0),
2735 LR.getValueType(), LL, RL);
2736 AddToWorkList(ORNode.getNode());
2737 return DAG.getSetCC(SDLoc(N), VT, ORNode, LR, Op1);
2740 // Simplify (and (setne X, 0), (setne X, -1)) -> (setuge (add X, 1), 2)
2741 if (LL == RL && isa<ConstantSDNode>(LR) && isa<ConstantSDNode>(RR) &&
2742 Op0 == Op1 && LL.getValueType().isInteger() &&
2743 Op0 == ISD::SETNE && ((cast<ConstantSDNode>(LR)->isNullValue() &&
2744 cast<ConstantSDNode>(RR)->isAllOnesValue()) ||
2745 (cast<ConstantSDNode>(LR)->isAllOnesValue() &&
2746 cast<ConstantSDNode>(RR)->isNullValue()))) {
2747 SDValue ADDNode = DAG.getNode(ISD::ADD, SDLoc(N0), LL.getValueType(),
2748 LL, DAG.getConstant(1, LL.getValueType()));
2749 AddToWorkList(ADDNode.getNode());
2750 return DAG.getSetCC(SDLoc(N), VT, ADDNode,
2751 DAG.getConstant(2, LL.getValueType()), ISD::SETUGE);
2753 // canonicalize equivalent to ll == rl
2754 if (LL == RR && LR == RL) {
2755 Op1 = ISD::getSetCCSwappedOperands(Op1);
2758 if (LL == RL && LR == RR) {
2759 bool isInteger = LL.getValueType().isInteger();
2760 ISD::CondCode Result = ISD::getSetCCAndOperation(Op0, Op1, isInteger);
2761 if (Result != ISD::SETCC_INVALID &&
2762 (!LegalOperations ||
2763 (TLI.isCondCodeLegal(Result, LL.getSimpleValueType()) &&
2764 TLI.isOperationLegal(ISD::SETCC,
2765 getSetCCResultType(N0.getSimpleValueType())))))
2766 return DAG.getSetCC(SDLoc(N), N0.getValueType(),
2771 // Simplify: (and (op x...), (op y...)) -> (op (and x, y))
2772 if (N0.getOpcode() == N1.getOpcode()) {
2773 SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
2774 if (Tmp.getNode()) return Tmp;
2777 // fold (and (sign_extend_inreg x, i16 to i32), 1) -> (and x, 1)
2778 // fold (and (sra)) -> (and (srl)) when possible.
2779 if (!VT.isVector() &&
2780 SimplifyDemandedBits(SDValue(N, 0)))
2781 return SDValue(N, 0);
2783 // fold (zext_inreg (extload x)) -> (zextload x)
2784 if (ISD::isEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode())) {
2785 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
2786 EVT MemVT = LN0->getMemoryVT();
2787 // If we zero all the possible extended bits, then we can turn this into
2788 // a zextload if we are running before legalize or the operation is legal.
2789 unsigned BitWidth = N1.getValueType().getScalarType().getSizeInBits();
2790 if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth,
2791 BitWidth - MemVT.getScalarType().getSizeInBits())) &&
2792 ((!LegalOperations && !LN0->isVolatile()) ||
2793 TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT))) {
2794 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N0), VT,
2795 LN0->getChain(), LN0->getBasePtr(),
2796 MemVT, LN0->getMemOperand());
2798 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
2799 return SDValue(N, 0); // Return N so it doesn't get rechecked!
2802 // fold (zext_inreg (sextload x)) -> (zextload x) iff load has one use
2803 if (ISD::isSEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
2805 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
2806 EVT MemVT = LN0->getMemoryVT();
2807 // If we zero all the possible extended bits, then we can turn this into
2808 // a zextload if we are running before legalize or the operation is legal.
2809 unsigned BitWidth = N1.getValueType().getScalarType().getSizeInBits();
2810 if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth,
2811 BitWidth - MemVT.getScalarType().getSizeInBits())) &&
2812 ((!LegalOperations && !LN0->isVolatile()) ||
2813 TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT))) {
2814 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N0), VT,
2815 LN0->getChain(), LN0->getBasePtr(),
2816 MemVT, LN0->getMemOperand());
2818 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
2819 return SDValue(N, 0); // Return N so it doesn't get rechecked!
2823 // fold (and (load x), 255) -> (zextload x, i8)
2824 // fold (and (extload x, i16), 255) -> (zextload x, i8)
2825 // fold (and (any_ext (extload x, i16)), 255) -> (zextload x, i8)
2826 if (N1C && (N0.getOpcode() == ISD::LOAD ||
2827 (N0.getOpcode() == ISD::ANY_EXTEND &&
2828 N0.getOperand(0).getOpcode() == ISD::LOAD))) {
2829 bool HasAnyExt = N0.getOpcode() == ISD::ANY_EXTEND;
2830 LoadSDNode *LN0 = HasAnyExt
2831 ? cast<LoadSDNode>(N0.getOperand(0))
2832 : cast<LoadSDNode>(N0);
2833 if (LN0->getExtensionType() != ISD::SEXTLOAD &&
2834 LN0->isUnindexed() && N0.hasOneUse() && SDValue(LN0, 0).hasOneUse()) {
2835 uint32_t ActiveBits = N1C->getAPIntValue().getActiveBits();
2836 if (ActiveBits > 0 && APIntOps::isMask(ActiveBits, N1C->getAPIntValue())){
2837 EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), ActiveBits);
2838 EVT LoadedVT = LN0->getMemoryVT();
2840 if (ExtVT == LoadedVT &&
2841 (!LegalOperations || TLI.isLoadExtLegal(ISD::ZEXTLOAD, ExtVT))) {
2842 EVT LoadResultTy = HasAnyExt ? LN0->getValueType(0) : VT;
2845 DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), LoadResultTy,
2846 LN0->getChain(), LN0->getBasePtr(), ExtVT,
2847 LN0->getMemOperand());
2849 CombineTo(LN0, NewLoad, NewLoad.getValue(1));
2850 return SDValue(N, 0); // Return N so it doesn't get rechecked!
2853 // Do not change the width of a volatile load.
2854 // Do not generate loads of non-round integer types since these can
2855 // be expensive (and would be wrong if the type is not byte sized).
2856 if (!LN0->isVolatile() && LoadedVT.bitsGT(ExtVT) && ExtVT.isRound() &&
2857 (!LegalOperations || TLI.isLoadExtLegal(ISD::ZEXTLOAD, ExtVT))) {
2858 EVT PtrType = LN0->getOperand(1).getValueType();
2860 unsigned Alignment = LN0->getAlignment();
2861 SDValue NewPtr = LN0->getBasePtr();
2863 // For big endian targets, we need to add an offset to the pointer
2864 // to load the correct bytes. For little endian systems, we merely
2865 // need to read fewer bytes from the same pointer.
2866 if (TLI.isBigEndian()) {
2867 unsigned LVTStoreBytes = LoadedVT.getStoreSize();
2868 unsigned EVTStoreBytes = ExtVT.getStoreSize();
2869 unsigned PtrOff = LVTStoreBytes - EVTStoreBytes;
2870 NewPtr = DAG.getNode(ISD::ADD, SDLoc(LN0), PtrType,
2871 NewPtr, DAG.getConstant(PtrOff, PtrType));
2872 Alignment = MinAlign(Alignment, PtrOff);
2875 AddToWorkList(NewPtr.getNode());
2877 EVT LoadResultTy = HasAnyExt ? LN0->getValueType(0) : VT;
2879 DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), LoadResultTy,
2880 LN0->getChain(), NewPtr,
2881 LN0->getPointerInfo(),
2882 ExtVT, LN0->isVolatile(), LN0->isNonTemporal(),
2883 Alignment, LN0->getTBAAInfo());
2885 CombineTo(LN0, Load, Load.getValue(1));
2886 return SDValue(N, 0); // Return N so it doesn't get rechecked!
2892 if (N0.getOpcode() == ISD::ADD && N1.getOpcode() == ISD::SRL &&
2893 VT.getSizeInBits() <= 64) {
2894 if (ConstantSDNode *ADDI = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
2895 APInt ADDC = ADDI->getAPIntValue();
2896 if (!TLI.isLegalAddImmediate(ADDC.getSExtValue())) {
2897 // Look for (and (add x, c1), (lshr y, c2)). If C1 wasn't a legal
2898 // immediate for an add, but it is legal if its top c2 bits are set,
2899 // transform the ADD so the immediate doesn't need to be materialized
2901 if (ConstantSDNode *SRLI = dyn_cast<ConstantSDNode>(N1.getOperand(1))) {
2902 APInt Mask = APInt::getHighBitsSet(VT.getSizeInBits(),
2903 SRLI->getZExtValue());
2904 if (DAG.MaskedValueIsZero(N0.getOperand(1), Mask)) {
2906 if (TLI.isLegalAddImmediate(ADDC.getSExtValue())) {
2908 DAG.getNode(ISD::ADD, SDLoc(N0), VT,
2909 N0.getOperand(0), DAG.getConstant(ADDC, VT));
2910 CombineTo(N0.getNode(), NewAdd);
2911 return SDValue(N, 0); // Return N so it doesn't get rechecked!
2919 // fold (and (or (srl N, 8), (shl N, 8)), 0xffff) -> (srl (bswap N), const)
2920 if (N1C && N1C->getAPIntValue() == 0xffff && N0.getOpcode() == ISD::OR) {
2921 SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0),
2922 N0.getOperand(1), false);
2923 if (BSwap.getNode())
2930 /// MatchBSwapHWord - Match (a >> 8) | (a << 8) as (bswap a) >> 16
2932 SDValue DAGCombiner::MatchBSwapHWordLow(SDNode *N, SDValue N0, SDValue N1,
2933 bool DemandHighBits) {
2934 if (!LegalOperations)
2937 EVT VT = N->getValueType(0);
2938 if (VT != MVT::i64 && VT != MVT::i32 && VT != MVT::i16)
2940 if (!TLI.isOperationLegal(ISD::BSWAP, VT))
2943 // Recognize (and (shl a, 8), 0xff), (and (srl a, 8), 0xff00)
2944 bool LookPassAnd0 = false;
2945 bool LookPassAnd1 = false;
2946 if (N0.getOpcode() == ISD::AND && N0.getOperand(0).getOpcode() == ISD::SRL)
2948 if (N1.getOpcode() == ISD::AND && N1.getOperand(0).getOpcode() == ISD::SHL)
2950 if (N0.getOpcode() == ISD::AND) {
2951 if (!N0.getNode()->hasOneUse())
2953 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
2954 if (!N01C || N01C->getZExtValue() != 0xFF00)
2956 N0 = N0.getOperand(0);
2957 LookPassAnd0 = true;
2960 if (N1.getOpcode() == ISD::AND) {
2961 if (!N1.getNode()->hasOneUse())
2963 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
2964 if (!N11C || N11C->getZExtValue() != 0xFF)
2966 N1 = N1.getOperand(0);
2967 LookPassAnd1 = true;
2970 if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
2972 if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
2974 if (!N0.getNode()->hasOneUse() ||
2975 !N1.getNode()->hasOneUse())
2978 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
2979 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
2982 if (N01C->getZExtValue() != 8 || N11C->getZExtValue() != 8)
2985 // Look for (shl (and a, 0xff), 8), (srl (and a, 0xff00), 8)
2986 SDValue N00 = N0->getOperand(0);
2987 if (!LookPassAnd0 && N00.getOpcode() == ISD::AND) {
2988 if (!N00.getNode()->hasOneUse())
2990 ConstantSDNode *N001C = dyn_cast<ConstantSDNode>(N00.getOperand(1));
2991 if (!N001C || N001C->getZExtValue() != 0xFF)
2993 N00 = N00.getOperand(0);
2994 LookPassAnd0 = true;
2997 SDValue N10 = N1->getOperand(0);
2998 if (!LookPassAnd1 && N10.getOpcode() == ISD::AND) {
2999 if (!N10.getNode()->hasOneUse())
3001 ConstantSDNode *N101C = dyn_cast<ConstantSDNode>(N10.getOperand(1));
3002 if (!N101C || N101C->getZExtValue() != 0xFF00)
3004 N10 = N10.getOperand(0);
3005 LookPassAnd1 = true;
3011 // Make sure everything beyond the low halfword gets set to zero since the SRL
3012 // 16 will clear the top bits.
3013 unsigned OpSizeInBits = VT.getSizeInBits();
3014 if (DemandHighBits && OpSizeInBits > 16) {
3015 // If the left-shift isn't masked out then the only way this is a bswap is
3016 // if all bits beyond the low 8 are 0. In that case the entire pattern
3017 // reduces to a left shift anyway: leave it for other parts of the combiner.
3021 // However, if the right shift isn't masked out then it might be because
3022 // it's not needed. See if we can spot that too.
3023 if (!LookPassAnd1 &&
3024 !DAG.MaskedValueIsZero(
3025 N10, APInt::getHighBitsSet(OpSizeInBits, OpSizeInBits - 16)))
3029 SDValue Res = DAG.getNode(ISD::BSWAP, SDLoc(N), VT, N00);
3030 if (OpSizeInBits > 16)
3031 Res = DAG.getNode(ISD::SRL, SDLoc(N), VT, Res,
3032 DAG.getConstant(OpSizeInBits-16, getShiftAmountTy(VT)));
3036 /// isBSwapHWordElement - Return true if the specified node is an element
3037 /// that makes up a 32-bit packed halfword byteswap. i.e.
3038 /// ((x&0xff)<<8)|((x&0xff00)>>8)|((x&0x00ff0000)<<8)|((x&0xff000000)>>8)
3039 static bool isBSwapHWordElement(SDValue N, SmallVectorImpl<SDNode *> &Parts) {
3040 if (!N.getNode()->hasOneUse())
3043 unsigned Opc = N.getOpcode();
3044 if (Opc != ISD::AND && Opc != ISD::SHL && Opc != ISD::SRL)
3047 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3052 switch (N1C->getZExtValue()) {
3055 case 0xFF: Num = 0; break;
3056 case 0xFF00: Num = 1; break;
3057 case 0xFF0000: Num = 2; break;
3058 case 0xFF000000: Num = 3; break;
3061 // Look for (x & 0xff) << 8 as well as ((x << 8) & 0xff00).
3062 SDValue N0 = N.getOperand(0);
3063 if (Opc == ISD::AND) {
3064 if (Num == 0 || Num == 2) {
3066 // (x >> 8) & 0xff0000
3067 if (N0.getOpcode() != ISD::SRL)
3069 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3070 if (!C || C->getZExtValue() != 8)
3073 // (x << 8) & 0xff00
3074 // (x << 8) & 0xff000000
3075 if (N0.getOpcode() != ISD::SHL)
3077 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3078 if (!C || C->getZExtValue() != 8)
3081 } else if (Opc == ISD::SHL) {
3083 // (x & 0xff0000) << 8
3084 if (Num != 0 && Num != 2)
3086 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3087 if (!C || C->getZExtValue() != 8)
3089 } else { // Opc == ISD::SRL
3090 // (x & 0xff00) >> 8
3091 // (x & 0xff000000) >> 8
3092 if (Num != 1 && Num != 3)
3094 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3095 if (!C || C->getZExtValue() != 8)
3102 Parts[Num] = N0.getOperand(0).getNode();
3106 /// MatchBSwapHWord - Match a 32-bit packed halfword bswap. That is
3107 /// ((x&0xff)<<8)|((x&0xff00)>>8)|((x&0x00ff0000)<<8)|((x&0xff000000)>>8)
3108 /// => (rotl (bswap x), 16)
3109 SDValue DAGCombiner::MatchBSwapHWord(SDNode *N, SDValue N0, SDValue N1) {
3110 if (!LegalOperations)
3113 EVT VT = N->getValueType(0);
3116 if (!TLI.isOperationLegal(ISD::BSWAP, VT))
3119 SmallVector<SDNode*,4> Parts(4, (SDNode*)0);
3121 // (or (or (and), (and)), (or (and), (and)))
3122 // (or (or (or (and), (and)), (and)), (and))
3123 if (N0.getOpcode() != ISD::OR)
3125 SDValue N00 = N0.getOperand(0);
3126 SDValue N01 = N0.getOperand(1);
3128 if (N1.getOpcode() == ISD::OR &&
3129 N00.getNumOperands() == 2 && N01.getNumOperands() == 2) {
3130 // (or (or (and), (and)), (or (and), (and)))
3131 SDValue N000 = N00.getOperand(0);
3132 if (!isBSwapHWordElement(N000, Parts))
3135 SDValue N001 = N00.getOperand(1);
3136 if (!isBSwapHWordElement(N001, Parts))
3138 SDValue N010 = N01.getOperand(0);
3139 if (!isBSwapHWordElement(N010, Parts))
3141 SDValue N011 = N01.getOperand(1);
3142 if (!isBSwapHWordElement(N011, Parts))
3145 // (or (or (or (and), (and)), (and)), (and))
3146 if (!isBSwapHWordElement(N1, Parts))
3148 if (!isBSwapHWordElement(N01, Parts))
3150 if (N00.getOpcode() != ISD::OR)
3152 SDValue N000 = N00.getOperand(0);
3153 if (!isBSwapHWordElement(N000, Parts))
3155 SDValue N001 = N00.getOperand(1);
3156 if (!isBSwapHWordElement(N001, Parts))
3160 // Make sure the parts are all coming from the same node.
3161 if (Parts[0] != Parts[1] || Parts[0] != Parts[2] || Parts[0] != Parts[3])
3164 SDValue BSwap = DAG.getNode(ISD::BSWAP, SDLoc(N), VT,
3165 SDValue(Parts[0],0));
3167 // Result of the bswap should be rotated by 16. If it's not legal, then
3168 // do (x << 16) | (x >> 16).
3169 SDValue ShAmt = DAG.getConstant(16, getShiftAmountTy(VT));
3170 if (TLI.isOperationLegalOrCustom(ISD::ROTL, VT))
3171 return DAG.getNode(ISD::ROTL, SDLoc(N), VT, BSwap, ShAmt);
3172 if (TLI.isOperationLegalOrCustom(ISD::ROTR, VT))
3173 return DAG.getNode(ISD::ROTR, SDLoc(N), VT, BSwap, ShAmt);
3174 return DAG.getNode(ISD::OR, SDLoc(N), VT,
3175 DAG.getNode(ISD::SHL, SDLoc(N), VT, BSwap, ShAmt),
3176 DAG.getNode(ISD::SRL, SDLoc(N), VT, BSwap, ShAmt));
3179 SDValue DAGCombiner::visitOR(SDNode *N) {
3180 SDValue N0 = N->getOperand(0);
3181 SDValue N1 = N->getOperand(1);
3182 SDValue LL, LR, RL, RR, CC0, CC1;
3183 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
3184 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
3185 EVT VT = N1.getValueType();
3188 if (VT.isVector()) {
3189 SDValue FoldedVOp = SimplifyVBinOp(N);
3190 if (FoldedVOp.getNode()) return FoldedVOp;
3192 // fold (or x, 0) -> x, vector edition
3193 if (ISD::isBuildVectorAllZeros(N0.getNode()))
3195 if (ISD::isBuildVectorAllZeros(N1.getNode()))
3198 // fold (or x, -1) -> -1, vector edition
3199 if (ISD::isBuildVectorAllOnes(N0.getNode()))
3201 if (ISD::isBuildVectorAllOnes(N1.getNode()))
3204 // fold (or (shuf A, V_0, MA), (shuf B, V_0, MB)) -> (shuf A, B, Mask1)
3205 // fold (or (shuf A, V_0, MA), (shuf B, V_0, MB)) -> (shuf B, A, Mask2)
3206 // Do this only if the resulting shuffle is legal.
3207 if (isa<ShuffleVectorSDNode>(N0) &&
3208 isa<ShuffleVectorSDNode>(N1) &&
3209 N0->getOperand(1) == N1->getOperand(1) &&
3210 ISD::isBuildVectorAllZeros(N0.getOperand(1).getNode())) {
3211 bool CanFold = true;
3212 unsigned NumElts = VT.getVectorNumElements();
3213 const ShuffleVectorSDNode *SV0 = cast<ShuffleVectorSDNode>(N0);
3214 const ShuffleVectorSDNode *SV1 = cast<ShuffleVectorSDNode>(N1);
3215 // We construct two shuffle masks:
3216 // - Mask1 is a shuffle mask for a shuffle with N0 as the first operand
3217 // and N1 as the second operand.
3218 // - Mask2 is a shuffle mask for a shuffle with N1 as the first operand
3219 // and N0 as the second operand.
3220 // We do this because OR is commutable and therefore there might be
3221 // two ways to fold this node into a shuffle.
3222 SmallVector<int,4> Mask1;
3223 SmallVector<int,4> Mask2;
3225 for (unsigned i = 0; i != NumElts && CanFold; ++i) {
3226 int M0 = SV0->getMaskElt(i);
3227 int M1 = SV1->getMaskElt(i);
3229 // Both shuffle indexes are undef. Propagate Undef.
3230 if (M0 < 0 && M1 < 0) {
3231 Mask1.push_back(M0);
3232 Mask2.push_back(M0);
3236 if (M0 < 0 || M1 < 0 ||
3237 (M0 < (int)NumElts && M1 < (int)NumElts) ||
3238 (M0 >= (int)NumElts && M1 >= (int)NumElts)) {
3243 Mask1.push_back(M0 < (int)NumElts ? M0 : M1 + NumElts);
3244 Mask2.push_back(M1 < (int)NumElts ? M1 : M0 + NumElts);
3248 // Fold this sequence only if the resulting shuffle is 'legal'.
3249 if (TLI.isShuffleMaskLegal(Mask1, VT))
3250 return DAG.getVectorShuffle(VT, SDLoc(N), N0->getOperand(0),
3251 N1->getOperand(0), &Mask1[0]);
3252 if (TLI.isShuffleMaskLegal(Mask2, VT))
3253 return DAG.getVectorShuffle(VT, SDLoc(N), N1->getOperand(0),
3254 N0->getOperand(0), &Mask2[0]);
3259 // fold (or x, undef) -> -1
3260 if (!LegalOperations &&
3261 (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)) {
3262 EVT EltVT = VT.isVector() ? VT.getVectorElementType() : VT;
3263 return DAG.getConstant(APInt::getAllOnesValue(EltVT.getSizeInBits()), VT);
3265 // fold (or c1, c2) -> c1|c2
3267 return DAG.FoldConstantArithmetic(ISD::OR, VT, N0C, N1C);
3268 // canonicalize constant to RHS
3270 return DAG.getNode(ISD::OR, SDLoc(N), VT, N1, N0);
3271 // fold (or x, 0) -> x
3272 if (N1C && N1C->isNullValue())
3274 // fold (or x, -1) -> -1
3275 if (N1C && N1C->isAllOnesValue())
3277 // fold (or x, c) -> c iff (x & ~c) == 0
3278 if (N1C && DAG.MaskedValueIsZero(N0, ~N1C->getAPIntValue()))
3281 // Recognize halfword bswaps as (bswap + rotl 16) or (bswap + shl 16)
3282 SDValue BSwap = MatchBSwapHWord(N, N0, N1);
3283 if (BSwap.getNode() != 0)
3285 BSwap = MatchBSwapHWordLow(N, N0, N1);
3286 if (BSwap.getNode() != 0)
3290 SDValue ROR = ReassociateOps(ISD::OR, SDLoc(N), N0, N1);
3291 if (ROR.getNode() != 0)
3293 // Canonicalize (or (and X, c1), c2) -> (and (or X, c2), c1|c2)
3294 // iff (c1 & c2) == 0.
3295 if (N1C && N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() &&
3296 isa<ConstantSDNode>(N0.getOperand(1))) {
3297 ConstantSDNode *C1 = cast<ConstantSDNode>(N0.getOperand(1));
3298 if ((C1->getAPIntValue() & N1C->getAPIntValue()) != 0) {
3299 SDValue COR = DAG.FoldConstantArithmetic(ISD::OR, VT, N1C, C1);
3302 return DAG.getNode(ISD::AND, SDLoc(N), VT,
3303 DAG.getNode(ISD::OR, SDLoc(N0), VT,
3304 N0.getOperand(0), N1), COR);
3307 // fold (or (setcc x), (setcc y)) -> (setcc (or x, y))
3308 if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){
3309 ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get();
3310 ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get();
3312 if (LR == RR && isa<ConstantSDNode>(LR) && Op0 == Op1 &&
3313 LL.getValueType().isInteger()) {
3314 // fold (or (setne X, 0), (setne Y, 0)) -> (setne (or X, Y), 0)
3315 // fold (or (setlt X, 0), (setlt Y, 0)) -> (setne (or X, Y), 0)
3316 if (cast<ConstantSDNode>(LR)->isNullValue() &&
3317 (Op1 == ISD::SETNE || Op1 == ISD::SETLT)) {
3318 SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(LR),
3319 LR.getValueType(), LL, RL);
3320 AddToWorkList(ORNode.getNode());
3321 return DAG.getSetCC(SDLoc(N), VT, ORNode, LR, Op1);
3323 // fold (or (setne X, -1), (setne Y, -1)) -> (setne (and X, Y), -1)
3324 // fold (or (setgt X, -1), (setgt Y -1)) -> (setgt (and X, Y), -1)
3325 if (cast<ConstantSDNode>(LR)->isAllOnesValue() &&
3326 (Op1 == ISD::SETNE || Op1 == ISD::SETGT)) {
3327 SDValue ANDNode = DAG.getNode(ISD::AND, SDLoc(LR),
3328 LR.getValueType(), LL, RL);
3329 AddToWorkList(ANDNode.getNode());
3330 return DAG.getSetCC(SDLoc(N), VT, ANDNode, LR, Op1);
3333 // canonicalize equivalent to ll == rl
3334 if (LL == RR && LR == RL) {
3335 Op1 = ISD::getSetCCSwappedOperands(Op1);
3338 if (LL == RL && LR == RR) {
3339 bool isInteger = LL.getValueType().isInteger();
3340 ISD::CondCode Result = ISD::getSetCCOrOperation(Op0, Op1, isInteger);
3341 if (Result != ISD::SETCC_INVALID &&
3342 (!LegalOperations ||
3343 (TLI.isCondCodeLegal(Result, LL.getSimpleValueType()) &&
3344 TLI.isOperationLegal(ISD::SETCC,
3345 getSetCCResultType(N0.getValueType())))))
3346 return DAG.getSetCC(SDLoc(N), N0.getValueType(),
3351 // Simplify: (or (op x...), (op y...)) -> (op (or x, y))
3352 if (N0.getOpcode() == N1.getOpcode()) {
3353 SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
3354 if (Tmp.getNode()) return Tmp;
3357 // (or (and X, C1), (and Y, C2)) -> (and (or X, Y), C3) if possible.
3358 if (N0.getOpcode() == ISD::AND &&
3359 N1.getOpcode() == ISD::AND &&
3360 N0.getOperand(1).getOpcode() == ISD::Constant &&
3361 N1.getOperand(1).getOpcode() == ISD::Constant &&
3362 // Don't increase # computations.
3363 (N0.getNode()->hasOneUse() || N1.getNode()->hasOneUse())) {
3364 // We can only do this xform if we know that bits from X that are set in C2
3365 // but not in C1 are already zero. Likewise for Y.
3366 const APInt &LHSMask =
3367 cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
3368 const APInt &RHSMask =
3369 cast<ConstantSDNode>(N1.getOperand(1))->getAPIntValue();
3371 if (DAG.MaskedValueIsZero(N0.getOperand(0), RHSMask&~LHSMask) &&
3372 DAG.MaskedValueIsZero(N1.getOperand(0), LHSMask&~RHSMask)) {
3373 SDValue X = DAG.getNode(ISD::OR, SDLoc(N0), VT,
3374 N0.getOperand(0), N1.getOperand(0));
3375 return DAG.getNode(ISD::AND, SDLoc(N), VT, X,
3376 DAG.getConstant(LHSMask | RHSMask, VT));
3380 // See if this is some rotate idiom.
3381 if (SDNode *Rot = MatchRotate(N0, N1, SDLoc(N)))
3382 return SDValue(Rot, 0);
3384 // Simplify the operands using demanded-bits information.
3385 if (!VT.isVector() &&
3386 SimplifyDemandedBits(SDValue(N, 0)))
3387 return SDValue(N, 0);
3392 /// MatchRotateHalf - Match "(X shl/srl V1) & V2" where V2 may not be present.
3393 static bool MatchRotateHalf(SDValue Op, SDValue &Shift, SDValue &Mask) {
3394 if (Op.getOpcode() == ISD::AND) {
3395 if (isa<ConstantSDNode>(Op.getOperand(1))) {
3396 Mask = Op.getOperand(1);
3397 Op = Op.getOperand(0);
3403 if (Op.getOpcode() == ISD::SRL || Op.getOpcode() == ISD::SHL) {
3411 // Return true if we can prove that, whenever Neg and Pos are both in the
3412 // range [0, OpSize), Neg == (Pos == 0 ? 0 : OpSize - Pos). This means that
3413 // for two opposing shifts shift1 and shift2 and a value X with OpBits bits:
3415 // (or (shift1 X, Neg), (shift2 X, Pos))
3417 // reduces to a rotate in direction shift2 by Pos and a rotate in direction
3418 // shift1 by Neg. The range [0, OpSize) means that we only need to consider
3419 // shift amounts with defined behavior.
3420 static bool matchRotateSub(SDValue Pos, SDValue Neg, unsigned OpSize) {
3421 // If OpSize is a power of 2 then:
3423 // (a) (Pos == 0 ? 0 : OpSize - Pos) == (OpSize - Pos) & (OpSize - 1)
3424 // (b) Neg == Neg & (OpSize - 1) whenever Neg is in [0, OpSize).
3426 // So if OpSize is a power of 2 and Neg is (and Neg', OpSize-1), we check
3427 // for the stronger condition:
3429 // Neg & (OpSize - 1) == (OpSize - Pos) & (OpSize - 1) [A]
3431 // for all Neg and Pos. Since Neg & (OpSize - 1) == Neg' & (OpSize - 1)
3432 // we can just replace Neg with Neg' for the rest of the function.
3434 // In other cases we check for the even stronger condition:
3436 // Neg == OpSize - Pos [B]
3438 // for all Neg and Pos. Note that the (or ...) then invokes undefined
3439 // behavior if Pos == 0 (and consequently Neg == OpSize).
3441 // We could actually use [A] whenever OpSize is a power of 2, but the
3442 // only extra cases that it would match are those uninteresting ones
3443 // where Neg and Pos are never in range at the same time. E.g. for
3444 // OpSize == 32, using [A] would allow a Neg of the form (sub 64, Pos)
3445 // as well as (sub 32, Pos), but:
3447 // (or (shift1 X, (sub 64, Pos)), (shift2 X, Pos))
3449 // always invokes undefined behavior for 32-bit X.
3451 // Below, Mask == OpSize - 1 when using [A] and is all-ones otherwise.
3452 unsigned LoBits = 0;
3453 if (Neg.getOpcode() == ISD::AND &&
3454 isPowerOf2_64(OpSize) &&
3455 Neg.getOperand(1).getOpcode() == ISD::Constant &&
3456 cast<ConstantSDNode>(Neg.getOperand(1))->getAPIntValue() == OpSize - 1) {
3457 Neg = Neg.getOperand(0);
3458 LoBits = Log2_64(OpSize);
3461 // Check whether Neg has the form (sub NegC, NegOp1) for some NegC and NegOp1.
3462 if (Neg.getOpcode() != ISD::SUB)
3464 ConstantSDNode *NegC = dyn_cast<ConstantSDNode>(Neg.getOperand(0));
3467 SDValue NegOp1 = Neg.getOperand(1);
3469 // The condition we need is now:
3471 // (NegC - NegOp1) & Mask == (OpSize - Pos) & Mask
3473 // If NegOp1 == Pos then we need:
3475 // OpSize & Mask == NegC & Mask
3477 // (because "x & Mask" is a truncation and distributes through subtraction).
3480 Width = NegC->getAPIntValue();
3481 // Check for cases where Pos has the form (add NegOp1, PosC) for some PosC.
3482 // Then the condition we want to prove becomes:
3484 // (NegC - NegOp1) & Mask == (OpSize - (NegOp1 + PosC)) & Mask
3486 // which, again because "x & Mask" is a truncation, becomes:
3488 // NegC & Mask == (OpSize - PosC) & Mask
3489 // OpSize & Mask == (NegC + PosC) & Mask
3490 else if (Pos.getOpcode() == ISD::ADD &&
3491 Pos.getOperand(0) == NegOp1 &&
3492 Pos.getOperand(1).getOpcode() == ISD::Constant)
3493 Width = (cast<ConstantSDNode>(Pos.getOperand(1))->getAPIntValue() +
3494 NegC->getAPIntValue());
3498 // Now we just need to check that OpSize & Mask == Width & Mask.
3500 return Width.getLoBits(LoBits) == 0;
3501 return Width == OpSize;
3504 // A subroutine of MatchRotate used once we have found an OR of two opposite
3505 // shifts of Shifted. If Neg == <operand size> - Pos then the OR reduces
3506 // to both (PosOpcode Shifted, Pos) and (NegOpcode Shifted, Neg), with the
3507 // former being preferred if supported. InnerPos and InnerNeg are Pos and
3508 // Neg with outer conversions stripped away.
3509 SDNode *DAGCombiner::MatchRotatePosNeg(SDValue Shifted, SDValue Pos,
3510 SDValue Neg, SDValue InnerPos,
3511 SDValue InnerNeg, unsigned PosOpcode,
3512 unsigned NegOpcode, SDLoc DL) {
3513 // fold (or (shl x, (*ext y)),
3514 // (srl x, (*ext (sub 32, y)))) ->
3515 // (rotl x, y) or (rotr x, (sub 32, y))
3517 // fold (or (shl x, (*ext (sub 32, y))),
3518 // (srl x, (*ext y))) ->
3519 // (rotr x, y) or (rotl x, (sub 32, y))
3520 EVT VT = Shifted.getValueType();
3521 if (matchRotateSub(InnerPos, InnerNeg, VT.getSizeInBits())) {
3522 bool HasPos = TLI.isOperationLegalOrCustom(PosOpcode, VT);
3523 return DAG.getNode(HasPos ? PosOpcode : NegOpcode, DL, VT, Shifted,
3524 HasPos ? Pos : Neg).getNode();
3527 // fold (or (shl (*ext x), (*ext y)),
3528 // (srl (*ext x), (*ext (sub 32, y)))) ->
3529 // (*ext (rotl x, y)) or (*ext (rotr x, (sub 32, y)))
3531 // fold (or (shl (*ext x), (*ext (sub 32, y))),
3532 // (srl (*ext x), (*ext y))) ->
3533 // (*ext (rotr x, y)) or (*ext (rotl x, (sub 32, y)))
3534 if (Shifted.getOpcode() == ISD::ZERO_EXTEND ||
3535 Shifted.getOpcode() == ISD::ANY_EXTEND) {
3536 SDValue InnerShifted = Shifted.getOperand(0);
3537 EVT InnerVT = InnerShifted.getValueType();
3538 bool HasPosInner = TLI.isOperationLegalOrCustom(PosOpcode, InnerVT);
3539 if (HasPosInner || TLI.isOperationLegalOrCustom(NegOpcode, InnerVT)) {
3540 if (matchRotateSub(InnerPos, InnerNeg, InnerVT.getSizeInBits())) {
3541 SDValue V = DAG.getNode(HasPosInner ? PosOpcode : NegOpcode, DL,
3542 InnerVT, InnerShifted, HasPosInner ? Pos : Neg);
3543 return DAG.getNode(Shifted.getOpcode(), DL, VT, V).getNode();
3551 // MatchRotate - Handle an 'or' of two operands. If this is one of the many
3552 // idioms for rotate, and if the target supports rotation instructions, generate
3554 SDNode *DAGCombiner::MatchRotate(SDValue LHS, SDValue RHS, SDLoc DL) {
3555 // Must be a legal type. Expanded 'n promoted things won't work with rotates.
3556 EVT VT = LHS.getValueType();
3557 if (!TLI.isTypeLegal(VT)) return 0;
3559 // The target must have at least one rotate flavor.
3560 bool HasROTL = TLI.isOperationLegalOrCustom(ISD::ROTL, VT);
3561 bool HasROTR = TLI.isOperationLegalOrCustom(ISD::ROTR, VT);
3562 if (!HasROTL && !HasROTR) return 0;
3564 // Match "(X shl/srl V1) & V2" where V2 may not be present.
3565 SDValue LHSShift; // The shift.
3566 SDValue LHSMask; // AND value if any.
3567 if (!MatchRotateHalf(LHS, LHSShift, LHSMask))
3568 return 0; // Not part of a rotate.
3570 SDValue RHSShift; // The shift.
3571 SDValue RHSMask; // AND value if any.
3572 if (!MatchRotateHalf(RHS, RHSShift, RHSMask))
3573 return 0; // Not part of a rotate.
3575 if (LHSShift.getOperand(0) != RHSShift.getOperand(0))
3576 return 0; // Not shifting the same value.
3578 if (LHSShift.getOpcode() == RHSShift.getOpcode())
3579 return 0; // Shifts must disagree.
3581 // Canonicalize shl to left side in a shl/srl pair.
3582 if (RHSShift.getOpcode() == ISD::SHL) {
3583 std::swap(LHS, RHS);
3584 std::swap(LHSShift, RHSShift);
3585 std::swap(LHSMask , RHSMask );
3588 unsigned OpSizeInBits = VT.getSizeInBits();
3589 SDValue LHSShiftArg = LHSShift.getOperand(0);
3590 SDValue LHSShiftAmt = LHSShift.getOperand(1);
3591 SDValue RHSShiftArg = RHSShift.getOperand(0);
3592 SDValue RHSShiftAmt = RHSShift.getOperand(1);
3594 // fold (or (shl x, C1), (srl x, C2)) -> (rotl x, C1)
3595 // fold (or (shl x, C1), (srl x, C2)) -> (rotr x, C2)
3596 if (LHSShiftAmt.getOpcode() == ISD::Constant &&
3597 RHSShiftAmt.getOpcode() == ISD::Constant) {
3598 uint64_t LShVal = cast<ConstantSDNode>(LHSShiftAmt)->getZExtValue();
3599 uint64_t RShVal = cast<ConstantSDNode>(RHSShiftAmt)->getZExtValue();
3600 if ((LShVal + RShVal) != OpSizeInBits)
3603 SDValue Rot = DAG.getNode(HasROTL ? ISD::ROTL : ISD::ROTR, DL, VT,
3604 LHSShiftArg, HasROTL ? LHSShiftAmt : RHSShiftAmt);
3606 // If there is an AND of either shifted operand, apply it to the result.
3607 if (LHSMask.getNode() || RHSMask.getNode()) {
3608 APInt Mask = APInt::getAllOnesValue(OpSizeInBits);
3610 if (LHSMask.getNode()) {
3611 APInt RHSBits = APInt::getLowBitsSet(OpSizeInBits, LShVal);
3612 Mask &= cast<ConstantSDNode>(LHSMask)->getAPIntValue() | RHSBits;
3614 if (RHSMask.getNode()) {
3615 APInt LHSBits = APInt::getHighBitsSet(OpSizeInBits, RShVal);
3616 Mask &= cast<ConstantSDNode>(RHSMask)->getAPIntValue() | LHSBits;
3619 Rot = DAG.getNode(ISD::AND, DL, VT, Rot, DAG.getConstant(Mask, VT));
3622 return Rot.getNode();
3625 // If there is a mask here, and we have a variable shift, we can't be sure
3626 // that we're masking out the right stuff.
3627 if (LHSMask.getNode() || RHSMask.getNode())
3630 // If the shift amount is sign/zext/any-extended just peel it off.
3631 SDValue LExtOp0 = LHSShiftAmt;
3632 SDValue RExtOp0 = RHSShiftAmt;
3633 if ((LHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND ||
3634 LHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND ||
3635 LHSShiftAmt.getOpcode() == ISD::ANY_EXTEND ||
3636 LHSShiftAmt.getOpcode() == ISD::TRUNCATE) &&
3637 (RHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND ||
3638 RHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND ||
3639 RHSShiftAmt.getOpcode() == ISD::ANY_EXTEND ||
3640 RHSShiftAmt.getOpcode() == ISD::TRUNCATE)) {
3641 LExtOp0 = LHSShiftAmt.getOperand(0);
3642 RExtOp0 = RHSShiftAmt.getOperand(0);
3645 SDNode *TryL = MatchRotatePosNeg(LHSShiftArg, LHSShiftAmt, RHSShiftAmt,
3646 LExtOp0, RExtOp0, ISD::ROTL, ISD::ROTR, DL);
3650 SDNode *TryR = MatchRotatePosNeg(RHSShiftArg, RHSShiftAmt, LHSShiftAmt,
3651 RExtOp0, LExtOp0, ISD::ROTR, ISD::ROTL, DL);
3658 SDValue DAGCombiner::visitXOR(SDNode *N) {
3659 SDValue N0 = N->getOperand(0);
3660 SDValue N1 = N->getOperand(1);
3661 SDValue LHS, RHS, CC;
3662 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
3663 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
3664 EVT VT = N0.getValueType();
3667 if (VT.isVector()) {
3668 SDValue FoldedVOp = SimplifyVBinOp(N);
3669 if (FoldedVOp.getNode()) return FoldedVOp;
3671 // fold (xor x, 0) -> x, vector edition
3672 if (ISD::isBuildVectorAllZeros(N0.getNode()))
3674 if (ISD::isBuildVectorAllZeros(N1.getNode()))
3678 // fold (xor undef, undef) -> 0. This is a common idiom (misuse).
3679 if (N0.getOpcode() == ISD::UNDEF && N1.getOpcode() == ISD::UNDEF)
3680 return DAG.getConstant(0, VT);
3681 // fold (xor x, undef) -> undef
3682 if (N0.getOpcode() == ISD::UNDEF)
3684 if (N1.getOpcode() == ISD::UNDEF)
3686 // fold (xor c1, c2) -> c1^c2
3688 return DAG.FoldConstantArithmetic(ISD::XOR, VT, N0C, N1C);
3689 // canonicalize constant to RHS
3691 return DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0);
3692 // fold (xor x, 0) -> x
3693 if (N1C && N1C->isNullValue())
3696 SDValue RXOR = ReassociateOps(ISD::XOR, SDLoc(N), N0, N1);
3697 if (RXOR.getNode() != 0)
3700 // fold !(x cc y) -> (x !cc y)
3701 if (N1C && N1C->getAPIntValue() == 1 && isSetCCEquivalent(N0, LHS, RHS, CC)) {
3702 bool isInt = LHS.getValueType().isInteger();
3703 ISD::CondCode NotCC = ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(),
3706 if (!LegalOperations ||
3707 TLI.isCondCodeLegal(NotCC, LHS.getSimpleValueType())) {
3708 switch (N0.getOpcode()) {
3710 llvm_unreachable("Unhandled SetCC Equivalent!");
3712 return DAG.getSetCC(SDLoc(N), VT, LHS, RHS, NotCC);
3713 case ISD::SELECT_CC:
3714 return DAG.getSelectCC(SDLoc(N), LHS, RHS, N0.getOperand(2),
3715 N0.getOperand(3), NotCC);
3720 // fold (not (zext (setcc x, y))) -> (zext (not (setcc x, y)))
3721 if (N1C && N1C->getAPIntValue() == 1 && N0.getOpcode() == ISD::ZERO_EXTEND &&
3722 N0.getNode()->hasOneUse() &&
3723 isSetCCEquivalent(N0.getOperand(0), LHS, RHS, CC)){
3724 SDValue V = N0.getOperand(0);
3725 V = DAG.getNode(ISD::XOR, SDLoc(N0), V.getValueType(), V,
3726 DAG.getConstant(1, V.getValueType()));
3727 AddToWorkList(V.getNode());
3728 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, V);
3731 // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are setcc
3732 if (N1C && N1C->getAPIntValue() == 1 && VT == MVT::i1 &&
3733 (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
3734 SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
3735 if (isOneUseSetCC(RHS) || isOneUseSetCC(LHS)) {
3736 unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
3737 LHS = DAG.getNode(ISD::XOR, SDLoc(LHS), VT, LHS, N1); // LHS = ~LHS
3738 RHS = DAG.getNode(ISD::XOR, SDLoc(RHS), VT, RHS, N1); // RHS = ~RHS
3739 AddToWorkList(LHS.getNode()); AddToWorkList(RHS.getNode());
3740 return DAG.getNode(NewOpcode, SDLoc(N), VT, LHS, RHS);
3743 // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are constants
3744 if (N1C && N1C->isAllOnesValue() &&
3745 (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
3746 SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
3747 if (isa<ConstantSDNode>(RHS) || isa<ConstantSDNode>(LHS)) {
3748 unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
3749 LHS = DAG.getNode(ISD::XOR, SDLoc(LHS), VT, LHS, N1); // LHS = ~LHS
3750 RHS = DAG.getNode(ISD::XOR, SDLoc(RHS), VT, RHS, N1); // RHS = ~RHS
3751 AddToWorkList(LHS.getNode()); AddToWorkList(RHS.getNode());
3752 return DAG.getNode(NewOpcode, SDLoc(N), VT, LHS, RHS);
3755 // fold (xor (and x, y), y) -> (and (not x), y)
3756 if (N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() &&
3757 N0->getOperand(1) == N1) {
3758 SDValue X = N0->getOperand(0);
3759 SDValue NotX = DAG.getNOT(SDLoc(X), X, VT);
3760 AddToWorkList(NotX.getNode());
3761 return DAG.getNode(ISD::AND, SDLoc(N), VT, NotX, N1);
3763 // fold (xor (xor x, c1), c2) -> (xor x, (xor c1, c2))
3764 if (N1C && N0.getOpcode() == ISD::XOR) {
3765 ConstantSDNode *N00C = dyn_cast<ConstantSDNode>(N0.getOperand(0));
3766 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3768 return DAG.getNode(ISD::XOR, SDLoc(N), VT, N0.getOperand(1),
3769 DAG.getConstant(N1C->getAPIntValue() ^
3770 N00C->getAPIntValue(), VT));
3772 return DAG.getNode(ISD::XOR, SDLoc(N), VT, N0.getOperand(0),
3773 DAG.getConstant(N1C->getAPIntValue() ^
3774 N01C->getAPIntValue(), VT));
3776 // fold (xor x, x) -> 0
3778 return tryFoldToZero(SDLoc(N), TLI, VT, DAG, LegalOperations, LegalTypes);
3780 // Simplify: xor (op x...), (op y...) -> (op (xor x, y))
3781 if (N0.getOpcode() == N1.getOpcode()) {
3782 SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
3783 if (Tmp.getNode()) return Tmp;
3786 // Simplify the expression using non-local knowledge.
3787 if (!VT.isVector() &&
3788 SimplifyDemandedBits(SDValue(N, 0)))
3789 return SDValue(N, 0);
3794 /// visitShiftByConstant - Handle transforms common to the three shifts, when
3795 /// the shift amount is a constant.
3796 SDValue DAGCombiner::visitShiftByConstant(SDNode *N, unsigned Amt) {
3797 assert(isa<ConstantSDNode>(N->getOperand(1)) &&
3798 "Expected an ConstantSDNode operand.");
3799 // We can't and shouldn't fold opaque constants.
3800 if (cast<ConstantSDNode>(N->getOperand(1))->isOpaque())
3803 SDNode *LHS = N->getOperand(0).getNode();
3804 if (!LHS->hasOneUse()) return SDValue();
3806 // We want to pull some binops through shifts, so that we have (and (shift))
3807 // instead of (shift (and)), likewise for add, or, xor, etc. This sort of
3808 // thing happens with address calculations, so it's important to canonicalize
3810 bool HighBitSet = false; // Can we transform this if the high bit is set?
3812 switch (LHS->getOpcode()) {
3813 default: return SDValue();
3816 HighBitSet = false; // We can only transform sra if the high bit is clear.
3819 HighBitSet = true; // We can only transform sra if the high bit is set.
3822 if (N->getOpcode() != ISD::SHL)
3823 return SDValue(); // only shl(add) not sr[al](add).
3824 HighBitSet = false; // We can only transform sra if the high bit is clear.
3828 // We require the RHS of the binop to be a constant and not opaque as well.
3829 ConstantSDNode *BinOpCst = dyn_cast<ConstantSDNode>(LHS->getOperand(1));
3830 if (!BinOpCst || BinOpCst->isOpaque()) return SDValue();
3832 // FIXME: disable this unless the input to the binop is a shift by a constant.
3833 // If it is not a shift, it pessimizes some common cases like:
3835 // void foo(int *X, int i) { X[i & 1235] = 1; }
3836 // int bar(int *X, int i) { return X[i & 255]; }
3837 SDNode *BinOpLHSVal = LHS->getOperand(0).getNode();
3838 if ((BinOpLHSVal->getOpcode() != ISD::SHL &&
3839 BinOpLHSVal->getOpcode() != ISD::SRA &&
3840 BinOpLHSVal->getOpcode() != ISD::SRL) ||
3841 !isa<ConstantSDNode>(BinOpLHSVal->getOperand(1)))
3844 EVT VT = N->getValueType(0);
3846 // If this is a signed shift right, and the high bit is modified by the
3847 // logical operation, do not perform the transformation. The highBitSet
3848 // boolean indicates the value of the high bit of the constant which would
3849 // cause it to be modified for this operation.
3850 if (N->getOpcode() == ISD::SRA) {
3851 bool BinOpRHSSignSet = BinOpCst->getAPIntValue().isNegative();
3852 if (BinOpRHSSignSet != HighBitSet)
3856 // Fold the constants, shifting the binop RHS by the shift amount.
3857 SDValue NewRHS = DAG.getNode(N->getOpcode(), SDLoc(LHS->getOperand(1)),
3859 LHS->getOperand(1), N->getOperand(1));
3860 assert(isa<ConstantSDNode>(NewRHS) && "Folding was not successful!");
3862 // Create the new shift.
3863 SDValue NewShift = DAG.getNode(N->getOpcode(),
3864 SDLoc(LHS->getOperand(0)),
3865 VT, LHS->getOperand(0), N->getOperand(1));
3867 // Create the new binop.
3868 return DAG.getNode(LHS->getOpcode(), SDLoc(N), VT, NewShift, NewRHS);
3871 SDValue DAGCombiner::distributeTruncateThroughAnd(SDNode *N) {
3872 assert(N->getOpcode() == ISD::TRUNCATE);
3873 assert(N->getOperand(0).getOpcode() == ISD::AND);
3875 // (truncate:TruncVT (and N00, N01C)) -> (and (truncate:TruncVT N00), TruncC)
3876 if (N->hasOneUse() && N->getOperand(0).hasOneUse()) {
3877 SDValue N01 = N->getOperand(0).getOperand(1);
3879 if (ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N01)) {
3880 EVT TruncVT = N->getValueType(0);
3881 SDValue N00 = N->getOperand(0).getOperand(0);
3882 APInt TruncC = N01C->getAPIntValue();
3883 TruncC = TruncC.trunc(TruncVT.getScalarType().getSizeInBits());
3885 return DAG.getNode(ISD::AND, SDLoc(N), TruncVT,
3886 DAG.getNode(ISD::TRUNCATE, SDLoc(N), TruncVT, N00),
3887 DAG.getConstant(TruncC, TruncVT));
3893 SDValue DAGCombiner::visitSHL(SDNode *N) {
3894 SDValue N0 = N->getOperand(0);
3895 SDValue N1 = N->getOperand(1);
3896 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
3897 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
3898 EVT VT = N0.getValueType();
3899 unsigned OpSizeInBits = VT.getScalarType().getSizeInBits();
3902 if (VT.isVector()) {
3903 SDValue FoldedVOp = SimplifyVBinOp(N);
3904 if (FoldedVOp.getNode()) return FoldedVOp;
3906 BuildVectorSDNode *N1CV = dyn_cast<BuildVectorSDNode>(N1);
3907 // If setcc produces all-one true value then:
3908 // (shl (and (setcc) N01CV) N1CV) -> (and (setcc) N01CV<<N1CV)
3909 if (N1CV && N1CV->isConstant() &&
3910 TLI.getBooleanContents(true) ==
3911 TargetLowering::ZeroOrNegativeOneBooleanContent &&
3912 N0.getOpcode() == ISD::AND) {
3913 SDValue N00 = N0->getOperand(0);
3914 SDValue N01 = N0->getOperand(1);
3915 BuildVectorSDNode *N01CV = dyn_cast<BuildVectorSDNode>(N01);
3917 if (N01CV && N01CV->isConstant() && N00.getOpcode() == ISD::SETCC) {
3918 SDValue C = DAG.FoldConstantArithmetic(ISD::SHL, VT, N01CV, N1CV);
3920 return DAG.getNode(ISD::AND, SDLoc(N), VT, N00, C);
3925 // fold (shl c1, c2) -> c1<<c2
3927 return DAG.FoldConstantArithmetic(ISD::SHL, VT, N0C, N1C);
3928 // fold (shl 0, x) -> 0
3929 if (N0C && N0C->isNullValue())
3931 // fold (shl x, c >= size(x)) -> undef
3932 if (N1C && N1C->getZExtValue() >= OpSizeInBits)
3933 return DAG.getUNDEF(VT);
3934 // fold (shl x, 0) -> x
3935 if (N1C && N1C->isNullValue())
3937 // fold (shl undef, x) -> 0
3938 if (N0.getOpcode() == ISD::UNDEF)
3939 return DAG.getConstant(0, VT);
3940 // if (shl x, c) is known to be zero, return 0
3941 if (DAG.MaskedValueIsZero(SDValue(N, 0),
3942 APInt::getAllOnesValue(OpSizeInBits)))
3943 return DAG.getConstant(0, VT);
3944 // fold (shl x, (trunc (and y, c))) -> (shl x, (and (trunc y), (trunc c))).
3945 if (N1.getOpcode() == ISD::TRUNCATE &&
3946 N1.getOperand(0).getOpcode() == ISD::AND) {
3947 SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode());
3948 if (NewOp1.getNode())
3949 return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0, NewOp1);
3952 if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
3953 return SDValue(N, 0);
3955 // fold (shl (shl x, c1), c2) -> 0 or (shl x, (add c1, c2))
3956 if (N1C && N0.getOpcode() == ISD::SHL &&
3957 N0.getOperand(1).getOpcode() == ISD::Constant) {
3958 uint64_t c1 = cast<ConstantSDNode>(N0.getOperand(1))->getZExtValue();
3959 uint64_t c2 = N1C->getZExtValue();
3960 if (c1 + c2 >= OpSizeInBits)
3961 return DAG.getConstant(0, VT);
3962 return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0.getOperand(0),
3963 DAG.getConstant(c1 + c2, N1.getValueType()));
3966 // fold (shl (ext (shl x, c1)), c2) -> (ext (shl x, (add c1, c2)))
3967 // For this to be valid, the second form must not preserve any of the bits
3968 // that are shifted out by the inner shift in the first form. This means
3969 // the outer shift size must be >= the number of bits added by the ext.
3970 // As a corollary, we don't care what kind of ext it is.
3971 if (N1C && (N0.getOpcode() == ISD::ZERO_EXTEND ||
3972 N0.getOpcode() == ISD::ANY_EXTEND ||
3973 N0.getOpcode() == ISD::SIGN_EXTEND) &&
3974 N0.getOperand(0).getOpcode() == ISD::SHL &&
3975 isa<ConstantSDNode>(N0.getOperand(0)->getOperand(1))) {
3977 cast<ConstantSDNode>(N0.getOperand(0)->getOperand(1))->getZExtValue();
3978 uint64_t c2 = N1C->getZExtValue();
3979 EVT InnerShiftVT = N0.getOperand(0).getValueType();
3980 uint64_t InnerShiftSize = InnerShiftVT.getScalarType().getSizeInBits();
3981 if (c2 >= OpSizeInBits - InnerShiftSize) {
3982 if (c1 + c2 >= OpSizeInBits)
3983 return DAG.getConstant(0, VT);
3984 return DAG.getNode(ISD::SHL, SDLoc(N0), VT,
3985 DAG.getNode(N0.getOpcode(), SDLoc(N0), VT,
3986 N0.getOperand(0)->getOperand(0)),
3987 DAG.getConstant(c1 + c2, N1.getValueType()));
3991 // fold (shl (zext (srl x, C)), C) -> (zext (shl (srl x, C), C))
3992 // Only fold this if the inner zext has no other uses to avoid increasing
3993 // the total number of instructions.
3994 if (N1C && N0.getOpcode() == ISD::ZERO_EXTEND && N0.hasOneUse() &&
3995 N0.getOperand(0).getOpcode() == ISD::SRL &&
3996 isa<ConstantSDNode>(N0.getOperand(0)->getOperand(1))) {
3998 cast<ConstantSDNode>(N0.getOperand(0)->getOperand(1))->getZExtValue();
3999 if (c1 < VT.getSizeInBits()) {
4000 uint64_t c2 = N1C->getZExtValue();
4002 SDValue NewOp0 = N0.getOperand(0);
4003 EVT CountVT = NewOp0.getOperand(1).getValueType();
4004 SDValue NewSHL = DAG.getNode(ISD::SHL, SDLoc(N), NewOp0.getValueType(),
4005 NewOp0, DAG.getConstant(c2, CountVT));
4006 AddToWorkList(NewSHL.getNode());
4007 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N0), VT, NewSHL);
4012 // fold (shl (srl x, c1), c2) -> (and (shl x, (sub c2, c1), MASK) or
4013 // (and (srl x, (sub c1, c2), MASK)
4014 // Only fold this if the inner shift has no other uses -- if it does, folding
4015 // this will increase the total number of instructions.
4016 if (N1C && N0.getOpcode() == ISD::SRL && N0.hasOneUse() &&
4017 N0.getOperand(1).getOpcode() == ISD::Constant) {
4018 uint64_t c1 = cast<ConstantSDNode>(N0.getOperand(1))->getZExtValue();
4019 if (c1 < VT.getSizeInBits()) {
4020 uint64_t c2 = N1C->getZExtValue();
4021 APInt Mask = APInt::getHighBitsSet(VT.getSizeInBits(),
4022 VT.getSizeInBits() - c1);
4025 Mask = Mask.shl(c2-c1);
4026 Shift = DAG.getNode(ISD::SHL, SDLoc(N), VT, N0.getOperand(0),
4027 DAG.getConstant(c2-c1, N1.getValueType()));
4029 Mask = Mask.lshr(c1-c2);
4030 Shift = DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0),
4031 DAG.getConstant(c1-c2, N1.getValueType()));
4033 return DAG.getNode(ISD::AND, SDLoc(N0), VT, Shift,
4034 DAG.getConstant(Mask, VT));
4037 // fold (shl (sra x, c1), c1) -> (and x, (shl -1, c1))
4038 if (N1C && N0.getOpcode() == ISD::SRA && N1 == N0.getOperand(1)) {
4039 SDValue HiBitsMask =
4040 DAG.getConstant(APInt::getHighBitsSet(VT.getSizeInBits(),
4041 VT.getSizeInBits() -
4042 N1C->getZExtValue()),
4044 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0.getOperand(0),
4049 SDValue NewSHL = visitShiftByConstant(N, N1C->getZExtValue());
4050 if (NewSHL.getNode())
4057 SDValue DAGCombiner::visitSRA(SDNode *N) {
4058 SDValue N0 = N->getOperand(0);
4059 SDValue N1 = N->getOperand(1);
4060 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
4061 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4062 EVT VT = N0.getValueType();
4063 unsigned OpSizeInBits = VT.getScalarType().getSizeInBits();
4066 if (VT.isVector()) {
4067 SDValue FoldedVOp = SimplifyVBinOp(N);
4068 if (FoldedVOp.getNode()) return FoldedVOp;
4071 // fold (sra c1, c2) -> (sra c1, c2)
4073 return DAG.FoldConstantArithmetic(ISD::SRA, VT, N0C, N1C);
4074 // fold (sra 0, x) -> 0
4075 if (N0C && N0C->isNullValue())
4077 // fold (sra -1, x) -> -1
4078 if (N0C && N0C->isAllOnesValue())
4080 // fold (sra x, (setge c, size(x))) -> undef
4081 if (N1C && N1C->getZExtValue() >= OpSizeInBits)
4082 return DAG.getUNDEF(VT);
4083 // fold (sra x, 0) -> x
4084 if (N1C && N1C->isNullValue())
4086 // fold (sra (shl x, c1), c1) -> sext_inreg for some c1 and target supports
4088 if (N1C && N0.getOpcode() == ISD::SHL && N1 == N0.getOperand(1)) {
4089 unsigned LowBits = OpSizeInBits - (unsigned)N1C->getZExtValue();
4090 EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), LowBits);
4092 ExtVT = EVT::getVectorVT(*DAG.getContext(),
4093 ExtVT, VT.getVectorNumElements());
4094 if ((!LegalOperations ||
4095 TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, ExtVT)))
4096 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
4097 N0.getOperand(0), DAG.getValueType(ExtVT));
4100 // fold (sra (sra x, c1), c2) -> (sra x, (add c1, c2))
4101 if (N1C && N0.getOpcode() == ISD::SRA) {
4102 if (ConstantSDNode *C1 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
4103 unsigned Sum = N1C->getZExtValue() + C1->getZExtValue();
4104 if (Sum >= OpSizeInBits) Sum = OpSizeInBits-1;
4105 return DAG.getNode(ISD::SRA, SDLoc(N), VT, N0.getOperand(0),
4106 DAG.getConstant(Sum, N1C->getValueType(0)));
4110 // fold (sra (shl X, m), (sub result_size, n))
4111 // -> (sign_extend (trunc (shl X, (sub (sub result_size, n), m)))) for
4112 // result_size - n != m.
4113 // If truncate is free for the target sext(shl) is likely to result in better
4115 if (N0.getOpcode() == ISD::SHL) {
4116 // Get the two constanst of the shifts, CN0 = m, CN = n.
4117 const ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
4119 // Determine what the truncate's result bitsize and type would be.
4121 EVT::getIntegerVT(*DAG.getContext(),
4122 OpSizeInBits - N1C->getZExtValue());
4123 // Determine the residual right-shift amount.
4124 signed ShiftAmt = N1C->getZExtValue() - N01C->getZExtValue();
4126 // If the shift is not a no-op (in which case this should be just a sign
4127 // extend already), the truncated to type is legal, sign_extend is legal
4128 // on that type, and the truncate to that type is both legal and free,
4129 // perform the transform.
4130 if ((ShiftAmt > 0) &&
4131 TLI.isOperationLegalOrCustom(ISD::SIGN_EXTEND, TruncVT) &&
4132 TLI.isOperationLegalOrCustom(ISD::TRUNCATE, VT) &&
4133 TLI.isTruncateFree(VT, TruncVT)) {
4135 SDValue Amt = DAG.getConstant(ShiftAmt,
4136 getShiftAmountTy(N0.getOperand(0).getValueType()));
4137 SDValue Shift = DAG.getNode(ISD::SRL, SDLoc(N0), VT,
4138 N0.getOperand(0), Amt);
4139 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0), TruncVT,
4141 return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N),
4142 N->getValueType(0), Trunc);
4147 // fold (sra x, (trunc (and y, c))) -> (sra x, (and (trunc y), (trunc c))).
4148 if (N1.getOpcode() == ISD::TRUNCATE &&
4149 N1.getOperand(0).getOpcode() == ISD::AND) {
4150 SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode());
4151 if (NewOp1.getNode())
4152 return DAG.getNode(ISD::SRA, SDLoc(N), VT, N0, NewOp1);
4155 // fold (sra (trunc (sr x, c1)), c2) -> (trunc (sra x, c1+c2))
4156 // if c1 is equal to the number of bits the trunc removes
4157 if (N0.getOpcode() == ISD::TRUNCATE &&
4158 (N0.getOperand(0).getOpcode() == ISD::SRL ||
4159 N0.getOperand(0).getOpcode() == ISD::SRA) &&
4160 N0.getOperand(0).hasOneUse() &&
4161 N0.getOperand(0).getOperand(1).hasOneUse() &&
4162 N1C && isa<ConstantSDNode>(N0.getOperand(0).getOperand(1))) {
4163 EVT LargeVT = N0.getOperand(0).getValueType();
4164 ConstantSDNode *LargeShiftAmt =
4165 cast<ConstantSDNode>(N0.getOperand(0).getOperand(1));
4167 if (LargeVT.getScalarType().getSizeInBits() - OpSizeInBits ==
4168 LargeShiftAmt->getZExtValue()) {
4170 DAG.getConstant(LargeShiftAmt->getZExtValue() + N1C->getZExtValue(),
4171 getShiftAmountTy(N0.getOperand(0).getOperand(0).getValueType()));
4172 SDValue SRA = DAG.getNode(ISD::SRA, SDLoc(N), LargeVT,
4173 N0.getOperand(0).getOperand(0), Amt);
4174 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, SRA);
4178 // Simplify, based on bits shifted out of the LHS.
4179 if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
4180 return SDValue(N, 0);
4183 // If the sign bit is known to be zero, switch this to a SRL.
4184 if (DAG.SignBitIsZero(N0))
4185 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, N1);
4188 SDValue NewSRA = visitShiftByConstant(N, N1C->getZExtValue());
4189 if (NewSRA.getNode())
4196 SDValue DAGCombiner::visitSRL(SDNode *N) {
4197 SDValue N0 = N->getOperand(0);
4198 SDValue N1 = N->getOperand(1);
4199 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
4200 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4201 EVT VT = N0.getValueType();
4202 unsigned OpSizeInBits = VT.getScalarType().getSizeInBits();
4205 if (VT.isVector()) {
4206 SDValue FoldedVOp = SimplifyVBinOp(N);
4207 if (FoldedVOp.getNode()) return FoldedVOp;
4210 // fold (srl c1, c2) -> c1 >>u c2
4212 return DAG.FoldConstantArithmetic(ISD::SRL, VT, N0C, N1C);
4213 // fold (srl 0, x) -> 0
4214 if (N0C && N0C->isNullValue())
4216 // fold (srl x, c >= size(x)) -> undef
4217 if (N1C && N1C->getZExtValue() >= OpSizeInBits)
4218 return DAG.getUNDEF(VT);
4219 // fold (srl x, 0) -> x
4220 if (N1C && N1C->isNullValue())
4222 // if (srl x, c) is known to be zero, return 0
4223 if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0),
4224 APInt::getAllOnesValue(OpSizeInBits)))
4225 return DAG.getConstant(0, VT);
4227 // fold (srl (srl x, c1), c2) -> 0 or (srl x, (add c1, c2))
4228 if (N1C && N0.getOpcode() == ISD::SRL &&
4229 N0.getOperand(1).getOpcode() == ISD::Constant) {
4230 uint64_t c1 = cast<ConstantSDNode>(N0.getOperand(1))->getZExtValue();
4231 uint64_t c2 = N1C->getZExtValue();
4232 if (c1 + c2 >= OpSizeInBits)
4233 return DAG.getConstant(0, VT);
4234 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0),
4235 DAG.getConstant(c1 + c2, N1.getValueType()));
4238 // fold (srl (trunc (srl x, c1)), c2) -> 0 or (trunc (srl x, (add c1, c2)))
4239 if (N1C && N0.getOpcode() == ISD::TRUNCATE &&
4240 N0.getOperand(0).getOpcode() == ISD::SRL &&
4241 isa<ConstantSDNode>(N0.getOperand(0)->getOperand(1))) {
4243 cast<ConstantSDNode>(N0.getOperand(0)->getOperand(1))->getZExtValue();
4244 uint64_t c2 = N1C->getZExtValue();
4245 EVT InnerShiftVT = N0.getOperand(0).getValueType();
4246 EVT ShiftCountVT = N0.getOperand(0)->getOperand(1).getValueType();
4247 uint64_t InnerShiftSize = InnerShiftVT.getScalarType().getSizeInBits();
4248 // This is only valid if the OpSizeInBits + c1 = size of inner shift.
4249 if (c1 + OpSizeInBits == InnerShiftSize) {
4250 if (c1 + c2 >= InnerShiftSize)
4251 return DAG.getConstant(0, VT);
4252 return DAG.getNode(ISD::TRUNCATE, SDLoc(N0), VT,
4253 DAG.getNode(ISD::SRL, SDLoc(N0), InnerShiftVT,
4254 N0.getOperand(0)->getOperand(0),
4255 DAG.getConstant(c1 + c2, ShiftCountVT)));
4259 // fold (srl (shl x, c), c) -> (and x, cst2)
4260 if (N1C && N0.getOpcode() == ISD::SHL && N0.getOperand(1) == N1 &&
4261 N0.getValueSizeInBits() <= 64) {
4262 uint64_t ShAmt = N1C->getZExtValue()+64-N0.getValueSizeInBits();
4263 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0.getOperand(0),
4264 DAG.getConstant(~0ULL >> ShAmt, VT));
4267 // fold (srl (anyextend x), c) -> (and (anyextend (srl x, c)), mask)
4268 if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
4269 // Shifting in all undef bits?
4270 EVT SmallVT = N0.getOperand(0).getValueType();
4271 if (N1C->getZExtValue() >= SmallVT.getSizeInBits())
4272 return DAG.getUNDEF(VT);
4274 if (!LegalTypes || TLI.isTypeDesirableForOp(ISD::SRL, SmallVT)) {
4275 uint64_t ShiftAmt = N1C->getZExtValue();
4276 SDValue SmallShift = DAG.getNode(ISD::SRL, SDLoc(N0), SmallVT,
4278 DAG.getConstant(ShiftAmt, getShiftAmountTy(SmallVT)));
4279 AddToWorkList(SmallShift.getNode());
4280 APInt Mask = APInt::getAllOnesValue(VT.getSizeInBits()).lshr(ShiftAmt);
4281 return DAG.getNode(ISD::AND, SDLoc(N), VT,
4282 DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, SmallShift),
4283 DAG.getConstant(Mask, VT));
4287 // fold (srl (sra X, Y), 31) -> (srl X, 31). This srl only looks at the sign
4288 // bit, which is unmodified by sra.
4289 if (N1C && N1C->getZExtValue() + 1 == VT.getSizeInBits()) {
4290 if (N0.getOpcode() == ISD::SRA)
4291 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0), N1);
4294 // fold (srl (ctlz x), "5") -> x iff x has one bit set (the low bit).
4295 if (N1C && N0.getOpcode() == ISD::CTLZ &&
4296 N1C->getAPIntValue() == Log2_32(VT.getSizeInBits())) {
4297 APInt KnownZero, KnownOne;
4298 DAG.ComputeMaskedBits(N0.getOperand(0), KnownZero, KnownOne);
4300 // If any of the input bits are KnownOne, then the input couldn't be all
4301 // zeros, thus the result of the srl will always be zero.
4302 if (KnownOne.getBoolValue()) return DAG.getConstant(0, VT);
4304 // If all of the bits input the to ctlz node are known to be zero, then
4305 // the result of the ctlz is "32" and the result of the shift is one.
4306 APInt UnknownBits = ~KnownZero;
4307 if (UnknownBits == 0) return DAG.getConstant(1, VT);
4309 // Otherwise, check to see if there is exactly one bit input to the ctlz.
4310 if ((UnknownBits & (UnknownBits - 1)) == 0) {
4311 // Okay, we know that only that the single bit specified by UnknownBits
4312 // could be set on input to the CTLZ node. If this bit is set, the SRL
4313 // will return 0, if it is clear, it returns 1. Change the CTLZ/SRL pair
4314 // to an SRL/XOR pair, which is likely to simplify more.
4315 unsigned ShAmt = UnknownBits.countTrailingZeros();
4316 SDValue Op = N0.getOperand(0);
4319 Op = DAG.getNode(ISD::SRL, SDLoc(N0), VT, Op,
4320 DAG.getConstant(ShAmt, getShiftAmountTy(Op.getValueType())));
4321 AddToWorkList(Op.getNode());
4324 return DAG.getNode(ISD::XOR, SDLoc(N), VT,
4325 Op, DAG.getConstant(1, VT));
4329 // fold (srl x, (trunc (and y, c))) -> (srl x, (and (trunc y), (trunc c))).
4330 if (N1.getOpcode() == ISD::TRUNCATE &&
4331 N1.getOperand(0).getOpcode() == ISD::AND) {
4332 SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode());
4333 if (NewOp1.getNode())
4334 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, NewOp1);
4337 // fold operands of srl based on knowledge that the low bits are not
4339 if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
4340 return SDValue(N, 0);
4343 SDValue NewSRL = visitShiftByConstant(N, N1C->getZExtValue());
4344 if (NewSRL.getNode())
4348 // Attempt to convert a srl of a load into a narrower zero-extending load.
4349 SDValue NarrowLoad = ReduceLoadWidth(N);
4350 if (NarrowLoad.getNode())
4353 // Here is a common situation. We want to optimize:
4356 // %b = and i32 %a, 2
4357 // %c = srl i32 %b, 1
4358 // brcond i32 %c ...
4364 // %c = setcc eq %b, 0
4367 // However when after the source operand of SRL is optimized into AND, the SRL
4368 // itself may not be optimized further. Look for it and add the BRCOND into
4370 if (N->hasOneUse()) {
4371 SDNode *Use = *N->use_begin();
4372 if (Use->getOpcode() == ISD::BRCOND)
4374 else if (Use->getOpcode() == ISD::TRUNCATE && Use->hasOneUse()) {
4375 // Also look pass the truncate.
4376 Use = *Use->use_begin();
4377 if (Use->getOpcode() == ISD::BRCOND)
4385 SDValue DAGCombiner::visitCTLZ(SDNode *N) {
4386 SDValue N0 = N->getOperand(0);
4387 EVT VT = N->getValueType(0);
4389 // fold (ctlz c1) -> c2
4390 if (isa<ConstantSDNode>(N0))
4391 return DAG.getNode(ISD::CTLZ, SDLoc(N), VT, N0);
4395 SDValue DAGCombiner::visitCTLZ_ZERO_UNDEF(SDNode *N) {
4396 SDValue N0 = N->getOperand(0);
4397 EVT VT = N->getValueType(0);
4399 // fold (ctlz_zero_undef c1) -> c2
4400 if (isa<ConstantSDNode>(N0))
4401 return DAG.getNode(ISD::CTLZ_ZERO_UNDEF, SDLoc(N), VT, N0);
4405 SDValue DAGCombiner::visitCTTZ(SDNode *N) {
4406 SDValue N0 = N->getOperand(0);
4407 EVT VT = N->getValueType(0);
4409 // fold (cttz c1) -> c2
4410 if (isa<ConstantSDNode>(N0))
4411 return DAG.getNode(ISD::CTTZ, SDLoc(N), VT, N0);
4415 SDValue DAGCombiner::visitCTTZ_ZERO_UNDEF(SDNode *N) {
4416 SDValue N0 = N->getOperand(0);
4417 EVT VT = N->getValueType(0);
4419 // fold (cttz_zero_undef c1) -> c2
4420 if (isa<ConstantSDNode>(N0))
4421 return DAG.getNode(ISD::CTTZ_ZERO_UNDEF, SDLoc(N), VT, N0);
4425 SDValue DAGCombiner::visitCTPOP(SDNode *N) {
4426 SDValue N0 = N->getOperand(0);
4427 EVT VT = N->getValueType(0);
4429 // fold (ctpop c1) -> c2
4430 if (isa<ConstantSDNode>(N0))
4431 return DAG.getNode(ISD::CTPOP, SDLoc(N), VT, N0);
4435 SDValue DAGCombiner::visitSELECT(SDNode *N) {
4436 SDValue N0 = N->getOperand(0);
4437 SDValue N1 = N->getOperand(1);
4438 SDValue N2 = N->getOperand(2);
4439 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
4440 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4441 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2);
4442 EVT VT = N->getValueType(0);
4443 EVT VT0 = N0.getValueType();
4445 // fold (select C, X, X) -> X
4448 // fold (select true, X, Y) -> X
4449 if (N0C && !N0C->isNullValue())
4451 // fold (select false, X, Y) -> Y
4452 if (N0C && N0C->isNullValue())
4454 // fold (select C, 1, X) -> (or C, X)
4455 if (VT == MVT::i1 && N1C && N1C->getAPIntValue() == 1)
4456 return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N2);
4457 // fold (select C, 0, 1) -> (xor C, 1)
4458 if (VT.isInteger() &&
4461 TLI.getBooleanContents(false) ==
4462 TargetLowering::ZeroOrOneBooleanContent)) &&
4463 N1C && N2C && N1C->isNullValue() && N2C->getAPIntValue() == 1) {
4466 return DAG.getNode(ISD::XOR, SDLoc(N), VT0,
4467 N0, DAG.getConstant(1, VT0));
4468 XORNode = DAG.getNode(ISD::XOR, SDLoc(N0), VT0,
4469 N0, DAG.getConstant(1, VT0));
4470 AddToWorkList(XORNode.getNode());
4472 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, XORNode);
4473 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, XORNode);
4475 // fold (select C, 0, X) -> (and (not C), X)
4476 if (VT == VT0 && VT == MVT::i1 && N1C && N1C->isNullValue()) {
4477 SDValue NOTNode = DAG.getNOT(SDLoc(N0), N0, VT);
4478 AddToWorkList(NOTNode.getNode());
4479 return DAG.getNode(ISD::AND, SDLoc(N), VT, NOTNode, N2);
4481 // fold (select C, X, 1) -> (or (not C), X)
4482 if (VT == VT0 && VT == MVT::i1 && N2C && N2C->getAPIntValue() == 1) {
4483 SDValue NOTNode = DAG.getNOT(SDLoc(N0), N0, VT);
4484 AddToWorkList(NOTNode.getNode());
4485 return DAG.getNode(ISD::OR, SDLoc(N), VT, NOTNode, N1);
4487 // fold (select C, X, 0) -> (and C, X)
4488 if (VT == MVT::i1 && N2C && N2C->isNullValue())
4489 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, N1);
4490 // fold (select X, X, Y) -> (or X, Y)
4491 // fold (select X, 1, Y) -> (or X, Y)
4492 if (VT == MVT::i1 && (N0 == N1 || (N1C && N1C->getAPIntValue() == 1)))
4493 return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N2);
4494 // fold (select X, Y, X) -> (and X, Y)
4495 // fold (select X, Y, 0) -> (and X, Y)
4496 if (VT == MVT::i1 && (N0 == N2 || (N2C && N2C->getAPIntValue() == 0)))
4497 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, N1);
4499 // If we can fold this based on the true/false value, do so.
4500 if (SimplifySelectOps(N, N1, N2))
4501 return SDValue(N, 0); // Don't revisit N.
4503 // fold selects based on a setcc into other things, such as min/max/abs
4504 if (N0.getOpcode() == ISD::SETCC) {
4506 // Check against MVT::Other for SELECT_CC, which is a workaround for targets
4507 // having to say they don't support SELECT_CC on every type the DAG knows
4508 // about, since there is no way to mark an opcode illegal at all value types
4509 if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, MVT::Other) &&
4510 TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT))
4511 return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT,
4512 N0.getOperand(0), N0.getOperand(1),
4513 N1, N2, N0.getOperand(2));
4514 return SimplifySelect(SDLoc(N), N0, N1, N2);
4521 std::pair<SDValue, SDValue> SplitVSETCC(const SDNode *N, SelectionDAG &DAG) {
4524 std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(N->getValueType(0));
4526 // Split the inputs.
4527 SDValue Lo, Hi, LL, LH, RL, RH;
4528 std::tie(LL, LH) = DAG.SplitVectorOperand(N, 0);
4529 std::tie(RL, RH) = DAG.SplitVectorOperand(N, 1);
4531 Lo = DAG.getNode(N->getOpcode(), DL, LoVT, LL, RL, N->getOperand(2));
4532 Hi = DAG.getNode(N->getOpcode(), DL, HiVT, LH, RH, N->getOperand(2));
4534 return std::make_pair(Lo, Hi);
4537 SDValue DAGCombiner::visitVSELECT(SDNode *N) {
4538 SDValue N0 = N->getOperand(0);
4539 SDValue N1 = N->getOperand(1);
4540 SDValue N2 = N->getOperand(2);
4543 // Canonicalize integer abs.
4544 // vselect (setg[te] X, 0), X, -X ->
4545 // vselect (setgt X, -1), X, -X ->
4546 // vselect (setl[te] X, 0), -X, X ->
4547 // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
4548 if (N0.getOpcode() == ISD::SETCC) {
4549 SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
4550 ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
4552 bool RHSIsAllZeros = ISD::isBuildVectorAllZeros(RHS.getNode());
4554 if (((RHSIsAllZeros && (CC == ISD::SETGT || CC == ISD::SETGE)) ||
4555 (ISD::isBuildVectorAllOnes(RHS.getNode()) && CC == ISD::SETGT)) &&
4556 N1 == LHS && N2.getOpcode() == ISD::SUB && N1 == N2.getOperand(1))
4557 isAbs = ISD::isBuildVectorAllZeros(N2.getOperand(0).getNode());
4558 else if ((RHSIsAllZeros && (CC == ISD::SETLT || CC == ISD::SETLE)) &&
4559 N2 == LHS && N1.getOpcode() == ISD::SUB && N2 == N1.getOperand(1))
4560 isAbs = ISD::isBuildVectorAllZeros(N1.getOperand(0).getNode());
4563 EVT VT = LHS.getValueType();
4564 SDValue Shift = DAG.getNode(
4565 ISD::SRA, DL, VT, LHS,
4566 DAG.getConstant(VT.getScalarType().getSizeInBits() - 1, VT));
4567 SDValue Add = DAG.getNode(ISD::ADD, DL, VT, LHS, Shift);
4568 AddToWorkList(Shift.getNode());
4569 AddToWorkList(Add.getNode());
4570 return DAG.getNode(ISD::XOR, DL, VT, Add, Shift);
4574 // If the VSELECT result requires splitting and the mask is provided by a
4575 // SETCC, then split both nodes and its operands before legalization. This
4576 // prevents the type legalizer from unrolling SETCC into scalar comparisons
4577 // and enables future optimizations (e.g. min/max pattern matching on X86).
4578 if (N0.getOpcode() == ISD::SETCC) {
4579 EVT VT = N->getValueType(0);
4581 // Check if any splitting is required.
4582 if (TLI.getTypeAction(*DAG.getContext(), VT) !=
4583 TargetLowering::TypeSplitVector)
4586 SDValue Lo, Hi, CCLo, CCHi, LL, LH, RL, RH;
4587 std::tie(CCLo, CCHi) = SplitVSETCC(N0.getNode(), DAG);
4588 std::tie(LL, LH) = DAG.SplitVectorOperand(N, 1);
4589 std::tie(RL, RH) = DAG.SplitVectorOperand(N, 2);
4591 Lo = DAG.getNode(N->getOpcode(), DL, LL.getValueType(), CCLo, LL, RL);
4592 Hi = DAG.getNode(N->getOpcode(), DL, LH.getValueType(), CCHi, LH, RH);
4594 // Add the new VSELECT nodes to the work list in case they need to be split
4596 AddToWorkList(Lo.getNode());
4597 AddToWorkList(Hi.getNode());
4599 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
4602 // Fold (vselect (build_vector all_ones), N1, N2) -> N1
4603 if (ISD::isBuildVectorAllOnes(N0.getNode()))
4605 // Fold (vselect (build_vector all_zeros), N1, N2) -> N2
4606 if (ISD::isBuildVectorAllZeros(N0.getNode()))
4612 SDValue DAGCombiner::visitSELECT_CC(SDNode *N) {
4613 SDValue N0 = N->getOperand(0);
4614 SDValue N1 = N->getOperand(1);
4615 SDValue N2 = N->getOperand(2);
4616 SDValue N3 = N->getOperand(3);
4617 SDValue N4 = N->getOperand(4);
4618 ISD::CondCode CC = cast<CondCodeSDNode>(N4)->get();
4620 // fold select_cc lhs, rhs, x, x, cc -> x
4624 // Determine if the condition we're dealing with is constant
4625 SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()),
4626 N0, N1, CC, SDLoc(N), false);
4627 if (SCC.getNode()) {
4628 AddToWorkList(SCC.getNode());
4630 if (ConstantSDNode *SCCC = dyn_cast<ConstantSDNode>(SCC.getNode())) {
4631 if (!SCCC->isNullValue())
4632 return N2; // cond always true -> true val
4634 return N3; // cond always false -> false val
4637 // Fold to a simpler select_cc
4638 if (SCC.getOpcode() == ISD::SETCC)
4639 return DAG.getNode(ISD::SELECT_CC, SDLoc(N), N2.getValueType(),
4640 SCC.getOperand(0), SCC.getOperand(1), N2, N3,
4644 // If we can fold this based on the true/false value, do so.
4645 if (SimplifySelectOps(N, N2, N3))
4646 return SDValue(N, 0); // Don't revisit N.
4648 // fold select_cc into other things, such as min/max/abs
4649 return SimplifySelectCC(SDLoc(N), N0, N1, N2, N3, CC);
4652 SDValue DAGCombiner::visitSETCC(SDNode *N) {
4653 return SimplifySetCC(N->getValueType(0), N->getOperand(0), N->getOperand(1),
4654 cast<CondCodeSDNode>(N->getOperand(2))->get(),
4658 // tryToFoldExtendOfConstant - Try to fold a sext/zext/aext
4659 // dag node into a ConstantSDNode or a build_vector of constants.
4660 // This function is called by the DAGCombiner when visiting sext/zext/aext
4661 // dag nodes (see for example method DAGCombiner::visitSIGN_EXTEND).
4662 // Vector extends are not folded if operations are legal; this is to
4663 // avoid introducing illegal build_vector dag nodes.
4664 static SDNode *tryToFoldExtendOfConstant(SDNode *N, const TargetLowering &TLI,
4665 SelectionDAG &DAG, bool LegalTypes,
4666 bool LegalOperations) {
4667 unsigned Opcode = N->getOpcode();
4668 SDValue N0 = N->getOperand(0);
4669 EVT VT = N->getValueType(0);
4671 assert((Opcode == ISD::SIGN_EXTEND || Opcode == ISD::ZERO_EXTEND ||
4672 Opcode == ISD::ANY_EXTEND) && "Expected EXTEND dag node in input!");
4674 // fold (sext c1) -> c1
4675 // fold (zext c1) -> c1
4676 // fold (aext c1) -> c1
4677 if (isa<ConstantSDNode>(N0))
4678 return DAG.getNode(Opcode, SDLoc(N), VT, N0).getNode();
4680 // fold (sext (build_vector AllConstants) -> (build_vector AllConstants)
4681 // fold (zext (build_vector AllConstants) -> (build_vector AllConstants)
4682 // fold (aext (build_vector AllConstants) -> (build_vector AllConstants)
4683 EVT SVT = VT.getScalarType();
4684 if (!(VT.isVector() &&
4685 (!LegalTypes || (!LegalOperations && TLI.isTypeLegal(SVT))) &&
4686 ISD::isBuildVectorOfConstantSDNodes(N0.getNode())))
4689 // We can fold this node into a build_vector.
4690 unsigned VTBits = SVT.getSizeInBits();
4691 unsigned EVTBits = N0->getValueType(0).getScalarType().getSizeInBits();
4692 unsigned ShAmt = VTBits - EVTBits;
4693 SmallVector<SDValue, 8> Elts;
4694 unsigned NumElts = N0->getNumOperands();
4697 for (unsigned i=0; i != NumElts; ++i) {
4698 SDValue Op = N0->getOperand(i);
4699 if (Op->getOpcode() == ISD::UNDEF) {
4700 Elts.push_back(DAG.getUNDEF(SVT));
4704 ConstantSDNode *CurrentND = cast<ConstantSDNode>(Op);
4705 const APInt &C = APInt(VTBits, CurrentND->getAPIntValue().getZExtValue());
4706 if (Opcode == ISD::SIGN_EXTEND)
4707 Elts.push_back(DAG.getConstant(C.shl(ShAmt).ashr(ShAmt).getZExtValue(),
4710 Elts.push_back(DAG.getConstant(C.shl(ShAmt).lshr(ShAmt).getZExtValue(),
4714 return DAG.getNode(ISD::BUILD_VECTOR, DL, VT, &Elts[0], NumElts).getNode();
4717 // ExtendUsesToFormExtLoad - Trying to extend uses of a load to enable this:
4718 // "fold ({s|z|a}ext (load x)) -> ({s|z|a}ext (truncate ({s|z|a}extload x)))"
4719 // transformation. Returns true if extension are possible and the above
4720 // mentioned transformation is profitable.
4721 static bool ExtendUsesToFormExtLoad(SDNode *N, SDValue N0,
4723 SmallVectorImpl<SDNode *> &ExtendNodes,
4724 const TargetLowering &TLI) {
4725 bool HasCopyToRegUses = false;
4726 bool isTruncFree = TLI.isTruncateFree(N->getValueType(0), N0.getValueType());
4727 for (SDNode::use_iterator UI = N0.getNode()->use_begin(),
4728 UE = N0.getNode()->use_end();
4733 if (UI.getUse().getResNo() != N0.getResNo())
4735 // FIXME: Only extend SETCC N, N and SETCC N, c for now.
4736 if (ExtOpc != ISD::ANY_EXTEND && User->getOpcode() == ISD::SETCC) {
4737 ISD::CondCode CC = cast<CondCodeSDNode>(User->getOperand(2))->get();
4738 if (ExtOpc == ISD::ZERO_EXTEND && ISD::isSignedIntSetCC(CC))
4739 // Sign bits will be lost after a zext.
4742 for (unsigned i = 0; i != 2; ++i) {
4743 SDValue UseOp = User->getOperand(i);
4746 if (!isa<ConstantSDNode>(UseOp))
4751 ExtendNodes.push_back(User);
4754 // If truncates aren't free and there are users we can't
4755 // extend, it isn't worthwhile.
4758 // Remember if this value is live-out.
4759 if (User->getOpcode() == ISD::CopyToReg)
4760 HasCopyToRegUses = true;
4763 if (HasCopyToRegUses) {
4764 bool BothLiveOut = false;
4765 for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
4767 SDUse &Use = UI.getUse();
4768 if (Use.getResNo() == 0 && Use.getUser()->getOpcode() == ISD::CopyToReg) {
4774 // Both unextended and extended values are live out. There had better be
4775 // a good reason for the transformation.
4776 return ExtendNodes.size();
4781 void DAGCombiner::ExtendSetCCUses(const SmallVectorImpl<SDNode *> &SetCCs,
4782 SDValue Trunc, SDValue ExtLoad, SDLoc DL,
4783 ISD::NodeType ExtType) {
4784 // Extend SetCC uses if necessary.
4785 for (unsigned i = 0, e = SetCCs.size(); i != e; ++i) {
4786 SDNode *SetCC = SetCCs[i];
4787 SmallVector<SDValue, 4> Ops;
4789 for (unsigned j = 0; j != 2; ++j) {
4790 SDValue SOp = SetCC->getOperand(j);
4792 Ops.push_back(ExtLoad);
4794 Ops.push_back(DAG.getNode(ExtType, DL, ExtLoad->getValueType(0), SOp));
4797 Ops.push_back(SetCC->getOperand(2));
4798 CombineTo(SetCC, DAG.getNode(ISD::SETCC, DL, SetCC->getValueType(0),
4799 &Ops[0], Ops.size()));
4803 SDValue DAGCombiner::visitSIGN_EXTEND(SDNode *N) {
4804 SDValue N0 = N->getOperand(0);
4805 EVT VT = N->getValueType(0);
4807 if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
4809 return SDValue(Res, 0);
4811 // fold (sext (sext x)) -> (sext x)
4812 // fold (sext (aext x)) -> (sext x)
4813 if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
4814 return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT,
4817 if (N0.getOpcode() == ISD::TRUNCATE) {
4818 // fold (sext (truncate (load x))) -> (sext (smaller load x))
4819 // fold (sext (truncate (srl (load x), c))) -> (sext (smaller load (x+c/n)))
4820 SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
4821 if (NarrowLoad.getNode()) {
4822 SDNode* oye = N0.getNode()->getOperand(0).getNode();
4823 if (NarrowLoad.getNode() != N0.getNode()) {
4824 CombineTo(N0.getNode(), NarrowLoad);
4825 // CombineTo deleted the truncate, if needed, but not what's under it.
4828 return SDValue(N, 0); // Return N so it doesn't get rechecked!
4831 // See if the value being truncated is already sign extended. If so, just
4832 // eliminate the trunc/sext pair.
4833 SDValue Op = N0.getOperand(0);
4834 unsigned OpBits = Op.getValueType().getScalarType().getSizeInBits();
4835 unsigned MidBits = N0.getValueType().getScalarType().getSizeInBits();
4836 unsigned DestBits = VT.getScalarType().getSizeInBits();
4837 unsigned NumSignBits = DAG.ComputeNumSignBits(Op);
4839 if (OpBits == DestBits) {
4840 // Op is i32, Mid is i8, and Dest is i32. If Op has more than 24 sign
4841 // bits, it is already ready.
4842 if (NumSignBits > DestBits-MidBits)
4844 } else if (OpBits < DestBits) {
4845 // Op is i32, Mid is i8, and Dest is i64. If Op has more than 24 sign
4846 // bits, just sext from i32.
4847 if (NumSignBits > OpBits-MidBits)
4848 return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, Op);
4850 // Op is i64, Mid is i8, and Dest is i32. If Op has more than 56 sign
4851 // bits, just truncate to i32.
4852 if (NumSignBits > OpBits-MidBits)
4853 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
4856 // fold (sext (truncate x)) -> (sextinreg x).
4857 if (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG,
4858 N0.getValueType())) {
4859 if (OpBits < DestBits)
4860 Op = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N0), VT, Op);
4861 else if (OpBits > DestBits)
4862 Op = DAG.getNode(ISD::TRUNCATE, SDLoc(N0), VT, Op);
4863 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, Op,
4864 DAG.getValueType(N0.getValueType()));
4868 // fold (sext (load x)) -> (sext (truncate (sextload x)))
4869 // None of the supported targets knows how to perform load and sign extend
4870 // on vectors in one instruction. We only perform this transformation on
4872 if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() &&
4873 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
4874 TLI.isLoadExtLegal(ISD::SEXTLOAD, N0.getValueType()))) {
4875 bool DoXform = true;
4876 SmallVector<SDNode*, 4> SetCCs;
4877 if (!N0.hasOneUse())
4878 DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::SIGN_EXTEND, SetCCs, TLI);
4880 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
4881 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
4883 LN0->getBasePtr(), N0.getValueType(),
4884 LN0->getMemOperand());
4885 CombineTo(N, ExtLoad);
4886 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
4887 N0.getValueType(), ExtLoad);
4888 CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
4889 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
4891 return SDValue(N, 0); // Return N so it doesn't get rechecked!
4895 // fold (sext (sextload x)) -> (sext (truncate (sextload x)))
4896 // fold (sext ( extload x)) -> (sext (truncate (sextload x)))
4897 if ((ISD::isSEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) &&
4898 ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) {
4899 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
4900 EVT MemVT = LN0->getMemoryVT();
4901 if ((!LegalOperations && !LN0->isVolatile()) ||
4902 TLI.isLoadExtLegal(ISD::SEXTLOAD, MemVT)) {
4903 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
4905 LN0->getBasePtr(), MemVT,
4906 LN0->getMemOperand());
4907 CombineTo(N, ExtLoad);
4908 CombineTo(N0.getNode(),
4909 DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
4910 N0.getValueType(), ExtLoad),
4911 ExtLoad.getValue(1));
4912 return SDValue(N, 0); // Return N so it doesn't get rechecked!
4916 // fold (sext (and/or/xor (load x), cst)) ->
4917 // (and/or/xor (sextload x), (sext cst))
4918 if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR ||
4919 N0.getOpcode() == ISD::XOR) &&
4920 isa<LoadSDNode>(N0.getOperand(0)) &&
4921 N0.getOperand(1).getOpcode() == ISD::Constant &&
4922 TLI.isLoadExtLegal(ISD::SEXTLOAD, N0.getValueType()) &&
4923 (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) {
4924 LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0));
4925 if (LN0->getExtensionType() != ISD::ZEXTLOAD) {
4926 bool DoXform = true;
4927 SmallVector<SDNode*, 4> SetCCs;
4928 if (!N0.hasOneUse())
4929 DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0), ISD::SIGN_EXTEND,
4932 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(LN0), VT,
4933 LN0->getChain(), LN0->getBasePtr(),
4935 LN0->getMemOperand());
4936 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
4937 Mask = Mask.sext(VT.getSizeInBits());
4938 SDValue And = DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
4939 ExtLoad, DAG.getConstant(Mask, VT));
4940 SDValue Trunc = DAG.getNode(ISD::TRUNCATE,
4941 SDLoc(N0.getOperand(0)),
4942 N0.getOperand(0).getValueType(), ExtLoad);
4944 CombineTo(N0.getOperand(0).getNode(), Trunc, ExtLoad.getValue(1));
4945 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
4947 return SDValue(N, 0); // Return N so it doesn't get rechecked!
4952 if (N0.getOpcode() == ISD::SETCC) {
4953 // sext(setcc) -> sext_in_reg(vsetcc) for vectors.
4954 // Only do this before legalize for now.
4955 if (VT.isVector() && !LegalOperations &&
4956 TLI.getBooleanContents(true) ==
4957 TargetLowering::ZeroOrNegativeOneBooleanContent) {
4958 EVT N0VT = N0.getOperand(0).getValueType();
4959 // On some architectures (such as SSE/NEON/etc) the SETCC result type is
4960 // of the same size as the compared operands. Only optimize sext(setcc())
4961 // if this is the case.
4962 EVT SVT = getSetCCResultType(N0VT);
4964 // We know that the # elements of the results is the same as the
4965 // # elements of the compare (and the # elements of the compare result
4966 // for that matter). Check to see that they are the same size. If so,
4967 // we know that the element size of the sext'd result matches the
4968 // element size of the compare operands.
4969 if (VT.getSizeInBits() == SVT.getSizeInBits())
4970 return DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
4972 cast<CondCodeSDNode>(N0.getOperand(2))->get());
4974 // If the desired elements are smaller or larger than the source
4975 // elements we can use a matching integer vector type and then
4976 // truncate/sign extend
4977 EVT MatchingVectorType = N0VT.changeVectorElementTypeToInteger();
4978 if (SVT == MatchingVectorType) {
4979 SDValue VsetCC = DAG.getSetCC(SDLoc(N), MatchingVectorType,
4980 N0.getOperand(0), N0.getOperand(1),
4981 cast<CondCodeSDNode>(N0.getOperand(2))->get());
4982 return DAG.getSExtOrTrunc(VsetCC, SDLoc(N), VT);
4986 // sext(setcc x, y, cc) -> (select (setcc x, y, cc), -1, 0)
4987 unsigned ElementWidth = VT.getScalarType().getSizeInBits();
4989 DAG.getConstant(APInt::getAllOnesValue(ElementWidth), VT);
4991 SimplifySelectCC(SDLoc(N), N0.getOperand(0), N0.getOperand(1),
4992 NegOne, DAG.getConstant(0, VT),
4993 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
4994 if (SCC.getNode()) return SCC;
4996 if (!VT.isVector()) {
4997 EVT SetCCVT = getSetCCResultType(N0.getOperand(0).getValueType());
4998 if (!LegalOperations || TLI.isOperationLegal(ISD::SETCC, SetCCVT)) {
5000 ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
5001 SDValue SetCC = DAG.getSetCC(DL,
5003 N0.getOperand(0), N0.getOperand(1), CC);
5004 EVT SelectVT = getSetCCResultType(VT);
5005 return DAG.getSelect(DL, VT,
5006 DAG.getSExtOrTrunc(SetCC, DL, SelectVT),
5007 NegOne, DAG.getConstant(0, VT));
5013 // fold (sext x) -> (zext x) if the sign bit is known zero.
5014 if ((!LegalOperations || TLI.isOperationLegal(ISD::ZERO_EXTEND, VT)) &&
5015 DAG.SignBitIsZero(N0))
5016 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, N0);
5021 // isTruncateOf - If N is a truncate of some other value, return true, record
5022 // the value being truncated in Op and which of Op's bits are zero in KnownZero.
5023 // This function computes KnownZero to avoid a duplicated call to
5024 // ComputeMaskedBits in the caller.
5025 static bool isTruncateOf(SelectionDAG &DAG, SDValue N, SDValue &Op,
5028 if (N->getOpcode() == ISD::TRUNCATE) {
5029 Op = N->getOperand(0);
5030 DAG.ComputeMaskedBits(Op, KnownZero, KnownOne);
5034 if (N->getOpcode() != ISD::SETCC || N->getValueType(0) != MVT::i1 ||
5035 cast<CondCodeSDNode>(N->getOperand(2))->get() != ISD::SETNE)
5038 SDValue Op0 = N->getOperand(0);
5039 SDValue Op1 = N->getOperand(1);
5040 assert(Op0.getValueType() == Op1.getValueType());
5042 ConstantSDNode *COp0 = dyn_cast<ConstantSDNode>(Op0);
5043 ConstantSDNode *COp1 = dyn_cast<ConstantSDNode>(Op1);
5044 if (COp0 && COp0->isNullValue())
5046 else if (COp1 && COp1->isNullValue())
5051 DAG.ComputeMaskedBits(Op, KnownZero, KnownOne);
5053 if (!(KnownZero | APInt(Op.getValueSizeInBits(), 1)).isAllOnesValue())
5059 SDValue DAGCombiner::visitZERO_EXTEND(SDNode *N) {
5060 SDValue N0 = N->getOperand(0);
5061 EVT VT = N->getValueType(0);
5063 if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
5065 return SDValue(Res, 0);
5067 // fold (zext (zext x)) -> (zext x)
5068 // fold (zext (aext x)) -> (zext x)
5069 if (N0.getOpcode() == ISD::ZERO_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
5070 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT,
5073 // fold (zext (truncate x)) -> (zext x) or
5074 // (zext (truncate x)) -> (truncate x)
5075 // This is valid when the truncated bits of x are already zero.
5076 // FIXME: We should extend this to work for vectors too.
5079 if (!VT.isVector() && isTruncateOf(DAG, N0, Op, KnownZero)) {
5080 APInt TruncatedBits =
5081 (Op.getValueSizeInBits() == N0.getValueSizeInBits()) ?
5082 APInt(Op.getValueSizeInBits(), 0) :
5083 APInt::getBitsSet(Op.getValueSizeInBits(),
5084 N0.getValueSizeInBits(),
5085 std::min(Op.getValueSizeInBits(),
5086 VT.getSizeInBits()));
5087 if (TruncatedBits == (KnownZero & TruncatedBits)) {
5088 if (VT.bitsGT(Op.getValueType()))
5089 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, Op);
5090 if (VT.bitsLT(Op.getValueType()))
5091 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
5097 // fold (zext (truncate (load x))) -> (zext (smaller load x))
5098 // fold (zext (truncate (srl (load x), c))) -> (zext (small load (x+c/n)))
5099 if (N0.getOpcode() == ISD::TRUNCATE) {
5100 SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
5101 if (NarrowLoad.getNode()) {
5102 SDNode* oye = N0.getNode()->getOperand(0).getNode();
5103 if (NarrowLoad.getNode() != N0.getNode()) {
5104 CombineTo(N0.getNode(), NarrowLoad);
5105 // CombineTo deleted the truncate, if needed, but not what's under it.
5108 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5112 // fold (zext (truncate x)) -> (and x, mask)
5113 if (N0.getOpcode() == ISD::TRUNCATE &&
5114 (!LegalOperations || TLI.isOperationLegal(ISD::AND, VT))) {
5116 // fold (zext (truncate (load x))) -> (zext (smaller load x))
5117 // fold (zext (truncate (srl (load x), c))) -> (zext (smaller load (x+c/n)))
5118 SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
5119 if (NarrowLoad.getNode()) {
5120 SDNode* oye = N0.getNode()->getOperand(0).getNode();
5121 if (NarrowLoad.getNode() != N0.getNode()) {
5122 CombineTo(N0.getNode(), NarrowLoad);
5123 // CombineTo deleted the truncate, if needed, but not what's under it.
5126 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5129 SDValue Op = N0.getOperand(0);
5130 if (Op.getValueType().bitsLT(VT)) {
5131 Op = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, Op);
5132 AddToWorkList(Op.getNode());
5133 } else if (Op.getValueType().bitsGT(VT)) {
5134 Op = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
5135 AddToWorkList(Op.getNode());
5137 return DAG.getZeroExtendInReg(Op, SDLoc(N),
5138 N0.getValueType().getScalarType());
5141 // Fold (zext (and (trunc x), cst)) -> (and x, cst),
5142 // if either of the casts is not free.
5143 if (N0.getOpcode() == ISD::AND &&
5144 N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
5145 N0.getOperand(1).getOpcode() == ISD::Constant &&
5146 (!TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(),
5147 N0.getValueType()) ||
5148 !TLI.isZExtFree(N0.getValueType(), VT))) {
5149 SDValue X = N0.getOperand(0).getOperand(0);
5150 if (X.getValueType().bitsLT(VT)) {
5151 X = DAG.getNode(ISD::ANY_EXTEND, SDLoc(X), VT, X);
5152 } else if (X.getValueType().bitsGT(VT)) {
5153 X = DAG.getNode(ISD::TRUNCATE, SDLoc(X), VT, X);
5155 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
5156 Mask = Mask.zext(VT.getSizeInBits());
5157 return DAG.getNode(ISD::AND, SDLoc(N), VT,
5158 X, DAG.getConstant(Mask, VT));
5161 // fold (zext (load x)) -> (zext (truncate (zextload x)))
5162 // None of the supported targets knows how to perform load and vector_zext
5163 // on vectors in one instruction. We only perform this transformation on
5165 if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() &&
5166 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
5167 TLI.isLoadExtLegal(ISD::ZEXTLOAD, N0.getValueType()))) {
5168 bool DoXform = true;
5169 SmallVector<SDNode*, 4> SetCCs;
5170 if (!N0.hasOneUse())
5171 DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ZERO_EXTEND, SetCCs, TLI);
5173 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5174 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT,
5176 LN0->getBasePtr(), N0.getValueType(),
5177 LN0->getMemOperand());
5178 CombineTo(N, ExtLoad);
5179 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
5180 N0.getValueType(), ExtLoad);
5181 CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
5183 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
5185 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5189 // fold (zext (and/or/xor (load x), cst)) ->
5190 // (and/or/xor (zextload x), (zext cst))
5191 if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR ||
5192 N0.getOpcode() == ISD::XOR) &&
5193 isa<LoadSDNode>(N0.getOperand(0)) &&
5194 N0.getOperand(1).getOpcode() == ISD::Constant &&
5195 TLI.isLoadExtLegal(ISD::ZEXTLOAD, N0.getValueType()) &&
5196 (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) {
5197 LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0));
5198 if (LN0->getExtensionType() != ISD::SEXTLOAD) {
5199 bool DoXform = true;
5200 SmallVector<SDNode*, 4> SetCCs;
5201 if (!N0.hasOneUse())
5202 DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0), ISD::ZERO_EXTEND,
5205 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), VT,
5206 LN0->getChain(), LN0->getBasePtr(),
5208 LN0->getMemOperand());
5209 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
5210 Mask = Mask.zext(VT.getSizeInBits());
5211 SDValue And = DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
5212 ExtLoad, DAG.getConstant(Mask, VT));
5213 SDValue Trunc = DAG.getNode(ISD::TRUNCATE,
5214 SDLoc(N0.getOperand(0)),
5215 N0.getOperand(0).getValueType(), ExtLoad);
5217 CombineTo(N0.getOperand(0).getNode(), Trunc, ExtLoad.getValue(1));
5218 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
5220 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5225 // fold (zext (zextload x)) -> (zext (truncate (zextload x)))
5226 // fold (zext ( extload x)) -> (zext (truncate (zextload x)))
5227 if ((ISD::isZEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) &&
5228 ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) {
5229 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5230 EVT MemVT = LN0->getMemoryVT();
5231 if ((!LegalOperations && !LN0->isVolatile()) ||
5232 TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT)) {
5233 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT,
5235 LN0->getBasePtr(), MemVT,
5236 LN0->getMemOperand());
5237 CombineTo(N, ExtLoad);
5238 CombineTo(N0.getNode(),
5239 DAG.getNode(ISD::TRUNCATE, SDLoc(N0), N0.getValueType(),
5241 ExtLoad.getValue(1));
5242 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5246 if (N0.getOpcode() == ISD::SETCC) {
5247 if (!LegalOperations && VT.isVector() &&
5248 N0.getValueType().getVectorElementType() == MVT::i1) {
5249 EVT N0VT = N0.getOperand(0).getValueType();
5250 if (getSetCCResultType(N0VT) == N0.getValueType())
5253 // zext(setcc) -> (and (vsetcc), (1, 1, ...) for vectors.
5254 // Only do this before legalize for now.
5255 EVT EltVT = VT.getVectorElementType();
5256 SmallVector<SDValue,8> OneOps(VT.getVectorNumElements(),
5257 DAG.getConstant(1, EltVT));
5258 if (VT.getSizeInBits() == N0VT.getSizeInBits())
5259 // We know that the # elements of the results is the same as the
5260 // # elements of the compare (and the # elements of the compare result
5261 // for that matter). Check to see that they are the same size. If so,
5262 // we know that the element size of the sext'd result matches the
5263 // element size of the compare operands.
5264 return DAG.getNode(ISD::AND, SDLoc(N), VT,
5265 DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
5267 cast<CondCodeSDNode>(N0.getOperand(2))->get()),
5268 DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT,
5269 &OneOps[0], OneOps.size()));
5271 // If the desired elements are smaller or larger than the source
5272 // elements we can use a matching integer vector type and then
5273 // truncate/sign extend
5274 EVT MatchingElementType =
5275 EVT::getIntegerVT(*DAG.getContext(),
5276 N0VT.getScalarType().getSizeInBits());
5277 EVT MatchingVectorType =
5278 EVT::getVectorVT(*DAG.getContext(), MatchingElementType,
5279 N0VT.getVectorNumElements());
5281 DAG.getSetCC(SDLoc(N), MatchingVectorType, N0.getOperand(0),
5283 cast<CondCodeSDNode>(N0.getOperand(2))->get());
5284 return DAG.getNode(ISD::AND, SDLoc(N), VT,
5285 DAG.getSExtOrTrunc(VsetCC, SDLoc(N), VT),
5286 DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT,
5287 &OneOps[0], OneOps.size()));
5290 // zext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
5292 SimplifySelectCC(SDLoc(N), N0.getOperand(0), N0.getOperand(1),
5293 DAG.getConstant(1, VT), DAG.getConstant(0, VT),
5294 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
5295 if (SCC.getNode()) return SCC;
5298 // (zext (shl (zext x), cst)) -> (shl (zext x), cst)
5299 if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL) &&
5300 isa<ConstantSDNode>(N0.getOperand(1)) &&
5301 N0.getOperand(0).getOpcode() == ISD::ZERO_EXTEND &&
5303 SDValue ShAmt = N0.getOperand(1);
5304 unsigned ShAmtVal = cast<ConstantSDNode>(ShAmt)->getZExtValue();
5305 if (N0.getOpcode() == ISD::SHL) {
5306 SDValue InnerZExt = N0.getOperand(0);
5307 // If the original shl may be shifting out bits, do not perform this
5309 unsigned KnownZeroBits = InnerZExt.getValueType().getSizeInBits() -
5310 InnerZExt.getOperand(0).getValueType().getSizeInBits();
5311 if (ShAmtVal > KnownZeroBits)
5317 // Ensure that the shift amount is wide enough for the shifted value.
5318 if (VT.getSizeInBits() >= 256)
5319 ShAmt = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, ShAmt);
5321 return DAG.getNode(N0.getOpcode(), DL, VT,
5322 DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0)),
5329 SDValue DAGCombiner::visitANY_EXTEND(SDNode *N) {
5330 SDValue N0 = N->getOperand(0);
5331 EVT VT = N->getValueType(0);
5333 if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
5335 return SDValue(Res, 0);
5337 // fold (aext (aext x)) -> (aext x)
5338 // fold (aext (zext x)) -> (zext x)
5339 // fold (aext (sext x)) -> (sext x)
5340 if (N0.getOpcode() == ISD::ANY_EXTEND ||
5341 N0.getOpcode() == ISD::ZERO_EXTEND ||
5342 N0.getOpcode() == ISD::SIGN_EXTEND)
5343 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, N0.getOperand(0));
5345 // fold (aext (truncate (load x))) -> (aext (smaller load x))
5346 // fold (aext (truncate (srl (load x), c))) -> (aext (small load (x+c/n)))
5347 if (N0.getOpcode() == ISD::TRUNCATE) {
5348 SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
5349 if (NarrowLoad.getNode()) {
5350 SDNode* oye = N0.getNode()->getOperand(0).getNode();
5351 if (NarrowLoad.getNode() != N0.getNode()) {
5352 CombineTo(N0.getNode(), NarrowLoad);
5353 // CombineTo deleted the truncate, if needed, but not what's under it.
5356 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5360 // fold (aext (truncate x))
5361 if (N0.getOpcode() == ISD::TRUNCATE) {
5362 SDValue TruncOp = N0.getOperand(0);
5363 if (TruncOp.getValueType() == VT)
5364 return TruncOp; // x iff x size == zext size.
5365 if (TruncOp.getValueType().bitsGT(VT))
5366 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, TruncOp);
5367 return DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, TruncOp);
5370 // Fold (aext (and (trunc x), cst)) -> (and x, cst)
5371 // if the trunc is not free.
5372 if (N0.getOpcode() == ISD::AND &&
5373 N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
5374 N0.getOperand(1).getOpcode() == ISD::Constant &&
5375 !TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(),
5376 N0.getValueType())) {
5377 SDValue X = N0.getOperand(0).getOperand(0);
5378 if (X.getValueType().bitsLT(VT)) {
5379 X = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, X);
5380 } else if (X.getValueType().bitsGT(VT)) {
5381 X = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, X);
5383 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
5384 Mask = Mask.zext(VT.getSizeInBits());
5385 return DAG.getNode(ISD::AND, SDLoc(N), VT,
5386 X, DAG.getConstant(Mask, VT));
5389 // fold (aext (load x)) -> (aext (truncate (extload x)))
5390 // None of the supported targets knows how to perform load and any_ext
5391 // on vectors in one instruction. We only perform this transformation on
5393 if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() &&
5394 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
5395 TLI.isLoadExtLegal(ISD::EXTLOAD, N0.getValueType()))) {
5396 bool DoXform = true;
5397 SmallVector<SDNode*, 4> SetCCs;
5398 if (!N0.hasOneUse())
5399 DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ANY_EXTEND, SetCCs, TLI);
5401 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5402 SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT,
5404 LN0->getBasePtr(), N0.getValueType(),
5405 LN0->getMemOperand());
5406 CombineTo(N, ExtLoad);
5407 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
5408 N0.getValueType(), ExtLoad);
5409 CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
5410 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
5412 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5416 // fold (aext (zextload x)) -> (aext (truncate (zextload x)))
5417 // fold (aext (sextload x)) -> (aext (truncate (sextload x)))
5418 // fold (aext ( extload x)) -> (aext (truncate (extload x)))
5419 if (N0.getOpcode() == ISD::LOAD &&
5420 !ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
5422 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5423 EVT MemVT = LN0->getMemoryVT();
5424 SDValue ExtLoad = DAG.getExtLoad(LN0->getExtensionType(), SDLoc(N),
5425 VT, LN0->getChain(), LN0->getBasePtr(),
5426 MemVT, LN0->getMemOperand());
5427 CombineTo(N, ExtLoad);
5428 CombineTo(N0.getNode(),
5429 DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
5430 N0.getValueType(), ExtLoad),
5431 ExtLoad.getValue(1));
5432 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5435 if (N0.getOpcode() == ISD::SETCC) {
5436 // aext(setcc) -> sext_in_reg(vsetcc) for vectors.
5437 // Only do this before legalize for now.
5438 if (VT.isVector() && !LegalOperations) {
5439 EVT N0VT = N0.getOperand(0).getValueType();
5440 // We know that the # elements of the results is the same as the
5441 // # elements of the compare (and the # elements of the compare result
5442 // for that matter). Check to see that they are the same size. If so,
5443 // we know that the element size of the sext'd result matches the
5444 // element size of the compare operands.
5445 if (VT.getSizeInBits() == N0VT.getSizeInBits())
5446 return DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
5448 cast<CondCodeSDNode>(N0.getOperand(2))->get());
5449 // If the desired elements are smaller or larger than the source
5450 // elements we can use a matching integer vector type and then
5451 // truncate/sign extend
5453 EVT MatchingElementType =
5454 EVT::getIntegerVT(*DAG.getContext(),
5455 N0VT.getScalarType().getSizeInBits());
5456 EVT MatchingVectorType =
5457 EVT::getVectorVT(*DAG.getContext(), MatchingElementType,
5458 N0VT.getVectorNumElements());
5460 DAG.getSetCC(SDLoc(N), MatchingVectorType, N0.getOperand(0),
5462 cast<CondCodeSDNode>(N0.getOperand(2))->get());
5463 return DAG.getSExtOrTrunc(VsetCC, SDLoc(N), VT);
5467 // aext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
5469 SimplifySelectCC(SDLoc(N), N0.getOperand(0), N0.getOperand(1),
5470 DAG.getConstant(1, VT), DAG.getConstant(0, VT),
5471 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
5479 /// GetDemandedBits - See if the specified operand can be simplified with the
5480 /// knowledge that only the bits specified by Mask are used. If so, return the
5481 /// simpler operand, otherwise return a null SDValue.
5482 SDValue DAGCombiner::GetDemandedBits(SDValue V, const APInt &Mask) {
5483 switch (V.getOpcode()) {
5485 case ISD::Constant: {
5486 const ConstantSDNode *CV = cast<ConstantSDNode>(V.getNode());
5487 assert(CV != 0 && "Const value should be ConstSDNode.");
5488 const APInt &CVal = CV->getAPIntValue();
5489 APInt NewVal = CVal & Mask;
5491 return DAG.getConstant(NewVal, V.getValueType());
5496 // If the LHS or RHS don't contribute bits to the or, drop them.
5497 if (DAG.MaskedValueIsZero(V.getOperand(0), Mask))
5498 return V.getOperand(1);
5499 if (DAG.MaskedValueIsZero(V.getOperand(1), Mask))
5500 return V.getOperand(0);
5503 // Only look at single-use SRLs.
5504 if (!V.getNode()->hasOneUse())
5506 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(V.getOperand(1))) {
5507 // See if we can recursively simplify the LHS.
5508 unsigned Amt = RHSC->getZExtValue();
5510 // Watch out for shift count overflow though.
5511 if (Amt >= Mask.getBitWidth()) break;
5512 APInt NewMask = Mask << Amt;
5513 SDValue SimplifyLHS = GetDemandedBits(V.getOperand(0), NewMask);
5514 if (SimplifyLHS.getNode())
5515 return DAG.getNode(ISD::SRL, SDLoc(V), V.getValueType(),
5516 SimplifyLHS, V.getOperand(1));
5522 /// ReduceLoadWidth - If the result of a wider load is shifted to right of N
5523 /// bits and then truncated to a narrower type and where N is a multiple
5524 /// of number of bits of the narrower type, transform it to a narrower load
5525 /// from address + N / num of bits of new type. If the result is to be
5526 /// extended, also fold the extension to form a extending load.
5527 SDValue DAGCombiner::ReduceLoadWidth(SDNode *N) {
5528 unsigned Opc = N->getOpcode();
5530 ISD::LoadExtType ExtType = ISD::NON_EXTLOAD;
5531 SDValue N0 = N->getOperand(0);
5532 EVT VT = N->getValueType(0);
5535 // This transformation isn't valid for vector loads.
5539 // Special case: SIGN_EXTEND_INREG is basically truncating to ExtVT then
5541 if (Opc == ISD::SIGN_EXTEND_INREG) {
5542 ExtType = ISD::SEXTLOAD;
5543 ExtVT = cast<VTSDNode>(N->getOperand(1))->getVT();
5544 } else if (Opc == ISD::SRL) {
5545 // Another special-case: SRL is basically zero-extending a narrower value.
5546 ExtType = ISD::ZEXTLOAD;
5548 ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1));
5549 if (!N01) return SDValue();
5550 ExtVT = EVT::getIntegerVT(*DAG.getContext(),
5551 VT.getSizeInBits() - N01->getZExtValue());
5553 if (LegalOperations && !TLI.isLoadExtLegal(ExtType, ExtVT))
5556 unsigned EVTBits = ExtVT.getSizeInBits();
5558 // Do not generate loads of non-round integer types since these can
5559 // be expensive (and would be wrong if the type is not byte sized).
5560 if (!ExtVT.isRound())
5564 if (N0.getOpcode() == ISD::SRL && N0.hasOneUse()) {
5565 if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
5566 ShAmt = N01->getZExtValue();
5567 // Is the shift amount a multiple of size of VT?
5568 if ((ShAmt & (EVTBits-1)) == 0) {
5569 N0 = N0.getOperand(0);
5570 // Is the load width a multiple of size of VT?
5571 if ((N0.getValueType().getSizeInBits() & (EVTBits-1)) != 0)
5575 // At this point, we must have a load or else we can't do the transform.
5576 if (!isa<LoadSDNode>(N0)) return SDValue();
5578 // Because a SRL must be assumed to *need* to zero-extend the high bits
5579 // (as opposed to anyext the high bits), we can't combine the zextload
5580 // lowering of SRL and an sextload.
5581 if (cast<LoadSDNode>(N0)->getExtensionType() == ISD::SEXTLOAD)
5584 // If the shift amount is larger than the input type then we're not
5585 // accessing any of the loaded bytes. If the load was a zextload/extload
5586 // then the result of the shift+trunc is zero/undef (handled elsewhere).
5587 if (ShAmt >= cast<LoadSDNode>(N0)->getMemoryVT().getSizeInBits())
5592 // If the load is shifted left (and the result isn't shifted back right),
5593 // we can fold the truncate through the shift.
5594 unsigned ShLeftAmt = 0;
5595 if (ShAmt == 0 && N0.getOpcode() == ISD::SHL && N0.hasOneUse() &&
5596 ExtVT == VT && TLI.isNarrowingProfitable(N0.getValueType(), VT)) {
5597 if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
5598 ShLeftAmt = N01->getZExtValue();
5599 N0 = N0.getOperand(0);
5603 // If we haven't found a load, we can't narrow it. Don't transform one with
5604 // multiple uses, this would require adding a new load.
5605 if (!isa<LoadSDNode>(N0) || !N0.hasOneUse())
5608 // Don't change the width of a volatile load.
5609 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5610 if (LN0->isVolatile())
5613 // Verify that we are actually reducing a load width here.
5614 if (LN0->getMemoryVT().getSizeInBits() < EVTBits)
5617 // For the transform to be legal, the load must produce only two values
5618 // (the value loaded and the chain). Don't transform a pre-increment
5619 // load, for example, which produces an extra value. Otherwise the
5620 // transformation is not equivalent, and the downstream logic to replace
5621 // uses gets things wrong.
5622 if (LN0->getNumValues() > 2)
5625 // If the load that we're shrinking is an extload and we're not just
5626 // discarding the extension we can't simply shrink the load. Bail.
5627 // TODO: It would be possible to merge the extensions in some cases.
5628 if (LN0->getExtensionType() != ISD::NON_EXTLOAD &&
5629 LN0->getMemoryVT().getSizeInBits() < ExtVT.getSizeInBits() + ShAmt)
5632 EVT PtrType = N0.getOperand(1).getValueType();
5634 if (PtrType == MVT::Untyped || PtrType.isExtended())
5635 // It's not possible to generate a constant of extended or untyped type.
5638 // For big endian targets, we need to adjust the offset to the pointer to
5639 // load the correct bytes.
5640 if (TLI.isBigEndian()) {
5641 unsigned LVTStoreBits = LN0->getMemoryVT().getStoreSizeInBits();
5642 unsigned EVTStoreBits = ExtVT.getStoreSizeInBits();
5643 ShAmt = LVTStoreBits - EVTStoreBits - ShAmt;
5646 uint64_t PtrOff = ShAmt / 8;
5647 unsigned NewAlign = MinAlign(LN0->getAlignment(), PtrOff);
5648 SDValue NewPtr = DAG.getNode(ISD::ADD, SDLoc(LN0),
5649 PtrType, LN0->getBasePtr(),
5650 DAG.getConstant(PtrOff, PtrType));
5651 AddToWorkList(NewPtr.getNode());
5654 if (ExtType == ISD::NON_EXTLOAD)
5655 Load = DAG.getLoad(VT, SDLoc(N0), LN0->getChain(), NewPtr,
5656 LN0->getPointerInfo().getWithOffset(PtrOff),
5657 LN0->isVolatile(), LN0->isNonTemporal(),
5658 LN0->isInvariant(), NewAlign, LN0->getTBAAInfo());
5660 Load = DAG.getExtLoad(ExtType, SDLoc(N0), VT, LN0->getChain(),NewPtr,
5661 LN0->getPointerInfo().getWithOffset(PtrOff),
5662 ExtVT, LN0->isVolatile(), LN0->isNonTemporal(),
5663 NewAlign, LN0->getTBAAInfo());
5665 // Replace the old load's chain with the new load's chain.
5666 WorkListRemover DeadNodes(*this);
5667 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1));
5669 // Shift the result left, if we've swallowed a left shift.
5670 SDValue Result = Load;
5671 if (ShLeftAmt != 0) {
5672 EVT ShImmTy = getShiftAmountTy(Result.getValueType());
5673 if (!isUIntN(ShImmTy.getSizeInBits(), ShLeftAmt))
5675 // If the shift amount is as large as the result size (but, presumably,
5676 // no larger than the source) then the useful bits of the result are
5677 // zero; we can't simply return the shortened shift, because the result
5678 // of that operation is undefined.
5679 if (ShLeftAmt >= VT.getSizeInBits())
5680 Result = DAG.getConstant(0, VT);
5682 Result = DAG.getNode(ISD::SHL, SDLoc(N0), VT,
5683 Result, DAG.getConstant(ShLeftAmt, ShImmTy));
5686 // Return the new loaded value.
5690 SDValue DAGCombiner::visitSIGN_EXTEND_INREG(SDNode *N) {
5691 SDValue N0 = N->getOperand(0);
5692 SDValue N1 = N->getOperand(1);
5693 EVT VT = N->getValueType(0);
5694 EVT EVT = cast<VTSDNode>(N1)->getVT();
5695 unsigned VTBits = VT.getScalarType().getSizeInBits();
5696 unsigned EVTBits = EVT.getScalarType().getSizeInBits();
5698 // fold (sext_in_reg c1) -> c1
5699 if (isa<ConstantSDNode>(N0) || N0.getOpcode() == ISD::UNDEF)
5700 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, N0, N1);
5702 // If the input is already sign extended, just drop the extension.
5703 if (DAG.ComputeNumSignBits(N0) >= VTBits-EVTBits+1)
5706 // fold (sext_in_reg (sext_in_reg x, VT2), VT1) -> (sext_in_reg x, minVT) pt2
5707 if (N0.getOpcode() == ISD::SIGN_EXTEND_INREG &&
5708 EVT.bitsLT(cast<VTSDNode>(N0.getOperand(1))->getVT()))
5709 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
5710 N0.getOperand(0), N1);
5712 // fold (sext_in_reg (sext x)) -> (sext x)
5713 // fold (sext_in_reg (aext x)) -> (sext x)
5714 // if x is small enough.
5715 if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND) {
5716 SDValue N00 = N0.getOperand(0);
5717 if (N00.getValueType().getScalarType().getSizeInBits() <= EVTBits &&
5718 (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND, VT)))
5719 return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, N00, N1);
5722 // fold (sext_in_reg x) -> (zext_in_reg x) if the sign bit is known zero.
5723 if (DAG.MaskedValueIsZero(N0, APInt::getBitsSet(VTBits, EVTBits-1, EVTBits)))
5724 return DAG.getZeroExtendInReg(N0, SDLoc(N), EVT);
5726 // fold operands of sext_in_reg based on knowledge that the top bits are not
5728 if (SimplifyDemandedBits(SDValue(N, 0)))
5729 return SDValue(N, 0);
5731 // fold (sext_in_reg (load x)) -> (smaller sextload x)
5732 // fold (sext_in_reg (srl (load x), c)) -> (smaller sextload (x+c/evtbits))
5733 SDValue NarrowLoad = ReduceLoadWidth(N);
5734 if (NarrowLoad.getNode())
5737 // fold (sext_in_reg (srl X, 24), i8) -> (sra X, 24)
5738 // fold (sext_in_reg (srl X, 23), i8) -> (sra X, 23) iff possible.
5739 // We already fold "(sext_in_reg (srl X, 25), i8) -> srl X, 25" above.
5740 if (N0.getOpcode() == ISD::SRL) {
5741 if (ConstantSDNode *ShAmt = dyn_cast<ConstantSDNode>(N0.getOperand(1)))
5742 if (ShAmt->getZExtValue()+EVTBits <= VTBits) {
5743 // We can turn this into an SRA iff the input to the SRL is already sign
5745 unsigned InSignBits = DAG.ComputeNumSignBits(N0.getOperand(0));
5746 if (VTBits-(ShAmt->getZExtValue()+EVTBits) < InSignBits)
5747 return DAG.getNode(ISD::SRA, SDLoc(N), VT,
5748 N0.getOperand(0), N0.getOperand(1));
5752 // fold (sext_inreg (extload x)) -> (sextload x)
5753 if (ISD::isEXTLoad(N0.getNode()) &&
5754 ISD::isUNINDEXEDLoad(N0.getNode()) &&
5755 EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
5756 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
5757 TLI.isLoadExtLegal(ISD::SEXTLOAD, EVT))) {
5758 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5759 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
5761 LN0->getBasePtr(), EVT,
5762 LN0->getMemOperand());
5763 CombineTo(N, ExtLoad);
5764 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
5765 AddToWorkList(ExtLoad.getNode());
5766 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5768 // fold (sext_inreg (zextload x)) -> (sextload x) iff load has one use
5769 if (ISD::isZEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
5771 EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
5772 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
5773 TLI.isLoadExtLegal(ISD::SEXTLOAD, EVT))) {
5774 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5775 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
5777 LN0->getBasePtr(), EVT,
5778 LN0->getMemOperand());
5779 CombineTo(N, ExtLoad);
5780 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
5781 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5784 // Form (sext_inreg (bswap >> 16)) or (sext_inreg (rotl (bswap) 16))
5785 if (EVTBits <= 16 && N0.getOpcode() == ISD::OR) {
5786 SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0),
5787 N0.getOperand(1), false);
5788 if (BSwap.getNode() != 0)
5789 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
5793 // Fold a sext_inreg of a build_vector of ConstantSDNodes or undefs
5794 // into a build_vector.
5795 if (ISD::isBuildVectorOfConstantSDNodes(N0.getNode())) {
5796 SmallVector<SDValue, 8> Elts;
5797 unsigned NumElts = N0->getNumOperands();
5798 unsigned ShAmt = VTBits - EVTBits;
5800 for (unsigned i = 0; i != NumElts; ++i) {
5801 SDValue Op = N0->getOperand(i);
5802 if (Op->getOpcode() == ISD::UNDEF) {
5807 ConstantSDNode *CurrentND = cast<ConstantSDNode>(Op);
5808 const APInt &C = APInt(VTBits, CurrentND->getAPIntValue().getZExtValue());
5809 Elts.push_back(DAG.getConstant(C.shl(ShAmt).ashr(ShAmt).getZExtValue(),
5810 Op.getValueType()));
5813 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, &Elts[0], NumElts);
5819 SDValue DAGCombiner::visitTRUNCATE(SDNode *N) {
5820 SDValue N0 = N->getOperand(0);
5821 EVT VT = N->getValueType(0);
5822 bool isLE = TLI.isLittleEndian();
5825 if (N0.getValueType() == N->getValueType(0))
5827 // fold (truncate c1) -> c1
5828 if (isa<ConstantSDNode>(N0))
5829 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0);
5830 // fold (truncate (truncate x)) -> (truncate x)
5831 if (N0.getOpcode() == ISD::TRUNCATE)
5832 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0));
5833 // fold (truncate (ext x)) -> (ext x) or (truncate x) or x
5834 if (N0.getOpcode() == ISD::ZERO_EXTEND ||
5835 N0.getOpcode() == ISD::SIGN_EXTEND ||
5836 N0.getOpcode() == ISD::ANY_EXTEND) {
5837 if (N0.getOperand(0).getValueType().bitsLT(VT))
5838 // if the source is smaller than the dest, we still need an extend
5839 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
5841 if (N0.getOperand(0).getValueType().bitsGT(VT))
5842 // if the source is larger than the dest, than we just need the truncate
5843 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0));
5844 // if the source and dest are the same type, we can drop both the extend
5845 // and the truncate.
5846 return N0.getOperand(0);
5849 // Fold extract-and-trunc into a narrow extract. For example:
5850 // i64 x = EXTRACT_VECTOR_ELT(v2i64 val, i32 1)
5851 // i32 y = TRUNCATE(i64 x)
5853 // v16i8 b = BITCAST (v2i64 val)
5854 // i8 x = EXTRACT_VECTOR_ELT(v16i8 b, i32 8)
5856 // Note: We only run this optimization after type legalization (which often
5857 // creates this pattern) and before operation legalization after which
5858 // we need to be more careful about the vector instructions that we generate.
5859 if (N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
5860 LegalTypes && !LegalOperations && N0->hasOneUse() && VT != MVT::i1) {
5862 EVT VecTy = N0.getOperand(0).getValueType();
5863 EVT ExTy = N0.getValueType();
5864 EVT TrTy = N->getValueType(0);
5866 unsigned NumElem = VecTy.getVectorNumElements();
5867 unsigned SizeRatio = ExTy.getSizeInBits()/TrTy.getSizeInBits();
5869 EVT NVT = EVT::getVectorVT(*DAG.getContext(), TrTy, SizeRatio * NumElem);
5870 assert(NVT.getSizeInBits() == VecTy.getSizeInBits() && "Invalid Size");
5872 SDValue EltNo = N0->getOperand(1);
5873 if (isa<ConstantSDNode>(EltNo) && isTypeLegal(NVT)) {
5874 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
5875 EVT IndexTy = TLI.getVectorIdxTy();
5876 int Index = isLE ? (Elt*SizeRatio) : (Elt*SizeRatio + (SizeRatio-1));
5878 SDValue V = DAG.getNode(ISD::BITCAST, SDLoc(N),
5879 NVT, N0.getOperand(0));
5881 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT,
5883 DAG.getConstant(Index, IndexTy));
5887 // Fold a series of buildvector, bitcast, and truncate if possible.
5889 // (2xi32 trunc (bitcast ((4xi32)buildvector x, x, y, y) 2xi64)) to
5890 // (2xi32 (buildvector x, y)).
5891 if (Level == AfterLegalizeVectorOps && VT.isVector() &&
5892 N0.getOpcode() == ISD::BITCAST && N0.hasOneUse() &&
5893 N0.getOperand(0).getOpcode() == ISD::BUILD_VECTOR &&
5894 N0.getOperand(0).hasOneUse()) {
5896 SDValue BuildVect = N0.getOperand(0);
5897 EVT BuildVectEltTy = BuildVect.getValueType().getVectorElementType();
5898 EVT TruncVecEltTy = VT.getVectorElementType();
5900 // Check that the element types match.
5901 if (BuildVectEltTy == TruncVecEltTy) {
5902 // Now we only need to compute the offset of the truncated elements.
5903 unsigned BuildVecNumElts = BuildVect.getNumOperands();
5904 unsigned TruncVecNumElts = VT.getVectorNumElements();
5905 unsigned TruncEltOffset = BuildVecNumElts / TruncVecNumElts;
5907 assert((BuildVecNumElts % TruncVecNumElts) == 0 &&
5908 "Invalid number of elements");
5910 SmallVector<SDValue, 8> Opnds;
5911 for (unsigned i = 0, e = BuildVecNumElts; i != e; i += TruncEltOffset)
5912 Opnds.push_back(BuildVect.getOperand(i));
5914 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, &Opnds[0],
5919 // See if we can simplify the input to this truncate through knowledge that
5920 // only the low bits are being used.
5921 // For example "trunc (or (shl x, 8), y)" // -> trunc y
5922 // Currently we only perform this optimization on scalars because vectors
5923 // may have different active low bits.
5924 if (!VT.isVector()) {
5926 GetDemandedBits(N0, APInt::getLowBitsSet(N0.getValueSizeInBits(),
5927 VT.getSizeInBits()));
5928 if (Shorter.getNode())
5929 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Shorter);
5931 // fold (truncate (load x)) -> (smaller load x)
5932 // fold (truncate (srl (load x), c)) -> (smaller load (x+c/evtbits))
5933 if (!LegalTypes || TLI.isTypeDesirableForOp(N0.getOpcode(), VT)) {
5934 SDValue Reduced = ReduceLoadWidth(N);
5935 if (Reduced.getNode())
5937 // Handle the case where the load remains an extending load even
5938 // after truncation.
5939 if (N0.hasOneUse() && ISD::isUNINDEXEDLoad(N0.getNode())) {
5940 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5941 if (!LN0->isVolatile() &&
5942 LN0->getMemoryVT().getStoreSizeInBits() < VT.getSizeInBits()) {
5943 SDValue NewLoad = DAG.getExtLoad(LN0->getExtensionType(), SDLoc(LN0),
5944 VT, LN0->getChain(), LN0->getBasePtr(),
5946 LN0->getMemOperand());
5947 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLoad.getValue(1));
5952 // fold (trunc (concat ... x ...)) -> (concat ..., (trunc x), ...)),
5953 // where ... are all 'undef'.
5954 if (N0.getOpcode() == ISD::CONCAT_VECTORS && !LegalTypes) {
5955 SmallVector<EVT, 8> VTs;
5958 unsigned NumDefs = 0;
5960 for (unsigned i = 0, e = N0.getNumOperands(); i != e; ++i) {
5961 SDValue X = N0.getOperand(i);
5962 if (X.getOpcode() != ISD::UNDEF) {
5967 // Stop if more than one members are non-undef.
5970 VTs.push_back(EVT::getVectorVT(*DAG.getContext(),
5971 VT.getVectorElementType(),
5972 X.getValueType().getVectorNumElements()));
5976 return DAG.getUNDEF(VT);
5979 assert(V.getNode() && "The single defined operand is empty!");
5980 SmallVector<SDValue, 8> Opnds;
5981 for (unsigned i = 0, e = VTs.size(); i != e; ++i) {
5983 Opnds.push_back(DAG.getUNDEF(VTs[i]));
5986 SDValue NV = DAG.getNode(ISD::TRUNCATE, SDLoc(V), VTs[i], V);
5987 AddToWorkList(NV.getNode());
5988 Opnds.push_back(NV);
5990 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
5991 &Opnds[0], Opnds.size());
5995 // Simplify the operands using demanded-bits information.
5996 if (!VT.isVector() &&
5997 SimplifyDemandedBits(SDValue(N, 0)))
5998 return SDValue(N, 0);
6003 static SDNode *getBuildPairElt(SDNode *N, unsigned i) {
6004 SDValue Elt = N->getOperand(i);
6005 if (Elt.getOpcode() != ISD::MERGE_VALUES)
6006 return Elt.getNode();
6007 return Elt.getOperand(Elt.getResNo()).getNode();
6010 /// CombineConsecutiveLoads - build_pair (load, load) -> load
6011 /// if load locations are consecutive.
6012 SDValue DAGCombiner::CombineConsecutiveLoads(SDNode *N, EVT VT) {
6013 assert(N->getOpcode() == ISD::BUILD_PAIR);
6015 LoadSDNode *LD1 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 0));
6016 LoadSDNode *LD2 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 1));
6017 if (!LD1 || !LD2 || !ISD::isNON_EXTLoad(LD1) || !LD1->hasOneUse() ||
6018 LD1->getAddressSpace() != LD2->getAddressSpace())
6020 EVT LD1VT = LD1->getValueType(0);
6022 if (ISD::isNON_EXTLoad(LD2) &&
6024 // If both are volatile this would reduce the number of volatile loads.
6025 // If one is volatile it might be ok, but play conservative and bail out.
6026 !LD1->isVolatile() &&
6027 !LD2->isVolatile() &&
6028 DAG.isConsecutiveLoad(LD2, LD1, LD1VT.getSizeInBits()/8, 1)) {
6029 unsigned Align = LD1->getAlignment();
6030 unsigned NewAlign = TLI.getDataLayout()->
6031 getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
6033 if (NewAlign <= Align &&
6034 (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT)))
6035 return DAG.getLoad(VT, SDLoc(N), LD1->getChain(),
6036 LD1->getBasePtr(), LD1->getPointerInfo(),
6037 false, false, false, Align);
6043 SDValue DAGCombiner::visitBITCAST(SDNode *N) {
6044 SDValue N0 = N->getOperand(0);
6045 EVT VT = N->getValueType(0);
6047 // If the input is a BUILD_VECTOR with all constant elements, fold this now.
6048 // Only do this before legalize, since afterward the target may be depending
6049 // on the bitconvert.
6050 // First check to see if this is all constant.
6052 N0.getOpcode() == ISD::BUILD_VECTOR && N0.getNode()->hasOneUse() &&
6054 bool isSimple = cast<BuildVectorSDNode>(N0)->isConstant();
6056 EVT DestEltVT = N->getValueType(0).getVectorElementType();
6057 assert(!DestEltVT.isVector() &&
6058 "Element type of vector ValueType must not be vector!");
6060 return ConstantFoldBITCASTofBUILD_VECTOR(N0.getNode(), DestEltVT);
6063 // If the input is a constant, let getNode fold it.
6064 if (isa<ConstantSDNode>(N0) || isa<ConstantFPSDNode>(N0)) {
6065 SDValue Res = DAG.getNode(ISD::BITCAST, SDLoc(N), VT, N0);
6066 if (Res.getNode() != N) {
6067 if (!LegalOperations ||
6068 TLI.isOperationLegal(Res.getNode()->getOpcode(), VT))
6071 // Folding it resulted in an illegal node, and it's too late to
6072 // do that. Clean up the old node and forego the transformation.
6073 // Ideally this won't happen very often, because instcombine
6074 // and the earlier dagcombine runs (where illegal nodes are
6075 // permitted) should have folded most of them already.
6076 DAG.DeleteNode(Res.getNode());
6080 // (conv (conv x, t1), t2) -> (conv x, t2)
6081 if (N0.getOpcode() == ISD::BITCAST)
6082 return DAG.getNode(ISD::BITCAST, SDLoc(N), VT,
6085 // fold (conv (load x)) -> (load (conv*)x)
6086 // If the resultant load doesn't need a higher alignment than the original!
6087 if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
6088 // Do not change the width of a volatile load.
6089 !cast<LoadSDNode>(N0)->isVolatile() &&
6090 (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT)) &&
6091 TLI.isLoadBitCastBeneficial(N0.getValueType(), VT)) {
6092 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6093 unsigned Align = TLI.getDataLayout()->
6094 getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
6095 unsigned OrigAlign = LN0->getAlignment();
6097 if (Align <= OrigAlign) {
6098 SDValue Load = DAG.getLoad(VT, SDLoc(N), LN0->getChain(),
6099 LN0->getBasePtr(), LN0->getPointerInfo(),
6100 LN0->isVolatile(), LN0->isNonTemporal(),
6101 LN0->isInvariant(), OrigAlign,
6102 LN0->getTBAAInfo());
6104 CombineTo(N0.getNode(),
6105 DAG.getNode(ISD::BITCAST, SDLoc(N0),
6106 N0.getValueType(), Load),
6112 // fold (bitconvert (fneg x)) -> (xor (bitconvert x), signbit)
6113 // fold (bitconvert (fabs x)) -> (and (bitconvert x), (not signbit))
6114 // This often reduces constant pool loads.
6115 if (((N0.getOpcode() == ISD::FNEG && !TLI.isFNegFree(N0.getValueType())) ||
6116 (N0.getOpcode() == ISD::FABS && !TLI.isFAbsFree(N0.getValueType()))) &&
6117 N0.getNode()->hasOneUse() && VT.isInteger() &&
6118 !VT.isVector() && !N0.getValueType().isVector()) {
6119 SDValue NewConv = DAG.getNode(ISD::BITCAST, SDLoc(N0), VT,
6121 AddToWorkList(NewConv.getNode());
6123 APInt SignBit = APInt::getSignBit(VT.getSizeInBits());
6124 if (N0.getOpcode() == ISD::FNEG)
6125 return DAG.getNode(ISD::XOR, SDLoc(N), VT,
6126 NewConv, DAG.getConstant(SignBit, VT));
6127 assert(N0.getOpcode() == ISD::FABS);
6128 return DAG.getNode(ISD::AND, SDLoc(N), VT,
6129 NewConv, DAG.getConstant(~SignBit, VT));
6132 // fold (bitconvert (fcopysign cst, x)) ->
6133 // (or (and (bitconvert x), sign), (and cst, (not sign)))
6134 // Note that we don't handle (copysign x, cst) because this can always be
6135 // folded to an fneg or fabs.
6136 if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse() &&
6137 isa<ConstantFPSDNode>(N0.getOperand(0)) &&
6138 VT.isInteger() && !VT.isVector()) {
6139 unsigned OrigXWidth = N0.getOperand(1).getValueType().getSizeInBits();
6140 EVT IntXVT = EVT::getIntegerVT(*DAG.getContext(), OrigXWidth);
6141 if (isTypeLegal(IntXVT)) {
6142 SDValue X = DAG.getNode(ISD::BITCAST, SDLoc(N0),
6143 IntXVT, N0.getOperand(1));
6144 AddToWorkList(X.getNode());
6146 // If X has a different width than the result/lhs, sext it or truncate it.
6147 unsigned VTWidth = VT.getSizeInBits();
6148 if (OrigXWidth < VTWidth) {
6149 X = DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, X);
6150 AddToWorkList(X.getNode());
6151 } else if (OrigXWidth > VTWidth) {
6152 // To get the sign bit in the right place, we have to shift it right
6153 // before truncating.
6154 X = DAG.getNode(ISD::SRL, SDLoc(X),
6155 X.getValueType(), X,
6156 DAG.getConstant(OrigXWidth-VTWidth, X.getValueType()));
6157 AddToWorkList(X.getNode());
6158 X = DAG.getNode(ISD::TRUNCATE, SDLoc(X), VT, X);
6159 AddToWorkList(X.getNode());
6162 APInt SignBit = APInt::getSignBit(VT.getSizeInBits());
6163 X = DAG.getNode(ISD::AND, SDLoc(X), VT,
6164 X, DAG.getConstant(SignBit, VT));
6165 AddToWorkList(X.getNode());
6167 SDValue Cst = DAG.getNode(ISD::BITCAST, SDLoc(N0),
6168 VT, N0.getOperand(0));
6169 Cst = DAG.getNode(ISD::AND, SDLoc(Cst), VT,
6170 Cst, DAG.getConstant(~SignBit, VT));
6171 AddToWorkList(Cst.getNode());
6173 return DAG.getNode(ISD::OR, SDLoc(N), VT, X, Cst);
6177 // bitconvert(build_pair(ld, ld)) -> ld iff load locations are consecutive.
6178 if (N0.getOpcode() == ISD::BUILD_PAIR) {
6179 SDValue CombineLD = CombineConsecutiveLoads(N0.getNode(), VT);
6180 if (CombineLD.getNode())
6187 SDValue DAGCombiner::visitBUILD_PAIR(SDNode *N) {
6188 EVT VT = N->getValueType(0);
6189 return CombineConsecutiveLoads(N, VT);
6192 /// ConstantFoldBITCASTofBUILD_VECTOR - We know that BV is a build_vector
6193 /// node with Constant, ConstantFP or Undef operands. DstEltVT indicates the
6194 /// destination element value type.
6195 SDValue DAGCombiner::
6196 ConstantFoldBITCASTofBUILD_VECTOR(SDNode *BV, EVT DstEltVT) {
6197 EVT SrcEltVT = BV->getValueType(0).getVectorElementType();
6199 // If this is already the right type, we're done.
6200 if (SrcEltVT == DstEltVT) return SDValue(BV, 0);
6202 unsigned SrcBitSize = SrcEltVT.getSizeInBits();
6203 unsigned DstBitSize = DstEltVT.getSizeInBits();
6205 // If this is a conversion of N elements of one type to N elements of another
6206 // type, convert each element. This handles FP<->INT cases.
6207 if (SrcBitSize == DstBitSize) {
6208 EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT,
6209 BV->getValueType(0).getVectorNumElements());
6211 // Due to the FP element handling below calling this routine recursively,
6212 // we can end up with a scalar-to-vector node here.
6213 if (BV->getOpcode() == ISD::SCALAR_TO_VECTOR)
6214 return DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(BV), VT,
6215 DAG.getNode(ISD::BITCAST, SDLoc(BV),
6216 DstEltVT, BV->getOperand(0)));
6218 SmallVector<SDValue, 8> Ops;
6219 for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) {
6220 SDValue Op = BV->getOperand(i);
6221 // If the vector element type is not legal, the BUILD_VECTOR operands
6222 // are promoted and implicitly truncated. Make that explicit here.
6223 if (Op.getValueType() != SrcEltVT)
6224 Op = DAG.getNode(ISD::TRUNCATE, SDLoc(BV), SrcEltVT, Op);
6225 Ops.push_back(DAG.getNode(ISD::BITCAST, SDLoc(BV),
6227 AddToWorkList(Ops.back().getNode());
6229 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(BV), VT,
6230 &Ops[0], Ops.size());
6233 // Otherwise, we're growing or shrinking the elements. To avoid having to
6234 // handle annoying details of growing/shrinking FP values, we convert them to
6236 if (SrcEltVT.isFloatingPoint()) {
6237 // Convert the input float vector to a int vector where the elements are the
6239 assert((SrcEltVT == MVT::f32 || SrcEltVT == MVT::f64) && "Unknown FP VT!");
6240 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), SrcEltVT.getSizeInBits());
6241 BV = ConstantFoldBITCASTofBUILD_VECTOR(BV, IntVT).getNode();
6245 // Now we know the input is an integer vector. If the output is a FP type,
6246 // convert to integer first, then to FP of the right size.
6247 if (DstEltVT.isFloatingPoint()) {
6248 assert((DstEltVT == MVT::f32 || DstEltVT == MVT::f64) && "Unknown FP VT!");
6249 EVT TmpVT = EVT::getIntegerVT(*DAG.getContext(), DstEltVT.getSizeInBits());
6250 SDNode *Tmp = ConstantFoldBITCASTofBUILD_VECTOR(BV, TmpVT).getNode();
6252 // Next, convert to FP elements of the same size.
6253 return ConstantFoldBITCASTofBUILD_VECTOR(Tmp, DstEltVT);
6256 // Okay, we know the src/dst types are both integers of differing types.
6257 // Handling growing first.
6258 assert(SrcEltVT.isInteger() && DstEltVT.isInteger());
6259 if (SrcBitSize < DstBitSize) {
6260 unsigned NumInputsPerOutput = DstBitSize/SrcBitSize;
6262 SmallVector<SDValue, 8> Ops;
6263 for (unsigned i = 0, e = BV->getNumOperands(); i != e;
6264 i += NumInputsPerOutput) {
6265 bool isLE = TLI.isLittleEndian();
6266 APInt NewBits = APInt(DstBitSize, 0);
6267 bool EltIsUndef = true;
6268 for (unsigned j = 0; j != NumInputsPerOutput; ++j) {
6269 // Shift the previously computed bits over.
6270 NewBits <<= SrcBitSize;
6271 SDValue Op = BV->getOperand(i+ (isLE ? (NumInputsPerOutput-j-1) : j));
6272 if (Op.getOpcode() == ISD::UNDEF) continue;
6275 NewBits |= cast<ConstantSDNode>(Op)->getAPIntValue().
6276 zextOrTrunc(SrcBitSize).zext(DstBitSize);
6280 Ops.push_back(DAG.getUNDEF(DstEltVT));
6282 Ops.push_back(DAG.getConstant(NewBits, DstEltVT));
6285 EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT, Ops.size());
6286 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(BV), VT,
6287 &Ops[0], Ops.size());
6290 // Finally, this must be the case where we are shrinking elements: each input
6291 // turns into multiple outputs.
6292 bool isS2V = ISD::isScalarToVector(BV);
6293 unsigned NumOutputsPerInput = SrcBitSize/DstBitSize;
6294 EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT,
6295 NumOutputsPerInput*BV->getNumOperands());
6296 SmallVector<SDValue, 8> Ops;
6298 for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) {
6299 if (BV->getOperand(i).getOpcode() == ISD::UNDEF) {
6300 for (unsigned j = 0; j != NumOutputsPerInput; ++j)
6301 Ops.push_back(DAG.getUNDEF(DstEltVT));
6305 APInt OpVal = cast<ConstantSDNode>(BV->getOperand(i))->
6306 getAPIntValue().zextOrTrunc(SrcBitSize);
6308 for (unsigned j = 0; j != NumOutputsPerInput; ++j) {
6309 APInt ThisVal = OpVal.trunc(DstBitSize);
6310 Ops.push_back(DAG.getConstant(ThisVal, DstEltVT));
6311 if (isS2V && i == 0 && j == 0 && ThisVal.zext(SrcBitSize) == OpVal)
6312 // Simply turn this into a SCALAR_TO_VECTOR of the new type.
6313 return DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(BV), VT,
6315 OpVal = OpVal.lshr(DstBitSize);
6318 // For big endian targets, swap the order of the pieces of each element.
6319 if (TLI.isBigEndian())
6320 std::reverse(Ops.end()-NumOutputsPerInput, Ops.end());
6323 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(BV), VT,
6324 &Ops[0], Ops.size());
6327 SDValue DAGCombiner::visitFADD(SDNode *N) {
6328 SDValue N0 = N->getOperand(0);
6329 SDValue N1 = N->getOperand(1);
6330 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6331 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6332 EVT VT = N->getValueType(0);
6335 if (VT.isVector()) {
6336 SDValue FoldedVOp = SimplifyVBinOp(N);
6337 if (FoldedVOp.getNode()) return FoldedVOp;
6340 // fold (fadd c1, c2) -> c1 + c2
6342 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N1);
6343 // canonicalize constant to RHS
6344 if (N0CFP && !N1CFP)
6345 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N1, N0);
6346 // fold (fadd A, 0) -> A
6347 if (DAG.getTarget().Options.UnsafeFPMath && N1CFP &&
6348 N1CFP->getValueAPF().isZero())
6350 // fold (fadd A, (fneg B)) -> (fsub A, B)
6351 if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) &&
6352 isNegatibleForFree(N1, LegalOperations, TLI, &DAG.getTarget().Options) == 2)
6353 return DAG.getNode(ISD::FSUB, SDLoc(N), VT, N0,
6354 GetNegatedExpression(N1, DAG, LegalOperations));
6355 // fold (fadd (fneg A), B) -> (fsub B, A)
6356 if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) &&
6357 isNegatibleForFree(N0, LegalOperations, TLI, &DAG.getTarget().Options) == 2)
6358 return DAG.getNode(ISD::FSUB, SDLoc(N), VT, N1,
6359 GetNegatedExpression(N0, DAG, LegalOperations));
6361 // If allowed, fold (fadd (fadd x, c1), c2) -> (fadd x, (fadd c1, c2))
6362 if (DAG.getTarget().Options.UnsafeFPMath && N1CFP &&
6363 N0.getOpcode() == ISD::FADD && N0.getNode()->hasOneUse() &&
6364 isa<ConstantFPSDNode>(N0.getOperand(1)))
6365 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0.getOperand(0),
6366 DAG.getNode(ISD::FADD, SDLoc(N), VT,
6367 N0.getOperand(1), N1));
6369 // No FP constant should be created after legalization as Instruction
6370 // Selection pass has hard time in dealing with FP constant.
6372 // We don't need test this condition for transformation like following, as
6373 // the DAG being transformed implies it is legal to take FP constant as
6376 // (fadd (fmul c, x), x) -> (fmul c+1, x)
6378 bool AllowNewFpConst = (Level < AfterLegalizeDAG);
6380 // If allow, fold (fadd (fneg x), x) -> 0.0
6381 if (AllowNewFpConst && DAG.getTarget().Options.UnsafeFPMath &&
6382 N0.getOpcode() == ISD::FNEG && N0.getOperand(0) == N1)
6383 return DAG.getConstantFP(0.0, VT);
6385 // If allow, fold (fadd x, (fneg x)) -> 0.0
6386 if (AllowNewFpConst && DAG.getTarget().Options.UnsafeFPMath &&
6387 N1.getOpcode() == ISD::FNEG && N1.getOperand(0) == N0)
6388 return DAG.getConstantFP(0.0, VT);
6390 // In unsafe math mode, we can fold chains of FADD's of the same value
6391 // into multiplications. This transform is not safe in general because
6392 // we are reducing the number of rounding steps.
6393 if (DAG.getTarget().Options.UnsafeFPMath &&
6394 TLI.isOperationLegalOrCustom(ISD::FMUL, VT) &&
6396 if (N0.getOpcode() == ISD::FMUL) {
6397 ConstantFPSDNode *CFP00 = dyn_cast<ConstantFPSDNode>(N0.getOperand(0));
6398 ConstantFPSDNode *CFP01 = dyn_cast<ConstantFPSDNode>(N0.getOperand(1));
6400 // (fadd (fmul c, x), x) -> (fmul x, c+1)
6401 if (CFP00 && !CFP01 && N0.getOperand(1) == N1) {
6402 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6404 DAG.getConstantFP(1.0, VT));
6405 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6409 // (fadd (fmul x, c), x) -> (fmul x, c+1)
6410 if (CFP01 && !CFP00 && N0.getOperand(0) == N1) {
6411 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6413 DAG.getConstantFP(1.0, VT));
6414 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6418 // (fadd (fmul c, x), (fadd x, x)) -> (fmul x, c+2)
6419 if (CFP00 && !CFP01 && N1.getOpcode() == ISD::FADD &&
6420 N1.getOperand(0) == N1.getOperand(1) &&
6421 N0.getOperand(1) == N1.getOperand(0)) {
6422 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6424 DAG.getConstantFP(2.0, VT));
6425 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6426 N0.getOperand(1), NewCFP);
6429 // (fadd (fmul x, c), (fadd x, x)) -> (fmul x, c+2)
6430 if (CFP01 && !CFP00 && N1.getOpcode() == ISD::FADD &&
6431 N1.getOperand(0) == N1.getOperand(1) &&
6432 N0.getOperand(0) == N1.getOperand(0)) {
6433 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6435 DAG.getConstantFP(2.0, VT));
6436 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6437 N0.getOperand(0), NewCFP);
6441 if (N1.getOpcode() == ISD::FMUL) {
6442 ConstantFPSDNode *CFP10 = dyn_cast<ConstantFPSDNode>(N1.getOperand(0));
6443 ConstantFPSDNode *CFP11 = dyn_cast<ConstantFPSDNode>(N1.getOperand(1));
6445 // (fadd x, (fmul c, x)) -> (fmul x, c+1)
6446 if (CFP10 && !CFP11 && N1.getOperand(1) == N0) {
6447 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6449 DAG.getConstantFP(1.0, VT));
6450 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6454 // (fadd x, (fmul x, c)) -> (fmul x, c+1)
6455 if (CFP11 && !CFP10 && N1.getOperand(0) == N0) {
6456 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6458 DAG.getConstantFP(1.0, VT));
6459 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6464 // (fadd (fadd x, x), (fmul c, x)) -> (fmul x, c+2)
6465 if (CFP10 && !CFP11 && N0.getOpcode() == ISD::FADD &&
6466 N0.getOperand(0) == N0.getOperand(1) &&
6467 N1.getOperand(1) == N0.getOperand(0)) {
6468 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6470 DAG.getConstantFP(2.0, VT));
6471 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6472 N1.getOperand(1), NewCFP);
6475 // (fadd (fadd x, x), (fmul x, c)) -> (fmul x, c+2)
6476 if (CFP11 && !CFP10 && N0.getOpcode() == ISD::FADD &&
6477 N0.getOperand(0) == N0.getOperand(1) &&
6478 N1.getOperand(0) == N0.getOperand(0)) {
6479 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6481 DAG.getConstantFP(2.0, VT));
6482 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6483 N1.getOperand(0), NewCFP);
6487 if (N0.getOpcode() == ISD::FADD && AllowNewFpConst) {
6488 ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N0.getOperand(0));
6489 // (fadd (fadd x, x), x) -> (fmul x, 3.0)
6490 if (!CFP && N0.getOperand(0) == N0.getOperand(1) &&
6491 (N0.getOperand(0) == N1))
6492 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6493 N1, DAG.getConstantFP(3.0, VT));
6496 if (N1.getOpcode() == ISD::FADD && AllowNewFpConst) {
6497 ConstantFPSDNode *CFP10 = dyn_cast<ConstantFPSDNode>(N1.getOperand(0));
6498 // (fadd x, (fadd x, x)) -> (fmul x, 3.0)
6499 if (!CFP10 && N1.getOperand(0) == N1.getOperand(1) &&
6500 N1.getOperand(0) == N0)
6501 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6502 N0, DAG.getConstantFP(3.0, VT));
6505 // (fadd (fadd x, x), (fadd x, x)) -> (fmul x, 4.0)
6506 if (AllowNewFpConst &&
6507 N0.getOpcode() == ISD::FADD && N1.getOpcode() == ISD::FADD &&
6508 N0.getOperand(0) == N0.getOperand(1) &&
6509 N1.getOperand(0) == N1.getOperand(1) &&
6510 N0.getOperand(0) == N1.getOperand(0))
6511 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6513 DAG.getConstantFP(4.0, VT));
6516 // FADD -> FMA combines:
6517 if ((DAG.getTarget().Options.AllowFPOpFusion == FPOpFusion::Fast ||
6518 DAG.getTarget().Options.UnsafeFPMath) &&
6519 DAG.getTarget().getTargetLowering()->isFMAFasterThanFMulAndFAdd(VT) &&
6520 (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT))) {
6522 // fold (fadd (fmul x, y), z) -> (fma x, y, z)
6523 if (N0.getOpcode() == ISD::FMUL && N0->hasOneUse())
6524 return DAG.getNode(ISD::FMA, SDLoc(N), VT,
6525 N0.getOperand(0), N0.getOperand(1), N1);
6527 // fold (fadd x, (fmul y, z)) -> (fma y, z, x)
6528 // Note: Commutes FADD operands.
6529 if (N1.getOpcode() == ISD::FMUL && N1->hasOneUse())
6530 return DAG.getNode(ISD::FMA, SDLoc(N), VT,
6531 N1.getOperand(0), N1.getOperand(1), N0);
6537 SDValue DAGCombiner::visitFSUB(SDNode *N) {
6538 SDValue N0 = N->getOperand(0);
6539 SDValue N1 = N->getOperand(1);
6540 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6541 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6542 EVT VT = N->getValueType(0);
6546 if (VT.isVector()) {
6547 SDValue FoldedVOp = SimplifyVBinOp(N);
6548 if (FoldedVOp.getNode()) return FoldedVOp;
6551 // fold (fsub c1, c2) -> c1-c2
6553 return DAG.getNode(ISD::FSUB, SDLoc(N), VT, N0, N1);
6554 // fold (fsub A, 0) -> A
6555 if (DAG.getTarget().Options.UnsafeFPMath &&
6556 N1CFP && N1CFP->getValueAPF().isZero())
6558 // fold (fsub 0, B) -> -B
6559 if (DAG.getTarget().Options.UnsafeFPMath &&
6560 N0CFP && N0CFP->getValueAPF().isZero()) {
6561 if (isNegatibleForFree(N1, LegalOperations, TLI, &DAG.getTarget().Options))
6562 return GetNegatedExpression(N1, DAG, LegalOperations);
6563 if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
6564 return DAG.getNode(ISD::FNEG, dl, VT, N1);
6566 // fold (fsub A, (fneg B)) -> (fadd A, B)
6567 if (isNegatibleForFree(N1, LegalOperations, TLI, &DAG.getTarget().Options))
6568 return DAG.getNode(ISD::FADD, dl, VT, N0,
6569 GetNegatedExpression(N1, DAG, LegalOperations));
6571 // If 'unsafe math' is enabled, fold
6572 // (fsub x, x) -> 0.0 &
6573 // (fsub x, (fadd x, y)) -> (fneg y) &
6574 // (fsub x, (fadd y, x)) -> (fneg y)
6575 if (DAG.getTarget().Options.UnsafeFPMath) {
6577 return DAG.getConstantFP(0.0f, VT);
6579 if (N1.getOpcode() == ISD::FADD) {
6580 SDValue N10 = N1->getOperand(0);
6581 SDValue N11 = N1->getOperand(1);
6583 if (N10 == N0 && isNegatibleForFree(N11, LegalOperations, TLI,
6584 &DAG.getTarget().Options))
6585 return GetNegatedExpression(N11, DAG, LegalOperations);
6587 if (N11 == N0 && isNegatibleForFree(N10, LegalOperations, TLI,
6588 &DAG.getTarget().Options))
6589 return GetNegatedExpression(N10, DAG, LegalOperations);
6593 // FSUB -> FMA combines:
6594 if ((DAG.getTarget().Options.AllowFPOpFusion == FPOpFusion::Fast ||
6595 DAG.getTarget().Options.UnsafeFPMath) &&
6596 DAG.getTarget().getTargetLowering()->isFMAFasterThanFMulAndFAdd(VT) &&
6597 (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT))) {
6599 // fold (fsub (fmul x, y), z) -> (fma x, y, (fneg z))
6600 if (N0.getOpcode() == ISD::FMUL && N0->hasOneUse())
6601 return DAG.getNode(ISD::FMA, dl, VT,
6602 N0.getOperand(0), N0.getOperand(1),
6603 DAG.getNode(ISD::FNEG, dl, VT, N1));
6605 // fold (fsub x, (fmul y, z)) -> (fma (fneg y), z, x)
6606 // Note: Commutes FSUB operands.
6607 if (N1.getOpcode() == ISD::FMUL && N1->hasOneUse())
6608 return DAG.getNode(ISD::FMA, dl, VT,
6609 DAG.getNode(ISD::FNEG, dl, VT,
6611 N1.getOperand(1), N0);
6613 // fold (fsub (fneg (fmul, x, y)), z) -> (fma (fneg x), y, (fneg z))
6614 if (N0.getOpcode() == ISD::FNEG &&
6615 N0.getOperand(0).getOpcode() == ISD::FMUL &&
6616 N0->hasOneUse() && N0.getOperand(0).hasOneUse()) {
6617 SDValue N00 = N0.getOperand(0).getOperand(0);
6618 SDValue N01 = N0.getOperand(0).getOperand(1);
6619 return DAG.getNode(ISD::FMA, dl, VT,
6620 DAG.getNode(ISD::FNEG, dl, VT, N00), N01,
6621 DAG.getNode(ISD::FNEG, dl, VT, N1));
6628 SDValue DAGCombiner::visitFMUL(SDNode *N) {
6629 SDValue N0 = N->getOperand(0);
6630 SDValue N1 = N->getOperand(1);
6631 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6632 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6633 EVT VT = N->getValueType(0);
6634 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6637 if (VT.isVector()) {
6638 SDValue FoldedVOp = SimplifyVBinOp(N);
6639 if (FoldedVOp.getNode()) return FoldedVOp;
6642 // fold (fmul c1, c2) -> c1*c2
6644 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0, N1);
6645 // canonicalize constant to RHS
6646 if (N0CFP && !N1CFP)
6647 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N1, N0);
6648 // fold (fmul A, 0) -> 0
6649 if (DAG.getTarget().Options.UnsafeFPMath &&
6650 N1CFP && N1CFP->getValueAPF().isZero())
6652 // fold (fmul A, 0) -> 0, vector edition.
6653 if (DAG.getTarget().Options.UnsafeFPMath &&
6654 ISD::isBuildVectorAllZeros(N1.getNode()))
6656 // fold (fmul A, 1.0) -> A
6657 if (N1CFP && N1CFP->isExactlyValue(1.0))
6659 // fold (fmul X, 2.0) -> (fadd X, X)
6660 if (N1CFP && N1CFP->isExactlyValue(+2.0))
6661 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N0);
6662 // fold (fmul X, -1.0) -> (fneg X)
6663 if (N1CFP && N1CFP->isExactlyValue(-1.0))
6664 if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
6665 return DAG.getNode(ISD::FNEG, SDLoc(N), VT, N0);
6667 // fold (fmul (fneg X), (fneg Y)) -> (fmul X, Y)
6668 if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI,
6669 &DAG.getTarget().Options)) {
6670 if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI,
6671 &DAG.getTarget().Options)) {
6672 // Both can be negated for free, check to see if at least one is cheaper
6674 if (LHSNeg == 2 || RHSNeg == 2)
6675 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6676 GetNegatedExpression(N0, DAG, LegalOperations),
6677 GetNegatedExpression(N1, DAG, LegalOperations));
6681 // If allowed, fold (fmul (fmul x, c1), c2) -> (fmul x, (fmul c1, c2))
6682 if (DAG.getTarget().Options.UnsafeFPMath &&
6683 N1CFP && N0.getOpcode() == ISD::FMUL &&
6684 N0.getNode()->hasOneUse() && isa<ConstantFPSDNode>(N0.getOperand(1)))
6685 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0.getOperand(0),
6686 DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6687 N0.getOperand(1), N1));
6692 SDValue DAGCombiner::visitFMA(SDNode *N) {
6693 SDValue N0 = N->getOperand(0);
6694 SDValue N1 = N->getOperand(1);
6695 SDValue N2 = N->getOperand(2);
6696 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6697 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6698 EVT VT = N->getValueType(0);
6701 if (DAG.getTarget().Options.UnsafeFPMath) {
6702 if (N0CFP && N0CFP->isZero())
6704 if (N1CFP && N1CFP->isZero())
6707 if (N0CFP && N0CFP->isExactlyValue(1.0))
6708 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N1, N2);
6709 if (N1CFP && N1CFP->isExactlyValue(1.0))
6710 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N2);
6712 // Canonicalize (fma c, x, y) -> (fma x, c, y)
6713 if (N0CFP && !N1CFP)
6714 return DAG.getNode(ISD::FMA, SDLoc(N), VT, N1, N0, N2);
6716 // (fma x, c1, (fmul x, c2)) -> (fmul x, c1+c2)
6717 if (DAG.getTarget().Options.UnsafeFPMath && N1CFP &&
6718 N2.getOpcode() == ISD::FMUL &&
6719 N0 == N2.getOperand(0) &&
6720 N2.getOperand(1).getOpcode() == ISD::ConstantFP) {
6721 return DAG.getNode(ISD::FMUL, dl, VT, N0,
6722 DAG.getNode(ISD::FADD, dl, VT, N1, N2.getOperand(1)));
6726 // (fma (fmul x, c1), c2, y) -> (fma x, c1*c2, y)
6727 if (DAG.getTarget().Options.UnsafeFPMath &&
6728 N0.getOpcode() == ISD::FMUL && N1CFP &&
6729 N0.getOperand(1).getOpcode() == ISD::ConstantFP) {
6730 return DAG.getNode(ISD::FMA, dl, VT,
6732 DAG.getNode(ISD::FMUL, dl, VT, N1, N0.getOperand(1)),
6736 // (fma x, 1, y) -> (fadd x, y)
6737 // (fma x, -1, y) -> (fadd (fneg x), y)
6739 if (N1CFP->isExactlyValue(1.0))
6740 return DAG.getNode(ISD::FADD, dl, VT, N0, N2);
6742 if (N1CFP->isExactlyValue(-1.0) &&
6743 (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))) {
6744 SDValue RHSNeg = DAG.getNode(ISD::FNEG, dl, VT, N0);
6745 AddToWorkList(RHSNeg.getNode());
6746 return DAG.getNode(ISD::FADD, dl, VT, N2, RHSNeg);
6750 // (fma x, c, x) -> (fmul x, (c+1))
6751 if (DAG.getTarget().Options.UnsafeFPMath && N1CFP && N0 == N2)
6752 return DAG.getNode(ISD::FMUL, dl, VT, N0,
6753 DAG.getNode(ISD::FADD, dl, VT,
6754 N1, DAG.getConstantFP(1.0, VT)));
6756 // (fma x, c, (fneg x)) -> (fmul x, (c-1))
6757 if (DAG.getTarget().Options.UnsafeFPMath && N1CFP &&
6758 N2.getOpcode() == ISD::FNEG && N2.getOperand(0) == N0)
6759 return DAG.getNode(ISD::FMUL, dl, VT, N0,
6760 DAG.getNode(ISD::FADD, dl, VT,
6761 N1, DAG.getConstantFP(-1.0, VT)));
6767 SDValue DAGCombiner::visitFDIV(SDNode *N) {
6768 SDValue N0 = N->getOperand(0);
6769 SDValue N1 = N->getOperand(1);
6770 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6771 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6772 EVT VT = N->getValueType(0);
6773 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6776 if (VT.isVector()) {
6777 SDValue FoldedVOp = SimplifyVBinOp(N);
6778 if (FoldedVOp.getNode()) return FoldedVOp;
6781 // fold (fdiv c1, c2) -> c1/c2
6783 return DAG.getNode(ISD::FDIV, SDLoc(N), VT, N0, N1);
6785 // fold (fdiv X, c2) -> fmul X, 1/c2 if losing precision is acceptable.
6786 if (N1CFP && DAG.getTarget().Options.UnsafeFPMath) {
6787 // Compute the reciprocal 1.0 / c2.
6788 APFloat N1APF = N1CFP->getValueAPF();
6789 APFloat Recip(N1APF.getSemantics(), 1); // 1.0
6790 APFloat::opStatus st = Recip.divide(N1APF, APFloat::rmNearestTiesToEven);
6791 // Only do the transform if the reciprocal is a legal fp immediate that
6792 // isn't too nasty (eg NaN, denormal, ...).
6793 if ((st == APFloat::opOK || st == APFloat::opInexact) && // Not too nasty
6794 (!LegalOperations ||
6795 // FIXME: custom lowering of ConstantFP might fail (see e.g. ARM
6796 // backend)... we should handle this gracefully after Legalize.
6797 // TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT) ||
6798 TLI.isOperationLegal(llvm::ISD::ConstantFP, VT) ||
6799 TLI.isFPImmLegal(Recip, VT)))
6800 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0,
6801 DAG.getConstantFP(Recip, VT));
6804 // (fdiv (fneg X), (fneg Y)) -> (fdiv X, Y)
6805 if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI,
6806 &DAG.getTarget().Options)) {
6807 if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI,
6808 &DAG.getTarget().Options)) {
6809 // Both can be negated for free, check to see if at least one is cheaper
6811 if (LHSNeg == 2 || RHSNeg == 2)
6812 return DAG.getNode(ISD::FDIV, SDLoc(N), VT,
6813 GetNegatedExpression(N0, DAG, LegalOperations),
6814 GetNegatedExpression(N1, DAG, LegalOperations));
6821 SDValue DAGCombiner::visitFREM(SDNode *N) {
6822 SDValue N0 = N->getOperand(0);
6823 SDValue N1 = N->getOperand(1);
6824 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6825 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6826 EVT VT = N->getValueType(0);
6828 // fold (frem c1, c2) -> fmod(c1,c2)
6830 return DAG.getNode(ISD::FREM, SDLoc(N), VT, N0, N1);
6835 SDValue DAGCombiner::visitFCOPYSIGN(SDNode *N) {
6836 SDValue N0 = N->getOperand(0);
6837 SDValue N1 = N->getOperand(1);
6838 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6839 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6840 EVT VT = N->getValueType(0);
6842 if (N0CFP && N1CFP) // Constant fold
6843 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, N0, N1);
6846 const APFloat& V = N1CFP->getValueAPF();
6847 // copysign(x, c1) -> fabs(x) iff ispos(c1)
6848 // copysign(x, c1) -> fneg(fabs(x)) iff isneg(c1)
6849 if (!V.isNegative()) {
6850 if (!LegalOperations || TLI.isOperationLegal(ISD::FABS, VT))
6851 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
6853 if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
6854 return DAG.getNode(ISD::FNEG, SDLoc(N), VT,
6855 DAG.getNode(ISD::FABS, SDLoc(N0), VT, N0));
6859 // copysign(fabs(x), y) -> copysign(x, y)
6860 // copysign(fneg(x), y) -> copysign(x, y)
6861 // copysign(copysign(x,z), y) -> copysign(x, y)
6862 if (N0.getOpcode() == ISD::FABS || N0.getOpcode() == ISD::FNEG ||
6863 N0.getOpcode() == ISD::FCOPYSIGN)
6864 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
6865 N0.getOperand(0), N1);
6867 // copysign(x, abs(y)) -> abs(x)
6868 if (N1.getOpcode() == ISD::FABS)
6869 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
6871 // copysign(x, copysign(y,z)) -> copysign(x, z)
6872 if (N1.getOpcode() == ISD::FCOPYSIGN)
6873 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
6874 N0, N1.getOperand(1));
6876 // copysign(x, fp_extend(y)) -> copysign(x, y)
6877 // copysign(x, fp_round(y)) -> copysign(x, y)
6878 if (N1.getOpcode() == ISD::FP_EXTEND || N1.getOpcode() == ISD::FP_ROUND)
6879 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
6880 N0, N1.getOperand(0));
6885 SDValue DAGCombiner::visitSINT_TO_FP(SDNode *N) {
6886 SDValue N0 = N->getOperand(0);
6887 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
6888 EVT VT = N->getValueType(0);
6889 EVT OpVT = N0.getValueType();
6891 // fold (sint_to_fp c1) -> c1fp
6893 // ...but only if the target supports immediate floating-point values
6894 (!LegalOperations ||
6895 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT)))
6896 return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0);
6898 // If the input is a legal type, and SINT_TO_FP is not legal on this target,
6899 // but UINT_TO_FP is legal on this target, try to convert.
6900 if (!TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT) &&
6901 TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT)) {
6902 // If the sign bit is known to be zero, we can change this to UINT_TO_FP.
6903 if (DAG.SignBitIsZero(N0))
6904 return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0);
6907 // The next optimizations are desirable only if SELECT_CC can be lowered.
6908 // Check against MVT::Other for SELECT_CC, which is a workaround for targets
6909 // having to say they don't support SELECT_CC on every type the DAG knows
6910 // about, since there is no way to mark an opcode illegal at all value types
6911 // (See also visitSELECT)
6912 if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, MVT::Other)) {
6913 // fold (sint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc)
6914 if (N0.getOpcode() == ISD::SETCC && N0.getValueType() == MVT::i1 &&
6916 (!LegalOperations ||
6917 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
6919 { N0.getOperand(0), N0.getOperand(1),
6920 DAG.getConstantFP(-1.0, VT) , DAG.getConstantFP(0.0, VT),
6922 return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT, Ops, 5);
6925 // fold (sint_to_fp (zext (setcc x, y, cc))) ->
6926 // (select_cc x, y, 1.0, 0.0,, cc)
6927 if (N0.getOpcode() == ISD::ZERO_EXTEND &&
6928 N0.getOperand(0).getOpcode() == ISD::SETCC &&!VT.isVector() &&
6929 (!LegalOperations ||
6930 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
6932 { N0.getOperand(0).getOperand(0), N0.getOperand(0).getOperand(1),
6933 DAG.getConstantFP(1.0, VT) , DAG.getConstantFP(0.0, VT),
6934 N0.getOperand(0).getOperand(2) };
6935 return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT, Ops, 5);
6942 SDValue DAGCombiner::visitUINT_TO_FP(SDNode *N) {
6943 SDValue N0 = N->getOperand(0);
6944 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
6945 EVT VT = N->getValueType(0);
6946 EVT OpVT = N0.getValueType();
6948 // fold (uint_to_fp c1) -> c1fp
6950 // ...but only if the target supports immediate floating-point values
6951 (!LegalOperations ||
6952 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT)))
6953 return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0);
6955 // If the input is a legal type, and UINT_TO_FP is not legal on this target,
6956 // but SINT_TO_FP is legal on this target, try to convert.
6957 if (!TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT) &&
6958 TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT)) {
6959 // If the sign bit is known to be zero, we can change this to SINT_TO_FP.
6960 if (DAG.SignBitIsZero(N0))
6961 return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0);
6964 // The next optimizations are desirable only if SELECT_CC can be lowered.
6965 // Check against MVT::Other for SELECT_CC, which is a workaround for targets
6966 // having to say they don't support SELECT_CC on every type the DAG knows
6967 // about, since there is no way to mark an opcode illegal at all value types
6968 // (See also visitSELECT)
6969 if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, MVT::Other)) {
6970 // fold (uint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc)
6972 if (N0.getOpcode() == ISD::SETCC && !VT.isVector() &&
6973 (!LegalOperations ||
6974 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
6976 { N0.getOperand(0), N0.getOperand(1),
6977 DAG.getConstantFP(1.0, VT), DAG.getConstantFP(0.0, VT),
6979 return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT, Ops, 5);
6986 SDValue DAGCombiner::visitFP_TO_SINT(SDNode *N) {
6987 SDValue N0 = N->getOperand(0);
6988 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6989 EVT VT = N->getValueType(0);
6991 // fold (fp_to_sint c1fp) -> c1
6993 return DAG.getNode(ISD::FP_TO_SINT, SDLoc(N), VT, N0);
6998 SDValue DAGCombiner::visitFP_TO_UINT(SDNode *N) {
6999 SDValue N0 = N->getOperand(0);
7000 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7001 EVT VT = N->getValueType(0);
7003 // fold (fp_to_uint c1fp) -> c1
7005 return DAG.getNode(ISD::FP_TO_UINT, SDLoc(N), VT, N0);
7010 SDValue DAGCombiner::visitFP_ROUND(SDNode *N) {
7011 SDValue N0 = N->getOperand(0);
7012 SDValue N1 = N->getOperand(1);
7013 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7014 EVT VT = N->getValueType(0);
7016 // fold (fp_round c1fp) -> c1fp
7018 return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT, N0, N1);
7020 // fold (fp_round (fp_extend x)) -> x
7021 if (N0.getOpcode() == ISD::FP_EXTEND && VT == N0.getOperand(0).getValueType())
7022 return N0.getOperand(0);
7024 // fold (fp_round (fp_round x)) -> (fp_round x)
7025 if (N0.getOpcode() == ISD::FP_ROUND) {
7026 // This is a value preserving truncation if both round's are.
7027 bool IsTrunc = N->getConstantOperandVal(1) == 1 &&
7028 N0.getNode()->getConstantOperandVal(1) == 1;
7029 return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT, N0.getOperand(0),
7030 DAG.getIntPtrConstant(IsTrunc));
7033 // fold (fp_round (copysign X, Y)) -> (copysign (fp_round X), Y)
7034 if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse()) {
7035 SDValue Tmp = DAG.getNode(ISD::FP_ROUND, SDLoc(N0), VT,
7036 N0.getOperand(0), N1);
7037 AddToWorkList(Tmp.getNode());
7038 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
7039 Tmp, N0.getOperand(1));
7045 SDValue DAGCombiner::visitFP_ROUND_INREG(SDNode *N) {
7046 SDValue N0 = N->getOperand(0);
7047 EVT VT = N->getValueType(0);
7048 EVT EVT = cast<VTSDNode>(N->getOperand(1))->getVT();
7049 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7051 // fold (fp_round_inreg c1fp) -> c1fp
7052 if (N0CFP && isTypeLegal(EVT)) {
7053 SDValue Round = DAG.getConstantFP(*N0CFP->getConstantFPValue(), EVT);
7054 return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, Round);
7060 SDValue DAGCombiner::visitFP_EXTEND(SDNode *N) {
7061 SDValue N0 = N->getOperand(0);
7062 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7063 EVT VT = N->getValueType(0);
7065 // If this is fp_round(fpextend), don't fold it, allow ourselves to be folded.
7066 if (N->hasOneUse() &&
7067 N->use_begin()->getOpcode() == ISD::FP_ROUND)
7070 // fold (fp_extend c1fp) -> c1fp
7072 return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, N0);
7074 // Turn fp_extend(fp_round(X, 1)) -> x since the fp_round doesn't affect the
7076 if (N0.getOpcode() == ISD::FP_ROUND
7077 && N0.getNode()->getConstantOperandVal(1) == 1) {
7078 SDValue In = N0.getOperand(0);
7079 if (In.getValueType() == VT) return In;
7080 if (VT.bitsLT(In.getValueType()))
7081 return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT,
7082 In, N0.getOperand(1));
7083 return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, In);
7086 // fold (fpext (load x)) -> (fpext (fptrunc (extload x)))
7087 if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
7088 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
7089 TLI.isLoadExtLegal(ISD::EXTLOAD, N0.getValueType()))) {
7090 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
7091 SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT,
7093 LN0->getBasePtr(), N0.getValueType(),
7094 LN0->getMemOperand());
7095 CombineTo(N, ExtLoad);
7096 CombineTo(N0.getNode(),
7097 DAG.getNode(ISD::FP_ROUND, SDLoc(N0),
7098 N0.getValueType(), ExtLoad, DAG.getIntPtrConstant(1)),
7099 ExtLoad.getValue(1));
7100 return SDValue(N, 0); // Return N so it doesn't get rechecked!
7106 SDValue DAGCombiner::visitFNEG(SDNode *N) {
7107 SDValue N0 = N->getOperand(0);
7108 EVT VT = N->getValueType(0);
7110 if (VT.isVector()) {
7111 SDValue FoldedVOp = SimplifyVUnaryOp(N);
7112 if (FoldedVOp.getNode()) return FoldedVOp;
7115 if (isNegatibleForFree(N0, LegalOperations, DAG.getTargetLoweringInfo(),
7116 &DAG.getTarget().Options))
7117 return GetNegatedExpression(N0, DAG, LegalOperations);
7119 // Transform fneg(bitconvert(x)) -> bitconvert(x^sign) to avoid loading
7120 // constant pool values.
7121 if (!TLI.isFNegFree(VT) && N0.getOpcode() == ISD::BITCAST &&
7123 N0.getNode()->hasOneUse() &&
7124 N0.getOperand(0).getValueType().isInteger()) {
7125 SDValue Int = N0.getOperand(0);
7126 EVT IntVT = Int.getValueType();
7127 if (IntVT.isInteger() && !IntVT.isVector()) {
7128 Int = DAG.getNode(ISD::XOR, SDLoc(N0), IntVT, Int,
7129 DAG.getConstant(APInt::getSignBit(IntVT.getSizeInBits()), IntVT));
7130 AddToWorkList(Int.getNode());
7131 return DAG.getNode(ISD::BITCAST, SDLoc(N),
7136 // (fneg (fmul c, x)) -> (fmul -c, x)
7137 if (N0.getOpcode() == ISD::FMUL) {
7138 ConstantFPSDNode *CFP1 = dyn_cast<ConstantFPSDNode>(N0.getOperand(1));
7140 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
7142 DAG.getNode(ISD::FNEG, SDLoc(N), VT,
7149 SDValue DAGCombiner::visitFCEIL(SDNode *N) {
7150 SDValue N0 = N->getOperand(0);
7151 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7152 EVT VT = N->getValueType(0);
7154 // fold (fceil c1) -> fceil(c1)
7156 return DAG.getNode(ISD::FCEIL, SDLoc(N), VT, N0);
7161 SDValue DAGCombiner::visitFTRUNC(SDNode *N) {
7162 SDValue N0 = N->getOperand(0);
7163 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7164 EVT VT = N->getValueType(0);
7166 // fold (ftrunc c1) -> ftrunc(c1)
7168 return DAG.getNode(ISD::FTRUNC, SDLoc(N), VT, N0);
7173 SDValue DAGCombiner::visitFFLOOR(SDNode *N) {
7174 SDValue N0 = N->getOperand(0);
7175 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7176 EVT VT = N->getValueType(0);
7178 // fold (ffloor c1) -> ffloor(c1)
7180 return DAG.getNode(ISD::FFLOOR, SDLoc(N), VT, N0);
7185 SDValue DAGCombiner::visitFABS(SDNode *N) {
7186 SDValue N0 = N->getOperand(0);
7187 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7188 EVT VT = N->getValueType(0);
7190 if (VT.isVector()) {
7191 SDValue FoldedVOp = SimplifyVUnaryOp(N);
7192 if (FoldedVOp.getNode()) return FoldedVOp;
7195 // fold (fabs c1) -> fabs(c1)
7197 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
7198 // fold (fabs (fabs x)) -> (fabs x)
7199 if (N0.getOpcode() == ISD::FABS)
7200 return N->getOperand(0);
7201 // fold (fabs (fneg x)) -> (fabs x)
7202 // fold (fabs (fcopysign x, y)) -> (fabs x)
7203 if (N0.getOpcode() == ISD::FNEG || N0.getOpcode() == ISD::FCOPYSIGN)
7204 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0.getOperand(0));
7206 // Transform fabs(bitconvert(x)) -> bitconvert(x&~sign) to avoid loading
7207 // constant pool values.
7208 if (!TLI.isFAbsFree(VT) &&
7209 N0.getOpcode() == ISD::BITCAST && N0.getNode()->hasOneUse() &&
7210 N0.getOperand(0).getValueType().isInteger() &&
7211 !N0.getOperand(0).getValueType().isVector()) {
7212 SDValue Int = N0.getOperand(0);
7213 EVT IntVT = Int.getValueType();
7214 if (IntVT.isInteger() && !IntVT.isVector()) {
7215 Int = DAG.getNode(ISD::AND, SDLoc(N0), IntVT, Int,
7216 DAG.getConstant(~APInt::getSignBit(IntVT.getSizeInBits()), IntVT));
7217 AddToWorkList(Int.getNode());
7218 return DAG.getNode(ISD::BITCAST, SDLoc(N),
7219 N->getValueType(0), Int);
7226 SDValue DAGCombiner::visitBRCOND(SDNode *N) {
7227 SDValue Chain = N->getOperand(0);
7228 SDValue N1 = N->getOperand(1);
7229 SDValue N2 = N->getOperand(2);
7231 // If N is a constant we could fold this into a fallthrough or unconditional
7232 // branch. However that doesn't happen very often in normal code, because
7233 // Instcombine/SimplifyCFG should have handled the available opportunities.
7234 // If we did this folding here, it would be necessary to update the
7235 // MachineBasicBlock CFG, which is awkward.
7237 // fold a brcond with a setcc condition into a BR_CC node if BR_CC is legal
7239 if (N1.getOpcode() == ISD::SETCC &&
7240 TLI.isOperationLegalOrCustom(ISD::BR_CC,
7241 N1.getOperand(0).getValueType())) {
7242 return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other,
7243 Chain, N1.getOperand(2),
7244 N1.getOperand(0), N1.getOperand(1), N2);
7247 if ((N1.hasOneUse() && N1.getOpcode() == ISD::SRL) ||
7248 ((N1.getOpcode() == ISD::TRUNCATE && N1.hasOneUse()) &&
7249 (N1.getOperand(0).hasOneUse() &&
7250 N1.getOperand(0).getOpcode() == ISD::SRL))) {
7252 if (N1.getOpcode() == ISD::TRUNCATE) {
7253 // Look pass the truncate.
7254 Trunc = N1.getNode();
7255 N1 = N1.getOperand(0);
7258 // Match this pattern so that we can generate simpler code:
7261 // %b = and i32 %a, 2
7262 // %c = srl i32 %b, 1
7263 // brcond i32 %c ...
7268 // %b = and i32 %a, 2
7269 // %c = setcc eq %b, 0
7272 // This applies only when the AND constant value has one bit set and the
7273 // SRL constant is equal to the log2 of the AND constant. The back-end is
7274 // smart enough to convert the result into a TEST/JMP sequence.
7275 SDValue Op0 = N1.getOperand(0);
7276 SDValue Op1 = N1.getOperand(1);
7278 if (Op0.getOpcode() == ISD::AND &&
7279 Op1.getOpcode() == ISD::Constant) {
7280 SDValue AndOp1 = Op0.getOperand(1);
7282 if (AndOp1.getOpcode() == ISD::Constant) {
7283 const APInt &AndConst = cast<ConstantSDNode>(AndOp1)->getAPIntValue();
7285 if (AndConst.isPowerOf2() &&
7286 cast<ConstantSDNode>(Op1)->getAPIntValue()==AndConst.logBase2()) {
7288 DAG.getSetCC(SDLoc(N),
7289 getSetCCResultType(Op0.getValueType()),
7290 Op0, DAG.getConstant(0, Op0.getValueType()),
7293 SDValue NewBRCond = DAG.getNode(ISD::BRCOND, SDLoc(N),
7294 MVT::Other, Chain, SetCC, N2);
7295 // Don't add the new BRCond into the worklist or else SimplifySelectCC
7296 // will convert it back to (X & C1) >> C2.
7297 CombineTo(N, NewBRCond, false);
7298 // Truncate is dead.
7300 removeFromWorkList(Trunc);
7301 DAG.DeleteNode(Trunc);
7303 // Replace the uses of SRL with SETCC
7304 WorkListRemover DeadNodes(*this);
7305 DAG.ReplaceAllUsesOfValueWith(N1, SetCC);
7306 removeFromWorkList(N1.getNode());
7307 DAG.DeleteNode(N1.getNode());
7308 return SDValue(N, 0); // Return N so it doesn't get rechecked!
7314 // Restore N1 if the above transformation doesn't match.
7315 N1 = N->getOperand(1);
7318 // Transform br(xor(x, y)) -> br(x != y)
7319 // Transform br(xor(xor(x,y), 1)) -> br (x == y)
7320 if (N1.hasOneUse() && N1.getOpcode() == ISD::XOR) {
7321 SDNode *TheXor = N1.getNode();
7322 SDValue Op0 = TheXor->getOperand(0);
7323 SDValue Op1 = TheXor->getOperand(1);
7324 if (Op0.getOpcode() == Op1.getOpcode()) {
7325 // Avoid missing important xor optimizations.
7326 SDValue Tmp = visitXOR(TheXor);
7327 if (Tmp.getNode()) {
7328 if (Tmp.getNode() != TheXor) {
7329 DEBUG(dbgs() << "\nReplacing.8 ";
7331 dbgs() << "\nWith: ";
7332 Tmp.getNode()->dump(&DAG);
7334 WorkListRemover DeadNodes(*this);
7335 DAG.ReplaceAllUsesOfValueWith(N1, Tmp);
7336 removeFromWorkList(TheXor);
7337 DAG.DeleteNode(TheXor);
7338 return DAG.getNode(ISD::BRCOND, SDLoc(N),
7339 MVT::Other, Chain, Tmp, N2);
7342 // visitXOR has changed XOR's operands or replaced the XOR completely,
7344 return SDValue(N, 0);
7348 if (Op0.getOpcode() != ISD::SETCC && Op1.getOpcode() != ISD::SETCC) {
7350 if (ConstantSDNode *RHSCI = dyn_cast<ConstantSDNode>(Op0))
7351 if (RHSCI->getAPIntValue() == 1 && Op0.hasOneUse() &&
7352 Op0.getOpcode() == ISD::XOR) {
7353 TheXor = Op0.getNode();
7357 EVT SetCCVT = N1.getValueType();
7359 SetCCVT = getSetCCResultType(SetCCVT);
7360 SDValue SetCC = DAG.getSetCC(SDLoc(TheXor),
7363 Equal ? ISD::SETEQ : ISD::SETNE);
7364 // Replace the uses of XOR with SETCC
7365 WorkListRemover DeadNodes(*this);
7366 DAG.ReplaceAllUsesOfValueWith(N1, SetCC);
7367 removeFromWorkList(N1.getNode());
7368 DAG.DeleteNode(N1.getNode());
7369 return DAG.getNode(ISD::BRCOND, SDLoc(N),
7370 MVT::Other, Chain, SetCC, N2);
7377 // Operand List for BR_CC: Chain, CondCC, CondLHS, CondRHS, DestBB.
7379 SDValue DAGCombiner::visitBR_CC(SDNode *N) {
7380 CondCodeSDNode *CC = cast<CondCodeSDNode>(N->getOperand(1));
7381 SDValue CondLHS = N->getOperand(2), CondRHS = N->getOperand(3);
7383 // If N is a constant we could fold this into a fallthrough or unconditional
7384 // branch. However that doesn't happen very often in normal code, because
7385 // Instcombine/SimplifyCFG should have handled the available opportunities.
7386 // If we did this folding here, it would be necessary to update the
7387 // MachineBasicBlock CFG, which is awkward.
7389 // Use SimplifySetCC to simplify SETCC's.
7390 SDValue Simp = SimplifySetCC(getSetCCResultType(CondLHS.getValueType()),
7391 CondLHS, CondRHS, CC->get(), SDLoc(N),
7393 if (Simp.getNode()) AddToWorkList(Simp.getNode());
7395 // fold to a simpler setcc
7396 if (Simp.getNode() && Simp.getOpcode() == ISD::SETCC)
7397 return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other,
7398 N->getOperand(0), Simp.getOperand(2),
7399 Simp.getOperand(0), Simp.getOperand(1),
7405 /// canFoldInAddressingMode - Return true if 'Use' is a load or a store that
7406 /// uses N as its base pointer and that N may be folded in the load / store
7407 /// addressing mode.
7408 static bool canFoldInAddressingMode(SDNode *N, SDNode *Use,
7410 const TargetLowering &TLI) {
7412 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Use)) {
7413 if (LD->isIndexed() || LD->getBasePtr().getNode() != N)
7415 VT = Use->getValueType(0);
7416 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(Use)) {
7417 if (ST->isIndexed() || ST->getBasePtr().getNode() != N)
7419 VT = ST->getValue().getValueType();
7423 TargetLowering::AddrMode AM;
7424 if (N->getOpcode() == ISD::ADD) {
7425 ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1));
7428 AM.BaseOffs = Offset->getSExtValue();
7432 } else if (N->getOpcode() == ISD::SUB) {
7433 ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1));
7436 AM.BaseOffs = -Offset->getSExtValue();
7443 return TLI.isLegalAddressingMode(AM, VT.getTypeForEVT(*DAG.getContext()));
7446 /// CombineToPreIndexedLoadStore - Try turning a load / store into a
7447 /// pre-indexed load / store when the base pointer is an add or subtract
7448 /// and it has other uses besides the load / store. After the
7449 /// transformation, the new indexed load / store has effectively folded
7450 /// the add / subtract in and all of its other uses are redirected to the
7451 /// new load / store.
7452 bool DAGCombiner::CombineToPreIndexedLoadStore(SDNode *N) {
7453 if (Level < AfterLegalizeDAG)
7459 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
7460 if (LD->isIndexed())
7462 VT = LD->getMemoryVT();
7463 if (!TLI.isIndexedLoadLegal(ISD::PRE_INC, VT) &&
7464 !TLI.isIndexedLoadLegal(ISD::PRE_DEC, VT))
7466 Ptr = LD->getBasePtr();
7467 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
7468 if (ST->isIndexed())
7470 VT = ST->getMemoryVT();
7471 if (!TLI.isIndexedStoreLegal(ISD::PRE_INC, VT) &&
7472 !TLI.isIndexedStoreLegal(ISD::PRE_DEC, VT))
7474 Ptr = ST->getBasePtr();
7480 // If the pointer is not an add/sub, or if it doesn't have multiple uses, bail
7481 // out. There is no reason to make this a preinc/predec.
7482 if ((Ptr.getOpcode() != ISD::ADD && Ptr.getOpcode() != ISD::SUB) ||
7483 Ptr.getNode()->hasOneUse())
7486 // Ask the target to do addressing mode selection.
7489 ISD::MemIndexedMode AM = ISD::UNINDEXED;
7490 if (!TLI.getPreIndexedAddressParts(N, BasePtr, Offset, AM, DAG))
7493 // Backends without true r+i pre-indexed forms may need to pass a
7494 // constant base with a variable offset so that constant coercion
7495 // will work with the patterns in canonical form.
7496 bool Swapped = false;
7497 if (isa<ConstantSDNode>(BasePtr)) {
7498 std::swap(BasePtr, Offset);
7502 // Don't create a indexed load / store with zero offset.
7503 if (isa<ConstantSDNode>(Offset) &&
7504 cast<ConstantSDNode>(Offset)->isNullValue())
7507 // Try turning it into a pre-indexed load / store except when:
7508 // 1) The new base ptr is a frame index.
7509 // 2) If N is a store and the new base ptr is either the same as or is a
7510 // predecessor of the value being stored.
7511 // 3) Another use of old base ptr is a predecessor of N. If ptr is folded
7512 // that would create a cycle.
7513 // 4) All uses are load / store ops that use it as old base ptr.
7515 // Check #1. Preinc'ing a frame index would require copying the stack pointer
7516 // (plus the implicit offset) to a register to preinc anyway.
7517 if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr))
7522 SDValue Val = cast<StoreSDNode>(N)->getValue();
7523 if (Val == BasePtr || BasePtr.getNode()->isPredecessorOf(Val.getNode()))
7527 // If the offset is a constant, there may be other adds of constants that
7528 // can be folded with this one. We should do this to avoid having to keep
7529 // a copy of the original base pointer.
7530 SmallVector<SDNode *, 16> OtherUses;
7531 if (isa<ConstantSDNode>(Offset))
7532 for (SDNode::use_iterator I = BasePtr.getNode()->use_begin(),
7533 E = BasePtr.getNode()->use_end(); I != E; ++I) {
7535 if (Use == Ptr.getNode())
7538 if (Use->isPredecessorOf(N))
7541 if (Use->getOpcode() != ISD::ADD && Use->getOpcode() != ISD::SUB) {
7546 SDValue Op0 = Use->getOperand(0), Op1 = Use->getOperand(1);
7547 if (Op1.getNode() == BasePtr.getNode())
7548 std::swap(Op0, Op1);
7549 assert(Op0.getNode() == BasePtr.getNode() &&
7550 "Use of ADD/SUB but not an operand");
7552 if (!isa<ConstantSDNode>(Op1)) {
7557 // FIXME: In some cases, we can be smarter about this.
7558 if (Op1.getValueType() != Offset.getValueType()) {
7563 OtherUses.push_back(Use);
7567 std::swap(BasePtr, Offset);
7569 // Now check for #3 and #4.
7570 bool RealUse = false;
7572 // Caches for hasPredecessorHelper
7573 SmallPtrSet<const SDNode *, 32> Visited;
7574 SmallVector<const SDNode *, 16> Worklist;
7576 for (SDNode::use_iterator I = Ptr.getNode()->use_begin(),
7577 E = Ptr.getNode()->use_end(); I != E; ++I) {
7581 if (N->hasPredecessorHelper(Use, Visited, Worklist))
7584 // If Ptr may be folded in addressing mode of other use, then it's
7585 // not profitable to do this transformation.
7586 if (!canFoldInAddressingMode(Ptr.getNode(), Use, DAG, TLI))
7595 Result = DAG.getIndexedLoad(SDValue(N,0), SDLoc(N),
7596 BasePtr, Offset, AM);
7598 Result = DAG.getIndexedStore(SDValue(N,0), SDLoc(N),
7599 BasePtr, Offset, AM);
7602 DEBUG(dbgs() << "\nReplacing.4 ";
7604 dbgs() << "\nWith: ";
7605 Result.getNode()->dump(&DAG);
7607 WorkListRemover DeadNodes(*this);
7609 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0));
7610 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2));
7612 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1));
7615 // Finally, since the node is now dead, remove it from the graph.
7619 std::swap(BasePtr, Offset);
7621 // Replace other uses of BasePtr that can be updated to use Ptr
7622 for (unsigned i = 0, e = OtherUses.size(); i != e; ++i) {
7623 unsigned OffsetIdx = 1;
7624 if (OtherUses[i]->getOperand(OffsetIdx).getNode() == BasePtr.getNode())
7626 assert(OtherUses[i]->getOperand(!OffsetIdx).getNode() ==
7627 BasePtr.getNode() && "Expected BasePtr operand");
7629 // We need to replace ptr0 in the following expression:
7630 // x0 * offset0 + y0 * ptr0 = t0
7632 // x1 * offset1 + y1 * ptr0 = t1 (the indexed load/store)
7634 // where x0, x1, y0 and y1 in {-1, 1} are given by the types of the
7635 // indexed load/store and the expresion that needs to be re-written.
7637 // Therefore, we have:
7638 // t0 = (x0 * offset0 - x1 * y0 * y1 *offset1) + (y0 * y1) * t1
7640 ConstantSDNode *CN =
7641 cast<ConstantSDNode>(OtherUses[i]->getOperand(OffsetIdx));
7643 APInt Offset0 = CN->getAPIntValue();
7644 APInt Offset1 = cast<ConstantSDNode>(Offset)->getAPIntValue();
7646 X0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 1) ? -1 : 1;
7647 Y0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 0) ? -1 : 1;
7648 X1 = (AM == ISD::PRE_DEC && !Swapped) ? -1 : 1;
7649 Y1 = (AM == ISD::PRE_DEC && Swapped) ? -1 : 1;
7651 unsigned Opcode = (Y0 * Y1 < 0) ? ISD::SUB : ISD::ADD;
7653 APInt CNV = Offset0;
7654 if (X0 < 0) CNV = -CNV;
7655 if (X1 * Y0 * Y1 < 0) CNV = CNV + Offset1;
7656 else CNV = CNV - Offset1;
7658 // We can now generate the new expression.
7659 SDValue NewOp1 = DAG.getConstant(CNV, CN->getValueType(0));
7660 SDValue NewOp2 = Result.getValue(isLoad ? 1 : 0);
7662 SDValue NewUse = DAG.getNode(Opcode,
7663 SDLoc(OtherUses[i]),
7664 OtherUses[i]->getValueType(0), NewOp1, NewOp2);
7665 DAG.ReplaceAllUsesOfValueWith(SDValue(OtherUses[i], 0), NewUse);
7666 removeFromWorkList(OtherUses[i]);
7667 DAG.DeleteNode(OtherUses[i]);
7670 // Replace the uses of Ptr with uses of the updated base value.
7671 DAG.ReplaceAllUsesOfValueWith(Ptr, Result.getValue(isLoad ? 1 : 0));
7672 removeFromWorkList(Ptr.getNode());
7673 DAG.DeleteNode(Ptr.getNode());
7678 /// CombineToPostIndexedLoadStore - Try to combine a load / store with a
7679 /// add / sub of the base pointer node into a post-indexed load / store.
7680 /// The transformation folded the add / subtract into the new indexed
7681 /// load / store effectively and all of its uses are redirected to the
7682 /// new load / store.
7683 bool DAGCombiner::CombineToPostIndexedLoadStore(SDNode *N) {
7684 if (Level < AfterLegalizeDAG)
7690 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
7691 if (LD->isIndexed())
7693 VT = LD->getMemoryVT();
7694 if (!TLI.isIndexedLoadLegal(ISD::POST_INC, VT) &&
7695 !TLI.isIndexedLoadLegal(ISD::POST_DEC, VT))
7697 Ptr = LD->getBasePtr();
7698 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
7699 if (ST->isIndexed())
7701 VT = ST->getMemoryVT();
7702 if (!TLI.isIndexedStoreLegal(ISD::POST_INC, VT) &&
7703 !TLI.isIndexedStoreLegal(ISD::POST_DEC, VT))
7705 Ptr = ST->getBasePtr();
7711 if (Ptr.getNode()->hasOneUse())
7714 for (SDNode::use_iterator I = Ptr.getNode()->use_begin(),
7715 E = Ptr.getNode()->use_end(); I != E; ++I) {
7718 (Op->getOpcode() != ISD::ADD && Op->getOpcode() != ISD::SUB))
7723 ISD::MemIndexedMode AM = ISD::UNINDEXED;
7724 if (TLI.getPostIndexedAddressParts(N, Op, BasePtr, Offset, AM, DAG)) {
7725 // Don't create a indexed load / store with zero offset.
7726 if (isa<ConstantSDNode>(Offset) &&
7727 cast<ConstantSDNode>(Offset)->isNullValue())
7730 // Try turning it into a post-indexed load / store except when
7731 // 1) All uses are load / store ops that use it as base ptr (and
7732 // it may be folded as addressing mmode).
7733 // 2) Op must be independent of N, i.e. Op is neither a predecessor
7734 // nor a successor of N. Otherwise, if Op is folded that would
7737 if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr))
7741 bool TryNext = false;
7742 for (SDNode::use_iterator II = BasePtr.getNode()->use_begin(),
7743 EE = BasePtr.getNode()->use_end(); II != EE; ++II) {
7745 if (Use == Ptr.getNode())
7748 // If all the uses are load / store addresses, then don't do the
7750 if (Use->getOpcode() == ISD::ADD || Use->getOpcode() == ISD::SUB){
7751 bool RealUse = false;
7752 for (SDNode::use_iterator III = Use->use_begin(),
7753 EEE = Use->use_end(); III != EEE; ++III) {
7754 SDNode *UseUse = *III;
7755 if (!canFoldInAddressingMode(Use, UseUse, DAG, TLI))
7770 if (!Op->isPredecessorOf(N) && !N->isPredecessorOf(Op)) {
7771 SDValue Result = isLoad
7772 ? DAG.getIndexedLoad(SDValue(N,0), SDLoc(N),
7773 BasePtr, Offset, AM)
7774 : DAG.getIndexedStore(SDValue(N,0), SDLoc(N),
7775 BasePtr, Offset, AM);
7778 DEBUG(dbgs() << "\nReplacing.5 ";
7780 dbgs() << "\nWith: ";
7781 Result.getNode()->dump(&DAG);
7783 WorkListRemover DeadNodes(*this);
7785 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0));
7786 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2));
7788 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1));
7791 // Finally, since the node is now dead, remove it from the graph.
7794 // Replace the uses of Use with uses of the updated base value.
7795 DAG.ReplaceAllUsesOfValueWith(SDValue(Op, 0),
7796 Result.getValue(isLoad ? 1 : 0));
7797 removeFromWorkList(Op);
7807 SDValue DAGCombiner::visitLOAD(SDNode *N) {
7808 LoadSDNode *LD = cast<LoadSDNode>(N);
7809 SDValue Chain = LD->getChain();
7810 SDValue Ptr = LD->getBasePtr();
7812 // If load is not volatile and there are no uses of the loaded value (and
7813 // the updated indexed value in case of indexed loads), change uses of the
7814 // chain value into uses of the chain input (i.e. delete the dead load).
7815 if (!LD->isVolatile()) {
7816 if (N->getValueType(1) == MVT::Other) {
7818 if (!N->hasAnyUseOfValue(0)) {
7819 // It's not safe to use the two value CombineTo variant here. e.g.
7820 // v1, chain2 = load chain1, loc
7821 // v2, chain3 = load chain2, loc
7823 // Now we replace use of chain2 with chain1. This makes the second load
7824 // isomorphic to the one we are deleting, and thus makes this load live.
7825 DEBUG(dbgs() << "\nReplacing.6 ";
7827 dbgs() << "\nWith chain: ";
7828 Chain.getNode()->dump(&DAG);
7830 WorkListRemover DeadNodes(*this);
7831 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain);
7833 if (N->use_empty()) {
7834 removeFromWorkList(N);
7838 return SDValue(N, 0); // Return N so it doesn't get rechecked!
7842 assert(N->getValueType(2) == MVT::Other && "Malformed indexed loads?");
7843 if (!N->hasAnyUseOfValue(0) && !N->hasAnyUseOfValue(1)) {
7844 SDValue Undef = DAG.getUNDEF(N->getValueType(0));
7845 DEBUG(dbgs() << "\nReplacing.7 ";
7847 dbgs() << "\nWith: ";
7848 Undef.getNode()->dump(&DAG);
7849 dbgs() << " and 2 other values\n");
7850 WorkListRemover DeadNodes(*this);
7851 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Undef);
7852 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1),
7853 DAG.getUNDEF(N->getValueType(1)));
7854 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 2), Chain);
7855 removeFromWorkList(N);
7857 return SDValue(N, 0); // Return N so it doesn't get rechecked!
7862 // If this load is directly stored, replace the load value with the stored
7864 // TODO: Handle store large -> read small portion.
7865 // TODO: Handle TRUNCSTORE/LOADEXT
7866 if (ISD::isNormalLoad(N) && !LD->isVolatile()) {
7867 if (ISD::isNON_TRUNCStore(Chain.getNode())) {
7868 StoreSDNode *PrevST = cast<StoreSDNode>(Chain);
7869 if (PrevST->getBasePtr() == Ptr &&
7870 PrevST->getValue().getValueType() == N->getValueType(0))
7871 return CombineTo(N, Chain.getOperand(1), Chain);
7875 // Try to infer better alignment information than the load already has.
7876 if (OptLevel != CodeGenOpt::None && LD->isUnindexed()) {
7877 if (unsigned Align = DAG.InferPtrAlignment(Ptr)) {
7878 if (Align > LD->getMemOperand()->getBaseAlignment()) {
7880 DAG.getExtLoad(LD->getExtensionType(), SDLoc(N),
7881 LD->getValueType(0),
7882 Chain, Ptr, LD->getPointerInfo(),
7884 LD->isVolatile(), LD->isNonTemporal(), Align,
7886 return CombineTo(N, NewLoad, SDValue(NewLoad.getNode(), 1), true);
7891 bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA :
7892 TLI.getTargetMachine().getSubtarget<TargetSubtargetInfo>().useAA();
7894 if (CombinerAAOnlyFunc.getNumOccurrences() &&
7895 CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
7898 if (UseAA && LD->isUnindexed()) {
7899 // Walk up chain skipping non-aliasing memory nodes.
7900 SDValue BetterChain = FindBetterChain(N, Chain);
7902 // If there is a better chain.
7903 if (Chain != BetterChain) {
7906 // Replace the chain to void dependency.
7907 if (LD->getExtensionType() == ISD::NON_EXTLOAD) {
7908 ReplLoad = DAG.getLoad(N->getValueType(0), SDLoc(LD),
7909 BetterChain, Ptr, LD->getMemOperand());
7911 ReplLoad = DAG.getExtLoad(LD->getExtensionType(), SDLoc(LD),
7912 LD->getValueType(0),
7913 BetterChain, Ptr, LD->getMemoryVT(),
7914 LD->getMemOperand());
7917 // Create token factor to keep old chain connected.
7918 SDValue Token = DAG.getNode(ISD::TokenFactor, SDLoc(N),
7919 MVT::Other, Chain, ReplLoad.getValue(1));
7921 // Make sure the new and old chains are cleaned up.
7922 AddToWorkList(Token.getNode());
7924 // Replace uses with load result and token factor. Don't add users
7926 return CombineTo(N, ReplLoad.getValue(0), Token, false);
7930 // Try transforming N to an indexed load.
7931 if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
7932 return SDValue(N, 0);
7934 // Try to slice up N to more direct loads if the slices are mapped to
7935 // different register banks or pairing can take place.
7937 return SDValue(N, 0);
7943 /// \brief Helper structure used to slice a load in smaller loads.
7944 /// Basically a slice is obtained from the following sequence:
7945 /// Origin = load Ty1, Base
7946 /// Shift = srl Ty1 Origin, CstTy Amount
7947 /// Inst = trunc Shift to Ty2
7949 /// Then, it will be rewriten into:
7950 /// Slice = load SliceTy, Base + SliceOffset
7951 /// [Inst = zext Slice to Ty2], only if SliceTy <> Ty2
7953 /// SliceTy is deduced from the number of bits that are actually used to
7955 struct LoadedSlice {
7956 /// \brief Helper structure used to compute the cost of a slice.
7958 /// Are we optimizing for code size.
7963 unsigned CrossRegisterBanksCopies;
7967 Cost(bool ForCodeSize = false)
7968 : ForCodeSize(ForCodeSize), Loads(0), Truncates(0),
7969 CrossRegisterBanksCopies(0), ZExts(0), Shift(0) {}
7971 /// \brief Get the cost of one isolated slice.
7972 Cost(const LoadedSlice &LS, bool ForCodeSize = false)
7973 : ForCodeSize(ForCodeSize), Loads(1), Truncates(0),
7974 CrossRegisterBanksCopies(0), ZExts(0), Shift(0) {
7975 EVT TruncType = LS.Inst->getValueType(0);
7976 EVT LoadedType = LS.getLoadedType();
7977 if (TruncType != LoadedType &&
7978 !LS.DAG->getTargetLoweringInfo().isZExtFree(LoadedType, TruncType))
7982 /// \brief Account for slicing gain in the current cost.
7983 /// Slicing provide a few gains like removing a shift or a
7984 /// truncate. This method allows to grow the cost of the original
7985 /// load with the gain from this slice.
7986 void addSliceGain(const LoadedSlice &LS) {
7987 // Each slice saves a truncate.
7988 const TargetLowering &TLI = LS.DAG->getTargetLoweringInfo();
7989 if (!TLI.isTruncateFree(LS.Inst->getValueType(0),
7990 LS.Inst->getOperand(0).getValueType()))
7992 // If there is a shift amount, this slice gets rid of it.
7995 // If this slice can merge a cross register bank copy, account for it.
7996 if (LS.canMergeExpensiveCrossRegisterBankCopy())
7997 ++CrossRegisterBanksCopies;
8000 Cost &operator+=(const Cost &RHS) {
8002 Truncates += RHS.Truncates;
8003 CrossRegisterBanksCopies += RHS.CrossRegisterBanksCopies;
8009 bool operator==(const Cost &RHS) const {
8010 return Loads == RHS.Loads && Truncates == RHS.Truncates &&
8011 CrossRegisterBanksCopies == RHS.CrossRegisterBanksCopies &&
8012 ZExts == RHS.ZExts && Shift == RHS.Shift;
8015 bool operator!=(const Cost &RHS) const { return !(*this == RHS); }
8017 bool operator<(const Cost &RHS) const {
8018 // Assume cross register banks copies are as expensive as loads.
8019 // FIXME: Do we want some more target hooks?
8020 unsigned ExpensiveOpsLHS = Loads + CrossRegisterBanksCopies;
8021 unsigned ExpensiveOpsRHS = RHS.Loads + RHS.CrossRegisterBanksCopies;
8022 // Unless we are optimizing for code size, consider the
8023 // expensive operation first.
8024 if (!ForCodeSize && ExpensiveOpsLHS != ExpensiveOpsRHS)
8025 return ExpensiveOpsLHS < ExpensiveOpsRHS;
8026 return (Truncates + ZExts + Shift + ExpensiveOpsLHS) <
8027 (RHS.Truncates + RHS.ZExts + RHS.Shift + ExpensiveOpsRHS);
8030 bool operator>(const Cost &RHS) const { return RHS < *this; }
8032 bool operator<=(const Cost &RHS) const { return !(RHS < *this); }
8034 bool operator>=(const Cost &RHS) const { return !(*this < RHS); }
8036 // The last instruction that represent the slice. This should be a
8037 // truncate instruction.
8039 // The original load instruction.
8041 // The right shift amount in bits from the original load.
8043 // The DAG from which Origin came from.
8044 // This is used to get some contextual information about legal types, etc.
8047 LoadedSlice(SDNode *Inst = NULL, LoadSDNode *Origin = NULL,
8048 unsigned Shift = 0, SelectionDAG *DAG = NULL)
8049 : Inst(Inst), Origin(Origin), Shift(Shift), DAG(DAG) {}
8051 LoadedSlice(const LoadedSlice &LS)
8052 : Inst(LS.Inst), Origin(LS.Origin), Shift(LS.Shift), DAG(LS.DAG) {}
8054 /// \brief Get the bits used in a chunk of bits \p BitWidth large.
8055 /// \return Result is \p BitWidth and has used bits set to 1 and
8056 /// not used bits set to 0.
8057 APInt getUsedBits() const {
8058 // Reproduce the trunc(lshr) sequence:
8059 // - Start from the truncated value.
8060 // - Zero extend to the desired bit width.
8062 assert(Origin && "No original load to compare against.");
8063 unsigned BitWidth = Origin->getValueSizeInBits(0);
8064 assert(Inst && "This slice is not bound to an instruction");
8065 assert(Inst->getValueSizeInBits(0) <= BitWidth &&
8066 "Extracted slice is bigger than the whole type!");
8067 APInt UsedBits(Inst->getValueSizeInBits(0), 0);
8068 UsedBits.setAllBits();
8069 UsedBits = UsedBits.zext(BitWidth);
8074 /// \brief Get the size of the slice to be loaded in bytes.
8075 unsigned getLoadedSize() const {
8076 unsigned SliceSize = getUsedBits().countPopulation();
8077 assert(!(SliceSize & 0x7) && "Size is not a multiple of a byte.");
8078 return SliceSize / 8;
8081 /// \brief Get the type that will be loaded for this slice.
8082 /// Note: This may not be the final type for the slice.
8083 EVT getLoadedType() const {
8084 assert(DAG && "Missing context");
8085 LLVMContext &Ctxt = *DAG->getContext();
8086 return EVT::getIntegerVT(Ctxt, getLoadedSize() * 8);
8089 /// \brief Get the alignment of the load used for this slice.
8090 unsigned getAlignment() const {
8091 unsigned Alignment = Origin->getAlignment();
8092 unsigned Offset = getOffsetFromBase();
8094 Alignment = MinAlign(Alignment, Alignment + Offset);
8098 /// \brief Check if this slice can be rewritten with legal operations.
8099 bool isLegal() const {
8100 // An invalid slice is not legal.
8101 if (!Origin || !Inst || !DAG)
8104 // Offsets are for indexed load only, we do not handle that.
8105 if (Origin->getOffset().getOpcode() != ISD::UNDEF)
8108 const TargetLowering &TLI = DAG->getTargetLoweringInfo();
8110 // Check that the type is legal.
8111 EVT SliceType = getLoadedType();
8112 if (!TLI.isTypeLegal(SliceType))
8115 // Check that the load is legal for this type.
8116 if (!TLI.isOperationLegal(ISD::LOAD, SliceType))
8119 // Check that the offset can be computed.
8120 // 1. Check its type.
8121 EVT PtrType = Origin->getBasePtr().getValueType();
8122 if (PtrType == MVT::Untyped || PtrType.isExtended())
8125 // 2. Check that it fits in the immediate.
8126 if (!TLI.isLegalAddImmediate(getOffsetFromBase()))
8129 // 3. Check that the computation is legal.
8130 if (!TLI.isOperationLegal(ISD::ADD, PtrType))
8133 // Check that the zext is legal if it needs one.
8134 EVT TruncateType = Inst->getValueType(0);
8135 if (TruncateType != SliceType &&
8136 !TLI.isOperationLegal(ISD::ZERO_EXTEND, TruncateType))
8142 /// \brief Get the offset in bytes of this slice in the original chunk of
8144 /// \pre DAG != NULL.
8145 uint64_t getOffsetFromBase() const {
8146 assert(DAG && "Missing context.");
8148 DAG->getTargetLoweringInfo().getDataLayout()->isBigEndian();
8149 assert(!(Shift & 0x7) && "Shifts not aligned on Bytes are not supported.");
8150 uint64_t Offset = Shift / 8;
8151 unsigned TySizeInBytes = Origin->getValueSizeInBits(0) / 8;
8152 assert(!(Origin->getValueSizeInBits(0) & 0x7) &&
8153 "The size of the original loaded type is not a multiple of a"
8155 // If Offset is bigger than TySizeInBytes, it means we are loading all
8156 // zeros. This should have been optimized before in the process.
8157 assert(TySizeInBytes > Offset &&
8158 "Invalid shift amount for given loaded size");
8160 Offset = TySizeInBytes - Offset - getLoadedSize();
8164 /// \brief Generate the sequence of instructions to load the slice
8165 /// represented by this object and redirect the uses of this slice to
8166 /// this new sequence of instructions.
8167 /// \pre this->Inst && this->Origin are valid Instructions and this
8168 /// object passed the legal check: LoadedSlice::isLegal returned true.
8169 /// \return The last instruction of the sequence used to load the slice.
8170 SDValue loadSlice() const {
8171 assert(Inst && Origin && "Unable to replace a non-existing slice.");
8172 const SDValue &OldBaseAddr = Origin->getBasePtr();
8173 SDValue BaseAddr = OldBaseAddr;
8174 // Get the offset in that chunk of bytes w.r.t. the endianess.
8175 int64_t Offset = static_cast<int64_t>(getOffsetFromBase());
8176 assert(Offset >= 0 && "Offset too big to fit in int64_t!");
8178 // BaseAddr = BaseAddr + Offset.
8179 EVT ArithType = BaseAddr.getValueType();
8180 BaseAddr = DAG->getNode(ISD::ADD, SDLoc(Origin), ArithType, BaseAddr,
8181 DAG->getConstant(Offset, ArithType));
8184 // Create the type of the loaded slice according to its size.
8185 EVT SliceType = getLoadedType();
8187 // Create the load for the slice.
8188 SDValue LastInst = DAG->getLoad(
8189 SliceType, SDLoc(Origin), Origin->getChain(), BaseAddr,
8190 Origin->getPointerInfo().getWithOffset(Offset), Origin->isVolatile(),
8191 Origin->isNonTemporal(), Origin->isInvariant(), getAlignment());
8192 // If the final type is not the same as the loaded type, this means that
8193 // we have to pad with zero. Create a zero extend for that.
8194 EVT FinalType = Inst->getValueType(0);
8195 if (SliceType != FinalType)
8197 DAG->getNode(ISD::ZERO_EXTEND, SDLoc(LastInst), FinalType, LastInst);
8201 /// \brief Check if this slice can be merged with an expensive cross register
8202 /// bank copy. E.g.,
8204 /// f = bitcast i32 i to float
8205 bool canMergeExpensiveCrossRegisterBankCopy() const {
8206 if (!Inst || !Inst->hasOneUse())
8208 SDNode *Use = *Inst->use_begin();
8209 if (Use->getOpcode() != ISD::BITCAST)
8211 assert(DAG && "Missing context");
8212 const TargetLowering &TLI = DAG->getTargetLoweringInfo();
8213 EVT ResVT = Use->getValueType(0);
8214 const TargetRegisterClass *ResRC = TLI.getRegClassFor(ResVT.getSimpleVT());
8215 const TargetRegisterClass *ArgRC =
8216 TLI.getRegClassFor(Use->getOperand(0).getValueType().getSimpleVT());
8217 if (ArgRC == ResRC || !TLI.isOperationLegal(ISD::LOAD, ResVT))
8220 // At this point, we know that we perform a cross-register-bank copy.
8221 // Check if it is expensive.
8222 const TargetRegisterInfo *TRI = TLI.getTargetMachine().getRegisterInfo();
8223 // Assume bitcasts are cheap, unless both register classes do not
8224 // explicitly share a common sub class.
8225 if (!TRI || TRI->getCommonSubClass(ArgRC, ResRC))
8228 // Check if it will be merged with the load.
8229 // 1. Check the alignment constraint.
8230 unsigned RequiredAlignment = TLI.getDataLayout()->getABITypeAlignment(
8231 ResVT.getTypeForEVT(*DAG->getContext()));
8233 if (RequiredAlignment > getAlignment())
8236 // 2. Check that the load is a legal operation for that type.
8237 if (!TLI.isOperationLegal(ISD::LOAD, ResVT))
8240 // 3. Check that we do not have a zext in the way.
8241 if (Inst->getValueType(0) != getLoadedType())
8249 /// \brief Check that all bits set in \p UsedBits form a dense region, i.e.,
8250 /// \p UsedBits looks like 0..0 1..1 0..0.
8251 static bool areUsedBitsDense(const APInt &UsedBits) {
8252 // If all the bits are one, this is dense!
8253 if (UsedBits.isAllOnesValue())
8256 // Get rid of the unused bits on the right.
8257 APInt NarrowedUsedBits = UsedBits.lshr(UsedBits.countTrailingZeros());
8258 // Get rid of the unused bits on the left.
8259 if (NarrowedUsedBits.countLeadingZeros())
8260 NarrowedUsedBits = NarrowedUsedBits.trunc(NarrowedUsedBits.getActiveBits());
8261 // Check that the chunk of bits is completely used.
8262 return NarrowedUsedBits.isAllOnesValue();
8265 /// \brief Check whether or not \p First and \p Second are next to each other
8266 /// in memory. This means that there is no hole between the bits loaded
8267 /// by \p First and the bits loaded by \p Second.
8268 static bool areSlicesNextToEachOther(const LoadedSlice &First,
8269 const LoadedSlice &Second) {
8270 assert(First.Origin == Second.Origin && First.Origin &&
8271 "Unable to match different memory origins.");
8272 APInt UsedBits = First.getUsedBits();
8273 assert((UsedBits & Second.getUsedBits()) == 0 &&
8274 "Slices are not supposed to overlap.");
8275 UsedBits |= Second.getUsedBits();
8276 return areUsedBitsDense(UsedBits);
8279 /// \brief Adjust the \p GlobalLSCost according to the target
8280 /// paring capabilities and the layout of the slices.
8281 /// \pre \p GlobalLSCost should account for at least as many loads as
8282 /// there is in the slices in \p LoadedSlices.
8283 static void adjustCostForPairing(SmallVectorImpl<LoadedSlice> &LoadedSlices,
8284 LoadedSlice::Cost &GlobalLSCost) {
8285 unsigned NumberOfSlices = LoadedSlices.size();
8286 // If there is less than 2 elements, no pairing is possible.
8287 if (NumberOfSlices < 2)
8290 // Sort the slices so that elements that are likely to be next to each
8291 // other in memory are next to each other in the list.
8292 std::sort(LoadedSlices.begin(), LoadedSlices.end(),
8293 [](const LoadedSlice &LHS, const LoadedSlice &RHS) {
8294 assert(LHS.Origin == RHS.Origin && "Different bases not implemented.");
8295 return LHS.getOffsetFromBase() < RHS.getOffsetFromBase();
8297 const TargetLowering &TLI = LoadedSlices[0].DAG->getTargetLoweringInfo();
8298 // First (resp. Second) is the first (resp. Second) potentially candidate
8299 // to be placed in a paired load.
8300 const LoadedSlice *First = NULL;
8301 const LoadedSlice *Second = NULL;
8302 for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice,
8303 // Set the beginning of the pair.
8306 Second = &LoadedSlices[CurrSlice];
8308 // If First is NULL, it means we start a new pair.
8309 // Get to the next slice.
8313 EVT LoadedType = First->getLoadedType();
8315 // If the types of the slices are different, we cannot pair them.
8316 if (LoadedType != Second->getLoadedType())
8319 // Check if the target supplies paired loads for this type.
8320 unsigned RequiredAlignment = 0;
8321 if (!TLI.hasPairedLoad(LoadedType, RequiredAlignment)) {
8322 // move to the next pair, this type is hopeless.
8326 // Check if we meet the alignment requirement.
8327 if (RequiredAlignment > First->getAlignment())
8330 // Check that both loads are next to each other in memory.
8331 if (!areSlicesNextToEachOther(*First, *Second))
8334 assert(GlobalLSCost.Loads > 0 && "We save more loads than we created!");
8335 --GlobalLSCost.Loads;
8336 // Move to the next pair.
8341 /// \brief Check the profitability of all involved LoadedSlice.
8342 /// Currently, it is considered profitable if there is exactly two
8343 /// involved slices (1) which are (2) next to each other in memory, and
8344 /// whose cost (\see LoadedSlice::Cost) is smaller than the original load (3).
8346 /// Note: The order of the elements in \p LoadedSlices may be modified, but not
8347 /// the elements themselves.
8349 /// FIXME: When the cost model will be mature enough, we can relax
8350 /// constraints (1) and (2).
8351 static bool isSlicingProfitable(SmallVectorImpl<LoadedSlice> &LoadedSlices,
8352 const APInt &UsedBits, bool ForCodeSize) {
8353 unsigned NumberOfSlices = LoadedSlices.size();
8354 if (StressLoadSlicing)
8355 return NumberOfSlices > 1;
8358 if (NumberOfSlices != 2)
8362 if (!areUsedBitsDense(UsedBits))
8366 LoadedSlice::Cost OrigCost(ForCodeSize), GlobalSlicingCost(ForCodeSize);
8367 // The original code has one big load.
8369 for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice) {
8370 const LoadedSlice &LS = LoadedSlices[CurrSlice];
8371 // Accumulate the cost of all the slices.
8372 LoadedSlice::Cost SliceCost(LS, ForCodeSize);
8373 GlobalSlicingCost += SliceCost;
8375 // Account as cost in the original configuration the gain obtained
8376 // with the current slices.
8377 OrigCost.addSliceGain(LS);
8380 // If the target supports paired load, adjust the cost accordingly.
8381 adjustCostForPairing(LoadedSlices, GlobalSlicingCost);
8382 return OrigCost > GlobalSlicingCost;
8385 /// \brief If the given load, \p LI, is used only by trunc or trunc(lshr)
8386 /// operations, split it in the various pieces being extracted.
8388 /// This sort of thing is introduced by SROA.
8389 /// This slicing takes care not to insert overlapping loads.
8390 /// \pre LI is a simple load (i.e., not an atomic or volatile load).
8391 bool DAGCombiner::SliceUpLoad(SDNode *N) {
8392 if (Level < AfterLegalizeDAG)
8395 LoadSDNode *LD = cast<LoadSDNode>(N);
8396 if (LD->isVolatile() || !ISD::isNormalLoad(LD) ||
8397 !LD->getValueType(0).isInteger())
8400 // Keep track of already used bits to detect overlapping values.
8401 // In that case, we will just abort the transformation.
8402 APInt UsedBits(LD->getValueSizeInBits(0), 0);
8404 SmallVector<LoadedSlice, 4> LoadedSlices;
8406 // Check if this load is used as several smaller chunks of bits.
8407 // Basically, look for uses in trunc or trunc(lshr) and record a new chain
8408 // of computation for each trunc.
8409 for (SDNode::use_iterator UI = LD->use_begin(), UIEnd = LD->use_end();
8410 UI != UIEnd; ++UI) {
8411 // Skip the uses of the chain.
8412 if (UI.getUse().getResNo() != 0)
8418 // Check if this is a trunc(lshr).
8419 if (User->getOpcode() == ISD::SRL && User->hasOneUse() &&
8420 isa<ConstantSDNode>(User->getOperand(1))) {
8421 Shift = cast<ConstantSDNode>(User->getOperand(1))->getZExtValue();
8422 User = *User->use_begin();
8425 // At this point, User is a Truncate, iff we encountered, trunc or
8427 if (User->getOpcode() != ISD::TRUNCATE)
8430 // The width of the type must be a power of 2 and greater than 8-bits.
8431 // Otherwise the load cannot be represented in LLVM IR.
8432 // Moreover, if we shifted with a non-8-bits multiple, the slice
8433 // will be across several bytes. We do not support that.
8434 unsigned Width = User->getValueSizeInBits(0);
8435 if (Width < 8 || !isPowerOf2_32(Width) || (Shift & 0x7))
8438 // Build the slice for this chain of computations.
8439 LoadedSlice LS(User, LD, Shift, &DAG);
8440 APInt CurrentUsedBits = LS.getUsedBits();
8442 // Check if this slice overlaps with another.
8443 if ((CurrentUsedBits & UsedBits) != 0)
8445 // Update the bits used globally.
8446 UsedBits |= CurrentUsedBits;
8448 // Check if the new slice would be legal.
8452 // Record the slice.
8453 LoadedSlices.push_back(LS);
8456 // Abort slicing if it does not seem to be profitable.
8457 if (!isSlicingProfitable(LoadedSlices, UsedBits, ForCodeSize))
8462 // Rewrite each chain to use an independent load.
8463 // By construction, each chain can be represented by a unique load.
8465 // Prepare the argument for the new token factor for all the slices.
8466 SmallVector<SDValue, 8> ArgChains;
8467 for (SmallVectorImpl<LoadedSlice>::const_iterator
8468 LSIt = LoadedSlices.begin(),
8469 LSItEnd = LoadedSlices.end();
8470 LSIt != LSItEnd; ++LSIt) {
8471 SDValue SliceInst = LSIt->loadSlice();
8472 CombineTo(LSIt->Inst, SliceInst, true);
8473 if (SliceInst.getNode()->getOpcode() != ISD::LOAD)
8474 SliceInst = SliceInst.getOperand(0);
8475 assert(SliceInst->getOpcode() == ISD::LOAD &&
8476 "It takes more than a zext to get to the loaded slice!!");
8477 ArgChains.push_back(SliceInst.getValue(1));
8480 SDValue Chain = DAG.getNode(ISD::TokenFactor, SDLoc(LD), MVT::Other,
8481 &ArgChains[0], ArgChains.size());
8482 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain);
8486 /// CheckForMaskedLoad - Check to see if V is (and load (ptr), imm), where the
8487 /// load is having specific bytes cleared out. If so, return the byte size
8488 /// being masked out and the shift amount.
8489 static std::pair<unsigned, unsigned>
8490 CheckForMaskedLoad(SDValue V, SDValue Ptr, SDValue Chain) {
8491 std::pair<unsigned, unsigned> Result(0, 0);
8493 // Check for the structure we're looking for.
8494 if (V->getOpcode() != ISD::AND ||
8495 !isa<ConstantSDNode>(V->getOperand(1)) ||
8496 !ISD::isNormalLoad(V->getOperand(0).getNode()))
8499 // Check the chain and pointer.
8500 LoadSDNode *LD = cast<LoadSDNode>(V->getOperand(0));
8501 if (LD->getBasePtr() != Ptr) return Result; // Not from same pointer.
8503 // The store should be chained directly to the load or be an operand of a
8505 if (LD == Chain.getNode())
8507 else if (Chain->getOpcode() != ISD::TokenFactor)
8508 return Result; // Fail.
8511 for (unsigned i = 0, e = Chain->getNumOperands(); i != e; ++i)
8512 if (Chain->getOperand(i).getNode() == LD) {
8516 if (!isOk) return Result;
8519 // This only handles simple types.
8520 if (V.getValueType() != MVT::i16 &&
8521 V.getValueType() != MVT::i32 &&
8522 V.getValueType() != MVT::i64)
8525 // Check the constant mask. Invert it so that the bits being masked out are
8526 // 0 and the bits being kept are 1. Use getSExtValue so that leading bits
8527 // follow the sign bit for uniformity.
8528 uint64_t NotMask = ~cast<ConstantSDNode>(V->getOperand(1))->getSExtValue();
8529 unsigned NotMaskLZ = countLeadingZeros(NotMask);
8530 if (NotMaskLZ & 7) return Result; // Must be multiple of a byte.
8531 unsigned NotMaskTZ = countTrailingZeros(NotMask);
8532 if (NotMaskTZ & 7) return Result; // Must be multiple of a byte.
8533 if (NotMaskLZ == 64) return Result; // All zero mask.
8535 // See if we have a continuous run of bits. If so, we have 0*1+0*
8536 if (CountTrailingOnes_64(NotMask >> NotMaskTZ)+NotMaskTZ+NotMaskLZ != 64)
8539 // Adjust NotMaskLZ down to be from the actual size of the int instead of i64.
8540 if (V.getValueType() != MVT::i64 && NotMaskLZ)
8541 NotMaskLZ -= 64-V.getValueSizeInBits();
8543 unsigned MaskedBytes = (V.getValueSizeInBits()-NotMaskLZ-NotMaskTZ)/8;
8544 switch (MaskedBytes) {
8548 default: return Result; // All one mask, or 5-byte mask.
8551 // Verify that the first bit starts at a multiple of mask so that the access
8552 // is aligned the same as the access width.
8553 if (NotMaskTZ && NotMaskTZ/8 % MaskedBytes) return Result;
8555 Result.first = MaskedBytes;
8556 Result.second = NotMaskTZ/8;
8561 /// ShrinkLoadReplaceStoreWithStore - Check to see if IVal is something that
8562 /// provides a value as specified by MaskInfo. If so, replace the specified
8563 /// store with a narrower store of truncated IVal.
8565 ShrinkLoadReplaceStoreWithStore(const std::pair<unsigned, unsigned> &MaskInfo,
8566 SDValue IVal, StoreSDNode *St,
8568 unsigned NumBytes = MaskInfo.first;
8569 unsigned ByteShift = MaskInfo.second;
8570 SelectionDAG &DAG = DC->getDAG();
8572 // Check to see if IVal is all zeros in the part being masked in by the 'or'
8573 // that uses this. If not, this is not a replacement.
8574 APInt Mask = ~APInt::getBitsSet(IVal.getValueSizeInBits(),
8575 ByteShift*8, (ByteShift+NumBytes)*8);
8576 if (!DAG.MaskedValueIsZero(IVal, Mask)) return 0;
8578 // Check that it is legal on the target to do this. It is legal if the new
8579 // VT we're shrinking to (i8/i16/i32) is legal or we're still before type
8581 MVT VT = MVT::getIntegerVT(NumBytes*8);
8582 if (!DC->isTypeLegal(VT))
8585 // Okay, we can do this! Replace the 'St' store with a store of IVal that is
8586 // shifted by ByteShift and truncated down to NumBytes.
8588 IVal = DAG.getNode(ISD::SRL, SDLoc(IVal), IVal.getValueType(), IVal,
8589 DAG.getConstant(ByteShift*8,
8590 DC->getShiftAmountTy(IVal.getValueType())));
8592 // Figure out the offset for the store and the alignment of the access.
8594 unsigned NewAlign = St->getAlignment();
8596 if (DAG.getTargetLoweringInfo().isLittleEndian())
8597 StOffset = ByteShift;
8599 StOffset = IVal.getValueType().getStoreSize() - ByteShift - NumBytes;
8601 SDValue Ptr = St->getBasePtr();
8603 Ptr = DAG.getNode(ISD::ADD, SDLoc(IVal), Ptr.getValueType(),
8604 Ptr, DAG.getConstant(StOffset, Ptr.getValueType()));
8605 NewAlign = MinAlign(NewAlign, StOffset);
8608 // Truncate down to the new size.
8609 IVal = DAG.getNode(ISD::TRUNCATE, SDLoc(IVal), VT, IVal);
8612 return DAG.getStore(St->getChain(), SDLoc(St), IVal, Ptr,
8613 St->getPointerInfo().getWithOffset(StOffset),
8614 false, false, NewAlign).getNode();
8618 /// ReduceLoadOpStoreWidth - Look for sequence of load / op / store where op is
8619 /// one of 'or', 'xor', and 'and' of immediates. If 'op' is only touching some
8620 /// of the loaded bits, try narrowing the load and store if it would end up
8621 /// being a win for performance or code size.
8622 SDValue DAGCombiner::ReduceLoadOpStoreWidth(SDNode *N) {
8623 StoreSDNode *ST = cast<StoreSDNode>(N);
8624 if (ST->isVolatile())
8627 SDValue Chain = ST->getChain();
8628 SDValue Value = ST->getValue();
8629 SDValue Ptr = ST->getBasePtr();
8630 EVT VT = Value.getValueType();
8632 if (ST->isTruncatingStore() || VT.isVector() || !Value.hasOneUse())
8635 unsigned Opc = Value.getOpcode();
8637 // If this is "store (or X, Y), P" and X is "(and (load P), cst)", where cst
8638 // is a byte mask indicating a consecutive number of bytes, check to see if
8639 // Y is known to provide just those bytes. If so, we try to replace the
8640 // load + replace + store sequence with a single (narrower) store, which makes
8642 if (Opc == ISD::OR) {
8643 std::pair<unsigned, unsigned> MaskedLoad;
8644 MaskedLoad = CheckForMaskedLoad(Value.getOperand(0), Ptr, Chain);
8645 if (MaskedLoad.first)
8646 if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad,
8647 Value.getOperand(1), ST,this))
8648 return SDValue(NewST, 0);
8650 // Or is commutative, so try swapping X and Y.
8651 MaskedLoad = CheckForMaskedLoad(Value.getOperand(1), Ptr, Chain);
8652 if (MaskedLoad.first)
8653 if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad,
8654 Value.getOperand(0), ST,this))
8655 return SDValue(NewST, 0);
8658 if ((Opc != ISD::OR && Opc != ISD::XOR && Opc != ISD::AND) ||
8659 Value.getOperand(1).getOpcode() != ISD::Constant)
8662 SDValue N0 = Value.getOperand(0);
8663 if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
8664 Chain == SDValue(N0.getNode(), 1)) {
8665 LoadSDNode *LD = cast<LoadSDNode>(N0);
8666 if (LD->getBasePtr() != Ptr ||
8667 LD->getPointerInfo().getAddrSpace() !=
8668 ST->getPointerInfo().getAddrSpace())
8671 // Find the type to narrow it the load / op / store to.
8672 SDValue N1 = Value.getOperand(1);
8673 unsigned BitWidth = N1.getValueSizeInBits();
8674 APInt Imm = cast<ConstantSDNode>(N1)->getAPIntValue();
8675 if (Opc == ISD::AND)
8676 Imm ^= APInt::getAllOnesValue(BitWidth);
8677 if (Imm == 0 || Imm.isAllOnesValue())
8679 unsigned ShAmt = Imm.countTrailingZeros();
8680 unsigned MSB = BitWidth - Imm.countLeadingZeros() - 1;
8681 unsigned NewBW = NextPowerOf2(MSB - ShAmt);
8682 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW);
8683 while (NewBW < BitWidth &&
8684 !(TLI.isOperationLegalOrCustom(Opc, NewVT) &&
8685 TLI.isNarrowingProfitable(VT, NewVT))) {
8686 NewBW = NextPowerOf2(NewBW);
8687 NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW);
8689 if (NewBW >= BitWidth)
8692 // If the lsb changed does not start at the type bitwidth boundary,
8693 // start at the previous one.
8695 ShAmt = (((ShAmt + NewBW - 1) / NewBW) * NewBW) - NewBW;
8696 APInt Mask = APInt::getBitsSet(BitWidth, ShAmt,
8697 std::min(BitWidth, ShAmt + NewBW));
8698 if ((Imm & Mask) == Imm) {
8699 APInt NewImm = (Imm & Mask).lshr(ShAmt).trunc(NewBW);
8700 if (Opc == ISD::AND)
8701 NewImm ^= APInt::getAllOnesValue(NewBW);
8702 uint64_t PtrOff = ShAmt / 8;
8703 // For big endian targets, we need to adjust the offset to the pointer to
8704 // load the correct bytes.
8705 if (TLI.isBigEndian())
8706 PtrOff = (BitWidth + 7 - NewBW) / 8 - PtrOff;
8708 unsigned NewAlign = MinAlign(LD->getAlignment(), PtrOff);
8709 Type *NewVTTy = NewVT.getTypeForEVT(*DAG.getContext());
8710 if (NewAlign < TLI.getDataLayout()->getABITypeAlignment(NewVTTy))
8713 SDValue NewPtr = DAG.getNode(ISD::ADD, SDLoc(LD),
8714 Ptr.getValueType(), Ptr,
8715 DAG.getConstant(PtrOff, Ptr.getValueType()));
8716 SDValue NewLD = DAG.getLoad(NewVT, SDLoc(N0),
8717 LD->getChain(), NewPtr,
8718 LD->getPointerInfo().getWithOffset(PtrOff),
8719 LD->isVolatile(), LD->isNonTemporal(),
8720 LD->isInvariant(), NewAlign,
8722 SDValue NewVal = DAG.getNode(Opc, SDLoc(Value), NewVT, NewLD,
8723 DAG.getConstant(NewImm, NewVT));
8724 SDValue NewST = DAG.getStore(Chain, SDLoc(N),
8726 ST->getPointerInfo().getWithOffset(PtrOff),
8727 false, false, NewAlign);
8729 AddToWorkList(NewPtr.getNode());
8730 AddToWorkList(NewLD.getNode());
8731 AddToWorkList(NewVal.getNode());
8732 WorkListRemover DeadNodes(*this);
8733 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLD.getValue(1));
8742 /// TransformFPLoadStorePair - For a given floating point load / store pair,
8743 /// if the load value isn't used by any other operations, then consider
8744 /// transforming the pair to integer load / store operations if the target
8745 /// deems the transformation profitable.
8746 SDValue DAGCombiner::TransformFPLoadStorePair(SDNode *N) {
8747 StoreSDNode *ST = cast<StoreSDNode>(N);
8748 SDValue Chain = ST->getChain();
8749 SDValue Value = ST->getValue();
8750 if (ISD::isNormalStore(ST) && ISD::isNormalLoad(Value.getNode()) &&
8751 Value.hasOneUse() &&
8752 Chain == SDValue(Value.getNode(), 1)) {
8753 LoadSDNode *LD = cast<LoadSDNode>(Value);
8754 EVT VT = LD->getMemoryVT();
8755 if (!VT.isFloatingPoint() ||
8756 VT != ST->getMemoryVT() ||
8757 LD->isNonTemporal() ||
8758 ST->isNonTemporal() ||
8759 LD->getPointerInfo().getAddrSpace() != 0 ||
8760 ST->getPointerInfo().getAddrSpace() != 0)
8763 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), VT.getSizeInBits());
8764 if (!TLI.isOperationLegal(ISD::LOAD, IntVT) ||
8765 !TLI.isOperationLegal(ISD::STORE, IntVT) ||
8766 !TLI.isDesirableToTransformToIntegerOp(ISD::LOAD, VT) ||
8767 !TLI.isDesirableToTransformToIntegerOp(ISD::STORE, VT))
8770 unsigned LDAlign = LD->getAlignment();
8771 unsigned STAlign = ST->getAlignment();
8772 Type *IntVTTy = IntVT.getTypeForEVT(*DAG.getContext());
8773 unsigned ABIAlign = TLI.getDataLayout()->getABITypeAlignment(IntVTTy);
8774 if (LDAlign < ABIAlign || STAlign < ABIAlign)
8777 SDValue NewLD = DAG.getLoad(IntVT, SDLoc(Value),
8778 LD->getChain(), LD->getBasePtr(),
8779 LD->getPointerInfo(),
8780 false, false, false, LDAlign);
8782 SDValue NewST = DAG.getStore(NewLD.getValue(1), SDLoc(N),
8783 NewLD, ST->getBasePtr(),
8784 ST->getPointerInfo(),
8785 false, false, STAlign);
8787 AddToWorkList(NewLD.getNode());
8788 AddToWorkList(NewST.getNode());
8789 WorkListRemover DeadNodes(*this);
8790 DAG.ReplaceAllUsesOfValueWith(Value.getValue(1), NewLD.getValue(1));
8798 /// Helper struct to parse and store a memory address as base + index + offset.
8799 /// We ignore sign extensions when it is safe to do so.
8800 /// The following two expressions are not equivalent. To differentiate we need
8801 /// to store whether there was a sign extension involved in the index
8803 /// (load (i64 add (i64 copyfromreg %c)
8804 /// (i64 signextend (add (i8 load %index)
8808 /// (load (i64 add (i64 copyfromreg %c)
8809 /// (i64 signextend (i32 add (i32 signextend (i8 load %index))
8811 struct BaseIndexOffset {
8815 bool IsIndexSignExt;
8817 BaseIndexOffset() : Offset(0), IsIndexSignExt(false) {}
8819 BaseIndexOffset(SDValue Base, SDValue Index, int64_t Offset,
8820 bool IsIndexSignExt) :
8821 Base(Base), Index(Index), Offset(Offset), IsIndexSignExt(IsIndexSignExt) {}
8823 bool equalBaseIndex(const BaseIndexOffset &Other) {
8824 return Other.Base == Base && Other.Index == Index &&
8825 Other.IsIndexSignExt == IsIndexSignExt;
8828 /// Parses tree in Ptr for base, index, offset addresses.
8829 static BaseIndexOffset match(SDValue Ptr) {
8830 bool IsIndexSignExt = false;
8832 // We only can pattern match BASE + INDEX + OFFSET. If Ptr is not an ADD
8833 // instruction, then it could be just the BASE or everything else we don't
8834 // know how to handle. Just use Ptr as BASE and give up.
8835 if (Ptr->getOpcode() != ISD::ADD)
8836 return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
8838 // We know that we have at least an ADD instruction. Try to pattern match
8839 // the simple case of BASE + OFFSET.
8840 if (isa<ConstantSDNode>(Ptr->getOperand(1))) {
8841 int64_t Offset = cast<ConstantSDNode>(Ptr->getOperand(1))->getSExtValue();
8842 return BaseIndexOffset(Ptr->getOperand(0), SDValue(), Offset,
8846 // Inside a loop the current BASE pointer is calculated using an ADD and a
8847 // MUL instruction. In this case Ptr is the actual BASE pointer.
8848 // (i64 add (i64 %array_ptr)
8849 // (i64 mul (i64 %induction_var)
8850 // (i64 %element_size)))
8851 if (Ptr->getOperand(1)->getOpcode() == ISD::MUL)
8852 return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
8854 // Look at Base + Index + Offset cases.
8855 SDValue Base = Ptr->getOperand(0);
8856 SDValue IndexOffset = Ptr->getOperand(1);
8858 // Skip signextends.
8859 if (IndexOffset->getOpcode() == ISD::SIGN_EXTEND) {
8860 IndexOffset = IndexOffset->getOperand(0);
8861 IsIndexSignExt = true;
8864 // Either the case of Base + Index (no offset) or something else.
8865 if (IndexOffset->getOpcode() != ISD::ADD)
8866 return BaseIndexOffset(Base, IndexOffset, 0, IsIndexSignExt);
8868 // Now we have the case of Base + Index + offset.
8869 SDValue Index = IndexOffset->getOperand(0);
8870 SDValue Offset = IndexOffset->getOperand(1);
8872 if (!isa<ConstantSDNode>(Offset))
8873 return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
8875 // Ignore signextends.
8876 if (Index->getOpcode() == ISD::SIGN_EXTEND) {
8877 Index = Index->getOperand(0);
8878 IsIndexSignExt = true;
8879 } else IsIndexSignExt = false;
8881 int64_t Off = cast<ConstantSDNode>(Offset)->getSExtValue();
8882 return BaseIndexOffset(Base, Index, Off, IsIndexSignExt);
8886 /// Holds a pointer to an LSBaseSDNode as well as information on where it
8887 /// is located in a sequence of memory operations connected by a chain.
8889 MemOpLink (LSBaseSDNode *N, int64_t Offset, unsigned Seq):
8890 MemNode(N), OffsetFromBase(Offset), SequenceNum(Seq) { }
8891 // Ptr to the mem node.
8892 LSBaseSDNode *MemNode;
8893 // Offset from the base ptr.
8894 int64_t OffsetFromBase;
8895 // What is the sequence number of this mem node.
8896 // Lowest mem operand in the DAG starts at zero.
8897 unsigned SequenceNum;
8900 bool DAGCombiner::MergeConsecutiveStores(StoreSDNode* St) {
8901 EVT MemVT = St->getMemoryVT();
8902 int64_t ElementSizeBytes = MemVT.getSizeInBits()/8;
8903 bool NoVectors = DAG.getMachineFunction().getFunction()->getAttributes().
8904 hasAttribute(AttributeSet::FunctionIndex, Attribute::NoImplicitFloat);
8906 // Don't merge vectors into wider inputs.
8907 if (MemVT.isVector() || !MemVT.isSimple())
8910 // Perform an early exit check. Do not bother looking at stored values that
8911 // are not constants or loads.
8912 SDValue StoredVal = St->getValue();
8913 bool IsLoadSrc = isa<LoadSDNode>(StoredVal);
8914 if (!isa<ConstantSDNode>(StoredVal) && !isa<ConstantFPSDNode>(StoredVal) &&
8918 // Only look at ends of store sequences.
8919 SDValue Chain = SDValue(St, 1);
8920 if (Chain->hasOneUse() && Chain->use_begin()->getOpcode() == ISD::STORE)
8923 // This holds the base pointer, index, and the offset in bytes from the base
8925 BaseIndexOffset BasePtr = BaseIndexOffset::match(St->getBasePtr());
8927 // We must have a base and an offset.
8928 if (!BasePtr.Base.getNode())
8931 // Do not handle stores to undef base pointers.
8932 if (BasePtr.Base.getOpcode() == ISD::UNDEF)
8935 // Save the LoadSDNodes that we find in the chain.
8936 // We need to make sure that these nodes do not interfere with
8937 // any of the store nodes.
8938 SmallVector<LSBaseSDNode*, 8> AliasLoadNodes;
8940 // Save the StoreSDNodes that we find in the chain.
8941 SmallVector<MemOpLink, 8> StoreNodes;
8943 // Walk up the chain and look for nodes with offsets from the same
8944 // base pointer. Stop when reaching an instruction with a different kind
8945 // or instruction which has a different base pointer.
8947 StoreSDNode *Index = St;
8949 // If the chain has more than one use, then we can't reorder the mem ops.
8950 if (Index != St && !SDValue(Index, 1)->hasOneUse())
8953 // Find the base pointer and offset for this memory node.
8954 BaseIndexOffset Ptr = BaseIndexOffset::match(Index->getBasePtr());
8956 // Check that the base pointer is the same as the original one.
8957 if (!Ptr.equalBaseIndex(BasePtr))
8960 // Check that the alignment is the same.
8961 if (Index->getAlignment() != St->getAlignment())
8964 // The memory operands must not be volatile.
8965 if (Index->isVolatile() || Index->isIndexed())
8969 if (StoreSDNode *St = dyn_cast<StoreSDNode>(Index))
8970 if (St->isTruncatingStore())
8973 // The stored memory type must be the same.
8974 if (Index->getMemoryVT() != MemVT)
8977 // We do not allow unaligned stores because we want to prevent overriding
8979 if (Index->getAlignment()*8 != MemVT.getSizeInBits())
8982 // We found a potential memory operand to merge.
8983 StoreNodes.push_back(MemOpLink(Index, Ptr.Offset, Seq++));
8985 // Find the next memory operand in the chain. If the next operand in the
8986 // chain is a store then move up and continue the scan with the next
8987 // memory operand. If the next operand is a load save it and use alias
8988 // information to check if it interferes with anything.
8989 SDNode *NextInChain = Index->getChain().getNode();
8991 if (StoreSDNode *STn = dyn_cast<StoreSDNode>(NextInChain)) {
8992 // We found a store node. Use it for the next iteration.
8995 } else if (LoadSDNode *Ldn = dyn_cast<LoadSDNode>(NextInChain)) {
8996 if (Ldn->isVolatile()) {
9001 // Save the load node for later. Continue the scan.
9002 AliasLoadNodes.push_back(Ldn);
9003 NextInChain = Ldn->getChain().getNode();
9012 // Check if there is anything to merge.
9013 if (StoreNodes.size() < 2)
9016 // Sort the memory operands according to their distance from the base pointer.
9017 std::sort(StoreNodes.begin(), StoreNodes.end(),
9018 [](MemOpLink LHS, MemOpLink RHS) {
9019 return LHS.OffsetFromBase < RHS.OffsetFromBase ||
9020 (LHS.OffsetFromBase == RHS.OffsetFromBase &&
9021 LHS.SequenceNum > RHS.SequenceNum);
9024 // Scan the memory operations on the chain and find the first non-consecutive
9025 // store memory address.
9026 unsigned LastConsecutiveStore = 0;
9027 int64_t StartAddress = StoreNodes[0].OffsetFromBase;
9028 for (unsigned i = 0, e = StoreNodes.size(); i < e; ++i) {
9030 // Check that the addresses are consecutive starting from the second
9031 // element in the list of stores.
9033 int64_t CurrAddress = StoreNodes[i].OffsetFromBase;
9034 if (CurrAddress - StartAddress != (ElementSizeBytes * i))
9039 // Check if this store interferes with any of the loads that we found.
9040 for (unsigned ld = 0, lde = AliasLoadNodes.size(); ld < lde; ++ld)
9041 if (isAlias(AliasLoadNodes[ld], StoreNodes[i].MemNode)) {
9045 // We found a load that alias with this store. Stop the sequence.
9049 // Mark this node as useful.
9050 LastConsecutiveStore = i;
9053 // The node with the lowest store address.
9054 LSBaseSDNode *FirstInChain = StoreNodes[0].MemNode;
9056 // Store the constants into memory as one consecutive store.
9058 unsigned LastLegalType = 0;
9059 unsigned LastLegalVectorType = 0;
9060 bool NonZero = false;
9061 for (unsigned i=0; i<LastConsecutiveStore+1; ++i) {
9062 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
9063 SDValue StoredVal = St->getValue();
9065 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(StoredVal)) {
9066 NonZero |= !C->isNullValue();
9067 } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(StoredVal)) {
9068 NonZero |= !C->getConstantFPValue()->isNullValue();
9074 // Find a legal type for the constant store.
9075 unsigned StoreBW = (i+1) * ElementSizeBytes * 8;
9076 EVT StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
9077 if (TLI.isTypeLegal(StoreTy))
9078 LastLegalType = i+1;
9079 // Or check whether a truncstore is legal.
9080 else if (TLI.getTypeAction(*DAG.getContext(), StoreTy) ==
9081 TargetLowering::TypePromoteInteger) {
9082 EVT LegalizedStoredValueTy =
9083 TLI.getTypeToTransformTo(*DAG.getContext(), StoredVal.getValueType());
9084 if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy))
9085 LastLegalType = i+1;
9088 // Find a legal type for the vector store.
9089 EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT, i+1);
9090 if (TLI.isTypeLegal(Ty))
9091 LastLegalVectorType = i + 1;
9094 // We only use vectors if the constant is known to be zero and the
9095 // function is not marked with the noimplicitfloat attribute.
9096 if (NonZero || NoVectors)
9097 LastLegalVectorType = 0;
9099 // Check if we found a legal integer type to store.
9100 if (LastLegalType == 0 && LastLegalVectorType == 0)
9103 bool UseVector = (LastLegalVectorType > LastLegalType) && !NoVectors;
9104 unsigned NumElem = UseVector ? LastLegalVectorType : LastLegalType;
9106 // Make sure we have something to merge.
9110 unsigned EarliestNodeUsed = 0;
9111 for (unsigned i=0; i < NumElem; ++i) {
9112 // Find a chain for the new wide-store operand. Notice that some
9113 // of the store nodes that we found may not be selected for inclusion
9114 // in the wide store. The chain we use needs to be the chain of the
9115 // earliest store node which is *used* and replaced by the wide store.
9116 if (StoreNodes[i].SequenceNum > StoreNodes[EarliestNodeUsed].SequenceNum)
9117 EarliestNodeUsed = i;
9120 // The earliest Node in the DAG.
9121 LSBaseSDNode *EarliestOp = StoreNodes[EarliestNodeUsed].MemNode;
9122 SDLoc DL(StoreNodes[0].MemNode);
9126 // Find a legal type for the vector store.
9127 EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT, NumElem);
9128 assert(TLI.isTypeLegal(Ty) && "Illegal vector store");
9129 StoredVal = DAG.getConstant(0, Ty);
9131 unsigned StoreBW = NumElem * ElementSizeBytes * 8;
9132 APInt StoreInt(StoreBW, 0);
9134 // Construct a single integer constant which is made of the smaller
9136 bool IsLE = TLI.isLittleEndian();
9137 for (unsigned i = 0; i < NumElem ; ++i) {
9138 unsigned Idx = IsLE ?(NumElem - 1 - i) : i;
9139 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[Idx].MemNode);
9140 SDValue Val = St->getValue();
9141 StoreInt<<=ElementSizeBytes*8;
9142 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Val)) {
9143 StoreInt|=C->getAPIntValue().zext(StoreBW);
9144 } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Val)) {
9145 StoreInt|= C->getValueAPF().bitcastToAPInt().zext(StoreBW);
9147 assert(false && "Invalid constant element type");
9151 // Create the new Load and Store operations.
9152 EVT StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
9153 StoredVal = DAG.getConstant(StoreInt, StoreTy);
9156 SDValue NewStore = DAG.getStore(EarliestOp->getChain(), DL, StoredVal,
9157 FirstInChain->getBasePtr(),
9158 FirstInChain->getPointerInfo(),
9160 FirstInChain->getAlignment());
9162 // Replace the first store with the new store
9163 CombineTo(EarliestOp, NewStore);
9164 // Erase all other stores.
9165 for (unsigned i = 0; i < NumElem ; ++i) {
9166 if (StoreNodes[i].MemNode == EarliestOp)
9168 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
9169 // ReplaceAllUsesWith will replace all uses that existed when it was
9170 // called, but graph optimizations may cause new ones to appear. For
9171 // example, the case in pr14333 looks like
9173 // St's chain -> St -> another store -> X
9175 // And the only difference from St to the other store is the chain.
9176 // When we change it's chain to be St's chain they become identical,
9177 // get CSEed and the net result is that X is now a use of St.
9178 // Since we know that St is redundant, just iterate.
9179 while (!St->use_empty())
9180 DAG.ReplaceAllUsesWith(SDValue(St, 0), St->getChain());
9181 removeFromWorkList(St);
9188 // Below we handle the case of multiple consecutive stores that
9189 // come from multiple consecutive loads. We merge them into a single
9190 // wide load and a single wide store.
9192 // Look for load nodes which are used by the stored values.
9193 SmallVector<MemOpLink, 8> LoadNodes;
9195 // Find acceptable loads. Loads need to have the same chain (token factor),
9196 // must not be zext, volatile, indexed, and they must be consecutive.
9197 BaseIndexOffset LdBasePtr;
9198 for (unsigned i=0; i<LastConsecutiveStore+1; ++i) {
9199 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
9200 LoadSDNode *Ld = dyn_cast<LoadSDNode>(St->getValue());
9203 // Loads must only have one use.
9204 if (!Ld->hasNUsesOfValue(1, 0))
9207 // Check that the alignment is the same as the stores.
9208 if (Ld->getAlignment() != St->getAlignment())
9211 // The memory operands must not be volatile.
9212 if (Ld->isVolatile() || Ld->isIndexed())
9215 // We do not accept ext loads.
9216 if (Ld->getExtensionType() != ISD::NON_EXTLOAD)
9219 // The stored memory type must be the same.
9220 if (Ld->getMemoryVT() != MemVT)
9223 BaseIndexOffset LdPtr = BaseIndexOffset::match(Ld->getBasePtr());
9224 // If this is not the first ptr that we check.
9225 if (LdBasePtr.Base.getNode()) {
9226 // The base ptr must be the same.
9227 if (!LdPtr.equalBaseIndex(LdBasePtr))
9230 // Check that all other base pointers are the same as this one.
9234 // We found a potential memory operand to merge.
9235 LoadNodes.push_back(MemOpLink(Ld, LdPtr.Offset, 0));
9238 if (LoadNodes.size() < 2)
9241 // Scan the memory operations on the chain and find the first non-consecutive
9242 // load memory address. These variables hold the index in the store node
9244 unsigned LastConsecutiveLoad = 0;
9245 // This variable refers to the size and not index in the array.
9246 unsigned LastLegalVectorType = 0;
9247 unsigned LastLegalIntegerType = 0;
9248 StartAddress = LoadNodes[0].OffsetFromBase;
9249 SDValue FirstChain = LoadNodes[0].MemNode->getChain();
9250 for (unsigned i = 1; i < LoadNodes.size(); ++i) {
9251 // All loads much share the same chain.
9252 if (LoadNodes[i].MemNode->getChain() != FirstChain)
9255 int64_t CurrAddress = LoadNodes[i].OffsetFromBase;
9256 if (CurrAddress - StartAddress != (ElementSizeBytes * i))
9258 LastConsecutiveLoad = i;
9260 // Find a legal type for the vector store.
9261 EVT StoreTy = EVT::getVectorVT(*DAG.getContext(), MemVT, i+1);
9262 if (TLI.isTypeLegal(StoreTy))
9263 LastLegalVectorType = i + 1;
9265 // Find a legal type for the integer store.
9266 unsigned StoreBW = (i+1) * ElementSizeBytes * 8;
9267 StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
9268 if (TLI.isTypeLegal(StoreTy))
9269 LastLegalIntegerType = i + 1;
9270 // Or check whether a truncstore and extload is legal.
9271 else if (TLI.getTypeAction(*DAG.getContext(), StoreTy) ==
9272 TargetLowering::TypePromoteInteger) {
9273 EVT LegalizedStoredValueTy =
9274 TLI.getTypeToTransformTo(*DAG.getContext(), StoreTy);
9275 if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy) &&
9276 TLI.isLoadExtLegal(ISD::ZEXTLOAD, StoreTy) &&
9277 TLI.isLoadExtLegal(ISD::SEXTLOAD, StoreTy) &&
9278 TLI.isLoadExtLegal(ISD::EXTLOAD, StoreTy))
9279 LastLegalIntegerType = i+1;
9283 // Only use vector types if the vector type is larger than the integer type.
9284 // If they are the same, use integers.
9285 bool UseVectorTy = LastLegalVectorType > LastLegalIntegerType && !NoVectors;
9286 unsigned LastLegalType = std::max(LastLegalVectorType, LastLegalIntegerType);
9288 // We add +1 here because the LastXXX variables refer to location while
9289 // the NumElem refers to array/index size.
9290 unsigned NumElem = std::min(LastConsecutiveStore, LastConsecutiveLoad) + 1;
9291 NumElem = std::min(LastLegalType, NumElem);
9296 // The earliest Node in the DAG.
9297 unsigned EarliestNodeUsed = 0;
9298 LSBaseSDNode *EarliestOp = StoreNodes[EarliestNodeUsed].MemNode;
9299 for (unsigned i=1; i<NumElem; ++i) {
9300 // Find a chain for the new wide-store operand. Notice that some
9301 // of the store nodes that we found may not be selected for inclusion
9302 // in the wide store. The chain we use needs to be the chain of the
9303 // earliest store node which is *used* and replaced by the wide store.
9304 if (StoreNodes[i].SequenceNum > StoreNodes[EarliestNodeUsed].SequenceNum)
9305 EarliestNodeUsed = i;
9308 // Find if it is better to use vectors or integers to load and store
9312 JointMemOpVT = EVT::getVectorVT(*DAG.getContext(), MemVT, NumElem);
9314 unsigned StoreBW = NumElem * ElementSizeBytes * 8;
9315 JointMemOpVT = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
9318 SDLoc LoadDL(LoadNodes[0].MemNode);
9319 SDLoc StoreDL(StoreNodes[0].MemNode);
9321 LoadSDNode *FirstLoad = cast<LoadSDNode>(LoadNodes[0].MemNode);
9322 SDValue NewLoad = DAG.getLoad(JointMemOpVT, LoadDL,
9323 FirstLoad->getChain(),
9324 FirstLoad->getBasePtr(),
9325 FirstLoad->getPointerInfo(),
9326 false, false, false,
9327 FirstLoad->getAlignment());
9329 SDValue NewStore = DAG.getStore(EarliestOp->getChain(), StoreDL, NewLoad,
9330 FirstInChain->getBasePtr(),
9331 FirstInChain->getPointerInfo(), false, false,
9332 FirstInChain->getAlignment());
9334 // Replace one of the loads with the new load.
9335 LoadSDNode *Ld = cast<LoadSDNode>(LoadNodes[0].MemNode);
9336 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1),
9337 SDValue(NewLoad.getNode(), 1));
9339 // Remove the rest of the load chains.
9340 for (unsigned i = 1; i < NumElem ; ++i) {
9341 // Replace all chain users of the old load nodes with the chain of the new
9343 LoadSDNode *Ld = cast<LoadSDNode>(LoadNodes[i].MemNode);
9344 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), Ld->getChain());
9347 // Replace the first store with the new store.
9348 CombineTo(EarliestOp, NewStore);
9349 // Erase all other stores.
9350 for (unsigned i = 0; i < NumElem ; ++i) {
9351 // Remove all Store nodes.
9352 if (StoreNodes[i].MemNode == EarliestOp)
9354 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
9355 DAG.ReplaceAllUsesOfValueWith(SDValue(St, 0), St->getChain());
9356 removeFromWorkList(St);
9363 SDValue DAGCombiner::visitSTORE(SDNode *N) {
9364 StoreSDNode *ST = cast<StoreSDNode>(N);
9365 SDValue Chain = ST->getChain();
9366 SDValue Value = ST->getValue();
9367 SDValue Ptr = ST->getBasePtr();
9369 // If this is a store of a bit convert, store the input value if the
9370 // resultant store does not need a higher alignment than the original.
9371 if (Value.getOpcode() == ISD::BITCAST && !ST->isTruncatingStore() &&
9372 ST->isUnindexed()) {
9373 unsigned OrigAlign = ST->getAlignment();
9374 EVT SVT = Value.getOperand(0).getValueType();
9375 unsigned Align = TLI.getDataLayout()->
9376 getABITypeAlignment(SVT.getTypeForEVT(*DAG.getContext()));
9377 if (Align <= OrigAlign &&
9378 ((!LegalOperations && !ST->isVolatile()) ||
9379 TLI.isOperationLegalOrCustom(ISD::STORE, SVT)))
9380 return DAG.getStore(Chain, SDLoc(N), Value.getOperand(0),
9381 Ptr, ST->getPointerInfo(), ST->isVolatile(),
9382 ST->isNonTemporal(), OrigAlign,
9386 // Turn 'store undef, Ptr' -> nothing.
9387 if (Value.getOpcode() == ISD::UNDEF && ST->isUnindexed())
9390 // Turn 'store float 1.0, Ptr' -> 'store int 0x12345678, Ptr'
9391 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Value)) {
9392 // NOTE: If the original store is volatile, this transform must not increase
9393 // the number of stores. For example, on x86-32 an f64 can be stored in one
9394 // processor operation but an i64 (which is not legal) requires two. So the
9395 // transform should not be done in this case.
9396 if (Value.getOpcode() != ISD::TargetConstantFP) {
9398 switch (CFP->getSimpleValueType(0).SimpleTy) {
9399 default: llvm_unreachable("Unknown FP type");
9400 case MVT::f16: // We don't do this for these yet.
9406 if ((isTypeLegal(MVT::i32) && !LegalOperations && !ST->isVolatile()) ||
9407 TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) {
9408 Tmp = DAG.getConstant((uint32_t)CFP->getValueAPF().
9409 bitcastToAPInt().getZExtValue(), MVT::i32);
9410 return DAG.getStore(Chain, SDLoc(N), Tmp,
9411 Ptr, ST->getMemOperand());
9415 if ((TLI.isTypeLegal(MVT::i64) && !LegalOperations &&
9416 !ST->isVolatile()) ||
9417 TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i64)) {
9418 Tmp = DAG.getConstant(CFP->getValueAPF().bitcastToAPInt().
9419 getZExtValue(), MVT::i64);
9420 return DAG.getStore(Chain, SDLoc(N), Tmp,
9421 Ptr, ST->getMemOperand());
9424 if (!ST->isVolatile() &&
9425 TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) {
9426 // Many FP stores are not made apparent until after legalize, e.g. for
9427 // argument passing. Since this is so common, custom legalize the
9428 // 64-bit integer store into two 32-bit stores.
9429 uint64_t Val = CFP->getValueAPF().bitcastToAPInt().getZExtValue();
9430 SDValue Lo = DAG.getConstant(Val & 0xFFFFFFFF, MVT::i32);
9431 SDValue Hi = DAG.getConstant(Val >> 32, MVT::i32);
9432 if (TLI.isBigEndian()) std::swap(Lo, Hi);
9434 unsigned Alignment = ST->getAlignment();
9435 bool isVolatile = ST->isVolatile();
9436 bool isNonTemporal = ST->isNonTemporal();
9437 const MDNode *TBAAInfo = ST->getTBAAInfo();
9439 SDValue St0 = DAG.getStore(Chain, SDLoc(ST), Lo,
9440 Ptr, ST->getPointerInfo(),
9441 isVolatile, isNonTemporal,
9442 ST->getAlignment(), TBAAInfo);
9443 Ptr = DAG.getNode(ISD::ADD, SDLoc(N), Ptr.getValueType(), Ptr,
9444 DAG.getConstant(4, Ptr.getValueType()));
9445 Alignment = MinAlign(Alignment, 4U);
9446 SDValue St1 = DAG.getStore(Chain, SDLoc(ST), Hi,
9447 Ptr, ST->getPointerInfo().getWithOffset(4),
9448 isVolatile, isNonTemporal,
9449 Alignment, TBAAInfo);
9450 return DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other,
9459 // Try to infer better alignment information than the store already has.
9460 if (OptLevel != CodeGenOpt::None && ST->isUnindexed()) {
9461 if (unsigned Align = DAG.InferPtrAlignment(Ptr)) {
9462 if (Align > ST->getAlignment())
9463 return DAG.getTruncStore(Chain, SDLoc(N), Value,
9464 Ptr, ST->getPointerInfo(), ST->getMemoryVT(),
9465 ST->isVolatile(), ST->isNonTemporal(), Align,
9470 // Try transforming a pair floating point load / store ops to integer
9471 // load / store ops.
9472 SDValue NewST = TransformFPLoadStorePair(N);
9473 if (NewST.getNode())
9476 bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA :
9477 TLI.getTargetMachine().getSubtarget<TargetSubtargetInfo>().useAA();
9479 if (CombinerAAOnlyFunc.getNumOccurrences() &&
9480 CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
9483 if (UseAA && ST->isUnindexed()) {
9484 // Walk up chain skipping non-aliasing memory nodes.
9485 SDValue BetterChain = FindBetterChain(N, Chain);
9487 // If there is a better chain.
9488 if (Chain != BetterChain) {
9491 // Replace the chain to avoid dependency.
9492 if (ST->isTruncatingStore()) {
9493 ReplStore = DAG.getTruncStore(BetterChain, SDLoc(N), Value, Ptr,
9494 ST->getMemoryVT(), ST->getMemOperand());
9496 ReplStore = DAG.getStore(BetterChain, SDLoc(N), Value, Ptr,
9497 ST->getMemOperand());
9500 // Create token to keep both nodes around.
9501 SDValue Token = DAG.getNode(ISD::TokenFactor, SDLoc(N),
9502 MVT::Other, Chain, ReplStore);
9504 // Make sure the new and old chains are cleaned up.
9505 AddToWorkList(Token.getNode());
9507 // Don't add users to work list.
9508 return CombineTo(N, Token, false);
9512 // Try transforming N to an indexed store.
9513 if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
9514 return SDValue(N, 0);
9516 // FIXME: is there such a thing as a truncating indexed store?
9517 if (ST->isTruncatingStore() && ST->isUnindexed() &&
9518 Value.getValueType().isInteger()) {
9519 // See if we can simplify the input to this truncstore with knowledge that
9520 // only the low bits are being used. For example:
9521 // "truncstore (or (shl x, 8), y), i8" -> "truncstore y, i8"
9523 GetDemandedBits(Value,
9524 APInt::getLowBitsSet(
9525 Value.getValueType().getScalarType().getSizeInBits(),
9526 ST->getMemoryVT().getScalarType().getSizeInBits()));
9527 AddToWorkList(Value.getNode());
9528 if (Shorter.getNode())
9529 return DAG.getTruncStore(Chain, SDLoc(N), Shorter,
9530 Ptr, ST->getMemoryVT(), ST->getMemOperand());
9532 // Otherwise, see if we can simplify the operation with
9533 // SimplifyDemandedBits, which only works if the value has a single use.
9534 if (SimplifyDemandedBits(Value,
9535 APInt::getLowBitsSet(
9536 Value.getValueType().getScalarType().getSizeInBits(),
9537 ST->getMemoryVT().getScalarType().getSizeInBits())))
9538 return SDValue(N, 0);
9541 // If this is a load followed by a store to the same location, then the store
9543 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Value)) {
9544 if (Ld->getBasePtr() == Ptr && ST->getMemoryVT() == Ld->getMemoryVT() &&
9545 ST->isUnindexed() && !ST->isVolatile() &&
9546 // There can't be any side effects between the load and store, such as
9548 Chain.reachesChainWithoutSideEffects(SDValue(Ld, 1))) {
9549 // The store is dead, remove it.
9554 // If this is an FP_ROUND or TRUNC followed by a store, fold this into a
9555 // truncating store. We can do this even if this is already a truncstore.
9556 if ((Value.getOpcode() == ISD::FP_ROUND || Value.getOpcode() == ISD::TRUNCATE)
9557 && Value.getNode()->hasOneUse() && ST->isUnindexed() &&
9558 TLI.isTruncStoreLegal(Value.getOperand(0).getValueType(),
9559 ST->getMemoryVT())) {
9560 return DAG.getTruncStore(Chain, SDLoc(N), Value.getOperand(0),
9561 Ptr, ST->getMemoryVT(), ST->getMemOperand());
9564 // Only perform this optimization before the types are legal, because we
9565 // don't want to perform this optimization on every DAGCombine invocation.
9567 bool EverChanged = false;
9570 // There can be multiple store sequences on the same chain.
9571 // Keep trying to merge store sequences until we are unable to do so
9572 // or until we merge the last store on the chain.
9573 bool Changed = MergeConsecutiveStores(ST);
9574 EverChanged |= Changed;
9575 if (!Changed) break;
9576 } while (ST->getOpcode() != ISD::DELETED_NODE);
9579 return SDValue(N, 0);
9582 return ReduceLoadOpStoreWidth(N);
9585 SDValue DAGCombiner::visitINSERT_VECTOR_ELT(SDNode *N) {
9586 SDValue InVec = N->getOperand(0);
9587 SDValue InVal = N->getOperand(1);
9588 SDValue EltNo = N->getOperand(2);
9591 // If the inserted element is an UNDEF, just use the input vector.
9592 if (InVal.getOpcode() == ISD::UNDEF)
9595 EVT VT = InVec.getValueType();
9597 // If we can't generate a legal BUILD_VECTOR, exit
9598 if (LegalOperations && !TLI.isOperationLegal(ISD::BUILD_VECTOR, VT))
9601 // Check that we know which element is being inserted
9602 if (!isa<ConstantSDNode>(EltNo))
9604 unsigned Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
9606 // Check that the operand is a BUILD_VECTOR (or UNDEF, which can essentially
9607 // be converted to a BUILD_VECTOR). Fill in the Ops vector with the
9609 SmallVector<SDValue, 8> Ops;
9610 // Do not combine these two vectors if the output vector will not replace
9611 // the input vector.
9612 if (InVec.getOpcode() == ISD::BUILD_VECTOR && InVec.hasOneUse()) {
9613 Ops.append(InVec.getNode()->op_begin(),
9614 InVec.getNode()->op_end());
9615 } else if (InVec.getOpcode() == ISD::UNDEF) {
9616 unsigned NElts = VT.getVectorNumElements();
9617 Ops.append(NElts, DAG.getUNDEF(InVal.getValueType()));
9622 // Insert the element
9623 if (Elt < Ops.size()) {
9624 // All the operands of BUILD_VECTOR must have the same type;
9625 // we enforce that here.
9626 EVT OpVT = Ops[0].getValueType();
9627 if (InVal.getValueType() != OpVT)
9628 InVal = OpVT.bitsGT(InVal.getValueType()) ?
9629 DAG.getNode(ISD::ANY_EXTEND, dl, OpVT, InVal) :
9630 DAG.getNode(ISD::TRUNCATE, dl, OpVT, InVal);
9634 // Return the new vector
9635 return DAG.getNode(ISD::BUILD_VECTOR, dl,
9636 VT, &Ops[0], Ops.size());
9639 SDValue DAGCombiner::visitEXTRACT_VECTOR_ELT(SDNode *N) {
9640 // (vextract (scalar_to_vector val, 0) -> val
9641 SDValue InVec = N->getOperand(0);
9642 EVT VT = InVec.getValueType();
9643 EVT NVT = N->getValueType(0);
9645 if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR) {
9646 // Check if the result type doesn't match the inserted element type. A
9647 // SCALAR_TO_VECTOR may truncate the inserted element and the
9648 // EXTRACT_VECTOR_ELT may widen the extracted vector.
9649 SDValue InOp = InVec.getOperand(0);
9650 if (InOp.getValueType() != NVT) {
9651 assert(InOp.getValueType().isInteger() && NVT.isInteger());
9652 return DAG.getSExtOrTrunc(InOp, SDLoc(InVec), NVT);
9657 SDValue EltNo = N->getOperand(1);
9658 bool ConstEltNo = isa<ConstantSDNode>(EltNo);
9660 // Transform: (EXTRACT_VECTOR_ELT( VECTOR_SHUFFLE )) -> EXTRACT_VECTOR_ELT.
9661 // We only perform this optimization before the op legalization phase because
9662 // we may introduce new vector instructions which are not backed by TD
9663 // patterns. For example on AVX, extracting elements from a wide vector
9664 // without using extract_subvector.
9665 if (InVec.getOpcode() == ISD::VECTOR_SHUFFLE
9666 && ConstEltNo && !LegalOperations) {
9667 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
9668 int NumElem = VT.getVectorNumElements();
9669 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(InVec);
9670 // Find the new index to extract from.
9671 int OrigElt = SVOp->getMaskElt(Elt);
9673 // Extracting an undef index is undef.
9675 return DAG.getUNDEF(NVT);
9677 // Select the right vector half to extract from.
9678 if (OrigElt < NumElem) {
9679 InVec = InVec->getOperand(0);
9681 InVec = InVec->getOperand(1);
9685 EVT IndexTy = TLI.getVectorIdxTy();
9686 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SDLoc(N), NVT,
9687 InVec, DAG.getConstant(OrigElt, IndexTy));
9690 // Perform only after legalization to ensure build_vector / vector_shuffle
9691 // optimizations have already been done.
9692 if (!LegalOperations) return SDValue();
9694 // (vextract (v4f32 load $addr), c) -> (f32 load $addr+c*size)
9695 // (vextract (v4f32 s2v (f32 load $addr)), c) -> (f32 load $addr+c*size)
9696 // (vextract (v4f32 shuffle (load $addr), <1,u,u,u>), 0) -> (f32 load $addr)
9699 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
9700 bool NewLoad = false;
9701 bool BCNumEltsChanged = false;
9702 EVT ExtVT = VT.getVectorElementType();
9705 // If the result of load has to be truncated, then it's not necessarily
9707 if (NVT.bitsLT(LVT) && !TLI.isTruncateFree(LVT, NVT))
9710 if (InVec.getOpcode() == ISD::BITCAST) {
9711 // Don't duplicate a load with other uses.
9712 if (!InVec.hasOneUse())
9715 EVT BCVT = InVec.getOperand(0).getValueType();
9716 if (!BCVT.isVector() || ExtVT.bitsGT(BCVT.getVectorElementType()))
9718 if (VT.getVectorNumElements() != BCVT.getVectorNumElements())
9719 BCNumEltsChanged = true;
9720 InVec = InVec.getOperand(0);
9721 ExtVT = BCVT.getVectorElementType();
9725 LoadSDNode *LN0 = NULL;
9726 const ShuffleVectorSDNode *SVN = NULL;
9727 if (ISD::isNormalLoad(InVec.getNode())) {
9728 LN0 = cast<LoadSDNode>(InVec);
9729 } else if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR &&
9730 InVec.getOperand(0).getValueType() == ExtVT &&
9731 ISD::isNormalLoad(InVec.getOperand(0).getNode())) {
9732 // Don't duplicate a load with other uses.
9733 if (!InVec.hasOneUse())
9736 LN0 = cast<LoadSDNode>(InVec.getOperand(0));
9737 } else if ((SVN = dyn_cast<ShuffleVectorSDNode>(InVec))) {
9738 // (vextract (vector_shuffle (load $addr), v2, <1, u, u, u>), 1)
9740 // (load $addr+1*size)
9742 // Don't duplicate a load with other uses.
9743 if (!InVec.hasOneUse())
9746 // If the bit convert changed the number of elements, it is unsafe
9747 // to examine the mask.
9748 if (BCNumEltsChanged)
9751 // Select the input vector, guarding against out of range extract vector.
9752 unsigned NumElems = VT.getVectorNumElements();
9753 int Idx = (Elt > (int)NumElems) ? -1 : SVN->getMaskElt(Elt);
9754 InVec = (Idx < (int)NumElems) ? InVec.getOperand(0) : InVec.getOperand(1);
9756 if (InVec.getOpcode() == ISD::BITCAST) {
9757 // Don't duplicate a load with other uses.
9758 if (!InVec.hasOneUse())
9761 InVec = InVec.getOperand(0);
9763 if (ISD::isNormalLoad(InVec.getNode())) {
9764 LN0 = cast<LoadSDNode>(InVec);
9765 Elt = (Idx < (int)NumElems) ? Idx : Idx - (int)NumElems;
9769 // Make sure we found a non-volatile load and the extractelement is
9771 if (!LN0 || !LN0->hasNUsesOfValue(1,0) || LN0->isVolatile())
9774 // If Idx was -1 above, Elt is going to be -1, so just return undef.
9776 return DAG.getUNDEF(LVT);
9778 unsigned Align = LN0->getAlignment();
9780 // Check the resultant load doesn't need a higher alignment than the
9784 ->getABITypeAlignment(LVT.getTypeForEVT(*DAG.getContext()));
9786 if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, LVT))
9792 SDValue NewPtr = LN0->getBasePtr();
9793 unsigned PtrOff = 0;
9796 PtrOff = LVT.getSizeInBits() * Elt / 8;
9797 EVT PtrType = NewPtr.getValueType();
9798 if (TLI.isBigEndian())
9799 PtrOff = VT.getSizeInBits() / 8 - PtrOff;
9800 NewPtr = DAG.getNode(ISD::ADD, SDLoc(N), PtrType, NewPtr,
9801 DAG.getConstant(PtrOff, PtrType));
9804 // The replacement we need to do here is a little tricky: we need to
9805 // replace an extractelement of a load with a load.
9806 // Use ReplaceAllUsesOfValuesWith to do the replacement.
9807 // Note that this replacement assumes that the extractvalue is the only
9808 // use of the load; that's okay because we don't want to perform this
9809 // transformation in other cases anyway.
9812 if (NVT.bitsGT(LVT)) {
9813 // If the result type of vextract is wider than the load, then issue an
9814 // extending load instead.
9815 ISD::LoadExtType ExtType = TLI.isLoadExtLegal(ISD::ZEXTLOAD, LVT)
9816 ? ISD::ZEXTLOAD : ISD::EXTLOAD;
9817 Load = DAG.getExtLoad(ExtType, SDLoc(N), NVT, LN0->getChain(),
9818 NewPtr, LN0->getPointerInfo().getWithOffset(PtrOff),
9819 LVT, LN0->isVolatile(), LN0->isNonTemporal(),
9820 Align, LN0->getTBAAInfo());
9821 Chain = Load.getValue(1);
9823 Load = DAG.getLoad(LVT, SDLoc(N), LN0->getChain(), NewPtr,
9824 LN0->getPointerInfo().getWithOffset(PtrOff),
9825 LN0->isVolatile(), LN0->isNonTemporal(),
9826 LN0->isInvariant(), Align, LN0->getTBAAInfo());
9827 Chain = Load.getValue(1);
9828 if (NVT.bitsLT(LVT))
9829 Load = DAG.getNode(ISD::TRUNCATE, SDLoc(N), NVT, Load);
9831 Load = DAG.getNode(ISD::BITCAST, SDLoc(N), NVT, Load);
9833 WorkListRemover DeadNodes(*this);
9834 SDValue From[] = { SDValue(N, 0), SDValue(LN0,1) };
9835 SDValue To[] = { Load, Chain };
9836 DAG.ReplaceAllUsesOfValuesWith(From, To, 2);
9837 // Since we're explcitly calling ReplaceAllUses, add the new node to the
9838 // worklist explicitly as well.
9839 AddToWorkList(Load.getNode());
9840 AddUsersToWorkList(Load.getNode()); // Add users too
9841 // Make sure to revisit this node to clean it up; it will usually be dead.
9843 return SDValue(N, 0);
9849 // Simplify (build_vec (ext )) to (bitcast (build_vec ))
9850 SDValue DAGCombiner::reduceBuildVecExtToExtBuildVec(SDNode *N) {
9851 // We perform this optimization post type-legalization because
9852 // the type-legalizer often scalarizes integer-promoted vectors.
9853 // Performing this optimization before may create bit-casts which
9854 // will be type-legalized to complex code sequences.
9855 // We perform this optimization only before the operation legalizer because we
9856 // may introduce illegal operations.
9857 if (Level != AfterLegalizeVectorOps && Level != AfterLegalizeTypes)
9860 unsigned NumInScalars = N->getNumOperands();
9862 EVT VT = N->getValueType(0);
9864 // Check to see if this is a BUILD_VECTOR of a bunch of values
9865 // which come from any_extend or zero_extend nodes. If so, we can create
9866 // a new BUILD_VECTOR using bit-casts which may enable other BUILD_VECTOR
9867 // optimizations. We do not handle sign-extend because we can't fill the sign
9869 EVT SourceType = MVT::Other;
9870 bool AllAnyExt = true;
9872 for (unsigned i = 0; i != NumInScalars; ++i) {
9873 SDValue In = N->getOperand(i);
9874 // Ignore undef inputs.
9875 if (In.getOpcode() == ISD::UNDEF) continue;
9877 bool AnyExt = In.getOpcode() == ISD::ANY_EXTEND;
9878 bool ZeroExt = In.getOpcode() == ISD::ZERO_EXTEND;
9880 // Abort if the element is not an extension.
9881 if (!ZeroExt && !AnyExt) {
9882 SourceType = MVT::Other;
9886 // The input is a ZeroExt or AnyExt. Check the original type.
9887 EVT InTy = In.getOperand(0).getValueType();
9889 // Check that all of the widened source types are the same.
9890 if (SourceType == MVT::Other)
9893 else if (InTy != SourceType) {
9894 // Multiple income types. Abort.
9895 SourceType = MVT::Other;
9899 // Check if all of the extends are ANY_EXTENDs.
9900 AllAnyExt &= AnyExt;
9903 // In order to have valid types, all of the inputs must be extended from the
9904 // same source type and all of the inputs must be any or zero extend.
9905 // Scalar sizes must be a power of two.
9906 EVT OutScalarTy = VT.getScalarType();
9907 bool ValidTypes = SourceType != MVT::Other &&
9908 isPowerOf2_32(OutScalarTy.getSizeInBits()) &&
9909 isPowerOf2_32(SourceType.getSizeInBits());
9911 // Create a new simpler BUILD_VECTOR sequence which other optimizations can
9912 // turn into a single shuffle instruction.
9916 bool isLE = TLI.isLittleEndian();
9917 unsigned ElemRatio = OutScalarTy.getSizeInBits()/SourceType.getSizeInBits();
9918 assert(ElemRatio > 1 && "Invalid element size ratio");
9919 SDValue Filler = AllAnyExt ? DAG.getUNDEF(SourceType):
9920 DAG.getConstant(0, SourceType);
9922 unsigned NewBVElems = ElemRatio * VT.getVectorNumElements();
9923 SmallVector<SDValue, 8> Ops(NewBVElems, Filler);
9925 // Populate the new build_vector
9926 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
9927 SDValue Cast = N->getOperand(i);
9928 assert((Cast.getOpcode() == ISD::ANY_EXTEND ||
9929 Cast.getOpcode() == ISD::ZERO_EXTEND ||
9930 Cast.getOpcode() == ISD::UNDEF) && "Invalid cast opcode");
9932 if (Cast.getOpcode() == ISD::UNDEF)
9933 In = DAG.getUNDEF(SourceType);
9935 In = Cast->getOperand(0);
9936 unsigned Index = isLE ? (i * ElemRatio) :
9937 (i * ElemRatio + (ElemRatio - 1));
9939 assert(Index < Ops.size() && "Invalid index");
9943 // The type of the new BUILD_VECTOR node.
9944 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), SourceType, NewBVElems);
9945 assert(VecVT.getSizeInBits() == VT.getSizeInBits() &&
9946 "Invalid vector size");
9947 // Check if the new vector type is legal.
9948 if (!isTypeLegal(VecVT)) return SDValue();
9950 // Make the new BUILD_VECTOR.
9951 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, VecVT, &Ops[0], Ops.size());
9953 // The new BUILD_VECTOR node has the potential to be further optimized.
9954 AddToWorkList(BV.getNode());
9955 // Bitcast to the desired type.
9956 return DAG.getNode(ISD::BITCAST, dl, VT, BV);
9959 SDValue DAGCombiner::reduceBuildVecConvertToConvertBuildVec(SDNode *N) {
9960 EVT VT = N->getValueType(0);
9962 unsigned NumInScalars = N->getNumOperands();
9965 EVT SrcVT = MVT::Other;
9966 unsigned Opcode = ISD::DELETED_NODE;
9967 unsigned NumDefs = 0;
9969 for (unsigned i = 0; i != NumInScalars; ++i) {
9970 SDValue In = N->getOperand(i);
9971 unsigned Opc = In.getOpcode();
9973 if (Opc == ISD::UNDEF)
9976 // If all scalar values are floats and converted from integers.
9977 if (Opcode == ISD::DELETED_NODE &&
9978 (Opc == ISD::UINT_TO_FP || Opc == ISD::SINT_TO_FP)) {
9985 EVT InVT = In.getOperand(0).getValueType();
9987 // If all scalar values are typed differently, bail out. It's chosen to
9988 // simplify BUILD_VECTOR of integer types.
9989 if (SrcVT == MVT::Other)
9996 // If the vector has just one element defined, it's not worth to fold it into
9997 // a vectorized one.
10001 assert((Opcode == ISD::UINT_TO_FP || Opcode == ISD::SINT_TO_FP)
10002 && "Should only handle conversion from integer to float.");
10003 assert(SrcVT != MVT::Other && "Cannot determine source type!");
10005 EVT NVT = EVT::getVectorVT(*DAG.getContext(), SrcVT, NumInScalars);
10007 if (!TLI.isOperationLegalOrCustom(Opcode, NVT))
10010 SmallVector<SDValue, 8> Opnds;
10011 for (unsigned i = 0; i != NumInScalars; ++i) {
10012 SDValue In = N->getOperand(i);
10014 if (In.getOpcode() == ISD::UNDEF)
10015 Opnds.push_back(DAG.getUNDEF(SrcVT));
10017 Opnds.push_back(In.getOperand(0));
10019 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, NVT,
10020 &Opnds[0], Opnds.size());
10021 AddToWorkList(BV.getNode());
10023 return DAG.getNode(Opcode, dl, VT, BV);
10026 SDValue DAGCombiner::visitBUILD_VECTOR(SDNode *N) {
10027 unsigned NumInScalars = N->getNumOperands();
10029 EVT VT = N->getValueType(0);
10031 // A vector built entirely of undefs is undef.
10032 if (ISD::allOperandsUndef(N))
10033 return DAG.getUNDEF(VT);
10035 SDValue V = reduceBuildVecExtToExtBuildVec(N);
10039 V = reduceBuildVecConvertToConvertBuildVec(N);
10043 // Check to see if this is a BUILD_VECTOR of a bunch of EXTRACT_VECTOR_ELT
10044 // operations. If so, and if the EXTRACT_VECTOR_ELT vector inputs come from
10045 // at most two distinct vectors, turn this into a shuffle node.
10047 // May only combine to shuffle after legalize if shuffle is legal.
10048 if (LegalOperations &&
10049 !TLI.isOperationLegalOrCustom(ISD::VECTOR_SHUFFLE, VT))
10052 SDValue VecIn1, VecIn2;
10053 for (unsigned i = 0; i != NumInScalars; ++i) {
10054 // Ignore undef inputs.
10055 if (N->getOperand(i).getOpcode() == ISD::UNDEF) continue;
10057 // If this input is something other than a EXTRACT_VECTOR_ELT with a
10058 // constant index, bail out.
10059 if (N->getOperand(i).getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
10060 !isa<ConstantSDNode>(N->getOperand(i).getOperand(1))) {
10061 VecIn1 = VecIn2 = SDValue(0, 0);
10065 // We allow up to two distinct input vectors.
10066 SDValue ExtractedFromVec = N->getOperand(i).getOperand(0);
10067 if (ExtractedFromVec == VecIn1 || ExtractedFromVec == VecIn2)
10070 if (VecIn1.getNode() == 0) {
10071 VecIn1 = ExtractedFromVec;
10072 } else if (VecIn2.getNode() == 0) {
10073 VecIn2 = ExtractedFromVec;
10075 // Too many inputs.
10076 VecIn1 = VecIn2 = SDValue(0, 0);
10081 // If everything is good, we can make a shuffle operation.
10082 if (VecIn1.getNode()) {
10083 SmallVector<int, 8> Mask;
10084 for (unsigned i = 0; i != NumInScalars; ++i) {
10085 if (N->getOperand(i).getOpcode() == ISD::UNDEF) {
10086 Mask.push_back(-1);
10090 // If extracting from the first vector, just use the index directly.
10091 SDValue Extract = N->getOperand(i);
10092 SDValue ExtVal = Extract.getOperand(1);
10093 if (Extract.getOperand(0) == VecIn1) {
10094 unsigned ExtIndex = cast<ConstantSDNode>(ExtVal)->getZExtValue();
10095 if (ExtIndex > VT.getVectorNumElements())
10098 Mask.push_back(ExtIndex);
10102 // Otherwise, use InIdx + VecSize
10103 unsigned Idx = cast<ConstantSDNode>(ExtVal)->getZExtValue();
10104 Mask.push_back(Idx+NumInScalars);
10107 // We can't generate a shuffle node with mismatched input and output types.
10108 // Attempt to transform a single input vector to the correct type.
10109 if ((VT != VecIn1.getValueType())) {
10110 // We don't support shuffeling between TWO values of different types.
10111 if (VecIn2.getNode() != 0)
10114 // We only support widening of vectors which are half the size of the
10115 // output registers. For example XMM->YMM widening on X86 with AVX.
10116 if (VecIn1.getValueType().getSizeInBits()*2 != VT.getSizeInBits())
10119 // If the input vector type has a different base type to the output
10120 // vector type, bail out.
10121 if (VecIn1.getValueType().getVectorElementType() !=
10122 VT.getVectorElementType())
10125 // Widen the input vector by adding undef values.
10126 VecIn1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
10127 VecIn1, DAG.getUNDEF(VecIn1.getValueType()));
10130 // If VecIn2 is unused then change it to undef.
10131 VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(VT);
10133 // Check that we were able to transform all incoming values to the same
10135 if (VecIn2.getValueType() != VecIn1.getValueType() ||
10136 VecIn1.getValueType() != VT)
10139 // Only type-legal BUILD_VECTOR nodes are converted to shuffle nodes.
10140 if (!isTypeLegal(VT))
10143 // Return the new VECTOR_SHUFFLE node.
10147 return DAG.getVectorShuffle(VT, dl, Ops[0], Ops[1], &Mask[0]);
10153 SDValue DAGCombiner::visitCONCAT_VECTORS(SDNode *N) {
10154 // TODO: Check to see if this is a CONCAT_VECTORS of a bunch of
10155 // EXTRACT_SUBVECTOR operations. If so, and if the EXTRACT_SUBVECTOR vector
10156 // inputs come from at most two distinct vectors, turn this into a shuffle
10159 // If we only have one input vector, we don't need to do any concatenation.
10160 if (N->getNumOperands() == 1)
10161 return N->getOperand(0);
10163 // Check if all of the operands are undefs.
10164 EVT VT = N->getValueType(0);
10165 if (ISD::allOperandsUndef(N))
10166 return DAG.getUNDEF(VT);
10168 // Optimize concat_vectors where one of the vectors is undef.
10169 if (N->getNumOperands() == 2 &&
10170 N->getOperand(1)->getOpcode() == ISD::UNDEF) {
10171 SDValue In = N->getOperand(0);
10172 assert(In.getValueType().isVector() && "Must concat vectors");
10174 // Transform: concat_vectors(scalar, undef) -> scalar_to_vector(sclr).
10175 if (In->getOpcode() == ISD::BITCAST &&
10176 !In->getOperand(0)->getValueType(0).isVector()) {
10177 SDValue Scalar = In->getOperand(0);
10178 EVT SclTy = Scalar->getValueType(0);
10180 if (!SclTy.isFloatingPoint() && !SclTy.isInteger())
10183 EVT NVT = EVT::getVectorVT(*DAG.getContext(), SclTy,
10184 VT.getSizeInBits() / SclTy.getSizeInBits());
10185 if (!TLI.isTypeLegal(NVT) || !TLI.isTypeLegal(Scalar.getValueType()))
10188 SDLoc dl = SDLoc(N);
10189 SDValue Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, NVT, Scalar);
10190 return DAG.getNode(ISD::BITCAST, dl, VT, Res);
10194 // fold (concat_vectors (BUILD_VECTOR A, B, ...), (BUILD_VECTOR C, D, ...))
10195 // -> (BUILD_VECTOR A, B, ..., C, D, ...)
10196 if (N->getNumOperands() == 2 &&
10197 N->getOperand(0).getOpcode() == ISD::BUILD_VECTOR &&
10198 N->getOperand(1).getOpcode() == ISD::BUILD_VECTOR) {
10199 EVT VT = N->getValueType(0);
10200 SDValue N0 = N->getOperand(0);
10201 SDValue N1 = N->getOperand(1);
10202 SmallVector<SDValue, 8> Opnds;
10203 unsigned BuildVecNumElts = N0.getNumOperands();
10205 for (unsigned i = 0; i != BuildVecNumElts; ++i)
10206 Opnds.push_back(N0.getOperand(i));
10207 for (unsigned i = 0; i != BuildVecNumElts; ++i)
10208 Opnds.push_back(N1.getOperand(i));
10210 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, &Opnds[0],
10214 // Type legalization of vectors and DAG canonicalization of SHUFFLE_VECTOR
10215 // nodes often generate nop CONCAT_VECTOR nodes.
10216 // Scan the CONCAT_VECTOR operands and look for a CONCAT operations that
10217 // place the incoming vectors at the exact same location.
10218 SDValue SingleSource = SDValue();
10219 unsigned PartNumElem = N->getOperand(0).getValueType().getVectorNumElements();
10221 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
10222 SDValue Op = N->getOperand(i);
10224 if (Op.getOpcode() == ISD::UNDEF)
10227 // Check if this is the identity extract:
10228 if (Op.getOpcode() != ISD::EXTRACT_SUBVECTOR)
10231 // Find the single incoming vector for the extract_subvector.
10232 if (SingleSource.getNode()) {
10233 if (Op.getOperand(0) != SingleSource)
10236 SingleSource = Op.getOperand(0);
10238 // Check the source type is the same as the type of the result.
10239 // If not, this concat may extend the vector, so we can not
10240 // optimize it away.
10241 if (SingleSource.getValueType() != N->getValueType(0))
10245 unsigned IdentityIndex = i * PartNumElem;
10246 ConstantSDNode *CS = dyn_cast<ConstantSDNode>(Op.getOperand(1));
10247 // The extract index must be constant.
10251 // Check that we are reading from the identity index.
10252 if (CS->getZExtValue() != IdentityIndex)
10256 if (SingleSource.getNode())
10257 return SingleSource;
10262 SDValue DAGCombiner::visitEXTRACT_SUBVECTOR(SDNode* N) {
10263 EVT NVT = N->getValueType(0);
10264 SDValue V = N->getOperand(0);
10266 if (V->getOpcode() == ISD::CONCAT_VECTORS) {
10268 // (extract_subvec (concat V1, V2, ...), i)
10271 // Only operand 0 is checked as 'concat' assumes all inputs of the same
10273 if (V->getOperand(0).getValueType() != NVT)
10275 unsigned Idx = dyn_cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
10276 unsigned NumElems = NVT.getVectorNumElements();
10277 assert((Idx % NumElems) == 0 &&
10278 "IDX in concat is not a multiple of the result vector length.");
10279 return V->getOperand(Idx / NumElems);
10283 if (V->getOpcode() == ISD::BITCAST)
10284 V = V.getOperand(0);
10286 if (V->getOpcode() == ISD::INSERT_SUBVECTOR) {
10288 // Handle only simple case where vector being inserted and vector
10289 // being extracted are of same type, and are half size of larger vectors.
10290 EVT BigVT = V->getOperand(0).getValueType();
10291 EVT SmallVT = V->getOperand(1).getValueType();
10292 if (!NVT.bitsEq(SmallVT) || NVT.getSizeInBits()*2 != BigVT.getSizeInBits())
10295 // Only handle cases where both indexes are constants with the same type.
10296 ConstantSDNode *ExtIdx = dyn_cast<ConstantSDNode>(N->getOperand(1));
10297 ConstantSDNode *InsIdx = dyn_cast<ConstantSDNode>(V->getOperand(2));
10299 if (InsIdx && ExtIdx &&
10300 InsIdx->getValueType(0).getSizeInBits() <= 64 &&
10301 ExtIdx->getValueType(0).getSizeInBits() <= 64) {
10303 // (extract_subvec (insert_subvec V1, V2, InsIdx), ExtIdx)
10305 // indices are equal or bit offsets are equal => V1
10306 // otherwise => (extract_subvec V1, ExtIdx)
10307 if (InsIdx->getZExtValue() * SmallVT.getScalarType().getSizeInBits() ==
10308 ExtIdx->getZExtValue() * NVT.getScalarType().getSizeInBits())
10309 return DAG.getNode(ISD::BITCAST, dl, NVT, V->getOperand(1));
10310 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, NVT,
10311 DAG.getNode(ISD::BITCAST, dl,
10312 N->getOperand(0).getValueType(),
10313 V->getOperand(0)), N->getOperand(1));
10320 // Tries to turn a shuffle of two CONCAT_VECTORS into a single concat.
10321 static SDValue partitionShuffleOfConcats(SDNode *N, SelectionDAG &DAG) {
10322 EVT VT = N->getValueType(0);
10323 unsigned NumElts = VT.getVectorNumElements();
10325 SDValue N0 = N->getOperand(0);
10326 SDValue N1 = N->getOperand(1);
10327 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
10329 SmallVector<SDValue, 4> Ops;
10330 EVT ConcatVT = N0.getOperand(0).getValueType();
10331 unsigned NumElemsPerConcat = ConcatVT.getVectorNumElements();
10332 unsigned NumConcats = NumElts / NumElemsPerConcat;
10334 // Look at every vector that's inserted. We're looking for exact
10335 // subvector-sized copies from a concatenated vector
10336 for (unsigned I = 0; I != NumConcats; ++I) {
10337 // Make sure we're dealing with a copy.
10338 unsigned Begin = I * NumElemsPerConcat;
10339 bool AllUndef = true, NoUndef = true;
10340 for (unsigned J = Begin; J != Begin + NumElemsPerConcat; ++J) {
10341 if (SVN->getMaskElt(J) >= 0)
10348 if (SVN->getMaskElt(Begin) % NumElemsPerConcat != 0)
10351 for (unsigned J = 1; J != NumElemsPerConcat; ++J)
10352 if (SVN->getMaskElt(Begin + J - 1) + 1 != SVN->getMaskElt(Begin + J))
10355 unsigned FirstElt = SVN->getMaskElt(Begin) / NumElemsPerConcat;
10356 if (FirstElt < N0.getNumOperands())
10357 Ops.push_back(N0.getOperand(FirstElt));
10359 Ops.push_back(N1.getOperand(FirstElt - N0.getNumOperands()));
10361 } else if (AllUndef) {
10362 Ops.push_back(DAG.getUNDEF(N0.getOperand(0).getValueType()));
10363 } else { // Mixed with general masks and undefs, can't do optimization.
10368 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Ops.data(),
10372 SDValue DAGCombiner::visitVECTOR_SHUFFLE(SDNode *N) {
10373 EVT VT = N->getValueType(0);
10374 unsigned NumElts = VT.getVectorNumElements();
10376 SDValue N0 = N->getOperand(0);
10377 SDValue N1 = N->getOperand(1);
10379 assert(N0.getValueType() == VT && "Vector shuffle must be normalized in DAG");
10381 // Canonicalize shuffle undef, undef -> undef
10382 if (N0.getOpcode() == ISD::UNDEF && N1.getOpcode() == ISD::UNDEF)
10383 return DAG.getUNDEF(VT);
10385 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
10387 // Canonicalize shuffle v, v -> v, undef
10389 SmallVector<int, 8> NewMask;
10390 for (unsigned i = 0; i != NumElts; ++i) {
10391 int Idx = SVN->getMaskElt(i);
10392 if (Idx >= (int)NumElts) Idx -= NumElts;
10393 NewMask.push_back(Idx);
10395 return DAG.getVectorShuffle(VT, SDLoc(N), N0, DAG.getUNDEF(VT),
10399 // Canonicalize shuffle undef, v -> v, undef. Commute the shuffle mask.
10400 if (N0.getOpcode() == ISD::UNDEF) {
10401 SmallVector<int, 8> NewMask;
10402 for (unsigned i = 0; i != NumElts; ++i) {
10403 int Idx = SVN->getMaskElt(i);
10405 if (Idx >= (int)NumElts)
10408 Idx = -1; // remove reference to lhs
10410 NewMask.push_back(Idx);
10412 return DAG.getVectorShuffle(VT, SDLoc(N), N1, DAG.getUNDEF(VT),
10416 // Remove references to rhs if it is undef
10417 if (N1.getOpcode() == ISD::UNDEF) {
10418 bool Changed = false;
10419 SmallVector<int, 8> NewMask;
10420 for (unsigned i = 0; i != NumElts; ++i) {
10421 int Idx = SVN->getMaskElt(i);
10422 if (Idx >= (int)NumElts) {
10426 NewMask.push_back(Idx);
10429 return DAG.getVectorShuffle(VT, SDLoc(N), N0, N1, &NewMask[0]);
10432 // If it is a splat, check if the argument vector is another splat or a
10433 // build_vector with all scalar elements the same.
10434 if (SVN->isSplat() && SVN->getSplatIndex() < (int)NumElts) {
10435 SDNode *V = N0.getNode();
10437 // If this is a bit convert that changes the element type of the vector but
10438 // not the number of vector elements, look through it. Be careful not to
10439 // look though conversions that change things like v4f32 to v2f64.
10440 if (V->getOpcode() == ISD::BITCAST) {
10441 SDValue ConvInput = V->getOperand(0);
10442 if (ConvInput.getValueType().isVector() &&
10443 ConvInput.getValueType().getVectorNumElements() == NumElts)
10444 V = ConvInput.getNode();
10447 if (V->getOpcode() == ISD::BUILD_VECTOR) {
10448 assert(V->getNumOperands() == NumElts &&
10449 "BUILD_VECTOR has wrong number of operands");
10451 bool AllSame = true;
10452 for (unsigned i = 0; i != NumElts; ++i) {
10453 if (V->getOperand(i).getOpcode() != ISD::UNDEF) {
10454 Base = V->getOperand(i);
10458 // Splat of <u, u, u, u>, return <u, u, u, u>
10459 if (!Base.getNode())
10461 for (unsigned i = 0; i != NumElts; ++i) {
10462 if (V->getOperand(i) != Base) {
10467 // Splat of <x, x, x, x>, return <x, x, x, x>
10473 if (N0.getOpcode() == ISD::CONCAT_VECTORS &&
10474 Level < AfterLegalizeVectorOps &&
10475 (N1.getOpcode() == ISD::UNDEF ||
10476 (N1.getOpcode() == ISD::CONCAT_VECTORS &&
10477 N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType()))) {
10478 SDValue V = partitionShuffleOfConcats(N, DAG);
10484 // If this shuffle node is simply a swizzle of another shuffle node,
10485 // and it reverses the swizzle of the previous shuffle then we can
10486 // optimize shuffle(shuffle(x, undef), undef) -> x.
10487 if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG &&
10488 N1.getOpcode() == ISD::UNDEF) {
10490 ShuffleVectorSDNode *OtherSV = cast<ShuffleVectorSDNode>(N0);
10492 // Shuffle nodes can only reverse shuffles with a single non-undef value.
10493 if (N0.getOperand(1).getOpcode() != ISD::UNDEF)
10496 // The incoming shuffle must be of the same type as the result of the
10497 // current shuffle.
10498 assert(OtherSV->getOperand(0).getValueType() == VT &&
10499 "Shuffle types don't match");
10501 for (unsigned i = 0; i != NumElts; ++i) {
10502 int Idx = SVN->getMaskElt(i);
10503 assert(Idx < (int)NumElts && "Index references undef operand");
10504 // Next, this index comes from the first value, which is the incoming
10505 // shuffle. Adopt the incoming index.
10507 Idx = OtherSV->getMaskElt(Idx);
10509 // The combined shuffle must map each index to itself.
10510 if (Idx >= 0 && (unsigned)Idx != i)
10514 return OtherSV->getOperand(0);
10520 SDValue DAGCombiner::visitINSERT_SUBVECTOR(SDNode *N) {
10521 SDValue N0 = N->getOperand(0);
10522 SDValue N2 = N->getOperand(2);
10524 // If the input vector is a concatenation, and the insert replaces
10525 // one of the halves, we can optimize into a single concat_vectors.
10526 if (N0.getOpcode() == ISD::CONCAT_VECTORS &&
10527 N0->getNumOperands() == 2 && N2.getOpcode() == ISD::Constant) {
10528 APInt InsIdx = cast<ConstantSDNode>(N2)->getAPIntValue();
10529 EVT VT = N->getValueType(0);
10531 // Lower half: fold (insert_subvector (concat_vectors X, Y), Z) ->
10532 // (concat_vectors Z, Y)
10534 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
10535 N->getOperand(1), N0.getOperand(1));
10537 // Upper half: fold (insert_subvector (concat_vectors X, Y), Z) ->
10538 // (concat_vectors X, Z)
10539 if (InsIdx == VT.getVectorNumElements()/2)
10540 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
10541 N0.getOperand(0), N->getOperand(1));
10547 /// XformToShuffleWithZero - Returns a vector_shuffle if it able to transform
10548 /// an AND to a vector_shuffle with the destination vector and a zero vector.
10549 /// e.g. AND V, <0xffffffff, 0, 0xffffffff, 0>. ==>
10550 /// vector_shuffle V, Zero, <0, 4, 2, 4>
10551 SDValue DAGCombiner::XformToShuffleWithZero(SDNode *N) {
10552 EVT VT = N->getValueType(0);
10554 SDValue LHS = N->getOperand(0);
10555 SDValue RHS = N->getOperand(1);
10556 if (N->getOpcode() == ISD::AND) {
10557 if (RHS.getOpcode() == ISD::BITCAST)
10558 RHS = RHS.getOperand(0);
10559 if (RHS.getOpcode() == ISD::BUILD_VECTOR) {
10560 SmallVector<int, 8> Indices;
10561 unsigned NumElts = RHS.getNumOperands();
10562 for (unsigned i = 0; i != NumElts; ++i) {
10563 SDValue Elt = RHS.getOperand(i);
10564 if (!isa<ConstantSDNode>(Elt))
10567 if (cast<ConstantSDNode>(Elt)->isAllOnesValue())
10568 Indices.push_back(i);
10569 else if (cast<ConstantSDNode>(Elt)->isNullValue())
10570 Indices.push_back(NumElts);
10575 // Let's see if the target supports this vector_shuffle.
10576 EVT RVT = RHS.getValueType();
10577 if (!TLI.isVectorClearMaskLegal(Indices, RVT))
10580 // Return the new VECTOR_SHUFFLE node.
10581 EVT EltVT = RVT.getVectorElementType();
10582 SmallVector<SDValue,8> ZeroOps(RVT.getVectorNumElements(),
10583 DAG.getConstant(0, EltVT));
10584 SDValue Zero = DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N),
10585 RVT, &ZeroOps[0], ZeroOps.size());
10586 LHS = DAG.getNode(ISD::BITCAST, dl, RVT, LHS);
10587 SDValue Shuf = DAG.getVectorShuffle(RVT, dl, LHS, Zero, &Indices[0]);
10588 return DAG.getNode(ISD::BITCAST, dl, VT, Shuf);
10595 /// SimplifyVBinOp - Visit a binary vector operation, like ADD.
10596 SDValue DAGCombiner::SimplifyVBinOp(SDNode *N) {
10597 assert(N->getValueType(0).isVector() &&
10598 "SimplifyVBinOp only works on vectors!");
10600 SDValue LHS = N->getOperand(0);
10601 SDValue RHS = N->getOperand(1);
10602 SDValue Shuffle = XformToShuffleWithZero(N);
10603 if (Shuffle.getNode()) return Shuffle;
10605 // If the LHS and RHS are BUILD_VECTOR nodes, see if we can constant fold
10607 if (LHS.getOpcode() == ISD::BUILD_VECTOR &&
10608 RHS.getOpcode() == ISD::BUILD_VECTOR) {
10609 // Check if both vectors are constants. If not bail out.
10610 if (!(cast<BuildVectorSDNode>(LHS)->isConstant() &&
10611 cast<BuildVectorSDNode>(RHS)->isConstant()))
10614 SmallVector<SDValue, 8> Ops;
10615 for (unsigned i = 0, e = LHS.getNumOperands(); i != e; ++i) {
10616 SDValue LHSOp = LHS.getOperand(i);
10617 SDValue RHSOp = RHS.getOperand(i);
10619 // Can't fold divide by zero.
10620 if (N->getOpcode() == ISD::SDIV || N->getOpcode() == ISD::UDIV ||
10621 N->getOpcode() == ISD::FDIV) {
10622 if ((RHSOp.getOpcode() == ISD::Constant &&
10623 cast<ConstantSDNode>(RHSOp.getNode())->isNullValue()) ||
10624 (RHSOp.getOpcode() == ISD::ConstantFP &&
10625 cast<ConstantFPSDNode>(RHSOp.getNode())->getValueAPF().isZero()))
10629 EVT VT = LHSOp.getValueType();
10630 EVT RVT = RHSOp.getValueType();
10632 // Integer BUILD_VECTOR operands may have types larger than the element
10633 // size (e.g., when the element type is not legal). Prior to type
10634 // legalization, the types may not match between the two BUILD_VECTORS.
10635 // Truncate one of the operands to make them match.
10636 if (RVT.getSizeInBits() > VT.getSizeInBits()) {
10637 RHSOp = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, RHSOp);
10639 LHSOp = DAG.getNode(ISD::TRUNCATE, SDLoc(N), RVT, LHSOp);
10643 SDValue FoldOp = DAG.getNode(N->getOpcode(), SDLoc(LHS), VT,
10645 if (FoldOp.getOpcode() != ISD::UNDEF &&
10646 FoldOp.getOpcode() != ISD::Constant &&
10647 FoldOp.getOpcode() != ISD::ConstantFP)
10649 Ops.push_back(FoldOp);
10650 AddToWorkList(FoldOp.getNode());
10653 if (Ops.size() == LHS.getNumOperands())
10654 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N),
10655 LHS.getValueType(), &Ops[0], Ops.size());
10661 /// SimplifyVUnaryOp - Visit a binary vector operation, like FABS/FNEG.
10662 SDValue DAGCombiner::SimplifyVUnaryOp(SDNode *N) {
10663 assert(N->getValueType(0).isVector() &&
10664 "SimplifyVUnaryOp only works on vectors!");
10666 SDValue N0 = N->getOperand(0);
10668 if (N0.getOpcode() != ISD::BUILD_VECTOR)
10671 // Operand is a BUILD_VECTOR node, see if we can constant fold it.
10672 SmallVector<SDValue, 8> Ops;
10673 for (unsigned i = 0, e = N0.getNumOperands(); i != e; ++i) {
10674 SDValue Op = N0.getOperand(i);
10675 if (Op.getOpcode() != ISD::UNDEF &&
10676 Op.getOpcode() != ISD::ConstantFP)
10678 EVT EltVT = Op.getValueType();
10679 SDValue FoldOp = DAG.getNode(N->getOpcode(), SDLoc(N0), EltVT, Op);
10680 if (FoldOp.getOpcode() != ISD::UNDEF &&
10681 FoldOp.getOpcode() != ISD::ConstantFP)
10683 Ops.push_back(FoldOp);
10684 AddToWorkList(FoldOp.getNode());
10687 if (Ops.size() != N0.getNumOperands())
10690 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N),
10691 N0.getValueType(), &Ops[0], Ops.size());
10694 SDValue DAGCombiner::SimplifySelect(SDLoc DL, SDValue N0,
10695 SDValue N1, SDValue N2){
10696 assert(N0.getOpcode() ==ISD::SETCC && "First argument must be a SetCC node!");
10698 SDValue SCC = SimplifySelectCC(DL, N0.getOperand(0), N0.getOperand(1), N1, N2,
10699 cast<CondCodeSDNode>(N0.getOperand(2))->get());
10701 // If we got a simplified select_cc node back from SimplifySelectCC, then
10702 // break it down into a new SETCC node, and a new SELECT node, and then return
10703 // the SELECT node, since we were called with a SELECT node.
10704 if (SCC.getNode()) {
10705 // Check to see if we got a select_cc back (to turn into setcc/select).
10706 // Otherwise, just return whatever node we got back, like fabs.
10707 if (SCC.getOpcode() == ISD::SELECT_CC) {
10708 SDValue SETCC = DAG.getNode(ISD::SETCC, SDLoc(N0),
10710 SCC.getOperand(0), SCC.getOperand(1),
10711 SCC.getOperand(4));
10712 AddToWorkList(SETCC.getNode());
10713 return DAG.getSelect(SDLoc(SCC), SCC.getValueType(),
10714 SCC.getOperand(2), SCC.getOperand(3), SETCC);
10722 /// SimplifySelectOps - Given a SELECT or a SELECT_CC node, where LHS and RHS
10723 /// are the two values being selected between, see if we can simplify the
10724 /// select. Callers of this should assume that TheSelect is deleted if this
10725 /// returns true. As such, they should return the appropriate thing (e.g. the
10726 /// node) back to the top-level of the DAG combiner loop to avoid it being
10728 bool DAGCombiner::SimplifySelectOps(SDNode *TheSelect, SDValue LHS,
10731 // Cannot simplify select with vector condition
10732 if (TheSelect->getOperand(0).getValueType().isVector()) return false;
10734 // If this is a select from two identical things, try to pull the operation
10735 // through the select.
10736 if (LHS.getOpcode() != RHS.getOpcode() ||
10737 !LHS.hasOneUse() || !RHS.hasOneUse())
10740 // If this is a load and the token chain is identical, replace the select
10741 // of two loads with a load through a select of the address to load from.
10742 // This triggers in things like "select bool X, 10.0, 123.0" after the FP
10743 // constants have been dropped into the constant pool.
10744 if (LHS.getOpcode() == ISD::LOAD) {
10745 LoadSDNode *LLD = cast<LoadSDNode>(LHS);
10746 LoadSDNode *RLD = cast<LoadSDNode>(RHS);
10748 // Token chains must be identical.
10749 if (LHS.getOperand(0) != RHS.getOperand(0) ||
10750 // Do not let this transformation reduce the number of volatile loads.
10751 LLD->isVolatile() || RLD->isVolatile() ||
10752 // If this is an EXTLOAD, the VT's must match.
10753 LLD->getMemoryVT() != RLD->getMemoryVT() ||
10754 // If this is an EXTLOAD, the kind of extension must match.
10755 (LLD->getExtensionType() != RLD->getExtensionType() &&
10756 // The only exception is if one of the extensions is anyext.
10757 LLD->getExtensionType() != ISD::EXTLOAD &&
10758 RLD->getExtensionType() != ISD::EXTLOAD) ||
10759 // FIXME: this discards src value information. This is
10760 // over-conservative. It would be beneficial to be able to remember
10761 // both potential memory locations. Since we are discarding
10762 // src value info, don't do the transformation if the memory
10763 // locations are not in the default address space.
10764 LLD->getPointerInfo().getAddrSpace() != 0 ||
10765 RLD->getPointerInfo().getAddrSpace() != 0 ||
10766 !TLI.isOperationLegalOrCustom(TheSelect->getOpcode(),
10767 LLD->getBasePtr().getValueType()))
10770 // Check that the select condition doesn't reach either load. If so,
10771 // folding this will induce a cycle into the DAG. If not, this is safe to
10772 // xform, so create a select of the addresses.
10774 if (TheSelect->getOpcode() == ISD::SELECT) {
10775 SDNode *CondNode = TheSelect->getOperand(0).getNode();
10776 if ((LLD->hasAnyUseOfValue(1) && LLD->isPredecessorOf(CondNode)) ||
10777 (RLD->hasAnyUseOfValue(1) && RLD->isPredecessorOf(CondNode)))
10779 // The loads must not depend on one another.
10780 if (LLD->isPredecessorOf(RLD) ||
10781 RLD->isPredecessorOf(LLD))
10783 Addr = DAG.getSelect(SDLoc(TheSelect),
10784 LLD->getBasePtr().getValueType(),
10785 TheSelect->getOperand(0), LLD->getBasePtr(),
10786 RLD->getBasePtr());
10787 } else { // Otherwise SELECT_CC
10788 SDNode *CondLHS = TheSelect->getOperand(0).getNode();
10789 SDNode *CondRHS = TheSelect->getOperand(1).getNode();
10791 if ((LLD->hasAnyUseOfValue(1) &&
10792 (LLD->isPredecessorOf(CondLHS) || LLD->isPredecessorOf(CondRHS))) ||
10793 (RLD->hasAnyUseOfValue(1) &&
10794 (RLD->isPredecessorOf(CondLHS) || RLD->isPredecessorOf(CondRHS))))
10797 Addr = DAG.getNode(ISD::SELECT_CC, SDLoc(TheSelect),
10798 LLD->getBasePtr().getValueType(),
10799 TheSelect->getOperand(0),
10800 TheSelect->getOperand(1),
10801 LLD->getBasePtr(), RLD->getBasePtr(),
10802 TheSelect->getOperand(4));
10806 if (LLD->getExtensionType() == ISD::NON_EXTLOAD) {
10807 Load = DAG.getLoad(TheSelect->getValueType(0),
10809 // FIXME: Discards pointer and TBAA info.
10810 LLD->getChain(), Addr, MachinePointerInfo(),
10811 LLD->isVolatile(), LLD->isNonTemporal(),
10812 LLD->isInvariant(), LLD->getAlignment());
10814 Load = DAG.getExtLoad(LLD->getExtensionType() == ISD::EXTLOAD ?
10815 RLD->getExtensionType() : LLD->getExtensionType(),
10817 TheSelect->getValueType(0),
10818 // FIXME: Discards pointer and TBAA info.
10819 LLD->getChain(), Addr, MachinePointerInfo(),
10820 LLD->getMemoryVT(), LLD->isVolatile(),
10821 LLD->isNonTemporal(), LLD->getAlignment());
10824 // Users of the select now use the result of the load.
10825 CombineTo(TheSelect, Load);
10827 // Users of the old loads now use the new load's chain. We know the
10828 // old-load value is dead now.
10829 CombineTo(LHS.getNode(), Load.getValue(0), Load.getValue(1));
10830 CombineTo(RHS.getNode(), Load.getValue(0), Load.getValue(1));
10837 /// SimplifySelectCC - Simplify an expression of the form (N0 cond N1) ? N2 : N3
10838 /// where 'cond' is the comparison specified by CC.
10839 SDValue DAGCombiner::SimplifySelectCC(SDLoc DL, SDValue N0, SDValue N1,
10840 SDValue N2, SDValue N3,
10841 ISD::CondCode CC, bool NotExtCompare) {
10842 // (x ? y : y) -> y.
10843 if (N2 == N3) return N2;
10845 EVT VT = N2.getValueType();
10846 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
10847 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2.getNode());
10848 ConstantSDNode *N3C = dyn_cast<ConstantSDNode>(N3.getNode());
10850 // Determine if the condition we're dealing with is constant
10851 SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()),
10852 N0, N1, CC, DL, false);
10853 if (SCC.getNode()) AddToWorkList(SCC.getNode());
10854 ConstantSDNode *SCCC = dyn_cast_or_null<ConstantSDNode>(SCC.getNode());
10856 // fold select_cc true, x, y -> x
10857 if (SCCC && !SCCC->isNullValue())
10859 // fold select_cc false, x, y -> y
10860 if (SCCC && SCCC->isNullValue())
10863 // Check to see if we can simplify the select into an fabs node
10864 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N1)) {
10865 // Allow either -0.0 or 0.0
10866 if (CFP->getValueAPF().isZero()) {
10867 // select (setg[te] X, +/-0.0), X, fneg(X) -> fabs
10868 if ((CC == ISD::SETGE || CC == ISD::SETGT) &&
10869 N0 == N2 && N3.getOpcode() == ISD::FNEG &&
10870 N2 == N3.getOperand(0))
10871 return DAG.getNode(ISD::FABS, DL, VT, N0);
10873 // select (setl[te] X, +/-0.0), fneg(X), X -> fabs
10874 if ((CC == ISD::SETLT || CC == ISD::SETLE) &&
10875 N0 == N3 && N2.getOpcode() == ISD::FNEG &&
10876 N2.getOperand(0) == N3)
10877 return DAG.getNode(ISD::FABS, DL, VT, N3);
10881 // Turn "(a cond b) ? 1.0f : 2.0f" into "load (tmp + ((a cond b) ? 0 : 4)"
10882 // where "tmp" is a constant pool entry containing an array with 1.0 and 2.0
10883 // in it. This is a win when the constant is not otherwise available because
10884 // it replaces two constant pool loads with one. We only do this if the FP
10885 // type is known to be legal, because if it isn't, then we are before legalize
10886 // types an we want the other legalization to happen first (e.g. to avoid
10887 // messing with soft float) and if the ConstantFP is not legal, because if
10888 // it is legal, we may not need to store the FP constant in a constant pool.
10889 if (ConstantFPSDNode *TV = dyn_cast<ConstantFPSDNode>(N2))
10890 if (ConstantFPSDNode *FV = dyn_cast<ConstantFPSDNode>(N3)) {
10891 if (TLI.isTypeLegal(N2.getValueType()) &&
10892 (TLI.getOperationAction(ISD::ConstantFP, N2.getValueType()) !=
10893 TargetLowering::Legal) &&
10894 // If both constants have multiple uses, then we won't need to do an
10895 // extra load, they are likely around in registers for other users.
10896 (TV->hasOneUse() || FV->hasOneUse())) {
10897 Constant *Elts[] = {
10898 const_cast<ConstantFP*>(FV->getConstantFPValue()),
10899 const_cast<ConstantFP*>(TV->getConstantFPValue())
10901 Type *FPTy = Elts[0]->getType();
10902 const DataLayout &TD = *TLI.getDataLayout();
10904 // Create a ConstantArray of the two constants.
10905 Constant *CA = ConstantArray::get(ArrayType::get(FPTy, 2), Elts);
10906 SDValue CPIdx = DAG.getConstantPool(CA, TLI.getPointerTy(),
10907 TD.getPrefTypeAlignment(FPTy));
10908 unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
10910 // Get the offsets to the 0 and 1 element of the array so that we can
10911 // select between them.
10912 SDValue Zero = DAG.getIntPtrConstant(0);
10913 unsigned EltSize = (unsigned)TD.getTypeAllocSize(Elts[0]->getType());
10914 SDValue One = DAG.getIntPtrConstant(EltSize);
10916 SDValue Cond = DAG.getSetCC(DL,
10917 getSetCCResultType(N0.getValueType()),
10919 AddToWorkList(Cond.getNode());
10920 SDValue CstOffset = DAG.getSelect(DL, Zero.getValueType(),
10922 AddToWorkList(CstOffset.getNode());
10923 CPIdx = DAG.getNode(ISD::ADD, DL, CPIdx.getValueType(), CPIdx,
10925 AddToWorkList(CPIdx.getNode());
10926 return DAG.getLoad(TV->getValueType(0), DL, DAG.getEntryNode(), CPIdx,
10927 MachinePointerInfo::getConstantPool(), false,
10928 false, false, Alignment);
10933 // Check to see if we can perform the "gzip trick", transforming
10934 // (select_cc setlt X, 0, A, 0) -> (and (sra X, (sub size(X), 1), A)
10935 if (N1C && N3C && N3C->isNullValue() && CC == ISD::SETLT &&
10936 (N1C->isNullValue() || // (a < 0) ? b : 0
10937 (N1C->getAPIntValue() == 1 && N0 == N2))) { // (a < 1) ? a : 0
10938 EVT XType = N0.getValueType();
10939 EVT AType = N2.getValueType();
10940 if (XType.bitsGE(AType)) {
10941 // and (sra X, size(X)-1, A) -> "and (srl X, C2), A" iff A is a
10942 // single-bit constant.
10943 if (N2C && ((N2C->getAPIntValue() & (N2C->getAPIntValue()-1)) == 0)) {
10944 unsigned ShCtV = N2C->getAPIntValue().logBase2();
10945 ShCtV = XType.getSizeInBits()-ShCtV-1;
10946 SDValue ShCt = DAG.getConstant(ShCtV,
10947 getShiftAmountTy(N0.getValueType()));
10948 SDValue Shift = DAG.getNode(ISD::SRL, SDLoc(N0),
10950 AddToWorkList(Shift.getNode());
10952 if (XType.bitsGT(AType)) {
10953 Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift);
10954 AddToWorkList(Shift.getNode());
10957 return DAG.getNode(ISD::AND, DL, AType, Shift, N2);
10960 SDValue Shift = DAG.getNode(ISD::SRA, SDLoc(N0),
10962 DAG.getConstant(XType.getSizeInBits()-1,
10963 getShiftAmountTy(N0.getValueType())));
10964 AddToWorkList(Shift.getNode());
10966 if (XType.bitsGT(AType)) {
10967 Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift);
10968 AddToWorkList(Shift.getNode());
10971 return DAG.getNode(ISD::AND, DL, AType, Shift, N2);
10975 // fold (select_cc seteq (and x, y), 0, 0, A) -> (and (shr (shl x)) A)
10976 // where y is has a single bit set.
10977 // A plaintext description would be, we can turn the SELECT_CC into an AND
10978 // when the condition can be materialized as an all-ones register. Any
10979 // single bit-test can be materialized as an all-ones register with
10980 // shift-left and shift-right-arith.
10981 if (CC == ISD::SETEQ && N0->getOpcode() == ISD::AND &&
10982 N0->getValueType(0) == VT &&
10983 N1C && N1C->isNullValue() &&
10984 N2C && N2C->isNullValue()) {
10985 SDValue AndLHS = N0->getOperand(0);
10986 ConstantSDNode *ConstAndRHS = dyn_cast<ConstantSDNode>(N0->getOperand(1));
10987 if (ConstAndRHS && ConstAndRHS->getAPIntValue().countPopulation() == 1) {
10988 // Shift the tested bit over the sign bit.
10989 APInt AndMask = ConstAndRHS->getAPIntValue();
10991 DAG.getConstant(AndMask.countLeadingZeros(),
10992 getShiftAmountTy(AndLHS.getValueType()));
10993 SDValue Shl = DAG.getNode(ISD::SHL, SDLoc(N0), VT, AndLHS, ShlAmt);
10995 // Now arithmetic right shift it all the way over, so the result is either
10996 // all-ones, or zero.
10998 DAG.getConstant(AndMask.getBitWidth()-1,
10999 getShiftAmountTy(Shl.getValueType()));
11000 SDValue Shr = DAG.getNode(ISD::SRA, SDLoc(N0), VT, Shl, ShrAmt);
11002 return DAG.getNode(ISD::AND, DL, VT, Shr, N3);
11006 // fold select C, 16, 0 -> shl C, 4
11007 if (N2C && N3C && N3C->isNullValue() && N2C->getAPIntValue().isPowerOf2() &&
11008 TLI.getBooleanContents(N0.getValueType().isVector()) ==
11009 TargetLowering::ZeroOrOneBooleanContent) {
11011 // If the caller doesn't want us to simplify this into a zext of a compare,
11013 if (NotExtCompare && N2C->getAPIntValue() == 1)
11016 // Get a SetCC of the condition
11017 // NOTE: Don't create a SETCC if it's not legal on this target.
11018 if (!LegalOperations ||
11019 TLI.isOperationLegal(ISD::SETCC,
11020 LegalTypes ? getSetCCResultType(N0.getValueType()) : MVT::i1)) {
11022 // cast from setcc result type to select result type
11024 SCC = DAG.getSetCC(DL, getSetCCResultType(N0.getValueType()),
11026 if (N2.getValueType().bitsLT(SCC.getValueType()))
11027 Temp = DAG.getZeroExtendInReg(SCC, SDLoc(N2),
11028 N2.getValueType());
11030 Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2),
11031 N2.getValueType(), SCC);
11033 SCC = DAG.getSetCC(SDLoc(N0), MVT::i1, N0, N1, CC);
11034 Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2),
11035 N2.getValueType(), SCC);
11038 AddToWorkList(SCC.getNode());
11039 AddToWorkList(Temp.getNode());
11041 if (N2C->getAPIntValue() == 1)
11044 // shl setcc result by log2 n2c
11045 return DAG.getNode(
11046 ISD::SHL, DL, N2.getValueType(), Temp,
11047 DAG.getConstant(N2C->getAPIntValue().logBase2(),
11048 getShiftAmountTy(Temp.getValueType())));
11052 // Check to see if this is the equivalent of setcc
11053 // FIXME: Turn all of these into setcc if setcc if setcc is legal
11054 // otherwise, go ahead with the folds.
11055 if (0 && N3C && N3C->isNullValue() && N2C && (N2C->getAPIntValue() == 1ULL)) {
11056 EVT XType = N0.getValueType();
11057 if (!LegalOperations ||
11058 TLI.isOperationLegal(ISD::SETCC, getSetCCResultType(XType))) {
11059 SDValue Res = DAG.getSetCC(DL, getSetCCResultType(XType), N0, N1, CC);
11060 if (Res.getValueType() != VT)
11061 Res = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, Res);
11065 // fold (seteq X, 0) -> (srl (ctlz X, log2(size(X))))
11066 if (N1C && N1C->isNullValue() && CC == ISD::SETEQ &&
11067 (!LegalOperations ||
11068 TLI.isOperationLegal(ISD::CTLZ, XType))) {
11069 SDValue Ctlz = DAG.getNode(ISD::CTLZ, SDLoc(N0), XType, N0);
11070 return DAG.getNode(ISD::SRL, DL, XType, Ctlz,
11071 DAG.getConstant(Log2_32(XType.getSizeInBits()),
11072 getShiftAmountTy(Ctlz.getValueType())));
11074 // fold (setgt X, 0) -> (srl (and (-X, ~X), size(X)-1))
11075 if (N1C && N1C->isNullValue() && CC == ISD::SETGT) {
11076 SDValue NegN0 = DAG.getNode(ISD::SUB, SDLoc(N0),
11077 XType, DAG.getConstant(0, XType), N0);
11078 SDValue NotN0 = DAG.getNOT(SDLoc(N0), N0, XType);
11079 return DAG.getNode(ISD::SRL, DL, XType,
11080 DAG.getNode(ISD::AND, DL, XType, NegN0, NotN0),
11081 DAG.getConstant(XType.getSizeInBits()-1,
11082 getShiftAmountTy(XType)));
11084 // fold (setgt X, -1) -> (xor (srl (X, size(X)-1), 1))
11085 if (N1C && N1C->isAllOnesValue() && CC == ISD::SETGT) {
11086 SDValue Sign = DAG.getNode(ISD::SRL, SDLoc(N0), XType, N0,
11087 DAG.getConstant(XType.getSizeInBits()-1,
11088 getShiftAmountTy(N0.getValueType())));
11089 return DAG.getNode(ISD::XOR, DL, XType, Sign, DAG.getConstant(1, XType));
11093 // Check to see if this is an integer abs.
11094 // select_cc setg[te] X, 0, X, -X ->
11095 // select_cc setgt X, -1, X, -X ->
11096 // select_cc setl[te] X, 0, -X, X ->
11097 // select_cc setlt X, 1, -X, X ->
11098 // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
11100 ConstantSDNode *SubC = NULL;
11101 if (((N1C->isNullValue() && (CC == ISD::SETGT || CC == ISD::SETGE)) ||
11102 (N1C->isAllOnesValue() && CC == ISD::SETGT)) &&
11103 N0 == N2 && N3.getOpcode() == ISD::SUB && N0 == N3.getOperand(1))
11104 SubC = dyn_cast<ConstantSDNode>(N3.getOperand(0));
11105 else if (((N1C->isNullValue() && (CC == ISD::SETLT || CC == ISD::SETLE)) ||
11106 (N1C->isOne() && CC == ISD::SETLT)) &&
11107 N0 == N3 && N2.getOpcode() == ISD::SUB && N0 == N2.getOperand(1))
11108 SubC = dyn_cast<ConstantSDNode>(N2.getOperand(0));
11110 EVT XType = N0.getValueType();
11111 if (SubC && SubC->isNullValue() && XType.isInteger()) {
11112 SDValue Shift = DAG.getNode(ISD::SRA, SDLoc(N0), XType,
11114 DAG.getConstant(XType.getSizeInBits()-1,
11115 getShiftAmountTy(N0.getValueType())));
11116 SDValue Add = DAG.getNode(ISD::ADD, SDLoc(N0),
11118 AddToWorkList(Shift.getNode());
11119 AddToWorkList(Add.getNode());
11120 return DAG.getNode(ISD::XOR, DL, XType, Add, Shift);
11127 /// SimplifySetCC - This is a stub for TargetLowering::SimplifySetCC.
11128 SDValue DAGCombiner::SimplifySetCC(EVT VT, SDValue N0,
11129 SDValue N1, ISD::CondCode Cond,
11130 SDLoc DL, bool foldBooleans) {
11131 TargetLowering::DAGCombinerInfo
11132 DagCombineInfo(DAG, Level, false, this);
11133 return TLI.SimplifySetCC(VT, N0, N1, Cond, foldBooleans, DagCombineInfo, DL);
11136 /// BuildSDIVSequence - Given an ISD::SDIV node expressing a divide by constant,
11137 /// return a DAG expression to select that will generate the same value by
11138 /// multiplying by a magic number. See:
11139 /// <http://the.wall.riscom.net/books/proc/ppc/cwg/code2.html>
11140 SDValue DAGCombiner::BuildSDIV(SDNode *N) {
11141 std::vector<SDNode*> Built;
11142 SDValue S = TLI.BuildSDIV(N, DAG, LegalOperations, &Built);
11144 for (std::vector<SDNode*>::iterator ii = Built.begin(), ee = Built.end();
11146 AddToWorkList(*ii);
11150 /// BuildUDIVSequence - Given an ISD::UDIV node expressing a divide by constant,
11151 /// return a DAG expression to select that will generate the same value by
11152 /// multiplying by a magic number. See:
11153 /// <http://the.wall.riscom.net/books/proc/ppc/cwg/code2.html>
11154 SDValue DAGCombiner::BuildUDIV(SDNode *N) {
11155 std::vector<SDNode*> Built;
11156 SDValue S = TLI.BuildUDIV(N, DAG, LegalOperations, &Built);
11158 for (std::vector<SDNode*>::iterator ii = Built.begin(), ee = Built.end();
11160 AddToWorkList(*ii);
11164 /// FindBaseOffset - Return true if base is a frame index, which is known not
11165 // to alias with anything but itself. Provides base object and offset as
11167 static bool FindBaseOffset(SDValue Ptr, SDValue &Base, int64_t &Offset,
11168 const GlobalValue *&GV, const void *&CV) {
11169 // Assume it is a primitive operation.
11170 Base = Ptr; Offset = 0; GV = 0; CV = 0;
11172 // If it's an adding a simple constant then integrate the offset.
11173 if (Base.getOpcode() == ISD::ADD) {
11174 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Base.getOperand(1))) {
11175 Base = Base.getOperand(0);
11176 Offset += C->getZExtValue();
11180 // Return the underlying GlobalValue, and update the Offset. Return false
11181 // for GlobalAddressSDNode since the same GlobalAddress may be represented
11182 // by multiple nodes with different offsets.
11183 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Base)) {
11184 GV = G->getGlobal();
11185 Offset += G->getOffset();
11189 // Return the underlying Constant value, and update the Offset. Return false
11190 // for ConstantSDNodes since the same constant pool entry may be represented
11191 // by multiple nodes with different offsets.
11192 if (ConstantPoolSDNode *C = dyn_cast<ConstantPoolSDNode>(Base)) {
11193 CV = C->isMachineConstantPoolEntry() ? (const void *)C->getMachineCPVal()
11194 : (const void *)C->getConstVal();
11195 Offset += C->getOffset();
11198 // If it's any of the following then it can't alias with anything but itself.
11199 return isa<FrameIndexSDNode>(Base);
11202 /// isAlias - Return true if there is any possibility that the two addresses
11204 bool DAGCombiner::isAlias(SDValue Ptr1, int64_t Size1, bool IsVolatile1,
11205 const Value *SrcValue1, int SrcValueOffset1,
11206 unsigned SrcValueAlign1,
11207 const MDNode *TBAAInfo1,
11208 SDValue Ptr2, int64_t Size2, bool IsVolatile2,
11209 const Value *SrcValue2, int SrcValueOffset2,
11210 unsigned SrcValueAlign2,
11211 const MDNode *TBAAInfo2) const {
11212 // If they are the same then they must be aliases.
11213 if (Ptr1 == Ptr2) return true;
11215 // If they are both volatile then they cannot be reordered.
11216 if (IsVolatile1 && IsVolatile2) return true;
11218 // Gather base node and offset information.
11219 SDValue Base1, Base2;
11220 int64_t Offset1, Offset2;
11221 const GlobalValue *GV1, *GV2;
11222 const void *CV1, *CV2;
11223 bool isFrameIndex1 = FindBaseOffset(Ptr1, Base1, Offset1, GV1, CV1);
11224 bool isFrameIndex2 = FindBaseOffset(Ptr2, Base2, Offset2, GV2, CV2);
11226 // If they have a same base address then check to see if they overlap.
11227 if (Base1 == Base2 || (GV1 && (GV1 == GV2)) || (CV1 && (CV1 == CV2)))
11228 return !((Offset1 + Size1) <= Offset2 || (Offset2 + Size2) <= Offset1);
11230 // It is possible for different frame indices to alias each other, mostly
11231 // when tail call optimization reuses return address slots for arguments.
11232 // To catch this case, look up the actual index of frame indices to compute
11233 // the real alias relationship.
11234 if (isFrameIndex1 && isFrameIndex2) {
11235 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
11236 Offset1 += MFI->getObjectOffset(cast<FrameIndexSDNode>(Base1)->getIndex());
11237 Offset2 += MFI->getObjectOffset(cast<FrameIndexSDNode>(Base2)->getIndex());
11238 return !((Offset1 + Size1) <= Offset2 || (Offset2 + Size2) <= Offset1);
11241 // Otherwise, if we know what the bases are, and they aren't identical, then
11242 // we know they cannot alias.
11243 if ((isFrameIndex1 || CV1 || GV1) && (isFrameIndex2 || CV2 || GV2))
11246 // If we know required SrcValue1 and SrcValue2 have relatively large alignment
11247 // compared to the size and offset of the access, we may be able to prove they
11248 // do not alias. This check is conservative for now to catch cases created by
11249 // splitting vector types.
11250 if ((SrcValueAlign1 == SrcValueAlign2) &&
11251 (SrcValueOffset1 != SrcValueOffset2) &&
11252 (Size1 == Size2) && (SrcValueAlign1 > Size1)) {
11253 int64_t OffAlign1 = SrcValueOffset1 % SrcValueAlign1;
11254 int64_t OffAlign2 = SrcValueOffset2 % SrcValueAlign1;
11256 // There is no overlap between these relatively aligned accesses of similar
11257 // size, return no alias.
11258 if ((OffAlign1 + Size1) <= OffAlign2 || (OffAlign2 + Size2) <= OffAlign1)
11262 bool UseAA = CombinerGlobalAA.getNumOccurrences() > 0 ? CombinerGlobalAA :
11263 TLI.getTargetMachine().getSubtarget<TargetSubtargetInfo>().useAA();
11265 if (CombinerAAOnlyFunc.getNumOccurrences() &&
11266 CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
11269 if (UseAA && SrcValue1 && SrcValue2) {
11270 // Use alias analysis information.
11271 int64_t MinOffset = std::min(SrcValueOffset1, SrcValueOffset2);
11272 int64_t Overlap1 = Size1 + SrcValueOffset1 - MinOffset;
11273 int64_t Overlap2 = Size2 + SrcValueOffset2 - MinOffset;
11274 AliasAnalysis::AliasResult AAResult =
11275 AA.alias(AliasAnalysis::Location(SrcValue1, Overlap1,
11276 UseTBAA ? TBAAInfo1 : 0),
11277 AliasAnalysis::Location(SrcValue2, Overlap2,
11278 UseTBAA ? TBAAInfo2 : 0));
11279 if (AAResult == AliasAnalysis::NoAlias)
11283 // Otherwise we have to assume they alias.
11287 bool DAGCombiner::isAlias(LSBaseSDNode *Op0, LSBaseSDNode *Op1) {
11288 SDValue Ptr0, Ptr1;
11289 int64_t Size0, Size1;
11290 bool IsVolatile0, IsVolatile1;
11291 const Value *SrcValue0, *SrcValue1;
11292 int SrcValueOffset0, SrcValueOffset1;
11293 unsigned SrcValueAlign0, SrcValueAlign1;
11294 const MDNode *SrcTBAAInfo0, *SrcTBAAInfo1;
11295 FindAliasInfo(Op0, Ptr0, Size0, IsVolatile0, SrcValue0, SrcValueOffset0,
11296 SrcValueAlign0, SrcTBAAInfo0);
11297 FindAliasInfo(Op1, Ptr1, Size1, IsVolatile1, SrcValue1, SrcValueOffset1,
11298 SrcValueAlign1, SrcTBAAInfo1);
11299 return isAlias(Ptr0, Size0, IsVolatile0, SrcValue0, SrcValueOffset0,
11300 SrcValueAlign0, SrcTBAAInfo0,
11301 Ptr1, Size1, IsVolatile1, SrcValue1, SrcValueOffset1,
11302 SrcValueAlign1, SrcTBAAInfo1);
11305 /// FindAliasInfo - Extracts the relevant alias information from the memory
11306 /// node. Returns true if the operand was a nonvolatile load.
11307 bool DAGCombiner::FindAliasInfo(SDNode *N,
11308 SDValue &Ptr, int64_t &Size, bool &IsVolatile,
11309 const Value *&SrcValue,
11310 int &SrcValueOffset,
11311 unsigned &SrcValueAlign,
11312 const MDNode *&TBAAInfo) const {
11313 LSBaseSDNode *LS = cast<LSBaseSDNode>(N);
11315 Ptr = LS->getBasePtr();
11316 Size = LS->getMemoryVT().getSizeInBits() >> 3;
11317 IsVolatile = LS->isVolatile();
11318 SrcValue = LS->getSrcValue();
11319 SrcValueOffset = LS->getSrcValueOffset();
11320 SrcValueAlign = LS->getOriginalAlignment();
11321 TBAAInfo = LS->getTBAAInfo();
11322 return isa<LoadSDNode>(LS) && !IsVolatile;
11325 /// GatherAllAliases - Walk up chain skipping non-aliasing memory nodes,
11326 /// looking for aliasing nodes and adding them to the Aliases vector.
11327 void DAGCombiner::GatherAllAliases(SDNode *N, SDValue OriginalChain,
11328 SmallVectorImpl<SDValue> &Aliases) {
11329 SmallVector<SDValue, 8> Chains; // List of chains to visit.
11330 SmallPtrSet<SDNode *, 16> Visited; // Visited node set.
11332 // Get alias information for node.
11336 const Value *SrcValue;
11337 int SrcValueOffset;
11338 unsigned SrcValueAlign;
11339 const MDNode *SrcTBAAInfo;
11340 bool IsLoad = FindAliasInfo(N, Ptr, Size, IsVolatile, SrcValue,
11341 SrcValueOffset, SrcValueAlign, SrcTBAAInfo);
11344 Chains.push_back(OriginalChain);
11345 unsigned Depth = 0;
11347 // Look at each chain and determine if it is an alias. If so, add it to the
11348 // aliases list. If not, then continue up the chain looking for the next
11350 while (!Chains.empty()) {
11351 SDValue Chain = Chains.back();
11354 // For TokenFactor nodes, look at each operand and only continue up the
11355 // chain until we find two aliases. If we've seen two aliases, assume we'll
11356 // find more and revert to original chain since the xform is unlikely to be
11359 // FIXME: The depth check could be made to return the last non-aliasing
11360 // chain we found before we hit a tokenfactor rather than the original
11362 if (Depth > 6 || Aliases.size() == 2) {
11364 Aliases.push_back(OriginalChain);
11368 // Don't bother if we've been before.
11369 if (!Visited.insert(Chain.getNode()))
11372 switch (Chain.getOpcode()) {
11373 case ISD::EntryToken:
11374 // Entry token is ideal chain operand, but handled in FindBetterChain.
11379 // Get alias information for Chain.
11383 const Value *OpSrcValue;
11384 int OpSrcValueOffset;
11385 unsigned OpSrcValueAlign;
11386 const MDNode *OpSrcTBAAInfo;
11387 bool IsOpLoad = FindAliasInfo(Chain.getNode(), OpPtr, OpSize,
11388 OpIsVolatile, OpSrcValue, OpSrcValueOffset,
11392 // If chain is alias then stop here.
11393 if (!(IsLoad && IsOpLoad) &&
11394 isAlias(Ptr, Size, IsVolatile, SrcValue, SrcValueOffset,
11395 SrcValueAlign, SrcTBAAInfo,
11396 OpPtr, OpSize, OpIsVolatile, OpSrcValue, OpSrcValueOffset,
11397 OpSrcValueAlign, OpSrcTBAAInfo)) {
11398 Aliases.push_back(Chain);
11400 // Look further up the chain.
11401 Chains.push_back(Chain.getOperand(0));
11407 case ISD::TokenFactor:
11408 // We have to check each of the operands of the token factor for "small"
11409 // token factors, so we queue them up. Adding the operands to the queue
11410 // (stack) in reverse order maintains the original order and increases the
11411 // likelihood that getNode will find a matching token factor (CSE.)
11412 if (Chain.getNumOperands() > 16) {
11413 Aliases.push_back(Chain);
11416 for (unsigned n = Chain.getNumOperands(); n;)
11417 Chains.push_back(Chain.getOperand(--n));
11422 // For all other instructions we will just have to take what we can get.
11423 Aliases.push_back(Chain);
11428 // We need to be careful here to also search for aliases through the
11429 // value operand of a store, etc. Consider the following situation:
11431 // L1 = load Token1, %52
11432 // S1 = store Token1, L1, %51
11433 // L2 = load Token1, %52+8
11434 // S2 = store Token1, L2, %51+8
11435 // Token2 = Token(S1, S2)
11436 // L3 = load Token2, %53
11437 // S3 = store Token2, L3, %52
11438 // L4 = load Token2, %53+8
11439 // S4 = store Token2, L4, %52+8
11440 // If we search for aliases of S3 (which loads address %52), and we look
11441 // only through the chain, then we'll miss the trivial dependence on L1
11442 // (which also loads from %52). We then might change all loads and
11443 // stores to use Token1 as their chain operand, which could result in
11444 // copying %53 into %52 before copying %52 into %51 (which should
11447 // The problem is, however, that searching for such data dependencies
11448 // can become expensive, and the cost is not directly related to the
11449 // chain depth. Instead, we'll rule out such configurations here by
11450 // insisting that we've visited all chain users (except for users
11451 // of the original chain, which is not necessary). When doing this,
11452 // we need to look through nodes we don't care about (otherwise, things
11453 // like register copies will interfere with trivial cases).
11455 SmallVector<const SDNode *, 16> Worklist;
11456 for (SmallPtrSet<SDNode *, 16>::iterator I = Visited.begin(),
11457 IE = Visited.end(); I != IE; ++I)
11458 if (*I != OriginalChain.getNode())
11459 Worklist.push_back(*I);
11461 while (!Worklist.empty()) {
11462 const SDNode *M = Worklist.pop_back_val();
11464 // We have already visited M, and want to make sure we've visited any uses
11465 // of M that we care about. For uses that we've not visisted, and don't
11466 // care about, queue them to the worklist.
11468 for (SDNode::use_iterator UI = M->use_begin(),
11469 UIE = M->use_end(); UI != UIE; ++UI)
11470 if (UI.getUse().getValueType() == MVT::Other && Visited.insert(*UI)) {
11471 if (isa<MemIntrinsicSDNode>(*UI) || isa<MemSDNode>(*UI)) {
11472 // We've not visited this use, and we care about it (it could have an
11473 // ordering dependency with the original node).
11475 Aliases.push_back(OriginalChain);
11479 // We've not visited this use, but we don't care about it. Mark it as
11480 // visited and enqueue it to the worklist.
11481 Worklist.push_back(*UI);
11486 /// FindBetterChain - Walk up chain skipping non-aliasing memory nodes, looking
11487 /// for a better chain (aliasing node.)
11488 SDValue DAGCombiner::FindBetterChain(SDNode *N, SDValue OldChain) {
11489 SmallVector<SDValue, 8> Aliases; // Ops for replacing token factor.
11491 // Accumulate all the aliases to this node.
11492 GatherAllAliases(N, OldChain, Aliases);
11494 // If no operands then chain to entry token.
11495 if (Aliases.size() == 0)
11496 return DAG.getEntryNode();
11498 // If a single operand then chain to it. We don't need to revisit it.
11499 if (Aliases.size() == 1)
11502 // Construct a custom tailored token factor.
11503 return DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other,
11504 &Aliases[0], Aliases.size());
11507 // SelectionDAG::Combine - This is the entry point for the file.
11509 void SelectionDAG::Combine(CombineLevel Level, AliasAnalysis &AA,
11510 CodeGenOpt::Level OptLevel) {
11511 /// run - This is the main entry point to this class.
11513 DAGCombiner(*this, AA, OptLevel).Run(Level);