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);
278 SDValue XformToShuffleWithZero(SDNode *N);
279 SDValue ReassociateOps(unsigned Opc, SDLoc DL, SDValue LHS, SDValue RHS);
281 SDValue visitShiftByConstant(SDNode *N, unsigned Amt);
283 bool SimplifySelectOps(SDNode *SELECT, SDValue LHS, SDValue RHS);
284 SDValue SimplifyBinOpWithSameOpcodeHands(SDNode *N);
285 SDValue SimplifySelect(SDLoc DL, SDValue N0, SDValue N1, SDValue N2);
286 SDValue SimplifySelectCC(SDLoc DL, SDValue N0, SDValue N1, SDValue N2,
287 SDValue N3, ISD::CondCode CC,
288 bool NotExtCompare = false);
289 SDValue SimplifySetCC(EVT VT, SDValue N0, SDValue N1, ISD::CondCode Cond,
290 SDLoc DL, bool foldBooleans = true);
291 SDValue SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp,
293 SDValue CombineConsecutiveLoads(SDNode *N, EVT VT);
294 SDValue ConstantFoldBITCASTofBUILD_VECTOR(SDNode *, EVT);
295 SDValue BuildSDIV(SDNode *N);
296 SDValue BuildUDIV(SDNode *N);
297 SDValue MatchBSwapHWordLow(SDNode *N, SDValue N0, SDValue N1,
298 bool DemandHighBits = true);
299 SDValue MatchBSwapHWord(SDNode *N, SDValue N0, SDValue N1);
300 SDNode *MatchRotatePosNeg(SDValue Shifted, SDValue Pos, SDValue Neg,
301 SDValue InnerPos, SDValue InnerNeg,
302 unsigned PosOpcode, unsigned NegOpcode,
304 SDNode *MatchRotate(SDValue LHS, SDValue RHS, SDLoc DL);
305 SDValue ReduceLoadWidth(SDNode *N);
306 SDValue ReduceLoadOpStoreWidth(SDNode *N);
307 SDValue TransformFPLoadStorePair(SDNode *N);
308 SDValue reduceBuildVecExtToExtBuildVec(SDNode *N);
309 SDValue reduceBuildVecConvertToConvertBuildVec(SDNode *N);
311 SDValue GetDemandedBits(SDValue V, const APInt &Mask);
313 /// GatherAllAliases - Walk up chain skipping non-aliasing memory nodes,
314 /// looking for aliasing nodes and adding them to the Aliases vector.
315 void GatherAllAliases(SDNode *N, SDValue OriginalChain,
316 SmallVectorImpl<SDValue> &Aliases);
318 /// isAlias - Return true if there is any possibility that the two addresses
320 bool isAlias(SDValue Ptr1, int64_t Size1, bool IsVolatile1,
321 const Value *SrcValue1, int SrcValueOffset1,
322 unsigned SrcValueAlign1,
323 const MDNode *TBAAInfo1,
324 SDValue Ptr2, int64_t Size2, bool IsVolatile2,
325 const Value *SrcValue2, int SrcValueOffset2,
326 unsigned SrcValueAlign2,
327 const MDNode *TBAAInfo2) const;
329 /// isAlias - Return true if there is any possibility that the two addresses
331 bool isAlias(LSBaseSDNode *Op0, LSBaseSDNode *Op1);
333 /// FindAliasInfo - Extracts the relevant alias information from the memory
334 /// node. Returns true if the operand was a load.
335 bool FindAliasInfo(SDNode *N,
336 SDValue &Ptr, int64_t &Size, bool &IsVolatile,
337 const Value *&SrcValue, int &SrcValueOffset,
338 unsigned &SrcValueAlignment,
339 const MDNode *&TBAAInfo) const;
341 /// FindBetterChain - Walk up chain skipping non-aliasing memory nodes,
342 /// looking for a better chain (aliasing node.)
343 SDValue FindBetterChain(SDNode *N, SDValue Chain);
345 /// Merge consecutive store operations into a wide store.
346 /// This optimization uses wide integers or vectors when possible.
347 /// \return True if some memory operations were changed.
348 bool MergeConsecutiveStores(StoreSDNode *N);
351 DAGCombiner(SelectionDAG &D, AliasAnalysis &A, CodeGenOpt::Level OL)
352 : DAG(D), TLI(D.getTargetLoweringInfo()), Level(BeforeLegalizeTypes),
353 OptLevel(OL), LegalOperations(false), LegalTypes(false), AA(A) {
354 AttributeSet FnAttrs =
355 DAG.getMachineFunction().getFunction()->getAttributes();
357 FnAttrs.hasAttribute(AttributeSet::FunctionIndex,
358 Attribute::OptimizeForSize) ||
359 FnAttrs.hasAttribute(AttributeSet::FunctionIndex, Attribute::MinSize);
362 /// Run - runs the dag combiner on all nodes in the work list
363 void Run(CombineLevel AtLevel);
365 SelectionDAG &getDAG() const { return DAG; }
367 /// getShiftAmountTy - Returns a type large enough to hold any valid
368 /// shift amount - before type legalization these can be huge.
369 EVT getShiftAmountTy(EVT LHSTy) {
370 assert(LHSTy.isInteger() && "Shift amount is not an integer type!");
371 if (LHSTy.isVector())
373 return LegalTypes ? TLI.getScalarShiftAmountTy(LHSTy)
374 : TLI.getPointerTy();
377 /// isTypeLegal - This method returns true if we are running before type
378 /// legalization or if the specified VT is legal.
379 bool isTypeLegal(const EVT &VT) {
380 if (!LegalTypes) return true;
381 return TLI.isTypeLegal(VT);
384 /// getSetCCResultType - Convenience wrapper around
385 /// TargetLowering::getSetCCResultType
386 EVT getSetCCResultType(EVT VT) const {
387 return TLI.getSetCCResultType(*DAG.getContext(), VT);
394 /// WorkListRemover - This class is a DAGUpdateListener that removes any deleted
395 /// nodes from the worklist.
396 class WorkListRemover : public SelectionDAG::DAGUpdateListener {
399 explicit WorkListRemover(DAGCombiner &dc)
400 : SelectionDAG::DAGUpdateListener(dc.getDAG()), DC(dc) {}
402 virtual void NodeDeleted(SDNode *N, SDNode *E) {
403 DC.removeFromWorkList(N);
408 //===----------------------------------------------------------------------===//
409 // TargetLowering::DAGCombinerInfo implementation
410 //===----------------------------------------------------------------------===//
412 void TargetLowering::DAGCombinerInfo::AddToWorklist(SDNode *N) {
413 ((DAGCombiner*)DC)->AddToWorkList(N);
416 void TargetLowering::DAGCombinerInfo::RemoveFromWorklist(SDNode *N) {
417 ((DAGCombiner*)DC)->removeFromWorkList(N);
420 SDValue TargetLowering::DAGCombinerInfo::
421 CombineTo(SDNode *N, const std::vector<SDValue> &To, bool AddTo) {
422 return ((DAGCombiner*)DC)->CombineTo(N, &To[0], To.size(), AddTo);
425 SDValue TargetLowering::DAGCombinerInfo::
426 CombineTo(SDNode *N, SDValue Res, bool AddTo) {
427 return ((DAGCombiner*)DC)->CombineTo(N, Res, AddTo);
431 SDValue TargetLowering::DAGCombinerInfo::
432 CombineTo(SDNode *N, SDValue Res0, SDValue Res1, bool AddTo) {
433 return ((DAGCombiner*)DC)->CombineTo(N, Res0, Res1, AddTo);
436 void TargetLowering::DAGCombinerInfo::
437 CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) {
438 return ((DAGCombiner*)DC)->CommitTargetLoweringOpt(TLO);
441 //===----------------------------------------------------------------------===//
443 //===----------------------------------------------------------------------===//
445 /// isNegatibleForFree - Return 1 if we can compute the negated form of the
446 /// specified expression for the same cost as the expression itself, or 2 if we
447 /// can compute the negated form more cheaply than the expression itself.
448 static char isNegatibleForFree(SDValue Op, bool LegalOperations,
449 const TargetLowering &TLI,
450 const TargetOptions *Options,
451 unsigned Depth = 0) {
452 // fneg is removable even if it has multiple uses.
453 if (Op.getOpcode() == ISD::FNEG) return 2;
455 // Don't allow anything with multiple uses.
456 if (!Op.hasOneUse()) return 0;
458 // Don't recurse exponentially.
459 if (Depth > 6) return 0;
461 switch (Op.getOpcode()) {
462 default: return false;
463 case ISD::ConstantFP:
464 // Don't invert constant FP values after legalize. The negated constant
465 // isn't necessarily legal.
466 return LegalOperations ? 0 : 1;
468 // FIXME: determine better conditions for this xform.
469 if (!Options->UnsafeFPMath) return 0;
471 // After operation legalization, it might not be legal to create new FSUBs.
472 if (LegalOperations &&
473 !TLI.isOperationLegalOrCustom(ISD::FSUB, Op.getValueType()))
476 // fold (fneg (fadd A, B)) -> (fsub (fneg A), B)
477 if (char V = isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI,
480 // fold (fneg (fadd A, B)) -> (fsub (fneg B), A)
481 return isNegatibleForFree(Op.getOperand(1), LegalOperations, TLI, Options,
484 // We can't turn -(A-B) into B-A when we honor signed zeros.
485 if (!Options->UnsafeFPMath) return 0;
487 // fold (fneg (fsub A, B)) -> (fsub B, A)
492 if (Options->HonorSignDependentRoundingFPMath()) return 0;
494 // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y) or (fmul X, (fneg Y))
495 if (char V = isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI,
499 return isNegatibleForFree(Op.getOperand(1), LegalOperations, TLI, Options,
505 return isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI, Options,
510 /// GetNegatedExpression - If isNegatibleForFree returns true, this function
511 /// returns the newly negated expression.
512 static SDValue GetNegatedExpression(SDValue Op, SelectionDAG &DAG,
513 bool LegalOperations, unsigned Depth = 0) {
514 // fneg is removable even if it has multiple uses.
515 if (Op.getOpcode() == ISD::FNEG) return Op.getOperand(0);
517 // Don't allow anything with multiple uses.
518 assert(Op.hasOneUse() && "Unknown reuse!");
520 assert(Depth <= 6 && "GetNegatedExpression doesn't match isNegatibleForFree");
521 switch (Op.getOpcode()) {
522 default: llvm_unreachable("Unknown code");
523 case ISD::ConstantFP: {
524 APFloat V = cast<ConstantFPSDNode>(Op)->getValueAPF();
526 return DAG.getConstantFP(V, Op.getValueType());
529 // FIXME: determine better conditions for this xform.
530 assert(DAG.getTarget().Options.UnsafeFPMath);
532 // fold (fneg (fadd A, B)) -> (fsub (fneg A), B)
533 if (isNegatibleForFree(Op.getOperand(0), LegalOperations,
534 DAG.getTargetLoweringInfo(),
535 &DAG.getTarget().Options, Depth+1))
536 return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
537 GetNegatedExpression(Op.getOperand(0), DAG,
538 LegalOperations, Depth+1),
540 // fold (fneg (fadd A, B)) -> (fsub (fneg B), A)
541 return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
542 GetNegatedExpression(Op.getOperand(1), DAG,
543 LegalOperations, Depth+1),
546 // We can't turn -(A-B) into B-A when we honor signed zeros.
547 assert(DAG.getTarget().Options.UnsafeFPMath);
549 // fold (fneg (fsub 0, B)) -> B
550 if (ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(Op.getOperand(0)))
551 if (N0CFP->getValueAPF().isZero())
552 return Op.getOperand(1);
554 // fold (fneg (fsub A, B)) -> (fsub B, A)
555 return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
556 Op.getOperand(1), Op.getOperand(0));
560 assert(!DAG.getTarget().Options.HonorSignDependentRoundingFPMath());
562 // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y)
563 if (isNegatibleForFree(Op.getOperand(0), LegalOperations,
564 DAG.getTargetLoweringInfo(),
565 &DAG.getTarget().Options, Depth+1))
566 return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
567 GetNegatedExpression(Op.getOperand(0), DAG,
568 LegalOperations, Depth+1),
571 // fold (fneg (fmul X, Y)) -> (fmul X, (fneg Y))
572 return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
574 GetNegatedExpression(Op.getOperand(1), DAG,
575 LegalOperations, Depth+1));
579 return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
580 GetNegatedExpression(Op.getOperand(0), DAG,
581 LegalOperations, Depth+1));
583 return DAG.getNode(ISD::FP_ROUND, SDLoc(Op), Op.getValueType(),
584 GetNegatedExpression(Op.getOperand(0), DAG,
585 LegalOperations, Depth+1),
591 // isSetCCEquivalent - Return true if this node is a setcc, or is a select_cc
592 // that selects between the values 1 and 0, making it equivalent to a setcc.
593 // Also, set the incoming LHS, RHS, and CC references to the appropriate
594 // nodes based on the type of node we are checking. This simplifies life a
595 // bit for the callers.
596 static bool isSetCCEquivalent(SDValue N, SDValue &LHS, SDValue &RHS,
598 if (N.getOpcode() == ISD::SETCC) {
599 LHS = N.getOperand(0);
600 RHS = N.getOperand(1);
601 CC = N.getOperand(2);
604 if (N.getOpcode() == ISD::SELECT_CC &&
605 N.getOperand(2).getOpcode() == ISD::Constant &&
606 N.getOperand(3).getOpcode() == ISD::Constant &&
607 cast<ConstantSDNode>(N.getOperand(2))->getAPIntValue() == 1 &&
608 cast<ConstantSDNode>(N.getOperand(3))->isNullValue()) {
609 LHS = N.getOperand(0);
610 RHS = N.getOperand(1);
611 CC = N.getOperand(4);
617 // isOneUseSetCC - Return true if this is a SetCC-equivalent operation with only
618 // one use. If this is true, it allows the users to invert the operation for
619 // free when it is profitable to do so.
620 static bool isOneUseSetCC(SDValue N) {
622 if (isSetCCEquivalent(N, N0, N1, N2) && N.getNode()->hasOneUse())
627 // \brief Returns the SDNode if it is a constant BuildVector or constant int.
628 static SDNode *isConstantBuildVectorOrConstantInt(SDValue N) {
629 if (isa<ConstantSDNode>(N))
631 BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N);
632 if(BV && BV->isConstant())
637 SDValue DAGCombiner::ReassociateOps(unsigned Opc, SDLoc DL,
638 SDValue N0, SDValue N1) {
639 EVT VT = N0.getValueType();
640 if (N0.getOpcode() == Opc) {
641 if (SDNode *L = isConstantBuildVectorOrConstantInt(N0.getOperand(1))) {
642 if (SDNode *R = isConstantBuildVectorOrConstantInt(N1)) {
643 // reassoc. (op (op x, c1), c2) -> (op x, (op c1, c2))
644 SDValue OpNode = DAG.FoldConstantArithmetic(Opc, VT, L, R);
645 if (!OpNode.getNode())
647 return DAG.getNode(Opc, DL, VT, N0.getOperand(0), OpNode);
649 if (N0.hasOneUse()) {
650 // reassoc. (op (op x, c1), y) -> (op (op x, y), c1) iff x+c1 has one
652 SDValue OpNode = DAG.getNode(Opc, SDLoc(N0), VT, N0.getOperand(0), N1);
653 if (!OpNode.getNode())
655 AddToWorkList(OpNode.getNode());
656 return DAG.getNode(Opc, DL, VT, OpNode, N0.getOperand(1));
661 if (N1.getOpcode() == Opc) {
662 if (SDNode *R = isConstantBuildVectorOrConstantInt(N1.getOperand(1))) {
663 if (SDNode *L = isConstantBuildVectorOrConstantInt(N0)) {
664 // reassoc. (op c2, (op x, c1)) -> (op x, (op c1, c2))
665 SDValue OpNode = DAG.FoldConstantArithmetic(Opc, VT, R, L);
666 if (!OpNode.getNode())
668 return DAG.getNode(Opc, DL, VT, N1.getOperand(0), OpNode);
670 if (N1.hasOneUse()) {
671 // reassoc. (op y, (op x, c1)) -> (op (op x, y), c1) iff x+c1 has one
673 SDValue OpNode = DAG.getNode(Opc, SDLoc(N0), VT, N1.getOperand(0), N0);
674 if (!OpNode.getNode())
676 AddToWorkList(OpNode.getNode());
677 return DAG.getNode(Opc, DL, VT, OpNode, N1.getOperand(1));
685 SDValue DAGCombiner::CombineTo(SDNode *N, const SDValue *To, unsigned NumTo,
687 assert(N->getNumValues() == NumTo && "Broken CombineTo call!");
689 DEBUG(dbgs() << "\nReplacing.1 ";
691 dbgs() << "\nWith: ";
692 To[0].getNode()->dump(&DAG);
693 dbgs() << " and " << NumTo-1 << " other values\n";
694 for (unsigned i = 0, e = NumTo; i != e; ++i)
695 assert((!To[i].getNode() ||
696 N->getValueType(i) == To[i].getValueType()) &&
697 "Cannot combine value to value of different type!"));
698 WorkListRemover DeadNodes(*this);
699 DAG.ReplaceAllUsesWith(N, To);
701 // Push the new nodes and any users onto the worklist
702 for (unsigned i = 0, e = NumTo; i != e; ++i) {
703 if (To[i].getNode()) {
704 AddToWorkList(To[i].getNode());
705 AddUsersToWorkList(To[i].getNode());
710 // Finally, if the node is now dead, remove it from the graph. The node
711 // may not be dead if the replacement process recursively simplified to
712 // something else needing this node.
713 if (N->use_empty()) {
714 // Nodes can be reintroduced into the worklist. Make sure we do not
715 // process a node that has been replaced.
716 removeFromWorkList(N);
718 // Finally, since the node is now dead, remove it from the graph.
721 return SDValue(N, 0);
725 CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) {
726 // Replace all uses. If any nodes become isomorphic to other nodes and
727 // are deleted, make sure to remove them from our worklist.
728 WorkListRemover DeadNodes(*this);
729 DAG.ReplaceAllUsesOfValueWith(TLO.Old, TLO.New);
731 // Push the new node and any (possibly new) users onto the worklist.
732 AddToWorkList(TLO.New.getNode());
733 AddUsersToWorkList(TLO.New.getNode());
735 // Finally, if the node is now dead, remove it from the graph. The node
736 // may not be dead if the replacement process recursively simplified to
737 // something else needing this node.
738 if (TLO.Old.getNode()->use_empty()) {
739 removeFromWorkList(TLO.Old.getNode());
741 // If the operands of this node are only used by the node, they will now
742 // be dead. Make sure to visit them first to delete dead nodes early.
743 for (unsigned i = 0, e = TLO.Old.getNode()->getNumOperands(); i != e; ++i)
744 if (TLO.Old.getNode()->getOperand(i).getNode()->hasOneUse())
745 AddToWorkList(TLO.Old.getNode()->getOperand(i).getNode());
747 DAG.DeleteNode(TLO.Old.getNode());
751 /// SimplifyDemandedBits - Check the specified integer node value to see if
752 /// it can be simplified or if things it uses can be simplified by bit
753 /// propagation. If so, return true.
754 bool DAGCombiner::SimplifyDemandedBits(SDValue Op, const APInt &Demanded) {
755 TargetLowering::TargetLoweringOpt TLO(DAG, LegalTypes, LegalOperations);
756 APInt KnownZero, KnownOne;
757 if (!TLI.SimplifyDemandedBits(Op, Demanded, KnownZero, KnownOne, TLO))
761 AddToWorkList(Op.getNode());
763 // Replace the old value with the new one.
765 DEBUG(dbgs() << "\nReplacing.2 ";
766 TLO.Old.getNode()->dump(&DAG);
767 dbgs() << "\nWith: ";
768 TLO.New.getNode()->dump(&DAG);
771 CommitTargetLoweringOpt(TLO);
775 void DAGCombiner::ReplaceLoadWithPromotedLoad(SDNode *Load, SDNode *ExtLoad) {
777 EVT VT = Load->getValueType(0);
778 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, dl, VT, SDValue(ExtLoad, 0));
780 DEBUG(dbgs() << "\nReplacing.9 ";
782 dbgs() << "\nWith: ";
783 Trunc.getNode()->dump(&DAG);
785 WorkListRemover DeadNodes(*this);
786 DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 0), Trunc);
787 DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 1), SDValue(ExtLoad, 1));
788 removeFromWorkList(Load);
789 DAG.DeleteNode(Load);
790 AddToWorkList(Trunc.getNode());
793 SDValue DAGCombiner::PromoteOperand(SDValue Op, EVT PVT, bool &Replace) {
796 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Op)) {
797 EVT MemVT = LD->getMemoryVT();
798 ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD)
799 ? (TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT) ? ISD::ZEXTLOAD
801 : LD->getExtensionType();
803 return DAG.getExtLoad(ExtType, dl, PVT,
804 LD->getChain(), LD->getBasePtr(),
805 MemVT, LD->getMemOperand());
808 unsigned Opc = Op.getOpcode();
811 case ISD::AssertSext:
812 return DAG.getNode(ISD::AssertSext, dl, PVT,
813 SExtPromoteOperand(Op.getOperand(0), PVT),
815 case ISD::AssertZext:
816 return DAG.getNode(ISD::AssertZext, dl, PVT,
817 ZExtPromoteOperand(Op.getOperand(0), PVT),
819 case ISD::Constant: {
821 Op.getValueType().isByteSized() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
822 return DAG.getNode(ExtOpc, dl, PVT, Op);
826 if (!TLI.isOperationLegal(ISD::ANY_EXTEND, PVT))
828 return DAG.getNode(ISD::ANY_EXTEND, dl, PVT, Op);
831 SDValue DAGCombiner::SExtPromoteOperand(SDValue Op, EVT PVT) {
832 if (!TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, PVT))
834 EVT OldVT = Op.getValueType();
836 bool Replace = false;
837 SDValue NewOp = PromoteOperand(Op, PVT, Replace);
838 if (NewOp.getNode() == 0)
840 AddToWorkList(NewOp.getNode());
843 ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode());
844 return DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, NewOp.getValueType(), NewOp,
845 DAG.getValueType(OldVT));
848 SDValue DAGCombiner::ZExtPromoteOperand(SDValue Op, EVT PVT) {
849 EVT OldVT = Op.getValueType();
851 bool Replace = false;
852 SDValue NewOp = PromoteOperand(Op, PVT, Replace);
853 if (NewOp.getNode() == 0)
855 AddToWorkList(NewOp.getNode());
858 ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode());
859 return DAG.getZeroExtendInReg(NewOp, dl, OldVT);
862 /// PromoteIntBinOp - Promote the specified integer binary operation if the
863 /// target indicates it is beneficial. e.g. On x86, it's usually better to
864 /// promote i16 operations to i32 since i16 instructions are longer.
865 SDValue DAGCombiner::PromoteIntBinOp(SDValue Op) {
866 if (!LegalOperations)
869 EVT VT = Op.getValueType();
870 if (VT.isVector() || !VT.isInteger())
873 // If operation type is 'undesirable', e.g. i16 on x86, consider
875 unsigned Opc = Op.getOpcode();
876 if (TLI.isTypeDesirableForOp(Opc, VT))
880 // Consult target whether it is a good idea to promote this operation and
881 // what's the right type to promote it to.
882 if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
883 assert(PVT != VT && "Don't know what type to promote to!");
885 bool Replace0 = false;
886 SDValue N0 = Op.getOperand(0);
887 SDValue NN0 = PromoteOperand(N0, PVT, Replace0);
888 if (NN0.getNode() == 0)
891 bool Replace1 = false;
892 SDValue N1 = Op.getOperand(1);
897 NN1 = PromoteOperand(N1, PVT, Replace1);
898 if (NN1.getNode() == 0)
902 AddToWorkList(NN0.getNode());
904 AddToWorkList(NN1.getNode());
907 ReplaceLoadWithPromotedLoad(N0.getNode(), NN0.getNode());
909 ReplaceLoadWithPromotedLoad(N1.getNode(), NN1.getNode());
911 DEBUG(dbgs() << "\nPromoting ";
912 Op.getNode()->dump(&DAG));
914 return DAG.getNode(ISD::TRUNCATE, dl, VT,
915 DAG.getNode(Opc, dl, PVT, NN0, NN1));
920 /// PromoteIntShiftOp - Promote the specified integer shift operation if the
921 /// target indicates it is beneficial. e.g. On x86, it's usually better to
922 /// promote i16 operations to i32 since i16 instructions are longer.
923 SDValue DAGCombiner::PromoteIntShiftOp(SDValue Op) {
924 if (!LegalOperations)
927 EVT VT = Op.getValueType();
928 if (VT.isVector() || !VT.isInteger())
931 // If operation type is 'undesirable', e.g. i16 on x86, consider
933 unsigned Opc = Op.getOpcode();
934 if (TLI.isTypeDesirableForOp(Opc, VT))
938 // Consult target whether it is a good idea to promote this operation and
939 // what's the right type to promote it to.
940 if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
941 assert(PVT != VT && "Don't know what type to promote to!");
943 bool Replace = false;
944 SDValue N0 = Op.getOperand(0);
946 N0 = SExtPromoteOperand(Op.getOperand(0), PVT);
947 else if (Opc == ISD::SRL)
948 N0 = ZExtPromoteOperand(Op.getOperand(0), PVT);
950 N0 = PromoteOperand(N0, PVT, Replace);
951 if (N0.getNode() == 0)
954 AddToWorkList(N0.getNode());
956 ReplaceLoadWithPromotedLoad(Op.getOperand(0).getNode(), N0.getNode());
958 DEBUG(dbgs() << "\nPromoting ";
959 Op.getNode()->dump(&DAG));
961 return DAG.getNode(ISD::TRUNCATE, dl, VT,
962 DAG.getNode(Opc, dl, PVT, N0, Op.getOperand(1)));
967 SDValue DAGCombiner::PromoteExtend(SDValue Op) {
968 if (!LegalOperations)
971 EVT VT = Op.getValueType();
972 if (VT.isVector() || !VT.isInteger())
975 // If operation type is 'undesirable', e.g. i16 on x86, consider
977 unsigned Opc = Op.getOpcode();
978 if (TLI.isTypeDesirableForOp(Opc, VT))
982 // Consult target whether it is a good idea to promote this operation and
983 // what's the right type to promote it to.
984 if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
985 assert(PVT != VT && "Don't know what type to promote to!");
986 // fold (aext (aext x)) -> (aext x)
987 // fold (aext (zext x)) -> (zext x)
988 // fold (aext (sext x)) -> (sext x)
989 DEBUG(dbgs() << "\nPromoting ";
990 Op.getNode()->dump(&DAG));
991 return DAG.getNode(Op.getOpcode(), SDLoc(Op), VT, Op.getOperand(0));
996 bool DAGCombiner::PromoteLoad(SDValue Op) {
997 if (!LegalOperations)
1000 EVT VT = Op.getValueType();
1001 if (VT.isVector() || !VT.isInteger())
1004 // If operation type is 'undesirable', e.g. i16 on x86, consider
1006 unsigned Opc = Op.getOpcode();
1007 if (TLI.isTypeDesirableForOp(Opc, VT))
1011 // Consult target whether it is a good idea to promote this operation and
1012 // what's the right type to promote it to.
1013 if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1014 assert(PVT != VT && "Don't know what type to promote to!");
1017 SDNode *N = Op.getNode();
1018 LoadSDNode *LD = cast<LoadSDNode>(N);
1019 EVT MemVT = LD->getMemoryVT();
1020 ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD)
1021 ? (TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT) ? ISD::ZEXTLOAD
1023 : LD->getExtensionType();
1024 SDValue NewLD = DAG.getExtLoad(ExtType, dl, PVT,
1025 LD->getChain(), LD->getBasePtr(),
1026 MemVT, LD->getMemOperand());
1027 SDValue Result = DAG.getNode(ISD::TRUNCATE, dl, VT, NewLD);
1029 DEBUG(dbgs() << "\nPromoting ";
1032 Result.getNode()->dump(&DAG);
1034 WorkListRemover DeadNodes(*this);
1035 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result);
1036 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), NewLD.getValue(1));
1037 removeFromWorkList(N);
1039 AddToWorkList(Result.getNode());
1046 //===----------------------------------------------------------------------===//
1047 // Main DAG Combiner implementation
1048 //===----------------------------------------------------------------------===//
1050 void DAGCombiner::Run(CombineLevel AtLevel) {
1051 // set the instance variables, so that the various visit routines may use it.
1053 LegalOperations = Level >= AfterLegalizeVectorOps;
1054 LegalTypes = Level >= AfterLegalizeTypes;
1056 // Add all the dag nodes to the worklist.
1057 for (SelectionDAG::allnodes_iterator I = DAG.allnodes_begin(),
1058 E = DAG.allnodes_end(); I != E; ++I)
1061 // Create a dummy node (which is not added to allnodes), that adds a reference
1062 // to the root node, preventing it from being deleted, and tracking any
1063 // changes of the root.
1064 HandleSDNode Dummy(DAG.getRoot());
1066 // The root of the dag may dangle to deleted nodes until the dag combiner is
1067 // done. Set it to null to avoid confusion.
1068 DAG.setRoot(SDValue());
1070 // while the worklist isn't empty, find a node and
1071 // try and combine it.
1072 while (!WorkListContents.empty()) {
1074 // The WorkListOrder holds the SDNodes in order, but it may contain
1076 // In order to avoid a linear scan, we use a set (O(log N)) to hold what the
1077 // worklist *should* contain, and check the node we want to visit is should
1078 // actually be visited.
1080 N = WorkListOrder.pop_back_val();
1081 } while (!WorkListContents.erase(N));
1083 // If N has no uses, it is dead. Make sure to revisit all N's operands once
1084 // N is deleted from the DAG, since they too may now be dead or may have a
1085 // reduced number of uses, allowing other xforms.
1086 if (N->use_empty() && N != &Dummy) {
1087 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1088 AddToWorkList(N->getOperand(i).getNode());
1094 SDValue RV = combine(N);
1096 if (RV.getNode() == 0)
1101 // If we get back the same node we passed in, rather than a new node or
1102 // zero, we know that the node must have defined multiple values and
1103 // CombineTo was used. Since CombineTo takes care of the worklist
1104 // mechanics for us, we have no work to do in this case.
1105 if (RV.getNode() == N)
1108 assert(N->getOpcode() != ISD::DELETED_NODE &&
1109 RV.getNode()->getOpcode() != ISD::DELETED_NODE &&
1110 "Node was deleted but visit returned new node!");
1112 DEBUG(dbgs() << "\nReplacing.3 ";
1114 dbgs() << "\nWith: ";
1115 RV.getNode()->dump(&DAG);
1118 // Transfer debug value.
1119 DAG.TransferDbgValues(SDValue(N, 0), RV);
1120 WorkListRemover DeadNodes(*this);
1121 if (N->getNumValues() == RV.getNode()->getNumValues())
1122 DAG.ReplaceAllUsesWith(N, RV.getNode());
1124 assert(N->getValueType(0) == RV.getValueType() &&
1125 N->getNumValues() == 1 && "Type mismatch");
1127 DAG.ReplaceAllUsesWith(N, &OpV);
1130 // Push the new node and any users onto the worklist
1131 AddToWorkList(RV.getNode());
1132 AddUsersToWorkList(RV.getNode());
1134 // Add any uses of the old node to the worklist in case this node is the
1135 // last one that uses them. They may become dead after this node is
1137 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1138 AddToWorkList(N->getOperand(i).getNode());
1140 // Finally, if the node is now dead, remove it from the graph. The node
1141 // may not be dead if the replacement process recursively simplified to
1142 // something else needing this node.
1143 if (N->use_empty()) {
1144 // Nodes can be reintroduced into the worklist. Make sure we do not
1145 // process a node that has been replaced.
1146 removeFromWorkList(N);
1148 // Finally, since the node is now dead, remove it from the graph.
1153 // If the root changed (e.g. it was a dead load, update the root).
1154 DAG.setRoot(Dummy.getValue());
1155 DAG.RemoveDeadNodes();
1158 SDValue DAGCombiner::visit(SDNode *N) {
1159 switch (N->getOpcode()) {
1161 case ISD::TokenFactor: return visitTokenFactor(N);
1162 case ISD::MERGE_VALUES: return visitMERGE_VALUES(N);
1163 case ISD::ADD: return visitADD(N);
1164 case ISD::SUB: return visitSUB(N);
1165 case ISD::ADDC: return visitADDC(N);
1166 case ISD::SUBC: return visitSUBC(N);
1167 case ISD::ADDE: return visitADDE(N);
1168 case ISD::SUBE: return visitSUBE(N);
1169 case ISD::MUL: return visitMUL(N);
1170 case ISD::SDIV: return visitSDIV(N);
1171 case ISD::UDIV: return visitUDIV(N);
1172 case ISD::SREM: return visitSREM(N);
1173 case ISD::UREM: return visitUREM(N);
1174 case ISD::MULHU: return visitMULHU(N);
1175 case ISD::MULHS: return visitMULHS(N);
1176 case ISD::SMUL_LOHI: return visitSMUL_LOHI(N);
1177 case ISD::UMUL_LOHI: return visitUMUL_LOHI(N);
1178 case ISD::SMULO: return visitSMULO(N);
1179 case ISD::UMULO: return visitUMULO(N);
1180 case ISD::SDIVREM: return visitSDIVREM(N);
1181 case ISD::UDIVREM: return visitUDIVREM(N);
1182 case ISD::AND: return visitAND(N);
1183 case ISD::OR: return visitOR(N);
1184 case ISD::XOR: return visitXOR(N);
1185 case ISD::SHL: return visitSHL(N);
1186 case ISD::SRA: return visitSRA(N);
1187 case ISD::SRL: return visitSRL(N);
1188 case ISD::CTLZ: return visitCTLZ(N);
1189 case ISD::CTLZ_ZERO_UNDEF: return visitCTLZ_ZERO_UNDEF(N);
1190 case ISD::CTTZ: return visitCTTZ(N);
1191 case ISD::CTTZ_ZERO_UNDEF: return visitCTTZ_ZERO_UNDEF(N);
1192 case ISD::CTPOP: return visitCTPOP(N);
1193 case ISD::SELECT: return visitSELECT(N);
1194 case ISD::VSELECT: return visitVSELECT(N);
1195 case ISD::SELECT_CC: return visitSELECT_CC(N);
1196 case ISD::SETCC: return visitSETCC(N);
1197 case ISD::SIGN_EXTEND: return visitSIGN_EXTEND(N);
1198 case ISD::ZERO_EXTEND: return visitZERO_EXTEND(N);
1199 case ISD::ANY_EXTEND: return visitANY_EXTEND(N);
1200 case ISD::SIGN_EXTEND_INREG: return visitSIGN_EXTEND_INREG(N);
1201 case ISD::TRUNCATE: return visitTRUNCATE(N);
1202 case ISD::BITCAST: return visitBITCAST(N);
1203 case ISD::BUILD_PAIR: return visitBUILD_PAIR(N);
1204 case ISD::FADD: return visitFADD(N);
1205 case ISD::FSUB: return visitFSUB(N);
1206 case ISD::FMUL: return visitFMUL(N);
1207 case ISD::FMA: return visitFMA(N);
1208 case ISD::FDIV: return visitFDIV(N);
1209 case ISD::FREM: return visitFREM(N);
1210 case ISD::FCOPYSIGN: return visitFCOPYSIGN(N);
1211 case ISD::SINT_TO_FP: return visitSINT_TO_FP(N);
1212 case ISD::UINT_TO_FP: return visitUINT_TO_FP(N);
1213 case ISD::FP_TO_SINT: return visitFP_TO_SINT(N);
1214 case ISD::FP_TO_UINT: return visitFP_TO_UINT(N);
1215 case ISD::FP_ROUND: return visitFP_ROUND(N);
1216 case ISD::FP_ROUND_INREG: return visitFP_ROUND_INREG(N);
1217 case ISD::FP_EXTEND: return visitFP_EXTEND(N);
1218 case ISD::FNEG: return visitFNEG(N);
1219 case ISD::FABS: return visitFABS(N);
1220 case ISD::FFLOOR: return visitFFLOOR(N);
1221 case ISD::FCEIL: return visitFCEIL(N);
1222 case ISD::FTRUNC: return visitFTRUNC(N);
1223 case ISD::BRCOND: return visitBRCOND(N);
1224 case ISD::BR_CC: return visitBR_CC(N);
1225 case ISD::LOAD: return visitLOAD(N);
1226 case ISD::STORE: return visitSTORE(N);
1227 case ISD::INSERT_VECTOR_ELT: return visitINSERT_VECTOR_ELT(N);
1228 case ISD::EXTRACT_VECTOR_ELT: return visitEXTRACT_VECTOR_ELT(N);
1229 case ISD::BUILD_VECTOR: return visitBUILD_VECTOR(N);
1230 case ISD::CONCAT_VECTORS: return visitCONCAT_VECTORS(N);
1231 case ISD::EXTRACT_SUBVECTOR: return visitEXTRACT_SUBVECTOR(N);
1232 case ISD::VECTOR_SHUFFLE: return visitVECTOR_SHUFFLE(N);
1237 SDValue DAGCombiner::combine(SDNode *N) {
1238 SDValue RV = visit(N);
1240 // If nothing happened, try a target-specific DAG combine.
1241 if (RV.getNode() == 0) {
1242 assert(N->getOpcode() != ISD::DELETED_NODE &&
1243 "Node was deleted but visit returned NULL!");
1245 if (N->getOpcode() >= ISD::BUILTIN_OP_END ||
1246 TLI.hasTargetDAGCombine((ISD::NodeType)N->getOpcode())) {
1248 // Expose the DAG combiner to the target combiner impls.
1249 TargetLowering::DAGCombinerInfo
1250 DagCombineInfo(DAG, Level, false, this);
1252 RV = TLI.PerformDAGCombine(N, DagCombineInfo);
1256 // If nothing happened still, try promoting the operation.
1257 if (RV.getNode() == 0) {
1258 switch (N->getOpcode()) {
1266 RV = PromoteIntBinOp(SDValue(N, 0));
1271 RV = PromoteIntShiftOp(SDValue(N, 0));
1273 case ISD::SIGN_EXTEND:
1274 case ISD::ZERO_EXTEND:
1275 case ISD::ANY_EXTEND:
1276 RV = PromoteExtend(SDValue(N, 0));
1279 if (PromoteLoad(SDValue(N, 0)))
1285 // If N is a commutative binary node, try commuting it to enable more
1287 if (RV.getNode() == 0 &&
1288 SelectionDAG::isCommutativeBinOp(N->getOpcode()) &&
1289 N->getNumValues() == 1) {
1290 SDValue N0 = N->getOperand(0);
1291 SDValue N1 = N->getOperand(1);
1293 // Constant operands are canonicalized to RHS.
1294 if (isa<ConstantSDNode>(N0) || !isa<ConstantSDNode>(N1)) {
1295 SDValue Ops[] = { N1, N0 };
1296 SDNode *CSENode = DAG.getNodeIfExists(N->getOpcode(), N->getVTList(),
1299 return SDValue(CSENode, 0);
1306 /// getInputChainForNode - Given a node, return its input chain if it has one,
1307 /// otherwise return a null sd operand.
1308 static SDValue getInputChainForNode(SDNode *N) {
1309 if (unsigned NumOps = N->getNumOperands()) {
1310 if (N->getOperand(0).getValueType() == MVT::Other)
1311 return N->getOperand(0);
1312 if (N->getOperand(NumOps-1).getValueType() == MVT::Other)
1313 return N->getOperand(NumOps-1);
1314 for (unsigned i = 1; i < NumOps-1; ++i)
1315 if (N->getOperand(i).getValueType() == MVT::Other)
1316 return N->getOperand(i);
1321 SDValue DAGCombiner::visitTokenFactor(SDNode *N) {
1322 // If N has two operands, where one has an input chain equal to the other,
1323 // the 'other' chain is redundant.
1324 if (N->getNumOperands() == 2) {
1325 if (getInputChainForNode(N->getOperand(0).getNode()) == N->getOperand(1))
1326 return N->getOperand(0);
1327 if (getInputChainForNode(N->getOperand(1).getNode()) == N->getOperand(0))
1328 return N->getOperand(1);
1331 SmallVector<SDNode *, 8> TFs; // List of token factors to visit.
1332 SmallVector<SDValue, 8> Ops; // Ops for replacing token factor.
1333 SmallPtrSet<SDNode*, 16> SeenOps;
1334 bool Changed = false; // If we should replace this token factor.
1336 // Start out with this token factor.
1339 // Iterate through token factors. The TFs grows when new token factors are
1341 for (unsigned i = 0; i < TFs.size(); ++i) {
1342 SDNode *TF = TFs[i];
1344 // Check each of the operands.
1345 for (unsigned i = 0, ie = TF->getNumOperands(); i != ie; ++i) {
1346 SDValue Op = TF->getOperand(i);
1348 switch (Op.getOpcode()) {
1349 case ISD::EntryToken:
1350 // Entry tokens don't need to be added to the list. They are
1355 case ISD::TokenFactor:
1356 if (Op.hasOneUse() &&
1357 std::find(TFs.begin(), TFs.end(), Op.getNode()) == TFs.end()) {
1358 // Queue up for processing.
1359 TFs.push_back(Op.getNode());
1360 // Clean up in case the token factor is removed.
1361 AddToWorkList(Op.getNode());
1368 // Only add if it isn't already in the list.
1369 if (SeenOps.insert(Op.getNode()))
1380 // If we've change things around then replace token factor.
1383 // The entry token is the only possible outcome.
1384 Result = DAG.getEntryNode();
1386 // New and improved token factor.
1387 Result = DAG.getNode(ISD::TokenFactor, SDLoc(N),
1388 MVT::Other, &Ops[0], Ops.size());
1391 // Don't add users to work list.
1392 return CombineTo(N, Result, false);
1398 /// MERGE_VALUES can always be eliminated.
1399 SDValue DAGCombiner::visitMERGE_VALUES(SDNode *N) {
1400 WorkListRemover DeadNodes(*this);
1401 // Replacing results may cause a different MERGE_VALUES to suddenly
1402 // be CSE'd with N, and carry its uses with it. Iterate until no
1403 // uses remain, to ensure that the node can be safely deleted.
1404 // First add the users of this node to the work list so that they
1405 // can be tried again once they have new operands.
1406 AddUsersToWorkList(N);
1408 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1409 DAG.ReplaceAllUsesOfValueWith(SDValue(N, i), N->getOperand(i));
1410 } while (!N->use_empty());
1411 removeFromWorkList(N);
1413 return SDValue(N, 0); // Return N so it doesn't get rechecked!
1417 SDValue combineShlAddConstant(SDLoc DL, SDValue N0, SDValue N1,
1418 SelectionDAG &DAG) {
1419 EVT VT = N0.getValueType();
1420 SDValue N00 = N0.getOperand(0);
1421 SDValue N01 = N0.getOperand(1);
1422 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N01);
1424 if (N01C && N00.getOpcode() == ISD::ADD && N00.getNode()->hasOneUse() &&
1425 isa<ConstantSDNode>(N00.getOperand(1))) {
1426 // fold (add (shl (add x, c1), c2), ) -> (add (add (shl x, c2), c1<<c2), )
1427 N0 = DAG.getNode(ISD::ADD, SDLoc(N0), VT,
1428 DAG.getNode(ISD::SHL, SDLoc(N00), VT,
1429 N00.getOperand(0), N01),
1430 DAG.getNode(ISD::SHL, SDLoc(N01), VT,
1431 N00.getOperand(1), N01));
1432 return DAG.getNode(ISD::ADD, DL, VT, N0, N1);
1438 SDValue DAGCombiner::visitADD(SDNode *N) {
1439 SDValue N0 = N->getOperand(0);
1440 SDValue N1 = N->getOperand(1);
1441 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1442 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1443 EVT VT = N0.getValueType();
1446 if (VT.isVector()) {
1447 SDValue FoldedVOp = SimplifyVBinOp(N);
1448 if (FoldedVOp.getNode()) return FoldedVOp;
1450 // fold (add x, 0) -> x, vector edition
1451 if (ISD::isBuildVectorAllZeros(N1.getNode()))
1453 if (ISD::isBuildVectorAllZeros(N0.getNode()))
1457 // fold (add x, undef) -> undef
1458 if (N0.getOpcode() == ISD::UNDEF)
1460 if (N1.getOpcode() == ISD::UNDEF)
1462 // fold (add c1, c2) -> c1+c2
1464 return DAG.FoldConstantArithmetic(ISD::ADD, VT, N0C, N1C);
1465 // canonicalize constant to RHS
1467 return DAG.getNode(ISD::ADD, SDLoc(N), VT, N1, N0);
1468 // fold (add x, 0) -> x
1469 if (N1C && N1C->isNullValue())
1471 // fold (add Sym, c) -> Sym+c
1472 if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N0))
1473 if (!LegalOperations && TLI.isOffsetFoldingLegal(GA) && N1C &&
1474 GA->getOpcode() == ISD::GlobalAddress)
1475 return DAG.getGlobalAddress(GA->getGlobal(), SDLoc(N1C), VT,
1477 (uint64_t)N1C->getSExtValue());
1478 // fold ((c1-A)+c2) -> (c1+c2)-A
1479 if (N1C && N0.getOpcode() == ISD::SUB)
1480 if (ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getOperand(0)))
1481 return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1482 DAG.getConstant(N1C->getAPIntValue()+
1483 N0C->getAPIntValue(), VT),
1486 SDValue RADD = ReassociateOps(ISD::ADD, SDLoc(N), N0, N1);
1487 if (RADD.getNode() != 0)
1489 // fold ((0-A) + B) -> B-A
1490 if (N0.getOpcode() == ISD::SUB && isa<ConstantSDNode>(N0.getOperand(0)) &&
1491 cast<ConstantSDNode>(N0.getOperand(0))->isNullValue())
1492 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1, N0.getOperand(1));
1493 // fold (A + (0-B)) -> A-B
1494 if (N1.getOpcode() == ISD::SUB && isa<ConstantSDNode>(N1.getOperand(0)) &&
1495 cast<ConstantSDNode>(N1.getOperand(0))->isNullValue())
1496 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, N1.getOperand(1));
1497 // fold (A+(B-A)) -> B
1498 if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(1))
1499 return N1.getOperand(0);
1500 // fold ((B-A)+A) -> B
1501 if (N0.getOpcode() == ISD::SUB && N1 == N0.getOperand(1))
1502 return N0.getOperand(0);
1503 // fold (A+(B-(A+C))) to (B-C)
1504 if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD &&
1505 N0 == N1.getOperand(1).getOperand(0))
1506 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1.getOperand(0),
1507 N1.getOperand(1).getOperand(1));
1508 // fold (A+(B-(C+A))) to (B-C)
1509 if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD &&
1510 N0 == N1.getOperand(1).getOperand(1))
1511 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1.getOperand(0),
1512 N1.getOperand(1).getOperand(0));
1513 // fold (A+((B-A)+or-C)) to (B+or-C)
1514 if ((N1.getOpcode() == ISD::SUB || N1.getOpcode() == ISD::ADD) &&
1515 N1.getOperand(0).getOpcode() == ISD::SUB &&
1516 N0 == N1.getOperand(0).getOperand(1))
1517 return DAG.getNode(N1.getOpcode(), SDLoc(N), VT,
1518 N1.getOperand(0).getOperand(0), N1.getOperand(1));
1520 // fold (A-B)+(C-D) to (A+C)-(B+D) when A or C is constant
1521 if (N0.getOpcode() == ISD::SUB && N1.getOpcode() == ISD::SUB) {
1522 SDValue N00 = N0.getOperand(0);
1523 SDValue N01 = N0.getOperand(1);
1524 SDValue N10 = N1.getOperand(0);
1525 SDValue N11 = N1.getOperand(1);
1527 if (isa<ConstantSDNode>(N00) || isa<ConstantSDNode>(N10))
1528 return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1529 DAG.getNode(ISD::ADD, SDLoc(N0), VT, N00, N10),
1530 DAG.getNode(ISD::ADD, SDLoc(N1), VT, N01, N11));
1533 if (!VT.isVector() && SimplifyDemandedBits(SDValue(N, 0)))
1534 return SDValue(N, 0);
1536 // fold (a+b) -> (a|b) iff a and b share no bits.
1537 if (VT.isInteger() && !VT.isVector()) {
1538 APInt LHSZero, LHSOne;
1539 APInt RHSZero, RHSOne;
1540 DAG.ComputeMaskedBits(N0, LHSZero, LHSOne);
1542 if (LHSZero.getBoolValue()) {
1543 DAG.ComputeMaskedBits(N1, RHSZero, RHSOne);
1545 // If all possibly-set bits on the LHS are clear on the RHS, return an OR.
1546 // If all possibly-set bits on the RHS are clear on the LHS, return an OR.
1547 if ((RHSZero & ~LHSZero) == ~LHSZero || (LHSZero & ~RHSZero) == ~RHSZero)
1548 return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N1);
1552 // fold (add (shl (add x, c1), c2), ) -> (add (add (shl x, c2), c1<<c2), )
1553 if (N0.getOpcode() == ISD::SHL && N0.getNode()->hasOneUse()) {
1554 SDValue Result = combineShlAddConstant(SDLoc(N), N0, N1, DAG);
1555 if (Result.getNode()) return Result;
1557 if (N1.getOpcode() == ISD::SHL && N1.getNode()->hasOneUse()) {
1558 SDValue Result = combineShlAddConstant(SDLoc(N), N1, N0, DAG);
1559 if (Result.getNode()) return Result;
1562 // fold (add x, shl(0 - y, n)) -> sub(x, shl(y, n))
1563 if (N1.getOpcode() == ISD::SHL &&
1564 N1.getOperand(0).getOpcode() == ISD::SUB)
1565 if (ConstantSDNode *C =
1566 dyn_cast<ConstantSDNode>(N1.getOperand(0).getOperand(0)))
1567 if (C->getAPIntValue() == 0)
1568 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N0,
1569 DAG.getNode(ISD::SHL, SDLoc(N), VT,
1570 N1.getOperand(0).getOperand(1),
1572 if (N0.getOpcode() == ISD::SHL &&
1573 N0.getOperand(0).getOpcode() == ISD::SUB)
1574 if (ConstantSDNode *C =
1575 dyn_cast<ConstantSDNode>(N0.getOperand(0).getOperand(0)))
1576 if (C->getAPIntValue() == 0)
1577 return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1,
1578 DAG.getNode(ISD::SHL, SDLoc(N), VT,
1579 N0.getOperand(0).getOperand(1),
1582 if (N1.getOpcode() == ISD::AND) {
1583 SDValue AndOp0 = N1.getOperand(0);
1584 ConstantSDNode *AndOp1 = dyn_cast<ConstantSDNode>(N1->getOperand(1));
1585 unsigned NumSignBits = DAG.ComputeNumSignBits(AndOp0);
1586 unsigned DestBits = VT.getScalarType().getSizeInBits();
1588 // (add z, (and (sbbl x, x), 1)) -> (sub z, (sbbl x, x))
1589 // and similar xforms where the inner op is either ~0 or 0.
1590 if (NumSignBits == DestBits && AndOp1 && AndOp1->isOne()) {
1592 return DAG.getNode(ISD::SUB, DL, VT, N->getOperand(0), AndOp0);
1596 // add (sext i1), X -> sub X, (zext i1)
1597 if (N0.getOpcode() == ISD::SIGN_EXTEND &&
1598 N0.getOperand(0).getValueType() == MVT::i1 &&
1599 !TLI.isOperationLegal(ISD::SIGN_EXTEND, MVT::i1)) {
1601 SDValue ZExt = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0));
1602 return DAG.getNode(ISD::SUB, DL, VT, N1, ZExt);
1608 SDValue DAGCombiner::visitADDC(SDNode *N) {
1609 SDValue N0 = N->getOperand(0);
1610 SDValue N1 = N->getOperand(1);
1611 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1612 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1613 EVT VT = N0.getValueType();
1615 // If the flag result is dead, turn this into an ADD.
1616 if (!N->hasAnyUseOfValue(1))
1617 return CombineTo(N, DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, N1),
1618 DAG.getNode(ISD::CARRY_FALSE,
1619 SDLoc(N), MVT::Glue));
1621 // canonicalize constant to RHS.
1623 return DAG.getNode(ISD::ADDC, SDLoc(N), N->getVTList(), N1, N0);
1625 // fold (addc x, 0) -> x + no carry out
1626 if (N1C && N1C->isNullValue())
1627 return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE,
1628 SDLoc(N), MVT::Glue));
1630 // fold (addc a, b) -> (or a, b), CARRY_FALSE iff a and b share no bits.
1631 APInt LHSZero, LHSOne;
1632 APInt RHSZero, RHSOne;
1633 DAG.ComputeMaskedBits(N0, LHSZero, LHSOne);
1635 if (LHSZero.getBoolValue()) {
1636 DAG.ComputeMaskedBits(N1, RHSZero, RHSOne);
1638 // If all possibly-set bits on the LHS are clear on the RHS, return an OR.
1639 // If all possibly-set bits on the RHS are clear on the LHS, return an OR.
1640 if ((RHSZero & ~LHSZero) == ~LHSZero || (LHSZero & ~RHSZero) == ~RHSZero)
1641 return CombineTo(N, DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N1),
1642 DAG.getNode(ISD::CARRY_FALSE,
1643 SDLoc(N), MVT::Glue));
1649 SDValue DAGCombiner::visitADDE(SDNode *N) {
1650 SDValue N0 = N->getOperand(0);
1651 SDValue N1 = N->getOperand(1);
1652 SDValue CarryIn = N->getOperand(2);
1653 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1654 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1656 // canonicalize constant to RHS
1658 return DAG.getNode(ISD::ADDE, SDLoc(N), N->getVTList(),
1661 // fold (adde x, y, false) -> (addc x, y)
1662 if (CarryIn.getOpcode() == ISD::CARRY_FALSE)
1663 return DAG.getNode(ISD::ADDC, SDLoc(N), N->getVTList(), N0, N1);
1668 // Since it may not be valid to emit a fold to zero for vector initializers
1669 // check if we can before folding.
1670 static SDValue tryFoldToZero(SDLoc DL, const TargetLowering &TLI, EVT VT,
1672 bool LegalOperations, bool LegalTypes) {
1674 return DAG.getConstant(0, VT);
1675 if (!LegalOperations || TLI.isOperationLegal(ISD::BUILD_VECTOR, VT))
1676 return DAG.getConstant(0, VT);
1680 SDValue DAGCombiner::visitSUB(SDNode *N) {
1681 SDValue N0 = N->getOperand(0);
1682 SDValue N1 = N->getOperand(1);
1683 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getNode());
1684 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
1685 ConstantSDNode *N1C1 = N1.getOpcode() != ISD::ADD ? 0 :
1686 dyn_cast<ConstantSDNode>(N1.getOperand(1).getNode());
1687 EVT VT = N0.getValueType();
1690 if (VT.isVector()) {
1691 SDValue FoldedVOp = SimplifyVBinOp(N);
1692 if (FoldedVOp.getNode()) return FoldedVOp;
1694 // fold (sub x, 0) -> x, vector edition
1695 if (ISD::isBuildVectorAllZeros(N1.getNode()))
1699 // fold (sub x, x) -> 0
1700 // FIXME: Refactor this and xor and other similar operations together.
1702 return tryFoldToZero(SDLoc(N), TLI, VT, DAG, LegalOperations, LegalTypes);
1703 // fold (sub c1, c2) -> c1-c2
1705 return DAG.FoldConstantArithmetic(ISD::SUB, VT, N0C, N1C);
1706 // fold (sub x, c) -> (add x, -c)
1708 return DAG.getNode(ISD::ADD, SDLoc(N), VT, N0,
1709 DAG.getConstant(-N1C->getAPIntValue(), VT));
1710 // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1)
1711 if (N0C && N0C->isAllOnesValue())
1712 return DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0);
1713 // fold A-(A-B) -> B
1714 if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(0))
1715 return N1.getOperand(1);
1716 // fold (A+B)-A -> B
1717 if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1)
1718 return N0.getOperand(1);
1719 // fold (A+B)-B -> A
1720 if (N0.getOpcode() == ISD::ADD && N0.getOperand(1) == N1)
1721 return N0.getOperand(0);
1722 // fold C2-(A+C1) -> (C2-C1)-A
1723 if (N1.getOpcode() == ISD::ADD && N0C && N1C1) {
1724 SDValue NewC = DAG.getConstant(N0C->getAPIntValue() - N1C1->getAPIntValue(),
1726 return DAG.getNode(ISD::SUB, SDLoc(N), VT, NewC,
1729 // fold ((A+(B+or-C))-B) -> A+or-C
1730 if (N0.getOpcode() == ISD::ADD &&
1731 (N0.getOperand(1).getOpcode() == ISD::SUB ||
1732 N0.getOperand(1).getOpcode() == ISD::ADD) &&
1733 N0.getOperand(1).getOperand(0) == N1)
1734 return DAG.getNode(N0.getOperand(1).getOpcode(), SDLoc(N), VT,
1735 N0.getOperand(0), N0.getOperand(1).getOperand(1));
1736 // fold ((A+(C+B))-B) -> A+C
1737 if (N0.getOpcode() == ISD::ADD &&
1738 N0.getOperand(1).getOpcode() == ISD::ADD &&
1739 N0.getOperand(1).getOperand(1) == N1)
1740 return DAG.getNode(ISD::ADD, SDLoc(N), VT,
1741 N0.getOperand(0), N0.getOperand(1).getOperand(0));
1742 // fold ((A-(B-C))-C) -> A-B
1743 if (N0.getOpcode() == ISD::SUB &&
1744 N0.getOperand(1).getOpcode() == ISD::SUB &&
1745 N0.getOperand(1).getOperand(1) == N1)
1746 return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1747 N0.getOperand(0), N0.getOperand(1).getOperand(0));
1749 // If either operand of a sub is undef, the result is undef
1750 if (N0.getOpcode() == ISD::UNDEF)
1752 if (N1.getOpcode() == ISD::UNDEF)
1755 // If the relocation model supports it, consider symbol offsets.
1756 if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N0))
1757 if (!LegalOperations && TLI.isOffsetFoldingLegal(GA)) {
1758 // fold (sub Sym, c) -> Sym-c
1759 if (N1C && GA->getOpcode() == ISD::GlobalAddress)
1760 return DAG.getGlobalAddress(GA->getGlobal(), SDLoc(N1C), VT,
1762 (uint64_t)N1C->getSExtValue());
1763 // fold (sub Sym+c1, Sym+c2) -> c1-c2
1764 if (GlobalAddressSDNode *GB = dyn_cast<GlobalAddressSDNode>(N1))
1765 if (GA->getGlobal() == GB->getGlobal())
1766 return DAG.getConstant((uint64_t)GA->getOffset() - GB->getOffset(),
1773 SDValue DAGCombiner::visitSUBC(SDNode *N) {
1774 SDValue N0 = N->getOperand(0);
1775 SDValue N1 = N->getOperand(1);
1776 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1777 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1778 EVT VT = N0.getValueType();
1780 // If the flag result is dead, turn this into an SUB.
1781 if (!N->hasAnyUseOfValue(1))
1782 return CombineTo(N, DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, N1),
1783 DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
1786 // fold (subc x, x) -> 0 + no borrow
1788 return CombineTo(N, DAG.getConstant(0, VT),
1789 DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
1792 // fold (subc x, 0) -> x + no borrow
1793 if (N1C && N1C->isNullValue())
1794 return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
1797 // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1) + no borrow
1798 if (N0C && N0C->isAllOnesValue())
1799 return CombineTo(N, DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0),
1800 DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
1806 SDValue DAGCombiner::visitSUBE(SDNode *N) {
1807 SDValue N0 = N->getOperand(0);
1808 SDValue N1 = N->getOperand(1);
1809 SDValue CarryIn = N->getOperand(2);
1811 // fold (sube x, y, false) -> (subc x, y)
1812 if (CarryIn.getOpcode() == ISD::CARRY_FALSE)
1813 return DAG.getNode(ISD::SUBC, SDLoc(N), N->getVTList(), N0, N1);
1818 /// isConstantSplatVector - Returns true if N is a BUILD_VECTOR node whose
1819 /// elements are all the same constant or undefined.
1820 static bool isConstantSplatVector(SDNode *N, APInt& SplatValue) {
1821 BuildVectorSDNode *C = dyn_cast<BuildVectorSDNode>(N);
1826 unsigned SplatBitSize;
1828 EVT EltVT = N->getValueType(0).getVectorElementType();
1829 return (C->isConstantSplat(SplatValue, SplatUndef, SplatBitSize,
1831 EltVT.getSizeInBits() >= SplatBitSize);
1834 SDValue DAGCombiner::visitMUL(SDNode *N) {
1835 SDValue N0 = N->getOperand(0);
1836 SDValue N1 = N->getOperand(1);
1837 EVT VT = N0.getValueType();
1839 // fold (mul x, undef) -> 0
1840 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
1841 return DAG.getConstant(0, VT);
1843 bool N0IsConst = false;
1844 bool N1IsConst = false;
1845 APInt ConstValue0, ConstValue1;
1847 if (VT.isVector()) {
1848 SDValue FoldedVOp = SimplifyVBinOp(N);
1849 if (FoldedVOp.getNode()) return FoldedVOp;
1851 N0IsConst = isConstantSplatVector(N0.getNode(), ConstValue0);
1852 N1IsConst = isConstantSplatVector(N1.getNode(), ConstValue1);
1854 N0IsConst = dyn_cast<ConstantSDNode>(N0) != 0;
1855 ConstValue0 = N0IsConst ? (dyn_cast<ConstantSDNode>(N0))->getAPIntValue()
1857 N1IsConst = dyn_cast<ConstantSDNode>(N1) != 0;
1858 ConstValue1 = N1IsConst ? (dyn_cast<ConstantSDNode>(N1))->getAPIntValue()
1862 // fold (mul c1, c2) -> c1*c2
1863 if (N0IsConst && N1IsConst)
1864 return DAG.FoldConstantArithmetic(ISD::MUL, VT, N0.getNode(), N1.getNode());
1866 // canonicalize constant to RHS
1867 if (N0IsConst && !N1IsConst)
1868 return DAG.getNode(ISD::MUL, SDLoc(N), VT, N1, N0);
1869 // fold (mul x, 0) -> 0
1870 if (N1IsConst && ConstValue1 == 0)
1872 // We require a splat of the entire scalar bit width for non-contiguous
1875 ConstValue1.getBitWidth() == VT.getScalarType().getSizeInBits();
1876 // fold (mul x, 1) -> x
1877 if (N1IsConst && ConstValue1 == 1 && IsFullSplat)
1879 // fold (mul x, -1) -> 0-x
1880 if (N1IsConst && ConstValue1.isAllOnesValue())
1881 return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1882 DAG.getConstant(0, VT), N0);
1883 // fold (mul x, (1 << c)) -> x << c
1884 if (N1IsConst && ConstValue1.isPowerOf2() && IsFullSplat)
1885 return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0,
1886 DAG.getConstant(ConstValue1.logBase2(),
1887 getShiftAmountTy(N0.getValueType())));
1888 // fold (mul x, -(1 << c)) -> -(x << c) or (-x) << c
1889 if (N1IsConst && (-ConstValue1).isPowerOf2() && IsFullSplat) {
1890 unsigned Log2Val = (-ConstValue1).logBase2();
1891 // FIXME: If the input is something that is easily negated (e.g. a
1892 // single-use add), we should put the negate there.
1893 return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1894 DAG.getConstant(0, VT),
1895 DAG.getNode(ISD::SHL, SDLoc(N), VT, N0,
1896 DAG.getConstant(Log2Val,
1897 getShiftAmountTy(N0.getValueType()))));
1901 // (mul (shl X, c1), c2) -> (mul X, c2 << c1)
1902 if (N1IsConst && N0.getOpcode() == ISD::SHL &&
1903 (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
1904 isa<ConstantSDNode>(N0.getOperand(1)))) {
1905 SDValue C3 = DAG.getNode(ISD::SHL, SDLoc(N), VT,
1906 N1, N0.getOperand(1));
1907 AddToWorkList(C3.getNode());
1908 return DAG.getNode(ISD::MUL, SDLoc(N), VT,
1909 N0.getOperand(0), C3);
1912 // Change (mul (shl X, C), Y) -> (shl (mul X, Y), C) when the shift has one
1915 SDValue Sh(0,0), Y(0,0);
1916 // Check for both (mul (shl X, C), Y) and (mul Y, (shl X, C)).
1917 if (N0.getOpcode() == ISD::SHL &&
1918 (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
1919 isa<ConstantSDNode>(N0.getOperand(1))) &&
1920 N0.getNode()->hasOneUse()) {
1922 } else if (N1.getOpcode() == ISD::SHL &&
1923 isa<ConstantSDNode>(N1.getOperand(1)) &&
1924 N1.getNode()->hasOneUse()) {
1929 SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT,
1930 Sh.getOperand(0), Y);
1931 return DAG.getNode(ISD::SHL, SDLoc(N), VT,
1932 Mul, Sh.getOperand(1));
1936 // fold (mul (add x, c1), c2) -> (add (mul x, c2), c1*c2)
1937 if (N1IsConst && N0.getOpcode() == ISD::ADD && N0.getNode()->hasOneUse() &&
1938 (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
1939 isa<ConstantSDNode>(N0.getOperand(1))))
1940 return DAG.getNode(ISD::ADD, SDLoc(N), VT,
1941 DAG.getNode(ISD::MUL, SDLoc(N0), VT,
1942 N0.getOperand(0), N1),
1943 DAG.getNode(ISD::MUL, SDLoc(N1), VT,
1944 N0.getOperand(1), N1));
1947 SDValue RMUL = ReassociateOps(ISD::MUL, SDLoc(N), N0, N1);
1948 if (RMUL.getNode() != 0)
1954 SDValue DAGCombiner::visitSDIV(SDNode *N) {
1955 SDValue N0 = N->getOperand(0);
1956 SDValue N1 = N->getOperand(1);
1957 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getNode());
1958 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
1959 EVT VT = N->getValueType(0);
1962 if (VT.isVector()) {
1963 SDValue FoldedVOp = SimplifyVBinOp(N);
1964 if (FoldedVOp.getNode()) return FoldedVOp;
1967 // fold (sdiv c1, c2) -> c1/c2
1968 if (N0C && N1C && !N1C->isNullValue())
1969 return DAG.FoldConstantArithmetic(ISD::SDIV, VT, N0C, N1C);
1970 // fold (sdiv X, 1) -> X
1971 if (N1C && N1C->getAPIntValue() == 1LL)
1973 // fold (sdiv X, -1) -> 0-X
1974 if (N1C && N1C->isAllOnesValue())
1975 return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1976 DAG.getConstant(0, VT), N0);
1977 // If we know the sign bits of both operands are zero, strength reduce to a
1978 // udiv instead. Handles (X&15) /s 4 -> X&15 >> 2
1979 if (!VT.isVector()) {
1980 if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
1981 return DAG.getNode(ISD::UDIV, SDLoc(N), N1.getValueType(),
1984 // fold (sdiv X, pow2) -> simple ops after legalize
1985 if (N1C && !N1C->isNullValue() &&
1986 (N1C->getAPIntValue().isPowerOf2() ||
1987 (-N1C->getAPIntValue()).isPowerOf2())) {
1988 // If dividing by powers of two is cheap, then don't perform the following
1990 if (TLI.isPow2DivCheap())
1993 unsigned lg2 = N1C->getAPIntValue().countTrailingZeros();
1995 // Splat the sign bit into the register
1996 SDValue SGN = DAG.getNode(ISD::SRA, SDLoc(N), VT, N0,
1997 DAG.getConstant(VT.getSizeInBits()-1,
1998 getShiftAmountTy(N0.getValueType())));
1999 AddToWorkList(SGN.getNode());
2001 // Add (N0 < 0) ? abs2 - 1 : 0;
2002 SDValue SRL = DAG.getNode(ISD::SRL, SDLoc(N), VT, SGN,
2003 DAG.getConstant(VT.getSizeInBits() - lg2,
2004 getShiftAmountTy(SGN.getValueType())));
2005 SDValue ADD = DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, SRL);
2006 AddToWorkList(SRL.getNode());
2007 AddToWorkList(ADD.getNode()); // Divide by pow2
2008 SDValue SRA = DAG.getNode(ISD::SRA, SDLoc(N), VT, ADD,
2009 DAG.getConstant(lg2, getShiftAmountTy(ADD.getValueType())));
2011 // If we're dividing by a positive value, we're done. Otherwise, we must
2012 // negate the result.
2013 if (N1C->getAPIntValue().isNonNegative())
2016 AddToWorkList(SRA.getNode());
2017 return DAG.getNode(ISD::SUB, SDLoc(N), VT,
2018 DAG.getConstant(0, VT), SRA);
2021 // if integer divide is expensive and we satisfy the requirements, emit an
2022 // alternate sequence.
2023 if (N1C && !N1C->isNullValue() && !TLI.isIntDivCheap()) {
2024 SDValue Op = BuildSDIV(N);
2025 if (Op.getNode()) return Op;
2029 if (N0.getOpcode() == ISD::UNDEF)
2030 return DAG.getConstant(0, VT);
2031 // X / undef -> undef
2032 if (N1.getOpcode() == ISD::UNDEF)
2038 SDValue DAGCombiner::visitUDIV(SDNode *N) {
2039 SDValue N0 = N->getOperand(0);
2040 SDValue N1 = N->getOperand(1);
2041 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getNode());
2042 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
2043 EVT VT = N->getValueType(0);
2046 if (VT.isVector()) {
2047 SDValue FoldedVOp = SimplifyVBinOp(N);
2048 if (FoldedVOp.getNode()) return FoldedVOp;
2051 // fold (udiv c1, c2) -> c1/c2
2052 if (N0C && N1C && !N1C->isNullValue())
2053 return DAG.FoldConstantArithmetic(ISD::UDIV, VT, N0C, N1C);
2054 // fold (udiv x, (1 << c)) -> x >>u c
2055 if (N1C && N1C->getAPIntValue().isPowerOf2())
2056 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0,
2057 DAG.getConstant(N1C->getAPIntValue().logBase2(),
2058 getShiftAmountTy(N0.getValueType())));
2059 // fold (udiv x, (shl c, y)) -> x >>u (log2(c)+y) iff c is power of 2
2060 if (N1.getOpcode() == ISD::SHL) {
2061 if (ConstantSDNode *SHC = dyn_cast<ConstantSDNode>(N1.getOperand(0))) {
2062 if (SHC->getAPIntValue().isPowerOf2()) {
2063 EVT ADDVT = N1.getOperand(1).getValueType();
2064 SDValue Add = DAG.getNode(ISD::ADD, SDLoc(N), ADDVT,
2066 DAG.getConstant(SHC->getAPIntValue()
2069 AddToWorkList(Add.getNode());
2070 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, Add);
2074 // fold (udiv x, c) -> alternate
2075 if (N1C && !N1C->isNullValue() && !TLI.isIntDivCheap()) {
2076 SDValue Op = BuildUDIV(N);
2077 if (Op.getNode()) return Op;
2081 if (N0.getOpcode() == ISD::UNDEF)
2082 return DAG.getConstant(0, VT);
2083 // X / undef -> undef
2084 if (N1.getOpcode() == ISD::UNDEF)
2090 SDValue DAGCombiner::visitSREM(SDNode *N) {
2091 SDValue N0 = N->getOperand(0);
2092 SDValue N1 = N->getOperand(1);
2093 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
2094 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2095 EVT VT = N->getValueType(0);
2097 // fold (srem c1, c2) -> c1%c2
2098 if (N0C && N1C && !N1C->isNullValue())
2099 return DAG.FoldConstantArithmetic(ISD::SREM, VT, N0C, N1C);
2100 // If we know the sign bits of both operands are zero, strength reduce to a
2101 // urem instead. Handles (X & 0x0FFFFFFF) %s 16 -> X&15
2102 if (!VT.isVector()) {
2103 if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
2104 return DAG.getNode(ISD::UREM, SDLoc(N), VT, N0, N1);
2107 // If X/C can be simplified by the division-by-constant logic, lower
2108 // X%C to the equivalent of X-X/C*C.
2109 if (N1C && !N1C->isNullValue()) {
2110 SDValue Div = DAG.getNode(ISD::SDIV, SDLoc(N), VT, N0, N1);
2111 AddToWorkList(Div.getNode());
2112 SDValue OptimizedDiv = combine(Div.getNode());
2113 if (OptimizedDiv.getNode() && OptimizedDiv.getNode() != Div.getNode()) {
2114 SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT,
2116 SDValue Sub = DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, Mul);
2117 AddToWorkList(Mul.getNode());
2123 if (N0.getOpcode() == ISD::UNDEF)
2124 return DAG.getConstant(0, VT);
2125 // X % undef -> undef
2126 if (N1.getOpcode() == ISD::UNDEF)
2132 SDValue DAGCombiner::visitUREM(SDNode *N) {
2133 SDValue N0 = N->getOperand(0);
2134 SDValue N1 = N->getOperand(1);
2135 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
2136 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2137 EVT VT = N->getValueType(0);
2139 // fold (urem c1, c2) -> c1%c2
2140 if (N0C && N1C && !N1C->isNullValue())
2141 return DAG.FoldConstantArithmetic(ISD::UREM, VT, N0C, N1C);
2142 // fold (urem x, pow2) -> (and x, pow2-1)
2143 if (N1C && !N1C->isNullValue() && N1C->getAPIntValue().isPowerOf2())
2144 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0,
2145 DAG.getConstant(N1C->getAPIntValue()-1,VT));
2146 // fold (urem x, (shl pow2, y)) -> (and x, (add (shl pow2, y), -1))
2147 if (N1.getOpcode() == ISD::SHL) {
2148 if (ConstantSDNode *SHC = dyn_cast<ConstantSDNode>(N1.getOperand(0))) {
2149 if (SHC->getAPIntValue().isPowerOf2()) {
2151 DAG.getNode(ISD::ADD, SDLoc(N), VT, N1,
2152 DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()),
2154 AddToWorkList(Add.getNode());
2155 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, Add);
2160 // If X/C can be simplified by the division-by-constant logic, lower
2161 // X%C to the equivalent of X-X/C*C.
2162 if (N1C && !N1C->isNullValue()) {
2163 SDValue Div = DAG.getNode(ISD::UDIV, SDLoc(N), VT, N0, N1);
2164 AddToWorkList(Div.getNode());
2165 SDValue OptimizedDiv = combine(Div.getNode());
2166 if (OptimizedDiv.getNode() && OptimizedDiv.getNode() != Div.getNode()) {
2167 SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT,
2169 SDValue Sub = DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, Mul);
2170 AddToWorkList(Mul.getNode());
2176 if (N0.getOpcode() == ISD::UNDEF)
2177 return DAG.getConstant(0, VT);
2178 // X % undef -> undef
2179 if (N1.getOpcode() == ISD::UNDEF)
2185 SDValue DAGCombiner::visitMULHS(SDNode *N) {
2186 SDValue N0 = N->getOperand(0);
2187 SDValue N1 = N->getOperand(1);
2188 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2189 EVT VT = N->getValueType(0);
2192 // fold (mulhs x, 0) -> 0
2193 if (N1C && N1C->isNullValue())
2195 // fold (mulhs x, 1) -> (sra x, size(x)-1)
2196 if (N1C && N1C->getAPIntValue() == 1)
2197 return DAG.getNode(ISD::SRA, SDLoc(N), N0.getValueType(), N0,
2198 DAG.getConstant(N0.getValueType().getSizeInBits() - 1,
2199 getShiftAmountTy(N0.getValueType())));
2200 // fold (mulhs x, undef) -> 0
2201 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2202 return DAG.getConstant(0, VT);
2204 // If the type twice as wide is legal, transform the mulhs to a wider multiply
2206 if (VT.isSimple() && !VT.isVector()) {
2207 MVT Simple = VT.getSimpleVT();
2208 unsigned SimpleSize = Simple.getSizeInBits();
2209 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2210 if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2211 N0 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N0);
2212 N1 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N1);
2213 N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1);
2214 N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1,
2215 DAG.getConstant(SimpleSize, getShiftAmountTy(N1.getValueType())));
2216 return DAG.getNode(ISD::TRUNCATE, DL, VT, N1);
2223 SDValue DAGCombiner::visitMULHU(SDNode *N) {
2224 SDValue N0 = N->getOperand(0);
2225 SDValue N1 = N->getOperand(1);
2226 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2227 EVT VT = N->getValueType(0);
2230 // fold (mulhu x, 0) -> 0
2231 if (N1C && N1C->isNullValue())
2233 // fold (mulhu x, 1) -> 0
2234 if (N1C && N1C->getAPIntValue() == 1)
2235 return DAG.getConstant(0, N0.getValueType());
2236 // fold (mulhu x, undef) -> 0
2237 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2238 return DAG.getConstant(0, VT);
2240 // If the type twice as wide is legal, transform the mulhu to a wider multiply
2242 if (VT.isSimple() && !VT.isVector()) {
2243 MVT Simple = VT.getSimpleVT();
2244 unsigned SimpleSize = Simple.getSizeInBits();
2245 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2246 if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2247 N0 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N0);
2248 N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N1);
2249 N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1);
2250 N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1,
2251 DAG.getConstant(SimpleSize, getShiftAmountTy(N1.getValueType())));
2252 return DAG.getNode(ISD::TRUNCATE, DL, VT, N1);
2259 /// SimplifyNodeWithTwoResults - Perform optimizations common to nodes that
2260 /// compute two values. LoOp and HiOp give the opcodes for the two computations
2261 /// that are being performed. Return true if a simplification was made.
2263 SDValue DAGCombiner::SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp,
2265 // If the high half is not needed, just compute the low half.
2266 bool HiExists = N->hasAnyUseOfValue(1);
2268 (!LegalOperations ||
2269 TLI.isOperationLegalOrCustom(LoOp, N->getValueType(0)))) {
2270 SDValue Res = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0),
2271 N->op_begin(), N->getNumOperands());
2272 return CombineTo(N, Res, Res);
2275 // If the low half is not needed, just compute the high half.
2276 bool LoExists = N->hasAnyUseOfValue(0);
2278 (!LegalOperations ||
2279 TLI.isOperationLegal(HiOp, N->getValueType(1)))) {
2280 SDValue Res = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1),
2281 N->op_begin(), N->getNumOperands());
2282 return CombineTo(N, Res, Res);
2285 // If both halves are used, return as it is.
2286 if (LoExists && HiExists)
2289 // If the two computed results can be simplified separately, separate them.
2291 SDValue Lo = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0),
2292 N->op_begin(), N->getNumOperands());
2293 AddToWorkList(Lo.getNode());
2294 SDValue LoOpt = combine(Lo.getNode());
2295 if (LoOpt.getNode() && LoOpt.getNode() != Lo.getNode() &&
2296 (!LegalOperations ||
2297 TLI.isOperationLegal(LoOpt.getOpcode(), LoOpt.getValueType())))
2298 return CombineTo(N, LoOpt, LoOpt);
2302 SDValue Hi = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1),
2303 N->op_begin(), N->getNumOperands());
2304 AddToWorkList(Hi.getNode());
2305 SDValue HiOpt = combine(Hi.getNode());
2306 if (HiOpt.getNode() && HiOpt != Hi &&
2307 (!LegalOperations ||
2308 TLI.isOperationLegal(HiOpt.getOpcode(), HiOpt.getValueType())))
2309 return CombineTo(N, HiOpt, HiOpt);
2315 SDValue DAGCombiner::visitSMUL_LOHI(SDNode *N) {
2316 SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHS);
2317 if (Res.getNode()) return Res;
2319 EVT VT = N->getValueType(0);
2322 // If the type twice as wide is legal, transform the mulhu to a wider multiply
2324 if (VT.isSimple() && !VT.isVector()) {
2325 MVT Simple = VT.getSimpleVT();
2326 unsigned SimpleSize = Simple.getSizeInBits();
2327 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2328 if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2329 SDValue Lo = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(0));
2330 SDValue Hi = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(1));
2331 Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi);
2332 // Compute the high part as N1.
2333 Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo,
2334 DAG.getConstant(SimpleSize, getShiftAmountTy(Lo.getValueType())));
2335 Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi);
2336 // Compute the low part as N0.
2337 Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo);
2338 return CombineTo(N, Lo, Hi);
2345 SDValue DAGCombiner::visitUMUL_LOHI(SDNode *N) {
2346 SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHU);
2347 if (Res.getNode()) return Res;
2349 EVT VT = N->getValueType(0);
2352 // If the type twice as wide is legal, transform the mulhu to a wider multiply
2354 if (VT.isSimple() && !VT.isVector()) {
2355 MVT Simple = VT.getSimpleVT();
2356 unsigned SimpleSize = Simple.getSizeInBits();
2357 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2358 if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2359 SDValue Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(0));
2360 SDValue Hi = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(1));
2361 Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi);
2362 // Compute the high part as N1.
2363 Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo,
2364 DAG.getConstant(SimpleSize, getShiftAmountTy(Lo.getValueType())));
2365 Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi);
2366 // Compute the low part as N0.
2367 Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo);
2368 return CombineTo(N, Lo, Hi);
2375 SDValue DAGCombiner::visitSMULO(SDNode *N) {
2376 // (smulo x, 2) -> (saddo x, x)
2377 if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1)))
2378 if (C2->getAPIntValue() == 2)
2379 return DAG.getNode(ISD::SADDO, SDLoc(N), N->getVTList(),
2380 N->getOperand(0), N->getOperand(0));
2385 SDValue DAGCombiner::visitUMULO(SDNode *N) {
2386 // (umulo x, 2) -> (uaddo x, x)
2387 if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1)))
2388 if (C2->getAPIntValue() == 2)
2389 return DAG.getNode(ISD::UADDO, SDLoc(N), N->getVTList(),
2390 N->getOperand(0), N->getOperand(0));
2395 SDValue DAGCombiner::visitSDIVREM(SDNode *N) {
2396 SDValue Res = SimplifyNodeWithTwoResults(N, ISD::SDIV, ISD::SREM);
2397 if (Res.getNode()) return Res;
2402 SDValue DAGCombiner::visitUDIVREM(SDNode *N) {
2403 SDValue Res = SimplifyNodeWithTwoResults(N, ISD::UDIV, ISD::UREM);
2404 if (Res.getNode()) return Res;
2409 /// SimplifyBinOpWithSameOpcodeHands - If this is a binary operator with
2410 /// two operands of the same opcode, try to simplify it.
2411 SDValue DAGCombiner::SimplifyBinOpWithSameOpcodeHands(SDNode *N) {
2412 SDValue N0 = N->getOperand(0), N1 = N->getOperand(1);
2413 EVT VT = N0.getValueType();
2414 assert(N0.getOpcode() == N1.getOpcode() && "Bad input!");
2416 // Bail early if none of these transforms apply.
2417 if (N0.getNode()->getNumOperands() == 0) return SDValue();
2419 // For each of OP in AND/OR/XOR:
2420 // fold (OP (zext x), (zext y)) -> (zext (OP x, y))
2421 // fold (OP (sext x), (sext y)) -> (sext (OP x, y))
2422 // fold (OP (aext x), (aext y)) -> (aext (OP x, y))
2423 // fold (OP (trunc x), (trunc y)) -> (trunc (OP x, y)) (if trunc isn't free)
2425 // do not sink logical op inside of a vector extend, since it may combine
2427 EVT Op0VT = N0.getOperand(0).getValueType();
2428 if ((N0.getOpcode() == ISD::ZERO_EXTEND ||
2429 N0.getOpcode() == ISD::SIGN_EXTEND ||
2430 // Avoid infinite looping with PromoteIntBinOp.
2431 (N0.getOpcode() == ISD::ANY_EXTEND &&
2432 (!LegalTypes || TLI.isTypeDesirableForOp(N->getOpcode(), Op0VT))) ||
2433 (N0.getOpcode() == ISD::TRUNCATE &&
2434 (!TLI.isZExtFree(VT, Op0VT) ||
2435 !TLI.isTruncateFree(Op0VT, VT)) &&
2436 TLI.isTypeLegal(Op0VT))) &&
2438 Op0VT == N1.getOperand(0).getValueType() &&
2439 (!LegalOperations || TLI.isOperationLegal(N->getOpcode(), Op0VT))) {
2440 SDValue ORNode = DAG.getNode(N->getOpcode(), SDLoc(N0),
2441 N0.getOperand(0).getValueType(),
2442 N0.getOperand(0), N1.getOperand(0));
2443 AddToWorkList(ORNode.getNode());
2444 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, ORNode);
2447 // For each of OP in SHL/SRL/SRA/AND...
2448 // fold (and (OP x, z), (OP y, z)) -> (OP (and x, y), z)
2449 // fold (or (OP x, z), (OP y, z)) -> (OP (or x, y), z)
2450 // fold (xor (OP x, z), (OP y, z)) -> (OP (xor x, y), z)
2451 if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL ||
2452 N0.getOpcode() == ISD::SRA || N0.getOpcode() == ISD::AND) &&
2453 N0.getOperand(1) == N1.getOperand(1)) {
2454 SDValue ORNode = DAG.getNode(N->getOpcode(), SDLoc(N0),
2455 N0.getOperand(0).getValueType(),
2456 N0.getOperand(0), N1.getOperand(0));
2457 AddToWorkList(ORNode.getNode());
2458 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
2459 ORNode, N0.getOperand(1));
2462 // Simplify xor/and/or (bitcast(A), bitcast(B)) -> bitcast(op (A,B))
2463 // Only perform this optimization after type legalization and before
2464 // LegalizeVectorOprs. LegalizeVectorOprs promotes vector operations by
2465 // adding bitcasts. For example (xor v4i32) is promoted to (v2i64), and
2466 // we don't want to undo this promotion.
2467 // We also handle SCALAR_TO_VECTOR because xor/or/and operations are cheaper
2469 if ((N0.getOpcode() == ISD::BITCAST ||
2470 N0.getOpcode() == ISD::SCALAR_TO_VECTOR) &&
2471 Level == AfterLegalizeTypes) {
2472 SDValue In0 = N0.getOperand(0);
2473 SDValue In1 = N1.getOperand(0);
2474 EVT In0Ty = In0.getValueType();
2475 EVT In1Ty = In1.getValueType();
2477 // If both incoming values are integers, and the original types are the
2479 if (In0Ty.isInteger() && In1Ty.isInteger() && In0Ty == In1Ty) {
2480 SDValue Op = DAG.getNode(N->getOpcode(), DL, In0Ty, In0, In1);
2481 SDValue BC = DAG.getNode(N0.getOpcode(), DL, VT, Op);
2482 AddToWorkList(Op.getNode());
2487 // Xor/and/or are indifferent to the swizzle operation (shuffle of one value).
2488 // Simplify xor/and/or (shuff(A), shuff(B)) -> shuff(op (A,B))
2489 // If both shuffles use the same mask, and both shuffle within a single
2490 // vector, then it is worthwhile to move the swizzle after the operation.
2491 // The type-legalizer generates this pattern when loading illegal
2492 // vector types from memory. In many cases this allows additional shuffle
2494 if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG &&
2495 N0.getOperand(1).getOpcode() == ISD::UNDEF &&
2496 N1.getOperand(1).getOpcode() == ISD::UNDEF) {
2497 ShuffleVectorSDNode *SVN0 = cast<ShuffleVectorSDNode>(N0);
2498 ShuffleVectorSDNode *SVN1 = cast<ShuffleVectorSDNode>(N1);
2500 assert(N0.getOperand(0).getValueType() == N1.getOperand(1).getValueType() &&
2501 "Inputs to shuffles are not the same type");
2503 unsigned NumElts = VT.getVectorNumElements();
2505 // Check that both shuffles use the same mask. The masks are known to be of
2506 // the same length because the result vector type is the same.
2507 bool SameMask = true;
2508 for (unsigned i = 0; i != NumElts; ++i) {
2509 int Idx0 = SVN0->getMaskElt(i);
2510 int Idx1 = SVN1->getMaskElt(i);
2518 SDValue Op = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
2519 N0.getOperand(0), N1.getOperand(0));
2520 AddToWorkList(Op.getNode());
2521 return DAG.getVectorShuffle(VT, SDLoc(N), Op,
2522 DAG.getUNDEF(VT), &SVN0->getMask()[0]);
2529 SDValue DAGCombiner::visitAND(SDNode *N) {
2530 SDValue N0 = N->getOperand(0);
2531 SDValue N1 = N->getOperand(1);
2532 SDValue LL, LR, RL, RR, CC0, CC1;
2533 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
2534 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2535 EVT VT = N1.getValueType();
2536 unsigned BitWidth = VT.getScalarType().getSizeInBits();
2539 if (VT.isVector()) {
2540 SDValue FoldedVOp = SimplifyVBinOp(N);
2541 if (FoldedVOp.getNode()) return FoldedVOp;
2543 // fold (and x, 0) -> 0, vector edition
2544 if (ISD::isBuildVectorAllZeros(N0.getNode()))
2546 if (ISD::isBuildVectorAllZeros(N1.getNode()))
2549 // fold (and x, -1) -> x, vector edition
2550 if (ISD::isBuildVectorAllOnes(N0.getNode()))
2552 if (ISD::isBuildVectorAllOnes(N1.getNode()))
2556 // fold (and x, undef) -> 0
2557 if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2558 return DAG.getConstant(0, VT);
2559 // fold (and c1, c2) -> c1&c2
2561 return DAG.FoldConstantArithmetic(ISD::AND, VT, N0C, N1C);
2562 // canonicalize constant to RHS
2564 return DAG.getNode(ISD::AND, SDLoc(N), VT, N1, N0);
2565 // fold (and x, -1) -> x
2566 if (N1C && N1C->isAllOnesValue())
2568 // if (and x, c) is known to be zero, return 0
2569 if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0),
2570 APInt::getAllOnesValue(BitWidth)))
2571 return DAG.getConstant(0, VT);
2573 SDValue RAND = ReassociateOps(ISD::AND, SDLoc(N), N0, N1);
2574 if (RAND.getNode() != 0)
2576 // fold (and (or x, C), D) -> D if (C & D) == D
2577 if (N1C && N0.getOpcode() == ISD::OR)
2578 if (ConstantSDNode *ORI = dyn_cast<ConstantSDNode>(N0.getOperand(1)))
2579 if ((ORI->getAPIntValue() & N1C->getAPIntValue()) == N1C->getAPIntValue())
2581 // fold (and (any_ext V), c) -> (zero_ext V) if 'and' only clears top bits.
2582 if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
2583 SDValue N0Op0 = N0.getOperand(0);
2584 APInt Mask = ~N1C->getAPIntValue();
2585 Mask = Mask.trunc(N0Op0.getValueSizeInBits());
2586 if (DAG.MaskedValueIsZero(N0Op0, Mask)) {
2587 SDValue Zext = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N),
2588 N0.getValueType(), N0Op0);
2590 // Replace uses of the AND with uses of the Zero extend node.
2593 // We actually want to replace all uses of the any_extend with the
2594 // zero_extend, to avoid duplicating things. This will later cause this
2595 // AND to be folded.
2596 CombineTo(N0.getNode(), Zext);
2597 return SDValue(N, 0); // Return N so it doesn't get rechecked!
2600 // similarly fold (and (X (load ([non_ext|any_ext|zero_ext] V))), c) ->
2601 // (X (load ([non_ext|zero_ext] V))) if 'and' only clears top bits which must
2602 // already be zero by virtue of the width of the base type of the load.
2604 // the 'X' node here can either be nothing or an extract_vector_elt to catch
2606 if ((N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
2607 N0.getOperand(0).getOpcode() == ISD::LOAD) ||
2608 N0.getOpcode() == ISD::LOAD) {
2609 LoadSDNode *Load = cast<LoadSDNode>( (N0.getOpcode() == ISD::LOAD) ?
2610 N0 : N0.getOperand(0) );
2612 // Get the constant (if applicable) the zero'th operand is being ANDed with.
2613 // This can be a pure constant or a vector splat, in which case we treat the
2614 // vector as a scalar and use the splat value.
2615 APInt Constant = APInt::getNullValue(1);
2616 if (const ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
2617 Constant = C->getAPIntValue();
2618 } else if (BuildVectorSDNode *Vector = dyn_cast<BuildVectorSDNode>(N1)) {
2619 APInt SplatValue, SplatUndef;
2620 unsigned SplatBitSize;
2622 bool IsSplat = Vector->isConstantSplat(SplatValue, SplatUndef,
2623 SplatBitSize, HasAnyUndefs);
2625 // Undef bits can contribute to a possible optimisation if set, so
2627 SplatValue |= SplatUndef;
2629 // The splat value may be something like "0x00FFFFFF", which means 0 for
2630 // the first vector value and FF for the rest, repeating. We need a mask
2631 // that will apply equally to all members of the vector, so AND all the
2632 // lanes of the constant together.
2633 EVT VT = Vector->getValueType(0);
2634 unsigned BitWidth = VT.getVectorElementType().getSizeInBits();
2636 // If the splat value has been compressed to a bitlength lower
2637 // than the size of the vector lane, we need to re-expand it to
2639 if (BitWidth > SplatBitSize)
2640 for (SplatValue = SplatValue.zextOrTrunc(BitWidth);
2641 SplatBitSize < BitWidth;
2642 SplatBitSize = SplatBitSize * 2)
2643 SplatValue |= SplatValue.shl(SplatBitSize);
2645 Constant = APInt::getAllOnesValue(BitWidth);
2646 for (unsigned i = 0, n = SplatBitSize/BitWidth; i < n; ++i)
2647 Constant &= SplatValue.lshr(i*BitWidth).zextOrTrunc(BitWidth);
2651 // If we want to change an EXTLOAD to a ZEXTLOAD, ensure a ZEXTLOAD is
2652 // actually legal and isn't going to get expanded, else this is a false
2654 bool CanZextLoadProfitably = TLI.isLoadExtLegal(ISD::ZEXTLOAD,
2655 Load->getMemoryVT());
2657 // Resize the constant to the same size as the original memory access before
2658 // extension. If it is still the AllOnesValue then this AND is completely
2661 Constant.zextOrTrunc(Load->getMemoryVT().getScalarType().getSizeInBits());
2664 switch (Load->getExtensionType()) {
2665 default: B = false; break;
2666 case ISD::EXTLOAD: B = CanZextLoadProfitably; break;
2668 case ISD::NON_EXTLOAD: B = true; break;
2671 if (B && Constant.isAllOnesValue()) {
2672 // If the load type was an EXTLOAD, convert to ZEXTLOAD in order to
2673 // preserve semantics once we get rid of the AND.
2674 SDValue NewLoad(Load, 0);
2675 if (Load->getExtensionType() == ISD::EXTLOAD) {
2676 NewLoad = DAG.getLoad(Load->getAddressingMode(), ISD::ZEXTLOAD,
2677 Load->getValueType(0), SDLoc(Load),
2678 Load->getChain(), Load->getBasePtr(),
2679 Load->getOffset(), Load->getMemoryVT(),
2680 Load->getMemOperand());
2681 // Replace uses of the EXTLOAD with the new ZEXTLOAD.
2682 if (Load->getNumValues() == 3) {
2683 // PRE/POST_INC loads have 3 values.
2684 SDValue To[] = { NewLoad.getValue(0), NewLoad.getValue(1),
2685 NewLoad.getValue(2) };
2686 CombineTo(Load, To, 3, true);
2688 CombineTo(Load, NewLoad.getValue(0), NewLoad.getValue(1));
2692 // Fold the AND away, taking care not to fold to the old load node if we
2694 CombineTo(N, (N0.getNode() == Load) ? NewLoad : N0);
2696 return SDValue(N, 0); // Return N so it doesn't get rechecked!
2699 // fold (and (setcc x), (setcc y)) -> (setcc (and x, y))
2700 if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){
2701 ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get();
2702 ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get();
2704 if (LR == RR && isa<ConstantSDNode>(LR) && Op0 == Op1 &&
2705 LL.getValueType().isInteger()) {
2706 // fold (and (seteq X, 0), (seteq Y, 0)) -> (seteq (or X, Y), 0)
2707 if (cast<ConstantSDNode>(LR)->isNullValue() && Op1 == ISD::SETEQ) {
2708 SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(N0),
2709 LR.getValueType(), LL, RL);
2710 AddToWorkList(ORNode.getNode());
2711 return DAG.getSetCC(SDLoc(N), VT, ORNode, LR, Op1);
2713 // fold (and (seteq X, -1), (seteq Y, -1)) -> (seteq (and X, Y), -1)
2714 if (cast<ConstantSDNode>(LR)->isAllOnesValue() && Op1 == ISD::SETEQ) {
2715 SDValue ANDNode = DAG.getNode(ISD::AND, SDLoc(N0),
2716 LR.getValueType(), LL, RL);
2717 AddToWorkList(ANDNode.getNode());
2718 return DAG.getSetCC(SDLoc(N), VT, ANDNode, LR, Op1);
2720 // fold (and (setgt X, -1), (setgt Y, -1)) -> (setgt (or X, Y), -1)
2721 if (cast<ConstantSDNode>(LR)->isAllOnesValue() && Op1 == ISD::SETGT) {
2722 SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(N0),
2723 LR.getValueType(), LL, RL);
2724 AddToWorkList(ORNode.getNode());
2725 return DAG.getSetCC(SDLoc(N), VT, ORNode, LR, Op1);
2728 // Simplify (and (setne X, 0), (setne X, -1)) -> (setuge (add X, 1), 2)
2729 if (LL == RL && isa<ConstantSDNode>(LR) && isa<ConstantSDNode>(RR) &&
2730 Op0 == Op1 && LL.getValueType().isInteger() &&
2731 Op0 == ISD::SETNE && ((cast<ConstantSDNode>(LR)->isNullValue() &&
2732 cast<ConstantSDNode>(RR)->isAllOnesValue()) ||
2733 (cast<ConstantSDNode>(LR)->isAllOnesValue() &&
2734 cast<ConstantSDNode>(RR)->isNullValue()))) {
2735 SDValue ADDNode = DAG.getNode(ISD::ADD, SDLoc(N0), LL.getValueType(),
2736 LL, DAG.getConstant(1, LL.getValueType()));
2737 AddToWorkList(ADDNode.getNode());
2738 return DAG.getSetCC(SDLoc(N), VT, ADDNode,
2739 DAG.getConstant(2, LL.getValueType()), ISD::SETUGE);
2741 // canonicalize equivalent to ll == rl
2742 if (LL == RR && LR == RL) {
2743 Op1 = ISD::getSetCCSwappedOperands(Op1);
2746 if (LL == RL && LR == RR) {
2747 bool isInteger = LL.getValueType().isInteger();
2748 ISD::CondCode Result = ISD::getSetCCAndOperation(Op0, Op1, isInteger);
2749 if (Result != ISD::SETCC_INVALID &&
2750 (!LegalOperations ||
2751 (TLI.isCondCodeLegal(Result, LL.getSimpleValueType()) &&
2752 TLI.isOperationLegal(ISD::SETCC,
2753 getSetCCResultType(N0.getSimpleValueType())))))
2754 return DAG.getSetCC(SDLoc(N), N0.getValueType(),
2759 // Simplify: (and (op x...), (op y...)) -> (op (and x, y))
2760 if (N0.getOpcode() == N1.getOpcode()) {
2761 SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
2762 if (Tmp.getNode()) return Tmp;
2765 // fold (and (sign_extend_inreg x, i16 to i32), 1) -> (and x, 1)
2766 // fold (and (sra)) -> (and (srl)) when possible.
2767 if (!VT.isVector() &&
2768 SimplifyDemandedBits(SDValue(N, 0)))
2769 return SDValue(N, 0);
2771 // fold (zext_inreg (extload x)) -> (zextload x)
2772 if (ISD::isEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode())) {
2773 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
2774 EVT MemVT = LN0->getMemoryVT();
2775 // If we zero all the possible extended bits, then we can turn this into
2776 // a zextload if we are running before legalize or the operation is legal.
2777 unsigned BitWidth = N1.getValueType().getScalarType().getSizeInBits();
2778 if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth,
2779 BitWidth - MemVT.getScalarType().getSizeInBits())) &&
2780 ((!LegalOperations && !LN0->isVolatile()) ||
2781 TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT))) {
2782 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N0), VT,
2783 LN0->getChain(), LN0->getBasePtr(),
2784 MemVT, LN0->getMemOperand());
2786 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
2787 return SDValue(N, 0); // Return N so it doesn't get rechecked!
2790 // fold (zext_inreg (sextload x)) -> (zextload x) iff load has one use
2791 if (ISD::isSEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
2793 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
2794 EVT MemVT = LN0->getMemoryVT();
2795 // If we zero all the possible extended bits, then we can turn this into
2796 // a zextload if we are running before legalize or the operation is legal.
2797 unsigned BitWidth = N1.getValueType().getScalarType().getSizeInBits();
2798 if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth,
2799 BitWidth - MemVT.getScalarType().getSizeInBits())) &&
2800 ((!LegalOperations && !LN0->isVolatile()) ||
2801 TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT))) {
2802 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N0), VT,
2803 LN0->getChain(), LN0->getBasePtr(),
2804 MemVT, LN0->getMemOperand());
2806 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
2807 return SDValue(N, 0); // Return N so it doesn't get rechecked!
2811 // fold (and (load x), 255) -> (zextload x, i8)
2812 // fold (and (extload x, i16), 255) -> (zextload x, i8)
2813 // fold (and (any_ext (extload x, i16)), 255) -> (zextload x, i8)
2814 if (N1C && (N0.getOpcode() == ISD::LOAD ||
2815 (N0.getOpcode() == ISD::ANY_EXTEND &&
2816 N0.getOperand(0).getOpcode() == ISD::LOAD))) {
2817 bool HasAnyExt = N0.getOpcode() == ISD::ANY_EXTEND;
2818 LoadSDNode *LN0 = HasAnyExt
2819 ? cast<LoadSDNode>(N0.getOperand(0))
2820 : cast<LoadSDNode>(N0);
2821 if (LN0->getExtensionType() != ISD::SEXTLOAD &&
2822 LN0->isUnindexed() && N0.hasOneUse() && SDValue(LN0, 0).hasOneUse()) {
2823 uint32_t ActiveBits = N1C->getAPIntValue().getActiveBits();
2824 if (ActiveBits > 0 && APIntOps::isMask(ActiveBits, N1C->getAPIntValue())){
2825 EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), ActiveBits);
2826 EVT LoadedVT = LN0->getMemoryVT();
2828 if (ExtVT == LoadedVT &&
2829 (!LegalOperations || TLI.isLoadExtLegal(ISD::ZEXTLOAD, ExtVT))) {
2830 EVT LoadResultTy = HasAnyExt ? LN0->getValueType(0) : VT;
2833 DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), LoadResultTy,
2834 LN0->getChain(), LN0->getBasePtr(), ExtVT,
2835 LN0->getMemOperand());
2837 CombineTo(LN0, NewLoad, NewLoad.getValue(1));
2838 return SDValue(N, 0); // Return N so it doesn't get rechecked!
2841 // Do not change the width of a volatile load.
2842 // Do not generate loads of non-round integer types since these can
2843 // be expensive (and would be wrong if the type is not byte sized).
2844 if (!LN0->isVolatile() && LoadedVT.bitsGT(ExtVT) && ExtVT.isRound() &&
2845 (!LegalOperations || TLI.isLoadExtLegal(ISD::ZEXTLOAD, ExtVT))) {
2846 EVT PtrType = LN0->getOperand(1).getValueType();
2848 unsigned Alignment = LN0->getAlignment();
2849 SDValue NewPtr = LN0->getBasePtr();
2851 // For big endian targets, we need to add an offset to the pointer
2852 // to load the correct bytes. For little endian systems, we merely
2853 // need to read fewer bytes from the same pointer.
2854 if (TLI.isBigEndian()) {
2855 unsigned LVTStoreBytes = LoadedVT.getStoreSize();
2856 unsigned EVTStoreBytes = ExtVT.getStoreSize();
2857 unsigned PtrOff = LVTStoreBytes - EVTStoreBytes;
2858 NewPtr = DAG.getNode(ISD::ADD, SDLoc(LN0), PtrType,
2859 NewPtr, DAG.getConstant(PtrOff, PtrType));
2860 Alignment = MinAlign(Alignment, PtrOff);
2863 AddToWorkList(NewPtr.getNode());
2865 EVT LoadResultTy = HasAnyExt ? LN0->getValueType(0) : VT;
2867 DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), LoadResultTy,
2868 LN0->getChain(), NewPtr,
2869 LN0->getPointerInfo(),
2870 ExtVT, LN0->isVolatile(), LN0->isNonTemporal(),
2871 Alignment, LN0->getTBAAInfo());
2873 CombineTo(LN0, Load, Load.getValue(1));
2874 return SDValue(N, 0); // Return N so it doesn't get rechecked!
2880 if (N0.getOpcode() == ISD::ADD && N1.getOpcode() == ISD::SRL &&
2881 VT.getSizeInBits() <= 64) {
2882 if (ConstantSDNode *ADDI = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
2883 APInt ADDC = ADDI->getAPIntValue();
2884 if (!TLI.isLegalAddImmediate(ADDC.getSExtValue())) {
2885 // Look for (and (add x, c1), (lshr y, c2)). If C1 wasn't a legal
2886 // immediate for an add, but it is legal if its top c2 bits are set,
2887 // transform the ADD so the immediate doesn't need to be materialized
2889 if (ConstantSDNode *SRLI = dyn_cast<ConstantSDNode>(N1.getOperand(1))) {
2890 APInt Mask = APInt::getHighBitsSet(VT.getSizeInBits(),
2891 SRLI->getZExtValue());
2892 if (DAG.MaskedValueIsZero(N0.getOperand(1), Mask)) {
2894 if (TLI.isLegalAddImmediate(ADDC.getSExtValue())) {
2896 DAG.getNode(ISD::ADD, SDLoc(N0), VT,
2897 N0.getOperand(0), DAG.getConstant(ADDC, VT));
2898 CombineTo(N0.getNode(), NewAdd);
2899 return SDValue(N, 0); // Return N so it doesn't get rechecked!
2907 // fold (and (or (srl N, 8), (shl N, 8)), 0xffff) -> (srl (bswap N), const)
2908 if (N1C && N1C->getAPIntValue() == 0xffff && N0.getOpcode() == ISD::OR) {
2909 SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0),
2910 N0.getOperand(1), false);
2911 if (BSwap.getNode())
2918 /// MatchBSwapHWord - Match (a >> 8) | (a << 8) as (bswap a) >> 16
2920 SDValue DAGCombiner::MatchBSwapHWordLow(SDNode *N, SDValue N0, SDValue N1,
2921 bool DemandHighBits) {
2922 if (!LegalOperations)
2925 EVT VT = N->getValueType(0);
2926 if (VT != MVT::i64 && VT != MVT::i32 && VT != MVT::i16)
2928 if (!TLI.isOperationLegal(ISD::BSWAP, VT))
2931 // Recognize (and (shl a, 8), 0xff), (and (srl a, 8), 0xff00)
2932 bool LookPassAnd0 = false;
2933 bool LookPassAnd1 = false;
2934 if (N0.getOpcode() == ISD::AND && N0.getOperand(0).getOpcode() == ISD::SRL)
2936 if (N1.getOpcode() == ISD::AND && N1.getOperand(0).getOpcode() == ISD::SHL)
2938 if (N0.getOpcode() == ISD::AND) {
2939 if (!N0.getNode()->hasOneUse())
2941 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
2942 if (!N01C || N01C->getZExtValue() != 0xFF00)
2944 N0 = N0.getOperand(0);
2945 LookPassAnd0 = true;
2948 if (N1.getOpcode() == ISD::AND) {
2949 if (!N1.getNode()->hasOneUse())
2951 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
2952 if (!N11C || N11C->getZExtValue() != 0xFF)
2954 N1 = N1.getOperand(0);
2955 LookPassAnd1 = true;
2958 if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
2960 if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
2962 if (!N0.getNode()->hasOneUse() ||
2963 !N1.getNode()->hasOneUse())
2966 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
2967 ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
2970 if (N01C->getZExtValue() != 8 || N11C->getZExtValue() != 8)
2973 // Look for (shl (and a, 0xff), 8), (srl (and a, 0xff00), 8)
2974 SDValue N00 = N0->getOperand(0);
2975 if (!LookPassAnd0 && N00.getOpcode() == ISD::AND) {
2976 if (!N00.getNode()->hasOneUse())
2978 ConstantSDNode *N001C = dyn_cast<ConstantSDNode>(N00.getOperand(1));
2979 if (!N001C || N001C->getZExtValue() != 0xFF)
2981 N00 = N00.getOperand(0);
2982 LookPassAnd0 = true;
2985 SDValue N10 = N1->getOperand(0);
2986 if (!LookPassAnd1 && N10.getOpcode() == ISD::AND) {
2987 if (!N10.getNode()->hasOneUse())
2989 ConstantSDNode *N101C = dyn_cast<ConstantSDNode>(N10.getOperand(1));
2990 if (!N101C || N101C->getZExtValue() != 0xFF00)
2992 N10 = N10.getOperand(0);
2993 LookPassAnd1 = true;
2999 // Make sure everything beyond the low halfword gets set to zero since the SRL
3000 // 16 will clear the top bits.
3001 unsigned OpSizeInBits = VT.getSizeInBits();
3002 if (DemandHighBits && OpSizeInBits > 16) {
3003 // If the left-shift isn't masked out then the only way this is a bswap is
3004 // if all bits beyond the low 8 are 0. In that case the entire pattern
3005 // reduces to a left shift anyway: leave it for other parts of the combiner.
3009 // However, if the right shift isn't masked out then it might be because
3010 // it's not needed. See if we can spot that too.
3011 if (!LookPassAnd1 &&
3012 !DAG.MaskedValueIsZero(
3013 N10, APInt::getHighBitsSet(OpSizeInBits, OpSizeInBits - 16)))
3017 SDValue Res = DAG.getNode(ISD::BSWAP, SDLoc(N), VT, N00);
3018 if (OpSizeInBits > 16)
3019 Res = DAG.getNode(ISD::SRL, SDLoc(N), VT, Res,
3020 DAG.getConstant(OpSizeInBits-16, getShiftAmountTy(VT)));
3024 /// isBSwapHWordElement - Return true if the specified node is an element
3025 /// that makes up a 32-bit packed halfword byteswap. i.e.
3026 /// ((x&0xff)<<8)|((x&0xff00)>>8)|((x&0x00ff0000)<<8)|((x&0xff000000)>>8)
3027 static bool isBSwapHWordElement(SDValue N, SmallVectorImpl<SDNode *> &Parts) {
3028 if (!N.getNode()->hasOneUse())
3031 unsigned Opc = N.getOpcode();
3032 if (Opc != ISD::AND && Opc != ISD::SHL && Opc != ISD::SRL)
3035 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3040 switch (N1C->getZExtValue()) {
3043 case 0xFF: Num = 0; break;
3044 case 0xFF00: Num = 1; break;
3045 case 0xFF0000: Num = 2; break;
3046 case 0xFF000000: Num = 3; break;
3049 // Look for (x & 0xff) << 8 as well as ((x << 8) & 0xff00).
3050 SDValue N0 = N.getOperand(0);
3051 if (Opc == ISD::AND) {
3052 if (Num == 0 || Num == 2) {
3054 // (x >> 8) & 0xff0000
3055 if (N0.getOpcode() != ISD::SRL)
3057 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3058 if (!C || C->getZExtValue() != 8)
3061 // (x << 8) & 0xff00
3062 // (x << 8) & 0xff000000
3063 if (N0.getOpcode() != ISD::SHL)
3065 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3066 if (!C || C->getZExtValue() != 8)
3069 } else if (Opc == ISD::SHL) {
3071 // (x & 0xff0000) << 8
3072 if (Num != 0 && Num != 2)
3074 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3075 if (!C || C->getZExtValue() != 8)
3077 } else { // Opc == ISD::SRL
3078 // (x & 0xff00) >> 8
3079 // (x & 0xff000000) >> 8
3080 if (Num != 1 && Num != 3)
3082 ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3083 if (!C || C->getZExtValue() != 8)
3090 Parts[Num] = N0.getOperand(0).getNode();
3094 /// MatchBSwapHWord - Match a 32-bit packed halfword bswap. That is
3095 /// ((x&0xff)<<8)|((x&0xff00)>>8)|((x&0x00ff0000)<<8)|((x&0xff000000)>>8)
3096 /// => (rotl (bswap x), 16)
3097 SDValue DAGCombiner::MatchBSwapHWord(SDNode *N, SDValue N0, SDValue N1) {
3098 if (!LegalOperations)
3101 EVT VT = N->getValueType(0);
3104 if (!TLI.isOperationLegal(ISD::BSWAP, VT))
3107 SmallVector<SDNode*,4> Parts(4, (SDNode*)0);
3109 // (or (or (and), (and)), (or (and), (and)))
3110 // (or (or (or (and), (and)), (and)), (and))
3111 if (N0.getOpcode() != ISD::OR)
3113 SDValue N00 = N0.getOperand(0);
3114 SDValue N01 = N0.getOperand(1);
3116 if (N1.getOpcode() == ISD::OR &&
3117 N00.getNumOperands() == 2 && N01.getNumOperands() == 2) {
3118 // (or (or (and), (and)), (or (and), (and)))
3119 SDValue N000 = N00.getOperand(0);
3120 if (!isBSwapHWordElement(N000, Parts))
3123 SDValue N001 = N00.getOperand(1);
3124 if (!isBSwapHWordElement(N001, Parts))
3126 SDValue N010 = N01.getOperand(0);
3127 if (!isBSwapHWordElement(N010, Parts))
3129 SDValue N011 = N01.getOperand(1);
3130 if (!isBSwapHWordElement(N011, Parts))
3133 // (or (or (or (and), (and)), (and)), (and))
3134 if (!isBSwapHWordElement(N1, Parts))
3136 if (!isBSwapHWordElement(N01, Parts))
3138 if (N00.getOpcode() != ISD::OR)
3140 SDValue N000 = N00.getOperand(0);
3141 if (!isBSwapHWordElement(N000, Parts))
3143 SDValue N001 = N00.getOperand(1);
3144 if (!isBSwapHWordElement(N001, Parts))
3148 // Make sure the parts are all coming from the same node.
3149 if (Parts[0] != Parts[1] || Parts[0] != Parts[2] || Parts[0] != Parts[3])
3152 SDValue BSwap = DAG.getNode(ISD::BSWAP, SDLoc(N), VT,
3153 SDValue(Parts[0],0));
3155 // Result of the bswap should be rotated by 16. If it's not legal, then
3156 // do (x << 16) | (x >> 16).
3157 SDValue ShAmt = DAG.getConstant(16, getShiftAmountTy(VT));
3158 if (TLI.isOperationLegalOrCustom(ISD::ROTL, VT))
3159 return DAG.getNode(ISD::ROTL, SDLoc(N), VT, BSwap, ShAmt);
3160 if (TLI.isOperationLegalOrCustom(ISD::ROTR, VT))
3161 return DAG.getNode(ISD::ROTR, SDLoc(N), VT, BSwap, ShAmt);
3162 return DAG.getNode(ISD::OR, SDLoc(N), VT,
3163 DAG.getNode(ISD::SHL, SDLoc(N), VT, BSwap, ShAmt),
3164 DAG.getNode(ISD::SRL, SDLoc(N), VT, BSwap, ShAmt));
3167 SDValue DAGCombiner::visitOR(SDNode *N) {
3168 SDValue N0 = N->getOperand(0);
3169 SDValue N1 = N->getOperand(1);
3170 SDValue LL, LR, RL, RR, CC0, CC1;
3171 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
3172 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
3173 EVT VT = N1.getValueType();
3176 if (VT.isVector()) {
3177 SDValue FoldedVOp = SimplifyVBinOp(N);
3178 if (FoldedVOp.getNode()) return FoldedVOp;
3180 // fold (or x, 0) -> x, vector edition
3181 if (ISD::isBuildVectorAllZeros(N0.getNode()))
3183 if (ISD::isBuildVectorAllZeros(N1.getNode()))
3186 // fold (or x, -1) -> -1, vector edition
3187 if (ISD::isBuildVectorAllOnes(N0.getNode()))
3189 if (ISD::isBuildVectorAllOnes(N1.getNode()))
3193 // fold (or x, undef) -> -1
3194 if (!LegalOperations &&
3195 (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)) {
3196 EVT EltVT = VT.isVector() ? VT.getVectorElementType() : VT;
3197 return DAG.getConstant(APInt::getAllOnesValue(EltVT.getSizeInBits()), VT);
3199 // fold (or c1, c2) -> c1|c2
3201 return DAG.FoldConstantArithmetic(ISD::OR, VT, N0C, N1C);
3202 // canonicalize constant to RHS
3204 return DAG.getNode(ISD::OR, SDLoc(N), VT, N1, N0);
3205 // fold (or x, 0) -> x
3206 if (N1C && N1C->isNullValue())
3208 // fold (or x, -1) -> -1
3209 if (N1C && N1C->isAllOnesValue())
3211 // fold (or x, c) -> c iff (x & ~c) == 0
3212 if (N1C && DAG.MaskedValueIsZero(N0, ~N1C->getAPIntValue()))
3215 // Recognize halfword bswaps as (bswap + rotl 16) or (bswap + shl 16)
3216 SDValue BSwap = MatchBSwapHWord(N, N0, N1);
3217 if (BSwap.getNode() != 0)
3219 BSwap = MatchBSwapHWordLow(N, N0, N1);
3220 if (BSwap.getNode() != 0)
3224 SDValue ROR = ReassociateOps(ISD::OR, SDLoc(N), N0, N1);
3225 if (ROR.getNode() != 0)
3227 // Canonicalize (or (and X, c1), c2) -> (and (or X, c2), c1|c2)
3228 // iff (c1 & c2) == 0.
3229 if (N1C && N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() &&
3230 isa<ConstantSDNode>(N0.getOperand(1))) {
3231 ConstantSDNode *C1 = cast<ConstantSDNode>(N0.getOperand(1));
3232 if ((C1->getAPIntValue() & N1C->getAPIntValue()) != 0) {
3233 SDValue COR = DAG.FoldConstantArithmetic(ISD::OR, VT, N1C, C1);
3236 return DAG.getNode(ISD::AND, SDLoc(N), VT,
3237 DAG.getNode(ISD::OR, SDLoc(N0), VT,
3238 N0.getOperand(0), N1), COR);
3241 // fold (or (setcc x), (setcc y)) -> (setcc (or x, y))
3242 if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){
3243 ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get();
3244 ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get();
3246 if (LR == RR && isa<ConstantSDNode>(LR) && Op0 == Op1 &&
3247 LL.getValueType().isInteger()) {
3248 // fold (or (setne X, 0), (setne Y, 0)) -> (setne (or X, Y), 0)
3249 // fold (or (setlt X, 0), (setlt Y, 0)) -> (setne (or X, Y), 0)
3250 if (cast<ConstantSDNode>(LR)->isNullValue() &&
3251 (Op1 == ISD::SETNE || Op1 == ISD::SETLT)) {
3252 SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(LR),
3253 LR.getValueType(), LL, RL);
3254 AddToWorkList(ORNode.getNode());
3255 return DAG.getSetCC(SDLoc(N), VT, ORNode, LR, Op1);
3257 // fold (or (setne X, -1), (setne Y, -1)) -> (setne (and X, Y), -1)
3258 // fold (or (setgt X, -1), (setgt Y -1)) -> (setgt (and X, Y), -1)
3259 if (cast<ConstantSDNode>(LR)->isAllOnesValue() &&
3260 (Op1 == ISD::SETNE || Op1 == ISD::SETGT)) {
3261 SDValue ANDNode = DAG.getNode(ISD::AND, SDLoc(LR),
3262 LR.getValueType(), LL, RL);
3263 AddToWorkList(ANDNode.getNode());
3264 return DAG.getSetCC(SDLoc(N), VT, ANDNode, LR, Op1);
3267 // canonicalize equivalent to ll == rl
3268 if (LL == RR && LR == RL) {
3269 Op1 = ISD::getSetCCSwappedOperands(Op1);
3272 if (LL == RL && LR == RR) {
3273 bool isInteger = LL.getValueType().isInteger();
3274 ISD::CondCode Result = ISD::getSetCCOrOperation(Op0, Op1, isInteger);
3275 if (Result != ISD::SETCC_INVALID &&
3276 (!LegalOperations ||
3277 (TLI.isCondCodeLegal(Result, LL.getSimpleValueType()) &&
3278 TLI.isOperationLegal(ISD::SETCC,
3279 getSetCCResultType(N0.getValueType())))))
3280 return DAG.getSetCC(SDLoc(N), N0.getValueType(),
3285 // Simplify: (or (op x...), (op y...)) -> (op (or x, y))
3286 if (N0.getOpcode() == N1.getOpcode()) {
3287 SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
3288 if (Tmp.getNode()) return Tmp;
3291 // (or (and X, C1), (and Y, C2)) -> (and (or X, Y), C3) if possible.
3292 if (N0.getOpcode() == ISD::AND &&
3293 N1.getOpcode() == ISD::AND &&
3294 N0.getOperand(1).getOpcode() == ISD::Constant &&
3295 N1.getOperand(1).getOpcode() == ISD::Constant &&
3296 // Don't increase # computations.
3297 (N0.getNode()->hasOneUse() || N1.getNode()->hasOneUse())) {
3298 // We can only do this xform if we know that bits from X that are set in C2
3299 // but not in C1 are already zero. Likewise for Y.
3300 const APInt &LHSMask =
3301 cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
3302 const APInt &RHSMask =
3303 cast<ConstantSDNode>(N1.getOperand(1))->getAPIntValue();
3305 if (DAG.MaskedValueIsZero(N0.getOperand(0), RHSMask&~LHSMask) &&
3306 DAG.MaskedValueIsZero(N1.getOperand(0), LHSMask&~RHSMask)) {
3307 SDValue X = DAG.getNode(ISD::OR, SDLoc(N0), VT,
3308 N0.getOperand(0), N1.getOperand(0));
3309 return DAG.getNode(ISD::AND, SDLoc(N), VT, X,
3310 DAG.getConstant(LHSMask | RHSMask, VT));
3314 // See if this is some rotate idiom.
3315 if (SDNode *Rot = MatchRotate(N0, N1, SDLoc(N)))
3316 return SDValue(Rot, 0);
3318 // Simplify the operands using demanded-bits information.
3319 if (!VT.isVector() &&
3320 SimplifyDemandedBits(SDValue(N, 0)))
3321 return SDValue(N, 0);
3326 /// MatchRotateHalf - Match "(X shl/srl V1) & V2" where V2 may not be present.
3327 static bool MatchRotateHalf(SDValue Op, SDValue &Shift, SDValue &Mask) {
3328 if (Op.getOpcode() == ISD::AND) {
3329 if (isa<ConstantSDNode>(Op.getOperand(1))) {
3330 Mask = Op.getOperand(1);
3331 Op = Op.getOperand(0);
3337 if (Op.getOpcode() == ISD::SRL || Op.getOpcode() == ISD::SHL) {
3345 // Return true if we can prove that, whenever Neg and Pos are both in the
3346 // range [0, OpSize), Neg == (Pos == 0 ? 0 : OpSize - Pos). This means that
3347 // for two opposing shifts shift1 and shift2 and a value X with OpBits bits:
3349 // (or (shift1 X, Neg), (shift2 X, Pos))
3351 // reduces to a rotate in direction shift2 by Pos and a rotate in direction
3352 // shift1 by Neg. The range [0, OpSize) means that we only need to consider
3353 // shift amounts with defined behavior.
3354 static bool matchRotateSub(SDValue Pos, SDValue Neg, unsigned OpSize) {
3355 // If OpSize is a power of 2 then:
3357 // (a) (Pos == 0 ? 0 : OpSize - Pos) == (OpSize - Pos) & (OpSize - 1)
3358 // (b) Neg == Neg & (OpSize - 1) whenever Neg is in [0, OpSize).
3360 // So if OpSize is a power of 2 and Neg is (and Neg', OpSize-1), we check
3361 // for the stronger condition:
3363 // Neg & (OpSize - 1) == (OpSize - Pos) & (OpSize - 1) [A]
3365 // for all Neg and Pos. Since Neg & (OpSize - 1) == Neg' & (OpSize - 1)
3366 // we can just replace Neg with Neg' for the rest of the function.
3368 // In other cases we check for the even stronger condition:
3370 // Neg == OpSize - Pos [B]
3372 // for all Neg and Pos. Note that the (or ...) then invokes undefined
3373 // behavior if Pos == 0 (and consequently Neg == OpSize).
3375 // We could actually use [A] whenever OpSize is a power of 2, but the
3376 // only extra cases that it would match are those uninteresting ones
3377 // where Neg and Pos are never in range at the same time. E.g. for
3378 // OpSize == 32, using [A] would allow a Neg of the form (sub 64, Pos)
3379 // as well as (sub 32, Pos), but:
3381 // (or (shift1 X, (sub 64, Pos)), (shift2 X, Pos))
3383 // always invokes undefined behavior for 32-bit X.
3385 // Below, Mask == OpSize - 1 when using [A] and is all-ones otherwise.
3386 unsigned LoBits = 0;
3387 if (Neg.getOpcode() == ISD::AND &&
3388 isPowerOf2_64(OpSize) &&
3389 Neg.getOperand(1).getOpcode() == ISD::Constant &&
3390 cast<ConstantSDNode>(Neg.getOperand(1))->getAPIntValue() == OpSize - 1) {
3391 Neg = Neg.getOperand(0);
3392 LoBits = Log2_64(OpSize);
3395 // Check whether Neg has the form (sub NegC, NegOp1) for some NegC and NegOp1.
3396 if (Neg.getOpcode() != ISD::SUB)
3398 ConstantSDNode *NegC = dyn_cast<ConstantSDNode>(Neg.getOperand(0));
3401 SDValue NegOp1 = Neg.getOperand(1);
3403 // The condition we need is now:
3405 // (NegC - NegOp1) & Mask == (OpSize - Pos) & Mask
3407 // If NegOp1 == Pos then we need:
3409 // OpSize & Mask == NegC & Mask
3411 // (because "x & Mask" is a truncation and distributes through subtraction).
3414 Width = NegC->getAPIntValue();
3415 // Check for cases where Pos has the form (add NegOp1, PosC) for some PosC.
3416 // Then the condition we want to prove becomes:
3418 // (NegC - NegOp1) & Mask == (OpSize - (NegOp1 + PosC)) & Mask
3420 // which, again because "x & Mask" is a truncation, becomes:
3422 // NegC & Mask == (OpSize - PosC) & Mask
3423 // OpSize & Mask == (NegC + PosC) & Mask
3424 else if (Pos.getOpcode() == ISD::ADD &&
3425 Pos.getOperand(0) == NegOp1 &&
3426 Pos.getOperand(1).getOpcode() == ISD::Constant)
3427 Width = (cast<ConstantSDNode>(Pos.getOperand(1))->getAPIntValue() +
3428 NegC->getAPIntValue());
3432 // Now we just need to check that OpSize & Mask == Width & Mask.
3434 return Width.getLoBits(LoBits) == 0;
3435 return Width == OpSize;
3438 // A subroutine of MatchRotate used once we have found an OR of two opposite
3439 // shifts of Shifted. If Neg == <operand size> - Pos then the OR reduces
3440 // to both (PosOpcode Shifted, Pos) and (NegOpcode Shifted, Neg), with the
3441 // former being preferred if supported. InnerPos and InnerNeg are Pos and
3442 // Neg with outer conversions stripped away.
3443 SDNode *DAGCombiner::MatchRotatePosNeg(SDValue Shifted, SDValue Pos,
3444 SDValue Neg, SDValue InnerPos,
3445 SDValue InnerNeg, unsigned PosOpcode,
3446 unsigned NegOpcode, SDLoc DL) {
3447 // fold (or (shl x, (*ext y)),
3448 // (srl x, (*ext (sub 32, y)))) ->
3449 // (rotl x, y) or (rotr x, (sub 32, y))
3451 // fold (or (shl x, (*ext (sub 32, y))),
3452 // (srl x, (*ext y))) ->
3453 // (rotr x, y) or (rotl x, (sub 32, y))
3454 EVT VT = Shifted.getValueType();
3455 if (matchRotateSub(InnerPos, InnerNeg, VT.getSizeInBits())) {
3456 bool HasPos = TLI.isOperationLegalOrCustom(PosOpcode, VT);
3457 return DAG.getNode(HasPos ? PosOpcode : NegOpcode, DL, VT, Shifted,
3458 HasPos ? Pos : Neg).getNode();
3461 // fold (or (shl (*ext x), (*ext y)),
3462 // (srl (*ext x), (*ext (sub 32, y)))) ->
3463 // (*ext (rotl x, y)) or (*ext (rotr x, (sub 32, y)))
3465 // fold (or (shl (*ext x), (*ext (sub 32, y))),
3466 // (srl (*ext x), (*ext y))) ->
3467 // (*ext (rotr x, y)) or (*ext (rotl x, (sub 32, y)))
3468 if (Shifted.getOpcode() == ISD::ZERO_EXTEND ||
3469 Shifted.getOpcode() == ISD::ANY_EXTEND) {
3470 SDValue InnerShifted = Shifted.getOperand(0);
3471 EVT InnerVT = InnerShifted.getValueType();
3472 bool HasPosInner = TLI.isOperationLegalOrCustom(PosOpcode, InnerVT);
3473 if (HasPosInner || TLI.isOperationLegalOrCustom(NegOpcode, InnerVT)) {
3474 if (matchRotateSub(InnerPos, InnerNeg, InnerVT.getSizeInBits())) {
3475 SDValue V = DAG.getNode(HasPosInner ? PosOpcode : NegOpcode, DL,
3476 InnerVT, InnerShifted, HasPosInner ? Pos : Neg);
3477 return DAG.getNode(Shifted.getOpcode(), DL, VT, V).getNode();
3485 // MatchRotate - Handle an 'or' of two operands. If this is one of the many
3486 // idioms for rotate, and if the target supports rotation instructions, generate
3488 SDNode *DAGCombiner::MatchRotate(SDValue LHS, SDValue RHS, SDLoc DL) {
3489 // Must be a legal type. Expanded 'n promoted things won't work with rotates.
3490 EVT VT = LHS.getValueType();
3491 if (!TLI.isTypeLegal(VT)) return 0;
3493 // The target must have at least one rotate flavor.
3494 bool HasROTL = TLI.isOperationLegalOrCustom(ISD::ROTL, VT);
3495 bool HasROTR = TLI.isOperationLegalOrCustom(ISD::ROTR, VT);
3496 if (!HasROTL && !HasROTR) return 0;
3498 // Match "(X shl/srl V1) & V2" where V2 may not be present.
3499 SDValue LHSShift; // The shift.
3500 SDValue LHSMask; // AND value if any.
3501 if (!MatchRotateHalf(LHS, LHSShift, LHSMask))
3502 return 0; // Not part of a rotate.
3504 SDValue RHSShift; // The shift.
3505 SDValue RHSMask; // AND value if any.
3506 if (!MatchRotateHalf(RHS, RHSShift, RHSMask))
3507 return 0; // Not part of a rotate.
3509 if (LHSShift.getOperand(0) != RHSShift.getOperand(0))
3510 return 0; // Not shifting the same value.
3512 if (LHSShift.getOpcode() == RHSShift.getOpcode())
3513 return 0; // Shifts must disagree.
3515 // Canonicalize shl to left side in a shl/srl pair.
3516 if (RHSShift.getOpcode() == ISD::SHL) {
3517 std::swap(LHS, RHS);
3518 std::swap(LHSShift, RHSShift);
3519 std::swap(LHSMask , RHSMask );
3522 unsigned OpSizeInBits = VT.getSizeInBits();
3523 SDValue LHSShiftArg = LHSShift.getOperand(0);
3524 SDValue LHSShiftAmt = LHSShift.getOperand(1);
3525 SDValue RHSShiftArg = RHSShift.getOperand(0);
3526 SDValue RHSShiftAmt = RHSShift.getOperand(1);
3528 // fold (or (shl x, C1), (srl x, C2)) -> (rotl x, C1)
3529 // fold (or (shl x, C1), (srl x, C2)) -> (rotr x, C2)
3530 if (LHSShiftAmt.getOpcode() == ISD::Constant &&
3531 RHSShiftAmt.getOpcode() == ISD::Constant) {
3532 uint64_t LShVal = cast<ConstantSDNode>(LHSShiftAmt)->getZExtValue();
3533 uint64_t RShVal = cast<ConstantSDNode>(RHSShiftAmt)->getZExtValue();
3534 if ((LShVal + RShVal) != OpSizeInBits)
3537 SDValue Rot = DAG.getNode(HasROTL ? ISD::ROTL : ISD::ROTR, DL, VT,
3538 LHSShiftArg, HasROTL ? LHSShiftAmt : RHSShiftAmt);
3540 // If there is an AND of either shifted operand, apply it to the result.
3541 if (LHSMask.getNode() || RHSMask.getNode()) {
3542 APInt Mask = APInt::getAllOnesValue(OpSizeInBits);
3544 if (LHSMask.getNode()) {
3545 APInt RHSBits = APInt::getLowBitsSet(OpSizeInBits, LShVal);
3546 Mask &= cast<ConstantSDNode>(LHSMask)->getAPIntValue() | RHSBits;
3548 if (RHSMask.getNode()) {
3549 APInt LHSBits = APInt::getHighBitsSet(OpSizeInBits, RShVal);
3550 Mask &= cast<ConstantSDNode>(RHSMask)->getAPIntValue() | LHSBits;
3553 Rot = DAG.getNode(ISD::AND, DL, VT, Rot, DAG.getConstant(Mask, VT));
3556 return Rot.getNode();
3559 // If there is a mask here, and we have a variable shift, we can't be sure
3560 // that we're masking out the right stuff.
3561 if (LHSMask.getNode() || RHSMask.getNode())
3564 // If the shift amount is sign/zext/any-extended just peel it off.
3565 SDValue LExtOp0 = LHSShiftAmt;
3566 SDValue RExtOp0 = RHSShiftAmt;
3567 if ((LHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND ||
3568 LHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND ||
3569 LHSShiftAmt.getOpcode() == ISD::ANY_EXTEND ||
3570 LHSShiftAmt.getOpcode() == ISD::TRUNCATE) &&
3571 (RHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND ||
3572 RHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND ||
3573 RHSShiftAmt.getOpcode() == ISD::ANY_EXTEND ||
3574 RHSShiftAmt.getOpcode() == ISD::TRUNCATE)) {
3575 LExtOp0 = LHSShiftAmt.getOperand(0);
3576 RExtOp0 = RHSShiftAmt.getOperand(0);
3579 SDNode *TryL = MatchRotatePosNeg(LHSShiftArg, LHSShiftAmt, RHSShiftAmt,
3580 LExtOp0, RExtOp0, ISD::ROTL, ISD::ROTR, DL);
3584 SDNode *TryR = MatchRotatePosNeg(RHSShiftArg, RHSShiftAmt, LHSShiftAmt,
3585 RExtOp0, LExtOp0, ISD::ROTR, ISD::ROTL, DL);
3592 SDValue DAGCombiner::visitXOR(SDNode *N) {
3593 SDValue N0 = N->getOperand(0);
3594 SDValue N1 = N->getOperand(1);
3595 SDValue LHS, RHS, CC;
3596 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
3597 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
3598 EVT VT = N0.getValueType();
3601 if (VT.isVector()) {
3602 SDValue FoldedVOp = SimplifyVBinOp(N);
3603 if (FoldedVOp.getNode()) return FoldedVOp;
3605 // fold (xor x, 0) -> x, vector edition
3606 if (ISD::isBuildVectorAllZeros(N0.getNode()))
3608 if (ISD::isBuildVectorAllZeros(N1.getNode()))
3612 // fold (xor undef, undef) -> 0. This is a common idiom (misuse).
3613 if (N0.getOpcode() == ISD::UNDEF && N1.getOpcode() == ISD::UNDEF)
3614 return DAG.getConstant(0, VT);
3615 // fold (xor x, undef) -> undef
3616 if (N0.getOpcode() == ISD::UNDEF)
3618 if (N1.getOpcode() == ISD::UNDEF)
3620 // fold (xor c1, c2) -> c1^c2
3622 return DAG.FoldConstantArithmetic(ISD::XOR, VT, N0C, N1C);
3623 // canonicalize constant to RHS
3625 return DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0);
3626 // fold (xor x, 0) -> x
3627 if (N1C && N1C->isNullValue())
3630 SDValue RXOR = ReassociateOps(ISD::XOR, SDLoc(N), N0, N1);
3631 if (RXOR.getNode() != 0)
3634 // fold !(x cc y) -> (x !cc y)
3635 if (N1C && N1C->getAPIntValue() == 1 && isSetCCEquivalent(N0, LHS, RHS, CC)) {
3636 bool isInt = LHS.getValueType().isInteger();
3637 ISD::CondCode NotCC = ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(),
3640 if (!LegalOperations ||
3641 TLI.isCondCodeLegal(NotCC, LHS.getSimpleValueType())) {
3642 switch (N0.getOpcode()) {
3644 llvm_unreachable("Unhandled SetCC Equivalent!");
3646 return DAG.getSetCC(SDLoc(N), VT, LHS, RHS, NotCC);
3647 case ISD::SELECT_CC:
3648 return DAG.getSelectCC(SDLoc(N), LHS, RHS, N0.getOperand(2),
3649 N0.getOperand(3), NotCC);
3654 // fold (not (zext (setcc x, y))) -> (zext (not (setcc x, y)))
3655 if (N1C && N1C->getAPIntValue() == 1 && N0.getOpcode() == ISD::ZERO_EXTEND &&
3656 N0.getNode()->hasOneUse() &&
3657 isSetCCEquivalent(N0.getOperand(0), LHS, RHS, CC)){
3658 SDValue V = N0.getOperand(0);
3659 V = DAG.getNode(ISD::XOR, SDLoc(N0), V.getValueType(), V,
3660 DAG.getConstant(1, V.getValueType()));
3661 AddToWorkList(V.getNode());
3662 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, V);
3665 // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are setcc
3666 if (N1C && N1C->getAPIntValue() == 1 && VT == MVT::i1 &&
3667 (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
3668 SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
3669 if (isOneUseSetCC(RHS) || isOneUseSetCC(LHS)) {
3670 unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
3671 LHS = DAG.getNode(ISD::XOR, SDLoc(LHS), VT, LHS, N1); // LHS = ~LHS
3672 RHS = DAG.getNode(ISD::XOR, SDLoc(RHS), VT, RHS, N1); // RHS = ~RHS
3673 AddToWorkList(LHS.getNode()); AddToWorkList(RHS.getNode());
3674 return DAG.getNode(NewOpcode, SDLoc(N), VT, LHS, RHS);
3677 // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are constants
3678 if (N1C && N1C->isAllOnesValue() &&
3679 (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
3680 SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
3681 if (isa<ConstantSDNode>(RHS) || isa<ConstantSDNode>(LHS)) {
3682 unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
3683 LHS = DAG.getNode(ISD::XOR, SDLoc(LHS), VT, LHS, N1); // LHS = ~LHS
3684 RHS = DAG.getNode(ISD::XOR, SDLoc(RHS), VT, RHS, N1); // RHS = ~RHS
3685 AddToWorkList(LHS.getNode()); AddToWorkList(RHS.getNode());
3686 return DAG.getNode(NewOpcode, SDLoc(N), VT, LHS, RHS);
3689 // fold (xor (and x, y), y) -> (and (not x), y)
3690 if (N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() &&
3691 N0->getOperand(1) == N1) {
3692 SDValue X = N0->getOperand(0);
3693 SDValue NotX = DAG.getNOT(SDLoc(X), X, VT);
3694 AddToWorkList(NotX.getNode());
3695 return DAG.getNode(ISD::AND, SDLoc(N), VT, NotX, N1);
3697 // fold (xor (xor x, c1), c2) -> (xor x, (xor c1, c2))
3698 if (N1C && N0.getOpcode() == ISD::XOR) {
3699 ConstantSDNode *N00C = dyn_cast<ConstantSDNode>(N0.getOperand(0));
3700 ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3702 return DAG.getNode(ISD::XOR, SDLoc(N), VT, N0.getOperand(1),
3703 DAG.getConstant(N1C->getAPIntValue() ^
3704 N00C->getAPIntValue(), VT));
3706 return DAG.getNode(ISD::XOR, SDLoc(N), VT, N0.getOperand(0),
3707 DAG.getConstant(N1C->getAPIntValue() ^
3708 N01C->getAPIntValue(), VT));
3710 // fold (xor x, x) -> 0
3712 return tryFoldToZero(SDLoc(N), TLI, VT, DAG, LegalOperations, LegalTypes);
3714 // Simplify: xor (op x...), (op y...) -> (op (xor x, y))
3715 if (N0.getOpcode() == N1.getOpcode()) {
3716 SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
3717 if (Tmp.getNode()) return Tmp;
3720 // Simplify the expression using non-local knowledge.
3721 if (!VT.isVector() &&
3722 SimplifyDemandedBits(SDValue(N, 0)))
3723 return SDValue(N, 0);
3728 /// visitShiftByConstant - Handle transforms common to the three shifts, when
3729 /// the shift amount is a constant.
3730 SDValue DAGCombiner::visitShiftByConstant(SDNode *N, unsigned Amt) {
3731 SDNode *LHS = N->getOperand(0).getNode();
3732 if (!LHS->hasOneUse()) return SDValue();
3734 // We want to pull some binops through shifts, so that we have (and (shift))
3735 // instead of (shift (and)), likewise for add, or, xor, etc. This sort of
3736 // thing happens with address calculations, so it's important to canonicalize
3738 bool HighBitSet = false; // Can we transform this if the high bit is set?
3740 switch (LHS->getOpcode()) {
3741 default: return SDValue();
3744 HighBitSet = false; // We can only transform sra if the high bit is clear.
3747 HighBitSet = true; // We can only transform sra if the high bit is set.
3750 if (N->getOpcode() != ISD::SHL)
3751 return SDValue(); // only shl(add) not sr[al](add).
3752 HighBitSet = false; // We can only transform sra if the high bit is clear.
3756 // We require the RHS of the binop to be a constant as well.
3757 ConstantSDNode *BinOpCst = dyn_cast<ConstantSDNode>(LHS->getOperand(1));
3758 if (!BinOpCst) return SDValue();
3760 // FIXME: disable this unless the input to the binop is a shift by a constant.
3761 // If it is not a shift, it pessimizes some common cases like:
3763 // void foo(int *X, int i) { X[i & 1235] = 1; }
3764 // int bar(int *X, int i) { return X[i & 255]; }
3765 SDNode *BinOpLHSVal = LHS->getOperand(0).getNode();
3766 if ((BinOpLHSVal->getOpcode() != ISD::SHL &&
3767 BinOpLHSVal->getOpcode() != ISD::SRA &&
3768 BinOpLHSVal->getOpcode() != ISD::SRL) ||
3769 !isa<ConstantSDNode>(BinOpLHSVal->getOperand(1)))
3772 EVT VT = N->getValueType(0);
3774 // If this is a signed shift right, and the high bit is modified by the
3775 // logical operation, do not perform the transformation. The highBitSet
3776 // boolean indicates the value of the high bit of the constant which would
3777 // cause it to be modified for this operation.
3778 if (N->getOpcode() == ISD::SRA) {
3779 bool BinOpRHSSignSet = BinOpCst->getAPIntValue().isNegative();
3780 if (BinOpRHSSignSet != HighBitSet)
3784 // Fold the constants, shifting the binop RHS by the shift amount.
3785 SDValue NewRHS = DAG.getNode(N->getOpcode(), SDLoc(LHS->getOperand(1)),
3787 LHS->getOperand(1), N->getOperand(1));
3789 // Create the new shift.
3790 SDValue NewShift = DAG.getNode(N->getOpcode(),
3791 SDLoc(LHS->getOperand(0)),
3792 VT, LHS->getOperand(0), N->getOperand(1));
3794 // Create the new binop.
3795 return DAG.getNode(LHS->getOpcode(), SDLoc(N), VT, NewShift, NewRHS);
3798 SDValue DAGCombiner::visitSHL(SDNode *N) {
3799 SDValue N0 = N->getOperand(0);
3800 SDValue N1 = N->getOperand(1);
3801 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
3802 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
3803 EVT VT = N0.getValueType();
3804 unsigned OpSizeInBits = VT.getScalarType().getSizeInBits();
3807 if (VT.isVector()) {
3808 SDValue FoldedVOp = SimplifyVBinOp(N);
3809 if (FoldedVOp.getNode()) return FoldedVOp;
3812 // fold (shl c1, c2) -> c1<<c2
3814 return DAG.FoldConstantArithmetic(ISD::SHL, VT, N0C, N1C);
3815 // fold (shl 0, x) -> 0
3816 if (N0C && N0C->isNullValue())
3818 // fold (shl x, c >= size(x)) -> undef
3819 if (N1C && N1C->getZExtValue() >= OpSizeInBits)
3820 return DAG.getUNDEF(VT);
3821 // fold (shl x, 0) -> x
3822 if (N1C && N1C->isNullValue())
3824 // fold (shl undef, x) -> 0
3825 if (N0.getOpcode() == ISD::UNDEF)
3826 return DAG.getConstant(0, VT);
3827 // if (shl x, c) is known to be zero, return 0
3828 if (DAG.MaskedValueIsZero(SDValue(N, 0),
3829 APInt::getAllOnesValue(OpSizeInBits)))
3830 return DAG.getConstant(0, VT);
3831 // fold (shl x, (trunc (and y, c))) -> (shl x, (and (trunc y), (trunc c))).
3832 if (N1.getOpcode() == ISD::TRUNCATE &&
3833 N1.getOperand(0).getOpcode() == ISD::AND &&
3834 N1.hasOneUse() && N1.getOperand(0).hasOneUse()) {
3835 SDValue N101 = N1.getOperand(0).getOperand(1);
3836 if (ConstantSDNode *N101C = dyn_cast<ConstantSDNode>(N101)) {
3837 EVT TruncVT = N1.getValueType();
3838 SDValue N100 = N1.getOperand(0).getOperand(0);
3839 APInt TruncC = N101C->getAPIntValue();
3840 TruncC = TruncC.trunc(TruncVT.getSizeInBits());
3841 return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0,
3842 DAG.getNode(ISD::AND, SDLoc(N), TruncVT,
3843 DAG.getNode(ISD::TRUNCATE,
3846 DAG.getConstant(TruncC, TruncVT)));
3850 if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
3851 return SDValue(N, 0);
3853 // fold (shl (shl x, c1), c2) -> 0 or (shl x, (add c1, c2))
3854 if (N1C && N0.getOpcode() == ISD::SHL &&
3855 N0.getOperand(1).getOpcode() == ISD::Constant) {
3856 uint64_t c1 = cast<ConstantSDNode>(N0.getOperand(1))->getZExtValue();
3857 uint64_t c2 = N1C->getZExtValue();
3858 if (c1 + c2 >= OpSizeInBits)
3859 return DAG.getConstant(0, VT);
3860 return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0.getOperand(0),
3861 DAG.getConstant(c1 + c2, N1.getValueType()));
3864 // fold (shl (ext (shl x, c1)), c2) -> (ext (shl x, (add c1, c2)))
3865 // For this to be valid, the second form must not preserve any of the bits
3866 // that are shifted out by the inner shift in the first form. This means
3867 // the outer shift size must be >= the number of bits added by the ext.
3868 // As a corollary, we don't care what kind of ext it is.
3869 if (N1C && (N0.getOpcode() == ISD::ZERO_EXTEND ||
3870 N0.getOpcode() == ISD::ANY_EXTEND ||
3871 N0.getOpcode() == ISD::SIGN_EXTEND) &&
3872 N0.getOperand(0).getOpcode() == ISD::SHL &&
3873 isa<ConstantSDNode>(N0.getOperand(0)->getOperand(1))) {
3875 cast<ConstantSDNode>(N0.getOperand(0)->getOperand(1))->getZExtValue();
3876 uint64_t c2 = N1C->getZExtValue();
3877 EVT InnerShiftVT = N0.getOperand(0).getValueType();
3878 uint64_t InnerShiftSize = InnerShiftVT.getScalarType().getSizeInBits();
3879 if (c2 >= OpSizeInBits - InnerShiftSize) {
3880 if (c1 + c2 >= OpSizeInBits)
3881 return DAG.getConstant(0, VT);
3882 return DAG.getNode(ISD::SHL, SDLoc(N0), VT,
3883 DAG.getNode(N0.getOpcode(), SDLoc(N0), VT,
3884 N0.getOperand(0)->getOperand(0)),
3885 DAG.getConstant(c1 + c2, N1.getValueType()));
3889 // fold (shl (zext (srl x, C)), C) -> (zext (shl (srl x, C), C))
3890 // Only fold this if the inner zext has no other uses to avoid increasing
3891 // the total number of instructions.
3892 if (N1C && N0.getOpcode() == ISD::ZERO_EXTEND && N0.hasOneUse() &&
3893 N0.getOperand(0).getOpcode() == ISD::SRL &&
3894 isa<ConstantSDNode>(N0.getOperand(0)->getOperand(1))) {
3896 cast<ConstantSDNode>(N0.getOperand(0)->getOperand(1))->getZExtValue();
3897 if (c1 < VT.getSizeInBits()) {
3898 uint64_t c2 = N1C->getZExtValue();
3900 SDValue NewOp0 = N0.getOperand(0);
3901 EVT CountVT = NewOp0.getOperand(1).getValueType();
3902 SDValue NewSHL = DAG.getNode(ISD::SHL, SDLoc(N), NewOp0.getValueType(),
3903 NewOp0, DAG.getConstant(c2, CountVT));
3904 AddToWorkList(NewSHL.getNode());
3905 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N0), VT, NewSHL);
3910 // fold (shl (srl x, c1), c2) -> (and (shl x, (sub c2, c1), MASK) or
3911 // (and (srl x, (sub c1, c2), MASK)
3912 // Only fold this if the inner shift has no other uses -- if it does, folding
3913 // this will increase the total number of instructions.
3914 if (N1C && N0.getOpcode() == ISD::SRL && N0.hasOneUse() &&
3915 N0.getOperand(1).getOpcode() == ISD::Constant) {
3916 uint64_t c1 = cast<ConstantSDNode>(N0.getOperand(1))->getZExtValue();
3917 if (c1 < VT.getSizeInBits()) {
3918 uint64_t c2 = N1C->getZExtValue();
3919 APInt Mask = APInt::getHighBitsSet(VT.getSizeInBits(),
3920 VT.getSizeInBits() - c1);
3923 Mask = Mask.shl(c2-c1);
3924 Shift = DAG.getNode(ISD::SHL, SDLoc(N), VT, N0.getOperand(0),
3925 DAG.getConstant(c2-c1, N1.getValueType()));
3927 Mask = Mask.lshr(c1-c2);
3928 Shift = DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0),
3929 DAG.getConstant(c1-c2, N1.getValueType()));
3931 return DAG.getNode(ISD::AND, SDLoc(N0), VT, Shift,
3932 DAG.getConstant(Mask, VT));
3935 // fold (shl (sra x, c1), c1) -> (and x, (shl -1, c1))
3936 if (N1C && N0.getOpcode() == ISD::SRA && N1 == N0.getOperand(1)) {
3937 SDValue HiBitsMask =
3938 DAG.getConstant(APInt::getHighBitsSet(VT.getSizeInBits(),
3939 VT.getSizeInBits() -
3940 N1C->getZExtValue()),
3942 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0.getOperand(0),
3947 SDValue NewSHL = visitShiftByConstant(N, N1C->getZExtValue());
3948 if (NewSHL.getNode())
3955 SDValue DAGCombiner::visitSRA(SDNode *N) {
3956 SDValue N0 = N->getOperand(0);
3957 SDValue N1 = N->getOperand(1);
3958 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
3959 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
3960 EVT VT = N0.getValueType();
3961 unsigned OpSizeInBits = VT.getScalarType().getSizeInBits();
3964 if (VT.isVector()) {
3965 SDValue FoldedVOp = SimplifyVBinOp(N);
3966 if (FoldedVOp.getNode()) return FoldedVOp;
3969 // fold (sra c1, c2) -> (sra c1, c2)
3971 return DAG.FoldConstantArithmetic(ISD::SRA, VT, N0C, N1C);
3972 // fold (sra 0, x) -> 0
3973 if (N0C && N0C->isNullValue())
3975 // fold (sra -1, x) -> -1
3976 if (N0C && N0C->isAllOnesValue())
3978 // fold (sra x, (setge c, size(x))) -> undef
3979 if (N1C && N1C->getZExtValue() >= OpSizeInBits)
3980 return DAG.getUNDEF(VT);
3981 // fold (sra x, 0) -> x
3982 if (N1C && N1C->isNullValue())
3984 // fold (sra (shl x, c1), c1) -> sext_inreg for some c1 and target supports
3986 if (N1C && N0.getOpcode() == ISD::SHL && N1 == N0.getOperand(1)) {
3987 unsigned LowBits = OpSizeInBits - (unsigned)N1C->getZExtValue();
3988 EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), LowBits);
3990 ExtVT = EVT::getVectorVT(*DAG.getContext(),
3991 ExtVT, VT.getVectorNumElements());
3992 if ((!LegalOperations ||
3993 TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, ExtVT)))
3994 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
3995 N0.getOperand(0), DAG.getValueType(ExtVT));
3998 // fold (sra (sra x, c1), c2) -> (sra x, (add c1, c2))
3999 if (N1C && N0.getOpcode() == ISD::SRA) {
4000 if (ConstantSDNode *C1 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
4001 unsigned Sum = N1C->getZExtValue() + C1->getZExtValue();
4002 if (Sum >= OpSizeInBits) Sum = OpSizeInBits-1;
4003 return DAG.getNode(ISD::SRA, SDLoc(N), VT, N0.getOperand(0),
4004 DAG.getConstant(Sum, N1C->getValueType(0)));
4008 // fold (sra (shl X, m), (sub result_size, n))
4009 // -> (sign_extend (trunc (shl X, (sub (sub result_size, n), m)))) for
4010 // result_size - n != m.
4011 // If truncate is free for the target sext(shl) is likely to result in better
4013 if (N0.getOpcode() == ISD::SHL) {
4014 // Get the two constanst of the shifts, CN0 = m, CN = n.
4015 const ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
4017 // Determine what the truncate's result bitsize and type would be.
4019 EVT::getIntegerVT(*DAG.getContext(),
4020 OpSizeInBits - N1C->getZExtValue());
4021 // Determine the residual right-shift amount.
4022 signed ShiftAmt = N1C->getZExtValue() - N01C->getZExtValue();
4024 // If the shift is not a no-op (in which case this should be just a sign
4025 // extend already), the truncated to type is legal, sign_extend is legal
4026 // on that type, and the truncate to that type is both legal and free,
4027 // perform the transform.
4028 if ((ShiftAmt > 0) &&
4029 TLI.isOperationLegalOrCustom(ISD::SIGN_EXTEND, TruncVT) &&
4030 TLI.isOperationLegalOrCustom(ISD::TRUNCATE, VT) &&
4031 TLI.isTruncateFree(VT, TruncVT)) {
4033 SDValue Amt = DAG.getConstant(ShiftAmt,
4034 getShiftAmountTy(N0.getOperand(0).getValueType()));
4035 SDValue Shift = DAG.getNode(ISD::SRL, SDLoc(N0), VT,
4036 N0.getOperand(0), Amt);
4037 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0), TruncVT,
4039 return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N),
4040 N->getValueType(0), Trunc);
4045 // fold (sra x, (trunc (and y, c))) -> (sra x, (and (trunc y), (trunc c))).
4046 if (N1.getOpcode() == ISD::TRUNCATE &&
4047 N1.getOperand(0).getOpcode() == ISD::AND &&
4048 N1.hasOneUse() && N1.getOperand(0).hasOneUse()) {
4049 SDValue N101 = N1.getOperand(0).getOperand(1);
4050 if (ConstantSDNode *N101C = dyn_cast<ConstantSDNode>(N101)) {
4051 EVT TruncVT = N1.getValueType();
4052 SDValue N100 = N1.getOperand(0).getOperand(0);
4053 APInt TruncC = N101C->getAPIntValue();
4054 TruncC = TruncC.trunc(TruncVT.getScalarType().getSizeInBits());
4055 return DAG.getNode(ISD::SRA, SDLoc(N), VT, N0,
4056 DAG.getNode(ISD::AND, SDLoc(N),
4058 DAG.getNode(ISD::TRUNCATE,
4061 DAG.getConstant(TruncC, TruncVT)));
4065 // fold (sra (trunc (sr x, c1)), c2) -> (trunc (sra x, c1+c2))
4066 // if c1 is equal to the number of bits the trunc removes
4067 if (N0.getOpcode() == ISD::TRUNCATE &&
4068 (N0.getOperand(0).getOpcode() == ISD::SRL ||
4069 N0.getOperand(0).getOpcode() == ISD::SRA) &&
4070 N0.getOperand(0).hasOneUse() &&
4071 N0.getOperand(0).getOperand(1).hasOneUse() &&
4072 N1C && isa<ConstantSDNode>(N0.getOperand(0).getOperand(1))) {
4073 EVT LargeVT = N0.getOperand(0).getValueType();
4074 ConstantSDNode *LargeShiftAmt =
4075 cast<ConstantSDNode>(N0.getOperand(0).getOperand(1));
4077 if (LargeVT.getScalarType().getSizeInBits() - OpSizeInBits ==
4078 LargeShiftAmt->getZExtValue()) {
4080 DAG.getConstant(LargeShiftAmt->getZExtValue() + N1C->getZExtValue(),
4081 getShiftAmountTy(N0.getOperand(0).getOperand(0).getValueType()));
4082 SDValue SRA = DAG.getNode(ISD::SRA, SDLoc(N), LargeVT,
4083 N0.getOperand(0).getOperand(0), Amt);
4084 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, SRA);
4088 // Simplify, based on bits shifted out of the LHS.
4089 if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
4090 return SDValue(N, 0);
4093 // If the sign bit is known to be zero, switch this to a SRL.
4094 if (DAG.SignBitIsZero(N0))
4095 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, N1);
4098 SDValue NewSRA = visitShiftByConstant(N, N1C->getZExtValue());
4099 if (NewSRA.getNode())
4106 SDValue DAGCombiner::visitSRL(SDNode *N) {
4107 SDValue N0 = N->getOperand(0);
4108 SDValue N1 = N->getOperand(1);
4109 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
4110 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4111 EVT VT = N0.getValueType();
4112 unsigned OpSizeInBits = VT.getScalarType().getSizeInBits();
4115 if (VT.isVector()) {
4116 SDValue FoldedVOp = SimplifyVBinOp(N);
4117 if (FoldedVOp.getNode()) return FoldedVOp;
4120 // fold (srl c1, c2) -> c1 >>u c2
4122 return DAG.FoldConstantArithmetic(ISD::SRL, VT, N0C, N1C);
4123 // fold (srl 0, x) -> 0
4124 if (N0C && N0C->isNullValue())
4126 // fold (srl x, c >= size(x)) -> undef
4127 if (N1C && N1C->getZExtValue() >= OpSizeInBits)
4128 return DAG.getUNDEF(VT);
4129 // fold (srl x, 0) -> x
4130 if (N1C && N1C->isNullValue())
4132 // if (srl x, c) is known to be zero, return 0
4133 if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0),
4134 APInt::getAllOnesValue(OpSizeInBits)))
4135 return DAG.getConstant(0, VT);
4137 // fold (srl (srl x, c1), c2) -> 0 or (srl x, (add c1, c2))
4138 if (N1C && N0.getOpcode() == ISD::SRL &&
4139 N0.getOperand(1).getOpcode() == ISD::Constant) {
4140 uint64_t c1 = cast<ConstantSDNode>(N0.getOperand(1))->getZExtValue();
4141 uint64_t c2 = N1C->getZExtValue();
4142 if (c1 + c2 >= OpSizeInBits)
4143 return DAG.getConstant(0, VT);
4144 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0),
4145 DAG.getConstant(c1 + c2, N1.getValueType()));
4148 // fold (srl (trunc (srl x, c1)), c2) -> 0 or (trunc (srl x, (add c1, c2)))
4149 if (N1C && N0.getOpcode() == ISD::TRUNCATE &&
4150 N0.getOperand(0).getOpcode() == ISD::SRL &&
4151 isa<ConstantSDNode>(N0.getOperand(0)->getOperand(1))) {
4153 cast<ConstantSDNode>(N0.getOperand(0)->getOperand(1))->getZExtValue();
4154 uint64_t c2 = N1C->getZExtValue();
4155 EVT InnerShiftVT = N0.getOperand(0).getValueType();
4156 EVT ShiftCountVT = N0.getOperand(0)->getOperand(1).getValueType();
4157 uint64_t InnerShiftSize = InnerShiftVT.getScalarType().getSizeInBits();
4158 // This is only valid if the OpSizeInBits + c1 = size of inner shift.
4159 if (c1 + OpSizeInBits == InnerShiftSize) {
4160 if (c1 + c2 >= InnerShiftSize)
4161 return DAG.getConstant(0, VT);
4162 return DAG.getNode(ISD::TRUNCATE, SDLoc(N0), VT,
4163 DAG.getNode(ISD::SRL, SDLoc(N0), InnerShiftVT,
4164 N0.getOperand(0)->getOperand(0),
4165 DAG.getConstant(c1 + c2, ShiftCountVT)));
4169 // fold (srl (shl x, c), c) -> (and x, cst2)
4170 if (N1C && N0.getOpcode() == ISD::SHL && N0.getOperand(1) == N1 &&
4171 N0.getValueSizeInBits() <= 64) {
4172 uint64_t ShAmt = N1C->getZExtValue()+64-N0.getValueSizeInBits();
4173 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0.getOperand(0),
4174 DAG.getConstant(~0ULL >> ShAmt, VT));
4177 // fold (srl (anyextend x), c) -> (and (anyextend (srl x, c)), mask)
4178 if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
4179 // Shifting in all undef bits?
4180 EVT SmallVT = N0.getOperand(0).getValueType();
4181 if (N1C->getZExtValue() >= SmallVT.getSizeInBits())
4182 return DAG.getUNDEF(VT);
4184 if (!LegalTypes || TLI.isTypeDesirableForOp(ISD::SRL, SmallVT)) {
4185 uint64_t ShiftAmt = N1C->getZExtValue();
4186 SDValue SmallShift = DAG.getNode(ISD::SRL, SDLoc(N0), SmallVT,
4188 DAG.getConstant(ShiftAmt, getShiftAmountTy(SmallVT)));
4189 AddToWorkList(SmallShift.getNode());
4190 APInt Mask = APInt::getAllOnesValue(VT.getSizeInBits()).lshr(ShiftAmt);
4191 return DAG.getNode(ISD::AND, SDLoc(N), VT,
4192 DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, SmallShift),
4193 DAG.getConstant(Mask, VT));
4197 // fold (srl (sra X, Y), 31) -> (srl X, 31). This srl only looks at the sign
4198 // bit, which is unmodified by sra.
4199 if (N1C && N1C->getZExtValue() + 1 == VT.getSizeInBits()) {
4200 if (N0.getOpcode() == ISD::SRA)
4201 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0), N1);
4204 // fold (srl (ctlz x), "5") -> x iff x has one bit set (the low bit).
4205 if (N1C && N0.getOpcode() == ISD::CTLZ &&
4206 N1C->getAPIntValue() == Log2_32(VT.getSizeInBits())) {
4207 APInt KnownZero, KnownOne;
4208 DAG.ComputeMaskedBits(N0.getOperand(0), KnownZero, KnownOne);
4210 // If any of the input bits are KnownOne, then the input couldn't be all
4211 // zeros, thus the result of the srl will always be zero.
4212 if (KnownOne.getBoolValue()) return DAG.getConstant(0, VT);
4214 // If all of the bits input the to ctlz node are known to be zero, then
4215 // the result of the ctlz is "32" and the result of the shift is one.
4216 APInt UnknownBits = ~KnownZero;
4217 if (UnknownBits == 0) return DAG.getConstant(1, VT);
4219 // Otherwise, check to see if there is exactly one bit input to the ctlz.
4220 if ((UnknownBits & (UnknownBits - 1)) == 0) {
4221 // Okay, we know that only that the single bit specified by UnknownBits
4222 // could be set on input to the CTLZ node. If this bit is set, the SRL
4223 // will return 0, if it is clear, it returns 1. Change the CTLZ/SRL pair
4224 // to an SRL/XOR pair, which is likely to simplify more.
4225 unsigned ShAmt = UnknownBits.countTrailingZeros();
4226 SDValue Op = N0.getOperand(0);
4229 Op = DAG.getNode(ISD::SRL, SDLoc(N0), VT, Op,
4230 DAG.getConstant(ShAmt, getShiftAmountTy(Op.getValueType())));
4231 AddToWorkList(Op.getNode());
4234 return DAG.getNode(ISD::XOR, SDLoc(N), VT,
4235 Op, DAG.getConstant(1, VT));
4239 // fold (srl x, (trunc (and y, c))) -> (srl x, (and (trunc y), (trunc c))).
4240 if (N1.getOpcode() == ISD::TRUNCATE &&
4241 N1.getOperand(0).getOpcode() == ISD::AND &&
4242 N1.hasOneUse() && N1.getOperand(0).hasOneUse()) {
4243 SDValue N101 = N1.getOperand(0).getOperand(1);
4244 if (ConstantSDNode *N101C = dyn_cast<ConstantSDNode>(N101)) {
4245 EVT TruncVT = N1.getValueType();
4246 SDValue N100 = N1.getOperand(0).getOperand(0);
4247 APInt TruncC = N101C->getAPIntValue();
4248 TruncC = TruncC.trunc(TruncVT.getSizeInBits());
4249 return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0,
4250 DAG.getNode(ISD::AND, SDLoc(N),
4252 DAG.getNode(ISD::TRUNCATE,
4255 DAG.getConstant(TruncC, TruncVT)));
4259 // fold operands of srl based on knowledge that the low bits are not
4261 if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
4262 return SDValue(N, 0);
4265 SDValue NewSRL = visitShiftByConstant(N, N1C->getZExtValue());
4266 if (NewSRL.getNode())
4270 // Attempt to convert a srl of a load into a narrower zero-extending load.
4271 SDValue NarrowLoad = ReduceLoadWidth(N);
4272 if (NarrowLoad.getNode())
4275 // Here is a common situation. We want to optimize:
4278 // %b = and i32 %a, 2
4279 // %c = srl i32 %b, 1
4280 // brcond i32 %c ...
4286 // %c = setcc eq %b, 0
4289 // However when after the source operand of SRL is optimized into AND, the SRL
4290 // itself may not be optimized further. Look for it and add the BRCOND into
4292 if (N->hasOneUse()) {
4293 SDNode *Use = *N->use_begin();
4294 if (Use->getOpcode() == ISD::BRCOND)
4296 else if (Use->getOpcode() == ISD::TRUNCATE && Use->hasOneUse()) {
4297 // Also look pass the truncate.
4298 Use = *Use->use_begin();
4299 if (Use->getOpcode() == ISD::BRCOND)
4307 SDValue DAGCombiner::visitCTLZ(SDNode *N) {
4308 SDValue N0 = N->getOperand(0);
4309 EVT VT = N->getValueType(0);
4311 // fold (ctlz c1) -> c2
4312 if (isa<ConstantSDNode>(N0))
4313 return DAG.getNode(ISD::CTLZ, SDLoc(N), VT, N0);
4317 SDValue DAGCombiner::visitCTLZ_ZERO_UNDEF(SDNode *N) {
4318 SDValue N0 = N->getOperand(0);
4319 EVT VT = N->getValueType(0);
4321 // fold (ctlz_zero_undef c1) -> c2
4322 if (isa<ConstantSDNode>(N0))
4323 return DAG.getNode(ISD::CTLZ_ZERO_UNDEF, SDLoc(N), VT, N0);
4327 SDValue DAGCombiner::visitCTTZ(SDNode *N) {
4328 SDValue N0 = N->getOperand(0);
4329 EVT VT = N->getValueType(0);
4331 // fold (cttz c1) -> c2
4332 if (isa<ConstantSDNode>(N0))
4333 return DAG.getNode(ISD::CTTZ, SDLoc(N), VT, N0);
4337 SDValue DAGCombiner::visitCTTZ_ZERO_UNDEF(SDNode *N) {
4338 SDValue N0 = N->getOperand(0);
4339 EVT VT = N->getValueType(0);
4341 // fold (cttz_zero_undef c1) -> c2
4342 if (isa<ConstantSDNode>(N0))
4343 return DAG.getNode(ISD::CTTZ_ZERO_UNDEF, SDLoc(N), VT, N0);
4347 SDValue DAGCombiner::visitCTPOP(SDNode *N) {
4348 SDValue N0 = N->getOperand(0);
4349 EVT VT = N->getValueType(0);
4351 // fold (ctpop c1) -> c2
4352 if (isa<ConstantSDNode>(N0))
4353 return DAG.getNode(ISD::CTPOP, SDLoc(N), VT, N0);
4357 SDValue DAGCombiner::visitSELECT(SDNode *N) {
4358 SDValue N0 = N->getOperand(0);
4359 SDValue N1 = N->getOperand(1);
4360 SDValue N2 = N->getOperand(2);
4361 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
4362 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4363 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2);
4364 EVT VT = N->getValueType(0);
4365 EVT VT0 = N0.getValueType();
4367 // fold (select C, X, X) -> X
4370 // fold (select true, X, Y) -> X
4371 if (N0C && !N0C->isNullValue())
4373 // fold (select false, X, Y) -> Y
4374 if (N0C && N0C->isNullValue())
4376 // fold (select C, 1, X) -> (or C, X)
4377 if (VT == MVT::i1 && N1C && N1C->getAPIntValue() == 1)
4378 return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N2);
4379 // fold (select C, 0, 1) -> (xor C, 1)
4380 if (VT.isInteger() &&
4383 TLI.getBooleanContents(false) ==
4384 TargetLowering::ZeroOrOneBooleanContent)) &&
4385 N1C && N2C && N1C->isNullValue() && N2C->getAPIntValue() == 1) {
4388 return DAG.getNode(ISD::XOR, SDLoc(N), VT0,
4389 N0, DAG.getConstant(1, VT0));
4390 XORNode = DAG.getNode(ISD::XOR, SDLoc(N0), VT0,
4391 N0, DAG.getConstant(1, VT0));
4392 AddToWorkList(XORNode.getNode());
4394 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, XORNode);
4395 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, XORNode);
4397 // fold (select C, 0, X) -> (and (not C), X)
4398 if (VT == VT0 && VT == MVT::i1 && N1C && N1C->isNullValue()) {
4399 SDValue NOTNode = DAG.getNOT(SDLoc(N0), N0, VT);
4400 AddToWorkList(NOTNode.getNode());
4401 return DAG.getNode(ISD::AND, SDLoc(N), VT, NOTNode, N2);
4403 // fold (select C, X, 1) -> (or (not C), X)
4404 if (VT == VT0 && VT == MVT::i1 && N2C && N2C->getAPIntValue() == 1) {
4405 SDValue NOTNode = DAG.getNOT(SDLoc(N0), N0, VT);
4406 AddToWorkList(NOTNode.getNode());
4407 return DAG.getNode(ISD::OR, SDLoc(N), VT, NOTNode, N1);
4409 // fold (select C, X, 0) -> (and C, X)
4410 if (VT == MVT::i1 && N2C && N2C->isNullValue())
4411 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, N1);
4412 // fold (select X, X, Y) -> (or X, Y)
4413 // fold (select X, 1, Y) -> (or X, Y)
4414 if (VT == MVT::i1 && (N0 == N1 || (N1C && N1C->getAPIntValue() == 1)))
4415 return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N2);
4416 // fold (select X, Y, X) -> (and X, Y)
4417 // fold (select X, Y, 0) -> (and X, Y)
4418 if (VT == MVT::i1 && (N0 == N2 || (N2C && N2C->getAPIntValue() == 0)))
4419 return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, N1);
4421 // If we can fold this based on the true/false value, do so.
4422 if (SimplifySelectOps(N, N1, N2))
4423 return SDValue(N, 0); // Don't revisit N.
4425 // fold selects based on a setcc into other things, such as min/max/abs
4426 if (N0.getOpcode() == ISD::SETCC) {
4428 // Check against MVT::Other for SELECT_CC, which is a workaround for targets
4429 // having to say they don't support SELECT_CC on every type the DAG knows
4430 // about, since there is no way to mark an opcode illegal at all value types
4431 if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, MVT::Other) &&
4432 TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT))
4433 return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT,
4434 N0.getOperand(0), N0.getOperand(1),
4435 N1, N2, N0.getOperand(2));
4436 return SimplifySelect(SDLoc(N), N0, N1, N2);
4443 std::pair<SDValue, SDValue> SplitVSETCC(const SDNode *N, SelectionDAG &DAG) {
4446 llvm::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(N->getValueType(0));
4448 // Split the inputs.
4449 SDValue Lo, Hi, LL, LH, RL, RH;
4450 llvm::tie(LL, LH) = DAG.SplitVectorOperand(N, 0);
4451 llvm::tie(RL, RH) = DAG.SplitVectorOperand(N, 1);
4453 Lo = DAG.getNode(N->getOpcode(), DL, LoVT, LL, RL, N->getOperand(2));
4454 Hi = DAG.getNode(N->getOpcode(), DL, HiVT, LH, RH, N->getOperand(2));
4456 return std::make_pair(Lo, Hi);
4459 SDValue DAGCombiner::visitVSELECT(SDNode *N) {
4460 SDValue N0 = N->getOperand(0);
4461 SDValue N1 = N->getOperand(1);
4462 SDValue N2 = N->getOperand(2);
4465 // Canonicalize integer abs.
4466 // vselect (setg[te] X, 0), X, -X ->
4467 // vselect (setgt X, -1), X, -X ->
4468 // vselect (setl[te] X, 0), -X, X ->
4469 // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
4470 if (N0.getOpcode() == ISD::SETCC) {
4471 SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
4472 ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
4474 bool RHSIsAllZeros = ISD::isBuildVectorAllZeros(RHS.getNode());
4476 if (((RHSIsAllZeros && (CC == ISD::SETGT || CC == ISD::SETGE)) ||
4477 (ISD::isBuildVectorAllOnes(RHS.getNode()) && CC == ISD::SETGT)) &&
4478 N1 == LHS && N2.getOpcode() == ISD::SUB && N1 == N2.getOperand(1))
4479 isAbs = ISD::isBuildVectorAllZeros(N2.getOperand(0).getNode());
4480 else if ((RHSIsAllZeros && (CC == ISD::SETLT || CC == ISD::SETLE)) &&
4481 N2 == LHS && N1.getOpcode() == ISD::SUB && N2 == N1.getOperand(1))
4482 isAbs = ISD::isBuildVectorAllZeros(N1.getOperand(0).getNode());
4485 EVT VT = LHS.getValueType();
4486 SDValue Shift = DAG.getNode(
4487 ISD::SRA, DL, VT, LHS,
4488 DAG.getConstant(VT.getScalarType().getSizeInBits() - 1, VT));
4489 SDValue Add = DAG.getNode(ISD::ADD, DL, VT, LHS, Shift);
4490 AddToWorkList(Shift.getNode());
4491 AddToWorkList(Add.getNode());
4492 return DAG.getNode(ISD::XOR, DL, VT, Add, Shift);
4496 // If the VSELECT result requires splitting and the mask is provided by a
4497 // SETCC, then split both nodes and its operands before legalization. This
4498 // prevents the type legalizer from unrolling SETCC into scalar comparisons
4499 // and enables future optimizations (e.g. min/max pattern matching on X86).
4500 if (N0.getOpcode() == ISD::SETCC) {
4501 EVT VT = N->getValueType(0);
4503 // Check if any splitting is required.
4504 if (TLI.getTypeAction(*DAG.getContext(), VT) !=
4505 TargetLowering::TypeSplitVector)
4508 SDValue Lo, Hi, CCLo, CCHi, LL, LH, RL, RH;
4509 llvm::tie(CCLo, CCHi) = SplitVSETCC(N0.getNode(), DAG);
4510 llvm::tie(LL, LH) = DAG.SplitVectorOperand(N, 1);
4511 llvm::tie(RL, RH) = DAG.SplitVectorOperand(N, 2);
4513 Lo = DAG.getNode(N->getOpcode(), DL, LL.getValueType(), CCLo, LL, RL);
4514 Hi = DAG.getNode(N->getOpcode(), DL, LH.getValueType(), CCHi, LH, RH);
4516 // Add the new VSELECT nodes to the work list in case they need to be split
4518 AddToWorkList(Lo.getNode());
4519 AddToWorkList(Hi.getNode());
4521 return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
4524 // Fold (vselect (build_vector all_ones), N1, N2) -> N1
4525 if (ISD::isBuildVectorAllOnes(N0.getNode()))
4527 // Fold (vselect (build_vector all_zeros), N1, N2) -> N2
4528 if (ISD::isBuildVectorAllZeros(N0.getNode()))
4534 SDValue DAGCombiner::visitSELECT_CC(SDNode *N) {
4535 SDValue N0 = N->getOperand(0);
4536 SDValue N1 = N->getOperand(1);
4537 SDValue N2 = N->getOperand(2);
4538 SDValue N3 = N->getOperand(3);
4539 SDValue N4 = N->getOperand(4);
4540 ISD::CondCode CC = cast<CondCodeSDNode>(N4)->get();
4542 // fold select_cc lhs, rhs, x, x, cc -> x
4546 // Determine if the condition we're dealing with is constant
4547 SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()),
4548 N0, N1, CC, SDLoc(N), false);
4549 if (SCC.getNode()) {
4550 AddToWorkList(SCC.getNode());
4552 if (ConstantSDNode *SCCC = dyn_cast<ConstantSDNode>(SCC.getNode())) {
4553 if (!SCCC->isNullValue())
4554 return N2; // cond always true -> true val
4556 return N3; // cond always false -> false val
4559 // Fold to a simpler select_cc
4560 if (SCC.getOpcode() == ISD::SETCC)
4561 return DAG.getNode(ISD::SELECT_CC, SDLoc(N), N2.getValueType(),
4562 SCC.getOperand(0), SCC.getOperand(1), N2, N3,
4566 // If we can fold this based on the true/false value, do so.
4567 if (SimplifySelectOps(N, N2, N3))
4568 return SDValue(N, 0); // Don't revisit N.
4570 // fold select_cc into other things, such as min/max/abs
4571 return SimplifySelectCC(SDLoc(N), N0, N1, N2, N3, CC);
4574 SDValue DAGCombiner::visitSETCC(SDNode *N) {
4575 return SimplifySetCC(N->getValueType(0), N->getOperand(0), N->getOperand(1),
4576 cast<CondCodeSDNode>(N->getOperand(2))->get(),
4580 // ExtendUsesToFormExtLoad - Trying to extend uses of a load to enable this:
4581 // "fold ({s|z|a}ext (load x)) -> ({s|z|a}ext (truncate ({s|z|a}extload x)))"
4582 // transformation. Returns true if extension are possible and the above
4583 // mentioned transformation is profitable.
4584 static bool ExtendUsesToFormExtLoad(SDNode *N, SDValue N0,
4586 SmallVectorImpl<SDNode *> &ExtendNodes,
4587 const TargetLowering &TLI) {
4588 bool HasCopyToRegUses = false;
4589 bool isTruncFree = TLI.isTruncateFree(N->getValueType(0), N0.getValueType());
4590 for (SDNode::use_iterator UI = N0.getNode()->use_begin(),
4591 UE = N0.getNode()->use_end();
4596 if (UI.getUse().getResNo() != N0.getResNo())
4598 // FIXME: Only extend SETCC N, N and SETCC N, c for now.
4599 if (ExtOpc != ISD::ANY_EXTEND && User->getOpcode() == ISD::SETCC) {
4600 ISD::CondCode CC = cast<CondCodeSDNode>(User->getOperand(2))->get();
4601 if (ExtOpc == ISD::ZERO_EXTEND && ISD::isSignedIntSetCC(CC))
4602 // Sign bits will be lost after a zext.
4605 for (unsigned i = 0; i != 2; ++i) {
4606 SDValue UseOp = User->getOperand(i);
4609 if (!isa<ConstantSDNode>(UseOp))
4614 ExtendNodes.push_back(User);
4617 // If truncates aren't free and there are users we can't
4618 // extend, it isn't worthwhile.
4621 // Remember if this value is live-out.
4622 if (User->getOpcode() == ISD::CopyToReg)
4623 HasCopyToRegUses = true;
4626 if (HasCopyToRegUses) {
4627 bool BothLiveOut = false;
4628 for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
4630 SDUse &Use = UI.getUse();
4631 if (Use.getResNo() == 0 && Use.getUser()->getOpcode() == ISD::CopyToReg) {
4637 // Both unextended and extended values are live out. There had better be
4638 // a good reason for the transformation.
4639 return ExtendNodes.size();
4644 void DAGCombiner::ExtendSetCCUses(const SmallVectorImpl<SDNode *> &SetCCs,
4645 SDValue Trunc, SDValue ExtLoad, SDLoc DL,
4646 ISD::NodeType ExtType) {
4647 // Extend SetCC uses if necessary.
4648 for (unsigned i = 0, e = SetCCs.size(); i != e; ++i) {
4649 SDNode *SetCC = SetCCs[i];
4650 SmallVector<SDValue, 4> Ops;
4652 for (unsigned j = 0; j != 2; ++j) {
4653 SDValue SOp = SetCC->getOperand(j);
4655 Ops.push_back(ExtLoad);
4657 Ops.push_back(DAG.getNode(ExtType, DL, ExtLoad->getValueType(0), SOp));
4660 Ops.push_back(SetCC->getOperand(2));
4661 CombineTo(SetCC, DAG.getNode(ISD::SETCC, DL, SetCC->getValueType(0),
4662 &Ops[0], Ops.size()));
4666 SDValue DAGCombiner::visitSIGN_EXTEND(SDNode *N) {
4667 SDValue N0 = N->getOperand(0);
4668 EVT VT = N->getValueType(0);
4670 // fold (sext c1) -> c1
4671 if (isa<ConstantSDNode>(N0))
4672 return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, N0);
4674 // fold (sext (sext x)) -> (sext x)
4675 // fold (sext (aext x)) -> (sext x)
4676 if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
4677 return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT,
4680 if (N0.getOpcode() == ISD::TRUNCATE) {
4681 // fold (sext (truncate (load x))) -> (sext (smaller load x))
4682 // fold (sext (truncate (srl (load x), c))) -> (sext (smaller load (x+c/n)))
4683 SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
4684 if (NarrowLoad.getNode()) {
4685 SDNode* oye = N0.getNode()->getOperand(0).getNode();
4686 if (NarrowLoad.getNode() != N0.getNode()) {
4687 CombineTo(N0.getNode(), NarrowLoad);
4688 // CombineTo deleted the truncate, if needed, but not what's under it.
4691 return SDValue(N, 0); // Return N so it doesn't get rechecked!
4694 // See if the value being truncated is already sign extended. If so, just
4695 // eliminate the trunc/sext pair.
4696 SDValue Op = N0.getOperand(0);
4697 unsigned OpBits = Op.getValueType().getScalarType().getSizeInBits();
4698 unsigned MidBits = N0.getValueType().getScalarType().getSizeInBits();
4699 unsigned DestBits = VT.getScalarType().getSizeInBits();
4700 unsigned NumSignBits = DAG.ComputeNumSignBits(Op);
4702 if (OpBits == DestBits) {
4703 // Op is i32, Mid is i8, and Dest is i32. If Op has more than 24 sign
4704 // bits, it is already ready.
4705 if (NumSignBits > DestBits-MidBits)
4707 } else if (OpBits < DestBits) {
4708 // Op is i32, Mid is i8, and Dest is i64. If Op has more than 24 sign
4709 // bits, just sext from i32.
4710 if (NumSignBits > OpBits-MidBits)
4711 return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, Op);
4713 // Op is i64, Mid is i8, and Dest is i32. If Op has more than 56 sign
4714 // bits, just truncate to i32.
4715 if (NumSignBits > OpBits-MidBits)
4716 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
4719 // fold (sext (truncate x)) -> (sextinreg x).
4720 if (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG,
4721 N0.getValueType())) {
4722 if (OpBits < DestBits)
4723 Op = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N0), VT, Op);
4724 else if (OpBits > DestBits)
4725 Op = DAG.getNode(ISD::TRUNCATE, SDLoc(N0), VT, Op);
4726 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, Op,
4727 DAG.getValueType(N0.getValueType()));
4731 // fold (sext (load x)) -> (sext (truncate (sextload x)))
4732 // None of the supported targets knows how to perform load and sign extend
4733 // on vectors in one instruction. We only perform this transformation on
4735 if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() &&
4736 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
4737 TLI.isLoadExtLegal(ISD::SEXTLOAD, N0.getValueType()))) {
4738 bool DoXform = true;
4739 SmallVector<SDNode*, 4> SetCCs;
4740 if (!N0.hasOneUse())
4741 DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::SIGN_EXTEND, SetCCs, TLI);
4743 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
4744 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
4746 LN0->getBasePtr(), N0.getValueType(),
4747 LN0->getMemOperand());
4748 CombineTo(N, ExtLoad);
4749 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
4750 N0.getValueType(), ExtLoad);
4751 CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
4752 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
4754 return SDValue(N, 0); // Return N so it doesn't get rechecked!
4758 // fold (sext (sextload x)) -> (sext (truncate (sextload x)))
4759 // fold (sext ( extload x)) -> (sext (truncate (sextload x)))
4760 if ((ISD::isSEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) &&
4761 ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) {
4762 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
4763 EVT MemVT = LN0->getMemoryVT();
4764 if ((!LegalOperations && !LN0->isVolatile()) ||
4765 TLI.isLoadExtLegal(ISD::SEXTLOAD, MemVT)) {
4766 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
4768 LN0->getBasePtr(), MemVT,
4769 LN0->getMemOperand());
4770 CombineTo(N, ExtLoad);
4771 CombineTo(N0.getNode(),
4772 DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
4773 N0.getValueType(), ExtLoad),
4774 ExtLoad.getValue(1));
4775 return SDValue(N, 0); // Return N so it doesn't get rechecked!
4779 // fold (sext (and/or/xor (load x), cst)) ->
4780 // (and/or/xor (sextload x), (sext cst))
4781 if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR ||
4782 N0.getOpcode() == ISD::XOR) &&
4783 isa<LoadSDNode>(N0.getOperand(0)) &&
4784 N0.getOperand(1).getOpcode() == ISD::Constant &&
4785 TLI.isLoadExtLegal(ISD::SEXTLOAD, N0.getValueType()) &&
4786 (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) {
4787 LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0));
4788 if (LN0->getExtensionType() != ISD::ZEXTLOAD) {
4789 bool DoXform = true;
4790 SmallVector<SDNode*, 4> SetCCs;
4791 if (!N0.hasOneUse())
4792 DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0), ISD::SIGN_EXTEND,
4795 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(LN0), VT,
4796 LN0->getChain(), LN0->getBasePtr(),
4798 LN0->getMemOperand());
4799 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
4800 Mask = Mask.sext(VT.getSizeInBits());
4801 SDValue And = DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
4802 ExtLoad, DAG.getConstant(Mask, VT));
4803 SDValue Trunc = DAG.getNode(ISD::TRUNCATE,
4804 SDLoc(N0.getOperand(0)),
4805 N0.getOperand(0).getValueType(), ExtLoad);
4807 CombineTo(N0.getOperand(0).getNode(), Trunc, ExtLoad.getValue(1));
4808 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
4810 return SDValue(N, 0); // Return N so it doesn't get rechecked!
4815 if (N0.getOpcode() == ISD::SETCC) {
4816 // sext(setcc) -> sext_in_reg(vsetcc) for vectors.
4817 // Only do this before legalize for now.
4818 if (VT.isVector() && !LegalOperations &&
4819 TLI.getBooleanContents(true) ==
4820 TargetLowering::ZeroOrNegativeOneBooleanContent) {
4821 EVT N0VT = N0.getOperand(0).getValueType();
4822 // On some architectures (such as SSE/NEON/etc) the SETCC result type is
4823 // of the same size as the compared operands. Only optimize sext(setcc())
4824 // if this is the case.
4825 EVT SVT = getSetCCResultType(N0VT);
4827 // We know that the # elements of the results is the same as the
4828 // # elements of the compare (and the # elements of the compare result
4829 // for that matter). Check to see that they are the same size. If so,
4830 // we know that the element size of the sext'd result matches the
4831 // element size of the compare operands.
4832 if (VT.getSizeInBits() == SVT.getSizeInBits())
4833 return DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
4835 cast<CondCodeSDNode>(N0.getOperand(2))->get());
4837 // If the desired elements are smaller or larger than the source
4838 // elements we can use a matching integer vector type and then
4839 // truncate/sign extend
4840 EVT MatchingVectorType = N0VT.changeVectorElementTypeToInteger();
4841 if (SVT == MatchingVectorType) {
4842 SDValue VsetCC = DAG.getSetCC(SDLoc(N), MatchingVectorType,
4843 N0.getOperand(0), N0.getOperand(1),
4844 cast<CondCodeSDNode>(N0.getOperand(2))->get());
4845 return DAG.getSExtOrTrunc(VsetCC, SDLoc(N), VT);
4849 // sext(setcc x, y, cc) -> (select_cc x, y, -1, 0, cc)
4850 unsigned ElementWidth = VT.getScalarType().getSizeInBits();
4852 DAG.getConstant(APInt::getAllOnesValue(ElementWidth), VT);
4854 SimplifySelectCC(SDLoc(N), N0.getOperand(0), N0.getOperand(1),
4855 NegOne, DAG.getConstant(0, VT),
4856 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
4857 if (SCC.getNode()) return SCC;
4858 if (!VT.isVector() &&
4859 (!LegalOperations ||
4860 TLI.isOperationLegal(ISD::SETCC, getSetCCResultType(VT)))) {
4861 return DAG.getSelect(SDLoc(N), VT,
4862 DAG.getSetCC(SDLoc(N),
4863 getSetCCResultType(VT),
4864 N0.getOperand(0), N0.getOperand(1),
4865 cast<CondCodeSDNode>(N0.getOperand(2))->get()),
4866 NegOne, DAG.getConstant(0, VT));
4870 // fold (sext x) -> (zext x) if the sign bit is known zero.
4871 if ((!LegalOperations || TLI.isOperationLegal(ISD::ZERO_EXTEND, VT)) &&
4872 DAG.SignBitIsZero(N0))
4873 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, N0);
4878 // isTruncateOf - If N is a truncate of some other value, return true, record
4879 // the value being truncated in Op and which of Op's bits are zero in KnownZero.
4880 // This function computes KnownZero to avoid a duplicated call to
4881 // ComputeMaskedBits in the caller.
4882 static bool isTruncateOf(SelectionDAG &DAG, SDValue N, SDValue &Op,
4885 if (N->getOpcode() == ISD::TRUNCATE) {
4886 Op = N->getOperand(0);
4887 DAG.ComputeMaskedBits(Op, KnownZero, KnownOne);
4891 if (N->getOpcode() != ISD::SETCC || N->getValueType(0) != MVT::i1 ||
4892 cast<CondCodeSDNode>(N->getOperand(2))->get() != ISD::SETNE)
4895 SDValue Op0 = N->getOperand(0);
4896 SDValue Op1 = N->getOperand(1);
4897 assert(Op0.getValueType() == Op1.getValueType());
4899 ConstantSDNode *COp0 = dyn_cast<ConstantSDNode>(Op0);
4900 ConstantSDNode *COp1 = dyn_cast<ConstantSDNode>(Op1);
4901 if (COp0 && COp0->isNullValue())
4903 else if (COp1 && COp1->isNullValue())
4908 DAG.ComputeMaskedBits(Op, KnownZero, KnownOne);
4910 if (!(KnownZero | APInt(Op.getValueSizeInBits(), 1)).isAllOnesValue())
4916 SDValue DAGCombiner::visitZERO_EXTEND(SDNode *N) {
4917 SDValue N0 = N->getOperand(0);
4918 EVT VT = N->getValueType(0);
4920 // fold (zext c1) -> c1
4921 if (isa<ConstantSDNode>(N0))
4922 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, N0);
4923 // fold (zext (zext x)) -> (zext x)
4924 // fold (zext (aext x)) -> (zext x)
4925 if (N0.getOpcode() == ISD::ZERO_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
4926 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT,
4929 // fold (zext (truncate x)) -> (zext x) or
4930 // (zext (truncate x)) -> (truncate x)
4931 // This is valid when the truncated bits of x are already zero.
4932 // FIXME: We should extend this to work for vectors too.
4935 if (!VT.isVector() && isTruncateOf(DAG, N0, Op, KnownZero)) {
4936 APInt TruncatedBits =
4937 (Op.getValueSizeInBits() == N0.getValueSizeInBits()) ?
4938 APInt(Op.getValueSizeInBits(), 0) :
4939 APInt::getBitsSet(Op.getValueSizeInBits(),
4940 N0.getValueSizeInBits(),
4941 std::min(Op.getValueSizeInBits(),
4942 VT.getSizeInBits()));
4943 if (TruncatedBits == (KnownZero & TruncatedBits)) {
4944 if (VT.bitsGT(Op.getValueType()))
4945 return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, Op);
4946 if (VT.bitsLT(Op.getValueType()))
4947 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
4953 // fold (zext (truncate (load x))) -> (zext (smaller load x))
4954 // fold (zext (truncate (srl (load x), c))) -> (zext (small load (x+c/n)))
4955 if (N0.getOpcode() == ISD::TRUNCATE) {
4956 SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
4957 if (NarrowLoad.getNode()) {
4958 SDNode* oye = N0.getNode()->getOperand(0).getNode();
4959 if (NarrowLoad.getNode() != N0.getNode()) {
4960 CombineTo(N0.getNode(), NarrowLoad);
4961 // CombineTo deleted the truncate, if needed, but not what's under it.
4964 return SDValue(N, 0); // Return N so it doesn't get rechecked!
4968 // fold (zext (truncate x)) -> (and x, mask)
4969 if (N0.getOpcode() == ISD::TRUNCATE &&
4970 (!LegalOperations || TLI.isOperationLegal(ISD::AND, VT))) {
4972 // fold (zext (truncate (load x))) -> (zext (smaller load x))
4973 // fold (zext (truncate (srl (load x), c))) -> (zext (smaller load (x+c/n)))
4974 SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
4975 if (NarrowLoad.getNode()) {
4976 SDNode* oye = N0.getNode()->getOperand(0).getNode();
4977 if (NarrowLoad.getNode() != N0.getNode()) {
4978 CombineTo(N0.getNode(), NarrowLoad);
4979 // CombineTo deleted the truncate, if needed, but not what's under it.
4982 return SDValue(N, 0); // Return N so it doesn't get rechecked!
4985 SDValue Op = N0.getOperand(0);
4986 if (Op.getValueType().bitsLT(VT)) {
4987 Op = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, Op);
4988 AddToWorkList(Op.getNode());
4989 } else if (Op.getValueType().bitsGT(VT)) {
4990 Op = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
4991 AddToWorkList(Op.getNode());
4993 return DAG.getZeroExtendInReg(Op, SDLoc(N),
4994 N0.getValueType().getScalarType());
4997 // Fold (zext (and (trunc x), cst)) -> (and x, cst),
4998 // if either of the casts is not free.
4999 if (N0.getOpcode() == ISD::AND &&
5000 N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
5001 N0.getOperand(1).getOpcode() == ISD::Constant &&
5002 (!TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(),
5003 N0.getValueType()) ||
5004 !TLI.isZExtFree(N0.getValueType(), VT))) {
5005 SDValue X = N0.getOperand(0).getOperand(0);
5006 if (X.getValueType().bitsLT(VT)) {
5007 X = DAG.getNode(ISD::ANY_EXTEND, SDLoc(X), VT, X);
5008 } else if (X.getValueType().bitsGT(VT)) {
5009 X = DAG.getNode(ISD::TRUNCATE, SDLoc(X), VT, X);
5011 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
5012 Mask = Mask.zext(VT.getSizeInBits());
5013 return DAG.getNode(ISD::AND, SDLoc(N), VT,
5014 X, DAG.getConstant(Mask, VT));
5017 // fold (zext (load x)) -> (zext (truncate (zextload x)))
5018 // None of the supported targets knows how to perform load and vector_zext
5019 // on vectors in one instruction. We only perform this transformation on
5021 if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() &&
5022 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
5023 TLI.isLoadExtLegal(ISD::ZEXTLOAD, N0.getValueType()))) {
5024 bool DoXform = true;
5025 SmallVector<SDNode*, 4> SetCCs;
5026 if (!N0.hasOneUse())
5027 DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ZERO_EXTEND, SetCCs, TLI);
5029 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5030 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT,
5032 LN0->getBasePtr(), N0.getValueType(),
5033 LN0->getMemOperand());
5034 CombineTo(N, ExtLoad);
5035 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
5036 N0.getValueType(), ExtLoad);
5037 CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
5039 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
5041 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5045 // fold (zext (and/or/xor (load x), cst)) ->
5046 // (and/or/xor (zextload x), (zext cst))
5047 if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR ||
5048 N0.getOpcode() == ISD::XOR) &&
5049 isa<LoadSDNode>(N0.getOperand(0)) &&
5050 N0.getOperand(1).getOpcode() == ISD::Constant &&
5051 TLI.isLoadExtLegal(ISD::ZEXTLOAD, N0.getValueType()) &&
5052 (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) {
5053 LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0));
5054 if (LN0->getExtensionType() != ISD::SEXTLOAD) {
5055 bool DoXform = true;
5056 SmallVector<SDNode*, 4> SetCCs;
5057 if (!N0.hasOneUse())
5058 DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0), ISD::ZERO_EXTEND,
5061 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), VT,
5062 LN0->getChain(), LN0->getBasePtr(),
5064 LN0->getMemOperand());
5065 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
5066 Mask = Mask.zext(VT.getSizeInBits());
5067 SDValue And = DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
5068 ExtLoad, DAG.getConstant(Mask, VT));
5069 SDValue Trunc = DAG.getNode(ISD::TRUNCATE,
5070 SDLoc(N0.getOperand(0)),
5071 N0.getOperand(0).getValueType(), ExtLoad);
5073 CombineTo(N0.getOperand(0).getNode(), Trunc, ExtLoad.getValue(1));
5074 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
5076 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5081 // fold (zext (zextload x)) -> (zext (truncate (zextload x)))
5082 // fold (zext ( extload x)) -> (zext (truncate (zextload x)))
5083 if ((ISD::isZEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) &&
5084 ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) {
5085 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5086 EVT MemVT = LN0->getMemoryVT();
5087 if ((!LegalOperations && !LN0->isVolatile()) ||
5088 TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT)) {
5089 SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT,
5091 LN0->getBasePtr(), MemVT,
5092 LN0->getMemOperand());
5093 CombineTo(N, ExtLoad);
5094 CombineTo(N0.getNode(),
5095 DAG.getNode(ISD::TRUNCATE, SDLoc(N0), N0.getValueType(),
5097 ExtLoad.getValue(1));
5098 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5102 if (N0.getOpcode() == ISD::SETCC) {
5103 if (!LegalOperations && VT.isVector() &&
5104 N0.getValueType().getVectorElementType() == MVT::i1) {
5105 EVT N0VT = N0.getOperand(0).getValueType();
5106 if (getSetCCResultType(N0VT) == N0.getValueType())
5109 // zext(setcc) -> (and (vsetcc), (1, 1, ...) for vectors.
5110 // Only do this before legalize for now.
5111 EVT EltVT = VT.getVectorElementType();
5112 SmallVector<SDValue,8> OneOps(VT.getVectorNumElements(),
5113 DAG.getConstant(1, EltVT));
5114 if (VT.getSizeInBits() == N0VT.getSizeInBits())
5115 // We know that the # elements of the results is the same as the
5116 // # elements of the compare (and the # elements of the compare result
5117 // for that matter). Check to see that they are the same size. If so,
5118 // we know that the element size of the sext'd result matches the
5119 // element size of the compare operands.
5120 return DAG.getNode(ISD::AND, SDLoc(N), VT,
5121 DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
5123 cast<CondCodeSDNode>(N0.getOperand(2))->get()),
5124 DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT,
5125 &OneOps[0], OneOps.size()));
5127 // If the desired elements are smaller or larger than the source
5128 // elements we can use a matching integer vector type and then
5129 // truncate/sign extend
5130 EVT MatchingElementType =
5131 EVT::getIntegerVT(*DAG.getContext(),
5132 N0VT.getScalarType().getSizeInBits());
5133 EVT MatchingVectorType =
5134 EVT::getVectorVT(*DAG.getContext(), MatchingElementType,
5135 N0VT.getVectorNumElements());
5137 DAG.getSetCC(SDLoc(N), MatchingVectorType, N0.getOperand(0),
5139 cast<CondCodeSDNode>(N0.getOperand(2))->get());
5140 return DAG.getNode(ISD::AND, SDLoc(N), VT,
5141 DAG.getSExtOrTrunc(VsetCC, SDLoc(N), VT),
5142 DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT,
5143 &OneOps[0], OneOps.size()));
5146 // zext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
5148 SimplifySelectCC(SDLoc(N), N0.getOperand(0), N0.getOperand(1),
5149 DAG.getConstant(1, VT), DAG.getConstant(0, VT),
5150 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
5151 if (SCC.getNode()) return SCC;
5154 // (zext (shl (zext x), cst)) -> (shl (zext x), cst)
5155 if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL) &&
5156 isa<ConstantSDNode>(N0.getOperand(1)) &&
5157 N0.getOperand(0).getOpcode() == ISD::ZERO_EXTEND &&
5159 SDValue ShAmt = N0.getOperand(1);
5160 unsigned ShAmtVal = cast<ConstantSDNode>(ShAmt)->getZExtValue();
5161 if (N0.getOpcode() == ISD::SHL) {
5162 SDValue InnerZExt = N0.getOperand(0);
5163 // If the original shl may be shifting out bits, do not perform this
5165 unsigned KnownZeroBits = InnerZExt.getValueType().getSizeInBits() -
5166 InnerZExt.getOperand(0).getValueType().getSizeInBits();
5167 if (ShAmtVal > KnownZeroBits)
5173 // Ensure that the shift amount is wide enough for the shifted value.
5174 if (VT.getSizeInBits() >= 256)
5175 ShAmt = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, ShAmt);
5177 return DAG.getNode(N0.getOpcode(), DL, VT,
5178 DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0)),
5185 SDValue DAGCombiner::visitANY_EXTEND(SDNode *N) {
5186 SDValue N0 = N->getOperand(0);
5187 EVT VT = N->getValueType(0);
5189 // fold (aext c1) -> c1
5190 if (isa<ConstantSDNode>(N0))
5191 return DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, N0);
5192 // fold (aext (aext x)) -> (aext x)
5193 // fold (aext (zext x)) -> (zext x)
5194 // fold (aext (sext x)) -> (sext x)
5195 if (N0.getOpcode() == ISD::ANY_EXTEND ||
5196 N0.getOpcode() == ISD::ZERO_EXTEND ||
5197 N0.getOpcode() == ISD::SIGN_EXTEND)
5198 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, N0.getOperand(0));
5200 // fold (aext (truncate (load x))) -> (aext (smaller load x))
5201 // fold (aext (truncate (srl (load x), c))) -> (aext (small load (x+c/n)))
5202 if (N0.getOpcode() == ISD::TRUNCATE) {
5203 SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
5204 if (NarrowLoad.getNode()) {
5205 SDNode* oye = N0.getNode()->getOperand(0).getNode();
5206 if (NarrowLoad.getNode() != N0.getNode()) {
5207 CombineTo(N0.getNode(), NarrowLoad);
5208 // CombineTo deleted the truncate, if needed, but not what's under it.
5211 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5215 // fold (aext (truncate x))
5216 if (N0.getOpcode() == ISD::TRUNCATE) {
5217 SDValue TruncOp = N0.getOperand(0);
5218 if (TruncOp.getValueType() == VT)
5219 return TruncOp; // x iff x size == zext size.
5220 if (TruncOp.getValueType().bitsGT(VT))
5221 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, TruncOp);
5222 return DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, TruncOp);
5225 // Fold (aext (and (trunc x), cst)) -> (and x, cst)
5226 // if the trunc is not free.
5227 if (N0.getOpcode() == ISD::AND &&
5228 N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
5229 N0.getOperand(1).getOpcode() == ISD::Constant &&
5230 !TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(),
5231 N0.getValueType())) {
5232 SDValue X = N0.getOperand(0).getOperand(0);
5233 if (X.getValueType().bitsLT(VT)) {
5234 X = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, X);
5235 } else if (X.getValueType().bitsGT(VT)) {
5236 X = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, X);
5238 APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
5239 Mask = Mask.zext(VT.getSizeInBits());
5240 return DAG.getNode(ISD::AND, SDLoc(N), VT,
5241 X, DAG.getConstant(Mask, VT));
5244 // fold (aext (load x)) -> (aext (truncate (extload x)))
5245 // None of the supported targets knows how to perform load and any_ext
5246 // on vectors in one instruction. We only perform this transformation on
5248 if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() &&
5249 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
5250 TLI.isLoadExtLegal(ISD::EXTLOAD, N0.getValueType()))) {
5251 bool DoXform = true;
5252 SmallVector<SDNode*, 4> SetCCs;
5253 if (!N0.hasOneUse())
5254 DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ANY_EXTEND, SetCCs, TLI);
5256 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5257 SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT,
5259 LN0->getBasePtr(), N0.getValueType(),
5260 LN0->getMemOperand());
5261 CombineTo(N, ExtLoad);
5262 SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
5263 N0.getValueType(), ExtLoad);
5264 CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
5265 ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
5267 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5271 // fold (aext (zextload x)) -> (aext (truncate (zextload x)))
5272 // fold (aext (sextload x)) -> (aext (truncate (sextload x)))
5273 // fold (aext ( extload x)) -> (aext (truncate (extload x)))
5274 if (N0.getOpcode() == ISD::LOAD &&
5275 !ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
5277 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5278 EVT MemVT = LN0->getMemoryVT();
5279 SDValue ExtLoad = DAG.getExtLoad(LN0->getExtensionType(), SDLoc(N),
5280 VT, LN0->getChain(), LN0->getBasePtr(),
5281 MemVT, LN0->getMemOperand());
5282 CombineTo(N, ExtLoad);
5283 CombineTo(N0.getNode(),
5284 DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
5285 N0.getValueType(), ExtLoad),
5286 ExtLoad.getValue(1));
5287 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5290 if (N0.getOpcode() == ISD::SETCC) {
5291 // aext(setcc) -> sext_in_reg(vsetcc) for vectors.
5292 // Only do this before legalize for now.
5293 if (VT.isVector() && !LegalOperations) {
5294 EVT N0VT = N0.getOperand(0).getValueType();
5295 // We know that the # elements of the results is the same as the
5296 // # elements of the compare (and the # elements of the compare result
5297 // for that matter). Check to see that they are the same size. If so,
5298 // we know that the element size of the sext'd result matches the
5299 // element size of the compare operands.
5300 if (VT.getSizeInBits() == N0VT.getSizeInBits())
5301 return DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
5303 cast<CondCodeSDNode>(N0.getOperand(2))->get());
5304 // If the desired elements are smaller or larger than the source
5305 // elements we can use a matching integer vector type and then
5306 // truncate/sign extend
5308 EVT MatchingElementType =
5309 EVT::getIntegerVT(*DAG.getContext(),
5310 N0VT.getScalarType().getSizeInBits());
5311 EVT MatchingVectorType =
5312 EVT::getVectorVT(*DAG.getContext(), MatchingElementType,
5313 N0VT.getVectorNumElements());
5315 DAG.getSetCC(SDLoc(N), MatchingVectorType, N0.getOperand(0),
5317 cast<CondCodeSDNode>(N0.getOperand(2))->get());
5318 return DAG.getSExtOrTrunc(VsetCC, SDLoc(N), VT);
5322 // aext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
5324 SimplifySelectCC(SDLoc(N), N0.getOperand(0), N0.getOperand(1),
5325 DAG.getConstant(1, VT), DAG.getConstant(0, VT),
5326 cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
5334 /// GetDemandedBits - See if the specified operand can be simplified with the
5335 /// knowledge that only the bits specified by Mask are used. If so, return the
5336 /// simpler operand, otherwise return a null SDValue.
5337 SDValue DAGCombiner::GetDemandedBits(SDValue V, const APInt &Mask) {
5338 switch (V.getOpcode()) {
5340 case ISD::Constant: {
5341 const ConstantSDNode *CV = cast<ConstantSDNode>(V.getNode());
5342 assert(CV != 0 && "Const value should be ConstSDNode.");
5343 const APInt &CVal = CV->getAPIntValue();
5344 APInt NewVal = CVal & Mask;
5346 return DAG.getConstant(NewVal, V.getValueType());
5351 // If the LHS or RHS don't contribute bits to the or, drop them.
5352 if (DAG.MaskedValueIsZero(V.getOperand(0), Mask))
5353 return V.getOperand(1);
5354 if (DAG.MaskedValueIsZero(V.getOperand(1), Mask))
5355 return V.getOperand(0);
5358 // Only look at single-use SRLs.
5359 if (!V.getNode()->hasOneUse())
5361 if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(V.getOperand(1))) {
5362 // See if we can recursively simplify the LHS.
5363 unsigned Amt = RHSC->getZExtValue();
5365 // Watch out for shift count overflow though.
5366 if (Amt >= Mask.getBitWidth()) break;
5367 APInt NewMask = Mask << Amt;
5368 SDValue SimplifyLHS = GetDemandedBits(V.getOperand(0), NewMask);
5369 if (SimplifyLHS.getNode())
5370 return DAG.getNode(ISD::SRL, SDLoc(V), V.getValueType(),
5371 SimplifyLHS, V.getOperand(1));
5377 /// ReduceLoadWidth - If the result of a wider load is shifted to right of N
5378 /// bits and then truncated to a narrower type and where N is a multiple
5379 /// of number of bits of the narrower type, transform it to a narrower load
5380 /// from address + N / num of bits of new type. If the result is to be
5381 /// extended, also fold the extension to form a extending load.
5382 SDValue DAGCombiner::ReduceLoadWidth(SDNode *N) {
5383 unsigned Opc = N->getOpcode();
5385 ISD::LoadExtType ExtType = ISD::NON_EXTLOAD;
5386 SDValue N0 = N->getOperand(0);
5387 EVT VT = N->getValueType(0);
5390 // This transformation isn't valid for vector loads.
5394 // Special case: SIGN_EXTEND_INREG is basically truncating to ExtVT then
5396 if (Opc == ISD::SIGN_EXTEND_INREG) {
5397 ExtType = ISD::SEXTLOAD;
5398 ExtVT = cast<VTSDNode>(N->getOperand(1))->getVT();
5399 } else if (Opc == ISD::SRL) {
5400 // Another special-case: SRL is basically zero-extending a narrower value.
5401 ExtType = ISD::ZEXTLOAD;
5403 ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1));
5404 if (!N01) return SDValue();
5405 ExtVT = EVT::getIntegerVT(*DAG.getContext(),
5406 VT.getSizeInBits() - N01->getZExtValue());
5408 if (LegalOperations && !TLI.isLoadExtLegal(ExtType, ExtVT))
5411 unsigned EVTBits = ExtVT.getSizeInBits();
5413 // Do not generate loads of non-round integer types since these can
5414 // be expensive (and would be wrong if the type is not byte sized).
5415 if (!ExtVT.isRound())
5419 if (N0.getOpcode() == ISD::SRL && N0.hasOneUse()) {
5420 if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
5421 ShAmt = N01->getZExtValue();
5422 // Is the shift amount a multiple of size of VT?
5423 if ((ShAmt & (EVTBits-1)) == 0) {
5424 N0 = N0.getOperand(0);
5425 // Is the load width a multiple of size of VT?
5426 if ((N0.getValueType().getSizeInBits() & (EVTBits-1)) != 0)
5430 // At this point, we must have a load or else we can't do the transform.
5431 if (!isa<LoadSDNode>(N0)) return SDValue();
5433 // Because a SRL must be assumed to *need* to zero-extend the high bits
5434 // (as opposed to anyext the high bits), we can't combine the zextload
5435 // lowering of SRL and an sextload.
5436 if (cast<LoadSDNode>(N0)->getExtensionType() == ISD::SEXTLOAD)
5439 // If the shift amount is larger than the input type then we're not
5440 // accessing any of the loaded bytes. If the load was a zextload/extload
5441 // then the result of the shift+trunc is zero/undef (handled elsewhere).
5442 if (ShAmt >= cast<LoadSDNode>(N0)->getMemoryVT().getSizeInBits())
5447 // If the load is shifted left (and the result isn't shifted back right),
5448 // we can fold the truncate through the shift.
5449 unsigned ShLeftAmt = 0;
5450 if (ShAmt == 0 && N0.getOpcode() == ISD::SHL && N0.hasOneUse() &&
5451 ExtVT == VT && TLI.isNarrowingProfitable(N0.getValueType(), VT)) {
5452 if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
5453 ShLeftAmt = N01->getZExtValue();
5454 N0 = N0.getOperand(0);
5458 // If we haven't found a load, we can't narrow it. Don't transform one with
5459 // multiple uses, this would require adding a new load.
5460 if (!isa<LoadSDNode>(N0) || !N0.hasOneUse())
5463 // Don't change the width of a volatile load.
5464 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5465 if (LN0->isVolatile())
5468 // Verify that we are actually reducing a load width here.
5469 if (LN0->getMemoryVT().getSizeInBits() < EVTBits)
5472 // For the transform to be legal, the load must produce only two values
5473 // (the value loaded and the chain). Don't transform a pre-increment
5474 // load, for example, which produces an extra value. Otherwise the
5475 // transformation is not equivalent, and the downstream logic to replace
5476 // uses gets things wrong.
5477 if (LN0->getNumValues() > 2)
5480 // If the load that we're shrinking is an extload and we're not just
5481 // discarding the extension we can't simply shrink the load. Bail.
5482 // TODO: It would be possible to merge the extensions in some cases.
5483 if (LN0->getExtensionType() != ISD::NON_EXTLOAD &&
5484 LN0->getMemoryVT().getSizeInBits() < ExtVT.getSizeInBits() + ShAmt)
5487 EVT PtrType = N0.getOperand(1).getValueType();
5489 if (PtrType == MVT::Untyped || PtrType.isExtended())
5490 // It's not possible to generate a constant of extended or untyped type.
5493 // For big endian targets, we need to adjust the offset to the pointer to
5494 // load the correct bytes.
5495 if (TLI.isBigEndian()) {
5496 unsigned LVTStoreBits = LN0->getMemoryVT().getStoreSizeInBits();
5497 unsigned EVTStoreBits = ExtVT.getStoreSizeInBits();
5498 ShAmt = LVTStoreBits - EVTStoreBits - ShAmt;
5501 uint64_t PtrOff = ShAmt / 8;
5502 unsigned NewAlign = MinAlign(LN0->getAlignment(), PtrOff);
5503 SDValue NewPtr = DAG.getNode(ISD::ADD, SDLoc(LN0),
5504 PtrType, LN0->getBasePtr(),
5505 DAG.getConstant(PtrOff, PtrType));
5506 AddToWorkList(NewPtr.getNode());
5509 if (ExtType == ISD::NON_EXTLOAD)
5510 Load = DAG.getLoad(VT, SDLoc(N0), LN0->getChain(), NewPtr,
5511 LN0->getPointerInfo().getWithOffset(PtrOff),
5512 LN0->isVolatile(), LN0->isNonTemporal(),
5513 LN0->isInvariant(), NewAlign, LN0->getTBAAInfo());
5515 Load = DAG.getExtLoad(ExtType, SDLoc(N0), VT, LN0->getChain(),NewPtr,
5516 LN0->getPointerInfo().getWithOffset(PtrOff),
5517 ExtVT, LN0->isVolatile(), LN0->isNonTemporal(),
5518 NewAlign, LN0->getTBAAInfo());
5520 // Replace the old load's chain with the new load's chain.
5521 WorkListRemover DeadNodes(*this);
5522 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1));
5524 // Shift the result left, if we've swallowed a left shift.
5525 SDValue Result = Load;
5526 if (ShLeftAmt != 0) {
5527 EVT ShImmTy = getShiftAmountTy(Result.getValueType());
5528 if (!isUIntN(ShImmTy.getSizeInBits(), ShLeftAmt))
5530 // If the shift amount is as large as the result size (but, presumably,
5531 // no larger than the source) then the useful bits of the result are
5532 // zero; we can't simply return the shortened shift, because the result
5533 // of that operation is undefined.
5534 if (ShLeftAmt >= VT.getSizeInBits())
5535 Result = DAG.getConstant(0, VT);
5537 Result = DAG.getNode(ISD::SHL, SDLoc(N0), VT,
5538 Result, DAG.getConstant(ShLeftAmt, ShImmTy));
5541 // Return the new loaded value.
5545 SDValue DAGCombiner::visitSIGN_EXTEND_INREG(SDNode *N) {
5546 SDValue N0 = N->getOperand(0);
5547 SDValue N1 = N->getOperand(1);
5548 EVT VT = N->getValueType(0);
5549 EVT EVT = cast<VTSDNode>(N1)->getVT();
5550 unsigned VTBits = VT.getScalarType().getSizeInBits();
5551 unsigned EVTBits = EVT.getScalarType().getSizeInBits();
5553 // fold (sext_in_reg c1) -> c1
5554 if (isa<ConstantSDNode>(N0) || N0.getOpcode() == ISD::UNDEF)
5555 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, N0, N1);
5557 // If the input is already sign extended, just drop the extension.
5558 if (DAG.ComputeNumSignBits(N0) >= VTBits-EVTBits+1)
5561 // fold (sext_in_reg (sext_in_reg x, VT2), VT1) -> (sext_in_reg x, minVT) pt2
5562 if (N0.getOpcode() == ISD::SIGN_EXTEND_INREG &&
5563 EVT.bitsLT(cast<VTSDNode>(N0.getOperand(1))->getVT()))
5564 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
5565 N0.getOperand(0), N1);
5567 // fold (sext_in_reg (sext x)) -> (sext x)
5568 // fold (sext_in_reg (aext x)) -> (sext x)
5569 // if x is small enough.
5570 if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND) {
5571 SDValue N00 = N0.getOperand(0);
5572 if (N00.getValueType().getScalarType().getSizeInBits() <= EVTBits &&
5573 (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND, VT)))
5574 return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, N00, N1);
5577 // fold (sext_in_reg x) -> (zext_in_reg x) if the sign bit is known zero.
5578 if (DAG.MaskedValueIsZero(N0, APInt::getBitsSet(VTBits, EVTBits-1, EVTBits)))
5579 return DAG.getZeroExtendInReg(N0, SDLoc(N), EVT);
5581 // fold operands of sext_in_reg based on knowledge that the top bits are not
5583 if (SimplifyDemandedBits(SDValue(N, 0)))
5584 return SDValue(N, 0);
5586 // fold (sext_in_reg (load x)) -> (smaller sextload x)
5587 // fold (sext_in_reg (srl (load x), c)) -> (smaller sextload (x+c/evtbits))
5588 SDValue NarrowLoad = ReduceLoadWidth(N);
5589 if (NarrowLoad.getNode())
5592 // fold (sext_in_reg (srl X, 24), i8) -> (sra X, 24)
5593 // fold (sext_in_reg (srl X, 23), i8) -> (sra X, 23) iff possible.
5594 // We already fold "(sext_in_reg (srl X, 25), i8) -> srl X, 25" above.
5595 if (N0.getOpcode() == ISD::SRL) {
5596 if (ConstantSDNode *ShAmt = dyn_cast<ConstantSDNode>(N0.getOperand(1)))
5597 if (ShAmt->getZExtValue()+EVTBits <= VTBits) {
5598 // We can turn this into an SRA iff the input to the SRL is already sign
5600 unsigned InSignBits = DAG.ComputeNumSignBits(N0.getOperand(0));
5601 if (VTBits-(ShAmt->getZExtValue()+EVTBits) < InSignBits)
5602 return DAG.getNode(ISD::SRA, SDLoc(N), VT,
5603 N0.getOperand(0), N0.getOperand(1));
5607 // fold (sext_inreg (extload x)) -> (sextload x)
5608 if (ISD::isEXTLoad(N0.getNode()) &&
5609 ISD::isUNINDEXEDLoad(N0.getNode()) &&
5610 EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
5611 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
5612 TLI.isLoadExtLegal(ISD::SEXTLOAD, EVT))) {
5613 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5614 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
5616 LN0->getBasePtr(), EVT,
5617 LN0->getMemOperand());
5618 CombineTo(N, ExtLoad);
5619 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
5620 AddToWorkList(ExtLoad.getNode());
5621 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5623 // fold (sext_inreg (zextload x)) -> (sextload x) iff load has one use
5624 if (ISD::isZEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
5626 EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
5627 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
5628 TLI.isLoadExtLegal(ISD::SEXTLOAD, EVT))) {
5629 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5630 SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
5632 LN0->getBasePtr(), EVT,
5633 LN0->getMemOperand());
5634 CombineTo(N, ExtLoad);
5635 CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
5636 return SDValue(N, 0); // Return N so it doesn't get rechecked!
5639 // Form (sext_inreg (bswap >> 16)) or (sext_inreg (rotl (bswap) 16))
5640 if (EVTBits <= 16 && N0.getOpcode() == ISD::OR) {
5641 SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0),
5642 N0.getOperand(1), false);
5643 if (BSwap.getNode() != 0)
5644 return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
5648 // Fold a sext_inreg of a build_vector of ConstantSDNodes or undefs
5649 // into a build_vector.
5650 if (ISD::isBuildVectorOfConstantSDNodes(N0.getNode())) {
5651 SmallVector<SDValue, 8> Elts;
5652 unsigned NumElts = N0->getNumOperands();
5653 unsigned ShAmt = VTBits - EVTBits;
5655 for (unsigned i = 0; i != NumElts; ++i) {
5656 SDValue Op = N0->getOperand(i);
5657 if (Op->getOpcode() == ISD::UNDEF) {
5662 ConstantSDNode *CurrentND = cast<ConstantSDNode>(Op);
5663 const APInt &C = APInt(VTBits, CurrentND->getAPIntValue().getZExtValue());
5664 Elts.push_back(DAG.getConstant(C.shl(ShAmt).ashr(ShAmt).getZExtValue(),
5665 Op.getValueType()));
5668 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, &Elts[0], NumElts);
5674 SDValue DAGCombiner::visitTRUNCATE(SDNode *N) {
5675 SDValue N0 = N->getOperand(0);
5676 EVT VT = N->getValueType(0);
5677 bool isLE = TLI.isLittleEndian();
5680 if (N0.getValueType() == N->getValueType(0))
5682 // fold (truncate c1) -> c1
5683 if (isa<ConstantSDNode>(N0))
5684 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0);
5685 // fold (truncate (truncate x)) -> (truncate x)
5686 if (N0.getOpcode() == ISD::TRUNCATE)
5687 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0));
5688 // fold (truncate (ext x)) -> (ext x) or (truncate x) or x
5689 if (N0.getOpcode() == ISD::ZERO_EXTEND ||
5690 N0.getOpcode() == ISD::SIGN_EXTEND ||
5691 N0.getOpcode() == ISD::ANY_EXTEND) {
5692 if (N0.getOperand(0).getValueType().bitsLT(VT))
5693 // if the source is smaller than the dest, we still need an extend
5694 return DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
5696 if (N0.getOperand(0).getValueType().bitsGT(VT))
5697 // if the source is larger than the dest, than we just need the truncate
5698 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0));
5699 // if the source and dest are the same type, we can drop both the extend
5700 // and the truncate.
5701 return N0.getOperand(0);
5704 // Fold extract-and-trunc into a narrow extract. For example:
5705 // i64 x = EXTRACT_VECTOR_ELT(v2i64 val, i32 1)
5706 // i32 y = TRUNCATE(i64 x)
5708 // v16i8 b = BITCAST (v2i64 val)
5709 // i8 x = EXTRACT_VECTOR_ELT(v16i8 b, i32 8)
5711 // Note: We only run this optimization after type legalization (which often
5712 // creates this pattern) and before operation legalization after which
5713 // we need to be more careful about the vector instructions that we generate.
5714 if (N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
5715 LegalTypes && !LegalOperations && N0->hasOneUse()) {
5717 EVT VecTy = N0.getOperand(0).getValueType();
5718 EVT ExTy = N0.getValueType();
5719 EVT TrTy = N->getValueType(0);
5721 unsigned NumElem = VecTy.getVectorNumElements();
5722 unsigned SizeRatio = ExTy.getSizeInBits()/TrTy.getSizeInBits();
5724 EVT NVT = EVT::getVectorVT(*DAG.getContext(), TrTy, SizeRatio * NumElem);
5725 assert(NVT.getSizeInBits() == VecTy.getSizeInBits() && "Invalid Size");
5727 SDValue EltNo = N0->getOperand(1);
5728 if (isa<ConstantSDNode>(EltNo) && isTypeLegal(NVT)) {
5729 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
5730 EVT IndexTy = TLI.getVectorIdxTy();
5731 int Index = isLE ? (Elt*SizeRatio) : (Elt*SizeRatio + (SizeRatio-1));
5733 SDValue V = DAG.getNode(ISD::BITCAST, SDLoc(N),
5734 NVT, N0.getOperand(0));
5736 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT,
5738 DAG.getConstant(Index, IndexTy));
5742 // Fold a series of buildvector, bitcast, and truncate if possible.
5744 // (2xi32 trunc (bitcast ((4xi32)buildvector x, x, y, y) 2xi64)) to
5745 // (2xi32 (buildvector x, y)).
5746 if (Level == AfterLegalizeVectorOps && VT.isVector() &&
5747 N0.getOpcode() == ISD::BITCAST && N0.hasOneUse() &&
5748 N0.getOperand(0).getOpcode() == ISD::BUILD_VECTOR &&
5749 N0.getOperand(0).hasOneUse()) {
5751 SDValue BuildVect = N0.getOperand(0);
5752 EVT BuildVectEltTy = BuildVect.getValueType().getVectorElementType();
5753 EVT TruncVecEltTy = VT.getVectorElementType();
5755 // Check that the element types match.
5756 if (BuildVectEltTy == TruncVecEltTy) {
5757 // Now we only need to compute the offset of the truncated elements.
5758 unsigned BuildVecNumElts = BuildVect.getNumOperands();
5759 unsigned TruncVecNumElts = VT.getVectorNumElements();
5760 unsigned TruncEltOffset = BuildVecNumElts / TruncVecNumElts;
5762 assert((BuildVecNumElts % TruncVecNumElts) == 0 &&
5763 "Invalid number of elements");
5765 SmallVector<SDValue, 8> Opnds;
5766 for (unsigned i = 0, e = BuildVecNumElts; i != e; i += TruncEltOffset)
5767 Opnds.push_back(BuildVect.getOperand(i));
5769 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, &Opnds[0],
5774 // See if we can simplify the input to this truncate through knowledge that
5775 // only the low bits are being used.
5776 // For example "trunc (or (shl x, 8), y)" // -> trunc y
5777 // Currently we only perform this optimization on scalars because vectors
5778 // may have different active low bits.
5779 if (!VT.isVector()) {
5781 GetDemandedBits(N0, APInt::getLowBitsSet(N0.getValueSizeInBits(),
5782 VT.getSizeInBits()));
5783 if (Shorter.getNode())
5784 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Shorter);
5786 // fold (truncate (load x)) -> (smaller load x)
5787 // fold (truncate (srl (load x), c)) -> (smaller load (x+c/evtbits))
5788 if (!LegalTypes || TLI.isTypeDesirableForOp(N0.getOpcode(), VT)) {
5789 SDValue Reduced = ReduceLoadWidth(N);
5790 if (Reduced.getNode())
5792 // Handle the case where the load remains an extending load even
5793 // after truncation.
5794 if (N0.hasOneUse() && ISD::isUNINDEXEDLoad(N0.getNode())) {
5795 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5796 if (!LN0->isVolatile() &&
5797 LN0->getMemoryVT().getStoreSizeInBits() < VT.getSizeInBits()) {
5798 SDValue NewLoad = DAG.getExtLoad(LN0->getExtensionType(), SDLoc(LN0),
5799 VT, LN0->getChain(), LN0->getBasePtr(),
5801 LN0->getMemOperand());
5802 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLoad.getValue(1));
5807 // fold (trunc (concat ... x ...)) -> (concat ..., (trunc x), ...)),
5808 // where ... are all 'undef'.
5809 if (N0.getOpcode() == ISD::CONCAT_VECTORS && !LegalTypes) {
5810 SmallVector<EVT, 8> VTs;
5813 unsigned NumDefs = 0;
5815 for (unsigned i = 0, e = N0.getNumOperands(); i != e; ++i) {
5816 SDValue X = N0.getOperand(i);
5817 if (X.getOpcode() != ISD::UNDEF) {
5822 // Stop if more than one members are non-undef.
5825 VTs.push_back(EVT::getVectorVT(*DAG.getContext(),
5826 VT.getVectorElementType(),
5827 X.getValueType().getVectorNumElements()));
5831 return DAG.getUNDEF(VT);
5834 assert(V.getNode() && "The single defined operand is empty!");
5835 SmallVector<SDValue, 8> Opnds;
5836 for (unsigned i = 0, e = VTs.size(); i != e; ++i) {
5838 Opnds.push_back(DAG.getUNDEF(VTs[i]));
5841 SDValue NV = DAG.getNode(ISD::TRUNCATE, SDLoc(V), VTs[i], V);
5842 AddToWorkList(NV.getNode());
5843 Opnds.push_back(NV);
5845 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
5846 &Opnds[0], Opnds.size());
5850 // Simplify the operands using demanded-bits information.
5851 if (!VT.isVector() &&
5852 SimplifyDemandedBits(SDValue(N, 0)))
5853 return SDValue(N, 0);
5858 static SDNode *getBuildPairElt(SDNode *N, unsigned i) {
5859 SDValue Elt = N->getOperand(i);
5860 if (Elt.getOpcode() != ISD::MERGE_VALUES)
5861 return Elt.getNode();
5862 return Elt.getOperand(Elt.getResNo()).getNode();
5865 /// CombineConsecutiveLoads - build_pair (load, load) -> load
5866 /// if load locations are consecutive.
5867 SDValue DAGCombiner::CombineConsecutiveLoads(SDNode *N, EVT VT) {
5868 assert(N->getOpcode() == ISD::BUILD_PAIR);
5870 LoadSDNode *LD1 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 0));
5871 LoadSDNode *LD2 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 1));
5872 if (!LD1 || !LD2 || !ISD::isNON_EXTLoad(LD1) || !LD1->hasOneUse() ||
5873 LD1->getPointerInfo().getAddrSpace() !=
5874 LD2->getPointerInfo().getAddrSpace())
5876 EVT LD1VT = LD1->getValueType(0);
5878 if (ISD::isNON_EXTLoad(LD2) &&
5880 // If both are volatile this would reduce the number of volatile loads.
5881 // If one is volatile it might be ok, but play conservative and bail out.
5882 !LD1->isVolatile() &&
5883 !LD2->isVolatile() &&
5884 DAG.isConsecutiveLoad(LD2, LD1, LD1VT.getSizeInBits()/8, 1)) {
5885 unsigned Align = LD1->getAlignment();
5886 unsigned NewAlign = TLI.getDataLayout()->
5887 getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
5889 if (NewAlign <= Align &&
5890 (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT)))
5891 return DAG.getLoad(VT, SDLoc(N), LD1->getChain(),
5892 LD1->getBasePtr(), LD1->getPointerInfo(),
5893 false, false, false, Align);
5899 SDValue DAGCombiner::visitBITCAST(SDNode *N) {
5900 SDValue N0 = N->getOperand(0);
5901 EVT VT = N->getValueType(0);
5903 // If the input is a BUILD_VECTOR with all constant elements, fold this now.
5904 // Only do this before legalize, since afterward the target may be depending
5905 // on the bitconvert.
5906 // First check to see if this is all constant.
5908 N0.getOpcode() == ISD::BUILD_VECTOR && N0.getNode()->hasOneUse() &&
5910 bool isSimple = cast<BuildVectorSDNode>(N0)->isConstant();
5912 EVT DestEltVT = N->getValueType(0).getVectorElementType();
5913 assert(!DestEltVT.isVector() &&
5914 "Element type of vector ValueType must not be vector!");
5916 return ConstantFoldBITCASTofBUILD_VECTOR(N0.getNode(), DestEltVT);
5919 // If the input is a constant, let getNode fold it.
5920 if (isa<ConstantSDNode>(N0) || isa<ConstantFPSDNode>(N0)) {
5921 SDValue Res = DAG.getNode(ISD::BITCAST, SDLoc(N), VT, N0);
5922 if (Res.getNode() != N) {
5923 if (!LegalOperations ||
5924 TLI.isOperationLegal(Res.getNode()->getOpcode(), VT))
5927 // Folding it resulted in an illegal node, and it's too late to
5928 // do that. Clean up the old node and forego the transformation.
5929 // Ideally this won't happen very often, because instcombine
5930 // and the earlier dagcombine runs (where illegal nodes are
5931 // permitted) should have folded most of them already.
5932 DAG.DeleteNode(Res.getNode());
5936 // (conv (conv x, t1), t2) -> (conv x, t2)
5937 if (N0.getOpcode() == ISD::BITCAST)
5938 return DAG.getNode(ISD::BITCAST, SDLoc(N), VT,
5941 // fold (conv (load x)) -> (load (conv*)x)
5942 // If the resultant load doesn't need a higher alignment than the original!
5943 if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
5944 // Do not change the width of a volatile load.
5945 !cast<LoadSDNode>(N0)->isVolatile() &&
5946 (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT)) &&
5947 TLI.isLoadBitCastBeneficial(N0.getValueType(), VT)) {
5948 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5949 unsigned Align = TLI.getDataLayout()->
5950 getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
5951 unsigned OrigAlign = LN0->getAlignment();
5953 if (Align <= OrigAlign) {
5954 SDValue Load = DAG.getLoad(VT, SDLoc(N), LN0->getChain(),
5955 LN0->getBasePtr(), LN0->getPointerInfo(),
5956 LN0->isVolatile(), LN0->isNonTemporal(),
5957 LN0->isInvariant(), OrigAlign,
5958 LN0->getTBAAInfo());
5960 CombineTo(N0.getNode(),
5961 DAG.getNode(ISD::BITCAST, SDLoc(N0),
5962 N0.getValueType(), Load),
5968 // fold (bitconvert (fneg x)) -> (xor (bitconvert x), signbit)
5969 // fold (bitconvert (fabs x)) -> (and (bitconvert x), (not signbit))
5970 // This often reduces constant pool loads.
5971 if (((N0.getOpcode() == ISD::FNEG && !TLI.isFNegFree(N0.getValueType())) ||
5972 (N0.getOpcode() == ISD::FABS && !TLI.isFAbsFree(N0.getValueType()))) &&
5973 N0.getNode()->hasOneUse() && VT.isInteger() &&
5974 !VT.isVector() && !N0.getValueType().isVector()) {
5975 SDValue NewConv = DAG.getNode(ISD::BITCAST, SDLoc(N0), VT,
5977 AddToWorkList(NewConv.getNode());
5979 APInt SignBit = APInt::getSignBit(VT.getSizeInBits());
5980 if (N0.getOpcode() == ISD::FNEG)
5981 return DAG.getNode(ISD::XOR, SDLoc(N), VT,
5982 NewConv, DAG.getConstant(SignBit, VT));
5983 assert(N0.getOpcode() == ISD::FABS);
5984 return DAG.getNode(ISD::AND, SDLoc(N), VT,
5985 NewConv, DAG.getConstant(~SignBit, VT));
5988 // fold (bitconvert (fcopysign cst, x)) ->
5989 // (or (and (bitconvert x), sign), (and cst, (not sign)))
5990 // Note that we don't handle (copysign x, cst) because this can always be
5991 // folded to an fneg or fabs.
5992 if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse() &&
5993 isa<ConstantFPSDNode>(N0.getOperand(0)) &&
5994 VT.isInteger() && !VT.isVector()) {
5995 unsigned OrigXWidth = N0.getOperand(1).getValueType().getSizeInBits();
5996 EVT IntXVT = EVT::getIntegerVT(*DAG.getContext(), OrigXWidth);
5997 if (isTypeLegal(IntXVT)) {
5998 SDValue X = DAG.getNode(ISD::BITCAST, SDLoc(N0),
5999 IntXVT, N0.getOperand(1));
6000 AddToWorkList(X.getNode());
6002 // If X has a different width than the result/lhs, sext it or truncate it.
6003 unsigned VTWidth = VT.getSizeInBits();
6004 if (OrigXWidth < VTWidth) {
6005 X = DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, X);
6006 AddToWorkList(X.getNode());
6007 } else if (OrigXWidth > VTWidth) {
6008 // To get the sign bit in the right place, we have to shift it right
6009 // before truncating.
6010 X = DAG.getNode(ISD::SRL, SDLoc(X),
6011 X.getValueType(), X,
6012 DAG.getConstant(OrigXWidth-VTWidth, X.getValueType()));
6013 AddToWorkList(X.getNode());
6014 X = DAG.getNode(ISD::TRUNCATE, SDLoc(X), VT, X);
6015 AddToWorkList(X.getNode());
6018 APInt SignBit = APInt::getSignBit(VT.getSizeInBits());
6019 X = DAG.getNode(ISD::AND, SDLoc(X), VT,
6020 X, DAG.getConstant(SignBit, VT));
6021 AddToWorkList(X.getNode());
6023 SDValue Cst = DAG.getNode(ISD::BITCAST, SDLoc(N0),
6024 VT, N0.getOperand(0));
6025 Cst = DAG.getNode(ISD::AND, SDLoc(Cst), VT,
6026 Cst, DAG.getConstant(~SignBit, VT));
6027 AddToWorkList(Cst.getNode());
6029 return DAG.getNode(ISD::OR, SDLoc(N), VT, X, Cst);
6033 // bitconvert(build_pair(ld, ld)) -> ld iff load locations are consecutive.
6034 if (N0.getOpcode() == ISD::BUILD_PAIR) {
6035 SDValue CombineLD = CombineConsecutiveLoads(N0.getNode(), VT);
6036 if (CombineLD.getNode())
6043 SDValue DAGCombiner::visitBUILD_PAIR(SDNode *N) {
6044 EVT VT = N->getValueType(0);
6045 return CombineConsecutiveLoads(N, VT);
6048 /// ConstantFoldBITCASTofBUILD_VECTOR - We know that BV is a build_vector
6049 /// node with Constant, ConstantFP or Undef operands. DstEltVT indicates the
6050 /// destination element value type.
6051 SDValue DAGCombiner::
6052 ConstantFoldBITCASTofBUILD_VECTOR(SDNode *BV, EVT DstEltVT) {
6053 EVT SrcEltVT = BV->getValueType(0).getVectorElementType();
6055 // If this is already the right type, we're done.
6056 if (SrcEltVT == DstEltVT) return SDValue(BV, 0);
6058 unsigned SrcBitSize = SrcEltVT.getSizeInBits();
6059 unsigned DstBitSize = DstEltVT.getSizeInBits();
6061 // If this is a conversion of N elements of one type to N elements of another
6062 // type, convert each element. This handles FP<->INT cases.
6063 if (SrcBitSize == DstBitSize) {
6064 EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT,
6065 BV->getValueType(0).getVectorNumElements());
6067 // Due to the FP element handling below calling this routine recursively,
6068 // we can end up with a scalar-to-vector node here.
6069 if (BV->getOpcode() == ISD::SCALAR_TO_VECTOR)
6070 return DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(BV), VT,
6071 DAG.getNode(ISD::BITCAST, SDLoc(BV),
6072 DstEltVT, BV->getOperand(0)));
6074 SmallVector<SDValue, 8> Ops;
6075 for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) {
6076 SDValue Op = BV->getOperand(i);
6077 // If the vector element type is not legal, the BUILD_VECTOR operands
6078 // are promoted and implicitly truncated. Make that explicit here.
6079 if (Op.getValueType() != SrcEltVT)
6080 Op = DAG.getNode(ISD::TRUNCATE, SDLoc(BV), SrcEltVT, Op);
6081 Ops.push_back(DAG.getNode(ISD::BITCAST, SDLoc(BV),
6083 AddToWorkList(Ops.back().getNode());
6085 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(BV), VT,
6086 &Ops[0], Ops.size());
6089 // Otherwise, we're growing or shrinking the elements. To avoid having to
6090 // handle annoying details of growing/shrinking FP values, we convert them to
6092 if (SrcEltVT.isFloatingPoint()) {
6093 // Convert the input float vector to a int vector where the elements are the
6095 assert((SrcEltVT == MVT::f32 || SrcEltVT == MVT::f64) && "Unknown FP VT!");
6096 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), SrcEltVT.getSizeInBits());
6097 BV = ConstantFoldBITCASTofBUILD_VECTOR(BV, IntVT).getNode();
6101 // Now we know the input is an integer vector. If the output is a FP type,
6102 // convert to integer first, then to FP of the right size.
6103 if (DstEltVT.isFloatingPoint()) {
6104 assert((DstEltVT == MVT::f32 || DstEltVT == MVT::f64) && "Unknown FP VT!");
6105 EVT TmpVT = EVT::getIntegerVT(*DAG.getContext(), DstEltVT.getSizeInBits());
6106 SDNode *Tmp = ConstantFoldBITCASTofBUILD_VECTOR(BV, TmpVT).getNode();
6108 // Next, convert to FP elements of the same size.
6109 return ConstantFoldBITCASTofBUILD_VECTOR(Tmp, DstEltVT);
6112 // Okay, we know the src/dst types are both integers of differing types.
6113 // Handling growing first.
6114 assert(SrcEltVT.isInteger() && DstEltVT.isInteger());
6115 if (SrcBitSize < DstBitSize) {
6116 unsigned NumInputsPerOutput = DstBitSize/SrcBitSize;
6118 SmallVector<SDValue, 8> Ops;
6119 for (unsigned i = 0, e = BV->getNumOperands(); i != e;
6120 i += NumInputsPerOutput) {
6121 bool isLE = TLI.isLittleEndian();
6122 APInt NewBits = APInt(DstBitSize, 0);
6123 bool EltIsUndef = true;
6124 for (unsigned j = 0; j != NumInputsPerOutput; ++j) {
6125 // Shift the previously computed bits over.
6126 NewBits <<= SrcBitSize;
6127 SDValue Op = BV->getOperand(i+ (isLE ? (NumInputsPerOutput-j-1) : j));
6128 if (Op.getOpcode() == ISD::UNDEF) continue;
6131 NewBits |= cast<ConstantSDNode>(Op)->getAPIntValue().
6132 zextOrTrunc(SrcBitSize).zext(DstBitSize);
6136 Ops.push_back(DAG.getUNDEF(DstEltVT));
6138 Ops.push_back(DAG.getConstant(NewBits, DstEltVT));
6141 EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT, Ops.size());
6142 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(BV), VT,
6143 &Ops[0], Ops.size());
6146 // Finally, this must be the case where we are shrinking elements: each input
6147 // turns into multiple outputs.
6148 bool isS2V = ISD::isScalarToVector(BV);
6149 unsigned NumOutputsPerInput = SrcBitSize/DstBitSize;
6150 EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT,
6151 NumOutputsPerInput*BV->getNumOperands());
6152 SmallVector<SDValue, 8> Ops;
6154 for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) {
6155 if (BV->getOperand(i).getOpcode() == ISD::UNDEF) {
6156 for (unsigned j = 0; j != NumOutputsPerInput; ++j)
6157 Ops.push_back(DAG.getUNDEF(DstEltVT));
6161 APInt OpVal = cast<ConstantSDNode>(BV->getOperand(i))->
6162 getAPIntValue().zextOrTrunc(SrcBitSize);
6164 for (unsigned j = 0; j != NumOutputsPerInput; ++j) {
6165 APInt ThisVal = OpVal.trunc(DstBitSize);
6166 Ops.push_back(DAG.getConstant(ThisVal, DstEltVT));
6167 if (isS2V && i == 0 && j == 0 && ThisVal.zext(SrcBitSize) == OpVal)
6168 // Simply turn this into a SCALAR_TO_VECTOR of the new type.
6169 return DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(BV), VT,
6171 OpVal = OpVal.lshr(DstBitSize);
6174 // For big endian targets, swap the order of the pieces of each element.
6175 if (TLI.isBigEndian())
6176 std::reverse(Ops.end()-NumOutputsPerInput, Ops.end());
6179 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(BV), VT,
6180 &Ops[0], Ops.size());
6183 SDValue DAGCombiner::visitFADD(SDNode *N) {
6184 SDValue N0 = N->getOperand(0);
6185 SDValue N1 = N->getOperand(1);
6186 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6187 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6188 EVT VT = N->getValueType(0);
6191 if (VT.isVector()) {
6192 SDValue FoldedVOp = SimplifyVBinOp(N);
6193 if (FoldedVOp.getNode()) return FoldedVOp;
6196 // fold (fadd c1, c2) -> c1 + c2
6198 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N1);
6199 // canonicalize constant to RHS
6200 if (N0CFP && !N1CFP)
6201 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N1, N0);
6202 // fold (fadd A, 0) -> A
6203 if (DAG.getTarget().Options.UnsafeFPMath && N1CFP &&
6204 N1CFP->getValueAPF().isZero())
6206 // fold (fadd A, (fneg B)) -> (fsub A, B)
6207 if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) &&
6208 isNegatibleForFree(N1, LegalOperations, TLI, &DAG.getTarget().Options) == 2)
6209 return DAG.getNode(ISD::FSUB, SDLoc(N), VT, N0,
6210 GetNegatedExpression(N1, DAG, LegalOperations));
6211 // fold (fadd (fneg A), B) -> (fsub B, A)
6212 if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) &&
6213 isNegatibleForFree(N0, LegalOperations, TLI, &DAG.getTarget().Options) == 2)
6214 return DAG.getNode(ISD::FSUB, SDLoc(N), VT, N1,
6215 GetNegatedExpression(N0, DAG, LegalOperations));
6217 // If allowed, fold (fadd (fadd x, c1), c2) -> (fadd x, (fadd c1, c2))
6218 if (DAG.getTarget().Options.UnsafeFPMath && N1CFP &&
6219 N0.getOpcode() == ISD::FADD && N0.getNode()->hasOneUse() &&
6220 isa<ConstantFPSDNode>(N0.getOperand(1)))
6221 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0.getOperand(0),
6222 DAG.getNode(ISD::FADD, SDLoc(N), VT,
6223 N0.getOperand(1), N1));
6225 // No FP constant should be created after legalization as Instruction
6226 // Selection pass has hard time in dealing with FP constant.
6228 // We don't need test this condition for transformation like following, as
6229 // the DAG being transformed implies it is legal to take FP constant as
6232 // (fadd (fmul c, x), x) -> (fmul c+1, x)
6234 bool AllowNewFpConst = (Level < AfterLegalizeDAG);
6236 // If allow, fold (fadd (fneg x), x) -> 0.0
6237 if (AllowNewFpConst && DAG.getTarget().Options.UnsafeFPMath &&
6238 N0.getOpcode() == ISD::FNEG && N0.getOperand(0) == N1)
6239 return DAG.getConstantFP(0.0, VT);
6241 // If allow, fold (fadd x, (fneg x)) -> 0.0
6242 if (AllowNewFpConst && DAG.getTarget().Options.UnsafeFPMath &&
6243 N1.getOpcode() == ISD::FNEG && N1.getOperand(0) == N0)
6244 return DAG.getConstantFP(0.0, VT);
6246 // In unsafe math mode, we can fold chains of FADD's of the same value
6247 // into multiplications. This transform is not safe in general because
6248 // we are reducing the number of rounding steps.
6249 if (DAG.getTarget().Options.UnsafeFPMath &&
6250 TLI.isOperationLegalOrCustom(ISD::FMUL, VT) &&
6252 if (N0.getOpcode() == ISD::FMUL) {
6253 ConstantFPSDNode *CFP00 = dyn_cast<ConstantFPSDNode>(N0.getOperand(0));
6254 ConstantFPSDNode *CFP01 = dyn_cast<ConstantFPSDNode>(N0.getOperand(1));
6256 // (fadd (fmul c, x), x) -> (fmul x, c+1)
6257 if (CFP00 && !CFP01 && N0.getOperand(1) == N1) {
6258 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6260 DAG.getConstantFP(1.0, VT));
6261 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6265 // (fadd (fmul x, c), x) -> (fmul x, c+1)
6266 if (CFP01 && !CFP00 && N0.getOperand(0) == N1) {
6267 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6269 DAG.getConstantFP(1.0, VT));
6270 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6274 // (fadd (fmul c, x), (fadd x, x)) -> (fmul x, c+2)
6275 if (CFP00 && !CFP01 && N1.getOpcode() == ISD::FADD &&
6276 N1.getOperand(0) == N1.getOperand(1) &&
6277 N0.getOperand(1) == N1.getOperand(0)) {
6278 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6280 DAG.getConstantFP(2.0, VT));
6281 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6282 N0.getOperand(1), NewCFP);
6285 // (fadd (fmul x, c), (fadd x, x)) -> (fmul x, c+2)
6286 if (CFP01 && !CFP00 && N1.getOpcode() == ISD::FADD &&
6287 N1.getOperand(0) == N1.getOperand(1) &&
6288 N0.getOperand(0) == N1.getOperand(0)) {
6289 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6291 DAG.getConstantFP(2.0, VT));
6292 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6293 N0.getOperand(0), NewCFP);
6297 if (N1.getOpcode() == ISD::FMUL) {
6298 ConstantFPSDNode *CFP10 = dyn_cast<ConstantFPSDNode>(N1.getOperand(0));
6299 ConstantFPSDNode *CFP11 = dyn_cast<ConstantFPSDNode>(N1.getOperand(1));
6301 // (fadd x, (fmul c, x)) -> (fmul x, c+1)
6302 if (CFP10 && !CFP11 && N1.getOperand(1) == N0) {
6303 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6305 DAG.getConstantFP(1.0, VT));
6306 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6310 // (fadd x, (fmul x, c)) -> (fmul x, c+1)
6311 if (CFP11 && !CFP10 && N1.getOperand(0) == N0) {
6312 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6314 DAG.getConstantFP(1.0, VT));
6315 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6320 // (fadd (fadd x, x), (fmul c, x)) -> (fmul x, c+2)
6321 if (CFP10 && !CFP11 && N0.getOpcode() == ISD::FADD &&
6322 N0.getOperand(0) == N0.getOperand(1) &&
6323 N1.getOperand(1) == N0.getOperand(0)) {
6324 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6326 DAG.getConstantFP(2.0, VT));
6327 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6328 N1.getOperand(1), NewCFP);
6331 // (fadd (fadd x, x), (fmul x, c)) -> (fmul x, c+2)
6332 if (CFP11 && !CFP10 && N0.getOpcode() == ISD::FADD &&
6333 N0.getOperand(0) == N0.getOperand(1) &&
6334 N1.getOperand(0) == N0.getOperand(0)) {
6335 SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6337 DAG.getConstantFP(2.0, VT));
6338 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6339 N1.getOperand(0), NewCFP);
6343 if (N0.getOpcode() == ISD::FADD && AllowNewFpConst) {
6344 ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N0.getOperand(0));
6345 // (fadd (fadd x, x), x) -> (fmul x, 3.0)
6346 if (!CFP && N0.getOperand(0) == N0.getOperand(1) &&
6347 (N0.getOperand(0) == N1))
6348 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6349 N1, DAG.getConstantFP(3.0, VT));
6352 if (N1.getOpcode() == ISD::FADD && AllowNewFpConst) {
6353 ConstantFPSDNode *CFP10 = dyn_cast<ConstantFPSDNode>(N1.getOperand(0));
6354 // (fadd x, (fadd x, x)) -> (fmul x, 3.0)
6355 if (!CFP10 && N1.getOperand(0) == N1.getOperand(1) &&
6356 N1.getOperand(0) == N0)
6357 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6358 N0, DAG.getConstantFP(3.0, VT));
6361 // (fadd (fadd x, x), (fadd x, x)) -> (fmul x, 4.0)
6362 if (AllowNewFpConst &&
6363 N0.getOpcode() == ISD::FADD && N1.getOpcode() == ISD::FADD &&
6364 N0.getOperand(0) == N0.getOperand(1) &&
6365 N1.getOperand(0) == N1.getOperand(1) &&
6366 N0.getOperand(0) == N1.getOperand(0))
6367 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6369 DAG.getConstantFP(4.0, VT));
6372 // FADD -> FMA combines:
6373 if ((DAG.getTarget().Options.AllowFPOpFusion == FPOpFusion::Fast ||
6374 DAG.getTarget().Options.UnsafeFPMath) &&
6375 DAG.getTarget().getTargetLowering()->isFMAFasterThanFMulAndFAdd(VT) &&
6376 (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT))) {
6378 // fold (fadd (fmul x, y), z) -> (fma x, y, z)
6379 if (N0.getOpcode() == ISD::FMUL && N0->hasOneUse())
6380 return DAG.getNode(ISD::FMA, SDLoc(N), VT,
6381 N0.getOperand(0), N0.getOperand(1), N1);
6383 // fold (fadd x, (fmul y, z)) -> (fma y, z, x)
6384 // Note: Commutes FADD operands.
6385 if (N1.getOpcode() == ISD::FMUL && N1->hasOneUse())
6386 return DAG.getNode(ISD::FMA, SDLoc(N), VT,
6387 N1.getOperand(0), N1.getOperand(1), N0);
6393 SDValue DAGCombiner::visitFSUB(SDNode *N) {
6394 SDValue N0 = N->getOperand(0);
6395 SDValue N1 = N->getOperand(1);
6396 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6397 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6398 EVT VT = N->getValueType(0);
6402 if (VT.isVector()) {
6403 SDValue FoldedVOp = SimplifyVBinOp(N);
6404 if (FoldedVOp.getNode()) return FoldedVOp;
6407 // fold (fsub c1, c2) -> c1-c2
6409 return DAG.getNode(ISD::FSUB, SDLoc(N), VT, N0, N1);
6410 // fold (fsub A, 0) -> A
6411 if (DAG.getTarget().Options.UnsafeFPMath &&
6412 N1CFP && N1CFP->getValueAPF().isZero())
6414 // fold (fsub 0, B) -> -B
6415 if (DAG.getTarget().Options.UnsafeFPMath &&
6416 N0CFP && N0CFP->getValueAPF().isZero()) {
6417 if (isNegatibleForFree(N1, LegalOperations, TLI, &DAG.getTarget().Options))
6418 return GetNegatedExpression(N1, DAG, LegalOperations);
6419 if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
6420 return DAG.getNode(ISD::FNEG, dl, VT, N1);
6422 // fold (fsub A, (fneg B)) -> (fadd A, B)
6423 if (isNegatibleForFree(N1, LegalOperations, TLI, &DAG.getTarget().Options))
6424 return DAG.getNode(ISD::FADD, dl, VT, N0,
6425 GetNegatedExpression(N1, DAG, LegalOperations));
6427 // If 'unsafe math' is enabled, fold
6428 // (fsub x, x) -> 0.0 &
6429 // (fsub x, (fadd x, y)) -> (fneg y) &
6430 // (fsub x, (fadd y, x)) -> (fneg y)
6431 if (DAG.getTarget().Options.UnsafeFPMath) {
6433 return DAG.getConstantFP(0.0f, VT);
6435 if (N1.getOpcode() == ISD::FADD) {
6436 SDValue N10 = N1->getOperand(0);
6437 SDValue N11 = N1->getOperand(1);
6439 if (N10 == N0 && isNegatibleForFree(N11, LegalOperations, TLI,
6440 &DAG.getTarget().Options))
6441 return GetNegatedExpression(N11, DAG, LegalOperations);
6443 if (N11 == N0 && isNegatibleForFree(N10, LegalOperations, TLI,
6444 &DAG.getTarget().Options))
6445 return GetNegatedExpression(N10, DAG, LegalOperations);
6449 // FSUB -> FMA combines:
6450 if ((DAG.getTarget().Options.AllowFPOpFusion == FPOpFusion::Fast ||
6451 DAG.getTarget().Options.UnsafeFPMath) &&
6452 DAG.getTarget().getTargetLowering()->isFMAFasterThanFMulAndFAdd(VT) &&
6453 (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT))) {
6455 // fold (fsub (fmul x, y), z) -> (fma x, y, (fneg z))
6456 if (N0.getOpcode() == ISD::FMUL && N0->hasOneUse())
6457 return DAG.getNode(ISD::FMA, dl, VT,
6458 N0.getOperand(0), N0.getOperand(1),
6459 DAG.getNode(ISD::FNEG, dl, VT, N1));
6461 // fold (fsub x, (fmul y, z)) -> (fma (fneg y), z, x)
6462 // Note: Commutes FSUB operands.
6463 if (N1.getOpcode() == ISD::FMUL && N1->hasOneUse())
6464 return DAG.getNode(ISD::FMA, dl, VT,
6465 DAG.getNode(ISD::FNEG, dl, VT,
6467 N1.getOperand(1), N0);
6469 // fold (fsub (fneg (fmul, x, y)), z) -> (fma (fneg x), y, (fneg z))
6470 if (N0.getOpcode() == ISD::FNEG &&
6471 N0.getOperand(0).getOpcode() == ISD::FMUL &&
6472 N0->hasOneUse() && N0.getOperand(0).hasOneUse()) {
6473 SDValue N00 = N0.getOperand(0).getOperand(0);
6474 SDValue N01 = N0.getOperand(0).getOperand(1);
6475 return DAG.getNode(ISD::FMA, dl, VT,
6476 DAG.getNode(ISD::FNEG, dl, VT, N00), N01,
6477 DAG.getNode(ISD::FNEG, dl, VT, N1));
6484 SDValue DAGCombiner::visitFMUL(SDNode *N) {
6485 SDValue N0 = N->getOperand(0);
6486 SDValue N1 = N->getOperand(1);
6487 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6488 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6489 EVT VT = N->getValueType(0);
6490 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6493 if (VT.isVector()) {
6494 SDValue FoldedVOp = SimplifyVBinOp(N);
6495 if (FoldedVOp.getNode()) return FoldedVOp;
6498 // fold (fmul c1, c2) -> c1*c2
6500 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0, N1);
6501 // canonicalize constant to RHS
6502 if (N0CFP && !N1CFP)
6503 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N1, N0);
6504 // fold (fmul A, 0) -> 0
6505 if (DAG.getTarget().Options.UnsafeFPMath &&
6506 N1CFP && N1CFP->getValueAPF().isZero())
6508 // fold (fmul A, 0) -> 0, vector edition.
6509 if (DAG.getTarget().Options.UnsafeFPMath &&
6510 ISD::isBuildVectorAllZeros(N1.getNode()))
6512 // fold (fmul A, 1.0) -> A
6513 if (N1CFP && N1CFP->isExactlyValue(1.0))
6515 // fold (fmul X, 2.0) -> (fadd X, X)
6516 if (N1CFP && N1CFP->isExactlyValue(+2.0))
6517 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N0);
6518 // fold (fmul X, -1.0) -> (fneg X)
6519 if (N1CFP && N1CFP->isExactlyValue(-1.0))
6520 if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
6521 return DAG.getNode(ISD::FNEG, SDLoc(N), VT, N0);
6523 // fold (fmul (fneg X), (fneg Y)) -> (fmul X, Y)
6524 if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI,
6525 &DAG.getTarget().Options)) {
6526 if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI,
6527 &DAG.getTarget().Options)) {
6528 // Both can be negated for free, check to see if at least one is cheaper
6530 if (LHSNeg == 2 || RHSNeg == 2)
6531 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6532 GetNegatedExpression(N0, DAG, LegalOperations),
6533 GetNegatedExpression(N1, DAG, LegalOperations));
6537 // If allowed, fold (fmul (fmul x, c1), c2) -> (fmul x, (fmul c1, c2))
6538 if (DAG.getTarget().Options.UnsafeFPMath &&
6539 N1CFP && N0.getOpcode() == ISD::FMUL &&
6540 N0.getNode()->hasOneUse() && isa<ConstantFPSDNode>(N0.getOperand(1)))
6541 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0.getOperand(0),
6542 DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6543 N0.getOperand(1), N1));
6548 SDValue DAGCombiner::visitFMA(SDNode *N) {
6549 SDValue N0 = N->getOperand(0);
6550 SDValue N1 = N->getOperand(1);
6551 SDValue N2 = N->getOperand(2);
6552 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6553 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6554 EVT VT = N->getValueType(0);
6557 if (DAG.getTarget().Options.UnsafeFPMath) {
6558 if (N0CFP && N0CFP->isZero())
6560 if (N1CFP && N1CFP->isZero())
6563 if (N0CFP && N0CFP->isExactlyValue(1.0))
6564 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N1, N2);
6565 if (N1CFP && N1CFP->isExactlyValue(1.0))
6566 return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N2);
6568 // Canonicalize (fma c, x, y) -> (fma x, c, y)
6569 if (N0CFP && !N1CFP)
6570 return DAG.getNode(ISD::FMA, SDLoc(N), VT, N1, N0, N2);
6572 // (fma x, c1, (fmul x, c2)) -> (fmul x, c1+c2)
6573 if (DAG.getTarget().Options.UnsafeFPMath && N1CFP &&
6574 N2.getOpcode() == ISD::FMUL &&
6575 N0 == N2.getOperand(0) &&
6576 N2.getOperand(1).getOpcode() == ISD::ConstantFP) {
6577 return DAG.getNode(ISD::FMUL, dl, VT, N0,
6578 DAG.getNode(ISD::FADD, dl, VT, N1, N2.getOperand(1)));
6582 // (fma (fmul x, c1), c2, y) -> (fma x, c1*c2, y)
6583 if (DAG.getTarget().Options.UnsafeFPMath &&
6584 N0.getOpcode() == ISD::FMUL && N1CFP &&
6585 N0.getOperand(1).getOpcode() == ISD::ConstantFP) {
6586 return DAG.getNode(ISD::FMA, dl, VT,
6588 DAG.getNode(ISD::FMUL, dl, VT, N1, N0.getOperand(1)),
6592 // (fma x, 1, y) -> (fadd x, y)
6593 // (fma x, -1, y) -> (fadd (fneg x), y)
6595 if (N1CFP->isExactlyValue(1.0))
6596 return DAG.getNode(ISD::FADD, dl, VT, N0, N2);
6598 if (N1CFP->isExactlyValue(-1.0) &&
6599 (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))) {
6600 SDValue RHSNeg = DAG.getNode(ISD::FNEG, dl, VT, N0);
6601 AddToWorkList(RHSNeg.getNode());
6602 return DAG.getNode(ISD::FADD, dl, VT, N2, RHSNeg);
6606 // (fma x, c, x) -> (fmul x, (c+1))
6607 if (DAG.getTarget().Options.UnsafeFPMath && N1CFP && N0 == N2)
6608 return DAG.getNode(ISD::FMUL, dl, VT, N0,
6609 DAG.getNode(ISD::FADD, dl, VT,
6610 N1, DAG.getConstantFP(1.0, VT)));
6612 // (fma x, c, (fneg x)) -> (fmul x, (c-1))
6613 if (DAG.getTarget().Options.UnsafeFPMath && N1CFP &&
6614 N2.getOpcode() == ISD::FNEG && N2.getOperand(0) == N0)
6615 return DAG.getNode(ISD::FMUL, dl, VT, N0,
6616 DAG.getNode(ISD::FADD, dl, VT,
6617 N1, DAG.getConstantFP(-1.0, VT)));
6623 SDValue DAGCombiner::visitFDIV(SDNode *N) {
6624 SDValue N0 = N->getOperand(0);
6625 SDValue N1 = N->getOperand(1);
6626 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6627 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6628 EVT VT = N->getValueType(0);
6629 const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6632 if (VT.isVector()) {
6633 SDValue FoldedVOp = SimplifyVBinOp(N);
6634 if (FoldedVOp.getNode()) return FoldedVOp;
6637 // fold (fdiv c1, c2) -> c1/c2
6639 return DAG.getNode(ISD::FDIV, SDLoc(N), VT, N0, N1);
6641 // fold (fdiv X, c2) -> fmul X, 1/c2 if losing precision is acceptable.
6642 if (N1CFP && DAG.getTarget().Options.UnsafeFPMath) {
6643 // Compute the reciprocal 1.0 / c2.
6644 APFloat N1APF = N1CFP->getValueAPF();
6645 APFloat Recip(N1APF.getSemantics(), 1); // 1.0
6646 APFloat::opStatus st = Recip.divide(N1APF, APFloat::rmNearestTiesToEven);
6647 // Only do the transform if the reciprocal is a legal fp immediate that
6648 // isn't too nasty (eg NaN, denormal, ...).
6649 if ((st == APFloat::opOK || st == APFloat::opInexact) && // Not too nasty
6650 (!LegalOperations ||
6651 // FIXME: custom lowering of ConstantFP might fail (see e.g. ARM
6652 // backend)... we should handle this gracefully after Legalize.
6653 // TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT) ||
6654 TLI.isOperationLegal(llvm::ISD::ConstantFP, VT) ||
6655 TLI.isFPImmLegal(Recip, VT)))
6656 return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0,
6657 DAG.getConstantFP(Recip, VT));
6660 // (fdiv (fneg X), (fneg Y)) -> (fdiv X, Y)
6661 if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI,
6662 &DAG.getTarget().Options)) {
6663 if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI,
6664 &DAG.getTarget().Options)) {
6665 // Both can be negated for free, check to see if at least one is cheaper
6667 if (LHSNeg == 2 || RHSNeg == 2)
6668 return DAG.getNode(ISD::FDIV, SDLoc(N), VT,
6669 GetNegatedExpression(N0, DAG, LegalOperations),
6670 GetNegatedExpression(N1, DAG, LegalOperations));
6677 SDValue DAGCombiner::visitFREM(SDNode *N) {
6678 SDValue N0 = N->getOperand(0);
6679 SDValue N1 = N->getOperand(1);
6680 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6681 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6682 EVT VT = N->getValueType(0);
6684 // fold (frem c1, c2) -> fmod(c1,c2)
6686 return DAG.getNode(ISD::FREM, SDLoc(N), VT, N0, N1);
6691 SDValue DAGCombiner::visitFCOPYSIGN(SDNode *N) {
6692 SDValue N0 = N->getOperand(0);
6693 SDValue N1 = N->getOperand(1);
6694 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6695 ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6696 EVT VT = N->getValueType(0);
6698 if (N0CFP && N1CFP) // Constant fold
6699 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, N0, N1);
6702 const APFloat& V = N1CFP->getValueAPF();
6703 // copysign(x, c1) -> fabs(x) iff ispos(c1)
6704 // copysign(x, c1) -> fneg(fabs(x)) iff isneg(c1)
6705 if (!V.isNegative()) {
6706 if (!LegalOperations || TLI.isOperationLegal(ISD::FABS, VT))
6707 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
6709 if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
6710 return DAG.getNode(ISD::FNEG, SDLoc(N), VT,
6711 DAG.getNode(ISD::FABS, SDLoc(N0), VT, N0));
6715 // copysign(fabs(x), y) -> copysign(x, y)
6716 // copysign(fneg(x), y) -> copysign(x, y)
6717 // copysign(copysign(x,z), y) -> copysign(x, y)
6718 if (N0.getOpcode() == ISD::FABS || N0.getOpcode() == ISD::FNEG ||
6719 N0.getOpcode() == ISD::FCOPYSIGN)
6720 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
6721 N0.getOperand(0), N1);
6723 // copysign(x, abs(y)) -> abs(x)
6724 if (N1.getOpcode() == ISD::FABS)
6725 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
6727 // copysign(x, copysign(y,z)) -> copysign(x, z)
6728 if (N1.getOpcode() == ISD::FCOPYSIGN)
6729 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
6730 N0, N1.getOperand(1));
6732 // copysign(x, fp_extend(y)) -> copysign(x, y)
6733 // copysign(x, fp_round(y)) -> copysign(x, y)
6734 if (N1.getOpcode() == ISD::FP_EXTEND || N1.getOpcode() == ISD::FP_ROUND)
6735 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
6736 N0, N1.getOperand(0));
6741 SDValue DAGCombiner::visitSINT_TO_FP(SDNode *N) {
6742 SDValue N0 = N->getOperand(0);
6743 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
6744 EVT VT = N->getValueType(0);
6745 EVT OpVT = N0.getValueType();
6747 // fold (sint_to_fp c1) -> c1fp
6749 // ...but only if the target supports immediate floating-point values
6750 (!LegalOperations ||
6751 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT)))
6752 return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0);
6754 // If the input is a legal type, and SINT_TO_FP is not legal on this target,
6755 // but UINT_TO_FP is legal on this target, try to convert.
6756 if (!TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT) &&
6757 TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT)) {
6758 // If the sign bit is known to be zero, we can change this to UINT_TO_FP.
6759 if (DAG.SignBitIsZero(N0))
6760 return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0);
6763 // The next optimizations are desirable only if SELECT_CC can be lowered.
6764 // Check against MVT::Other for SELECT_CC, which is a workaround for targets
6765 // having to say they don't support SELECT_CC on every type the DAG knows
6766 // about, since there is no way to mark an opcode illegal at all value types
6767 // (See also visitSELECT)
6768 if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, MVT::Other)) {
6769 // fold (sint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc)
6770 if (N0.getOpcode() == ISD::SETCC && N0.getValueType() == MVT::i1 &&
6772 (!LegalOperations ||
6773 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
6775 { N0.getOperand(0), N0.getOperand(1),
6776 DAG.getConstantFP(-1.0, VT) , DAG.getConstantFP(0.0, VT),
6778 return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT, Ops, 5);
6781 // fold (sint_to_fp (zext (setcc x, y, cc))) ->
6782 // (select_cc x, y, 1.0, 0.0,, cc)
6783 if (N0.getOpcode() == ISD::ZERO_EXTEND &&
6784 N0.getOperand(0).getOpcode() == ISD::SETCC &&!VT.isVector() &&
6785 (!LegalOperations ||
6786 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
6788 { N0.getOperand(0).getOperand(0), N0.getOperand(0).getOperand(1),
6789 DAG.getConstantFP(1.0, VT) , DAG.getConstantFP(0.0, VT),
6790 N0.getOperand(0).getOperand(2) };
6791 return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT, Ops, 5);
6798 SDValue DAGCombiner::visitUINT_TO_FP(SDNode *N) {
6799 SDValue N0 = N->getOperand(0);
6800 ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
6801 EVT VT = N->getValueType(0);
6802 EVT OpVT = N0.getValueType();
6804 // fold (uint_to_fp c1) -> c1fp
6806 // ...but only if the target supports immediate floating-point values
6807 (!LegalOperations ||
6808 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT)))
6809 return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0);
6811 // If the input is a legal type, and UINT_TO_FP is not legal on this target,
6812 // but SINT_TO_FP is legal on this target, try to convert.
6813 if (!TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT) &&
6814 TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT)) {
6815 // If the sign bit is known to be zero, we can change this to SINT_TO_FP.
6816 if (DAG.SignBitIsZero(N0))
6817 return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0);
6820 // The next optimizations are desirable only if SELECT_CC can be lowered.
6821 // Check against MVT::Other for SELECT_CC, which is a workaround for targets
6822 // having to say they don't support SELECT_CC on every type the DAG knows
6823 // about, since there is no way to mark an opcode illegal at all value types
6824 // (See also visitSELECT)
6825 if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, MVT::Other)) {
6826 // fold (uint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc)
6828 if (N0.getOpcode() == ISD::SETCC && !VT.isVector() &&
6829 (!LegalOperations ||
6830 TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
6832 { N0.getOperand(0), N0.getOperand(1),
6833 DAG.getConstantFP(1.0, VT), DAG.getConstantFP(0.0, VT),
6835 return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT, Ops, 5);
6842 SDValue DAGCombiner::visitFP_TO_SINT(SDNode *N) {
6843 SDValue N0 = N->getOperand(0);
6844 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6845 EVT VT = N->getValueType(0);
6847 // fold (fp_to_sint c1fp) -> c1
6849 return DAG.getNode(ISD::FP_TO_SINT, SDLoc(N), VT, N0);
6854 SDValue DAGCombiner::visitFP_TO_UINT(SDNode *N) {
6855 SDValue N0 = N->getOperand(0);
6856 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6857 EVT VT = N->getValueType(0);
6859 // fold (fp_to_uint c1fp) -> c1
6861 return DAG.getNode(ISD::FP_TO_UINT, SDLoc(N), VT, N0);
6866 SDValue DAGCombiner::visitFP_ROUND(SDNode *N) {
6867 SDValue N0 = N->getOperand(0);
6868 SDValue N1 = N->getOperand(1);
6869 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6870 EVT VT = N->getValueType(0);
6872 // fold (fp_round c1fp) -> c1fp
6874 return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT, N0, N1);
6876 // fold (fp_round (fp_extend x)) -> x
6877 if (N0.getOpcode() == ISD::FP_EXTEND && VT == N0.getOperand(0).getValueType())
6878 return N0.getOperand(0);
6880 // fold (fp_round (fp_round x)) -> (fp_round x)
6881 if (N0.getOpcode() == ISD::FP_ROUND) {
6882 // This is a value preserving truncation if both round's are.
6883 bool IsTrunc = N->getConstantOperandVal(1) == 1 &&
6884 N0.getNode()->getConstantOperandVal(1) == 1;
6885 return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT, N0.getOperand(0),
6886 DAG.getIntPtrConstant(IsTrunc));
6889 // fold (fp_round (copysign X, Y)) -> (copysign (fp_round X), Y)
6890 if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse()) {
6891 SDValue Tmp = DAG.getNode(ISD::FP_ROUND, SDLoc(N0), VT,
6892 N0.getOperand(0), N1);
6893 AddToWorkList(Tmp.getNode());
6894 return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
6895 Tmp, N0.getOperand(1));
6901 SDValue DAGCombiner::visitFP_ROUND_INREG(SDNode *N) {
6902 SDValue N0 = N->getOperand(0);
6903 EVT VT = N->getValueType(0);
6904 EVT EVT = cast<VTSDNode>(N->getOperand(1))->getVT();
6905 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6907 // fold (fp_round_inreg c1fp) -> c1fp
6908 if (N0CFP && isTypeLegal(EVT)) {
6909 SDValue Round = DAG.getConstantFP(*N0CFP->getConstantFPValue(), EVT);
6910 return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, Round);
6916 SDValue DAGCombiner::visitFP_EXTEND(SDNode *N) {
6917 SDValue N0 = N->getOperand(0);
6918 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6919 EVT VT = N->getValueType(0);
6921 // If this is fp_round(fpextend), don't fold it, allow ourselves to be folded.
6922 if (N->hasOneUse() &&
6923 N->use_begin()->getOpcode() == ISD::FP_ROUND)
6926 // fold (fp_extend c1fp) -> c1fp
6928 return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, N0);
6930 // Turn fp_extend(fp_round(X, 1)) -> x since the fp_round doesn't affect the
6932 if (N0.getOpcode() == ISD::FP_ROUND
6933 && N0.getNode()->getConstantOperandVal(1) == 1) {
6934 SDValue In = N0.getOperand(0);
6935 if (In.getValueType() == VT) return In;
6936 if (VT.bitsLT(In.getValueType()))
6937 return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT,
6938 In, N0.getOperand(1));
6939 return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, In);
6942 // fold (fpext (load x)) -> (fpext (fptrunc (extload x)))
6943 if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
6944 ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
6945 TLI.isLoadExtLegal(ISD::EXTLOAD, N0.getValueType()))) {
6946 LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6947 SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT,
6949 LN0->getBasePtr(), N0.getValueType(),
6950 LN0->getMemOperand());
6951 CombineTo(N, ExtLoad);
6952 CombineTo(N0.getNode(),
6953 DAG.getNode(ISD::FP_ROUND, SDLoc(N0),
6954 N0.getValueType(), ExtLoad, DAG.getIntPtrConstant(1)),
6955 ExtLoad.getValue(1));
6956 return SDValue(N, 0); // Return N so it doesn't get rechecked!
6962 SDValue DAGCombiner::visitFNEG(SDNode *N) {
6963 SDValue N0 = N->getOperand(0);
6964 EVT VT = N->getValueType(0);
6966 if (VT.isVector()) {
6967 SDValue FoldedVOp = SimplifyVUnaryOp(N);
6968 if (FoldedVOp.getNode()) return FoldedVOp;
6971 if (isNegatibleForFree(N0, LegalOperations, DAG.getTargetLoweringInfo(),
6972 &DAG.getTarget().Options))
6973 return GetNegatedExpression(N0, DAG, LegalOperations);
6975 // Transform fneg(bitconvert(x)) -> bitconvert(x^sign) to avoid loading
6976 // constant pool values.
6977 if (!TLI.isFNegFree(VT) && N0.getOpcode() == ISD::BITCAST &&
6979 N0.getNode()->hasOneUse() &&
6980 N0.getOperand(0).getValueType().isInteger()) {
6981 SDValue Int = N0.getOperand(0);
6982 EVT IntVT = Int.getValueType();
6983 if (IntVT.isInteger() && !IntVT.isVector()) {
6984 Int = DAG.getNode(ISD::XOR, SDLoc(N0), IntVT, Int,
6985 DAG.getConstant(APInt::getSignBit(IntVT.getSizeInBits()), IntVT));
6986 AddToWorkList(Int.getNode());
6987 return DAG.getNode(ISD::BITCAST, SDLoc(N),
6992 // (fneg (fmul c, x)) -> (fmul -c, x)
6993 if (N0.getOpcode() == ISD::FMUL) {
6994 ConstantFPSDNode *CFP1 = dyn_cast<ConstantFPSDNode>(N0.getOperand(1));
6996 return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6998 DAG.getNode(ISD::FNEG, SDLoc(N), VT,
7005 SDValue DAGCombiner::visitFCEIL(SDNode *N) {
7006 SDValue N0 = N->getOperand(0);
7007 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7008 EVT VT = N->getValueType(0);
7010 // fold (fceil c1) -> fceil(c1)
7012 return DAG.getNode(ISD::FCEIL, SDLoc(N), VT, N0);
7017 SDValue DAGCombiner::visitFTRUNC(SDNode *N) {
7018 SDValue N0 = N->getOperand(0);
7019 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7020 EVT VT = N->getValueType(0);
7022 // fold (ftrunc c1) -> ftrunc(c1)
7024 return DAG.getNode(ISD::FTRUNC, SDLoc(N), VT, N0);
7029 SDValue DAGCombiner::visitFFLOOR(SDNode *N) {
7030 SDValue N0 = N->getOperand(0);
7031 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7032 EVT VT = N->getValueType(0);
7034 // fold (ffloor c1) -> ffloor(c1)
7036 return DAG.getNode(ISD::FFLOOR, SDLoc(N), VT, N0);
7041 SDValue DAGCombiner::visitFABS(SDNode *N) {
7042 SDValue N0 = N->getOperand(0);
7043 ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7044 EVT VT = N->getValueType(0);
7046 if (VT.isVector()) {
7047 SDValue FoldedVOp = SimplifyVUnaryOp(N);
7048 if (FoldedVOp.getNode()) return FoldedVOp;
7051 // fold (fabs c1) -> fabs(c1)
7053 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
7054 // fold (fabs (fabs x)) -> (fabs x)
7055 if (N0.getOpcode() == ISD::FABS)
7056 return N->getOperand(0);
7057 // fold (fabs (fneg x)) -> (fabs x)
7058 // fold (fabs (fcopysign x, y)) -> (fabs x)
7059 if (N0.getOpcode() == ISD::FNEG || N0.getOpcode() == ISD::FCOPYSIGN)
7060 return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0.getOperand(0));
7062 // Transform fabs(bitconvert(x)) -> bitconvert(x&~sign) to avoid loading
7063 // constant pool values.
7064 if (!TLI.isFAbsFree(VT) &&
7065 N0.getOpcode() == ISD::BITCAST && N0.getNode()->hasOneUse() &&
7066 N0.getOperand(0).getValueType().isInteger() &&
7067 !N0.getOperand(0).getValueType().isVector()) {
7068 SDValue Int = N0.getOperand(0);
7069 EVT IntVT = Int.getValueType();
7070 if (IntVT.isInteger() && !IntVT.isVector()) {
7071 Int = DAG.getNode(ISD::AND, SDLoc(N0), IntVT, Int,
7072 DAG.getConstant(~APInt::getSignBit(IntVT.getSizeInBits()), IntVT));
7073 AddToWorkList(Int.getNode());
7074 return DAG.getNode(ISD::BITCAST, SDLoc(N),
7075 N->getValueType(0), Int);
7082 SDValue DAGCombiner::visitBRCOND(SDNode *N) {
7083 SDValue Chain = N->getOperand(0);
7084 SDValue N1 = N->getOperand(1);
7085 SDValue N2 = N->getOperand(2);
7087 // If N is a constant we could fold this into a fallthrough or unconditional
7088 // branch. However that doesn't happen very often in normal code, because
7089 // Instcombine/SimplifyCFG should have handled the available opportunities.
7090 // If we did this folding here, it would be necessary to update the
7091 // MachineBasicBlock CFG, which is awkward.
7093 // fold a brcond with a setcc condition into a BR_CC node if BR_CC is legal
7095 if (N1.getOpcode() == ISD::SETCC &&
7096 TLI.isOperationLegalOrCustom(ISD::BR_CC,
7097 N1.getOperand(0).getValueType())) {
7098 return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other,
7099 Chain, N1.getOperand(2),
7100 N1.getOperand(0), N1.getOperand(1), N2);
7103 if ((N1.hasOneUse() && N1.getOpcode() == ISD::SRL) ||
7104 ((N1.getOpcode() == ISD::TRUNCATE && N1.hasOneUse()) &&
7105 (N1.getOperand(0).hasOneUse() &&
7106 N1.getOperand(0).getOpcode() == ISD::SRL))) {
7108 if (N1.getOpcode() == ISD::TRUNCATE) {
7109 // Look pass the truncate.
7110 Trunc = N1.getNode();
7111 N1 = N1.getOperand(0);
7114 // Match this pattern so that we can generate simpler code:
7117 // %b = and i32 %a, 2
7118 // %c = srl i32 %b, 1
7119 // brcond i32 %c ...
7124 // %b = and i32 %a, 2
7125 // %c = setcc eq %b, 0
7128 // This applies only when the AND constant value has one bit set and the
7129 // SRL constant is equal to the log2 of the AND constant. The back-end is
7130 // smart enough to convert the result into a TEST/JMP sequence.
7131 SDValue Op0 = N1.getOperand(0);
7132 SDValue Op1 = N1.getOperand(1);
7134 if (Op0.getOpcode() == ISD::AND &&
7135 Op1.getOpcode() == ISD::Constant) {
7136 SDValue AndOp1 = Op0.getOperand(1);
7138 if (AndOp1.getOpcode() == ISD::Constant) {
7139 const APInt &AndConst = cast<ConstantSDNode>(AndOp1)->getAPIntValue();
7141 if (AndConst.isPowerOf2() &&
7142 cast<ConstantSDNode>(Op1)->getAPIntValue()==AndConst.logBase2()) {
7144 DAG.getSetCC(SDLoc(N),
7145 getSetCCResultType(Op0.getValueType()),
7146 Op0, DAG.getConstant(0, Op0.getValueType()),
7149 SDValue NewBRCond = DAG.getNode(ISD::BRCOND, SDLoc(N),
7150 MVT::Other, Chain, SetCC, N2);
7151 // Don't add the new BRCond into the worklist or else SimplifySelectCC
7152 // will convert it back to (X & C1) >> C2.
7153 CombineTo(N, NewBRCond, false);
7154 // Truncate is dead.
7156 removeFromWorkList(Trunc);
7157 DAG.DeleteNode(Trunc);
7159 // Replace the uses of SRL with SETCC
7160 WorkListRemover DeadNodes(*this);
7161 DAG.ReplaceAllUsesOfValueWith(N1, SetCC);
7162 removeFromWorkList(N1.getNode());
7163 DAG.DeleteNode(N1.getNode());
7164 return SDValue(N, 0); // Return N so it doesn't get rechecked!
7170 // Restore N1 if the above transformation doesn't match.
7171 N1 = N->getOperand(1);
7174 // Transform br(xor(x, y)) -> br(x != y)
7175 // Transform br(xor(xor(x,y), 1)) -> br (x == y)
7176 if (N1.hasOneUse() && N1.getOpcode() == ISD::XOR) {
7177 SDNode *TheXor = N1.getNode();
7178 SDValue Op0 = TheXor->getOperand(0);
7179 SDValue Op1 = TheXor->getOperand(1);
7180 if (Op0.getOpcode() == Op1.getOpcode()) {
7181 // Avoid missing important xor optimizations.
7182 SDValue Tmp = visitXOR(TheXor);
7183 if (Tmp.getNode()) {
7184 if (Tmp.getNode() != TheXor) {
7185 DEBUG(dbgs() << "\nReplacing.8 ";
7187 dbgs() << "\nWith: ";
7188 Tmp.getNode()->dump(&DAG);
7190 WorkListRemover DeadNodes(*this);
7191 DAG.ReplaceAllUsesOfValueWith(N1, Tmp);
7192 removeFromWorkList(TheXor);
7193 DAG.DeleteNode(TheXor);
7194 return DAG.getNode(ISD::BRCOND, SDLoc(N),
7195 MVT::Other, Chain, Tmp, N2);
7198 // visitXOR has changed XOR's operands or replaced the XOR completely,
7200 return SDValue(N, 0);
7204 if (Op0.getOpcode() != ISD::SETCC && Op1.getOpcode() != ISD::SETCC) {
7206 if (ConstantSDNode *RHSCI = dyn_cast<ConstantSDNode>(Op0))
7207 if (RHSCI->getAPIntValue() == 1 && Op0.hasOneUse() &&
7208 Op0.getOpcode() == ISD::XOR) {
7209 TheXor = Op0.getNode();
7213 EVT SetCCVT = N1.getValueType();
7215 SetCCVT = getSetCCResultType(SetCCVT);
7216 SDValue SetCC = DAG.getSetCC(SDLoc(TheXor),
7219 Equal ? ISD::SETEQ : ISD::SETNE);
7220 // Replace the uses of XOR with SETCC
7221 WorkListRemover DeadNodes(*this);
7222 DAG.ReplaceAllUsesOfValueWith(N1, SetCC);
7223 removeFromWorkList(N1.getNode());
7224 DAG.DeleteNode(N1.getNode());
7225 return DAG.getNode(ISD::BRCOND, SDLoc(N),
7226 MVT::Other, Chain, SetCC, N2);
7233 // Operand List for BR_CC: Chain, CondCC, CondLHS, CondRHS, DestBB.
7235 SDValue DAGCombiner::visitBR_CC(SDNode *N) {
7236 CondCodeSDNode *CC = cast<CondCodeSDNode>(N->getOperand(1));
7237 SDValue CondLHS = N->getOperand(2), CondRHS = N->getOperand(3);
7239 // If N is a constant we could fold this into a fallthrough or unconditional
7240 // branch. However that doesn't happen very often in normal code, because
7241 // Instcombine/SimplifyCFG should have handled the available opportunities.
7242 // If we did this folding here, it would be necessary to update the
7243 // MachineBasicBlock CFG, which is awkward.
7245 // Use SimplifySetCC to simplify SETCC's.
7246 SDValue Simp = SimplifySetCC(getSetCCResultType(CondLHS.getValueType()),
7247 CondLHS, CondRHS, CC->get(), SDLoc(N),
7249 if (Simp.getNode()) AddToWorkList(Simp.getNode());
7251 // fold to a simpler setcc
7252 if (Simp.getNode() && Simp.getOpcode() == ISD::SETCC)
7253 return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other,
7254 N->getOperand(0), Simp.getOperand(2),
7255 Simp.getOperand(0), Simp.getOperand(1),
7261 /// canFoldInAddressingMode - Return true if 'Use' is a load or a store that
7262 /// uses N as its base pointer and that N may be folded in the load / store
7263 /// addressing mode.
7264 static bool canFoldInAddressingMode(SDNode *N, SDNode *Use,
7266 const TargetLowering &TLI) {
7268 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Use)) {
7269 if (LD->isIndexed() || LD->getBasePtr().getNode() != N)
7271 VT = Use->getValueType(0);
7272 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(Use)) {
7273 if (ST->isIndexed() || ST->getBasePtr().getNode() != N)
7275 VT = ST->getValue().getValueType();
7279 TargetLowering::AddrMode AM;
7280 if (N->getOpcode() == ISD::ADD) {
7281 ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1));
7284 AM.BaseOffs = Offset->getSExtValue();
7288 } else if (N->getOpcode() == ISD::SUB) {
7289 ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1));
7292 AM.BaseOffs = -Offset->getSExtValue();
7299 return TLI.isLegalAddressingMode(AM, VT.getTypeForEVT(*DAG.getContext()));
7302 /// CombineToPreIndexedLoadStore - Try turning a load / store into a
7303 /// pre-indexed load / store when the base pointer is an add or subtract
7304 /// and it has other uses besides the load / store. After the
7305 /// transformation, the new indexed load / store has effectively folded
7306 /// the add / subtract in and all of its other uses are redirected to the
7307 /// new load / store.
7308 bool DAGCombiner::CombineToPreIndexedLoadStore(SDNode *N) {
7309 if (Level < AfterLegalizeDAG)
7315 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
7316 if (LD->isIndexed())
7318 VT = LD->getMemoryVT();
7319 if (!TLI.isIndexedLoadLegal(ISD::PRE_INC, VT) &&
7320 !TLI.isIndexedLoadLegal(ISD::PRE_DEC, VT))
7322 Ptr = LD->getBasePtr();
7323 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
7324 if (ST->isIndexed())
7326 VT = ST->getMemoryVT();
7327 if (!TLI.isIndexedStoreLegal(ISD::PRE_INC, VT) &&
7328 !TLI.isIndexedStoreLegal(ISD::PRE_DEC, VT))
7330 Ptr = ST->getBasePtr();
7336 // If the pointer is not an add/sub, or if it doesn't have multiple uses, bail
7337 // out. There is no reason to make this a preinc/predec.
7338 if ((Ptr.getOpcode() != ISD::ADD && Ptr.getOpcode() != ISD::SUB) ||
7339 Ptr.getNode()->hasOneUse())
7342 // Ask the target to do addressing mode selection.
7345 ISD::MemIndexedMode AM = ISD::UNINDEXED;
7346 if (!TLI.getPreIndexedAddressParts(N, BasePtr, Offset, AM, DAG))
7349 // Backends without true r+i pre-indexed forms may need to pass a
7350 // constant base with a variable offset so that constant coercion
7351 // will work with the patterns in canonical form.
7352 bool Swapped = false;
7353 if (isa<ConstantSDNode>(BasePtr)) {
7354 std::swap(BasePtr, Offset);
7358 // Don't create a indexed load / store with zero offset.
7359 if (isa<ConstantSDNode>(Offset) &&
7360 cast<ConstantSDNode>(Offset)->isNullValue())
7363 // Try turning it into a pre-indexed load / store except when:
7364 // 1) The new base ptr is a frame index.
7365 // 2) If N is a store and the new base ptr is either the same as or is a
7366 // predecessor of the value being stored.
7367 // 3) Another use of old base ptr is a predecessor of N. If ptr is folded
7368 // that would create a cycle.
7369 // 4) All uses are load / store ops that use it as old base ptr.
7371 // Check #1. Preinc'ing a frame index would require copying the stack pointer
7372 // (plus the implicit offset) to a register to preinc anyway.
7373 if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr))
7378 SDValue Val = cast<StoreSDNode>(N)->getValue();
7379 if (Val == BasePtr || BasePtr.getNode()->isPredecessorOf(Val.getNode()))
7383 // If the offset is a constant, there may be other adds of constants that
7384 // can be folded with this one. We should do this to avoid having to keep
7385 // a copy of the original base pointer.
7386 SmallVector<SDNode *, 16> OtherUses;
7387 if (isa<ConstantSDNode>(Offset))
7388 for (SDNode::use_iterator I = BasePtr.getNode()->use_begin(),
7389 E = BasePtr.getNode()->use_end(); I != E; ++I) {
7391 if (Use == Ptr.getNode())
7394 if (Use->isPredecessorOf(N))
7397 if (Use->getOpcode() != ISD::ADD && Use->getOpcode() != ISD::SUB) {
7402 SDValue Op0 = Use->getOperand(0), Op1 = Use->getOperand(1);
7403 if (Op1.getNode() == BasePtr.getNode())
7404 std::swap(Op0, Op1);
7405 assert(Op0.getNode() == BasePtr.getNode() &&
7406 "Use of ADD/SUB but not an operand");
7408 if (!isa<ConstantSDNode>(Op1)) {
7413 // FIXME: In some cases, we can be smarter about this.
7414 if (Op1.getValueType() != Offset.getValueType()) {
7419 OtherUses.push_back(Use);
7423 std::swap(BasePtr, Offset);
7425 // Now check for #3 and #4.
7426 bool RealUse = false;
7428 // Caches for hasPredecessorHelper
7429 SmallPtrSet<const SDNode *, 32> Visited;
7430 SmallVector<const SDNode *, 16> Worklist;
7432 for (SDNode::use_iterator I = Ptr.getNode()->use_begin(),
7433 E = Ptr.getNode()->use_end(); I != E; ++I) {
7437 if (N->hasPredecessorHelper(Use, Visited, Worklist))
7440 // If Ptr may be folded in addressing mode of other use, then it's
7441 // not profitable to do this transformation.
7442 if (!canFoldInAddressingMode(Ptr.getNode(), Use, DAG, TLI))
7451 Result = DAG.getIndexedLoad(SDValue(N,0), SDLoc(N),
7452 BasePtr, Offset, AM);
7454 Result = DAG.getIndexedStore(SDValue(N,0), SDLoc(N),
7455 BasePtr, Offset, AM);
7458 DEBUG(dbgs() << "\nReplacing.4 ";
7460 dbgs() << "\nWith: ";
7461 Result.getNode()->dump(&DAG);
7463 WorkListRemover DeadNodes(*this);
7465 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0));
7466 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2));
7468 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1));
7471 // Finally, since the node is now dead, remove it from the graph.
7475 std::swap(BasePtr, Offset);
7477 // Replace other uses of BasePtr that can be updated to use Ptr
7478 for (unsigned i = 0, e = OtherUses.size(); i != e; ++i) {
7479 unsigned OffsetIdx = 1;
7480 if (OtherUses[i]->getOperand(OffsetIdx).getNode() == BasePtr.getNode())
7482 assert(OtherUses[i]->getOperand(!OffsetIdx).getNode() ==
7483 BasePtr.getNode() && "Expected BasePtr operand");
7485 // We need to replace ptr0 in the following expression:
7486 // x0 * offset0 + y0 * ptr0 = t0
7488 // x1 * offset1 + y1 * ptr0 = t1 (the indexed load/store)
7490 // where x0, x1, y0 and y1 in {-1, 1} are given by the types of the
7491 // indexed load/store and the expresion that needs to be re-written.
7493 // Therefore, we have:
7494 // t0 = (x0 * offset0 - x1 * y0 * y1 *offset1) + (y0 * y1) * t1
7496 ConstantSDNode *CN =
7497 cast<ConstantSDNode>(OtherUses[i]->getOperand(OffsetIdx));
7499 APInt Offset0 = CN->getAPIntValue();
7500 APInt Offset1 = cast<ConstantSDNode>(Offset)->getAPIntValue();
7502 X0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 1) ? -1 : 1;
7503 Y0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 0) ? -1 : 1;
7504 X1 = (AM == ISD::PRE_DEC && !Swapped) ? -1 : 1;
7505 Y1 = (AM == ISD::PRE_DEC && Swapped) ? -1 : 1;
7507 unsigned Opcode = (Y0 * Y1 < 0) ? ISD::SUB : ISD::ADD;
7509 APInt CNV = Offset0;
7510 if (X0 < 0) CNV = -CNV;
7511 if (X1 * Y0 * Y1 < 0) CNV = CNV + Offset1;
7512 else CNV = CNV - Offset1;
7514 // We can now generate the new expression.
7515 SDValue NewOp1 = DAG.getConstant(CNV, CN->getValueType(0));
7516 SDValue NewOp2 = Result.getValue(isLoad ? 1 : 0);
7518 SDValue NewUse = DAG.getNode(Opcode,
7519 SDLoc(OtherUses[i]),
7520 OtherUses[i]->getValueType(0), NewOp1, NewOp2);
7521 DAG.ReplaceAllUsesOfValueWith(SDValue(OtherUses[i], 0), NewUse);
7522 removeFromWorkList(OtherUses[i]);
7523 DAG.DeleteNode(OtherUses[i]);
7526 // Replace the uses of Ptr with uses of the updated base value.
7527 DAG.ReplaceAllUsesOfValueWith(Ptr, Result.getValue(isLoad ? 1 : 0));
7528 removeFromWorkList(Ptr.getNode());
7529 DAG.DeleteNode(Ptr.getNode());
7534 /// CombineToPostIndexedLoadStore - Try to combine a load / store with a
7535 /// add / sub of the base pointer node into a post-indexed load / store.
7536 /// The transformation folded the add / subtract into the new indexed
7537 /// load / store effectively and all of its uses are redirected to the
7538 /// new load / store.
7539 bool DAGCombiner::CombineToPostIndexedLoadStore(SDNode *N) {
7540 if (Level < AfterLegalizeDAG)
7546 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
7547 if (LD->isIndexed())
7549 VT = LD->getMemoryVT();
7550 if (!TLI.isIndexedLoadLegal(ISD::POST_INC, VT) &&
7551 !TLI.isIndexedLoadLegal(ISD::POST_DEC, VT))
7553 Ptr = LD->getBasePtr();
7554 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
7555 if (ST->isIndexed())
7557 VT = ST->getMemoryVT();
7558 if (!TLI.isIndexedStoreLegal(ISD::POST_INC, VT) &&
7559 !TLI.isIndexedStoreLegal(ISD::POST_DEC, VT))
7561 Ptr = ST->getBasePtr();
7567 if (Ptr.getNode()->hasOneUse())
7570 for (SDNode::use_iterator I = Ptr.getNode()->use_begin(),
7571 E = Ptr.getNode()->use_end(); I != E; ++I) {
7574 (Op->getOpcode() != ISD::ADD && Op->getOpcode() != ISD::SUB))
7579 ISD::MemIndexedMode AM = ISD::UNINDEXED;
7580 if (TLI.getPostIndexedAddressParts(N, Op, BasePtr, Offset, AM, DAG)) {
7581 // Don't create a indexed load / store with zero offset.
7582 if (isa<ConstantSDNode>(Offset) &&
7583 cast<ConstantSDNode>(Offset)->isNullValue())
7586 // Try turning it into a post-indexed load / store except when
7587 // 1) All uses are load / store ops that use it as base ptr (and
7588 // it may be folded as addressing mmode).
7589 // 2) Op must be independent of N, i.e. Op is neither a predecessor
7590 // nor a successor of N. Otherwise, if Op is folded that would
7593 if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr))
7597 bool TryNext = false;
7598 for (SDNode::use_iterator II = BasePtr.getNode()->use_begin(),
7599 EE = BasePtr.getNode()->use_end(); II != EE; ++II) {
7601 if (Use == Ptr.getNode())
7604 // If all the uses are load / store addresses, then don't do the
7606 if (Use->getOpcode() == ISD::ADD || Use->getOpcode() == ISD::SUB){
7607 bool RealUse = false;
7608 for (SDNode::use_iterator III = Use->use_begin(),
7609 EEE = Use->use_end(); III != EEE; ++III) {
7610 SDNode *UseUse = *III;
7611 if (!canFoldInAddressingMode(Use, UseUse, DAG, TLI))
7626 if (!Op->isPredecessorOf(N) && !N->isPredecessorOf(Op)) {
7627 SDValue Result = isLoad
7628 ? DAG.getIndexedLoad(SDValue(N,0), SDLoc(N),
7629 BasePtr, Offset, AM)
7630 : DAG.getIndexedStore(SDValue(N,0), SDLoc(N),
7631 BasePtr, Offset, AM);
7634 DEBUG(dbgs() << "\nReplacing.5 ";
7636 dbgs() << "\nWith: ";
7637 Result.getNode()->dump(&DAG);
7639 WorkListRemover DeadNodes(*this);
7641 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0));
7642 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2));
7644 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1));
7647 // Finally, since the node is now dead, remove it from the graph.
7650 // Replace the uses of Use with uses of the updated base value.
7651 DAG.ReplaceAllUsesOfValueWith(SDValue(Op, 0),
7652 Result.getValue(isLoad ? 1 : 0));
7653 removeFromWorkList(Op);
7663 SDValue DAGCombiner::visitLOAD(SDNode *N) {
7664 LoadSDNode *LD = cast<LoadSDNode>(N);
7665 SDValue Chain = LD->getChain();
7666 SDValue Ptr = LD->getBasePtr();
7668 // If load is not volatile and there are no uses of the loaded value (and
7669 // the updated indexed value in case of indexed loads), change uses of the
7670 // chain value into uses of the chain input (i.e. delete the dead load).
7671 if (!LD->isVolatile()) {
7672 if (N->getValueType(1) == MVT::Other) {
7674 if (!N->hasAnyUseOfValue(0)) {
7675 // It's not safe to use the two value CombineTo variant here. e.g.
7676 // v1, chain2 = load chain1, loc
7677 // v2, chain3 = load chain2, loc
7679 // Now we replace use of chain2 with chain1. This makes the second load
7680 // isomorphic to the one we are deleting, and thus makes this load live.
7681 DEBUG(dbgs() << "\nReplacing.6 ";
7683 dbgs() << "\nWith chain: ";
7684 Chain.getNode()->dump(&DAG);
7686 WorkListRemover DeadNodes(*this);
7687 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain);
7689 if (N->use_empty()) {
7690 removeFromWorkList(N);
7694 return SDValue(N, 0); // Return N so it doesn't get rechecked!
7698 assert(N->getValueType(2) == MVT::Other && "Malformed indexed loads?");
7699 if (!N->hasAnyUseOfValue(0) && !N->hasAnyUseOfValue(1)) {
7700 SDValue Undef = DAG.getUNDEF(N->getValueType(0));
7701 DEBUG(dbgs() << "\nReplacing.7 ";
7703 dbgs() << "\nWith: ";
7704 Undef.getNode()->dump(&DAG);
7705 dbgs() << " and 2 other values\n");
7706 WorkListRemover DeadNodes(*this);
7707 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Undef);
7708 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1),
7709 DAG.getUNDEF(N->getValueType(1)));
7710 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 2), Chain);
7711 removeFromWorkList(N);
7713 return SDValue(N, 0); // Return N so it doesn't get rechecked!
7718 // If this load is directly stored, replace the load value with the stored
7720 // TODO: Handle store large -> read small portion.
7721 // TODO: Handle TRUNCSTORE/LOADEXT
7722 if (ISD::isNormalLoad(N) && !LD->isVolatile()) {
7723 if (ISD::isNON_TRUNCStore(Chain.getNode())) {
7724 StoreSDNode *PrevST = cast<StoreSDNode>(Chain);
7725 if (PrevST->getBasePtr() == Ptr &&
7726 PrevST->getValue().getValueType() == N->getValueType(0))
7727 return CombineTo(N, Chain.getOperand(1), Chain);
7731 // Try to infer better alignment information than the load already has.
7732 if (OptLevel != CodeGenOpt::None && LD->isUnindexed()) {
7733 if (unsigned Align = DAG.InferPtrAlignment(Ptr)) {
7734 if (Align > LD->getMemOperand()->getBaseAlignment()) {
7736 DAG.getExtLoad(LD->getExtensionType(), SDLoc(N),
7737 LD->getValueType(0),
7738 Chain, Ptr, LD->getPointerInfo(),
7740 LD->isVolatile(), LD->isNonTemporal(), Align,
7742 return CombineTo(N, NewLoad, SDValue(NewLoad.getNode(), 1), true);
7747 bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA :
7748 TLI.getTargetMachine().getSubtarget<TargetSubtargetInfo>().useAA();
7750 if (CombinerAAOnlyFunc.getNumOccurrences() &&
7751 CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
7754 if (UseAA && LD->isUnindexed()) {
7755 // Walk up chain skipping non-aliasing memory nodes.
7756 SDValue BetterChain = FindBetterChain(N, Chain);
7758 // If there is a better chain.
7759 if (Chain != BetterChain) {
7762 // Replace the chain to void dependency.
7763 if (LD->getExtensionType() == ISD::NON_EXTLOAD) {
7764 ReplLoad = DAG.getLoad(N->getValueType(0), SDLoc(LD),
7765 BetterChain, Ptr, LD->getMemOperand());
7767 ReplLoad = DAG.getExtLoad(LD->getExtensionType(), SDLoc(LD),
7768 LD->getValueType(0),
7769 BetterChain, Ptr, LD->getMemoryVT(),
7770 LD->getMemOperand());
7773 // Create token factor to keep old chain connected.
7774 SDValue Token = DAG.getNode(ISD::TokenFactor, SDLoc(N),
7775 MVT::Other, Chain, ReplLoad.getValue(1));
7777 // Make sure the new and old chains are cleaned up.
7778 AddToWorkList(Token.getNode());
7780 // Replace uses with load result and token factor. Don't add users
7782 return CombineTo(N, ReplLoad.getValue(0), Token, false);
7786 // Try transforming N to an indexed load.
7787 if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
7788 return SDValue(N, 0);
7790 // Try to slice up N to more direct loads if the slices are mapped to
7791 // different register banks or pairing can take place.
7793 return SDValue(N, 0);
7799 /// \brief Helper structure used to slice a load in smaller loads.
7800 /// Basically a slice is obtained from the following sequence:
7801 /// Origin = load Ty1, Base
7802 /// Shift = srl Ty1 Origin, CstTy Amount
7803 /// Inst = trunc Shift to Ty2
7805 /// Then, it will be rewriten into:
7806 /// Slice = load SliceTy, Base + SliceOffset
7807 /// [Inst = zext Slice to Ty2], only if SliceTy <> Ty2
7809 /// SliceTy is deduced from the number of bits that are actually used to
7811 struct LoadedSlice {
7812 /// \brief Helper structure used to compute the cost of a slice.
7814 /// Are we optimizing for code size.
7819 unsigned CrossRegisterBanksCopies;
7823 Cost(bool ForCodeSize = false)
7824 : ForCodeSize(ForCodeSize), Loads(0), Truncates(0),
7825 CrossRegisterBanksCopies(0), ZExts(0), Shift(0) {}
7827 /// \brief Get the cost of one isolated slice.
7828 Cost(const LoadedSlice &LS, bool ForCodeSize = false)
7829 : ForCodeSize(ForCodeSize), Loads(1), Truncates(0),
7830 CrossRegisterBanksCopies(0), ZExts(0), Shift(0) {
7831 EVT TruncType = LS.Inst->getValueType(0);
7832 EVT LoadedType = LS.getLoadedType();
7833 if (TruncType != LoadedType &&
7834 !LS.DAG->getTargetLoweringInfo().isZExtFree(LoadedType, TruncType))
7838 /// \brief Account for slicing gain in the current cost.
7839 /// Slicing provide a few gains like removing a shift or a
7840 /// truncate. This method allows to grow the cost of the original
7841 /// load with the gain from this slice.
7842 void addSliceGain(const LoadedSlice &LS) {
7843 // Each slice saves a truncate.
7844 const TargetLowering &TLI = LS.DAG->getTargetLoweringInfo();
7845 if (!TLI.isTruncateFree(LS.Inst->getValueType(0),
7846 LS.Inst->getOperand(0).getValueType()))
7848 // If there is a shift amount, this slice gets rid of it.
7851 // If this slice can merge a cross register bank copy, account for it.
7852 if (LS.canMergeExpensiveCrossRegisterBankCopy())
7853 ++CrossRegisterBanksCopies;
7856 Cost &operator+=(const Cost &RHS) {
7858 Truncates += RHS.Truncates;
7859 CrossRegisterBanksCopies += RHS.CrossRegisterBanksCopies;
7865 bool operator==(const Cost &RHS) const {
7866 return Loads == RHS.Loads && Truncates == RHS.Truncates &&
7867 CrossRegisterBanksCopies == RHS.CrossRegisterBanksCopies &&
7868 ZExts == RHS.ZExts && Shift == RHS.Shift;
7871 bool operator!=(const Cost &RHS) const { return !(*this == RHS); }
7873 bool operator<(const Cost &RHS) const {
7874 // Assume cross register banks copies are as expensive as loads.
7875 // FIXME: Do we want some more target hooks?
7876 unsigned ExpensiveOpsLHS = Loads + CrossRegisterBanksCopies;
7877 unsigned ExpensiveOpsRHS = RHS.Loads + RHS.CrossRegisterBanksCopies;
7878 // Unless we are optimizing for code size, consider the
7879 // expensive operation first.
7880 if (!ForCodeSize && ExpensiveOpsLHS != ExpensiveOpsRHS)
7881 return ExpensiveOpsLHS < ExpensiveOpsRHS;
7882 return (Truncates + ZExts + Shift + ExpensiveOpsLHS) <
7883 (RHS.Truncates + RHS.ZExts + RHS.Shift + ExpensiveOpsRHS);
7886 bool operator>(const Cost &RHS) const { return RHS < *this; }
7888 bool operator<=(const Cost &RHS) const { return !(RHS < *this); }
7890 bool operator>=(const Cost &RHS) const { return !(*this < RHS); }
7892 // The last instruction that represent the slice. This should be a
7893 // truncate instruction.
7895 // The original load instruction.
7897 // The right shift amount in bits from the original load.
7899 // The DAG from which Origin came from.
7900 // This is used to get some contextual information about legal types, etc.
7903 LoadedSlice(SDNode *Inst = NULL, LoadSDNode *Origin = NULL,
7904 unsigned Shift = 0, SelectionDAG *DAG = NULL)
7905 : Inst(Inst), Origin(Origin), Shift(Shift), DAG(DAG) {}
7907 LoadedSlice(const LoadedSlice &LS)
7908 : Inst(LS.Inst), Origin(LS.Origin), Shift(LS.Shift), DAG(LS.DAG) {}
7910 /// \brief Get the bits used in a chunk of bits \p BitWidth large.
7911 /// \return Result is \p BitWidth and has used bits set to 1 and
7912 /// not used bits set to 0.
7913 APInt getUsedBits() const {
7914 // Reproduce the trunc(lshr) sequence:
7915 // - Start from the truncated value.
7916 // - Zero extend to the desired bit width.
7918 assert(Origin && "No original load to compare against.");
7919 unsigned BitWidth = Origin->getValueSizeInBits(0);
7920 assert(Inst && "This slice is not bound to an instruction");
7921 assert(Inst->getValueSizeInBits(0) <= BitWidth &&
7922 "Extracted slice is bigger than the whole type!");
7923 APInt UsedBits(Inst->getValueSizeInBits(0), 0);
7924 UsedBits.setAllBits();
7925 UsedBits = UsedBits.zext(BitWidth);
7930 /// \brief Get the size of the slice to be loaded in bytes.
7931 unsigned getLoadedSize() const {
7932 unsigned SliceSize = getUsedBits().countPopulation();
7933 assert(!(SliceSize & 0x7) && "Size is not a multiple of a byte.");
7934 return SliceSize / 8;
7937 /// \brief Get the type that will be loaded for this slice.
7938 /// Note: This may not be the final type for the slice.
7939 EVT getLoadedType() const {
7940 assert(DAG && "Missing context");
7941 LLVMContext &Ctxt = *DAG->getContext();
7942 return EVT::getIntegerVT(Ctxt, getLoadedSize() * 8);
7945 /// \brief Get the alignment of the load used for this slice.
7946 unsigned getAlignment() const {
7947 unsigned Alignment = Origin->getAlignment();
7948 unsigned Offset = getOffsetFromBase();
7950 Alignment = MinAlign(Alignment, Alignment + Offset);
7954 /// \brief Check if this slice can be rewritten with legal operations.
7955 bool isLegal() const {
7956 // An invalid slice is not legal.
7957 if (!Origin || !Inst || !DAG)
7960 // Offsets are for indexed load only, we do not handle that.
7961 if (Origin->getOffset().getOpcode() != ISD::UNDEF)
7964 const TargetLowering &TLI = DAG->getTargetLoweringInfo();
7966 // Check that the type is legal.
7967 EVT SliceType = getLoadedType();
7968 if (!TLI.isTypeLegal(SliceType))
7971 // Check that the load is legal for this type.
7972 if (!TLI.isOperationLegal(ISD::LOAD, SliceType))
7975 // Check that the offset can be computed.
7976 // 1. Check its type.
7977 EVT PtrType = Origin->getBasePtr().getValueType();
7978 if (PtrType == MVT::Untyped || PtrType.isExtended())
7981 // 2. Check that it fits in the immediate.
7982 if (!TLI.isLegalAddImmediate(getOffsetFromBase()))
7985 // 3. Check that the computation is legal.
7986 if (!TLI.isOperationLegal(ISD::ADD, PtrType))
7989 // Check that the zext is legal if it needs one.
7990 EVT TruncateType = Inst->getValueType(0);
7991 if (TruncateType != SliceType &&
7992 !TLI.isOperationLegal(ISD::ZERO_EXTEND, TruncateType))
7998 /// \brief Get the offset in bytes of this slice in the original chunk of
8000 /// \pre DAG != NULL.
8001 uint64_t getOffsetFromBase() const {
8002 assert(DAG && "Missing context.");
8004 DAG->getTargetLoweringInfo().getDataLayout()->isBigEndian();
8005 assert(!(Shift & 0x7) && "Shifts not aligned on Bytes are not supported.");
8006 uint64_t Offset = Shift / 8;
8007 unsigned TySizeInBytes = Origin->getValueSizeInBits(0) / 8;
8008 assert(!(Origin->getValueSizeInBits(0) & 0x7) &&
8009 "The size of the original loaded type is not a multiple of a"
8011 // If Offset is bigger than TySizeInBytes, it means we are loading all
8012 // zeros. This should have been optimized before in the process.
8013 assert(TySizeInBytes > Offset &&
8014 "Invalid shift amount for given loaded size");
8016 Offset = TySizeInBytes - Offset - getLoadedSize();
8020 /// \brief Generate the sequence of instructions to load the slice
8021 /// represented by this object and redirect the uses of this slice to
8022 /// this new sequence of instructions.
8023 /// \pre this->Inst && this->Origin are valid Instructions and this
8024 /// object passed the legal check: LoadedSlice::isLegal returned true.
8025 /// \return The last instruction of the sequence used to load the slice.
8026 SDValue loadSlice() const {
8027 assert(Inst && Origin && "Unable to replace a non-existing slice.");
8028 const SDValue &OldBaseAddr = Origin->getBasePtr();
8029 SDValue BaseAddr = OldBaseAddr;
8030 // Get the offset in that chunk of bytes w.r.t. the endianess.
8031 int64_t Offset = static_cast<int64_t>(getOffsetFromBase());
8032 assert(Offset >= 0 && "Offset too big to fit in int64_t!");
8034 // BaseAddr = BaseAddr + Offset.
8035 EVT ArithType = BaseAddr.getValueType();
8036 BaseAddr = DAG->getNode(ISD::ADD, SDLoc(Origin), ArithType, BaseAddr,
8037 DAG->getConstant(Offset, ArithType));
8040 // Create the type of the loaded slice according to its size.
8041 EVT SliceType = getLoadedType();
8043 // Create the load for the slice.
8044 SDValue LastInst = DAG->getLoad(
8045 SliceType, SDLoc(Origin), Origin->getChain(), BaseAddr,
8046 Origin->getPointerInfo().getWithOffset(Offset), Origin->isVolatile(),
8047 Origin->isNonTemporal(), Origin->isInvariant(), getAlignment());
8048 // If the final type is not the same as the loaded type, this means that
8049 // we have to pad with zero. Create a zero extend for that.
8050 EVT FinalType = Inst->getValueType(0);
8051 if (SliceType != FinalType)
8053 DAG->getNode(ISD::ZERO_EXTEND, SDLoc(LastInst), FinalType, LastInst);
8057 /// \brief Check if this slice can be merged with an expensive cross register
8058 /// bank copy. E.g.,
8060 /// f = bitcast i32 i to float
8061 bool canMergeExpensiveCrossRegisterBankCopy() const {
8062 if (!Inst || !Inst->hasOneUse())
8064 SDNode *Use = *Inst->use_begin();
8065 if (Use->getOpcode() != ISD::BITCAST)
8067 assert(DAG && "Missing context");
8068 const TargetLowering &TLI = DAG->getTargetLoweringInfo();
8069 EVT ResVT = Use->getValueType(0);
8070 const TargetRegisterClass *ResRC = TLI.getRegClassFor(ResVT.getSimpleVT());
8071 const TargetRegisterClass *ArgRC =
8072 TLI.getRegClassFor(Use->getOperand(0).getValueType().getSimpleVT());
8073 if (ArgRC == ResRC || !TLI.isOperationLegal(ISD::LOAD, ResVT))
8076 // At this point, we know that we perform a cross-register-bank copy.
8077 // Check if it is expensive.
8078 const TargetRegisterInfo *TRI = TLI.getTargetMachine().getRegisterInfo();
8079 // Assume bitcasts are cheap, unless both register classes do not
8080 // explicitly share a common sub class.
8081 if (!TRI || TRI->getCommonSubClass(ArgRC, ResRC))
8084 // Check if it will be merged with the load.
8085 // 1. Check the alignment constraint.
8086 unsigned RequiredAlignment = TLI.getDataLayout()->getABITypeAlignment(
8087 ResVT.getTypeForEVT(*DAG->getContext()));
8089 if (RequiredAlignment > getAlignment())
8092 // 2. Check that the load is a legal operation for that type.
8093 if (!TLI.isOperationLegal(ISD::LOAD, ResVT))
8096 // 3. Check that we do not have a zext in the way.
8097 if (Inst->getValueType(0) != getLoadedType())
8105 /// \brief Sorts LoadedSlice according to their offset.
8106 struct LoadedSliceSorter {
8107 bool operator()(const LoadedSlice &LHS, const LoadedSlice &RHS) {
8108 assert(LHS.Origin == RHS.Origin && "Different bases not implemented.");
8109 return LHS.getOffsetFromBase() < RHS.getOffsetFromBase();
8113 /// \brief Check that all bits set in \p UsedBits form a dense region, i.e.,
8114 /// \p UsedBits looks like 0..0 1..1 0..0.
8115 static bool areUsedBitsDense(const APInt &UsedBits) {
8116 // If all the bits are one, this is dense!
8117 if (UsedBits.isAllOnesValue())
8120 // Get rid of the unused bits on the right.
8121 APInt NarrowedUsedBits = UsedBits.lshr(UsedBits.countTrailingZeros());
8122 // Get rid of the unused bits on the left.
8123 if (NarrowedUsedBits.countLeadingZeros())
8124 NarrowedUsedBits = NarrowedUsedBits.trunc(NarrowedUsedBits.getActiveBits());
8125 // Check that the chunk of bits is completely used.
8126 return NarrowedUsedBits.isAllOnesValue();
8129 /// \brief Check whether or not \p First and \p Second are next to each other
8130 /// in memory. This means that there is no hole between the bits loaded
8131 /// by \p First and the bits loaded by \p Second.
8132 static bool areSlicesNextToEachOther(const LoadedSlice &First,
8133 const LoadedSlice &Second) {
8134 assert(First.Origin == Second.Origin && First.Origin &&
8135 "Unable to match different memory origins.");
8136 APInt UsedBits = First.getUsedBits();
8137 assert((UsedBits & Second.getUsedBits()) == 0 &&
8138 "Slices are not supposed to overlap.");
8139 UsedBits |= Second.getUsedBits();
8140 return areUsedBitsDense(UsedBits);
8143 /// \brief Adjust the \p GlobalLSCost according to the target
8144 /// paring capabilities and the layout of the slices.
8145 /// \pre \p GlobalLSCost should account for at least as many loads as
8146 /// there is in the slices in \p LoadedSlices.
8147 static void adjustCostForPairing(SmallVectorImpl<LoadedSlice> &LoadedSlices,
8148 LoadedSlice::Cost &GlobalLSCost) {
8149 unsigned NumberOfSlices = LoadedSlices.size();
8150 // If there is less than 2 elements, no pairing is possible.
8151 if (NumberOfSlices < 2)
8154 // Sort the slices so that elements that are likely to be next to each
8155 // other in memory are next to each other in the list.
8156 std::sort(LoadedSlices.begin(), LoadedSlices.end(), LoadedSliceSorter());
8157 const TargetLowering &TLI = LoadedSlices[0].DAG->getTargetLoweringInfo();
8158 // First (resp. Second) is the first (resp. Second) potentially candidate
8159 // to be placed in a paired load.
8160 const LoadedSlice *First = NULL;
8161 const LoadedSlice *Second = NULL;
8162 for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice,
8163 // Set the beginning of the pair.
8166 Second = &LoadedSlices[CurrSlice];
8168 // If First is NULL, it means we start a new pair.
8169 // Get to the next slice.
8173 EVT LoadedType = First->getLoadedType();
8175 // If the types of the slices are different, we cannot pair them.
8176 if (LoadedType != Second->getLoadedType())
8179 // Check if the target supplies paired loads for this type.
8180 unsigned RequiredAlignment = 0;
8181 if (!TLI.hasPairedLoad(LoadedType, RequiredAlignment)) {
8182 // move to the next pair, this type is hopeless.
8186 // Check if we meet the alignment requirement.
8187 if (RequiredAlignment > First->getAlignment())
8190 // Check that both loads are next to each other in memory.
8191 if (!areSlicesNextToEachOther(*First, *Second))
8194 assert(GlobalLSCost.Loads > 0 && "We save more loads than we created!");
8195 --GlobalLSCost.Loads;
8196 // Move to the next pair.
8201 /// \brief Check the profitability of all involved LoadedSlice.
8202 /// Currently, it is considered profitable if there is exactly two
8203 /// involved slices (1) which are (2) next to each other in memory, and
8204 /// whose cost (\see LoadedSlice::Cost) is smaller than the original load (3).
8206 /// Note: The order of the elements in \p LoadedSlices may be modified, but not
8207 /// the elements themselves.
8209 /// FIXME: When the cost model will be mature enough, we can relax
8210 /// constraints (1) and (2).
8211 static bool isSlicingProfitable(SmallVectorImpl<LoadedSlice> &LoadedSlices,
8212 const APInt &UsedBits, bool ForCodeSize) {
8213 unsigned NumberOfSlices = LoadedSlices.size();
8214 if (StressLoadSlicing)
8215 return NumberOfSlices > 1;
8218 if (NumberOfSlices != 2)
8222 if (!areUsedBitsDense(UsedBits))
8226 LoadedSlice::Cost OrigCost(ForCodeSize), GlobalSlicingCost(ForCodeSize);
8227 // The original code has one big load.
8229 for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice) {
8230 const LoadedSlice &LS = LoadedSlices[CurrSlice];
8231 // Accumulate the cost of all the slices.
8232 LoadedSlice::Cost SliceCost(LS, ForCodeSize);
8233 GlobalSlicingCost += SliceCost;
8235 // Account as cost in the original configuration the gain obtained
8236 // with the current slices.
8237 OrigCost.addSliceGain(LS);
8240 // If the target supports paired load, adjust the cost accordingly.
8241 adjustCostForPairing(LoadedSlices, GlobalSlicingCost);
8242 return OrigCost > GlobalSlicingCost;
8245 /// \brief If the given load, \p LI, is used only by trunc or trunc(lshr)
8246 /// operations, split it in the various pieces being extracted.
8248 /// This sort of thing is introduced by SROA.
8249 /// This slicing takes care not to insert overlapping loads.
8250 /// \pre LI is a simple load (i.e., not an atomic or volatile load).
8251 bool DAGCombiner::SliceUpLoad(SDNode *N) {
8252 if (Level < AfterLegalizeDAG)
8255 LoadSDNode *LD = cast<LoadSDNode>(N);
8256 if (LD->isVolatile() || !ISD::isNormalLoad(LD) ||
8257 !LD->getValueType(0).isInteger())
8260 // Keep track of already used bits to detect overlapping values.
8261 // In that case, we will just abort the transformation.
8262 APInt UsedBits(LD->getValueSizeInBits(0), 0);
8264 SmallVector<LoadedSlice, 4> LoadedSlices;
8266 // Check if this load is used as several smaller chunks of bits.
8267 // Basically, look for uses in trunc or trunc(lshr) and record a new chain
8268 // of computation for each trunc.
8269 for (SDNode::use_iterator UI = LD->use_begin(), UIEnd = LD->use_end();
8270 UI != UIEnd; ++UI) {
8271 // Skip the uses of the chain.
8272 if (UI.getUse().getResNo() != 0)
8278 // Check if this is a trunc(lshr).
8279 if (User->getOpcode() == ISD::SRL && User->hasOneUse() &&
8280 isa<ConstantSDNode>(User->getOperand(1))) {
8281 Shift = cast<ConstantSDNode>(User->getOperand(1))->getZExtValue();
8282 User = *User->use_begin();
8285 // At this point, User is a Truncate, iff we encountered, trunc or
8287 if (User->getOpcode() != ISD::TRUNCATE)
8290 // The width of the type must be a power of 2 and greater than 8-bits.
8291 // Otherwise the load cannot be represented in LLVM IR.
8292 // Moreover, if we shifted with a non-8-bits multiple, the slice
8293 // will be across several bytes. We do not support that.
8294 unsigned Width = User->getValueSizeInBits(0);
8295 if (Width < 8 || !isPowerOf2_32(Width) || (Shift & 0x7))
8298 // Build the slice for this chain of computations.
8299 LoadedSlice LS(User, LD, Shift, &DAG);
8300 APInt CurrentUsedBits = LS.getUsedBits();
8302 // Check if this slice overlaps with another.
8303 if ((CurrentUsedBits & UsedBits) != 0)
8305 // Update the bits used globally.
8306 UsedBits |= CurrentUsedBits;
8308 // Check if the new slice would be legal.
8312 // Record the slice.
8313 LoadedSlices.push_back(LS);
8316 // Abort slicing if it does not seem to be profitable.
8317 if (!isSlicingProfitable(LoadedSlices, UsedBits, ForCodeSize))
8322 // Rewrite each chain to use an independent load.
8323 // By construction, each chain can be represented by a unique load.
8325 // Prepare the argument for the new token factor for all the slices.
8326 SmallVector<SDValue, 8> ArgChains;
8327 for (SmallVectorImpl<LoadedSlice>::const_iterator
8328 LSIt = LoadedSlices.begin(),
8329 LSItEnd = LoadedSlices.end();
8330 LSIt != LSItEnd; ++LSIt) {
8331 SDValue SliceInst = LSIt->loadSlice();
8332 CombineTo(LSIt->Inst, SliceInst, true);
8333 if (SliceInst.getNode()->getOpcode() != ISD::LOAD)
8334 SliceInst = SliceInst.getOperand(0);
8335 assert(SliceInst->getOpcode() == ISD::LOAD &&
8336 "It takes more than a zext to get to the loaded slice!!");
8337 ArgChains.push_back(SliceInst.getValue(1));
8340 SDValue Chain = DAG.getNode(ISD::TokenFactor, SDLoc(LD), MVT::Other,
8341 &ArgChains[0], ArgChains.size());
8342 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain);
8346 /// CheckForMaskedLoad - Check to see if V is (and load (ptr), imm), where the
8347 /// load is having specific bytes cleared out. If so, return the byte size
8348 /// being masked out and the shift amount.
8349 static std::pair<unsigned, unsigned>
8350 CheckForMaskedLoad(SDValue V, SDValue Ptr, SDValue Chain) {
8351 std::pair<unsigned, unsigned> Result(0, 0);
8353 // Check for the structure we're looking for.
8354 if (V->getOpcode() != ISD::AND ||
8355 !isa<ConstantSDNode>(V->getOperand(1)) ||
8356 !ISD::isNormalLoad(V->getOperand(0).getNode()))
8359 // Check the chain and pointer.
8360 LoadSDNode *LD = cast<LoadSDNode>(V->getOperand(0));
8361 if (LD->getBasePtr() != Ptr) return Result; // Not from same pointer.
8363 // The store should be chained directly to the load or be an operand of a
8365 if (LD == Chain.getNode())
8367 else if (Chain->getOpcode() != ISD::TokenFactor)
8368 return Result; // Fail.
8371 for (unsigned i = 0, e = Chain->getNumOperands(); i != e; ++i)
8372 if (Chain->getOperand(i).getNode() == LD) {
8376 if (!isOk) return Result;
8379 // This only handles simple types.
8380 if (V.getValueType() != MVT::i16 &&
8381 V.getValueType() != MVT::i32 &&
8382 V.getValueType() != MVT::i64)
8385 // Check the constant mask. Invert it so that the bits being masked out are
8386 // 0 and the bits being kept are 1. Use getSExtValue so that leading bits
8387 // follow the sign bit for uniformity.
8388 uint64_t NotMask = ~cast<ConstantSDNode>(V->getOperand(1))->getSExtValue();
8389 unsigned NotMaskLZ = countLeadingZeros(NotMask);
8390 if (NotMaskLZ & 7) return Result; // Must be multiple of a byte.
8391 unsigned NotMaskTZ = countTrailingZeros(NotMask);
8392 if (NotMaskTZ & 7) return Result; // Must be multiple of a byte.
8393 if (NotMaskLZ == 64) return Result; // All zero mask.
8395 // See if we have a continuous run of bits. If so, we have 0*1+0*
8396 if (CountTrailingOnes_64(NotMask >> NotMaskTZ)+NotMaskTZ+NotMaskLZ != 64)
8399 // Adjust NotMaskLZ down to be from the actual size of the int instead of i64.
8400 if (V.getValueType() != MVT::i64 && NotMaskLZ)
8401 NotMaskLZ -= 64-V.getValueSizeInBits();
8403 unsigned MaskedBytes = (V.getValueSizeInBits()-NotMaskLZ-NotMaskTZ)/8;
8404 switch (MaskedBytes) {
8408 default: return Result; // All one mask, or 5-byte mask.
8411 // Verify that the first bit starts at a multiple of mask so that the access
8412 // is aligned the same as the access width.
8413 if (NotMaskTZ && NotMaskTZ/8 % MaskedBytes) return Result;
8415 Result.first = MaskedBytes;
8416 Result.second = NotMaskTZ/8;
8421 /// ShrinkLoadReplaceStoreWithStore - Check to see if IVal is something that
8422 /// provides a value as specified by MaskInfo. If so, replace the specified
8423 /// store with a narrower store of truncated IVal.
8425 ShrinkLoadReplaceStoreWithStore(const std::pair<unsigned, unsigned> &MaskInfo,
8426 SDValue IVal, StoreSDNode *St,
8428 unsigned NumBytes = MaskInfo.first;
8429 unsigned ByteShift = MaskInfo.second;
8430 SelectionDAG &DAG = DC->getDAG();
8432 // Check to see if IVal is all zeros in the part being masked in by the 'or'
8433 // that uses this. If not, this is not a replacement.
8434 APInt Mask = ~APInt::getBitsSet(IVal.getValueSizeInBits(),
8435 ByteShift*8, (ByteShift+NumBytes)*8);
8436 if (!DAG.MaskedValueIsZero(IVal, Mask)) return 0;
8438 // Check that it is legal on the target to do this. It is legal if the new
8439 // VT we're shrinking to (i8/i16/i32) is legal or we're still before type
8441 MVT VT = MVT::getIntegerVT(NumBytes*8);
8442 if (!DC->isTypeLegal(VT))
8445 // Okay, we can do this! Replace the 'St' store with a store of IVal that is
8446 // shifted by ByteShift and truncated down to NumBytes.
8448 IVal = DAG.getNode(ISD::SRL, SDLoc(IVal), IVal.getValueType(), IVal,
8449 DAG.getConstant(ByteShift*8,
8450 DC->getShiftAmountTy(IVal.getValueType())));
8452 // Figure out the offset for the store and the alignment of the access.
8454 unsigned NewAlign = St->getAlignment();
8456 if (DAG.getTargetLoweringInfo().isLittleEndian())
8457 StOffset = ByteShift;
8459 StOffset = IVal.getValueType().getStoreSize() - ByteShift - NumBytes;
8461 SDValue Ptr = St->getBasePtr();
8463 Ptr = DAG.getNode(ISD::ADD, SDLoc(IVal), Ptr.getValueType(),
8464 Ptr, DAG.getConstant(StOffset, Ptr.getValueType()));
8465 NewAlign = MinAlign(NewAlign, StOffset);
8468 // Truncate down to the new size.
8469 IVal = DAG.getNode(ISD::TRUNCATE, SDLoc(IVal), VT, IVal);
8472 return DAG.getStore(St->getChain(), SDLoc(St), IVal, Ptr,
8473 St->getPointerInfo().getWithOffset(StOffset),
8474 false, false, NewAlign).getNode();
8478 /// ReduceLoadOpStoreWidth - Look for sequence of load / op / store where op is
8479 /// one of 'or', 'xor', and 'and' of immediates. If 'op' is only touching some
8480 /// of the loaded bits, try narrowing the load and store if it would end up
8481 /// being a win for performance or code size.
8482 SDValue DAGCombiner::ReduceLoadOpStoreWidth(SDNode *N) {
8483 StoreSDNode *ST = cast<StoreSDNode>(N);
8484 if (ST->isVolatile())
8487 SDValue Chain = ST->getChain();
8488 SDValue Value = ST->getValue();
8489 SDValue Ptr = ST->getBasePtr();
8490 EVT VT = Value.getValueType();
8492 if (ST->isTruncatingStore() || VT.isVector() || !Value.hasOneUse())
8495 unsigned Opc = Value.getOpcode();
8497 // If this is "store (or X, Y), P" and X is "(and (load P), cst)", where cst
8498 // is a byte mask indicating a consecutive number of bytes, check to see if
8499 // Y is known to provide just those bytes. If so, we try to replace the
8500 // load + replace + store sequence with a single (narrower) store, which makes
8502 if (Opc == ISD::OR) {
8503 std::pair<unsigned, unsigned> MaskedLoad;
8504 MaskedLoad = CheckForMaskedLoad(Value.getOperand(0), Ptr, Chain);
8505 if (MaskedLoad.first)
8506 if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad,
8507 Value.getOperand(1), ST,this))
8508 return SDValue(NewST, 0);
8510 // Or is commutative, so try swapping X and Y.
8511 MaskedLoad = CheckForMaskedLoad(Value.getOperand(1), Ptr, Chain);
8512 if (MaskedLoad.first)
8513 if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad,
8514 Value.getOperand(0), ST,this))
8515 return SDValue(NewST, 0);
8518 if ((Opc != ISD::OR && Opc != ISD::XOR && Opc != ISD::AND) ||
8519 Value.getOperand(1).getOpcode() != ISD::Constant)
8522 SDValue N0 = Value.getOperand(0);
8523 if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
8524 Chain == SDValue(N0.getNode(), 1)) {
8525 LoadSDNode *LD = cast<LoadSDNode>(N0);
8526 if (LD->getBasePtr() != Ptr ||
8527 LD->getPointerInfo().getAddrSpace() !=
8528 ST->getPointerInfo().getAddrSpace())
8531 // Find the type to narrow it the load / op / store to.
8532 SDValue N1 = Value.getOperand(1);
8533 unsigned BitWidth = N1.getValueSizeInBits();
8534 APInt Imm = cast<ConstantSDNode>(N1)->getAPIntValue();
8535 if (Opc == ISD::AND)
8536 Imm ^= APInt::getAllOnesValue(BitWidth);
8537 if (Imm == 0 || Imm.isAllOnesValue())
8539 unsigned ShAmt = Imm.countTrailingZeros();
8540 unsigned MSB = BitWidth - Imm.countLeadingZeros() - 1;
8541 unsigned NewBW = NextPowerOf2(MSB - ShAmt);
8542 EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW);
8543 while (NewBW < BitWidth &&
8544 !(TLI.isOperationLegalOrCustom(Opc, NewVT) &&
8545 TLI.isNarrowingProfitable(VT, NewVT))) {
8546 NewBW = NextPowerOf2(NewBW);
8547 NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW);
8549 if (NewBW >= BitWidth)
8552 // If the lsb changed does not start at the type bitwidth boundary,
8553 // start at the previous one.
8555 ShAmt = (((ShAmt + NewBW - 1) / NewBW) * NewBW) - NewBW;
8556 APInt Mask = APInt::getBitsSet(BitWidth, ShAmt,
8557 std::min(BitWidth, ShAmt + NewBW));
8558 if ((Imm & Mask) == Imm) {
8559 APInt NewImm = (Imm & Mask).lshr(ShAmt).trunc(NewBW);
8560 if (Opc == ISD::AND)
8561 NewImm ^= APInt::getAllOnesValue(NewBW);
8562 uint64_t PtrOff = ShAmt / 8;
8563 // For big endian targets, we need to adjust the offset to the pointer to
8564 // load the correct bytes.
8565 if (TLI.isBigEndian())
8566 PtrOff = (BitWidth + 7 - NewBW) / 8 - PtrOff;
8568 unsigned NewAlign = MinAlign(LD->getAlignment(), PtrOff);
8569 Type *NewVTTy = NewVT.getTypeForEVT(*DAG.getContext());
8570 if (NewAlign < TLI.getDataLayout()->getABITypeAlignment(NewVTTy))
8573 SDValue NewPtr = DAG.getNode(ISD::ADD, SDLoc(LD),
8574 Ptr.getValueType(), Ptr,
8575 DAG.getConstant(PtrOff, Ptr.getValueType()));
8576 SDValue NewLD = DAG.getLoad(NewVT, SDLoc(N0),
8577 LD->getChain(), NewPtr,
8578 LD->getPointerInfo().getWithOffset(PtrOff),
8579 LD->isVolatile(), LD->isNonTemporal(),
8580 LD->isInvariant(), NewAlign,
8582 SDValue NewVal = DAG.getNode(Opc, SDLoc(Value), NewVT, NewLD,
8583 DAG.getConstant(NewImm, NewVT));
8584 SDValue NewST = DAG.getStore(Chain, SDLoc(N),
8586 ST->getPointerInfo().getWithOffset(PtrOff),
8587 false, false, NewAlign);
8589 AddToWorkList(NewPtr.getNode());
8590 AddToWorkList(NewLD.getNode());
8591 AddToWorkList(NewVal.getNode());
8592 WorkListRemover DeadNodes(*this);
8593 DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLD.getValue(1));
8602 /// TransformFPLoadStorePair - For a given floating point load / store pair,
8603 /// if the load value isn't used by any other operations, then consider
8604 /// transforming the pair to integer load / store operations if the target
8605 /// deems the transformation profitable.
8606 SDValue DAGCombiner::TransformFPLoadStorePair(SDNode *N) {
8607 StoreSDNode *ST = cast<StoreSDNode>(N);
8608 SDValue Chain = ST->getChain();
8609 SDValue Value = ST->getValue();
8610 if (ISD::isNormalStore(ST) && ISD::isNormalLoad(Value.getNode()) &&
8611 Value.hasOneUse() &&
8612 Chain == SDValue(Value.getNode(), 1)) {
8613 LoadSDNode *LD = cast<LoadSDNode>(Value);
8614 EVT VT = LD->getMemoryVT();
8615 if (!VT.isFloatingPoint() ||
8616 VT != ST->getMemoryVT() ||
8617 LD->isNonTemporal() ||
8618 ST->isNonTemporal() ||
8619 LD->getPointerInfo().getAddrSpace() != 0 ||
8620 ST->getPointerInfo().getAddrSpace() != 0)
8623 EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), VT.getSizeInBits());
8624 if (!TLI.isOperationLegal(ISD::LOAD, IntVT) ||
8625 !TLI.isOperationLegal(ISD::STORE, IntVT) ||
8626 !TLI.isDesirableToTransformToIntegerOp(ISD::LOAD, VT) ||
8627 !TLI.isDesirableToTransformToIntegerOp(ISD::STORE, VT))
8630 unsigned LDAlign = LD->getAlignment();
8631 unsigned STAlign = ST->getAlignment();
8632 Type *IntVTTy = IntVT.getTypeForEVT(*DAG.getContext());
8633 unsigned ABIAlign = TLI.getDataLayout()->getABITypeAlignment(IntVTTy);
8634 if (LDAlign < ABIAlign || STAlign < ABIAlign)
8637 SDValue NewLD = DAG.getLoad(IntVT, SDLoc(Value),
8638 LD->getChain(), LD->getBasePtr(),
8639 LD->getPointerInfo(),
8640 false, false, false, LDAlign);
8642 SDValue NewST = DAG.getStore(NewLD.getValue(1), SDLoc(N),
8643 NewLD, ST->getBasePtr(),
8644 ST->getPointerInfo(),
8645 false, false, STAlign);
8647 AddToWorkList(NewLD.getNode());
8648 AddToWorkList(NewST.getNode());
8649 WorkListRemover DeadNodes(*this);
8650 DAG.ReplaceAllUsesOfValueWith(Value.getValue(1), NewLD.getValue(1));
8658 /// Helper struct to parse and store a memory address as base + index + offset.
8659 /// We ignore sign extensions when it is safe to do so.
8660 /// The following two expressions are not equivalent. To differentiate we need
8661 /// to store whether there was a sign extension involved in the index
8663 /// (load (i64 add (i64 copyfromreg %c)
8664 /// (i64 signextend (add (i8 load %index)
8668 /// (load (i64 add (i64 copyfromreg %c)
8669 /// (i64 signextend (i32 add (i32 signextend (i8 load %index))
8671 struct BaseIndexOffset {
8675 bool IsIndexSignExt;
8677 BaseIndexOffset() : Offset(0), IsIndexSignExt(false) {}
8679 BaseIndexOffset(SDValue Base, SDValue Index, int64_t Offset,
8680 bool IsIndexSignExt) :
8681 Base(Base), Index(Index), Offset(Offset), IsIndexSignExt(IsIndexSignExt) {}
8683 bool equalBaseIndex(const BaseIndexOffset &Other) {
8684 return Other.Base == Base && Other.Index == Index &&
8685 Other.IsIndexSignExt == IsIndexSignExt;
8688 /// Parses tree in Ptr for base, index, offset addresses.
8689 static BaseIndexOffset match(SDValue Ptr) {
8690 bool IsIndexSignExt = false;
8692 // We only can pattern match BASE + INDEX + OFFSET. If Ptr is not an ADD
8693 // instruction, then it could be just the BASE or everything else we don't
8694 // know how to handle. Just use Ptr as BASE and give up.
8695 if (Ptr->getOpcode() != ISD::ADD)
8696 return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
8698 // We know that we have at least an ADD instruction. Try to pattern match
8699 // the simple case of BASE + OFFSET.
8700 if (isa<ConstantSDNode>(Ptr->getOperand(1))) {
8701 int64_t Offset = cast<ConstantSDNode>(Ptr->getOperand(1))->getSExtValue();
8702 return BaseIndexOffset(Ptr->getOperand(0), SDValue(), Offset,
8706 // Inside a loop the current BASE pointer is calculated using an ADD and a
8707 // MUL instruction. In this case Ptr is the actual BASE pointer.
8708 // (i64 add (i64 %array_ptr)
8709 // (i64 mul (i64 %induction_var)
8710 // (i64 %element_size)))
8711 if (Ptr->getOperand(1)->getOpcode() == ISD::MUL)
8712 return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
8714 // Look at Base + Index + Offset cases.
8715 SDValue Base = Ptr->getOperand(0);
8716 SDValue IndexOffset = Ptr->getOperand(1);
8718 // Skip signextends.
8719 if (IndexOffset->getOpcode() == ISD::SIGN_EXTEND) {
8720 IndexOffset = IndexOffset->getOperand(0);
8721 IsIndexSignExt = true;
8724 // Either the case of Base + Index (no offset) or something else.
8725 if (IndexOffset->getOpcode() != ISD::ADD)
8726 return BaseIndexOffset(Base, IndexOffset, 0, IsIndexSignExt);
8728 // Now we have the case of Base + Index + offset.
8729 SDValue Index = IndexOffset->getOperand(0);
8730 SDValue Offset = IndexOffset->getOperand(1);
8732 if (!isa<ConstantSDNode>(Offset))
8733 return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
8735 // Ignore signextends.
8736 if (Index->getOpcode() == ISD::SIGN_EXTEND) {
8737 Index = Index->getOperand(0);
8738 IsIndexSignExt = true;
8739 } else IsIndexSignExt = false;
8741 int64_t Off = cast<ConstantSDNode>(Offset)->getSExtValue();
8742 return BaseIndexOffset(Base, Index, Off, IsIndexSignExt);
8746 /// Holds a pointer to an LSBaseSDNode as well as information on where it
8747 /// is located in a sequence of memory operations connected by a chain.
8749 MemOpLink (LSBaseSDNode *N, int64_t Offset, unsigned Seq):
8750 MemNode(N), OffsetFromBase(Offset), SequenceNum(Seq) { }
8751 // Ptr to the mem node.
8752 LSBaseSDNode *MemNode;
8753 // Offset from the base ptr.
8754 int64_t OffsetFromBase;
8755 // What is the sequence number of this mem node.
8756 // Lowest mem operand in the DAG starts at zero.
8757 unsigned SequenceNum;
8760 /// Sorts store nodes in a link according to their offset from a shared
8762 struct ConsecutiveMemoryChainSorter {
8763 bool operator()(MemOpLink LHS, MemOpLink RHS) {
8764 return LHS.OffsetFromBase < RHS.OffsetFromBase;
8768 bool DAGCombiner::MergeConsecutiveStores(StoreSDNode* St) {
8769 EVT MemVT = St->getMemoryVT();
8770 int64_t ElementSizeBytes = MemVT.getSizeInBits()/8;
8771 bool NoVectors = DAG.getMachineFunction().getFunction()->getAttributes().
8772 hasAttribute(AttributeSet::FunctionIndex, Attribute::NoImplicitFloat);
8774 // Don't merge vectors into wider inputs.
8775 if (MemVT.isVector() || !MemVT.isSimple())
8778 // Perform an early exit check. Do not bother looking at stored values that
8779 // are not constants or loads.
8780 SDValue StoredVal = St->getValue();
8781 bool IsLoadSrc = isa<LoadSDNode>(StoredVal);
8782 if (!isa<ConstantSDNode>(StoredVal) && !isa<ConstantFPSDNode>(StoredVal) &&
8786 // Only look at ends of store sequences.
8787 SDValue Chain = SDValue(St, 1);
8788 if (Chain->hasOneUse() && Chain->use_begin()->getOpcode() == ISD::STORE)
8791 // This holds the base pointer, index, and the offset in bytes from the base
8793 BaseIndexOffset BasePtr = BaseIndexOffset::match(St->getBasePtr());
8795 // We must have a base and an offset.
8796 if (!BasePtr.Base.getNode())
8799 // Do not handle stores to undef base pointers.
8800 if (BasePtr.Base.getOpcode() == ISD::UNDEF)
8803 // Save the LoadSDNodes that we find in the chain.
8804 // We need to make sure that these nodes do not interfere with
8805 // any of the store nodes.
8806 SmallVector<LSBaseSDNode*, 8> AliasLoadNodes;
8808 // Save the StoreSDNodes that we find in the chain.
8809 SmallVector<MemOpLink, 8> StoreNodes;
8811 // Walk up the chain and look for nodes with offsets from the same
8812 // base pointer. Stop when reaching an instruction with a different kind
8813 // or instruction which has a different base pointer.
8815 StoreSDNode *Index = St;
8817 // If the chain has more than one use, then we can't reorder the mem ops.
8818 if (Index != St && !SDValue(Index, 1)->hasOneUse())
8821 // Find the base pointer and offset for this memory node.
8822 BaseIndexOffset Ptr = BaseIndexOffset::match(Index->getBasePtr());
8824 // Check that the base pointer is the same as the original one.
8825 if (!Ptr.equalBaseIndex(BasePtr))
8828 // Check that the alignment is the same.
8829 if (Index->getAlignment() != St->getAlignment())
8832 // The memory operands must not be volatile.
8833 if (Index->isVolatile() || Index->isIndexed())
8837 if (StoreSDNode *St = dyn_cast<StoreSDNode>(Index))
8838 if (St->isTruncatingStore())
8841 // The stored memory type must be the same.
8842 if (Index->getMemoryVT() != MemVT)
8845 // We do not allow unaligned stores because we want to prevent overriding
8847 if (Index->getAlignment()*8 != MemVT.getSizeInBits())
8850 // We found a potential memory operand to merge.
8851 StoreNodes.push_back(MemOpLink(Index, Ptr.Offset, Seq++));
8853 // Find the next memory operand in the chain. If the next operand in the
8854 // chain is a store then move up and continue the scan with the next
8855 // memory operand. If the next operand is a load save it and use alias
8856 // information to check if it interferes with anything.
8857 SDNode *NextInChain = Index->getChain().getNode();
8859 if (StoreSDNode *STn = dyn_cast<StoreSDNode>(NextInChain)) {
8860 // We found a store node. Use it for the next iteration.
8863 } else if (LoadSDNode *Ldn = dyn_cast<LoadSDNode>(NextInChain)) {
8864 if (Ldn->isVolatile()) {
8869 // Save the load node for later. Continue the scan.
8870 AliasLoadNodes.push_back(Ldn);
8871 NextInChain = Ldn->getChain().getNode();
8880 // Check if there is anything to merge.
8881 if (StoreNodes.size() < 2)
8884 // Sort the memory operands according to their distance from the base pointer.
8885 std::sort(StoreNodes.begin(), StoreNodes.end(),
8886 ConsecutiveMemoryChainSorter());
8888 // Scan the memory operations on the chain and find the first non-consecutive
8889 // store memory address.
8890 unsigned LastConsecutiveStore = 0;
8891 int64_t StartAddress = StoreNodes[0].OffsetFromBase;
8892 for (unsigned i = 0, e = StoreNodes.size(); i < e; ++i) {
8894 // Check that the addresses are consecutive starting from the second
8895 // element in the list of stores.
8897 int64_t CurrAddress = StoreNodes[i].OffsetFromBase;
8898 if (CurrAddress - StartAddress != (ElementSizeBytes * i))
8903 // Check if this store interferes with any of the loads that we found.
8904 for (unsigned ld = 0, lde = AliasLoadNodes.size(); ld < lde; ++ld)
8905 if (isAlias(AliasLoadNodes[ld], StoreNodes[i].MemNode)) {
8909 // We found a load that alias with this store. Stop the sequence.
8913 // Mark this node as useful.
8914 LastConsecutiveStore = i;
8917 // The node with the lowest store address.
8918 LSBaseSDNode *FirstInChain = StoreNodes[0].MemNode;
8920 // Store the constants into memory as one consecutive store.
8922 unsigned LastLegalType = 0;
8923 unsigned LastLegalVectorType = 0;
8924 bool NonZero = false;
8925 for (unsigned i=0; i<LastConsecutiveStore+1; ++i) {
8926 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
8927 SDValue StoredVal = St->getValue();
8929 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(StoredVal)) {
8930 NonZero |= !C->isNullValue();
8931 } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(StoredVal)) {
8932 NonZero |= !C->getConstantFPValue()->isNullValue();
8938 // Find a legal type for the constant store.
8939 unsigned StoreBW = (i+1) * ElementSizeBytes * 8;
8940 EVT StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
8941 if (TLI.isTypeLegal(StoreTy))
8942 LastLegalType = i+1;
8943 // Or check whether a truncstore is legal.
8944 else if (TLI.getTypeAction(*DAG.getContext(), StoreTy) ==
8945 TargetLowering::TypePromoteInteger) {
8946 EVT LegalizedStoredValueTy =
8947 TLI.getTypeToTransformTo(*DAG.getContext(), StoredVal.getValueType());
8948 if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy))
8949 LastLegalType = i+1;
8952 // Find a legal type for the vector store.
8953 EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT, i+1);
8954 if (TLI.isTypeLegal(Ty))
8955 LastLegalVectorType = i + 1;
8958 // We only use vectors if the constant is known to be zero and the
8959 // function is not marked with the noimplicitfloat attribute.
8960 if (NonZero || NoVectors)
8961 LastLegalVectorType = 0;
8963 // Check if we found a legal integer type to store.
8964 if (LastLegalType == 0 && LastLegalVectorType == 0)
8967 bool UseVector = (LastLegalVectorType > LastLegalType) && !NoVectors;
8968 unsigned NumElem = UseVector ? LastLegalVectorType : LastLegalType;
8970 // Make sure we have something to merge.
8974 unsigned EarliestNodeUsed = 0;
8975 for (unsigned i=0; i < NumElem; ++i) {
8976 // Find a chain for the new wide-store operand. Notice that some
8977 // of the store nodes that we found may not be selected for inclusion
8978 // in the wide store. The chain we use needs to be the chain of the
8979 // earliest store node which is *used* and replaced by the wide store.
8980 if (StoreNodes[i].SequenceNum > StoreNodes[EarliestNodeUsed].SequenceNum)
8981 EarliestNodeUsed = i;
8984 // The earliest Node in the DAG.
8985 LSBaseSDNode *EarliestOp = StoreNodes[EarliestNodeUsed].MemNode;
8986 SDLoc DL(StoreNodes[0].MemNode);
8990 // Find a legal type for the vector store.
8991 EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT, NumElem);
8992 assert(TLI.isTypeLegal(Ty) && "Illegal vector store");
8993 StoredVal = DAG.getConstant(0, Ty);
8995 unsigned StoreBW = NumElem * ElementSizeBytes * 8;
8996 APInt StoreInt(StoreBW, 0);
8998 // Construct a single integer constant which is made of the smaller
9000 bool IsLE = TLI.isLittleEndian();
9001 for (unsigned i = 0; i < NumElem ; ++i) {
9002 unsigned Idx = IsLE ?(NumElem - 1 - i) : i;
9003 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[Idx].MemNode);
9004 SDValue Val = St->getValue();
9005 StoreInt<<=ElementSizeBytes*8;
9006 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Val)) {
9007 StoreInt|=C->getAPIntValue().zext(StoreBW);
9008 } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Val)) {
9009 StoreInt|= C->getValueAPF().bitcastToAPInt().zext(StoreBW);
9011 assert(false && "Invalid constant element type");
9015 // Create the new Load and Store operations.
9016 EVT StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
9017 StoredVal = DAG.getConstant(StoreInt, StoreTy);
9020 SDValue NewStore = DAG.getStore(EarliestOp->getChain(), DL, StoredVal,
9021 FirstInChain->getBasePtr(),
9022 FirstInChain->getPointerInfo(),
9024 FirstInChain->getAlignment());
9026 // Replace the first store with the new store
9027 CombineTo(EarliestOp, NewStore);
9028 // Erase all other stores.
9029 for (unsigned i = 0; i < NumElem ; ++i) {
9030 if (StoreNodes[i].MemNode == EarliestOp)
9032 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
9033 // ReplaceAllUsesWith will replace all uses that existed when it was
9034 // called, but graph optimizations may cause new ones to appear. For
9035 // example, the case in pr14333 looks like
9037 // St's chain -> St -> another store -> X
9039 // And the only difference from St to the other store is the chain.
9040 // When we change it's chain to be St's chain they become identical,
9041 // get CSEed and the net result is that X is now a use of St.
9042 // Since we know that St is redundant, just iterate.
9043 while (!St->use_empty())
9044 DAG.ReplaceAllUsesWith(SDValue(St, 0), St->getChain());
9045 removeFromWorkList(St);
9052 // Below we handle the case of multiple consecutive stores that
9053 // come from multiple consecutive loads. We merge them into a single
9054 // wide load and a single wide store.
9056 // Look for load nodes which are used by the stored values.
9057 SmallVector<MemOpLink, 8> LoadNodes;
9059 // Find acceptable loads. Loads need to have the same chain (token factor),
9060 // must not be zext, volatile, indexed, and they must be consecutive.
9061 BaseIndexOffset LdBasePtr;
9062 for (unsigned i=0; i<LastConsecutiveStore+1; ++i) {
9063 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
9064 LoadSDNode *Ld = dyn_cast<LoadSDNode>(St->getValue());
9067 // Loads must only have one use.
9068 if (!Ld->hasNUsesOfValue(1, 0))
9071 // Check that the alignment is the same as the stores.
9072 if (Ld->getAlignment() != St->getAlignment())
9075 // The memory operands must not be volatile.
9076 if (Ld->isVolatile() || Ld->isIndexed())
9079 // We do not accept ext loads.
9080 if (Ld->getExtensionType() != ISD::NON_EXTLOAD)
9083 // The stored memory type must be the same.
9084 if (Ld->getMemoryVT() != MemVT)
9087 BaseIndexOffset LdPtr = BaseIndexOffset::match(Ld->getBasePtr());
9088 // If this is not the first ptr that we check.
9089 if (LdBasePtr.Base.getNode()) {
9090 // The base ptr must be the same.
9091 if (!LdPtr.equalBaseIndex(LdBasePtr))
9094 // Check that all other base pointers are the same as this one.
9098 // We found a potential memory operand to merge.
9099 LoadNodes.push_back(MemOpLink(Ld, LdPtr.Offset, 0));
9102 if (LoadNodes.size() < 2)
9105 // Scan the memory operations on the chain and find the first non-consecutive
9106 // load memory address. These variables hold the index in the store node
9108 unsigned LastConsecutiveLoad = 0;
9109 // This variable refers to the size and not index in the array.
9110 unsigned LastLegalVectorType = 0;
9111 unsigned LastLegalIntegerType = 0;
9112 StartAddress = LoadNodes[0].OffsetFromBase;
9113 SDValue FirstChain = LoadNodes[0].MemNode->getChain();
9114 for (unsigned i = 1; i < LoadNodes.size(); ++i) {
9115 // All loads much share the same chain.
9116 if (LoadNodes[i].MemNode->getChain() != FirstChain)
9119 int64_t CurrAddress = LoadNodes[i].OffsetFromBase;
9120 if (CurrAddress - StartAddress != (ElementSizeBytes * i))
9122 LastConsecutiveLoad = i;
9124 // Find a legal type for the vector store.
9125 EVT StoreTy = EVT::getVectorVT(*DAG.getContext(), MemVT, i+1);
9126 if (TLI.isTypeLegal(StoreTy))
9127 LastLegalVectorType = i + 1;
9129 // Find a legal type for the integer store.
9130 unsigned StoreBW = (i+1) * ElementSizeBytes * 8;
9131 StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
9132 if (TLI.isTypeLegal(StoreTy))
9133 LastLegalIntegerType = i + 1;
9134 // Or check whether a truncstore and extload is legal.
9135 else if (TLI.getTypeAction(*DAG.getContext(), StoreTy) ==
9136 TargetLowering::TypePromoteInteger) {
9137 EVT LegalizedStoredValueTy =
9138 TLI.getTypeToTransformTo(*DAG.getContext(), StoreTy);
9139 if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy) &&
9140 TLI.isLoadExtLegal(ISD::ZEXTLOAD, StoreTy) &&
9141 TLI.isLoadExtLegal(ISD::SEXTLOAD, StoreTy) &&
9142 TLI.isLoadExtLegal(ISD::EXTLOAD, StoreTy))
9143 LastLegalIntegerType = i+1;
9147 // Only use vector types if the vector type is larger than the integer type.
9148 // If they are the same, use integers.
9149 bool UseVectorTy = LastLegalVectorType > LastLegalIntegerType && !NoVectors;
9150 unsigned LastLegalType = std::max(LastLegalVectorType, LastLegalIntegerType);
9152 // We add +1 here because the LastXXX variables refer to location while
9153 // the NumElem refers to array/index size.
9154 unsigned NumElem = std::min(LastConsecutiveStore, LastConsecutiveLoad) + 1;
9155 NumElem = std::min(LastLegalType, NumElem);
9160 // The earliest Node in the DAG.
9161 unsigned EarliestNodeUsed = 0;
9162 LSBaseSDNode *EarliestOp = StoreNodes[EarliestNodeUsed].MemNode;
9163 for (unsigned i=1; i<NumElem; ++i) {
9164 // Find a chain for the new wide-store operand. Notice that some
9165 // of the store nodes that we found may not be selected for inclusion
9166 // in the wide store. The chain we use needs to be the chain of the
9167 // earliest store node which is *used* and replaced by the wide store.
9168 if (StoreNodes[i].SequenceNum > StoreNodes[EarliestNodeUsed].SequenceNum)
9169 EarliestNodeUsed = i;
9172 // Find if it is better to use vectors or integers to load and store
9176 JointMemOpVT = EVT::getVectorVT(*DAG.getContext(), MemVT, NumElem);
9178 unsigned StoreBW = NumElem * ElementSizeBytes * 8;
9179 JointMemOpVT = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
9182 SDLoc LoadDL(LoadNodes[0].MemNode);
9183 SDLoc StoreDL(StoreNodes[0].MemNode);
9185 LoadSDNode *FirstLoad = cast<LoadSDNode>(LoadNodes[0].MemNode);
9186 SDValue NewLoad = DAG.getLoad(JointMemOpVT, LoadDL,
9187 FirstLoad->getChain(),
9188 FirstLoad->getBasePtr(),
9189 FirstLoad->getPointerInfo(),
9190 false, false, false,
9191 FirstLoad->getAlignment());
9193 SDValue NewStore = DAG.getStore(EarliestOp->getChain(), StoreDL, NewLoad,
9194 FirstInChain->getBasePtr(),
9195 FirstInChain->getPointerInfo(), false, false,
9196 FirstInChain->getAlignment());
9198 // Replace one of the loads with the new load.
9199 LoadSDNode *Ld = cast<LoadSDNode>(LoadNodes[0].MemNode);
9200 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1),
9201 SDValue(NewLoad.getNode(), 1));
9203 // Remove the rest of the load chains.
9204 for (unsigned i = 1; i < NumElem ; ++i) {
9205 // Replace all chain users of the old load nodes with the chain of the new
9207 LoadSDNode *Ld = cast<LoadSDNode>(LoadNodes[i].MemNode);
9208 DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), Ld->getChain());
9211 // Replace the first store with the new store.
9212 CombineTo(EarliestOp, NewStore);
9213 // Erase all other stores.
9214 for (unsigned i = 0; i < NumElem ; ++i) {
9215 // Remove all Store nodes.
9216 if (StoreNodes[i].MemNode == EarliestOp)
9218 StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
9219 DAG.ReplaceAllUsesOfValueWith(SDValue(St, 0), St->getChain());
9220 removeFromWorkList(St);
9227 SDValue DAGCombiner::visitSTORE(SDNode *N) {
9228 StoreSDNode *ST = cast<StoreSDNode>(N);
9229 SDValue Chain = ST->getChain();
9230 SDValue Value = ST->getValue();
9231 SDValue Ptr = ST->getBasePtr();
9233 // If this is a store of a bit convert, store the input value if the
9234 // resultant store does not need a higher alignment than the original.
9235 if (Value.getOpcode() == ISD::BITCAST && !ST->isTruncatingStore() &&
9236 ST->isUnindexed()) {
9237 unsigned OrigAlign = ST->getAlignment();
9238 EVT SVT = Value.getOperand(0).getValueType();
9239 unsigned Align = TLI.getDataLayout()->
9240 getABITypeAlignment(SVT.getTypeForEVT(*DAG.getContext()));
9241 if (Align <= OrigAlign &&
9242 ((!LegalOperations && !ST->isVolatile()) ||
9243 TLI.isOperationLegalOrCustom(ISD::STORE, SVT)))
9244 return DAG.getStore(Chain, SDLoc(N), Value.getOperand(0),
9245 Ptr, ST->getPointerInfo(), ST->isVolatile(),
9246 ST->isNonTemporal(), OrigAlign,
9250 // Turn 'store undef, Ptr' -> nothing.
9251 if (Value.getOpcode() == ISD::UNDEF && ST->isUnindexed())
9254 // Turn 'store float 1.0, Ptr' -> 'store int 0x12345678, Ptr'
9255 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Value)) {
9256 // NOTE: If the original store is volatile, this transform must not increase
9257 // the number of stores. For example, on x86-32 an f64 can be stored in one
9258 // processor operation but an i64 (which is not legal) requires two. So the
9259 // transform should not be done in this case.
9260 if (Value.getOpcode() != ISD::TargetConstantFP) {
9262 switch (CFP->getSimpleValueType(0).SimpleTy) {
9263 default: llvm_unreachable("Unknown FP type");
9264 case MVT::f16: // We don't do this for these yet.
9270 if ((isTypeLegal(MVT::i32) && !LegalOperations && !ST->isVolatile()) ||
9271 TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) {
9272 Tmp = DAG.getConstant((uint32_t)CFP->getValueAPF().
9273 bitcastToAPInt().getZExtValue(), MVT::i32);
9274 return DAG.getStore(Chain, SDLoc(N), Tmp,
9275 Ptr, ST->getMemOperand());
9279 if ((TLI.isTypeLegal(MVT::i64) && !LegalOperations &&
9280 !ST->isVolatile()) ||
9281 TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i64)) {
9282 Tmp = DAG.getConstant(CFP->getValueAPF().bitcastToAPInt().
9283 getZExtValue(), MVT::i64);
9284 return DAG.getStore(Chain, SDLoc(N), Tmp,
9285 Ptr, ST->getMemOperand());
9288 if (!ST->isVolatile() &&
9289 TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) {
9290 // Many FP stores are not made apparent until after legalize, e.g. for
9291 // argument passing. Since this is so common, custom legalize the
9292 // 64-bit integer store into two 32-bit stores.
9293 uint64_t Val = CFP->getValueAPF().bitcastToAPInt().getZExtValue();
9294 SDValue Lo = DAG.getConstant(Val & 0xFFFFFFFF, MVT::i32);
9295 SDValue Hi = DAG.getConstant(Val >> 32, MVT::i32);
9296 if (TLI.isBigEndian()) std::swap(Lo, Hi);
9298 unsigned Alignment = ST->getAlignment();
9299 bool isVolatile = ST->isVolatile();
9300 bool isNonTemporal = ST->isNonTemporal();
9301 const MDNode *TBAAInfo = ST->getTBAAInfo();
9303 SDValue St0 = DAG.getStore(Chain, SDLoc(ST), Lo,
9304 Ptr, ST->getPointerInfo(),
9305 isVolatile, isNonTemporal,
9306 ST->getAlignment(), TBAAInfo);
9307 Ptr = DAG.getNode(ISD::ADD, SDLoc(N), Ptr.getValueType(), Ptr,
9308 DAG.getConstant(4, Ptr.getValueType()));
9309 Alignment = MinAlign(Alignment, 4U);
9310 SDValue St1 = DAG.getStore(Chain, SDLoc(ST), Hi,
9311 Ptr, ST->getPointerInfo().getWithOffset(4),
9312 isVolatile, isNonTemporal,
9313 Alignment, TBAAInfo);
9314 return DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other,
9323 // Try to infer better alignment information than the store already has.
9324 if (OptLevel != CodeGenOpt::None && ST->isUnindexed()) {
9325 if (unsigned Align = DAG.InferPtrAlignment(Ptr)) {
9326 if (Align > ST->getAlignment())
9327 return DAG.getTruncStore(Chain, SDLoc(N), Value,
9328 Ptr, ST->getPointerInfo(), ST->getMemoryVT(),
9329 ST->isVolatile(), ST->isNonTemporal(), Align,
9334 // Try transforming a pair floating point load / store ops to integer
9335 // load / store ops.
9336 SDValue NewST = TransformFPLoadStorePair(N);
9337 if (NewST.getNode())
9340 bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA :
9341 TLI.getTargetMachine().getSubtarget<TargetSubtargetInfo>().useAA();
9343 if (CombinerAAOnlyFunc.getNumOccurrences() &&
9344 CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
9347 if (UseAA && ST->isUnindexed()) {
9348 // Walk up chain skipping non-aliasing memory nodes.
9349 SDValue BetterChain = FindBetterChain(N, Chain);
9351 // If there is a better chain.
9352 if (Chain != BetterChain) {
9355 // Replace the chain to avoid dependency.
9356 if (ST->isTruncatingStore()) {
9357 ReplStore = DAG.getTruncStore(BetterChain, SDLoc(N), Value, Ptr,
9358 ST->getMemoryVT(), ST->getMemOperand());
9360 ReplStore = DAG.getStore(BetterChain, SDLoc(N), Value, Ptr,
9361 ST->getMemOperand());
9364 // Create token to keep both nodes around.
9365 SDValue Token = DAG.getNode(ISD::TokenFactor, SDLoc(N),
9366 MVT::Other, Chain, ReplStore);
9368 // Make sure the new and old chains are cleaned up.
9369 AddToWorkList(Token.getNode());
9371 // Don't add users to work list.
9372 return CombineTo(N, Token, false);
9376 // Try transforming N to an indexed store.
9377 if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
9378 return SDValue(N, 0);
9380 // FIXME: is there such a thing as a truncating indexed store?
9381 if (ST->isTruncatingStore() && ST->isUnindexed() &&
9382 Value.getValueType().isInteger()) {
9383 // See if we can simplify the input to this truncstore with knowledge that
9384 // only the low bits are being used. For example:
9385 // "truncstore (or (shl x, 8), y), i8" -> "truncstore y, i8"
9387 GetDemandedBits(Value,
9388 APInt::getLowBitsSet(
9389 Value.getValueType().getScalarType().getSizeInBits(),
9390 ST->getMemoryVT().getScalarType().getSizeInBits()));
9391 AddToWorkList(Value.getNode());
9392 if (Shorter.getNode())
9393 return DAG.getTruncStore(Chain, SDLoc(N), Shorter,
9394 Ptr, ST->getMemoryVT(), ST->getMemOperand());
9396 // Otherwise, see if we can simplify the operation with
9397 // SimplifyDemandedBits, which only works if the value has a single use.
9398 if (SimplifyDemandedBits(Value,
9399 APInt::getLowBitsSet(
9400 Value.getValueType().getScalarType().getSizeInBits(),
9401 ST->getMemoryVT().getScalarType().getSizeInBits())))
9402 return SDValue(N, 0);
9405 // If this is a load followed by a store to the same location, then the store
9407 if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Value)) {
9408 if (Ld->getBasePtr() == Ptr && ST->getMemoryVT() == Ld->getMemoryVT() &&
9409 ST->isUnindexed() && !ST->isVolatile() &&
9410 // There can't be any side effects between the load and store, such as
9412 Chain.reachesChainWithoutSideEffects(SDValue(Ld, 1))) {
9413 // The store is dead, remove it.
9418 // If this is an FP_ROUND or TRUNC followed by a store, fold this into a
9419 // truncating store. We can do this even if this is already a truncstore.
9420 if ((Value.getOpcode() == ISD::FP_ROUND || Value.getOpcode() == ISD::TRUNCATE)
9421 && Value.getNode()->hasOneUse() && ST->isUnindexed() &&
9422 TLI.isTruncStoreLegal(Value.getOperand(0).getValueType(),
9423 ST->getMemoryVT())) {
9424 return DAG.getTruncStore(Chain, SDLoc(N), Value.getOperand(0),
9425 Ptr, ST->getMemoryVT(), ST->getMemOperand());
9428 // Only perform this optimization before the types are legal, because we
9429 // don't want to perform this optimization on every DAGCombine invocation.
9431 bool EverChanged = false;
9434 // There can be multiple store sequences on the same chain.
9435 // Keep trying to merge store sequences until we are unable to do so
9436 // or until we merge the last store on the chain.
9437 bool Changed = MergeConsecutiveStores(ST);
9438 EverChanged |= Changed;
9439 if (!Changed) break;
9440 } while (ST->getOpcode() != ISD::DELETED_NODE);
9443 return SDValue(N, 0);
9446 return ReduceLoadOpStoreWidth(N);
9449 SDValue DAGCombiner::visitINSERT_VECTOR_ELT(SDNode *N) {
9450 SDValue InVec = N->getOperand(0);
9451 SDValue InVal = N->getOperand(1);
9452 SDValue EltNo = N->getOperand(2);
9455 // If the inserted element is an UNDEF, just use the input vector.
9456 if (InVal.getOpcode() == ISD::UNDEF)
9459 EVT VT = InVec.getValueType();
9461 // If we can't generate a legal BUILD_VECTOR, exit
9462 if (LegalOperations && !TLI.isOperationLegal(ISD::BUILD_VECTOR, VT))
9465 // Check that we know which element is being inserted
9466 if (!isa<ConstantSDNode>(EltNo))
9468 unsigned Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
9470 // Check that the operand is a BUILD_VECTOR (or UNDEF, which can essentially
9471 // be converted to a BUILD_VECTOR). Fill in the Ops vector with the
9473 SmallVector<SDValue, 8> Ops;
9474 // Do not combine these two vectors if the output vector will not replace
9475 // the input vector.
9476 if (InVec.getOpcode() == ISD::BUILD_VECTOR && InVec.hasOneUse()) {
9477 Ops.append(InVec.getNode()->op_begin(),
9478 InVec.getNode()->op_end());
9479 } else if (InVec.getOpcode() == ISD::UNDEF) {
9480 unsigned NElts = VT.getVectorNumElements();
9481 Ops.append(NElts, DAG.getUNDEF(InVal.getValueType()));
9486 // Insert the element
9487 if (Elt < Ops.size()) {
9488 // All the operands of BUILD_VECTOR must have the same type;
9489 // we enforce that here.
9490 EVT OpVT = Ops[0].getValueType();
9491 if (InVal.getValueType() != OpVT)
9492 InVal = OpVT.bitsGT(InVal.getValueType()) ?
9493 DAG.getNode(ISD::ANY_EXTEND, dl, OpVT, InVal) :
9494 DAG.getNode(ISD::TRUNCATE, dl, OpVT, InVal);
9498 // Return the new vector
9499 return DAG.getNode(ISD::BUILD_VECTOR, dl,
9500 VT, &Ops[0], Ops.size());
9503 SDValue DAGCombiner::visitEXTRACT_VECTOR_ELT(SDNode *N) {
9504 // (vextract (scalar_to_vector val, 0) -> val
9505 SDValue InVec = N->getOperand(0);
9506 EVT VT = InVec.getValueType();
9507 EVT NVT = N->getValueType(0);
9509 if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR) {
9510 // Check if the result type doesn't match the inserted element type. A
9511 // SCALAR_TO_VECTOR may truncate the inserted element and the
9512 // EXTRACT_VECTOR_ELT may widen the extracted vector.
9513 SDValue InOp = InVec.getOperand(0);
9514 if (InOp.getValueType() != NVT) {
9515 assert(InOp.getValueType().isInteger() && NVT.isInteger());
9516 return DAG.getSExtOrTrunc(InOp, SDLoc(InVec), NVT);
9521 SDValue EltNo = N->getOperand(1);
9522 bool ConstEltNo = isa<ConstantSDNode>(EltNo);
9524 // Transform: (EXTRACT_VECTOR_ELT( VECTOR_SHUFFLE )) -> EXTRACT_VECTOR_ELT.
9525 // We only perform this optimization before the op legalization phase because
9526 // we may introduce new vector instructions which are not backed by TD
9527 // patterns. For example on AVX, extracting elements from a wide vector
9528 // without using extract_subvector.
9529 if (InVec.getOpcode() == ISD::VECTOR_SHUFFLE
9530 && ConstEltNo && !LegalOperations) {
9531 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
9532 int NumElem = VT.getVectorNumElements();
9533 ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(InVec);
9534 // Find the new index to extract from.
9535 int OrigElt = SVOp->getMaskElt(Elt);
9537 // Extracting an undef index is undef.
9539 return DAG.getUNDEF(NVT);
9541 // Select the right vector half to extract from.
9542 if (OrigElt < NumElem) {
9543 InVec = InVec->getOperand(0);
9545 InVec = InVec->getOperand(1);
9549 EVT IndexTy = TLI.getVectorIdxTy();
9550 return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SDLoc(N), NVT,
9551 InVec, DAG.getConstant(OrigElt, IndexTy));
9554 // Perform only after legalization to ensure build_vector / vector_shuffle
9555 // optimizations have already been done.
9556 if (!LegalOperations) return SDValue();
9558 // (vextract (v4f32 load $addr), c) -> (f32 load $addr+c*size)
9559 // (vextract (v4f32 s2v (f32 load $addr)), c) -> (f32 load $addr+c*size)
9560 // (vextract (v4f32 shuffle (load $addr), <1,u,u,u>), 0) -> (f32 load $addr)
9563 int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
9564 bool NewLoad = false;
9565 bool BCNumEltsChanged = false;
9566 EVT ExtVT = VT.getVectorElementType();
9569 // If the result of load has to be truncated, then it's not necessarily
9571 if (NVT.bitsLT(LVT) && !TLI.isTruncateFree(LVT, NVT))
9574 if (InVec.getOpcode() == ISD::BITCAST) {
9575 // Don't duplicate a load with other uses.
9576 if (!InVec.hasOneUse())
9579 EVT BCVT = InVec.getOperand(0).getValueType();
9580 if (!BCVT.isVector() || ExtVT.bitsGT(BCVT.getVectorElementType()))
9582 if (VT.getVectorNumElements() != BCVT.getVectorNumElements())
9583 BCNumEltsChanged = true;
9584 InVec = InVec.getOperand(0);
9585 ExtVT = BCVT.getVectorElementType();
9589 LoadSDNode *LN0 = NULL;
9590 const ShuffleVectorSDNode *SVN = NULL;
9591 if (ISD::isNormalLoad(InVec.getNode())) {
9592 LN0 = cast<LoadSDNode>(InVec);
9593 } else if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR &&
9594 InVec.getOperand(0).getValueType() == ExtVT &&
9595 ISD::isNormalLoad(InVec.getOperand(0).getNode())) {
9596 // Don't duplicate a load with other uses.
9597 if (!InVec.hasOneUse())
9600 LN0 = cast<LoadSDNode>(InVec.getOperand(0));
9601 } else if ((SVN = dyn_cast<ShuffleVectorSDNode>(InVec))) {
9602 // (vextract (vector_shuffle (load $addr), v2, <1, u, u, u>), 1)
9604 // (load $addr+1*size)
9606 // Don't duplicate a load with other uses.
9607 if (!InVec.hasOneUse())
9610 // If the bit convert changed the number of elements, it is unsafe
9611 // to examine the mask.
9612 if (BCNumEltsChanged)
9615 // Select the input vector, guarding against out of range extract vector.
9616 unsigned NumElems = VT.getVectorNumElements();
9617 int Idx = (Elt > (int)NumElems) ? -1 : SVN->getMaskElt(Elt);
9618 InVec = (Idx < (int)NumElems) ? InVec.getOperand(0) : InVec.getOperand(1);
9620 if (InVec.getOpcode() == ISD::BITCAST) {
9621 // Don't duplicate a load with other uses.
9622 if (!InVec.hasOneUse())
9625 InVec = InVec.getOperand(0);
9627 if (ISD::isNormalLoad(InVec.getNode())) {
9628 LN0 = cast<LoadSDNode>(InVec);
9629 Elt = (Idx < (int)NumElems) ? Idx : Idx - (int)NumElems;
9633 // Make sure we found a non-volatile load and the extractelement is
9635 if (!LN0 || !LN0->hasNUsesOfValue(1,0) || LN0->isVolatile())
9638 // If Idx was -1 above, Elt is going to be -1, so just return undef.
9640 return DAG.getUNDEF(LVT);
9642 unsigned Align = LN0->getAlignment();
9644 // Check the resultant load doesn't need a higher alignment than the
9648 ->getABITypeAlignment(LVT.getTypeForEVT(*DAG.getContext()));
9650 if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, LVT))
9656 SDValue NewPtr = LN0->getBasePtr();
9657 unsigned PtrOff = 0;
9660 PtrOff = LVT.getSizeInBits() * Elt / 8;
9661 EVT PtrType = NewPtr.getValueType();
9662 if (TLI.isBigEndian())
9663 PtrOff = VT.getSizeInBits() / 8 - PtrOff;
9664 NewPtr = DAG.getNode(ISD::ADD, SDLoc(N), PtrType, NewPtr,
9665 DAG.getConstant(PtrOff, PtrType));
9668 // The replacement we need to do here is a little tricky: we need to
9669 // replace an extractelement of a load with a load.
9670 // Use ReplaceAllUsesOfValuesWith to do the replacement.
9671 // Note that this replacement assumes that the extractvalue is the only
9672 // use of the load; that's okay because we don't want to perform this
9673 // transformation in other cases anyway.
9676 if (NVT.bitsGT(LVT)) {
9677 // If the result type of vextract is wider than the load, then issue an
9678 // extending load instead.
9679 ISD::LoadExtType ExtType = TLI.isLoadExtLegal(ISD::ZEXTLOAD, LVT)
9680 ? ISD::ZEXTLOAD : ISD::EXTLOAD;
9681 Load = DAG.getExtLoad(ExtType, SDLoc(N), NVT, LN0->getChain(),
9682 NewPtr, LN0->getPointerInfo().getWithOffset(PtrOff),
9683 LVT, LN0->isVolatile(), LN0->isNonTemporal(),
9684 Align, LN0->getTBAAInfo());
9685 Chain = Load.getValue(1);
9687 Load = DAG.getLoad(LVT, SDLoc(N), LN0->getChain(), NewPtr,
9688 LN0->getPointerInfo().getWithOffset(PtrOff),
9689 LN0->isVolatile(), LN0->isNonTemporal(),
9690 LN0->isInvariant(), Align, LN0->getTBAAInfo());
9691 Chain = Load.getValue(1);
9692 if (NVT.bitsLT(LVT))
9693 Load = DAG.getNode(ISD::TRUNCATE, SDLoc(N), NVT, Load);
9695 Load = DAG.getNode(ISD::BITCAST, SDLoc(N), NVT, Load);
9697 WorkListRemover DeadNodes(*this);
9698 SDValue From[] = { SDValue(N, 0), SDValue(LN0,1) };
9699 SDValue To[] = { Load, Chain };
9700 DAG.ReplaceAllUsesOfValuesWith(From, To, 2);
9701 // Since we're explcitly calling ReplaceAllUses, add the new node to the
9702 // worklist explicitly as well.
9703 AddToWorkList(Load.getNode());
9704 AddUsersToWorkList(Load.getNode()); // Add users too
9705 // Make sure to revisit this node to clean it up; it will usually be dead.
9707 return SDValue(N, 0);
9713 // Simplify (build_vec (ext )) to (bitcast (build_vec ))
9714 SDValue DAGCombiner::reduceBuildVecExtToExtBuildVec(SDNode *N) {
9715 // We perform this optimization post type-legalization because
9716 // the type-legalizer often scalarizes integer-promoted vectors.
9717 // Performing this optimization before may create bit-casts which
9718 // will be type-legalized to complex code sequences.
9719 // We perform this optimization only before the operation legalizer because we
9720 // may introduce illegal operations.
9721 if (Level != AfterLegalizeVectorOps && Level != AfterLegalizeTypes)
9724 unsigned NumInScalars = N->getNumOperands();
9726 EVT VT = N->getValueType(0);
9728 // Check to see if this is a BUILD_VECTOR of a bunch of values
9729 // which come from any_extend or zero_extend nodes. If so, we can create
9730 // a new BUILD_VECTOR using bit-casts which may enable other BUILD_VECTOR
9731 // optimizations. We do not handle sign-extend because we can't fill the sign
9733 EVT SourceType = MVT::Other;
9734 bool AllAnyExt = true;
9736 for (unsigned i = 0; i != NumInScalars; ++i) {
9737 SDValue In = N->getOperand(i);
9738 // Ignore undef inputs.
9739 if (In.getOpcode() == ISD::UNDEF) continue;
9741 bool AnyExt = In.getOpcode() == ISD::ANY_EXTEND;
9742 bool ZeroExt = In.getOpcode() == ISD::ZERO_EXTEND;
9744 // Abort if the element is not an extension.
9745 if (!ZeroExt && !AnyExt) {
9746 SourceType = MVT::Other;
9750 // The input is a ZeroExt or AnyExt. Check the original type.
9751 EVT InTy = In.getOperand(0).getValueType();
9753 // Check that all of the widened source types are the same.
9754 if (SourceType == MVT::Other)
9757 else if (InTy != SourceType) {
9758 // Multiple income types. Abort.
9759 SourceType = MVT::Other;
9763 // Check if all of the extends are ANY_EXTENDs.
9764 AllAnyExt &= AnyExt;
9767 // In order to have valid types, all of the inputs must be extended from the
9768 // same source type and all of the inputs must be any or zero extend.
9769 // Scalar sizes must be a power of two.
9770 EVT OutScalarTy = VT.getScalarType();
9771 bool ValidTypes = SourceType != MVT::Other &&
9772 isPowerOf2_32(OutScalarTy.getSizeInBits()) &&
9773 isPowerOf2_32(SourceType.getSizeInBits());
9775 // Create a new simpler BUILD_VECTOR sequence which other optimizations can
9776 // turn into a single shuffle instruction.
9780 bool isLE = TLI.isLittleEndian();
9781 unsigned ElemRatio = OutScalarTy.getSizeInBits()/SourceType.getSizeInBits();
9782 assert(ElemRatio > 1 && "Invalid element size ratio");
9783 SDValue Filler = AllAnyExt ? DAG.getUNDEF(SourceType):
9784 DAG.getConstant(0, SourceType);
9786 unsigned NewBVElems = ElemRatio * VT.getVectorNumElements();
9787 SmallVector<SDValue, 8> Ops(NewBVElems, Filler);
9789 // Populate the new build_vector
9790 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
9791 SDValue Cast = N->getOperand(i);
9792 assert((Cast.getOpcode() == ISD::ANY_EXTEND ||
9793 Cast.getOpcode() == ISD::ZERO_EXTEND ||
9794 Cast.getOpcode() == ISD::UNDEF) && "Invalid cast opcode");
9796 if (Cast.getOpcode() == ISD::UNDEF)
9797 In = DAG.getUNDEF(SourceType);
9799 In = Cast->getOperand(0);
9800 unsigned Index = isLE ? (i * ElemRatio) :
9801 (i * ElemRatio + (ElemRatio - 1));
9803 assert(Index < Ops.size() && "Invalid index");
9807 // The type of the new BUILD_VECTOR node.
9808 EVT VecVT = EVT::getVectorVT(*DAG.getContext(), SourceType, NewBVElems);
9809 assert(VecVT.getSizeInBits() == VT.getSizeInBits() &&
9810 "Invalid vector size");
9811 // Check if the new vector type is legal.
9812 if (!isTypeLegal(VecVT)) return SDValue();
9814 // Make the new BUILD_VECTOR.
9815 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, VecVT, &Ops[0], Ops.size());
9817 // The new BUILD_VECTOR node has the potential to be further optimized.
9818 AddToWorkList(BV.getNode());
9819 // Bitcast to the desired type.
9820 return DAG.getNode(ISD::BITCAST, dl, VT, BV);
9823 SDValue DAGCombiner::reduceBuildVecConvertToConvertBuildVec(SDNode *N) {
9824 EVT VT = N->getValueType(0);
9826 unsigned NumInScalars = N->getNumOperands();
9829 EVT SrcVT = MVT::Other;
9830 unsigned Opcode = ISD::DELETED_NODE;
9831 unsigned NumDefs = 0;
9833 for (unsigned i = 0; i != NumInScalars; ++i) {
9834 SDValue In = N->getOperand(i);
9835 unsigned Opc = In.getOpcode();
9837 if (Opc == ISD::UNDEF)
9840 // If all scalar values are floats and converted from integers.
9841 if (Opcode == ISD::DELETED_NODE &&
9842 (Opc == ISD::UINT_TO_FP || Opc == ISD::SINT_TO_FP)) {
9849 EVT InVT = In.getOperand(0).getValueType();
9851 // If all scalar values are typed differently, bail out. It's chosen to
9852 // simplify BUILD_VECTOR of integer types.
9853 if (SrcVT == MVT::Other)
9860 // If the vector has just one element defined, it's not worth to fold it into
9861 // a vectorized one.
9865 assert((Opcode == ISD::UINT_TO_FP || Opcode == ISD::SINT_TO_FP)
9866 && "Should only handle conversion from integer to float.");
9867 assert(SrcVT != MVT::Other && "Cannot determine source type!");
9869 EVT NVT = EVT::getVectorVT(*DAG.getContext(), SrcVT, NumInScalars);
9871 if (!TLI.isOperationLegalOrCustom(Opcode, NVT))
9874 SmallVector<SDValue, 8> Opnds;
9875 for (unsigned i = 0; i != NumInScalars; ++i) {
9876 SDValue In = N->getOperand(i);
9878 if (In.getOpcode() == ISD::UNDEF)
9879 Opnds.push_back(DAG.getUNDEF(SrcVT));
9881 Opnds.push_back(In.getOperand(0));
9883 SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, NVT,
9884 &Opnds[0], Opnds.size());
9885 AddToWorkList(BV.getNode());
9887 return DAG.getNode(Opcode, dl, VT, BV);
9890 SDValue DAGCombiner::visitBUILD_VECTOR(SDNode *N) {
9891 unsigned NumInScalars = N->getNumOperands();
9893 EVT VT = N->getValueType(0);
9895 // A vector built entirely of undefs is undef.
9896 if (ISD::allOperandsUndef(N))
9897 return DAG.getUNDEF(VT);
9899 SDValue V = reduceBuildVecExtToExtBuildVec(N);
9903 V = reduceBuildVecConvertToConvertBuildVec(N);
9907 // Check to see if this is a BUILD_VECTOR of a bunch of EXTRACT_VECTOR_ELT
9908 // operations. If so, and if the EXTRACT_VECTOR_ELT vector inputs come from
9909 // at most two distinct vectors, turn this into a shuffle node.
9911 // May only combine to shuffle after legalize if shuffle is legal.
9912 if (LegalOperations &&
9913 !TLI.isOperationLegalOrCustom(ISD::VECTOR_SHUFFLE, VT))
9916 SDValue VecIn1, VecIn2;
9917 for (unsigned i = 0; i != NumInScalars; ++i) {
9918 // Ignore undef inputs.
9919 if (N->getOperand(i).getOpcode() == ISD::UNDEF) continue;
9921 // If this input is something other than a EXTRACT_VECTOR_ELT with a
9922 // constant index, bail out.
9923 if (N->getOperand(i).getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
9924 !isa<ConstantSDNode>(N->getOperand(i).getOperand(1))) {
9925 VecIn1 = VecIn2 = SDValue(0, 0);
9929 // We allow up to two distinct input vectors.
9930 SDValue ExtractedFromVec = N->getOperand(i).getOperand(0);
9931 if (ExtractedFromVec == VecIn1 || ExtractedFromVec == VecIn2)
9934 if (VecIn1.getNode() == 0) {
9935 VecIn1 = ExtractedFromVec;
9936 } else if (VecIn2.getNode() == 0) {
9937 VecIn2 = ExtractedFromVec;
9940 VecIn1 = VecIn2 = SDValue(0, 0);
9945 // If everything is good, we can make a shuffle operation.
9946 if (VecIn1.getNode()) {
9947 SmallVector<int, 8> Mask;
9948 for (unsigned i = 0; i != NumInScalars; ++i) {
9949 if (N->getOperand(i).getOpcode() == ISD::UNDEF) {
9954 // If extracting from the first vector, just use the index directly.
9955 SDValue Extract = N->getOperand(i);
9956 SDValue ExtVal = Extract.getOperand(1);
9957 if (Extract.getOperand(0) == VecIn1) {
9958 unsigned ExtIndex = cast<ConstantSDNode>(ExtVal)->getZExtValue();
9959 if (ExtIndex > VT.getVectorNumElements())
9962 Mask.push_back(ExtIndex);
9966 // Otherwise, use InIdx + VecSize
9967 unsigned Idx = cast<ConstantSDNode>(ExtVal)->getZExtValue();
9968 Mask.push_back(Idx+NumInScalars);
9971 // We can't generate a shuffle node with mismatched input and output types.
9972 // Attempt to transform a single input vector to the correct type.
9973 if ((VT != VecIn1.getValueType())) {
9974 // We don't support shuffeling between TWO values of different types.
9975 if (VecIn2.getNode() != 0)
9978 // We only support widening of vectors which are half the size of the
9979 // output registers. For example XMM->YMM widening on X86 with AVX.
9980 if (VecIn1.getValueType().getSizeInBits()*2 != VT.getSizeInBits())
9983 // If the input vector type has a different base type to the output
9984 // vector type, bail out.
9985 if (VecIn1.getValueType().getVectorElementType() !=
9986 VT.getVectorElementType())
9989 // Widen the input vector by adding undef values.
9990 VecIn1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
9991 VecIn1, DAG.getUNDEF(VecIn1.getValueType()));
9994 // If VecIn2 is unused then change it to undef.
9995 VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(VT);
9997 // Check that we were able to transform all incoming values to the same
9999 if (VecIn2.getValueType() != VecIn1.getValueType() ||
10000 VecIn1.getValueType() != VT)
10003 // Only type-legal BUILD_VECTOR nodes are converted to shuffle nodes.
10004 if (!isTypeLegal(VT))
10007 // Return the new VECTOR_SHUFFLE node.
10011 return DAG.getVectorShuffle(VT, dl, Ops[0], Ops[1], &Mask[0]);
10017 SDValue DAGCombiner::visitCONCAT_VECTORS(SDNode *N) {
10018 // TODO: Check to see if this is a CONCAT_VECTORS of a bunch of
10019 // EXTRACT_SUBVECTOR operations. If so, and if the EXTRACT_SUBVECTOR vector
10020 // inputs come from at most two distinct vectors, turn this into a shuffle
10023 // If we only have one input vector, we don't need to do any concatenation.
10024 if (N->getNumOperands() == 1)
10025 return N->getOperand(0);
10027 // Check if all of the operands are undefs.
10028 EVT VT = N->getValueType(0);
10029 if (ISD::allOperandsUndef(N))
10030 return DAG.getUNDEF(VT);
10032 // Optimize concat_vectors where one of the vectors is undef.
10033 if (N->getNumOperands() == 2 &&
10034 N->getOperand(1)->getOpcode() == ISD::UNDEF) {
10035 SDValue In = N->getOperand(0);
10036 assert(In.getValueType().isVector() && "Must concat vectors");
10038 // Transform: concat_vectors(scalar, undef) -> scalar_to_vector(sclr).
10039 if (In->getOpcode() == ISD::BITCAST &&
10040 !In->getOperand(0)->getValueType(0).isVector()) {
10041 SDValue Scalar = In->getOperand(0);
10042 EVT SclTy = Scalar->getValueType(0);
10044 if (!SclTy.isFloatingPoint() && !SclTy.isInteger())
10047 EVT NVT = EVT::getVectorVT(*DAG.getContext(), SclTy,
10048 VT.getSizeInBits() / SclTy.getSizeInBits());
10049 if (!TLI.isTypeLegal(NVT) || !TLI.isTypeLegal(Scalar.getValueType()))
10052 SDLoc dl = SDLoc(N);
10053 SDValue Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, NVT, Scalar);
10054 return DAG.getNode(ISD::BITCAST, dl, VT, Res);
10058 // Type legalization of vectors and DAG canonicalization of SHUFFLE_VECTOR
10059 // nodes often generate nop CONCAT_VECTOR nodes.
10060 // Scan the CONCAT_VECTOR operands and look for a CONCAT operations that
10061 // place the incoming vectors at the exact same location.
10062 SDValue SingleSource = SDValue();
10063 unsigned PartNumElem = N->getOperand(0).getValueType().getVectorNumElements();
10065 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
10066 SDValue Op = N->getOperand(i);
10068 if (Op.getOpcode() == ISD::UNDEF)
10071 // Check if this is the identity extract:
10072 if (Op.getOpcode() != ISD::EXTRACT_SUBVECTOR)
10075 // Find the single incoming vector for the extract_subvector.
10076 if (SingleSource.getNode()) {
10077 if (Op.getOperand(0) != SingleSource)
10080 SingleSource = Op.getOperand(0);
10082 // Check the source type is the same as the type of the result.
10083 // If not, this concat may extend the vector, so we can not
10084 // optimize it away.
10085 if (SingleSource.getValueType() != N->getValueType(0))
10089 unsigned IdentityIndex = i * PartNumElem;
10090 ConstantSDNode *CS = dyn_cast<ConstantSDNode>(Op.getOperand(1));
10091 // The extract index must be constant.
10095 // Check that we are reading from the identity index.
10096 if (CS->getZExtValue() != IdentityIndex)
10100 if (SingleSource.getNode())
10101 return SingleSource;
10106 SDValue DAGCombiner::visitEXTRACT_SUBVECTOR(SDNode* N) {
10107 EVT NVT = N->getValueType(0);
10108 SDValue V = N->getOperand(0);
10110 if (V->getOpcode() == ISD::CONCAT_VECTORS) {
10112 // (extract_subvec (concat V1, V2, ...), i)
10115 // Only operand 0 is checked as 'concat' assumes all inputs of the same
10117 if (V->getOperand(0).getValueType() != NVT)
10119 unsigned Idx = dyn_cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
10120 unsigned NumElems = NVT.getVectorNumElements();
10121 assert((Idx % NumElems) == 0 &&
10122 "IDX in concat is not a multiple of the result vector length.");
10123 return V->getOperand(Idx / NumElems);
10127 if (V->getOpcode() == ISD::BITCAST)
10128 V = V.getOperand(0);
10130 if (V->getOpcode() == ISD::INSERT_SUBVECTOR) {
10132 // Handle only simple case where vector being inserted and vector
10133 // being extracted are of same type, and are half size of larger vectors.
10134 EVT BigVT = V->getOperand(0).getValueType();
10135 EVT SmallVT = V->getOperand(1).getValueType();
10136 if (!NVT.bitsEq(SmallVT) || NVT.getSizeInBits()*2 != BigVT.getSizeInBits())
10139 // Only handle cases where both indexes are constants with the same type.
10140 ConstantSDNode *ExtIdx = dyn_cast<ConstantSDNode>(N->getOperand(1));
10141 ConstantSDNode *InsIdx = dyn_cast<ConstantSDNode>(V->getOperand(2));
10143 if (InsIdx && ExtIdx &&
10144 InsIdx->getValueType(0).getSizeInBits() <= 64 &&
10145 ExtIdx->getValueType(0).getSizeInBits() <= 64) {
10147 // (extract_subvec (insert_subvec V1, V2, InsIdx), ExtIdx)
10149 // indices are equal or bit offsets are equal => V1
10150 // otherwise => (extract_subvec V1, ExtIdx)
10151 if (InsIdx->getZExtValue() * SmallVT.getScalarType().getSizeInBits() ==
10152 ExtIdx->getZExtValue() * NVT.getScalarType().getSizeInBits())
10153 return DAG.getNode(ISD::BITCAST, dl, NVT, V->getOperand(1));
10154 return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, NVT,
10155 DAG.getNode(ISD::BITCAST, dl,
10156 N->getOperand(0).getValueType(),
10157 V->getOperand(0)), N->getOperand(1));
10164 // Tries to turn a shuffle of two CONCAT_VECTORS into a single concat.
10165 static SDValue partitionShuffleOfConcats(SDNode *N, SelectionDAG &DAG) {
10166 EVT VT = N->getValueType(0);
10167 unsigned NumElts = VT.getVectorNumElements();
10169 SDValue N0 = N->getOperand(0);
10170 SDValue N1 = N->getOperand(1);
10171 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
10173 SmallVector<SDValue, 4> Ops;
10174 EVT ConcatVT = N0.getOperand(0).getValueType();
10175 unsigned NumElemsPerConcat = ConcatVT.getVectorNumElements();
10176 unsigned NumConcats = NumElts / NumElemsPerConcat;
10178 // Look at every vector that's inserted. We're looking for exact
10179 // subvector-sized copies from a concatenated vector
10180 for (unsigned I = 0; I != NumConcats; ++I) {
10181 // Make sure we're dealing with a copy.
10182 unsigned Begin = I * NumElemsPerConcat;
10183 bool AllUndef = true, NoUndef = true;
10184 for (unsigned J = Begin; J != Begin + NumElemsPerConcat; ++J) {
10185 if (SVN->getMaskElt(J) >= 0)
10192 if (SVN->getMaskElt(Begin) % NumElemsPerConcat != 0)
10195 for (unsigned J = 1; J != NumElemsPerConcat; ++J)
10196 if (SVN->getMaskElt(Begin + J - 1) + 1 != SVN->getMaskElt(Begin + J))
10199 unsigned FirstElt = SVN->getMaskElt(Begin) / NumElemsPerConcat;
10200 if (FirstElt < N0.getNumOperands())
10201 Ops.push_back(N0.getOperand(FirstElt));
10203 Ops.push_back(N1.getOperand(FirstElt - N0.getNumOperands()));
10205 } else if (AllUndef) {
10206 Ops.push_back(DAG.getUNDEF(N0.getOperand(0).getValueType()));
10207 } else { // Mixed with general masks and undefs, can't do optimization.
10212 return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Ops.data(),
10216 SDValue DAGCombiner::visitVECTOR_SHUFFLE(SDNode *N) {
10217 EVT VT = N->getValueType(0);
10218 unsigned NumElts = VT.getVectorNumElements();
10220 SDValue N0 = N->getOperand(0);
10221 SDValue N1 = N->getOperand(1);
10223 assert(N0.getValueType() == VT && "Vector shuffle must be normalized in DAG");
10225 // Canonicalize shuffle undef, undef -> undef
10226 if (N0.getOpcode() == ISD::UNDEF && N1.getOpcode() == ISD::UNDEF)
10227 return DAG.getUNDEF(VT);
10229 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
10231 // Canonicalize shuffle v, v -> v, undef
10233 SmallVector<int, 8> NewMask;
10234 for (unsigned i = 0; i != NumElts; ++i) {
10235 int Idx = SVN->getMaskElt(i);
10236 if (Idx >= (int)NumElts) Idx -= NumElts;
10237 NewMask.push_back(Idx);
10239 return DAG.getVectorShuffle(VT, SDLoc(N), N0, DAG.getUNDEF(VT),
10243 // Canonicalize shuffle undef, v -> v, undef. Commute the shuffle mask.
10244 if (N0.getOpcode() == ISD::UNDEF) {
10245 SmallVector<int, 8> NewMask;
10246 for (unsigned i = 0; i != NumElts; ++i) {
10247 int Idx = SVN->getMaskElt(i);
10249 if (Idx >= (int)NumElts)
10252 Idx = -1; // remove reference to lhs
10254 NewMask.push_back(Idx);
10256 return DAG.getVectorShuffle(VT, SDLoc(N), N1, DAG.getUNDEF(VT),
10260 // Remove references to rhs if it is undef
10261 if (N1.getOpcode() == ISD::UNDEF) {
10262 bool Changed = false;
10263 SmallVector<int, 8> NewMask;
10264 for (unsigned i = 0; i != NumElts; ++i) {
10265 int Idx = SVN->getMaskElt(i);
10266 if (Idx >= (int)NumElts) {
10270 NewMask.push_back(Idx);
10273 return DAG.getVectorShuffle(VT, SDLoc(N), N0, N1, &NewMask[0]);
10276 // If it is a splat, check if the argument vector is another splat or a
10277 // build_vector with all scalar elements the same.
10278 if (SVN->isSplat() && SVN->getSplatIndex() < (int)NumElts) {
10279 SDNode *V = N0.getNode();
10281 // If this is a bit convert that changes the element type of the vector but
10282 // not the number of vector elements, look through it. Be careful not to
10283 // look though conversions that change things like v4f32 to v2f64.
10284 if (V->getOpcode() == ISD::BITCAST) {
10285 SDValue ConvInput = V->getOperand(0);
10286 if (ConvInput.getValueType().isVector() &&
10287 ConvInput.getValueType().getVectorNumElements() == NumElts)
10288 V = ConvInput.getNode();
10291 if (V->getOpcode() == ISD::BUILD_VECTOR) {
10292 assert(V->getNumOperands() == NumElts &&
10293 "BUILD_VECTOR has wrong number of operands");
10295 bool AllSame = true;
10296 for (unsigned i = 0; i != NumElts; ++i) {
10297 if (V->getOperand(i).getOpcode() != ISD::UNDEF) {
10298 Base = V->getOperand(i);
10302 // Splat of <u, u, u, u>, return <u, u, u, u>
10303 if (!Base.getNode())
10305 for (unsigned i = 0; i != NumElts; ++i) {
10306 if (V->getOperand(i) != Base) {
10311 // Splat of <x, x, x, x>, return <x, x, x, x>
10317 if (N0.getOpcode() == ISD::CONCAT_VECTORS &&
10318 Level < AfterLegalizeVectorOps &&
10319 (N1.getOpcode() == ISD::UNDEF ||
10320 (N1.getOpcode() == ISD::CONCAT_VECTORS &&
10321 N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType()))) {
10322 SDValue V = partitionShuffleOfConcats(N, DAG);
10328 // If this shuffle node is simply a swizzle of another shuffle node,
10329 // and it reverses the swizzle of the previous shuffle then we can
10330 // optimize shuffle(shuffle(x, undef), undef) -> x.
10331 if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG &&
10332 N1.getOpcode() == ISD::UNDEF) {
10334 ShuffleVectorSDNode *OtherSV = cast<ShuffleVectorSDNode>(N0);
10336 // Shuffle nodes can only reverse shuffles with a single non-undef value.
10337 if (N0.getOperand(1).getOpcode() != ISD::UNDEF)
10340 // The incoming shuffle must be of the same type as the result of the
10341 // current shuffle.
10342 assert(OtherSV->getOperand(0).getValueType() == VT &&
10343 "Shuffle types don't match");
10345 for (unsigned i = 0; i != NumElts; ++i) {
10346 int Idx = SVN->getMaskElt(i);
10347 assert(Idx < (int)NumElts && "Index references undef operand");
10348 // Next, this index comes from the first value, which is the incoming
10349 // shuffle. Adopt the incoming index.
10351 Idx = OtherSV->getMaskElt(Idx);
10353 // The combined shuffle must map each index to itself.
10354 if (Idx >= 0 && (unsigned)Idx != i)
10358 return OtherSV->getOperand(0);
10364 /// XformToShuffleWithZero - Returns a vector_shuffle if it able to transform
10365 /// an AND to a vector_shuffle with the destination vector and a zero vector.
10366 /// e.g. AND V, <0xffffffff, 0, 0xffffffff, 0>. ==>
10367 /// vector_shuffle V, Zero, <0, 4, 2, 4>
10368 SDValue DAGCombiner::XformToShuffleWithZero(SDNode *N) {
10369 EVT VT = N->getValueType(0);
10371 SDValue LHS = N->getOperand(0);
10372 SDValue RHS = N->getOperand(1);
10373 if (N->getOpcode() == ISD::AND) {
10374 if (RHS.getOpcode() == ISD::BITCAST)
10375 RHS = RHS.getOperand(0);
10376 if (RHS.getOpcode() == ISD::BUILD_VECTOR) {
10377 SmallVector<int, 8> Indices;
10378 unsigned NumElts = RHS.getNumOperands();
10379 for (unsigned i = 0; i != NumElts; ++i) {
10380 SDValue Elt = RHS.getOperand(i);
10381 if (!isa<ConstantSDNode>(Elt))
10384 if (cast<ConstantSDNode>(Elt)->isAllOnesValue())
10385 Indices.push_back(i);
10386 else if (cast<ConstantSDNode>(Elt)->isNullValue())
10387 Indices.push_back(NumElts);
10392 // Let's see if the target supports this vector_shuffle.
10393 EVT RVT = RHS.getValueType();
10394 if (!TLI.isVectorClearMaskLegal(Indices, RVT))
10397 // Return the new VECTOR_SHUFFLE node.
10398 EVT EltVT = RVT.getVectorElementType();
10399 SmallVector<SDValue,8> ZeroOps(RVT.getVectorNumElements(),
10400 DAG.getConstant(0, EltVT));
10401 SDValue Zero = DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N),
10402 RVT, &ZeroOps[0], ZeroOps.size());
10403 LHS = DAG.getNode(ISD::BITCAST, dl, RVT, LHS);
10404 SDValue Shuf = DAG.getVectorShuffle(RVT, dl, LHS, Zero, &Indices[0]);
10405 return DAG.getNode(ISD::BITCAST, dl, VT, Shuf);
10412 /// SimplifyVBinOp - Visit a binary vector operation, like ADD.
10413 SDValue DAGCombiner::SimplifyVBinOp(SDNode *N) {
10414 assert(N->getValueType(0).isVector() &&
10415 "SimplifyVBinOp only works on vectors!");
10417 SDValue LHS = N->getOperand(0);
10418 SDValue RHS = N->getOperand(1);
10419 SDValue Shuffle = XformToShuffleWithZero(N);
10420 if (Shuffle.getNode()) return Shuffle;
10422 // If the LHS and RHS are BUILD_VECTOR nodes, see if we can constant fold
10424 if (LHS.getOpcode() == ISD::BUILD_VECTOR &&
10425 RHS.getOpcode() == ISD::BUILD_VECTOR) {
10426 // Check if both vectors are constants. If not bail out.
10427 if (!(cast<BuildVectorSDNode>(LHS)->isConstant() &&
10428 cast<BuildVectorSDNode>(RHS)->isConstant()))
10431 SmallVector<SDValue, 8> Ops;
10432 for (unsigned i = 0, e = LHS.getNumOperands(); i != e; ++i) {
10433 SDValue LHSOp = LHS.getOperand(i);
10434 SDValue RHSOp = RHS.getOperand(i);
10436 // Can't fold divide by zero.
10437 if (N->getOpcode() == ISD::SDIV || N->getOpcode() == ISD::UDIV ||
10438 N->getOpcode() == ISD::FDIV) {
10439 if ((RHSOp.getOpcode() == ISD::Constant &&
10440 cast<ConstantSDNode>(RHSOp.getNode())->isNullValue()) ||
10441 (RHSOp.getOpcode() == ISD::ConstantFP &&
10442 cast<ConstantFPSDNode>(RHSOp.getNode())->getValueAPF().isZero()))
10446 EVT VT = LHSOp.getValueType();
10447 EVT RVT = RHSOp.getValueType();
10449 // Integer BUILD_VECTOR operands may have types larger than the element
10450 // size (e.g., when the element type is not legal). Prior to type
10451 // legalization, the types may not match between the two BUILD_VECTORS.
10452 // Truncate one of the operands to make them match.
10453 if (RVT.getSizeInBits() > VT.getSizeInBits()) {
10454 RHSOp = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, RHSOp);
10456 LHSOp = DAG.getNode(ISD::TRUNCATE, SDLoc(N), RVT, LHSOp);
10460 SDValue FoldOp = DAG.getNode(N->getOpcode(), SDLoc(LHS), VT,
10462 if (FoldOp.getOpcode() != ISD::UNDEF &&
10463 FoldOp.getOpcode() != ISD::Constant &&
10464 FoldOp.getOpcode() != ISD::ConstantFP)
10466 Ops.push_back(FoldOp);
10467 AddToWorkList(FoldOp.getNode());
10470 if (Ops.size() == LHS.getNumOperands())
10471 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N),
10472 LHS.getValueType(), &Ops[0], Ops.size());
10478 /// SimplifyVUnaryOp - Visit a binary vector operation, like FABS/FNEG.
10479 SDValue DAGCombiner::SimplifyVUnaryOp(SDNode *N) {
10480 assert(N->getValueType(0).isVector() &&
10481 "SimplifyVUnaryOp only works on vectors!");
10483 SDValue N0 = N->getOperand(0);
10485 if (N0.getOpcode() != ISD::BUILD_VECTOR)
10488 // Operand is a BUILD_VECTOR node, see if we can constant fold it.
10489 SmallVector<SDValue, 8> Ops;
10490 for (unsigned i = 0, e = N0.getNumOperands(); i != e; ++i) {
10491 SDValue Op = N0.getOperand(i);
10492 if (Op.getOpcode() != ISD::UNDEF &&
10493 Op.getOpcode() != ISD::ConstantFP)
10495 EVT EltVT = Op.getValueType();
10496 SDValue FoldOp = DAG.getNode(N->getOpcode(), SDLoc(N0), EltVT, Op);
10497 if (FoldOp.getOpcode() != ISD::UNDEF &&
10498 FoldOp.getOpcode() != ISD::ConstantFP)
10500 Ops.push_back(FoldOp);
10501 AddToWorkList(FoldOp.getNode());
10504 if (Ops.size() != N0.getNumOperands())
10507 return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N),
10508 N0.getValueType(), &Ops[0], Ops.size());
10511 SDValue DAGCombiner::SimplifySelect(SDLoc DL, SDValue N0,
10512 SDValue N1, SDValue N2){
10513 assert(N0.getOpcode() ==ISD::SETCC && "First argument must be a SetCC node!");
10515 SDValue SCC = SimplifySelectCC(DL, N0.getOperand(0), N0.getOperand(1), N1, N2,
10516 cast<CondCodeSDNode>(N0.getOperand(2))->get());
10518 // If we got a simplified select_cc node back from SimplifySelectCC, then
10519 // break it down into a new SETCC node, and a new SELECT node, and then return
10520 // the SELECT node, since we were called with a SELECT node.
10521 if (SCC.getNode()) {
10522 // Check to see if we got a select_cc back (to turn into setcc/select).
10523 // Otherwise, just return whatever node we got back, like fabs.
10524 if (SCC.getOpcode() == ISD::SELECT_CC) {
10525 SDValue SETCC = DAG.getNode(ISD::SETCC, SDLoc(N0),
10527 SCC.getOperand(0), SCC.getOperand(1),
10528 SCC.getOperand(4));
10529 AddToWorkList(SETCC.getNode());
10530 return DAG.getSelect(SDLoc(SCC), SCC.getValueType(),
10531 SCC.getOperand(2), SCC.getOperand(3), SETCC);
10539 /// SimplifySelectOps - Given a SELECT or a SELECT_CC node, where LHS and RHS
10540 /// are the two values being selected between, see if we can simplify the
10541 /// select. Callers of this should assume that TheSelect is deleted if this
10542 /// returns true. As such, they should return the appropriate thing (e.g. the
10543 /// node) back to the top-level of the DAG combiner loop to avoid it being
10545 bool DAGCombiner::SimplifySelectOps(SDNode *TheSelect, SDValue LHS,
10548 // Cannot simplify select with vector condition
10549 if (TheSelect->getOperand(0).getValueType().isVector()) return false;
10551 // If this is a select from two identical things, try to pull the operation
10552 // through the select.
10553 if (LHS.getOpcode() != RHS.getOpcode() ||
10554 !LHS.hasOneUse() || !RHS.hasOneUse())
10557 // If this is a load and the token chain is identical, replace the select
10558 // of two loads with a load through a select of the address to load from.
10559 // This triggers in things like "select bool X, 10.0, 123.0" after the FP
10560 // constants have been dropped into the constant pool.
10561 if (LHS.getOpcode() == ISD::LOAD) {
10562 LoadSDNode *LLD = cast<LoadSDNode>(LHS);
10563 LoadSDNode *RLD = cast<LoadSDNode>(RHS);
10565 // Token chains must be identical.
10566 if (LHS.getOperand(0) != RHS.getOperand(0) ||
10567 // Do not let this transformation reduce the number of volatile loads.
10568 LLD->isVolatile() || RLD->isVolatile() ||
10569 // If this is an EXTLOAD, the VT's must match.
10570 LLD->getMemoryVT() != RLD->getMemoryVT() ||
10571 // If this is an EXTLOAD, the kind of extension must match.
10572 (LLD->getExtensionType() != RLD->getExtensionType() &&
10573 // The only exception is if one of the extensions is anyext.
10574 LLD->getExtensionType() != ISD::EXTLOAD &&
10575 RLD->getExtensionType() != ISD::EXTLOAD) ||
10576 // FIXME: this discards src value information. This is
10577 // over-conservative. It would be beneficial to be able to remember
10578 // both potential memory locations. Since we are discarding
10579 // src value info, don't do the transformation if the memory
10580 // locations are not in the default address space.
10581 LLD->getPointerInfo().getAddrSpace() != 0 ||
10582 RLD->getPointerInfo().getAddrSpace() != 0 ||
10583 !TLI.isOperationLegalOrCustom(TheSelect->getOpcode(),
10584 LLD->getBasePtr().getValueType()))
10587 // Check that the select condition doesn't reach either load. If so,
10588 // folding this will induce a cycle into the DAG. If not, this is safe to
10589 // xform, so create a select of the addresses.
10591 if (TheSelect->getOpcode() == ISD::SELECT) {
10592 SDNode *CondNode = TheSelect->getOperand(0).getNode();
10593 if ((LLD->hasAnyUseOfValue(1) && LLD->isPredecessorOf(CondNode)) ||
10594 (RLD->hasAnyUseOfValue(1) && RLD->isPredecessorOf(CondNode)))
10596 // The loads must not depend on one another.
10597 if (LLD->isPredecessorOf(RLD) ||
10598 RLD->isPredecessorOf(LLD))
10600 Addr = DAG.getSelect(SDLoc(TheSelect),
10601 LLD->getBasePtr().getValueType(),
10602 TheSelect->getOperand(0), LLD->getBasePtr(),
10603 RLD->getBasePtr());
10604 } else { // Otherwise SELECT_CC
10605 SDNode *CondLHS = TheSelect->getOperand(0).getNode();
10606 SDNode *CondRHS = TheSelect->getOperand(1).getNode();
10608 if ((LLD->hasAnyUseOfValue(1) &&
10609 (LLD->isPredecessorOf(CondLHS) || LLD->isPredecessorOf(CondRHS))) ||
10610 (RLD->hasAnyUseOfValue(1) &&
10611 (RLD->isPredecessorOf(CondLHS) || RLD->isPredecessorOf(CondRHS))))
10614 Addr = DAG.getNode(ISD::SELECT_CC, SDLoc(TheSelect),
10615 LLD->getBasePtr().getValueType(),
10616 TheSelect->getOperand(0),
10617 TheSelect->getOperand(1),
10618 LLD->getBasePtr(), RLD->getBasePtr(),
10619 TheSelect->getOperand(4));
10623 if (LLD->getExtensionType() == ISD::NON_EXTLOAD) {
10624 Load = DAG.getLoad(TheSelect->getValueType(0),
10626 // FIXME: Discards pointer and TBAA info.
10627 LLD->getChain(), Addr, MachinePointerInfo(),
10628 LLD->isVolatile(), LLD->isNonTemporal(),
10629 LLD->isInvariant(), LLD->getAlignment());
10631 Load = DAG.getExtLoad(LLD->getExtensionType() == ISD::EXTLOAD ?
10632 RLD->getExtensionType() : LLD->getExtensionType(),
10634 TheSelect->getValueType(0),
10635 // FIXME: Discards pointer and TBAA info.
10636 LLD->getChain(), Addr, MachinePointerInfo(),
10637 LLD->getMemoryVT(), LLD->isVolatile(),
10638 LLD->isNonTemporal(), LLD->getAlignment());
10641 // Users of the select now use the result of the load.
10642 CombineTo(TheSelect, Load);
10644 // Users of the old loads now use the new load's chain. We know the
10645 // old-load value is dead now.
10646 CombineTo(LHS.getNode(), Load.getValue(0), Load.getValue(1));
10647 CombineTo(RHS.getNode(), Load.getValue(0), Load.getValue(1));
10654 /// SimplifySelectCC - Simplify an expression of the form (N0 cond N1) ? N2 : N3
10655 /// where 'cond' is the comparison specified by CC.
10656 SDValue DAGCombiner::SimplifySelectCC(SDLoc DL, SDValue N0, SDValue N1,
10657 SDValue N2, SDValue N3,
10658 ISD::CondCode CC, bool NotExtCompare) {
10659 // (x ? y : y) -> y.
10660 if (N2 == N3) return N2;
10662 EVT VT = N2.getValueType();
10663 ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
10664 ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2.getNode());
10665 ConstantSDNode *N3C = dyn_cast<ConstantSDNode>(N3.getNode());
10667 // Determine if the condition we're dealing with is constant
10668 SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()),
10669 N0, N1, CC, DL, false);
10670 if (SCC.getNode()) AddToWorkList(SCC.getNode());
10671 ConstantSDNode *SCCC = dyn_cast_or_null<ConstantSDNode>(SCC.getNode());
10673 // fold select_cc true, x, y -> x
10674 if (SCCC && !SCCC->isNullValue())
10676 // fold select_cc false, x, y -> y
10677 if (SCCC && SCCC->isNullValue())
10680 // Check to see if we can simplify the select into an fabs node
10681 if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N1)) {
10682 // Allow either -0.0 or 0.0
10683 if (CFP->getValueAPF().isZero()) {
10684 // select (setg[te] X, +/-0.0), X, fneg(X) -> fabs
10685 if ((CC == ISD::SETGE || CC == ISD::SETGT) &&
10686 N0 == N2 && N3.getOpcode() == ISD::FNEG &&
10687 N2 == N3.getOperand(0))
10688 return DAG.getNode(ISD::FABS, DL, VT, N0);
10690 // select (setl[te] X, +/-0.0), fneg(X), X -> fabs
10691 if ((CC == ISD::SETLT || CC == ISD::SETLE) &&
10692 N0 == N3 && N2.getOpcode() == ISD::FNEG &&
10693 N2.getOperand(0) == N3)
10694 return DAG.getNode(ISD::FABS, DL, VT, N3);
10698 // Turn "(a cond b) ? 1.0f : 2.0f" into "load (tmp + ((a cond b) ? 0 : 4)"
10699 // where "tmp" is a constant pool entry containing an array with 1.0 and 2.0
10700 // in it. This is a win when the constant is not otherwise available because
10701 // it replaces two constant pool loads with one. We only do this if the FP
10702 // type is known to be legal, because if it isn't, then we are before legalize
10703 // types an we want the other legalization to happen first (e.g. to avoid
10704 // messing with soft float) and if the ConstantFP is not legal, because if
10705 // it is legal, we may not need to store the FP constant in a constant pool.
10706 if (ConstantFPSDNode *TV = dyn_cast<ConstantFPSDNode>(N2))
10707 if (ConstantFPSDNode *FV = dyn_cast<ConstantFPSDNode>(N3)) {
10708 if (TLI.isTypeLegal(N2.getValueType()) &&
10709 (TLI.getOperationAction(ISD::ConstantFP, N2.getValueType()) !=
10710 TargetLowering::Legal) &&
10711 // If both constants have multiple uses, then we won't need to do an
10712 // extra load, they are likely around in registers for other users.
10713 (TV->hasOneUse() || FV->hasOneUse())) {
10714 Constant *Elts[] = {
10715 const_cast<ConstantFP*>(FV->getConstantFPValue()),
10716 const_cast<ConstantFP*>(TV->getConstantFPValue())
10718 Type *FPTy = Elts[0]->getType();
10719 const DataLayout &TD = *TLI.getDataLayout();
10721 // Create a ConstantArray of the two constants.
10722 Constant *CA = ConstantArray::get(ArrayType::get(FPTy, 2), Elts);
10723 SDValue CPIdx = DAG.getConstantPool(CA, TLI.getPointerTy(),
10724 TD.getPrefTypeAlignment(FPTy));
10725 unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
10727 // Get the offsets to the 0 and 1 element of the array so that we can
10728 // select between them.
10729 SDValue Zero = DAG.getIntPtrConstant(0);
10730 unsigned EltSize = (unsigned)TD.getTypeAllocSize(Elts[0]->getType());
10731 SDValue One = DAG.getIntPtrConstant(EltSize);
10733 SDValue Cond = DAG.getSetCC(DL,
10734 getSetCCResultType(N0.getValueType()),
10736 AddToWorkList(Cond.getNode());
10737 SDValue CstOffset = DAG.getSelect(DL, Zero.getValueType(),
10739 AddToWorkList(CstOffset.getNode());
10740 CPIdx = DAG.getNode(ISD::ADD, DL, CPIdx.getValueType(), CPIdx,
10742 AddToWorkList(CPIdx.getNode());
10743 return DAG.getLoad(TV->getValueType(0), DL, DAG.getEntryNode(), CPIdx,
10744 MachinePointerInfo::getConstantPool(), false,
10745 false, false, Alignment);
10750 // Check to see if we can perform the "gzip trick", transforming
10751 // (select_cc setlt X, 0, A, 0) -> (and (sra X, (sub size(X), 1), A)
10752 if (N1C && N3C && N3C->isNullValue() && CC == ISD::SETLT &&
10753 (N1C->isNullValue() || // (a < 0) ? b : 0
10754 (N1C->getAPIntValue() == 1 && N0 == N2))) { // (a < 1) ? a : 0
10755 EVT XType = N0.getValueType();
10756 EVT AType = N2.getValueType();
10757 if (XType.bitsGE(AType)) {
10758 // and (sra X, size(X)-1, A) -> "and (srl X, C2), A" iff A is a
10759 // single-bit constant.
10760 if (N2C && ((N2C->getAPIntValue() & (N2C->getAPIntValue()-1)) == 0)) {
10761 unsigned ShCtV = N2C->getAPIntValue().logBase2();
10762 ShCtV = XType.getSizeInBits()-ShCtV-1;
10763 SDValue ShCt = DAG.getConstant(ShCtV,
10764 getShiftAmountTy(N0.getValueType()));
10765 SDValue Shift = DAG.getNode(ISD::SRL, SDLoc(N0),
10767 AddToWorkList(Shift.getNode());
10769 if (XType.bitsGT(AType)) {
10770 Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift);
10771 AddToWorkList(Shift.getNode());
10774 return DAG.getNode(ISD::AND, DL, AType, Shift, N2);
10777 SDValue Shift = DAG.getNode(ISD::SRA, SDLoc(N0),
10779 DAG.getConstant(XType.getSizeInBits()-1,
10780 getShiftAmountTy(N0.getValueType())));
10781 AddToWorkList(Shift.getNode());
10783 if (XType.bitsGT(AType)) {
10784 Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift);
10785 AddToWorkList(Shift.getNode());
10788 return DAG.getNode(ISD::AND, DL, AType, Shift, N2);
10792 // fold (select_cc seteq (and x, y), 0, 0, A) -> (and (shr (shl x)) A)
10793 // where y is has a single bit set.
10794 // A plaintext description would be, we can turn the SELECT_CC into an AND
10795 // when the condition can be materialized as an all-ones register. Any
10796 // single bit-test can be materialized as an all-ones register with
10797 // shift-left and shift-right-arith.
10798 if (CC == ISD::SETEQ && N0->getOpcode() == ISD::AND &&
10799 N0->getValueType(0) == VT &&
10800 N1C && N1C->isNullValue() &&
10801 N2C && N2C->isNullValue()) {
10802 SDValue AndLHS = N0->getOperand(0);
10803 ConstantSDNode *ConstAndRHS = dyn_cast<ConstantSDNode>(N0->getOperand(1));
10804 if (ConstAndRHS && ConstAndRHS->getAPIntValue().countPopulation() == 1) {
10805 // Shift the tested bit over the sign bit.
10806 APInt AndMask = ConstAndRHS->getAPIntValue();
10808 DAG.getConstant(AndMask.countLeadingZeros(),
10809 getShiftAmountTy(AndLHS.getValueType()));
10810 SDValue Shl = DAG.getNode(ISD::SHL, SDLoc(N0), VT, AndLHS, ShlAmt);
10812 // Now arithmetic right shift it all the way over, so the result is either
10813 // all-ones, or zero.
10815 DAG.getConstant(AndMask.getBitWidth()-1,
10816 getShiftAmountTy(Shl.getValueType()));
10817 SDValue Shr = DAG.getNode(ISD::SRA, SDLoc(N0), VT, Shl, ShrAmt);
10819 return DAG.getNode(ISD::AND, DL, VT, Shr, N3);
10823 // fold select C, 16, 0 -> shl C, 4
10824 if (N2C && N3C && N3C->isNullValue() && N2C->getAPIntValue().isPowerOf2() &&
10825 TLI.getBooleanContents(N0.getValueType().isVector()) ==
10826 TargetLowering::ZeroOrOneBooleanContent) {
10828 // If the caller doesn't want us to simplify this into a zext of a compare,
10830 if (NotExtCompare && N2C->getAPIntValue() == 1)
10833 // Get a SetCC of the condition
10834 // NOTE: Don't create a SETCC if it's not legal on this target.
10835 if (!LegalOperations ||
10836 TLI.isOperationLegal(ISD::SETCC,
10837 LegalTypes ? getSetCCResultType(N0.getValueType()) : MVT::i1)) {
10839 // cast from setcc result type to select result type
10841 SCC = DAG.getSetCC(DL, getSetCCResultType(N0.getValueType()),
10843 if (N2.getValueType().bitsLT(SCC.getValueType()))
10844 Temp = DAG.getZeroExtendInReg(SCC, SDLoc(N2),
10845 N2.getValueType());
10847 Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2),
10848 N2.getValueType(), SCC);
10850 SCC = DAG.getSetCC(SDLoc(N0), MVT::i1, N0, N1, CC);
10851 Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2),
10852 N2.getValueType(), SCC);
10855 AddToWorkList(SCC.getNode());
10856 AddToWorkList(Temp.getNode());
10858 if (N2C->getAPIntValue() == 1)
10861 // shl setcc result by log2 n2c
10862 return DAG.getNode(
10863 ISD::SHL, DL, N2.getValueType(), Temp,
10864 DAG.getConstant(N2C->getAPIntValue().logBase2(),
10865 getShiftAmountTy(Temp.getValueType())));
10869 // Check to see if this is the equivalent of setcc
10870 // FIXME: Turn all of these into setcc if setcc if setcc is legal
10871 // otherwise, go ahead with the folds.
10872 if (0 && N3C && N3C->isNullValue() && N2C && (N2C->getAPIntValue() == 1ULL)) {
10873 EVT XType = N0.getValueType();
10874 if (!LegalOperations ||
10875 TLI.isOperationLegal(ISD::SETCC, getSetCCResultType(XType))) {
10876 SDValue Res = DAG.getSetCC(DL, getSetCCResultType(XType), N0, N1, CC);
10877 if (Res.getValueType() != VT)
10878 Res = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, Res);
10882 // fold (seteq X, 0) -> (srl (ctlz X, log2(size(X))))
10883 if (N1C && N1C->isNullValue() && CC == ISD::SETEQ &&
10884 (!LegalOperations ||
10885 TLI.isOperationLegal(ISD::CTLZ, XType))) {
10886 SDValue Ctlz = DAG.getNode(ISD::CTLZ, SDLoc(N0), XType, N0);
10887 return DAG.getNode(ISD::SRL, DL, XType, Ctlz,
10888 DAG.getConstant(Log2_32(XType.getSizeInBits()),
10889 getShiftAmountTy(Ctlz.getValueType())));
10891 // fold (setgt X, 0) -> (srl (and (-X, ~X), size(X)-1))
10892 if (N1C && N1C->isNullValue() && CC == ISD::SETGT) {
10893 SDValue NegN0 = DAG.getNode(ISD::SUB, SDLoc(N0),
10894 XType, DAG.getConstant(0, XType), N0);
10895 SDValue NotN0 = DAG.getNOT(SDLoc(N0), N0, XType);
10896 return DAG.getNode(ISD::SRL, DL, XType,
10897 DAG.getNode(ISD::AND, DL, XType, NegN0, NotN0),
10898 DAG.getConstant(XType.getSizeInBits()-1,
10899 getShiftAmountTy(XType)));
10901 // fold (setgt X, -1) -> (xor (srl (X, size(X)-1), 1))
10902 if (N1C && N1C->isAllOnesValue() && CC == ISD::SETGT) {
10903 SDValue Sign = DAG.getNode(ISD::SRL, SDLoc(N0), XType, N0,
10904 DAG.getConstant(XType.getSizeInBits()-1,
10905 getShiftAmountTy(N0.getValueType())));
10906 return DAG.getNode(ISD::XOR, DL, XType, Sign, DAG.getConstant(1, XType));
10910 // Check to see if this is an integer abs.
10911 // select_cc setg[te] X, 0, X, -X ->
10912 // select_cc setgt X, -1, X, -X ->
10913 // select_cc setl[te] X, 0, -X, X ->
10914 // select_cc setlt X, 1, -X, X ->
10915 // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
10917 ConstantSDNode *SubC = NULL;
10918 if (((N1C->isNullValue() && (CC == ISD::SETGT || CC == ISD::SETGE)) ||
10919 (N1C->isAllOnesValue() && CC == ISD::SETGT)) &&
10920 N0 == N2 && N3.getOpcode() == ISD::SUB && N0 == N3.getOperand(1))
10921 SubC = dyn_cast<ConstantSDNode>(N3.getOperand(0));
10922 else if (((N1C->isNullValue() && (CC == ISD::SETLT || CC == ISD::SETLE)) ||
10923 (N1C->isOne() && CC == ISD::SETLT)) &&
10924 N0 == N3 && N2.getOpcode() == ISD::SUB && N0 == N2.getOperand(1))
10925 SubC = dyn_cast<ConstantSDNode>(N2.getOperand(0));
10927 EVT XType = N0.getValueType();
10928 if (SubC && SubC->isNullValue() && XType.isInteger()) {
10929 SDValue Shift = DAG.getNode(ISD::SRA, SDLoc(N0), XType,
10931 DAG.getConstant(XType.getSizeInBits()-1,
10932 getShiftAmountTy(N0.getValueType())));
10933 SDValue Add = DAG.getNode(ISD::ADD, SDLoc(N0),
10935 AddToWorkList(Shift.getNode());
10936 AddToWorkList(Add.getNode());
10937 return DAG.getNode(ISD::XOR, DL, XType, Add, Shift);
10944 /// SimplifySetCC - This is a stub for TargetLowering::SimplifySetCC.
10945 SDValue DAGCombiner::SimplifySetCC(EVT VT, SDValue N0,
10946 SDValue N1, ISD::CondCode Cond,
10947 SDLoc DL, bool foldBooleans) {
10948 TargetLowering::DAGCombinerInfo
10949 DagCombineInfo(DAG, Level, false, this);
10950 return TLI.SimplifySetCC(VT, N0, N1, Cond, foldBooleans, DagCombineInfo, DL);
10953 /// BuildSDIVSequence - Given an ISD::SDIV node expressing a divide by constant,
10954 /// return a DAG expression to select that will generate the same value by
10955 /// multiplying by a magic number. See:
10956 /// <http://the.wall.riscom.net/books/proc/ppc/cwg/code2.html>
10957 SDValue DAGCombiner::BuildSDIV(SDNode *N) {
10958 std::vector<SDNode*> Built;
10959 SDValue S = TLI.BuildSDIV(N, DAG, LegalOperations, &Built);
10961 for (std::vector<SDNode*>::iterator ii = Built.begin(), ee = Built.end();
10963 AddToWorkList(*ii);
10967 /// BuildUDIVSequence - Given an ISD::UDIV node expressing a divide by constant,
10968 /// return a DAG expression to select that will generate the same value by
10969 /// multiplying by a magic number. See:
10970 /// <http://the.wall.riscom.net/books/proc/ppc/cwg/code2.html>
10971 SDValue DAGCombiner::BuildUDIV(SDNode *N) {
10972 std::vector<SDNode*> Built;
10973 SDValue S = TLI.BuildUDIV(N, DAG, LegalOperations, &Built);
10975 for (std::vector<SDNode*>::iterator ii = Built.begin(), ee = Built.end();
10977 AddToWorkList(*ii);
10981 /// FindBaseOffset - Return true if base is a frame index, which is known not
10982 // to alias with anything but itself. Provides base object and offset as
10984 static bool FindBaseOffset(SDValue Ptr, SDValue &Base, int64_t &Offset,
10985 const GlobalValue *&GV, const void *&CV) {
10986 // Assume it is a primitive operation.
10987 Base = Ptr; Offset = 0; GV = 0; CV = 0;
10989 // If it's an adding a simple constant then integrate the offset.
10990 if (Base.getOpcode() == ISD::ADD) {
10991 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Base.getOperand(1))) {
10992 Base = Base.getOperand(0);
10993 Offset += C->getZExtValue();
10997 // Return the underlying GlobalValue, and update the Offset. Return false
10998 // for GlobalAddressSDNode since the same GlobalAddress may be represented
10999 // by multiple nodes with different offsets.
11000 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Base)) {
11001 GV = G->getGlobal();
11002 Offset += G->getOffset();
11006 // Return the underlying Constant value, and update the Offset. Return false
11007 // for ConstantSDNodes since the same constant pool entry may be represented
11008 // by multiple nodes with different offsets.
11009 if (ConstantPoolSDNode *C = dyn_cast<ConstantPoolSDNode>(Base)) {
11010 CV = C->isMachineConstantPoolEntry() ? (const void *)C->getMachineCPVal()
11011 : (const void *)C->getConstVal();
11012 Offset += C->getOffset();
11015 // If it's any of the following then it can't alias with anything but itself.
11016 return isa<FrameIndexSDNode>(Base);
11019 /// isAlias - Return true if there is any possibility that the two addresses
11021 bool DAGCombiner::isAlias(SDValue Ptr1, int64_t Size1, bool IsVolatile1,
11022 const Value *SrcValue1, int SrcValueOffset1,
11023 unsigned SrcValueAlign1,
11024 const MDNode *TBAAInfo1,
11025 SDValue Ptr2, int64_t Size2, bool IsVolatile2,
11026 const Value *SrcValue2, int SrcValueOffset2,
11027 unsigned SrcValueAlign2,
11028 const MDNode *TBAAInfo2) const {
11029 // If they are the same then they must be aliases.
11030 if (Ptr1 == Ptr2) return true;
11032 // If they are both volatile then they cannot be reordered.
11033 if (IsVolatile1 && IsVolatile2) return true;
11035 // Gather base node and offset information.
11036 SDValue Base1, Base2;
11037 int64_t Offset1, Offset2;
11038 const GlobalValue *GV1, *GV2;
11039 const void *CV1, *CV2;
11040 bool isFrameIndex1 = FindBaseOffset(Ptr1, Base1, Offset1, GV1, CV1);
11041 bool isFrameIndex2 = FindBaseOffset(Ptr2, Base2, Offset2, GV2, CV2);
11043 // If they have a same base address then check to see if they overlap.
11044 if (Base1 == Base2 || (GV1 && (GV1 == GV2)) || (CV1 && (CV1 == CV2)))
11045 return !((Offset1 + Size1) <= Offset2 || (Offset2 + Size2) <= Offset1);
11047 // It is possible for different frame indices to alias each other, mostly
11048 // when tail call optimization reuses return address slots for arguments.
11049 // To catch this case, look up the actual index of frame indices to compute
11050 // the real alias relationship.
11051 if (isFrameIndex1 && isFrameIndex2) {
11052 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
11053 Offset1 += MFI->getObjectOffset(cast<FrameIndexSDNode>(Base1)->getIndex());
11054 Offset2 += MFI->getObjectOffset(cast<FrameIndexSDNode>(Base2)->getIndex());
11055 return !((Offset1 + Size1) <= Offset2 || (Offset2 + Size2) <= Offset1);
11058 // Otherwise, if we know what the bases are, and they aren't identical, then
11059 // we know they cannot alias.
11060 if ((isFrameIndex1 || CV1 || GV1) && (isFrameIndex2 || CV2 || GV2))
11063 // If we know required SrcValue1 and SrcValue2 have relatively large alignment
11064 // compared to the size and offset of the access, we may be able to prove they
11065 // do not alias. This check is conservative for now to catch cases created by
11066 // splitting vector types.
11067 if ((SrcValueAlign1 == SrcValueAlign2) &&
11068 (SrcValueOffset1 != SrcValueOffset2) &&
11069 (Size1 == Size2) && (SrcValueAlign1 > Size1)) {
11070 int64_t OffAlign1 = SrcValueOffset1 % SrcValueAlign1;
11071 int64_t OffAlign2 = SrcValueOffset2 % SrcValueAlign1;
11073 // There is no overlap between these relatively aligned accesses of similar
11074 // size, return no alias.
11075 if ((OffAlign1 + Size1) <= OffAlign2 || (OffAlign2 + Size2) <= OffAlign1)
11079 bool UseAA = CombinerGlobalAA.getNumOccurrences() > 0 ? CombinerGlobalAA :
11080 TLI.getTargetMachine().getSubtarget<TargetSubtargetInfo>().useAA();
11082 if (CombinerAAOnlyFunc.getNumOccurrences() &&
11083 CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
11086 if (UseAA && SrcValue1 && SrcValue2) {
11087 // Use alias analysis information.
11088 int64_t MinOffset = std::min(SrcValueOffset1, SrcValueOffset2);
11089 int64_t Overlap1 = Size1 + SrcValueOffset1 - MinOffset;
11090 int64_t Overlap2 = Size2 + SrcValueOffset2 - MinOffset;
11091 AliasAnalysis::AliasResult AAResult =
11092 AA.alias(AliasAnalysis::Location(SrcValue1, Overlap1,
11093 UseTBAA ? TBAAInfo1 : 0),
11094 AliasAnalysis::Location(SrcValue2, Overlap2,
11095 UseTBAA ? TBAAInfo2 : 0));
11096 if (AAResult == AliasAnalysis::NoAlias)
11100 // Otherwise we have to assume they alias.
11104 bool DAGCombiner::isAlias(LSBaseSDNode *Op0, LSBaseSDNode *Op1) {
11105 SDValue Ptr0, Ptr1;
11106 int64_t Size0, Size1;
11107 bool IsVolatile0, IsVolatile1;
11108 const Value *SrcValue0, *SrcValue1;
11109 int SrcValueOffset0, SrcValueOffset1;
11110 unsigned SrcValueAlign0, SrcValueAlign1;
11111 const MDNode *SrcTBAAInfo0, *SrcTBAAInfo1;
11112 FindAliasInfo(Op0, Ptr0, Size0, IsVolatile0, SrcValue0, SrcValueOffset0,
11113 SrcValueAlign0, SrcTBAAInfo0);
11114 FindAliasInfo(Op1, Ptr1, Size1, IsVolatile1, SrcValue1, SrcValueOffset1,
11115 SrcValueAlign1, SrcTBAAInfo1);
11116 return isAlias(Ptr0, Size0, IsVolatile0, SrcValue0, SrcValueOffset0,
11117 SrcValueAlign0, SrcTBAAInfo0,
11118 Ptr1, Size1, IsVolatile1, SrcValue1, SrcValueOffset1,
11119 SrcValueAlign1, SrcTBAAInfo1);
11122 /// FindAliasInfo - Extracts the relevant alias information from the memory
11123 /// node. Returns true if the operand was a nonvolatile load.
11124 bool DAGCombiner::FindAliasInfo(SDNode *N,
11125 SDValue &Ptr, int64_t &Size, bool &IsVolatile,
11126 const Value *&SrcValue,
11127 int &SrcValueOffset,
11128 unsigned &SrcValueAlign,
11129 const MDNode *&TBAAInfo) const {
11130 LSBaseSDNode *LS = cast<LSBaseSDNode>(N);
11132 Ptr = LS->getBasePtr();
11133 Size = LS->getMemoryVT().getSizeInBits() >> 3;
11134 IsVolatile = LS->isVolatile();
11135 SrcValue = LS->getSrcValue();
11136 SrcValueOffset = LS->getSrcValueOffset();
11137 SrcValueAlign = LS->getOriginalAlignment();
11138 TBAAInfo = LS->getTBAAInfo();
11139 return isa<LoadSDNode>(LS) && !IsVolatile;
11142 /// GatherAllAliases - Walk up chain skipping non-aliasing memory nodes,
11143 /// looking for aliasing nodes and adding them to the Aliases vector.
11144 void DAGCombiner::GatherAllAliases(SDNode *N, SDValue OriginalChain,
11145 SmallVectorImpl<SDValue> &Aliases) {
11146 SmallVector<SDValue, 8> Chains; // List of chains to visit.
11147 SmallPtrSet<SDNode *, 16> Visited; // Visited node set.
11149 // Get alias information for node.
11153 const Value *SrcValue;
11154 int SrcValueOffset;
11155 unsigned SrcValueAlign;
11156 const MDNode *SrcTBAAInfo;
11157 bool IsLoad = FindAliasInfo(N, Ptr, Size, IsVolatile, SrcValue,
11158 SrcValueOffset, SrcValueAlign, SrcTBAAInfo);
11161 Chains.push_back(OriginalChain);
11162 unsigned Depth = 0;
11164 // Look at each chain and determine if it is an alias. If so, add it to the
11165 // aliases list. If not, then continue up the chain looking for the next
11167 while (!Chains.empty()) {
11168 SDValue Chain = Chains.back();
11171 // For TokenFactor nodes, look at each operand and only continue up the
11172 // chain until we find two aliases. If we've seen two aliases, assume we'll
11173 // find more and revert to original chain since the xform is unlikely to be
11176 // FIXME: The depth check could be made to return the last non-aliasing
11177 // chain we found before we hit a tokenfactor rather than the original
11179 if (Depth > 6 || Aliases.size() == 2) {
11181 Aliases.push_back(OriginalChain);
11185 // Don't bother if we've been before.
11186 if (!Visited.insert(Chain.getNode()))
11189 switch (Chain.getOpcode()) {
11190 case ISD::EntryToken:
11191 // Entry token is ideal chain operand, but handled in FindBetterChain.
11196 // Get alias information for Chain.
11200 const Value *OpSrcValue;
11201 int OpSrcValueOffset;
11202 unsigned OpSrcValueAlign;
11203 const MDNode *OpSrcTBAAInfo;
11204 bool IsOpLoad = FindAliasInfo(Chain.getNode(), OpPtr, OpSize,
11205 OpIsVolatile, OpSrcValue, OpSrcValueOffset,
11209 // If chain is alias then stop here.
11210 if (!(IsLoad && IsOpLoad) &&
11211 isAlias(Ptr, Size, IsVolatile, SrcValue, SrcValueOffset,
11212 SrcValueAlign, SrcTBAAInfo,
11213 OpPtr, OpSize, OpIsVolatile, OpSrcValue, OpSrcValueOffset,
11214 OpSrcValueAlign, OpSrcTBAAInfo)) {
11215 Aliases.push_back(Chain);
11217 // Look further up the chain.
11218 Chains.push_back(Chain.getOperand(0));
11224 case ISD::TokenFactor:
11225 // We have to check each of the operands of the token factor for "small"
11226 // token factors, so we queue them up. Adding the operands to the queue
11227 // (stack) in reverse order maintains the original order and increases the
11228 // likelihood that getNode will find a matching token factor (CSE.)
11229 if (Chain.getNumOperands() > 16) {
11230 Aliases.push_back(Chain);
11233 for (unsigned n = Chain.getNumOperands(); n;)
11234 Chains.push_back(Chain.getOperand(--n));
11239 // For all other instructions we will just have to take what we can get.
11240 Aliases.push_back(Chain);
11245 // We need to be careful here to also search for aliases through the
11246 // value operand of a store, etc. Consider the following situation:
11248 // L1 = load Token1, %52
11249 // S1 = store Token1, L1, %51
11250 // L2 = load Token1, %52+8
11251 // S2 = store Token1, L2, %51+8
11252 // Token2 = Token(S1, S2)
11253 // L3 = load Token2, %53
11254 // S3 = store Token2, L3, %52
11255 // L4 = load Token2, %53+8
11256 // S4 = store Token2, L4, %52+8
11257 // If we search for aliases of S3 (which loads address %52), and we look
11258 // only through the chain, then we'll miss the trivial dependence on L1
11259 // (which also loads from %52). We then might change all loads and
11260 // stores to use Token1 as their chain operand, which could result in
11261 // copying %53 into %52 before copying %52 into %51 (which should
11264 // The problem is, however, that searching for such data dependencies
11265 // can become expensive, and the cost is not directly related to the
11266 // chain depth. Instead, we'll rule out such configurations here by
11267 // insisting that we've visited all chain users (except for users
11268 // of the original chain, which is not necessary). When doing this,
11269 // we need to look through nodes we don't care about (otherwise, things
11270 // like register copies will interfere with trivial cases).
11272 SmallVector<const SDNode *, 16> Worklist;
11273 for (SmallPtrSet<SDNode *, 16>::iterator I = Visited.begin(),
11274 IE = Visited.end(); I != IE; ++I)
11275 if (*I != OriginalChain.getNode())
11276 Worklist.push_back(*I);
11278 while (!Worklist.empty()) {
11279 const SDNode *M = Worklist.pop_back_val();
11281 // We have already visited M, and want to make sure we've visited any uses
11282 // of M that we care about. For uses that we've not visisted, and don't
11283 // care about, queue them to the worklist.
11285 for (SDNode::use_iterator UI = M->use_begin(),
11286 UIE = M->use_end(); UI != UIE; ++UI)
11287 if (UI.getUse().getValueType() == MVT::Other && Visited.insert(*UI)) {
11288 if (isa<MemIntrinsicSDNode>(*UI) || isa<MemSDNode>(*UI)) {
11289 // We've not visited this use, and we care about it (it could have an
11290 // ordering dependency with the original node).
11292 Aliases.push_back(OriginalChain);
11296 // We've not visited this use, but we don't care about it. Mark it as
11297 // visited and enqueue it to the worklist.
11298 Worklist.push_back(*UI);
11303 /// FindBetterChain - Walk up chain skipping non-aliasing memory nodes, looking
11304 /// for a better chain (aliasing node.)
11305 SDValue DAGCombiner::FindBetterChain(SDNode *N, SDValue OldChain) {
11306 SmallVector<SDValue, 8> Aliases; // Ops for replacing token factor.
11308 // Accumulate all the aliases to this node.
11309 GatherAllAliases(N, OldChain, Aliases);
11311 // If no operands then chain to entry token.
11312 if (Aliases.size() == 0)
11313 return DAG.getEntryNode();
11315 // If a single operand then chain to it. We don't need to revisit it.
11316 if (Aliases.size() == 1)
11319 // Construct a custom tailored token factor.
11320 return DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other,
11321 &Aliases[0], Aliases.size());
11324 // SelectionDAG::Combine - This is the entry point for the file.
11326 void SelectionDAG::Combine(CombineLevel Level, AliasAnalysis &AA,
11327 CodeGenOpt::Level OptLevel) {
11328 /// run - This is the main entry point to this class.
11330 DAGCombiner(*this, AA, OptLevel).Run(Level);