Re-apply the change from r191393 with fix for pr17380.
[oota-llvm.git] / lib / CodeGen / SelectionDAG / DAGCombiner.cpp
1 //===-- DAGCombiner.cpp - Implement a DAG node combiner -------------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
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.
12 //
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.
16 //
17 //===----------------------------------------------------------------------===//
18
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/TargetSubtargetInfo.h"
39 #include <algorithm>
40 using namespace llvm;
41
42 STATISTIC(NodesCombined   , "Number of dag nodes combined");
43 STATISTIC(PreIndexedNodes , "Number of pre-indexed nodes created");
44 STATISTIC(PostIndexedNodes, "Number of post-indexed nodes created");
45 STATISTIC(OpsNarrowed     , "Number of load/op/store narrowed");
46 STATISTIC(LdStFP2Int      , "Number of fp load/store pairs transformed to int");
47
48 namespace {
49   static cl::opt<bool>
50     CombinerAA("combiner-alias-analysis", cl::Hidden,
51                cl::desc("Turn on alias analysis during testing"));
52
53   static cl::opt<bool>
54     CombinerGlobalAA("combiner-global-alias-analysis", cl::Hidden,
55                cl::desc("Include global information in alias analysis"));
56
57 //------------------------------ DAGCombiner ---------------------------------//
58
59   class DAGCombiner {
60     SelectionDAG &DAG;
61     const TargetLowering &TLI;
62     CombineLevel Level;
63     CodeGenOpt::Level OptLevel;
64     bool LegalOperations;
65     bool LegalTypes;
66
67     // Worklist of all of the nodes that need to be simplified.
68     //
69     // This has the semantics that when adding to the worklist,
70     // the item added must be next to be processed. It should
71     // also only appear once. The naive approach to this takes
72     // linear time.
73     //
74     // To reduce the insert/remove time to logarithmic, we use
75     // a set and a vector to maintain our worklist.
76     //
77     // The set contains the items on the worklist, but does not
78     // maintain the order they should be visited.
79     //
80     // The vector maintains the order nodes should be visited, but may
81     // contain duplicate or removed nodes. When choosing a node to
82     // visit, we pop off the order stack until we find an item that is
83     // also in the contents set. All operations are O(log N).
84     SmallPtrSet<SDNode*, 64> WorkListContents;
85     SmallVector<SDNode*, 64> WorkListOrder;
86
87     // AA - Used for DAG load/store alias analysis.
88     AliasAnalysis &AA;
89
90     /// AddUsersToWorkList - When an instruction is simplified, add all users of
91     /// the instruction to the work lists because they might get more simplified
92     /// now.
93     ///
94     void AddUsersToWorkList(SDNode *N) {
95       for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
96            UI != UE; ++UI)
97         AddToWorkList(*UI);
98     }
99
100     /// visit - call the node-specific routine that knows how to fold each
101     /// particular type of node.
102     SDValue visit(SDNode *N);
103
104   public:
105     /// AddToWorkList - Add to the work list making sure its instance is at the
106     /// back (next to be processed.)
107     void AddToWorkList(SDNode *N) {
108       WorkListContents.insert(N);
109       WorkListOrder.push_back(N);
110     }
111
112     /// removeFromWorkList - remove all instances of N from the worklist.
113     ///
114     void removeFromWorkList(SDNode *N) {
115       WorkListContents.erase(N);
116     }
117
118     SDValue CombineTo(SDNode *N, const SDValue *To, unsigned NumTo,
119                       bool AddTo = true);
120
121     SDValue CombineTo(SDNode *N, SDValue Res, bool AddTo = true) {
122       return CombineTo(N, &Res, 1, AddTo);
123     }
124
125     SDValue CombineTo(SDNode *N, SDValue Res0, SDValue Res1,
126                       bool AddTo = true) {
127       SDValue To[] = { Res0, Res1 };
128       return CombineTo(N, To, 2, AddTo);
129     }
130
131     void CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO);
132
133   private:
134
135     /// SimplifyDemandedBits - Check the specified integer node value to see if
136     /// it can be simplified or if things it uses can be simplified by bit
137     /// propagation.  If so, return true.
138     bool SimplifyDemandedBits(SDValue Op) {
139       unsigned BitWidth = Op.getValueType().getScalarType().getSizeInBits();
140       APInt Demanded = APInt::getAllOnesValue(BitWidth);
141       return SimplifyDemandedBits(Op, Demanded);
142     }
143
144     bool SimplifyDemandedBits(SDValue Op, const APInt &Demanded);
145
146     bool CombineToPreIndexedLoadStore(SDNode *N);
147     bool CombineToPostIndexedLoadStore(SDNode *N);
148
149     void ReplaceLoadWithPromotedLoad(SDNode *Load, SDNode *ExtLoad);
150     SDValue PromoteOperand(SDValue Op, EVT PVT, bool &Replace);
151     SDValue SExtPromoteOperand(SDValue Op, EVT PVT);
152     SDValue ZExtPromoteOperand(SDValue Op, EVT PVT);
153     SDValue PromoteIntBinOp(SDValue Op);
154     SDValue PromoteIntShiftOp(SDValue Op);
155     SDValue PromoteExtend(SDValue Op);
156     bool PromoteLoad(SDValue Op);
157
158     void ExtendSetCCUses(const SmallVectorImpl<SDNode *> &SetCCs,
159                          SDValue Trunc, SDValue ExtLoad, SDLoc DL,
160                          ISD::NodeType ExtType);
161
162     /// combine - call the node-specific routine that knows how to fold each
163     /// particular type of node. If that doesn't do anything, try the
164     /// target-specific DAG combines.
165     SDValue combine(SDNode *N);
166
167     // Visitation implementation - Implement dag node combining for different
168     // node types.  The semantics are as follows:
169     // Return Value:
170     //   SDValue.getNode() == 0 - No change was made
171     //   SDValue.getNode() == N - N was replaced, is dead and has been handled.
172     //   otherwise              - N should be replaced by the returned Operand.
173     //
174     SDValue visitTokenFactor(SDNode *N);
175     SDValue visitMERGE_VALUES(SDNode *N);
176     SDValue visitADD(SDNode *N);
177     SDValue visitSUB(SDNode *N);
178     SDValue visitADDC(SDNode *N);
179     SDValue visitSUBC(SDNode *N);
180     SDValue visitADDE(SDNode *N);
181     SDValue visitSUBE(SDNode *N);
182     SDValue visitMUL(SDNode *N);
183     SDValue visitSDIV(SDNode *N);
184     SDValue visitUDIV(SDNode *N);
185     SDValue visitSREM(SDNode *N);
186     SDValue visitUREM(SDNode *N);
187     SDValue visitMULHU(SDNode *N);
188     SDValue visitMULHS(SDNode *N);
189     SDValue visitSMUL_LOHI(SDNode *N);
190     SDValue visitUMUL_LOHI(SDNode *N);
191     SDValue visitSMULO(SDNode *N);
192     SDValue visitUMULO(SDNode *N);
193     SDValue visitSDIVREM(SDNode *N);
194     SDValue visitUDIVREM(SDNode *N);
195     SDValue visitAND(SDNode *N);
196     SDValue visitOR(SDNode *N);
197     SDValue visitXOR(SDNode *N);
198     SDValue SimplifyVBinOp(SDNode *N);
199     SDValue SimplifyVUnaryOp(SDNode *N);
200     SDValue visitSHL(SDNode *N);
201     SDValue visitSRA(SDNode *N);
202     SDValue visitSRL(SDNode *N);
203     SDValue visitCTLZ(SDNode *N);
204     SDValue visitCTLZ_ZERO_UNDEF(SDNode *N);
205     SDValue visitCTTZ(SDNode *N);
206     SDValue visitCTTZ_ZERO_UNDEF(SDNode *N);
207     SDValue visitCTPOP(SDNode *N);
208     SDValue visitSELECT(SDNode *N);
209     SDValue visitVSELECT(SDNode *N);
210     SDValue visitSELECT_CC(SDNode *N);
211     SDValue visitSETCC(SDNode *N);
212     SDValue visitSIGN_EXTEND(SDNode *N);
213     SDValue visitZERO_EXTEND(SDNode *N);
214     SDValue visitANY_EXTEND(SDNode *N);
215     SDValue visitSIGN_EXTEND_INREG(SDNode *N);
216     SDValue visitTRUNCATE(SDNode *N);
217     SDValue visitBITCAST(SDNode *N);
218     SDValue visitBUILD_PAIR(SDNode *N);
219     SDValue visitFADD(SDNode *N);
220     SDValue visitFSUB(SDNode *N);
221     SDValue visitFMUL(SDNode *N);
222     SDValue visitFMA(SDNode *N);
223     SDValue visitFDIV(SDNode *N);
224     SDValue visitFREM(SDNode *N);
225     SDValue visitFCOPYSIGN(SDNode *N);
226     SDValue visitSINT_TO_FP(SDNode *N);
227     SDValue visitUINT_TO_FP(SDNode *N);
228     SDValue visitFP_TO_SINT(SDNode *N);
229     SDValue visitFP_TO_UINT(SDNode *N);
230     SDValue visitFP_ROUND(SDNode *N);
231     SDValue visitFP_ROUND_INREG(SDNode *N);
232     SDValue visitFP_EXTEND(SDNode *N);
233     SDValue visitFNEG(SDNode *N);
234     SDValue visitFABS(SDNode *N);
235     SDValue visitFCEIL(SDNode *N);
236     SDValue visitFTRUNC(SDNode *N);
237     SDValue visitFFLOOR(SDNode *N);
238     SDValue visitBRCOND(SDNode *N);
239     SDValue visitBR_CC(SDNode *N);
240     SDValue visitLOAD(SDNode *N);
241     SDValue visitSTORE(SDNode *N);
242     SDValue visitINSERT_VECTOR_ELT(SDNode *N);
243     SDValue visitEXTRACT_VECTOR_ELT(SDNode *N);
244     SDValue visitBUILD_VECTOR(SDNode *N);
245     SDValue visitCONCAT_VECTORS(SDNode *N);
246     SDValue visitEXTRACT_SUBVECTOR(SDNode *N);
247     SDValue visitVECTOR_SHUFFLE(SDNode *N);
248
249     SDValue XformToShuffleWithZero(SDNode *N);
250     SDValue ReassociateOps(unsigned Opc, SDLoc DL, SDValue LHS, SDValue RHS);
251
252     SDValue visitShiftByConstant(SDNode *N, unsigned Amt);
253
254     bool SimplifySelectOps(SDNode *SELECT, SDValue LHS, SDValue RHS);
255     SDValue SimplifyBinOpWithSameOpcodeHands(SDNode *N);
256     SDValue SimplifySelect(SDLoc DL, SDValue N0, SDValue N1, SDValue N2);
257     SDValue SimplifySelectCC(SDLoc DL, SDValue N0, SDValue N1, SDValue N2,
258                              SDValue N3, ISD::CondCode CC,
259                              bool NotExtCompare = false);
260     SDValue SimplifySetCC(EVT VT, SDValue N0, SDValue N1, ISD::CondCode Cond,
261                           SDLoc DL, bool foldBooleans = true);
262     SDValue SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp,
263                                          unsigned HiOp);
264     SDValue CombineConsecutiveLoads(SDNode *N, EVT VT);
265     SDValue ConstantFoldBITCASTofBUILD_VECTOR(SDNode *, EVT);
266     SDValue BuildSDIV(SDNode *N);
267     SDValue BuildUDIV(SDNode *N);
268     SDValue MatchBSwapHWordLow(SDNode *N, SDValue N0, SDValue N1,
269                                bool DemandHighBits = true);
270     SDValue MatchBSwapHWord(SDNode *N, SDValue N0, SDValue N1);
271     SDNode *MatchRotate(SDValue LHS, SDValue RHS, SDLoc DL);
272     SDValue ReduceLoadWidth(SDNode *N);
273     SDValue ReduceLoadOpStoreWidth(SDNode *N);
274     SDValue TransformFPLoadStorePair(SDNode *N);
275     SDValue reduceBuildVecExtToExtBuildVec(SDNode *N);
276     SDValue reduceBuildVecConvertToConvertBuildVec(SDNode *N);
277
278     SDValue GetDemandedBits(SDValue V, const APInt &Mask);
279
280     /// GatherAllAliases - Walk up chain skipping non-aliasing memory nodes,
281     /// looking for aliasing nodes and adding them to the Aliases vector.
282     void GatherAllAliases(SDNode *N, SDValue OriginalChain,
283                           SmallVectorImpl<SDValue> &Aliases);
284
285     /// isAlias - Return true if there is any possibility that the two addresses
286     /// overlap.
287     bool isAlias(SDValue Ptr1, int64_t Size1,
288                  const Value *SrcValue1, int SrcValueOffset1,
289                  unsigned SrcValueAlign1,
290                  const MDNode *TBAAInfo1,
291                  SDValue Ptr2, int64_t Size2,
292                  const Value *SrcValue2, int SrcValueOffset2,
293                  unsigned SrcValueAlign2,
294                  const MDNode *TBAAInfo2) const;
295
296     /// isAlias - Return true if there is any possibility that the two addresses
297     /// overlap.
298     bool isAlias(LSBaseSDNode *Op0, LSBaseSDNode *Op1);
299
300     /// FindAliasInfo - Extracts the relevant alias information from the memory
301     /// node.  Returns true if the operand was a load.
302     bool FindAliasInfo(SDNode *N,
303                        SDValue &Ptr, int64_t &Size,
304                        const Value *&SrcValue, int &SrcValueOffset,
305                        unsigned &SrcValueAlignment,
306                        const MDNode *&TBAAInfo) const;
307
308     /// FindBetterChain - Walk up chain skipping non-aliasing memory nodes,
309     /// looking for a better chain (aliasing node.)
310     SDValue FindBetterChain(SDNode *N, SDValue Chain);
311
312     /// Merge consecutive store operations into a wide store.
313     /// This optimization uses wide integers or vectors when possible.
314     /// \return True if some memory operations were changed.
315     bool MergeConsecutiveStores(StoreSDNode *N);
316
317   public:
318     DAGCombiner(SelectionDAG &D, AliasAnalysis &A, CodeGenOpt::Level OL)
319       : DAG(D), TLI(D.getTargetLoweringInfo()), Level(BeforeLegalizeTypes),
320         OptLevel(OL), LegalOperations(false), LegalTypes(false), AA(A) {}
321
322     /// Run - runs the dag combiner on all nodes in the work list
323     void Run(CombineLevel AtLevel);
324
325     SelectionDAG &getDAG() const { return DAG; }
326
327     /// getShiftAmountTy - Returns a type large enough to hold any valid
328     /// shift amount - before type legalization these can be huge.
329     EVT getShiftAmountTy(EVT LHSTy) {
330       assert(LHSTy.isInteger() && "Shift amount is not an integer type!");
331       if (LHSTy.isVector())
332         return LHSTy;
333       return LegalTypes ? TLI.getScalarShiftAmountTy(LHSTy) : TLI.getPointerTy();
334     }
335
336     /// isTypeLegal - This method returns true if we are running before type
337     /// legalization or if the specified VT is legal.
338     bool isTypeLegal(const EVT &VT) {
339       if (!LegalTypes) return true;
340       return TLI.isTypeLegal(VT);
341     }
342
343     /// getSetCCResultType - Convenience wrapper around
344     /// TargetLowering::getSetCCResultType
345     EVT getSetCCResultType(EVT VT) const {
346       return TLI.getSetCCResultType(*DAG.getContext(), VT);
347     }
348   };
349 }
350
351
352 namespace {
353 /// WorkListRemover - This class is a DAGUpdateListener that removes any deleted
354 /// nodes from the worklist.
355 class WorkListRemover : public SelectionDAG::DAGUpdateListener {
356   DAGCombiner &DC;
357 public:
358   explicit WorkListRemover(DAGCombiner &dc)
359     : SelectionDAG::DAGUpdateListener(dc.getDAG()), DC(dc) {}
360
361   virtual void NodeDeleted(SDNode *N, SDNode *E) {
362     DC.removeFromWorkList(N);
363   }
364 };
365 }
366
367 //===----------------------------------------------------------------------===//
368 //  TargetLowering::DAGCombinerInfo implementation
369 //===----------------------------------------------------------------------===//
370
371 void TargetLowering::DAGCombinerInfo::AddToWorklist(SDNode *N) {
372   ((DAGCombiner*)DC)->AddToWorkList(N);
373 }
374
375 void TargetLowering::DAGCombinerInfo::RemoveFromWorklist(SDNode *N) {
376   ((DAGCombiner*)DC)->removeFromWorkList(N);
377 }
378
379 SDValue TargetLowering::DAGCombinerInfo::
380 CombineTo(SDNode *N, const std::vector<SDValue> &To, bool AddTo) {
381   return ((DAGCombiner*)DC)->CombineTo(N, &To[0], To.size(), AddTo);
382 }
383
384 SDValue TargetLowering::DAGCombinerInfo::
385 CombineTo(SDNode *N, SDValue Res, bool AddTo) {
386   return ((DAGCombiner*)DC)->CombineTo(N, Res, AddTo);
387 }
388
389
390 SDValue TargetLowering::DAGCombinerInfo::
391 CombineTo(SDNode *N, SDValue Res0, SDValue Res1, bool AddTo) {
392   return ((DAGCombiner*)DC)->CombineTo(N, Res0, Res1, AddTo);
393 }
394
395 void TargetLowering::DAGCombinerInfo::
396 CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) {
397   return ((DAGCombiner*)DC)->CommitTargetLoweringOpt(TLO);
398 }
399
400 //===----------------------------------------------------------------------===//
401 // Helper Functions
402 //===----------------------------------------------------------------------===//
403
404 /// isNegatibleForFree - Return 1 if we can compute the negated form of the
405 /// specified expression for the same cost as the expression itself, or 2 if we
406 /// can compute the negated form more cheaply than the expression itself.
407 static char isNegatibleForFree(SDValue Op, bool LegalOperations,
408                                const TargetLowering &TLI,
409                                const TargetOptions *Options,
410                                unsigned Depth = 0) {
411   // fneg is removable even if it has multiple uses.
412   if (Op.getOpcode() == ISD::FNEG) return 2;
413
414   // Don't allow anything with multiple uses.
415   if (!Op.hasOneUse()) return 0;
416
417   // Don't recurse exponentially.
418   if (Depth > 6) return 0;
419
420   switch (Op.getOpcode()) {
421   default: return false;
422   case ISD::ConstantFP:
423     // Don't invert constant FP values after legalize.  The negated constant
424     // isn't necessarily legal.
425     return LegalOperations ? 0 : 1;
426   case ISD::FADD:
427     // FIXME: determine better conditions for this xform.
428     if (!Options->UnsafeFPMath) return 0;
429
430     // After operation legalization, it might not be legal to create new FSUBs.
431     if (LegalOperations &&
432         !TLI.isOperationLegalOrCustom(ISD::FSUB,  Op.getValueType()))
433       return 0;
434
435     // fold (fneg (fadd A, B)) -> (fsub (fneg A), B)
436     if (char V = isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI,
437                                     Options, Depth + 1))
438       return V;
439     // fold (fneg (fadd A, B)) -> (fsub (fneg B), A)
440     return isNegatibleForFree(Op.getOperand(1), LegalOperations, TLI, Options,
441                               Depth + 1);
442   case ISD::FSUB:
443     // We can't turn -(A-B) into B-A when we honor signed zeros.
444     if (!Options->UnsafeFPMath) return 0;
445
446     // fold (fneg (fsub A, B)) -> (fsub B, A)
447     return 1;
448
449   case ISD::FMUL:
450   case ISD::FDIV:
451     if (Options->HonorSignDependentRoundingFPMath()) return 0;
452
453     // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y) or (fmul X, (fneg Y))
454     if (char V = isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI,
455                                     Options, Depth + 1))
456       return V;
457
458     return isNegatibleForFree(Op.getOperand(1), LegalOperations, TLI, Options,
459                               Depth + 1);
460
461   case ISD::FP_EXTEND:
462   case ISD::FP_ROUND:
463   case ISD::FSIN:
464     return isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI, Options,
465                               Depth + 1);
466   }
467 }
468
469 /// GetNegatedExpression - If isNegatibleForFree returns true, this function
470 /// returns the newly negated expression.
471 static SDValue GetNegatedExpression(SDValue Op, SelectionDAG &DAG,
472                                     bool LegalOperations, unsigned Depth = 0) {
473   // fneg is removable even if it has multiple uses.
474   if (Op.getOpcode() == ISD::FNEG) return Op.getOperand(0);
475
476   // Don't allow anything with multiple uses.
477   assert(Op.hasOneUse() && "Unknown reuse!");
478
479   assert(Depth <= 6 && "GetNegatedExpression doesn't match isNegatibleForFree");
480   switch (Op.getOpcode()) {
481   default: llvm_unreachable("Unknown code");
482   case ISD::ConstantFP: {
483     APFloat V = cast<ConstantFPSDNode>(Op)->getValueAPF();
484     V.changeSign();
485     return DAG.getConstantFP(V, Op.getValueType());
486   }
487   case ISD::FADD:
488     // FIXME: determine better conditions for this xform.
489     assert(DAG.getTarget().Options.UnsafeFPMath);
490
491     // fold (fneg (fadd A, B)) -> (fsub (fneg A), B)
492     if (isNegatibleForFree(Op.getOperand(0), LegalOperations,
493                            DAG.getTargetLoweringInfo(),
494                            &DAG.getTarget().Options, Depth+1))
495       return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
496                          GetNegatedExpression(Op.getOperand(0), DAG,
497                                               LegalOperations, Depth+1),
498                          Op.getOperand(1));
499     // fold (fneg (fadd A, B)) -> (fsub (fneg B), A)
500     return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
501                        GetNegatedExpression(Op.getOperand(1), DAG,
502                                             LegalOperations, Depth+1),
503                        Op.getOperand(0));
504   case ISD::FSUB:
505     // We can't turn -(A-B) into B-A when we honor signed zeros.
506     assert(DAG.getTarget().Options.UnsafeFPMath);
507
508     // fold (fneg (fsub 0, B)) -> B
509     if (ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(Op.getOperand(0)))
510       if (N0CFP->getValueAPF().isZero())
511         return Op.getOperand(1);
512
513     // fold (fneg (fsub A, B)) -> (fsub B, A)
514     return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
515                        Op.getOperand(1), Op.getOperand(0));
516
517   case ISD::FMUL:
518   case ISD::FDIV:
519     assert(!DAG.getTarget().Options.HonorSignDependentRoundingFPMath());
520
521     // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y)
522     if (isNegatibleForFree(Op.getOperand(0), LegalOperations,
523                            DAG.getTargetLoweringInfo(),
524                            &DAG.getTarget().Options, Depth+1))
525       return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
526                          GetNegatedExpression(Op.getOperand(0), DAG,
527                                               LegalOperations, Depth+1),
528                          Op.getOperand(1));
529
530     // fold (fneg (fmul X, Y)) -> (fmul X, (fneg Y))
531     return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
532                        Op.getOperand(0),
533                        GetNegatedExpression(Op.getOperand(1), DAG,
534                                             LegalOperations, Depth+1));
535
536   case ISD::FP_EXTEND:
537   case ISD::FSIN:
538     return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
539                        GetNegatedExpression(Op.getOperand(0), DAG,
540                                             LegalOperations, Depth+1));
541   case ISD::FP_ROUND:
542       return DAG.getNode(ISD::FP_ROUND, SDLoc(Op), Op.getValueType(),
543                          GetNegatedExpression(Op.getOperand(0), DAG,
544                                               LegalOperations, Depth+1),
545                          Op.getOperand(1));
546   }
547 }
548
549
550 // isSetCCEquivalent - Return true if this node is a setcc, or is a select_cc
551 // that selects between the values 1 and 0, making it equivalent to a setcc.
552 // Also, set the incoming LHS, RHS, and CC references to the appropriate
553 // nodes based on the type of node we are checking.  This simplifies life a
554 // bit for the callers.
555 static bool isSetCCEquivalent(SDValue N, SDValue &LHS, SDValue &RHS,
556                               SDValue &CC) {
557   if (N.getOpcode() == ISD::SETCC) {
558     LHS = N.getOperand(0);
559     RHS = N.getOperand(1);
560     CC  = N.getOperand(2);
561     return true;
562   }
563   if (N.getOpcode() == ISD::SELECT_CC &&
564       N.getOperand(2).getOpcode() == ISD::Constant &&
565       N.getOperand(3).getOpcode() == ISD::Constant &&
566       cast<ConstantSDNode>(N.getOperand(2))->getAPIntValue() == 1 &&
567       cast<ConstantSDNode>(N.getOperand(3))->isNullValue()) {
568     LHS = N.getOperand(0);
569     RHS = N.getOperand(1);
570     CC  = N.getOperand(4);
571     return true;
572   }
573   return false;
574 }
575
576 // isOneUseSetCC - Return true if this is a SetCC-equivalent operation with only
577 // one use.  If this is true, it allows the users to invert the operation for
578 // free when it is profitable to do so.
579 static bool isOneUseSetCC(SDValue N) {
580   SDValue N0, N1, N2;
581   if (isSetCCEquivalent(N, N0, N1, N2) && N.getNode()->hasOneUse())
582     return true;
583   return false;
584 }
585
586 SDValue DAGCombiner::ReassociateOps(unsigned Opc, SDLoc DL,
587                                     SDValue N0, SDValue N1) {
588   EVT VT = N0.getValueType();
589   if (N0.getOpcode() == Opc && isa<ConstantSDNode>(N0.getOperand(1))) {
590     if (isa<ConstantSDNode>(N1)) {
591       // reassoc. (op (op x, c1), c2) -> (op x, (op c1, c2))
592       SDValue OpNode =
593         DAG.FoldConstantArithmetic(Opc, VT,
594                                    cast<ConstantSDNode>(N0.getOperand(1)),
595                                    cast<ConstantSDNode>(N1));
596       return DAG.getNode(Opc, DL, VT, N0.getOperand(0), OpNode);
597     }
598     if (N0.hasOneUse()) {
599       // reassoc. (op (op x, c1), y) -> (op (op x, y), c1) iff x+c1 has one use
600       SDValue OpNode = DAG.getNode(Opc, SDLoc(N0), VT,
601                                    N0.getOperand(0), N1);
602       AddToWorkList(OpNode.getNode());
603       return DAG.getNode(Opc, DL, VT, OpNode, N0.getOperand(1));
604     }
605   }
606
607   if (N1.getOpcode() == Opc && isa<ConstantSDNode>(N1.getOperand(1))) {
608     if (isa<ConstantSDNode>(N0)) {
609       // reassoc. (op c2, (op x, c1)) -> (op x, (op c1, c2))
610       SDValue OpNode =
611         DAG.FoldConstantArithmetic(Opc, VT,
612                                    cast<ConstantSDNode>(N1.getOperand(1)),
613                                    cast<ConstantSDNode>(N0));
614       return DAG.getNode(Opc, DL, VT, N1.getOperand(0), OpNode);
615     }
616     if (N1.hasOneUse()) {
617       // reassoc. (op y, (op x, c1)) -> (op (op x, y), c1) iff x+c1 has one use
618       SDValue OpNode = DAG.getNode(Opc, SDLoc(N0), VT,
619                                    N1.getOperand(0), N0);
620       AddToWorkList(OpNode.getNode());
621       return DAG.getNode(Opc, DL, VT, OpNode, N1.getOperand(1));
622     }
623   }
624
625   return SDValue();
626 }
627
628 SDValue DAGCombiner::CombineTo(SDNode *N, const SDValue *To, unsigned NumTo,
629                                bool AddTo) {
630   assert(N->getNumValues() == NumTo && "Broken CombineTo call!");
631   ++NodesCombined;
632   DEBUG(dbgs() << "\nReplacing.1 ";
633         N->dump(&DAG);
634         dbgs() << "\nWith: ";
635         To[0].getNode()->dump(&DAG);
636         dbgs() << " and " << NumTo-1 << " other values\n";
637         for (unsigned i = 0, e = NumTo; i != e; ++i)
638           assert((!To[i].getNode() ||
639                   N->getValueType(i) == To[i].getValueType()) &&
640                  "Cannot combine value to value of different type!"));
641   WorkListRemover DeadNodes(*this);
642   DAG.ReplaceAllUsesWith(N, To);
643   if (AddTo) {
644     // Push the new nodes and any users onto the worklist
645     for (unsigned i = 0, e = NumTo; i != e; ++i) {
646       if (To[i].getNode()) {
647         AddToWorkList(To[i].getNode());
648         AddUsersToWorkList(To[i].getNode());
649       }
650     }
651   }
652
653   // Finally, if the node is now dead, remove it from the graph.  The node
654   // may not be dead if the replacement process recursively simplified to
655   // something else needing this node.
656   if (N->use_empty()) {
657     // Nodes can be reintroduced into the worklist.  Make sure we do not
658     // process a node that has been replaced.
659     removeFromWorkList(N);
660
661     // Finally, since the node is now dead, remove it from the graph.
662     DAG.DeleteNode(N);
663   }
664   return SDValue(N, 0);
665 }
666
667 void DAGCombiner::
668 CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) {
669   // Replace all uses.  If any nodes become isomorphic to other nodes and
670   // are deleted, make sure to remove them from our worklist.
671   WorkListRemover DeadNodes(*this);
672   DAG.ReplaceAllUsesOfValueWith(TLO.Old, TLO.New);
673
674   // Push the new node and any (possibly new) users onto the worklist.
675   AddToWorkList(TLO.New.getNode());
676   AddUsersToWorkList(TLO.New.getNode());
677
678   // Finally, if the node is now dead, remove it from the graph.  The node
679   // may not be dead if the replacement process recursively simplified to
680   // something else needing this node.
681   if (TLO.Old.getNode()->use_empty()) {
682     removeFromWorkList(TLO.Old.getNode());
683
684     // If the operands of this node are only used by the node, they will now
685     // be dead.  Make sure to visit them first to delete dead nodes early.
686     for (unsigned i = 0, e = TLO.Old.getNode()->getNumOperands(); i != e; ++i)
687       if (TLO.Old.getNode()->getOperand(i).getNode()->hasOneUse())
688         AddToWorkList(TLO.Old.getNode()->getOperand(i).getNode());
689
690     DAG.DeleteNode(TLO.Old.getNode());
691   }
692 }
693
694 /// SimplifyDemandedBits - Check the specified integer node value to see if
695 /// it can be simplified or if things it uses can be simplified by bit
696 /// propagation.  If so, return true.
697 bool DAGCombiner::SimplifyDemandedBits(SDValue Op, const APInt &Demanded) {
698   TargetLowering::TargetLoweringOpt TLO(DAG, LegalTypes, LegalOperations);
699   APInt KnownZero, KnownOne;
700   if (!TLI.SimplifyDemandedBits(Op, Demanded, KnownZero, KnownOne, TLO))
701     return false;
702
703   // Revisit the node.
704   AddToWorkList(Op.getNode());
705
706   // Replace the old value with the new one.
707   ++NodesCombined;
708   DEBUG(dbgs() << "\nReplacing.2 ";
709         TLO.Old.getNode()->dump(&DAG);
710         dbgs() << "\nWith: ";
711         TLO.New.getNode()->dump(&DAG);
712         dbgs() << '\n');
713
714   CommitTargetLoweringOpt(TLO);
715   return true;
716 }
717
718 void DAGCombiner::ReplaceLoadWithPromotedLoad(SDNode *Load, SDNode *ExtLoad) {
719   SDLoc dl(Load);
720   EVT VT = Load->getValueType(0);
721   SDValue Trunc = DAG.getNode(ISD::TRUNCATE, dl, VT, SDValue(ExtLoad, 0));
722
723   DEBUG(dbgs() << "\nReplacing.9 ";
724         Load->dump(&DAG);
725         dbgs() << "\nWith: ";
726         Trunc.getNode()->dump(&DAG);
727         dbgs() << '\n');
728   WorkListRemover DeadNodes(*this);
729   DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 0), Trunc);
730   DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 1), SDValue(ExtLoad, 1));
731   removeFromWorkList(Load);
732   DAG.DeleteNode(Load);
733   AddToWorkList(Trunc.getNode());
734 }
735
736 SDValue DAGCombiner::PromoteOperand(SDValue Op, EVT PVT, bool &Replace) {
737   Replace = false;
738   SDLoc dl(Op);
739   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Op)) {
740     EVT MemVT = LD->getMemoryVT();
741     ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD)
742       ? (TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT) ? ISD::ZEXTLOAD
743                                                   : ISD::EXTLOAD)
744       : LD->getExtensionType();
745     Replace = true;
746     return DAG.getExtLoad(ExtType, dl, PVT,
747                           LD->getChain(), LD->getBasePtr(),
748                           LD->getPointerInfo(),
749                           MemVT, LD->isVolatile(),
750                           LD->isNonTemporal(), LD->getAlignment());
751   }
752
753   unsigned Opc = Op.getOpcode();
754   switch (Opc) {
755   default: break;
756   case ISD::AssertSext:
757     return DAG.getNode(ISD::AssertSext, dl, PVT,
758                        SExtPromoteOperand(Op.getOperand(0), PVT),
759                        Op.getOperand(1));
760   case ISD::AssertZext:
761     return DAG.getNode(ISD::AssertZext, dl, PVT,
762                        ZExtPromoteOperand(Op.getOperand(0), PVT),
763                        Op.getOperand(1));
764   case ISD::Constant: {
765     unsigned ExtOpc =
766       Op.getValueType().isByteSized() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
767     return DAG.getNode(ExtOpc, dl, PVT, Op);
768   }
769   }
770
771   if (!TLI.isOperationLegal(ISD::ANY_EXTEND, PVT))
772     return SDValue();
773   return DAG.getNode(ISD::ANY_EXTEND, dl, PVT, Op);
774 }
775
776 SDValue DAGCombiner::SExtPromoteOperand(SDValue Op, EVT PVT) {
777   if (!TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, PVT))
778     return SDValue();
779   EVT OldVT = Op.getValueType();
780   SDLoc dl(Op);
781   bool Replace = false;
782   SDValue NewOp = PromoteOperand(Op, PVT, Replace);
783   if (NewOp.getNode() == 0)
784     return SDValue();
785   AddToWorkList(NewOp.getNode());
786
787   if (Replace)
788     ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode());
789   return DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, NewOp.getValueType(), NewOp,
790                      DAG.getValueType(OldVT));
791 }
792
793 SDValue DAGCombiner::ZExtPromoteOperand(SDValue Op, EVT PVT) {
794   EVT OldVT = Op.getValueType();
795   SDLoc dl(Op);
796   bool Replace = false;
797   SDValue NewOp = PromoteOperand(Op, PVT, Replace);
798   if (NewOp.getNode() == 0)
799     return SDValue();
800   AddToWorkList(NewOp.getNode());
801
802   if (Replace)
803     ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode());
804   return DAG.getZeroExtendInReg(NewOp, dl, OldVT);
805 }
806
807 /// PromoteIntBinOp - Promote the specified integer binary operation if the
808 /// target indicates it is beneficial. e.g. On x86, it's usually better to
809 /// promote i16 operations to i32 since i16 instructions are longer.
810 SDValue DAGCombiner::PromoteIntBinOp(SDValue Op) {
811   if (!LegalOperations)
812     return SDValue();
813
814   EVT VT = Op.getValueType();
815   if (VT.isVector() || !VT.isInteger())
816     return SDValue();
817
818   // If operation type is 'undesirable', e.g. i16 on x86, consider
819   // promoting it.
820   unsigned Opc = Op.getOpcode();
821   if (TLI.isTypeDesirableForOp(Opc, VT))
822     return SDValue();
823
824   EVT PVT = VT;
825   // Consult target whether it is a good idea to promote this operation and
826   // what's the right type to promote it to.
827   if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
828     assert(PVT != VT && "Don't know what type to promote to!");
829
830     bool Replace0 = false;
831     SDValue N0 = Op.getOperand(0);
832     SDValue NN0 = PromoteOperand(N0, PVT, Replace0);
833     if (NN0.getNode() == 0)
834       return SDValue();
835
836     bool Replace1 = false;
837     SDValue N1 = Op.getOperand(1);
838     SDValue NN1;
839     if (N0 == N1)
840       NN1 = NN0;
841     else {
842       NN1 = PromoteOperand(N1, PVT, Replace1);
843       if (NN1.getNode() == 0)
844         return SDValue();
845     }
846
847     AddToWorkList(NN0.getNode());
848     if (NN1.getNode())
849       AddToWorkList(NN1.getNode());
850
851     if (Replace0)
852       ReplaceLoadWithPromotedLoad(N0.getNode(), NN0.getNode());
853     if (Replace1)
854       ReplaceLoadWithPromotedLoad(N1.getNode(), NN1.getNode());
855
856     DEBUG(dbgs() << "\nPromoting ";
857           Op.getNode()->dump(&DAG));
858     SDLoc dl(Op);
859     return DAG.getNode(ISD::TRUNCATE, dl, VT,
860                        DAG.getNode(Opc, dl, PVT, NN0, NN1));
861   }
862   return SDValue();
863 }
864
865 /// PromoteIntShiftOp - Promote the specified integer shift operation if the
866 /// target indicates it is beneficial. e.g. On x86, it's usually better to
867 /// promote i16 operations to i32 since i16 instructions are longer.
868 SDValue DAGCombiner::PromoteIntShiftOp(SDValue Op) {
869   if (!LegalOperations)
870     return SDValue();
871
872   EVT VT = Op.getValueType();
873   if (VT.isVector() || !VT.isInteger())
874     return SDValue();
875
876   // If operation type is 'undesirable', e.g. i16 on x86, consider
877   // promoting it.
878   unsigned Opc = Op.getOpcode();
879   if (TLI.isTypeDesirableForOp(Opc, VT))
880     return SDValue();
881
882   EVT PVT = VT;
883   // Consult target whether it is a good idea to promote this operation and
884   // what's the right type to promote it to.
885   if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
886     assert(PVT != VT && "Don't know what type to promote to!");
887
888     bool Replace = false;
889     SDValue N0 = Op.getOperand(0);
890     if (Opc == ISD::SRA)
891       N0 = SExtPromoteOperand(Op.getOperand(0), PVT);
892     else if (Opc == ISD::SRL)
893       N0 = ZExtPromoteOperand(Op.getOperand(0), PVT);
894     else
895       N0 = PromoteOperand(N0, PVT, Replace);
896     if (N0.getNode() == 0)
897       return SDValue();
898
899     AddToWorkList(N0.getNode());
900     if (Replace)
901       ReplaceLoadWithPromotedLoad(Op.getOperand(0).getNode(), N0.getNode());
902
903     DEBUG(dbgs() << "\nPromoting ";
904           Op.getNode()->dump(&DAG));
905     SDLoc dl(Op);
906     return DAG.getNode(ISD::TRUNCATE, dl, VT,
907                        DAG.getNode(Opc, dl, PVT, N0, Op.getOperand(1)));
908   }
909   return SDValue();
910 }
911
912 SDValue DAGCombiner::PromoteExtend(SDValue Op) {
913   if (!LegalOperations)
914     return SDValue();
915
916   EVT VT = Op.getValueType();
917   if (VT.isVector() || !VT.isInteger())
918     return SDValue();
919
920   // If operation type is 'undesirable', e.g. i16 on x86, consider
921   // promoting it.
922   unsigned Opc = Op.getOpcode();
923   if (TLI.isTypeDesirableForOp(Opc, VT))
924     return SDValue();
925
926   EVT PVT = VT;
927   // Consult target whether it is a good idea to promote this operation and
928   // what's the right type to promote it to.
929   if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
930     assert(PVT != VT && "Don't know what type to promote to!");
931     // fold (aext (aext x)) -> (aext x)
932     // fold (aext (zext x)) -> (zext x)
933     // fold (aext (sext x)) -> (sext x)
934     DEBUG(dbgs() << "\nPromoting ";
935           Op.getNode()->dump(&DAG));
936     return DAG.getNode(Op.getOpcode(), SDLoc(Op), VT, Op.getOperand(0));
937   }
938   return SDValue();
939 }
940
941 bool DAGCombiner::PromoteLoad(SDValue Op) {
942   if (!LegalOperations)
943     return false;
944
945   EVT VT = Op.getValueType();
946   if (VT.isVector() || !VT.isInteger())
947     return false;
948
949   // If operation type is 'undesirable', e.g. i16 on x86, consider
950   // promoting it.
951   unsigned Opc = Op.getOpcode();
952   if (TLI.isTypeDesirableForOp(Opc, VT))
953     return false;
954
955   EVT PVT = VT;
956   // Consult target whether it is a good idea to promote this operation and
957   // what's the right type to promote it to.
958   if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
959     assert(PVT != VT && "Don't know what type to promote to!");
960
961     SDLoc dl(Op);
962     SDNode *N = Op.getNode();
963     LoadSDNode *LD = cast<LoadSDNode>(N);
964     EVT MemVT = LD->getMemoryVT();
965     ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD)
966       ? (TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT) ? ISD::ZEXTLOAD
967                                                   : ISD::EXTLOAD)
968       : LD->getExtensionType();
969     SDValue NewLD = DAG.getExtLoad(ExtType, dl, PVT,
970                                    LD->getChain(), LD->getBasePtr(),
971                                    LD->getPointerInfo(),
972                                    MemVT, LD->isVolatile(),
973                                    LD->isNonTemporal(), LD->getAlignment());
974     SDValue Result = DAG.getNode(ISD::TRUNCATE, dl, VT, NewLD);
975
976     DEBUG(dbgs() << "\nPromoting ";
977           N->dump(&DAG);
978           dbgs() << "\nTo: ";
979           Result.getNode()->dump(&DAG);
980           dbgs() << '\n');
981     WorkListRemover DeadNodes(*this);
982     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result);
983     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), NewLD.getValue(1));
984     removeFromWorkList(N);
985     DAG.DeleteNode(N);
986     AddToWorkList(Result.getNode());
987     return true;
988   }
989   return false;
990 }
991
992
993 //===----------------------------------------------------------------------===//
994 //  Main DAG Combiner implementation
995 //===----------------------------------------------------------------------===//
996
997 void DAGCombiner::Run(CombineLevel AtLevel) {
998   // set the instance variables, so that the various visit routines may use it.
999   Level = AtLevel;
1000   LegalOperations = Level >= AfterLegalizeVectorOps;
1001   LegalTypes = Level >= AfterLegalizeTypes;
1002
1003   // Add all the dag nodes to the worklist.
1004   for (SelectionDAG::allnodes_iterator I = DAG.allnodes_begin(),
1005        E = DAG.allnodes_end(); I != E; ++I)
1006     AddToWorkList(I);
1007
1008   // Create a dummy node (which is not added to allnodes), that adds a reference
1009   // to the root node, preventing it from being deleted, and tracking any
1010   // changes of the root.
1011   HandleSDNode Dummy(DAG.getRoot());
1012
1013   // The root of the dag may dangle to deleted nodes until the dag combiner is
1014   // done.  Set it to null to avoid confusion.
1015   DAG.setRoot(SDValue());
1016
1017   // while the worklist isn't empty, find a node and
1018   // try and combine it.
1019   while (!WorkListContents.empty()) {
1020     SDNode *N;
1021     // The WorkListOrder holds the SDNodes in order, but it may contain duplicates.
1022     // In order to avoid a linear scan, we use a set (O(log N)) to hold what the
1023     // worklist *should* contain, and check the node we want to visit is should
1024     // actually be visited.
1025     do {
1026       N = WorkListOrder.pop_back_val();
1027     } while (!WorkListContents.erase(N));
1028
1029     // If N has no uses, it is dead.  Make sure to revisit all N's operands once
1030     // N is deleted from the DAG, since they too may now be dead or may have a
1031     // reduced number of uses, allowing other xforms.
1032     if (N->use_empty() && N != &Dummy) {
1033       for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1034         AddToWorkList(N->getOperand(i).getNode());
1035
1036       DAG.DeleteNode(N);
1037       continue;
1038     }
1039
1040     SDValue RV = combine(N);
1041
1042     if (RV.getNode() == 0)
1043       continue;
1044
1045     ++NodesCombined;
1046
1047     // If we get back the same node we passed in, rather than a new node or
1048     // zero, we know that the node must have defined multiple values and
1049     // CombineTo was used.  Since CombineTo takes care of the worklist
1050     // mechanics for us, we have no work to do in this case.
1051     if (RV.getNode() == N)
1052       continue;
1053
1054     assert(N->getOpcode() != ISD::DELETED_NODE &&
1055            RV.getNode()->getOpcode() != ISD::DELETED_NODE &&
1056            "Node was deleted but visit returned new node!");
1057
1058     DEBUG(dbgs() << "\nReplacing.3 ";
1059           N->dump(&DAG);
1060           dbgs() << "\nWith: ";
1061           RV.getNode()->dump(&DAG);
1062           dbgs() << '\n');
1063
1064     // Transfer debug value.
1065     DAG.TransferDbgValues(SDValue(N, 0), RV);
1066     WorkListRemover DeadNodes(*this);
1067     if (N->getNumValues() == RV.getNode()->getNumValues())
1068       DAG.ReplaceAllUsesWith(N, RV.getNode());
1069     else {
1070       assert(N->getValueType(0) == RV.getValueType() &&
1071              N->getNumValues() == 1 && "Type mismatch");
1072       SDValue OpV = RV;
1073       DAG.ReplaceAllUsesWith(N, &OpV);
1074     }
1075
1076     // Push the new node and any users onto the worklist
1077     AddToWorkList(RV.getNode());
1078     AddUsersToWorkList(RV.getNode());
1079
1080     // Add any uses of the old node to the worklist in case this node is the
1081     // last one that uses them.  They may become dead after this node is
1082     // deleted.
1083     for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1084       AddToWorkList(N->getOperand(i).getNode());
1085
1086     // Finally, if the node is now dead, remove it from the graph.  The node
1087     // may not be dead if the replacement process recursively simplified to
1088     // something else needing this node.
1089     if (N->use_empty()) {
1090       // Nodes can be reintroduced into the worklist.  Make sure we do not
1091       // process a node that has been replaced.
1092       removeFromWorkList(N);
1093
1094       // Finally, since the node is now dead, remove it from the graph.
1095       DAG.DeleteNode(N);
1096     }
1097   }
1098
1099   // If the root changed (e.g. it was a dead load, update the root).
1100   DAG.setRoot(Dummy.getValue());
1101   DAG.RemoveDeadNodes();
1102 }
1103
1104 SDValue DAGCombiner::visit(SDNode *N) {
1105   switch (N->getOpcode()) {
1106   default: break;
1107   case ISD::TokenFactor:        return visitTokenFactor(N);
1108   case ISD::MERGE_VALUES:       return visitMERGE_VALUES(N);
1109   case ISD::ADD:                return visitADD(N);
1110   case ISD::SUB:                return visitSUB(N);
1111   case ISD::ADDC:               return visitADDC(N);
1112   case ISD::SUBC:               return visitSUBC(N);
1113   case ISD::ADDE:               return visitADDE(N);
1114   case ISD::SUBE:               return visitSUBE(N);
1115   case ISD::MUL:                return visitMUL(N);
1116   case ISD::SDIV:               return visitSDIV(N);
1117   case ISD::UDIV:               return visitUDIV(N);
1118   case ISD::SREM:               return visitSREM(N);
1119   case ISD::UREM:               return visitUREM(N);
1120   case ISD::MULHU:              return visitMULHU(N);
1121   case ISD::MULHS:              return visitMULHS(N);
1122   case ISD::SMUL_LOHI:          return visitSMUL_LOHI(N);
1123   case ISD::UMUL_LOHI:          return visitUMUL_LOHI(N);
1124   case ISD::SMULO:              return visitSMULO(N);
1125   case ISD::UMULO:              return visitUMULO(N);
1126   case ISD::SDIVREM:            return visitSDIVREM(N);
1127   case ISD::UDIVREM:            return visitUDIVREM(N);
1128   case ISD::AND:                return visitAND(N);
1129   case ISD::OR:                 return visitOR(N);
1130   case ISD::XOR:                return visitXOR(N);
1131   case ISD::SHL:                return visitSHL(N);
1132   case ISD::SRA:                return visitSRA(N);
1133   case ISD::SRL:                return visitSRL(N);
1134   case ISD::CTLZ:               return visitCTLZ(N);
1135   case ISD::CTLZ_ZERO_UNDEF:    return visitCTLZ_ZERO_UNDEF(N);
1136   case ISD::CTTZ:               return visitCTTZ(N);
1137   case ISD::CTTZ_ZERO_UNDEF:    return visitCTTZ_ZERO_UNDEF(N);
1138   case ISD::CTPOP:              return visitCTPOP(N);
1139   case ISD::SELECT:             return visitSELECT(N);
1140   case ISD::VSELECT:            return visitVSELECT(N);
1141   case ISD::SELECT_CC:          return visitSELECT_CC(N);
1142   case ISD::SETCC:              return visitSETCC(N);
1143   case ISD::SIGN_EXTEND:        return visitSIGN_EXTEND(N);
1144   case ISD::ZERO_EXTEND:        return visitZERO_EXTEND(N);
1145   case ISD::ANY_EXTEND:         return visitANY_EXTEND(N);
1146   case ISD::SIGN_EXTEND_INREG:  return visitSIGN_EXTEND_INREG(N);
1147   case ISD::TRUNCATE:           return visitTRUNCATE(N);
1148   case ISD::BITCAST:            return visitBITCAST(N);
1149   case ISD::BUILD_PAIR:         return visitBUILD_PAIR(N);
1150   case ISD::FADD:               return visitFADD(N);
1151   case ISD::FSUB:               return visitFSUB(N);
1152   case ISD::FMUL:               return visitFMUL(N);
1153   case ISD::FMA:                return visitFMA(N);
1154   case ISD::FDIV:               return visitFDIV(N);
1155   case ISD::FREM:               return visitFREM(N);
1156   case ISD::FCOPYSIGN:          return visitFCOPYSIGN(N);
1157   case ISD::SINT_TO_FP:         return visitSINT_TO_FP(N);
1158   case ISD::UINT_TO_FP:         return visitUINT_TO_FP(N);
1159   case ISD::FP_TO_SINT:         return visitFP_TO_SINT(N);
1160   case ISD::FP_TO_UINT:         return visitFP_TO_UINT(N);
1161   case ISD::FP_ROUND:           return visitFP_ROUND(N);
1162   case ISD::FP_ROUND_INREG:     return visitFP_ROUND_INREG(N);
1163   case ISD::FP_EXTEND:          return visitFP_EXTEND(N);
1164   case ISD::FNEG:               return visitFNEG(N);
1165   case ISD::FABS:               return visitFABS(N);
1166   case ISD::FFLOOR:             return visitFFLOOR(N);
1167   case ISD::FCEIL:              return visitFCEIL(N);
1168   case ISD::FTRUNC:             return visitFTRUNC(N);
1169   case ISD::BRCOND:             return visitBRCOND(N);
1170   case ISD::BR_CC:              return visitBR_CC(N);
1171   case ISD::LOAD:               return visitLOAD(N);
1172   case ISD::STORE:              return visitSTORE(N);
1173   case ISD::INSERT_VECTOR_ELT:  return visitINSERT_VECTOR_ELT(N);
1174   case ISD::EXTRACT_VECTOR_ELT: return visitEXTRACT_VECTOR_ELT(N);
1175   case ISD::BUILD_VECTOR:       return visitBUILD_VECTOR(N);
1176   case ISD::CONCAT_VECTORS:     return visitCONCAT_VECTORS(N);
1177   case ISD::EXTRACT_SUBVECTOR:  return visitEXTRACT_SUBVECTOR(N);
1178   case ISD::VECTOR_SHUFFLE:     return visitVECTOR_SHUFFLE(N);
1179   }
1180   return SDValue();
1181 }
1182
1183 SDValue DAGCombiner::combine(SDNode *N) {
1184   SDValue RV = visit(N);
1185
1186   // If nothing happened, try a target-specific DAG combine.
1187   if (RV.getNode() == 0) {
1188     assert(N->getOpcode() != ISD::DELETED_NODE &&
1189            "Node was deleted but visit returned NULL!");
1190
1191     if (N->getOpcode() >= ISD::BUILTIN_OP_END ||
1192         TLI.hasTargetDAGCombine((ISD::NodeType)N->getOpcode())) {
1193
1194       // Expose the DAG combiner to the target combiner impls.
1195       TargetLowering::DAGCombinerInfo
1196         DagCombineInfo(DAG, Level, false, this);
1197
1198       RV = TLI.PerformDAGCombine(N, DagCombineInfo);
1199     }
1200   }
1201
1202   // If nothing happened still, try promoting the operation.
1203   if (RV.getNode() == 0) {
1204     switch (N->getOpcode()) {
1205     default: break;
1206     case ISD::ADD:
1207     case ISD::SUB:
1208     case ISD::MUL:
1209     case ISD::AND:
1210     case ISD::OR:
1211     case ISD::XOR:
1212       RV = PromoteIntBinOp(SDValue(N, 0));
1213       break;
1214     case ISD::SHL:
1215     case ISD::SRA:
1216     case ISD::SRL:
1217       RV = PromoteIntShiftOp(SDValue(N, 0));
1218       break;
1219     case ISD::SIGN_EXTEND:
1220     case ISD::ZERO_EXTEND:
1221     case ISD::ANY_EXTEND:
1222       RV = PromoteExtend(SDValue(N, 0));
1223       break;
1224     case ISD::LOAD:
1225       if (PromoteLoad(SDValue(N, 0)))
1226         RV = SDValue(N, 0);
1227       break;
1228     }
1229   }
1230
1231   // If N is a commutative binary node, try commuting it to enable more
1232   // sdisel CSE.
1233   if (RV.getNode() == 0 &&
1234       SelectionDAG::isCommutativeBinOp(N->getOpcode()) &&
1235       N->getNumValues() == 1) {
1236     SDValue N0 = N->getOperand(0);
1237     SDValue N1 = N->getOperand(1);
1238
1239     // Constant operands are canonicalized to RHS.
1240     if (isa<ConstantSDNode>(N0) || !isa<ConstantSDNode>(N1)) {
1241       SDValue Ops[] = { N1, N0 };
1242       SDNode *CSENode = DAG.getNodeIfExists(N->getOpcode(), N->getVTList(),
1243                                             Ops, 2);
1244       if (CSENode)
1245         return SDValue(CSENode, 0);
1246     }
1247   }
1248
1249   return RV;
1250 }
1251
1252 /// getInputChainForNode - Given a node, return its input chain if it has one,
1253 /// otherwise return a null sd operand.
1254 static SDValue getInputChainForNode(SDNode *N) {
1255   if (unsigned NumOps = N->getNumOperands()) {
1256     if (N->getOperand(0).getValueType() == MVT::Other)
1257       return N->getOperand(0);
1258     if (N->getOperand(NumOps-1).getValueType() == MVT::Other)
1259       return N->getOperand(NumOps-1);
1260     for (unsigned i = 1; i < NumOps-1; ++i)
1261       if (N->getOperand(i).getValueType() == MVT::Other)
1262         return N->getOperand(i);
1263   }
1264   return SDValue();
1265 }
1266
1267 SDValue DAGCombiner::visitTokenFactor(SDNode *N) {
1268   // If N has two operands, where one has an input chain equal to the other,
1269   // the 'other' chain is redundant.
1270   if (N->getNumOperands() == 2) {
1271     if (getInputChainForNode(N->getOperand(0).getNode()) == N->getOperand(1))
1272       return N->getOperand(0);
1273     if (getInputChainForNode(N->getOperand(1).getNode()) == N->getOperand(0))
1274       return N->getOperand(1);
1275   }
1276
1277   SmallVector<SDNode *, 8> TFs;     // List of token factors to visit.
1278   SmallVector<SDValue, 8> Ops;    // Ops for replacing token factor.
1279   SmallPtrSet<SDNode*, 16> SeenOps;
1280   bool Changed = false;             // If we should replace this token factor.
1281
1282   // Start out with this token factor.
1283   TFs.push_back(N);
1284
1285   // Iterate through token factors.  The TFs grows when new token factors are
1286   // encountered.
1287   for (unsigned i = 0; i < TFs.size(); ++i) {
1288     SDNode *TF = TFs[i];
1289
1290     // Check each of the operands.
1291     for (unsigned i = 0, ie = TF->getNumOperands(); i != ie; ++i) {
1292       SDValue Op = TF->getOperand(i);
1293
1294       switch (Op.getOpcode()) {
1295       case ISD::EntryToken:
1296         // Entry tokens don't need to be added to the list. They are
1297         // rededundant.
1298         Changed = true;
1299         break;
1300
1301       case ISD::TokenFactor:
1302         if (Op.hasOneUse() &&
1303             std::find(TFs.begin(), TFs.end(), Op.getNode()) == TFs.end()) {
1304           // Queue up for processing.
1305           TFs.push_back(Op.getNode());
1306           // Clean up in case the token factor is removed.
1307           AddToWorkList(Op.getNode());
1308           Changed = true;
1309           break;
1310         }
1311         // Fall thru
1312
1313       default:
1314         // Only add if it isn't already in the list.
1315         if (SeenOps.insert(Op.getNode()))
1316           Ops.push_back(Op);
1317         else
1318           Changed = true;
1319         break;
1320       }
1321     }
1322   }
1323
1324   SDValue Result;
1325
1326   // If we've change things around then replace token factor.
1327   if (Changed) {
1328     if (Ops.empty()) {
1329       // The entry token is the only possible outcome.
1330       Result = DAG.getEntryNode();
1331     } else {
1332       // New and improved token factor.
1333       Result = DAG.getNode(ISD::TokenFactor, SDLoc(N),
1334                            MVT::Other, &Ops[0], Ops.size());
1335     }
1336
1337     // Don't add users to work list.
1338     return CombineTo(N, Result, false);
1339   }
1340
1341   return Result;
1342 }
1343
1344 /// MERGE_VALUES can always be eliminated.
1345 SDValue DAGCombiner::visitMERGE_VALUES(SDNode *N) {
1346   WorkListRemover DeadNodes(*this);
1347   // Replacing results may cause a different MERGE_VALUES to suddenly
1348   // be CSE'd with N, and carry its uses with it. Iterate until no
1349   // uses remain, to ensure that the node can be safely deleted.
1350   // First add the users of this node to the work list so that they
1351   // can be tried again once they have new operands.
1352   AddUsersToWorkList(N);
1353   do {
1354     for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1355       DAG.ReplaceAllUsesOfValueWith(SDValue(N, i), N->getOperand(i));
1356   } while (!N->use_empty());
1357   removeFromWorkList(N);
1358   DAG.DeleteNode(N);
1359   return SDValue(N, 0);   // Return N so it doesn't get rechecked!
1360 }
1361
1362 static
1363 SDValue combineShlAddConstant(SDLoc DL, SDValue N0, SDValue N1,
1364                               SelectionDAG &DAG) {
1365   EVT VT = N0.getValueType();
1366   SDValue N00 = N0.getOperand(0);
1367   SDValue N01 = N0.getOperand(1);
1368   ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N01);
1369
1370   if (N01C && N00.getOpcode() == ISD::ADD && N00.getNode()->hasOneUse() &&
1371       isa<ConstantSDNode>(N00.getOperand(1))) {
1372     // fold (add (shl (add x, c1), c2), ) -> (add (add (shl x, c2), c1<<c2), )
1373     N0 = DAG.getNode(ISD::ADD, SDLoc(N0), VT,
1374                      DAG.getNode(ISD::SHL, SDLoc(N00), VT,
1375                                  N00.getOperand(0), N01),
1376                      DAG.getNode(ISD::SHL, SDLoc(N01), VT,
1377                                  N00.getOperand(1), N01));
1378     return DAG.getNode(ISD::ADD, DL, VT, N0, N1);
1379   }
1380
1381   return SDValue();
1382 }
1383
1384 SDValue DAGCombiner::visitADD(SDNode *N) {
1385   SDValue N0 = N->getOperand(0);
1386   SDValue N1 = N->getOperand(1);
1387   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1388   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1389   EVT VT = N0.getValueType();
1390
1391   // fold vector ops
1392   if (VT.isVector()) {
1393     SDValue FoldedVOp = SimplifyVBinOp(N);
1394     if (FoldedVOp.getNode()) return FoldedVOp;
1395
1396     // fold (add x, 0) -> x, vector edition
1397     if (ISD::isBuildVectorAllZeros(N1.getNode()))
1398       return N0;
1399     if (ISD::isBuildVectorAllZeros(N0.getNode()))
1400       return N1;
1401   }
1402
1403   // fold (add x, undef) -> undef
1404   if (N0.getOpcode() == ISD::UNDEF)
1405     return N0;
1406   if (N1.getOpcode() == ISD::UNDEF)
1407     return N1;
1408   // fold (add c1, c2) -> c1+c2
1409   if (N0C && N1C)
1410     return DAG.FoldConstantArithmetic(ISD::ADD, VT, N0C, N1C);
1411   // canonicalize constant to RHS
1412   if (N0C && !N1C)
1413     return DAG.getNode(ISD::ADD, SDLoc(N), VT, N1, N0);
1414   // fold (add x, 0) -> x
1415   if (N1C && N1C->isNullValue())
1416     return N0;
1417   // fold (add Sym, c) -> Sym+c
1418   if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N0))
1419     if (!LegalOperations && TLI.isOffsetFoldingLegal(GA) && N1C &&
1420         GA->getOpcode() == ISD::GlobalAddress)
1421       return DAG.getGlobalAddress(GA->getGlobal(), SDLoc(N1C), VT,
1422                                   GA->getOffset() +
1423                                     (uint64_t)N1C->getSExtValue());
1424   // fold ((c1-A)+c2) -> (c1+c2)-A
1425   if (N1C && N0.getOpcode() == ISD::SUB)
1426     if (ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getOperand(0)))
1427       return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1428                          DAG.getConstant(N1C->getAPIntValue()+
1429                                          N0C->getAPIntValue(), VT),
1430                          N0.getOperand(1));
1431   // reassociate add
1432   SDValue RADD = ReassociateOps(ISD::ADD, SDLoc(N), N0, N1);
1433   if (RADD.getNode() != 0)
1434     return RADD;
1435   // fold ((0-A) + B) -> B-A
1436   if (N0.getOpcode() == ISD::SUB && isa<ConstantSDNode>(N0.getOperand(0)) &&
1437       cast<ConstantSDNode>(N0.getOperand(0))->isNullValue())
1438     return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1, N0.getOperand(1));
1439   // fold (A + (0-B)) -> A-B
1440   if (N1.getOpcode() == ISD::SUB && isa<ConstantSDNode>(N1.getOperand(0)) &&
1441       cast<ConstantSDNode>(N1.getOperand(0))->isNullValue())
1442     return DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, N1.getOperand(1));
1443   // fold (A+(B-A)) -> B
1444   if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(1))
1445     return N1.getOperand(0);
1446   // fold ((B-A)+A) -> B
1447   if (N0.getOpcode() == ISD::SUB && N1 == N0.getOperand(1))
1448     return N0.getOperand(0);
1449   // fold (A+(B-(A+C))) to (B-C)
1450   if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD &&
1451       N0 == N1.getOperand(1).getOperand(0))
1452     return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1.getOperand(0),
1453                        N1.getOperand(1).getOperand(1));
1454   // fold (A+(B-(C+A))) to (B-C)
1455   if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD &&
1456       N0 == N1.getOperand(1).getOperand(1))
1457     return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1.getOperand(0),
1458                        N1.getOperand(1).getOperand(0));
1459   // fold (A+((B-A)+or-C)) to (B+or-C)
1460   if ((N1.getOpcode() == ISD::SUB || N1.getOpcode() == ISD::ADD) &&
1461       N1.getOperand(0).getOpcode() == ISD::SUB &&
1462       N0 == N1.getOperand(0).getOperand(1))
1463     return DAG.getNode(N1.getOpcode(), SDLoc(N), VT,
1464                        N1.getOperand(0).getOperand(0), N1.getOperand(1));
1465
1466   // fold (A-B)+(C-D) to (A+C)-(B+D) when A or C is constant
1467   if (N0.getOpcode() == ISD::SUB && N1.getOpcode() == ISD::SUB) {
1468     SDValue N00 = N0.getOperand(0);
1469     SDValue N01 = N0.getOperand(1);
1470     SDValue N10 = N1.getOperand(0);
1471     SDValue N11 = N1.getOperand(1);
1472
1473     if (isa<ConstantSDNode>(N00) || isa<ConstantSDNode>(N10))
1474       return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1475                          DAG.getNode(ISD::ADD, SDLoc(N0), VT, N00, N10),
1476                          DAG.getNode(ISD::ADD, SDLoc(N1), VT, N01, N11));
1477   }
1478
1479   if (!VT.isVector() && SimplifyDemandedBits(SDValue(N, 0)))
1480     return SDValue(N, 0);
1481
1482   // fold (a+b) -> (a|b) iff a and b share no bits.
1483   if (VT.isInteger() && !VT.isVector()) {
1484     APInt LHSZero, LHSOne;
1485     APInt RHSZero, RHSOne;
1486     DAG.ComputeMaskedBits(N0, LHSZero, LHSOne);
1487
1488     if (LHSZero.getBoolValue()) {
1489       DAG.ComputeMaskedBits(N1, RHSZero, RHSOne);
1490
1491       // If all possibly-set bits on the LHS are clear on the RHS, return an OR.
1492       // If all possibly-set bits on the RHS are clear on the LHS, return an OR.
1493       if ((RHSZero & ~LHSZero) == ~LHSZero || (LHSZero & ~RHSZero) == ~RHSZero)
1494         return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N1);
1495     }
1496   }
1497
1498   // fold (add (shl (add x, c1), c2), ) -> (add (add (shl x, c2), c1<<c2), )
1499   if (N0.getOpcode() == ISD::SHL && N0.getNode()->hasOneUse()) {
1500     SDValue Result = combineShlAddConstant(SDLoc(N), N0, N1, DAG);
1501     if (Result.getNode()) return Result;
1502   }
1503   if (N1.getOpcode() == ISD::SHL && N1.getNode()->hasOneUse()) {
1504     SDValue Result = combineShlAddConstant(SDLoc(N), N1, N0, DAG);
1505     if (Result.getNode()) return Result;
1506   }
1507
1508   // fold (add x, shl(0 - y, n)) -> sub(x, shl(y, n))
1509   if (N1.getOpcode() == ISD::SHL &&
1510       N1.getOperand(0).getOpcode() == ISD::SUB)
1511     if (ConstantSDNode *C =
1512           dyn_cast<ConstantSDNode>(N1.getOperand(0).getOperand(0)))
1513       if (C->getAPIntValue() == 0)
1514         return DAG.getNode(ISD::SUB, SDLoc(N), VT, N0,
1515                            DAG.getNode(ISD::SHL, SDLoc(N), VT,
1516                                        N1.getOperand(0).getOperand(1),
1517                                        N1.getOperand(1)));
1518   if (N0.getOpcode() == ISD::SHL &&
1519       N0.getOperand(0).getOpcode() == ISD::SUB)
1520     if (ConstantSDNode *C =
1521           dyn_cast<ConstantSDNode>(N0.getOperand(0).getOperand(0)))
1522       if (C->getAPIntValue() == 0)
1523         return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1,
1524                            DAG.getNode(ISD::SHL, SDLoc(N), VT,
1525                                        N0.getOperand(0).getOperand(1),
1526                                        N0.getOperand(1)));
1527
1528   if (N1.getOpcode() == ISD::AND) {
1529     SDValue AndOp0 = N1.getOperand(0);
1530     ConstantSDNode *AndOp1 = dyn_cast<ConstantSDNode>(N1->getOperand(1));
1531     unsigned NumSignBits = DAG.ComputeNumSignBits(AndOp0);
1532     unsigned DestBits = VT.getScalarType().getSizeInBits();
1533
1534     // (add z, (and (sbbl x, x), 1)) -> (sub z, (sbbl x, x))
1535     // and similar xforms where the inner op is either ~0 or 0.
1536     if (NumSignBits == DestBits && AndOp1 && AndOp1->isOne()) {
1537       SDLoc DL(N);
1538       return DAG.getNode(ISD::SUB, DL, VT, N->getOperand(0), AndOp0);
1539     }
1540   }
1541
1542   // add (sext i1), X -> sub X, (zext i1)
1543   if (N0.getOpcode() == ISD::SIGN_EXTEND &&
1544       N0.getOperand(0).getValueType() == MVT::i1 &&
1545       !TLI.isOperationLegal(ISD::SIGN_EXTEND, MVT::i1)) {
1546     SDLoc DL(N);
1547     SDValue ZExt = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0));
1548     return DAG.getNode(ISD::SUB, DL, VT, N1, ZExt);
1549   }
1550
1551   return SDValue();
1552 }
1553
1554 SDValue DAGCombiner::visitADDC(SDNode *N) {
1555   SDValue N0 = N->getOperand(0);
1556   SDValue N1 = N->getOperand(1);
1557   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1558   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1559   EVT VT = N0.getValueType();
1560
1561   // If the flag result is dead, turn this into an ADD.
1562   if (!N->hasAnyUseOfValue(1))
1563     return CombineTo(N, DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, N1),
1564                      DAG.getNode(ISD::CARRY_FALSE,
1565                                  SDLoc(N), MVT::Glue));
1566
1567   // canonicalize constant to RHS.
1568   if (N0C && !N1C)
1569     return DAG.getNode(ISD::ADDC, SDLoc(N), N->getVTList(), N1, N0);
1570
1571   // fold (addc x, 0) -> x + no carry out
1572   if (N1C && N1C->isNullValue())
1573     return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE,
1574                                         SDLoc(N), MVT::Glue));
1575
1576   // fold (addc a, b) -> (or a, b), CARRY_FALSE iff a and b share no bits.
1577   APInt LHSZero, LHSOne;
1578   APInt RHSZero, RHSOne;
1579   DAG.ComputeMaskedBits(N0, LHSZero, LHSOne);
1580
1581   if (LHSZero.getBoolValue()) {
1582     DAG.ComputeMaskedBits(N1, RHSZero, RHSOne);
1583
1584     // If all possibly-set bits on the LHS are clear on the RHS, return an OR.
1585     // If all possibly-set bits on the RHS are clear on the LHS, return an OR.
1586     if ((RHSZero & ~LHSZero) == ~LHSZero || (LHSZero & ~RHSZero) == ~RHSZero)
1587       return CombineTo(N, DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N1),
1588                        DAG.getNode(ISD::CARRY_FALSE,
1589                                    SDLoc(N), MVT::Glue));
1590   }
1591
1592   return SDValue();
1593 }
1594
1595 SDValue DAGCombiner::visitADDE(SDNode *N) {
1596   SDValue N0 = N->getOperand(0);
1597   SDValue N1 = N->getOperand(1);
1598   SDValue CarryIn = N->getOperand(2);
1599   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1600   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1601
1602   // canonicalize constant to RHS
1603   if (N0C && !N1C)
1604     return DAG.getNode(ISD::ADDE, SDLoc(N), N->getVTList(),
1605                        N1, N0, CarryIn);
1606
1607   // fold (adde x, y, false) -> (addc x, y)
1608   if (CarryIn.getOpcode() == ISD::CARRY_FALSE)
1609     return DAG.getNode(ISD::ADDC, SDLoc(N), N->getVTList(), N0, N1);
1610
1611   return SDValue();
1612 }
1613
1614 // Since it may not be valid to emit a fold to zero for vector initializers
1615 // check if we can before folding.
1616 static SDValue tryFoldToZero(SDLoc DL, const TargetLowering &TLI, EVT VT,
1617                              SelectionDAG &DAG,
1618                              bool LegalOperations, bool LegalTypes) {
1619   if (!VT.isVector())
1620     return DAG.getConstant(0, VT);
1621   if (!LegalOperations || TLI.isOperationLegal(ISD::BUILD_VECTOR, VT)) {
1622     // Produce a vector of zeros.
1623     EVT ElemTy = VT.getVectorElementType();
1624     if (LegalTypes && TLI.getTypeAction(*DAG.getContext(), ElemTy) ==
1625                       TargetLowering::TypePromoteInteger)
1626       ElemTy = TLI.getTypeToTransformTo(*DAG.getContext(), ElemTy);
1627     assert((!LegalTypes || TLI.isTypeLegal(ElemTy)) &&
1628            "Type for zero vector elements is not legal");
1629     SDValue El = DAG.getConstant(0, ElemTy);
1630     std::vector<SDValue> Ops(VT.getVectorNumElements(), El);
1631     return DAG.getNode(ISD::BUILD_VECTOR, DL, VT,
1632       &Ops[0], Ops.size());
1633   }
1634   return SDValue();
1635 }
1636
1637 SDValue DAGCombiner::visitSUB(SDNode *N) {
1638   SDValue N0 = N->getOperand(0);
1639   SDValue N1 = N->getOperand(1);
1640   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getNode());
1641   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
1642   ConstantSDNode *N1C1 = N1.getOpcode() != ISD::ADD ? 0 :
1643     dyn_cast<ConstantSDNode>(N1.getOperand(1).getNode());
1644   EVT VT = N0.getValueType();
1645
1646   // fold vector ops
1647   if (VT.isVector()) {
1648     SDValue FoldedVOp = SimplifyVBinOp(N);
1649     if (FoldedVOp.getNode()) return FoldedVOp;
1650
1651     // fold (sub x, 0) -> x, vector edition
1652     if (ISD::isBuildVectorAllZeros(N1.getNode()))
1653       return N0;
1654   }
1655
1656   // fold (sub x, x) -> 0
1657   // FIXME: Refactor this and xor and other similar operations together.
1658   if (N0 == N1)
1659     return tryFoldToZero(SDLoc(N), TLI, VT, DAG, LegalOperations, LegalTypes);
1660   // fold (sub c1, c2) -> c1-c2
1661   if (N0C && N1C)
1662     return DAG.FoldConstantArithmetic(ISD::SUB, VT, N0C, N1C);
1663   // fold (sub x, c) -> (add x, -c)
1664   if (N1C)
1665     return DAG.getNode(ISD::ADD, SDLoc(N), VT, N0,
1666                        DAG.getConstant(-N1C->getAPIntValue(), VT));
1667   // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1)
1668   if (N0C && N0C->isAllOnesValue())
1669     return DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0);
1670   // fold A-(A-B) -> B
1671   if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(0))
1672     return N1.getOperand(1);
1673   // fold (A+B)-A -> B
1674   if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1)
1675     return N0.getOperand(1);
1676   // fold (A+B)-B -> A
1677   if (N0.getOpcode() == ISD::ADD && N0.getOperand(1) == N1)
1678     return N0.getOperand(0);
1679   // fold C2-(A+C1) -> (C2-C1)-A
1680   if (N1.getOpcode() == ISD::ADD && N0C && N1C1) {
1681     SDValue NewC = DAG.getConstant(N0C->getAPIntValue() - N1C1->getAPIntValue(),
1682                                    VT);
1683     return DAG.getNode(ISD::SUB, SDLoc(N), VT, NewC,
1684                        N1.getOperand(0));
1685   }
1686   // fold ((A+(B+or-C))-B) -> A+or-C
1687   if (N0.getOpcode() == ISD::ADD &&
1688       (N0.getOperand(1).getOpcode() == ISD::SUB ||
1689        N0.getOperand(1).getOpcode() == ISD::ADD) &&
1690       N0.getOperand(1).getOperand(0) == N1)
1691     return DAG.getNode(N0.getOperand(1).getOpcode(), SDLoc(N), VT,
1692                        N0.getOperand(0), N0.getOperand(1).getOperand(1));
1693   // fold ((A+(C+B))-B) -> A+C
1694   if (N0.getOpcode() == ISD::ADD &&
1695       N0.getOperand(1).getOpcode() == ISD::ADD &&
1696       N0.getOperand(1).getOperand(1) == N1)
1697     return DAG.getNode(ISD::ADD, SDLoc(N), VT,
1698                        N0.getOperand(0), N0.getOperand(1).getOperand(0));
1699   // fold ((A-(B-C))-C) -> A-B
1700   if (N0.getOpcode() == ISD::SUB &&
1701       N0.getOperand(1).getOpcode() == ISD::SUB &&
1702       N0.getOperand(1).getOperand(1) == N1)
1703     return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1704                        N0.getOperand(0), N0.getOperand(1).getOperand(0));
1705
1706   // If either operand of a sub is undef, the result is undef
1707   if (N0.getOpcode() == ISD::UNDEF)
1708     return N0;
1709   if (N1.getOpcode() == ISD::UNDEF)
1710     return N1;
1711
1712   // If the relocation model supports it, consider symbol offsets.
1713   if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N0))
1714     if (!LegalOperations && TLI.isOffsetFoldingLegal(GA)) {
1715       // fold (sub Sym, c) -> Sym-c
1716       if (N1C && GA->getOpcode() == ISD::GlobalAddress)
1717         return DAG.getGlobalAddress(GA->getGlobal(), SDLoc(N1C), VT,
1718                                     GA->getOffset() -
1719                                       (uint64_t)N1C->getSExtValue());
1720       // fold (sub Sym+c1, Sym+c2) -> c1-c2
1721       if (GlobalAddressSDNode *GB = dyn_cast<GlobalAddressSDNode>(N1))
1722         if (GA->getGlobal() == GB->getGlobal())
1723           return DAG.getConstant((uint64_t)GA->getOffset() - GB->getOffset(),
1724                                  VT);
1725     }
1726
1727   return SDValue();
1728 }
1729
1730 SDValue DAGCombiner::visitSUBC(SDNode *N) {
1731   SDValue N0 = N->getOperand(0);
1732   SDValue N1 = N->getOperand(1);
1733   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1734   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1735   EVT VT = N0.getValueType();
1736
1737   // If the flag result is dead, turn this into an SUB.
1738   if (!N->hasAnyUseOfValue(1))
1739     return CombineTo(N, DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, N1),
1740                      DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
1741                                  MVT::Glue));
1742
1743   // fold (subc x, x) -> 0 + no borrow
1744   if (N0 == N1)
1745     return CombineTo(N, DAG.getConstant(0, VT),
1746                      DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
1747                                  MVT::Glue));
1748
1749   // fold (subc x, 0) -> x + no borrow
1750   if (N1C && N1C->isNullValue())
1751     return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
1752                                         MVT::Glue));
1753
1754   // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1) + no borrow
1755   if (N0C && N0C->isAllOnesValue())
1756     return CombineTo(N, DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0),
1757                      DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
1758                                  MVT::Glue));
1759
1760   return SDValue();
1761 }
1762
1763 SDValue DAGCombiner::visitSUBE(SDNode *N) {
1764   SDValue N0 = N->getOperand(0);
1765   SDValue N1 = N->getOperand(1);
1766   SDValue CarryIn = N->getOperand(2);
1767
1768   // fold (sube x, y, false) -> (subc x, y)
1769   if (CarryIn.getOpcode() == ISD::CARRY_FALSE)
1770     return DAG.getNode(ISD::SUBC, SDLoc(N), N->getVTList(), N0, N1);
1771
1772   return SDValue();
1773 }
1774
1775 /// isConstantSplatVector - Returns true if N is a BUILD_VECTOR node whose elements are
1776 /// all the same constant or undefined.
1777 static bool isConstantSplatVector(SDNode *N, APInt& SplatValue) {
1778   BuildVectorSDNode *C = dyn_cast<BuildVectorSDNode>(N);
1779   if (!C)
1780     return false;
1781
1782   APInt SplatUndef;
1783   unsigned SplatBitSize;
1784   bool HasAnyUndefs;
1785   EVT EltVT = N->getValueType(0).getVectorElementType();
1786   return (C->isConstantSplat(SplatValue, SplatUndef, SplatBitSize,
1787                              HasAnyUndefs) &&
1788           EltVT.getSizeInBits() >= SplatBitSize);
1789 }
1790
1791 SDValue DAGCombiner::visitMUL(SDNode *N) {
1792   SDValue N0 = N->getOperand(0);
1793   SDValue N1 = N->getOperand(1);
1794   EVT VT = N0.getValueType();
1795
1796   // fold (mul x, undef) -> 0
1797   if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
1798     return DAG.getConstant(0, VT);
1799
1800   bool N0IsConst = false;
1801   bool N1IsConst = false;
1802   APInt ConstValue0, ConstValue1;
1803   // fold vector ops
1804   if (VT.isVector()) {
1805     SDValue FoldedVOp = SimplifyVBinOp(N);
1806     if (FoldedVOp.getNode()) return FoldedVOp;
1807
1808     N0IsConst = isConstantSplatVector(N0.getNode(), ConstValue0);
1809     N1IsConst = isConstantSplatVector(N1.getNode(), ConstValue1);
1810   } else {
1811     N0IsConst = dyn_cast<ConstantSDNode>(N0) != 0;
1812     ConstValue0 = N0IsConst? (dyn_cast<ConstantSDNode>(N0))->getAPIntValue() : APInt();
1813     N1IsConst = dyn_cast<ConstantSDNode>(N1) != 0;
1814     ConstValue1 = N1IsConst? (dyn_cast<ConstantSDNode>(N1))->getAPIntValue() : APInt();
1815   }
1816
1817   // fold (mul c1, c2) -> c1*c2
1818   if (N0IsConst && N1IsConst)
1819     return DAG.FoldConstantArithmetic(ISD::MUL, VT, N0.getNode(), N1.getNode());
1820
1821   // canonicalize constant to RHS
1822   if (N0IsConst && !N1IsConst)
1823     return DAG.getNode(ISD::MUL, SDLoc(N), VT, N1, N0);
1824   // fold (mul x, 0) -> 0
1825   if (N1IsConst && ConstValue1 == 0)
1826     return N1;
1827   // We require a splat of the entire scalar bit width for non-contiguous
1828   // bit patterns.
1829   bool IsFullSplat =
1830     ConstValue1.getBitWidth() == VT.getScalarType().getSizeInBits();
1831   // fold (mul x, 1) -> x
1832   if (N1IsConst && ConstValue1 == 1 && IsFullSplat)
1833     return N0;
1834   // fold (mul x, -1) -> 0-x
1835   if (N1IsConst && ConstValue1.isAllOnesValue())
1836     return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1837                        DAG.getConstant(0, VT), N0);
1838   // fold (mul x, (1 << c)) -> x << c
1839   if (N1IsConst && ConstValue1.isPowerOf2() && IsFullSplat)
1840     return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0,
1841                        DAG.getConstant(ConstValue1.logBase2(),
1842                                        getShiftAmountTy(N0.getValueType())));
1843   // fold (mul x, -(1 << c)) -> -(x << c) or (-x) << c
1844   if (N1IsConst && (-ConstValue1).isPowerOf2() && IsFullSplat) {
1845     unsigned Log2Val = (-ConstValue1).logBase2();
1846     // FIXME: If the input is something that is easily negated (e.g. a
1847     // single-use add), we should put the negate there.
1848     return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1849                        DAG.getConstant(0, VT),
1850                        DAG.getNode(ISD::SHL, SDLoc(N), VT, N0,
1851                             DAG.getConstant(Log2Val,
1852                                       getShiftAmountTy(N0.getValueType()))));
1853   }
1854
1855   APInt Val;
1856   // (mul (shl X, c1), c2) -> (mul X, c2 << c1)
1857   if (N1IsConst && N0.getOpcode() == ISD::SHL &&
1858       (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
1859                      isa<ConstantSDNode>(N0.getOperand(1)))) {
1860     SDValue C3 = DAG.getNode(ISD::SHL, SDLoc(N), VT,
1861                              N1, N0.getOperand(1));
1862     AddToWorkList(C3.getNode());
1863     return DAG.getNode(ISD::MUL, SDLoc(N), VT,
1864                        N0.getOperand(0), C3);
1865   }
1866
1867   // Change (mul (shl X, C), Y) -> (shl (mul X, Y), C) when the shift has one
1868   // use.
1869   {
1870     SDValue Sh(0,0), Y(0,0);
1871     // Check for both (mul (shl X, C), Y)  and  (mul Y, (shl X, C)).
1872     if (N0.getOpcode() == ISD::SHL &&
1873         (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
1874                        isa<ConstantSDNode>(N0.getOperand(1))) &&
1875         N0.getNode()->hasOneUse()) {
1876       Sh = N0; Y = N1;
1877     } else if (N1.getOpcode() == ISD::SHL &&
1878                isa<ConstantSDNode>(N1.getOperand(1)) &&
1879                N1.getNode()->hasOneUse()) {
1880       Sh = N1; Y = N0;
1881     }
1882
1883     if (Sh.getNode()) {
1884       SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT,
1885                                 Sh.getOperand(0), Y);
1886       return DAG.getNode(ISD::SHL, SDLoc(N), VT,
1887                          Mul, Sh.getOperand(1));
1888     }
1889   }
1890
1891   // fold (mul (add x, c1), c2) -> (add (mul x, c2), c1*c2)
1892   if (N1IsConst && N0.getOpcode() == ISD::ADD && N0.getNode()->hasOneUse() &&
1893       (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
1894                      isa<ConstantSDNode>(N0.getOperand(1))))
1895     return DAG.getNode(ISD::ADD, SDLoc(N), VT,
1896                        DAG.getNode(ISD::MUL, SDLoc(N0), VT,
1897                                    N0.getOperand(0), N1),
1898                        DAG.getNode(ISD::MUL, SDLoc(N1), VT,
1899                                    N0.getOperand(1), N1));
1900
1901   // reassociate mul
1902   SDValue RMUL = ReassociateOps(ISD::MUL, SDLoc(N), N0, N1);
1903   if (RMUL.getNode() != 0)
1904     return RMUL;
1905
1906   return SDValue();
1907 }
1908
1909 SDValue DAGCombiner::visitSDIV(SDNode *N) {
1910   SDValue N0 = N->getOperand(0);
1911   SDValue N1 = N->getOperand(1);
1912   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getNode());
1913   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
1914   EVT VT = N->getValueType(0);
1915
1916   // fold vector ops
1917   if (VT.isVector()) {
1918     SDValue FoldedVOp = SimplifyVBinOp(N);
1919     if (FoldedVOp.getNode()) return FoldedVOp;
1920   }
1921
1922   // fold (sdiv c1, c2) -> c1/c2
1923   if (N0C && N1C && !N1C->isNullValue())
1924     return DAG.FoldConstantArithmetic(ISD::SDIV, VT, N0C, N1C);
1925   // fold (sdiv X, 1) -> X
1926   if (N1C && N1C->getAPIntValue() == 1LL)
1927     return N0;
1928   // fold (sdiv X, -1) -> 0-X
1929   if (N1C && N1C->isAllOnesValue())
1930     return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1931                        DAG.getConstant(0, VT), N0);
1932   // If we know the sign bits of both operands are zero, strength reduce to a
1933   // udiv instead.  Handles (X&15) /s 4 -> X&15 >> 2
1934   if (!VT.isVector()) {
1935     if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
1936       return DAG.getNode(ISD::UDIV, SDLoc(N), N1.getValueType(),
1937                          N0, N1);
1938   }
1939   // fold (sdiv X, pow2) -> simple ops after legalize
1940   if (N1C && !N1C->isNullValue() &&
1941       (N1C->getAPIntValue().isPowerOf2() ||
1942        (-N1C->getAPIntValue()).isPowerOf2())) {
1943     // If dividing by powers of two is cheap, then don't perform the following
1944     // fold.
1945     if (TLI.isPow2DivCheap())
1946       return SDValue();
1947
1948     unsigned lg2 = N1C->getAPIntValue().countTrailingZeros();
1949
1950     // Splat the sign bit into the register
1951     SDValue SGN = DAG.getNode(ISD::SRA, SDLoc(N), VT, N0,
1952                               DAG.getConstant(VT.getSizeInBits()-1,
1953                                        getShiftAmountTy(N0.getValueType())));
1954     AddToWorkList(SGN.getNode());
1955
1956     // Add (N0 < 0) ? abs2 - 1 : 0;
1957     SDValue SRL = DAG.getNode(ISD::SRL, SDLoc(N), VT, SGN,
1958                               DAG.getConstant(VT.getSizeInBits() - lg2,
1959                                        getShiftAmountTy(SGN.getValueType())));
1960     SDValue ADD = DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, SRL);
1961     AddToWorkList(SRL.getNode());
1962     AddToWorkList(ADD.getNode());    // Divide by pow2
1963     SDValue SRA = DAG.getNode(ISD::SRA, SDLoc(N), VT, ADD,
1964                   DAG.getConstant(lg2, getShiftAmountTy(ADD.getValueType())));
1965
1966     // If we're dividing by a positive value, we're done.  Otherwise, we must
1967     // negate the result.
1968     if (N1C->getAPIntValue().isNonNegative())
1969       return SRA;
1970
1971     AddToWorkList(SRA.getNode());
1972     return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1973                        DAG.getConstant(0, VT), SRA);
1974   }
1975
1976   // if integer divide is expensive and we satisfy the requirements, emit an
1977   // alternate sequence.
1978   if (N1C && !N1C->isNullValue() && !TLI.isIntDivCheap()) {
1979     SDValue Op = BuildSDIV(N);
1980     if (Op.getNode()) return Op;
1981   }
1982
1983   // undef / X -> 0
1984   if (N0.getOpcode() == ISD::UNDEF)
1985     return DAG.getConstant(0, VT);
1986   // X / undef -> undef
1987   if (N1.getOpcode() == ISD::UNDEF)
1988     return N1;
1989
1990   return SDValue();
1991 }
1992
1993 SDValue DAGCombiner::visitUDIV(SDNode *N) {
1994   SDValue N0 = N->getOperand(0);
1995   SDValue N1 = N->getOperand(1);
1996   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getNode());
1997   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
1998   EVT VT = N->getValueType(0);
1999
2000   // fold vector ops
2001   if (VT.isVector()) {
2002     SDValue FoldedVOp = SimplifyVBinOp(N);
2003     if (FoldedVOp.getNode()) return FoldedVOp;
2004   }
2005
2006   // fold (udiv c1, c2) -> c1/c2
2007   if (N0C && N1C && !N1C->isNullValue())
2008     return DAG.FoldConstantArithmetic(ISD::UDIV, VT, N0C, N1C);
2009   // fold (udiv x, (1 << c)) -> x >>u c
2010   if (N1C && N1C->getAPIntValue().isPowerOf2())
2011     return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0,
2012                        DAG.getConstant(N1C->getAPIntValue().logBase2(),
2013                                        getShiftAmountTy(N0.getValueType())));
2014   // fold (udiv x, (shl c, y)) -> x >>u (log2(c)+y) iff c is power of 2
2015   if (N1.getOpcode() == ISD::SHL) {
2016     if (ConstantSDNode *SHC = dyn_cast<ConstantSDNode>(N1.getOperand(0))) {
2017       if (SHC->getAPIntValue().isPowerOf2()) {
2018         EVT ADDVT = N1.getOperand(1).getValueType();
2019         SDValue Add = DAG.getNode(ISD::ADD, SDLoc(N), ADDVT,
2020                                   N1.getOperand(1),
2021                                   DAG.getConstant(SHC->getAPIntValue()
2022                                                                   .logBase2(),
2023                                                   ADDVT));
2024         AddToWorkList(Add.getNode());
2025         return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, Add);
2026       }
2027     }
2028   }
2029   // fold (udiv x, c) -> alternate
2030   if (N1C && !N1C->isNullValue() && !TLI.isIntDivCheap()) {
2031     SDValue Op = BuildUDIV(N);
2032     if (Op.getNode()) return Op;
2033   }
2034
2035   // undef / X -> 0
2036   if (N0.getOpcode() == ISD::UNDEF)
2037     return DAG.getConstant(0, VT);
2038   // X / undef -> undef
2039   if (N1.getOpcode() == ISD::UNDEF)
2040     return N1;
2041
2042   return SDValue();
2043 }
2044
2045 SDValue DAGCombiner::visitSREM(SDNode *N) {
2046   SDValue N0 = N->getOperand(0);
2047   SDValue N1 = N->getOperand(1);
2048   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
2049   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2050   EVT VT = N->getValueType(0);
2051
2052   // fold (srem c1, c2) -> c1%c2
2053   if (N0C && N1C && !N1C->isNullValue())
2054     return DAG.FoldConstantArithmetic(ISD::SREM, VT, N0C, N1C);
2055   // If we know the sign bits of both operands are zero, strength reduce to a
2056   // urem instead.  Handles (X & 0x0FFFFFFF) %s 16 -> X&15
2057   if (!VT.isVector()) {
2058     if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
2059       return DAG.getNode(ISD::UREM, SDLoc(N), VT, N0, N1);
2060   }
2061
2062   // If X/C can be simplified by the division-by-constant logic, lower
2063   // X%C to the equivalent of X-X/C*C.
2064   if (N1C && !N1C->isNullValue()) {
2065     SDValue Div = DAG.getNode(ISD::SDIV, SDLoc(N), VT, N0, N1);
2066     AddToWorkList(Div.getNode());
2067     SDValue OptimizedDiv = combine(Div.getNode());
2068     if (OptimizedDiv.getNode() && OptimizedDiv.getNode() != Div.getNode()) {
2069       SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT,
2070                                 OptimizedDiv, N1);
2071       SDValue Sub = DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, Mul);
2072       AddToWorkList(Mul.getNode());
2073       return Sub;
2074     }
2075   }
2076
2077   // undef % X -> 0
2078   if (N0.getOpcode() == ISD::UNDEF)
2079     return DAG.getConstant(0, VT);
2080   // X % undef -> undef
2081   if (N1.getOpcode() == ISD::UNDEF)
2082     return N1;
2083
2084   return SDValue();
2085 }
2086
2087 SDValue DAGCombiner::visitUREM(SDNode *N) {
2088   SDValue N0 = N->getOperand(0);
2089   SDValue N1 = N->getOperand(1);
2090   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
2091   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2092   EVT VT = N->getValueType(0);
2093
2094   // fold (urem c1, c2) -> c1%c2
2095   if (N0C && N1C && !N1C->isNullValue())
2096     return DAG.FoldConstantArithmetic(ISD::UREM, VT, N0C, N1C);
2097   // fold (urem x, pow2) -> (and x, pow2-1)
2098   if (N1C && !N1C->isNullValue() && N1C->getAPIntValue().isPowerOf2())
2099     return DAG.getNode(ISD::AND, SDLoc(N), VT, N0,
2100                        DAG.getConstant(N1C->getAPIntValue()-1,VT));
2101   // fold (urem x, (shl pow2, y)) -> (and x, (add (shl pow2, y), -1))
2102   if (N1.getOpcode() == ISD::SHL) {
2103     if (ConstantSDNode *SHC = dyn_cast<ConstantSDNode>(N1.getOperand(0))) {
2104       if (SHC->getAPIntValue().isPowerOf2()) {
2105         SDValue Add =
2106           DAG.getNode(ISD::ADD, SDLoc(N), VT, N1,
2107                  DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()),
2108                                  VT));
2109         AddToWorkList(Add.getNode());
2110         return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, Add);
2111       }
2112     }
2113   }
2114
2115   // If X/C can be simplified by the division-by-constant logic, lower
2116   // X%C to the equivalent of X-X/C*C.
2117   if (N1C && !N1C->isNullValue()) {
2118     SDValue Div = DAG.getNode(ISD::UDIV, SDLoc(N), VT, N0, N1);
2119     AddToWorkList(Div.getNode());
2120     SDValue OptimizedDiv = combine(Div.getNode());
2121     if (OptimizedDiv.getNode() && OptimizedDiv.getNode() != Div.getNode()) {
2122       SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT,
2123                                 OptimizedDiv, N1);
2124       SDValue Sub = DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, Mul);
2125       AddToWorkList(Mul.getNode());
2126       return Sub;
2127     }
2128   }
2129
2130   // undef % X -> 0
2131   if (N0.getOpcode() == ISD::UNDEF)
2132     return DAG.getConstant(0, VT);
2133   // X % undef -> undef
2134   if (N1.getOpcode() == ISD::UNDEF)
2135     return N1;
2136
2137   return SDValue();
2138 }
2139
2140 SDValue DAGCombiner::visitMULHS(SDNode *N) {
2141   SDValue N0 = N->getOperand(0);
2142   SDValue N1 = N->getOperand(1);
2143   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2144   EVT VT = N->getValueType(0);
2145   SDLoc DL(N);
2146
2147   // fold (mulhs x, 0) -> 0
2148   if (N1C && N1C->isNullValue())
2149     return N1;
2150   // fold (mulhs x, 1) -> (sra x, size(x)-1)
2151   if (N1C && N1C->getAPIntValue() == 1)
2152     return DAG.getNode(ISD::SRA, SDLoc(N), N0.getValueType(), N0,
2153                        DAG.getConstant(N0.getValueType().getSizeInBits() - 1,
2154                                        getShiftAmountTy(N0.getValueType())));
2155   // fold (mulhs x, undef) -> 0
2156   if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2157     return DAG.getConstant(0, VT);
2158
2159   // If the type twice as wide is legal, transform the mulhs to a wider multiply
2160   // plus a shift.
2161   if (VT.isSimple() && !VT.isVector()) {
2162     MVT Simple = VT.getSimpleVT();
2163     unsigned SimpleSize = Simple.getSizeInBits();
2164     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2165     if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2166       N0 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N0);
2167       N1 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N1);
2168       N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1);
2169       N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1,
2170             DAG.getConstant(SimpleSize, getShiftAmountTy(N1.getValueType())));
2171       return DAG.getNode(ISD::TRUNCATE, DL, VT, N1);
2172     }
2173   }
2174
2175   return SDValue();
2176 }
2177
2178 SDValue DAGCombiner::visitMULHU(SDNode *N) {
2179   SDValue N0 = N->getOperand(0);
2180   SDValue N1 = N->getOperand(1);
2181   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2182   EVT VT = N->getValueType(0);
2183   SDLoc DL(N);
2184
2185   // fold (mulhu x, 0) -> 0
2186   if (N1C && N1C->isNullValue())
2187     return N1;
2188   // fold (mulhu x, 1) -> 0
2189   if (N1C && N1C->getAPIntValue() == 1)
2190     return DAG.getConstant(0, N0.getValueType());
2191   // fold (mulhu x, undef) -> 0
2192   if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2193     return DAG.getConstant(0, VT);
2194
2195   // If the type twice as wide is legal, transform the mulhu to a wider multiply
2196   // plus a shift.
2197   if (VT.isSimple() && !VT.isVector()) {
2198     MVT Simple = VT.getSimpleVT();
2199     unsigned SimpleSize = Simple.getSizeInBits();
2200     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2201     if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2202       N0 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N0);
2203       N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N1);
2204       N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1);
2205       N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1,
2206             DAG.getConstant(SimpleSize, getShiftAmountTy(N1.getValueType())));
2207       return DAG.getNode(ISD::TRUNCATE, DL, VT, N1);
2208     }
2209   }
2210
2211   return SDValue();
2212 }
2213
2214 /// SimplifyNodeWithTwoResults - Perform optimizations common to nodes that
2215 /// compute two values. LoOp and HiOp give the opcodes for the two computations
2216 /// that are being performed. Return true if a simplification was made.
2217 ///
2218 SDValue DAGCombiner::SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp,
2219                                                 unsigned HiOp) {
2220   // If the high half is not needed, just compute the low half.
2221   bool HiExists = N->hasAnyUseOfValue(1);
2222   if (!HiExists &&
2223       (!LegalOperations ||
2224        TLI.isOperationLegal(LoOp, N->getValueType(0)))) {
2225     SDValue Res = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0),
2226                               N->op_begin(), N->getNumOperands());
2227     return CombineTo(N, Res, Res);
2228   }
2229
2230   // If the low half is not needed, just compute the high half.
2231   bool LoExists = N->hasAnyUseOfValue(0);
2232   if (!LoExists &&
2233       (!LegalOperations ||
2234        TLI.isOperationLegal(HiOp, N->getValueType(1)))) {
2235     SDValue Res = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1),
2236                               N->op_begin(), N->getNumOperands());
2237     return CombineTo(N, Res, Res);
2238   }
2239
2240   // If both halves are used, return as it is.
2241   if (LoExists && HiExists)
2242     return SDValue();
2243
2244   // If the two computed results can be simplified separately, separate them.
2245   if (LoExists) {
2246     SDValue Lo = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0),
2247                              N->op_begin(), N->getNumOperands());
2248     AddToWorkList(Lo.getNode());
2249     SDValue LoOpt = combine(Lo.getNode());
2250     if (LoOpt.getNode() && LoOpt.getNode() != Lo.getNode() &&
2251         (!LegalOperations ||
2252          TLI.isOperationLegal(LoOpt.getOpcode(), LoOpt.getValueType())))
2253       return CombineTo(N, LoOpt, LoOpt);
2254   }
2255
2256   if (HiExists) {
2257     SDValue Hi = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1),
2258                              N->op_begin(), N->getNumOperands());
2259     AddToWorkList(Hi.getNode());
2260     SDValue HiOpt = combine(Hi.getNode());
2261     if (HiOpt.getNode() && HiOpt != Hi &&
2262         (!LegalOperations ||
2263          TLI.isOperationLegal(HiOpt.getOpcode(), HiOpt.getValueType())))
2264       return CombineTo(N, HiOpt, HiOpt);
2265   }
2266
2267   return SDValue();
2268 }
2269
2270 SDValue DAGCombiner::visitSMUL_LOHI(SDNode *N) {
2271   SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHS);
2272   if (Res.getNode()) return Res;
2273
2274   EVT VT = N->getValueType(0);
2275   SDLoc DL(N);
2276
2277   // If the type twice as wide is legal, transform the mulhu to a wider multiply
2278   // plus a shift.
2279   if (VT.isSimple() && !VT.isVector()) {
2280     MVT Simple = VT.getSimpleVT();
2281     unsigned SimpleSize = Simple.getSizeInBits();
2282     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2283     if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2284       SDValue Lo = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(0));
2285       SDValue Hi = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(1));
2286       Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi);
2287       // Compute the high part as N1.
2288       Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo,
2289             DAG.getConstant(SimpleSize, getShiftAmountTy(Lo.getValueType())));
2290       Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi);
2291       // Compute the low part as N0.
2292       Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo);
2293       return CombineTo(N, Lo, Hi);
2294     }
2295   }
2296
2297   return SDValue();
2298 }
2299
2300 SDValue DAGCombiner::visitUMUL_LOHI(SDNode *N) {
2301   SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHU);
2302   if (Res.getNode()) return Res;
2303
2304   EVT VT = N->getValueType(0);
2305   SDLoc DL(N);
2306
2307   // If the type twice as wide is legal, transform the mulhu to a wider multiply
2308   // plus a shift.
2309   if (VT.isSimple() && !VT.isVector()) {
2310     MVT Simple = VT.getSimpleVT();
2311     unsigned SimpleSize = Simple.getSizeInBits();
2312     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2313     if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2314       SDValue Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(0));
2315       SDValue Hi = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(1));
2316       Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi);
2317       // Compute the high part as N1.
2318       Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo,
2319             DAG.getConstant(SimpleSize, getShiftAmountTy(Lo.getValueType())));
2320       Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi);
2321       // Compute the low part as N0.
2322       Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo);
2323       return CombineTo(N, Lo, Hi);
2324     }
2325   }
2326
2327   return SDValue();
2328 }
2329
2330 SDValue DAGCombiner::visitSMULO(SDNode *N) {
2331   // (smulo x, 2) -> (saddo x, x)
2332   if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1)))
2333     if (C2->getAPIntValue() == 2)
2334       return DAG.getNode(ISD::SADDO, SDLoc(N), N->getVTList(),
2335                          N->getOperand(0), N->getOperand(0));
2336
2337   return SDValue();
2338 }
2339
2340 SDValue DAGCombiner::visitUMULO(SDNode *N) {
2341   // (umulo x, 2) -> (uaddo x, x)
2342   if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1)))
2343     if (C2->getAPIntValue() == 2)
2344       return DAG.getNode(ISD::UADDO, SDLoc(N), N->getVTList(),
2345                          N->getOperand(0), N->getOperand(0));
2346
2347   return SDValue();
2348 }
2349
2350 SDValue DAGCombiner::visitSDIVREM(SDNode *N) {
2351   SDValue Res = SimplifyNodeWithTwoResults(N, ISD::SDIV, ISD::SREM);
2352   if (Res.getNode()) return Res;
2353
2354   return SDValue();
2355 }
2356
2357 SDValue DAGCombiner::visitUDIVREM(SDNode *N) {
2358   SDValue Res = SimplifyNodeWithTwoResults(N, ISD::UDIV, ISD::UREM);
2359   if (Res.getNode()) return Res;
2360
2361   return SDValue();
2362 }
2363
2364 /// SimplifyBinOpWithSameOpcodeHands - If this is a binary operator with
2365 /// two operands of the same opcode, try to simplify it.
2366 SDValue DAGCombiner::SimplifyBinOpWithSameOpcodeHands(SDNode *N) {
2367   SDValue N0 = N->getOperand(0), N1 = N->getOperand(1);
2368   EVT VT = N0.getValueType();
2369   assert(N0.getOpcode() == N1.getOpcode() && "Bad input!");
2370
2371   // Bail early if none of these transforms apply.
2372   if (N0.getNode()->getNumOperands() == 0) return SDValue();
2373
2374   // For each of OP in AND/OR/XOR:
2375   // fold (OP (zext x), (zext y)) -> (zext (OP x, y))
2376   // fold (OP (sext x), (sext y)) -> (sext (OP x, y))
2377   // fold (OP (aext x), (aext y)) -> (aext (OP x, y))
2378   // fold (OP (trunc x), (trunc y)) -> (trunc (OP x, y)) (if trunc isn't free)
2379   //
2380   // do not sink logical op inside of a vector extend, since it may combine
2381   // into a vsetcc.
2382   EVT Op0VT = N0.getOperand(0).getValueType();
2383   if ((N0.getOpcode() == ISD::ZERO_EXTEND ||
2384        N0.getOpcode() == ISD::SIGN_EXTEND ||
2385        // Avoid infinite looping with PromoteIntBinOp.
2386        (N0.getOpcode() == ISD::ANY_EXTEND &&
2387         (!LegalTypes || TLI.isTypeDesirableForOp(N->getOpcode(), Op0VT))) ||
2388        (N0.getOpcode() == ISD::TRUNCATE &&
2389         (!TLI.isZExtFree(VT, Op0VT) ||
2390          !TLI.isTruncateFree(Op0VT, VT)) &&
2391         TLI.isTypeLegal(Op0VT))) &&
2392       !VT.isVector() &&
2393       Op0VT == N1.getOperand(0).getValueType() &&
2394       (!LegalOperations || TLI.isOperationLegal(N->getOpcode(), Op0VT))) {
2395     SDValue ORNode = DAG.getNode(N->getOpcode(), SDLoc(N0),
2396                                  N0.getOperand(0).getValueType(),
2397                                  N0.getOperand(0), N1.getOperand(0));
2398     AddToWorkList(ORNode.getNode());
2399     return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, ORNode);
2400   }
2401
2402   // For each of OP in SHL/SRL/SRA/AND...
2403   //   fold (and (OP x, z), (OP y, z)) -> (OP (and x, y), z)
2404   //   fold (or  (OP x, z), (OP y, z)) -> (OP (or  x, y), z)
2405   //   fold (xor (OP x, z), (OP y, z)) -> (OP (xor x, y), z)
2406   if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL ||
2407        N0.getOpcode() == ISD::SRA || N0.getOpcode() == ISD::AND) &&
2408       N0.getOperand(1) == N1.getOperand(1)) {
2409     SDValue ORNode = DAG.getNode(N->getOpcode(), SDLoc(N0),
2410                                  N0.getOperand(0).getValueType(),
2411                                  N0.getOperand(0), N1.getOperand(0));
2412     AddToWorkList(ORNode.getNode());
2413     return DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
2414                        ORNode, N0.getOperand(1));
2415   }
2416
2417   // Simplify xor/and/or (bitcast(A), bitcast(B)) -> bitcast(op (A,B))
2418   // Only perform this optimization after type legalization and before
2419   // LegalizeVectorOprs. LegalizeVectorOprs promotes vector operations by
2420   // adding bitcasts. For example (xor v4i32) is promoted to (v2i64), and
2421   // we don't want to undo this promotion.
2422   // We also handle SCALAR_TO_VECTOR because xor/or/and operations are cheaper
2423   // on scalars.
2424   if ((N0.getOpcode() == ISD::BITCAST ||
2425        N0.getOpcode() == ISD::SCALAR_TO_VECTOR) &&
2426       Level == AfterLegalizeTypes) {
2427     SDValue In0 = N0.getOperand(0);
2428     SDValue In1 = N1.getOperand(0);
2429     EVT In0Ty = In0.getValueType();
2430     EVT In1Ty = In1.getValueType();
2431     SDLoc DL(N);
2432     // If both incoming values are integers, and the original types are the
2433     // same.
2434     if (In0Ty.isInteger() && In1Ty.isInteger() && In0Ty == In1Ty) {
2435       SDValue Op = DAG.getNode(N->getOpcode(), DL, In0Ty, In0, In1);
2436       SDValue BC = DAG.getNode(N0.getOpcode(), DL, VT, Op);
2437       AddToWorkList(Op.getNode());
2438       return BC;
2439     }
2440   }
2441
2442   // Xor/and/or are indifferent to the swizzle operation (shuffle of one value).
2443   // Simplify xor/and/or (shuff(A), shuff(B)) -> shuff(op (A,B))
2444   // If both shuffles use the same mask, and both shuffle within a single
2445   // vector, then it is worthwhile to move the swizzle after the operation.
2446   // The type-legalizer generates this pattern when loading illegal
2447   // vector types from memory. In many cases this allows additional shuffle
2448   // optimizations.
2449   if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG &&
2450       N0.getOperand(1).getOpcode() == ISD::UNDEF &&
2451       N1.getOperand(1).getOpcode() == ISD::UNDEF) {
2452     ShuffleVectorSDNode *SVN0 = cast<ShuffleVectorSDNode>(N0);
2453     ShuffleVectorSDNode *SVN1 = cast<ShuffleVectorSDNode>(N1);
2454
2455     assert(N0.getOperand(0).getValueType() == N1.getOperand(1).getValueType() &&
2456            "Inputs to shuffles are not the same type");
2457
2458     unsigned NumElts = VT.getVectorNumElements();
2459
2460     // Check that both shuffles use the same mask. The masks are known to be of
2461     // the same length because the result vector type is the same.
2462     bool SameMask = true;
2463     for (unsigned i = 0; i != NumElts; ++i) {
2464       int Idx0 = SVN0->getMaskElt(i);
2465       int Idx1 = SVN1->getMaskElt(i);
2466       if (Idx0 != Idx1) {
2467         SameMask = false;
2468         break;
2469       }
2470     }
2471
2472     if (SameMask) {
2473       SDValue Op = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
2474                                N0.getOperand(0), N1.getOperand(0));
2475       AddToWorkList(Op.getNode());
2476       return DAG.getVectorShuffle(VT, SDLoc(N), Op,
2477                                   DAG.getUNDEF(VT), &SVN0->getMask()[0]);
2478     }
2479   }
2480
2481   return SDValue();
2482 }
2483
2484 SDValue DAGCombiner::visitAND(SDNode *N) {
2485   SDValue N0 = N->getOperand(0);
2486   SDValue N1 = N->getOperand(1);
2487   SDValue LL, LR, RL, RR, CC0, CC1;
2488   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
2489   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2490   EVT VT = N1.getValueType();
2491   unsigned BitWidth = VT.getScalarType().getSizeInBits();
2492
2493   // fold vector ops
2494   if (VT.isVector()) {
2495     SDValue FoldedVOp = SimplifyVBinOp(N);
2496     if (FoldedVOp.getNode()) return FoldedVOp;
2497
2498     // fold (and x, 0) -> 0, vector edition
2499     if (ISD::isBuildVectorAllZeros(N0.getNode()))
2500       return N0;
2501     if (ISD::isBuildVectorAllZeros(N1.getNode()))
2502       return N1;
2503
2504     // fold (and x, -1) -> x, vector edition
2505     if (ISD::isBuildVectorAllOnes(N0.getNode()))
2506       return N1;
2507     if (ISD::isBuildVectorAllOnes(N1.getNode()))
2508       return N0;
2509   }
2510
2511   // fold (and x, undef) -> 0
2512   if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2513     return DAG.getConstant(0, VT);
2514   // fold (and c1, c2) -> c1&c2
2515   if (N0C && N1C)
2516     return DAG.FoldConstantArithmetic(ISD::AND, VT, N0C, N1C);
2517   // canonicalize constant to RHS
2518   if (N0C && !N1C)
2519     return DAG.getNode(ISD::AND, SDLoc(N), VT, N1, N0);
2520   // fold (and x, -1) -> x
2521   if (N1C && N1C->isAllOnesValue())
2522     return N0;
2523   // if (and x, c) is known to be zero, return 0
2524   if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0),
2525                                    APInt::getAllOnesValue(BitWidth)))
2526     return DAG.getConstant(0, VT);
2527   // reassociate and
2528   SDValue RAND = ReassociateOps(ISD::AND, SDLoc(N), N0, N1);
2529   if (RAND.getNode() != 0)
2530     return RAND;
2531   // fold (and (or x, C), D) -> D if (C & D) == D
2532   if (N1C && N0.getOpcode() == ISD::OR)
2533     if (ConstantSDNode *ORI = dyn_cast<ConstantSDNode>(N0.getOperand(1)))
2534       if ((ORI->getAPIntValue() & N1C->getAPIntValue()) == N1C->getAPIntValue())
2535         return N1;
2536   // fold (and (any_ext V), c) -> (zero_ext V) if 'and' only clears top bits.
2537   if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
2538     SDValue N0Op0 = N0.getOperand(0);
2539     APInt Mask = ~N1C->getAPIntValue();
2540     Mask = Mask.trunc(N0Op0.getValueSizeInBits());
2541     if (DAG.MaskedValueIsZero(N0Op0, Mask)) {
2542       SDValue Zext = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N),
2543                                  N0.getValueType(), N0Op0);
2544
2545       // Replace uses of the AND with uses of the Zero extend node.
2546       CombineTo(N, Zext);
2547
2548       // We actually want to replace all uses of the any_extend with the
2549       // zero_extend, to avoid duplicating things.  This will later cause this
2550       // AND to be folded.
2551       CombineTo(N0.getNode(), Zext);
2552       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
2553     }
2554   }
2555   // similarly fold (and (X (load ([non_ext|any_ext|zero_ext] V))), c) ->
2556   // (X (load ([non_ext|zero_ext] V))) if 'and' only clears top bits which must
2557   // already be zero by virtue of the width of the base type of the load.
2558   //
2559   // the 'X' node here can either be nothing or an extract_vector_elt to catch
2560   // more cases.
2561   if ((N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
2562        N0.getOperand(0).getOpcode() == ISD::LOAD) ||
2563       N0.getOpcode() == ISD::LOAD) {
2564     LoadSDNode *Load = cast<LoadSDNode>( (N0.getOpcode() == ISD::LOAD) ?
2565                                          N0 : N0.getOperand(0) );
2566
2567     // Get the constant (if applicable) the zero'th operand is being ANDed with.
2568     // This can be a pure constant or a vector splat, in which case we treat the
2569     // vector as a scalar and use the splat value.
2570     APInt Constant = APInt::getNullValue(1);
2571     if (const ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
2572       Constant = C->getAPIntValue();
2573     } else if (BuildVectorSDNode *Vector = dyn_cast<BuildVectorSDNode>(N1)) {
2574       APInt SplatValue, SplatUndef;
2575       unsigned SplatBitSize;
2576       bool HasAnyUndefs;
2577       bool IsSplat = Vector->isConstantSplat(SplatValue, SplatUndef,
2578                                              SplatBitSize, HasAnyUndefs);
2579       if (IsSplat) {
2580         // Undef bits can contribute to a possible optimisation if set, so
2581         // set them.
2582         SplatValue |= SplatUndef;
2583
2584         // The splat value may be something like "0x00FFFFFF", which means 0 for
2585         // the first vector value and FF for the rest, repeating. We need a mask
2586         // that will apply equally to all members of the vector, so AND all the
2587         // lanes of the constant together.
2588         EVT VT = Vector->getValueType(0);
2589         unsigned BitWidth = VT.getVectorElementType().getSizeInBits();
2590
2591         // If the splat value has been compressed to a bitlength lower
2592         // than the size of the vector lane, we need to re-expand it to
2593         // the lane size.
2594         if (BitWidth > SplatBitSize)
2595           for (SplatValue = SplatValue.zextOrTrunc(BitWidth);
2596                SplatBitSize < BitWidth;
2597                SplatBitSize = SplatBitSize * 2)
2598             SplatValue |= SplatValue.shl(SplatBitSize);
2599
2600         Constant = APInt::getAllOnesValue(BitWidth);
2601         for (unsigned i = 0, n = SplatBitSize/BitWidth; i < n; ++i)
2602           Constant &= SplatValue.lshr(i*BitWidth).zextOrTrunc(BitWidth);
2603       }
2604     }
2605
2606     // If we want to change an EXTLOAD to a ZEXTLOAD, ensure a ZEXTLOAD is
2607     // actually legal and isn't going to get expanded, else this is a false
2608     // optimisation.
2609     bool CanZextLoadProfitably = TLI.isLoadExtLegal(ISD::ZEXTLOAD,
2610                                                     Load->getMemoryVT());
2611
2612     // Resize the constant to the same size as the original memory access before
2613     // extension. If it is still the AllOnesValue then this AND is completely
2614     // unneeded.
2615     Constant =
2616       Constant.zextOrTrunc(Load->getMemoryVT().getScalarType().getSizeInBits());
2617
2618     bool B;
2619     switch (Load->getExtensionType()) {
2620     default: B = false; break;
2621     case ISD::EXTLOAD: B = CanZextLoadProfitably; break;
2622     case ISD::ZEXTLOAD:
2623     case ISD::NON_EXTLOAD: B = true; break;
2624     }
2625
2626     if (B && Constant.isAllOnesValue()) {
2627       // If the load type was an EXTLOAD, convert to ZEXTLOAD in order to
2628       // preserve semantics once we get rid of the AND.
2629       SDValue NewLoad(Load, 0);
2630       if (Load->getExtensionType() == ISD::EXTLOAD) {
2631         NewLoad = DAG.getLoad(Load->getAddressingMode(), ISD::ZEXTLOAD,
2632                               Load->getValueType(0), SDLoc(Load),
2633                               Load->getChain(), Load->getBasePtr(),
2634                               Load->getOffset(), Load->getMemoryVT(),
2635                               Load->getMemOperand());
2636         // Replace uses of the EXTLOAD with the new ZEXTLOAD.
2637         if (Load->getNumValues() == 3) {
2638           // PRE/POST_INC loads have 3 values.
2639           SDValue To[] = { NewLoad.getValue(0), NewLoad.getValue(1),
2640                            NewLoad.getValue(2) };
2641           CombineTo(Load, To, 3, true);
2642         } else {
2643           CombineTo(Load, NewLoad.getValue(0), NewLoad.getValue(1));
2644         }
2645       }
2646
2647       // Fold the AND away, taking care not to fold to the old load node if we
2648       // replaced it.
2649       CombineTo(N, (N0.getNode() == Load) ? NewLoad : N0);
2650
2651       return SDValue(N, 0); // Return N so it doesn't get rechecked!
2652     }
2653   }
2654   // fold (and (setcc x), (setcc y)) -> (setcc (and x, y))
2655   if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){
2656     ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get();
2657     ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get();
2658
2659     if (LR == RR && isa<ConstantSDNode>(LR) && Op0 == Op1 &&
2660         LL.getValueType().isInteger()) {
2661       // fold (and (seteq X, 0), (seteq Y, 0)) -> (seteq (or X, Y), 0)
2662       if (cast<ConstantSDNode>(LR)->isNullValue() && Op1 == ISD::SETEQ) {
2663         SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(N0),
2664                                      LR.getValueType(), LL, RL);
2665         AddToWorkList(ORNode.getNode());
2666         return DAG.getSetCC(SDLoc(N), VT, ORNode, LR, Op1);
2667       }
2668       // fold (and (seteq X, -1), (seteq Y, -1)) -> (seteq (and X, Y), -1)
2669       if (cast<ConstantSDNode>(LR)->isAllOnesValue() && Op1 == ISD::SETEQ) {
2670         SDValue ANDNode = DAG.getNode(ISD::AND, SDLoc(N0),
2671                                       LR.getValueType(), LL, RL);
2672         AddToWorkList(ANDNode.getNode());
2673         return DAG.getSetCC(SDLoc(N), VT, ANDNode, LR, Op1);
2674       }
2675       // fold (and (setgt X,  -1), (setgt Y,  -1)) -> (setgt (or X, Y), -1)
2676       if (cast<ConstantSDNode>(LR)->isAllOnesValue() && Op1 == ISD::SETGT) {
2677         SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(N0),
2678                                      LR.getValueType(), LL, RL);
2679         AddToWorkList(ORNode.getNode());
2680         return DAG.getSetCC(SDLoc(N), VT, ORNode, LR, Op1);
2681       }
2682     }
2683     // Simplify (and (setne X, 0), (setne X, -1)) -> (setuge (add X, 1), 2)
2684     if (LL == RL && isa<ConstantSDNode>(LR) && isa<ConstantSDNode>(RR) &&
2685         Op0 == Op1 && LL.getValueType().isInteger() &&
2686       Op0 == ISD::SETNE && ((cast<ConstantSDNode>(LR)->isNullValue() &&
2687                                  cast<ConstantSDNode>(RR)->isAllOnesValue()) ||
2688                                 (cast<ConstantSDNode>(LR)->isAllOnesValue() &&
2689                                  cast<ConstantSDNode>(RR)->isNullValue()))) {
2690       SDValue ADDNode = DAG.getNode(ISD::ADD, SDLoc(N0), LL.getValueType(),
2691                                     LL, DAG.getConstant(1, LL.getValueType()));
2692       AddToWorkList(ADDNode.getNode());
2693       return DAG.getSetCC(SDLoc(N), VT, ADDNode,
2694                           DAG.getConstant(2, LL.getValueType()), ISD::SETUGE);
2695     }
2696     // canonicalize equivalent to ll == rl
2697     if (LL == RR && LR == RL) {
2698       Op1 = ISD::getSetCCSwappedOperands(Op1);
2699       std::swap(RL, RR);
2700     }
2701     if (LL == RL && LR == RR) {
2702       bool isInteger = LL.getValueType().isInteger();
2703       ISD::CondCode Result = ISD::getSetCCAndOperation(Op0, Op1, isInteger);
2704       if (Result != ISD::SETCC_INVALID &&
2705           (!LegalOperations ||
2706            (TLI.isCondCodeLegal(Result, LL.getSimpleValueType()) &&
2707             TLI.isOperationLegal(ISD::SETCC,
2708                             getSetCCResultType(N0.getSimpleValueType())))))
2709         return DAG.getSetCC(SDLoc(N), N0.getValueType(),
2710                             LL, LR, Result);
2711     }
2712   }
2713
2714   // Simplify: (and (op x...), (op y...))  -> (op (and x, y))
2715   if (N0.getOpcode() == N1.getOpcode()) {
2716     SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
2717     if (Tmp.getNode()) return Tmp;
2718   }
2719
2720   // fold (and (sign_extend_inreg x, i16 to i32), 1) -> (and x, 1)
2721   // fold (and (sra)) -> (and (srl)) when possible.
2722   if (!VT.isVector() &&
2723       SimplifyDemandedBits(SDValue(N, 0)))
2724     return SDValue(N, 0);
2725
2726   // fold (zext_inreg (extload x)) -> (zextload x)
2727   if (ISD::isEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode())) {
2728     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
2729     EVT MemVT = LN0->getMemoryVT();
2730     // If we zero all the possible extended bits, then we can turn this into
2731     // a zextload if we are running before legalize or the operation is legal.
2732     unsigned BitWidth = N1.getValueType().getScalarType().getSizeInBits();
2733     if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth,
2734                            BitWidth - MemVT.getScalarType().getSizeInBits())) &&
2735         ((!LegalOperations && !LN0->isVolatile()) ||
2736          TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT))) {
2737       SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N0), VT,
2738                                        LN0->getChain(), LN0->getBasePtr(),
2739                                        LN0->getPointerInfo(), MemVT,
2740                                        LN0->isVolatile(), LN0->isNonTemporal(),
2741                                        LN0->getAlignment());
2742       AddToWorkList(N);
2743       CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
2744       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
2745     }
2746   }
2747   // fold (zext_inreg (sextload x)) -> (zextload x) iff load has one use
2748   if (ISD::isSEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
2749       N0.hasOneUse()) {
2750     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
2751     EVT MemVT = LN0->getMemoryVT();
2752     // If we zero all the possible extended bits, then we can turn this into
2753     // a zextload if we are running before legalize or the operation is legal.
2754     unsigned BitWidth = N1.getValueType().getScalarType().getSizeInBits();
2755     if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth,
2756                            BitWidth - MemVT.getScalarType().getSizeInBits())) &&
2757         ((!LegalOperations && !LN0->isVolatile()) ||
2758          TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT))) {
2759       SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N0), VT,
2760                                        LN0->getChain(),
2761                                        LN0->getBasePtr(), LN0->getPointerInfo(),
2762                                        MemVT,
2763                                        LN0->isVolatile(), LN0->isNonTemporal(),
2764                                        LN0->getAlignment());
2765       AddToWorkList(N);
2766       CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
2767       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
2768     }
2769   }
2770
2771   // fold (and (load x), 255) -> (zextload x, i8)
2772   // fold (and (extload x, i16), 255) -> (zextload x, i8)
2773   // fold (and (any_ext (extload x, i16)), 255) -> (zextload x, i8)
2774   if (N1C && (N0.getOpcode() == ISD::LOAD ||
2775               (N0.getOpcode() == ISD::ANY_EXTEND &&
2776                N0.getOperand(0).getOpcode() == ISD::LOAD))) {
2777     bool HasAnyExt = N0.getOpcode() == ISD::ANY_EXTEND;
2778     LoadSDNode *LN0 = HasAnyExt
2779       ? cast<LoadSDNode>(N0.getOperand(0))
2780       : cast<LoadSDNode>(N0);
2781     if (LN0->getExtensionType() != ISD::SEXTLOAD &&
2782         LN0->isUnindexed() && N0.hasOneUse() && SDValue(LN0, 0).hasOneUse()) {
2783       uint32_t ActiveBits = N1C->getAPIntValue().getActiveBits();
2784       if (ActiveBits > 0 && APIntOps::isMask(ActiveBits, N1C->getAPIntValue())){
2785         EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), ActiveBits);
2786         EVT LoadedVT = LN0->getMemoryVT();
2787
2788         if (ExtVT == LoadedVT &&
2789             (!LegalOperations || TLI.isLoadExtLegal(ISD::ZEXTLOAD, ExtVT))) {
2790           EVT LoadResultTy = HasAnyExt ? LN0->getValueType(0) : VT;
2791
2792           SDValue NewLoad =
2793             DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), LoadResultTy,
2794                            LN0->getChain(), LN0->getBasePtr(),
2795                            LN0->getPointerInfo(),
2796                            ExtVT, LN0->isVolatile(), LN0->isNonTemporal(),
2797                            LN0->getAlignment());
2798           AddToWorkList(N);
2799           CombineTo(LN0, NewLoad, NewLoad.getValue(1));
2800           return SDValue(N, 0);   // Return N so it doesn't get rechecked!
2801         }
2802
2803         // Do not change the width of a volatile load.
2804         // Do not generate loads of non-round integer types since these can
2805         // be expensive (and would be wrong if the type is not byte sized).
2806         if (!LN0->isVolatile() && LoadedVT.bitsGT(ExtVT) && ExtVT.isRound() &&
2807             (!LegalOperations || TLI.isLoadExtLegal(ISD::ZEXTLOAD, ExtVT))) {
2808           EVT PtrType = LN0->getOperand(1).getValueType();
2809
2810           unsigned Alignment = LN0->getAlignment();
2811           SDValue NewPtr = LN0->getBasePtr();
2812
2813           // For big endian targets, we need to add an offset to the pointer
2814           // to load the correct bytes.  For little endian systems, we merely
2815           // need to read fewer bytes from the same pointer.
2816           if (TLI.isBigEndian()) {
2817             unsigned LVTStoreBytes = LoadedVT.getStoreSize();
2818             unsigned EVTStoreBytes = ExtVT.getStoreSize();
2819             unsigned PtrOff = LVTStoreBytes - EVTStoreBytes;
2820             NewPtr = DAG.getNode(ISD::ADD, SDLoc(LN0), PtrType,
2821                                  NewPtr, DAG.getConstant(PtrOff, PtrType));
2822             Alignment = MinAlign(Alignment, PtrOff);
2823           }
2824
2825           AddToWorkList(NewPtr.getNode());
2826
2827           EVT LoadResultTy = HasAnyExt ? LN0->getValueType(0) : VT;
2828           SDValue Load =
2829             DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), LoadResultTy,
2830                            LN0->getChain(), NewPtr,
2831                            LN0->getPointerInfo(),
2832                            ExtVT, LN0->isVolatile(), LN0->isNonTemporal(),
2833                            Alignment);
2834           AddToWorkList(N);
2835           CombineTo(LN0, Load, Load.getValue(1));
2836           return SDValue(N, 0);   // Return N so it doesn't get rechecked!
2837         }
2838       }
2839     }
2840   }
2841
2842   if (N0.getOpcode() == ISD::ADD && N1.getOpcode() == ISD::SRL &&
2843       VT.getSizeInBits() <= 64) {
2844     if (ConstantSDNode *ADDI = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
2845       APInt ADDC = ADDI->getAPIntValue();
2846       if (!TLI.isLegalAddImmediate(ADDC.getSExtValue())) {
2847         // Look for (and (add x, c1), (lshr y, c2)). If C1 wasn't a legal
2848         // immediate for an add, but it is legal if its top c2 bits are set,
2849         // transform the ADD so the immediate doesn't need to be materialized
2850         // in a register.
2851         if (ConstantSDNode *SRLI = dyn_cast<ConstantSDNode>(N1.getOperand(1))) {
2852           APInt Mask = APInt::getHighBitsSet(VT.getSizeInBits(),
2853                                              SRLI->getZExtValue());
2854           if (DAG.MaskedValueIsZero(N0.getOperand(1), Mask)) {
2855             ADDC |= Mask;
2856             if (TLI.isLegalAddImmediate(ADDC.getSExtValue())) {
2857               SDValue NewAdd =
2858                 DAG.getNode(ISD::ADD, SDLoc(N0), VT,
2859                             N0.getOperand(0), DAG.getConstant(ADDC, VT));
2860               CombineTo(N0.getNode(), NewAdd);
2861               return SDValue(N, 0); // Return N so it doesn't get rechecked!
2862             }
2863           }
2864         }
2865       }
2866     }
2867   }
2868
2869   // fold (and (or (srl N, 8), (shl N, 8)), 0xffff) -> (srl (bswap N), const)
2870   if (N1C && N1C->getAPIntValue() == 0xffff && N0.getOpcode() == ISD::OR) {
2871     SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0),
2872                                        N0.getOperand(1), false);
2873     if (BSwap.getNode())
2874       return BSwap;
2875   }
2876
2877   return SDValue();
2878 }
2879
2880 /// MatchBSwapHWord - Match (a >> 8) | (a << 8) as (bswap a) >> 16
2881 ///
2882 SDValue DAGCombiner::MatchBSwapHWordLow(SDNode *N, SDValue N0, SDValue N1,
2883                                         bool DemandHighBits) {
2884   if (!LegalOperations)
2885     return SDValue();
2886
2887   EVT VT = N->getValueType(0);
2888   if (VT != MVT::i64 && VT != MVT::i32 && VT != MVT::i16)
2889     return SDValue();
2890   if (!TLI.isOperationLegal(ISD::BSWAP, VT))
2891     return SDValue();
2892
2893   // Recognize (and (shl a, 8), 0xff), (and (srl a, 8), 0xff00)
2894   bool LookPassAnd0 = false;
2895   bool LookPassAnd1 = false;
2896   if (N0.getOpcode() == ISD::AND && N0.getOperand(0).getOpcode() == ISD::SRL)
2897       std::swap(N0, N1);
2898   if (N1.getOpcode() == ISD::AND && N1.getOperand(0).getOpcode() == ISD::SHL)
2899       std::swap(N0, N1);
2900   if (N0.getOpcode() == ISD::AND) {
2901     if (!N0.getNode()->hasOneUse())
2902       return SDValue();
2903     ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
2904     if (!N01C || N01C->getZExtValue() != 0xFF00)
2905       return SDValue();
2906     N0 = N0.getOperand(0);
2907     LookPassAnd0 = true;
2908   }
2909
2910   if (N1.getOpcode() == ISD::AND) {
2911     if (!N1.getNode()->hasOneUse())
2912       return SDValue();
2913     ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
2914     if (!N11C || N11C->getZExtValue() != 0xFF)
2915       return SDValue();
2916     N1 = N1.getOperand(0);
2917     LookPassAnd1 = true;
2918   }
2919
2920   if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
2921     std::swap(N0, N1);
2922   if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
2923     return SDValue();
2924   if (!N0.getNode()->hasOneUse() ||
2925       !N1.getNode()->hasOneUse())
2926     return SDValue();
2927
2928   ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
2929   ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
2930   if (!N01C || !N11C)
2931     return SDValue();
2932   if (N01C->getZExtValue() != 8 || N11C->getZExtValue() != 8)
2933     return SDValue();
2934
2935   // Look for (shl (and a, 0xff), 8), (srl (and a, 0xff00), 8)
2936   SDValue N00 = N0->getOperand(0);
2937   if (!LookPassAnd0 && N00.getOpcode() == ISD::AND) {
2938     if (!N00.getNode()->hasOneUse())
2939       return SDValue();
2940     ConstantSDNode *N001C = dyn_cast<ConstantSDNode>(N00.getOperand(1));
2941     if (!N001C || N001C->getZExtValue() != 0xFF)
2942       return SDValue();
2943     N00 = N00.getOperand(0);
2944     LookPassAnd0 = true;
2945   }
2946
2947   SDValue N10 = N1->getOperand(0);
2948   if (!LookPassAnd1 && N10.getOpcode() == ISD::AND) {
2949     if (!N10.getNode()->hasOneUse())
2950       return SDValue();
2951     ConstantSDNode *N101C = dyn_cast<ConstantSDNode>(N10.getOperand(1));
2952     if (!N101C || N101C->getZExtValue() != 0xFF00)
2953       return SDValue();
2954     N10 = N10.getOperand(0);
2955     LookPassAnd1 = true;
2956   }
2957
2958   if (N00 != N10)
2959     return SDValue();
2960
2961   // Make sure everything beyond the low halfword gets set to zero since the SRL
2962   // 16 will clear the top bits.
2963   unsigned OpSizeInBits = VT.getSizeInBits();
2964   if (DemandHighBits && OpSizeInBits > 16) {
2965     // If the left-shift isn't masked out then the only way this is a bswap is
2966     // if all bits beyond the low 8 are 0. In that case the entire pattern
2967     // reduces to a left shift anyway: leave it for other parts of the combiner.
2968     if (!LookPassAnd0)
2969       return SDValue();
2970
2971     // However, if the right shift isn't masked out then it might be because
2972     // it's not needed. See if we can spot that too.
2973     if (!LookPassAnd1 &&
2974         !DAG.MaskedValueIsZero(
2975             N10, APInt::getHighBitsSet(OpSizeInBits, OpSizeInBits - 16)))
2976       return SDValue();
2977   }
2978
2979   SDValue Res = DAG.getNode(ISD::BSWAP, SDLoc(N), VT, N00);
2980   if (OpSizeInBits > 16)
2981     Res = DAG.getNode(ISD::SRL, SDLoc(N), VT, Res,
2982                       DAG.getConstant(OpSizeInBits-16, getShiftAmountTy(VT)));
2983   return Res;
2984 }
2985
2986 /// isBSwapHWordElement - Return true if the specified node is an element
2987 /// that makes up a 32-bit packed halfword byteswap. i.e.
2988 /// ((x&0xff)<<8)|((x&0xff00)>>8)|((x&0x00ff0000)<<8)|((x&0xff000000)>>8)
2989 static bool isBSwapHWordElement(SDValue N, SmallVectorImpl<SDNode *> &Parts) {
2990   if (!N.getNode()->hasOneUse())
2991     return false;
2992
2993   unsigned Opc = N.getOpcode();
2994   if (Opc != ISD::AND && Opc != ISD::SHL && Opc != ISD::SRL)
2995     return false;
2996
2997   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N.getOperand(1));
2998   if (!N1C)
2999     return false;
3000
3001   unsigned Num;
3002   switch (N1C->getZExtValue()) {
3003   default:
3004     return false;
3005   case 0xFF:       Num = 0; break;
3006   case 0xFF00:     Num = 1; break;
3007   case 0xFF0000:   Num = 2; break;
3008   case 0xFF000000: Num = 3; break;
3009   }
3010
3011   // Look for (x & 0xff) << 8 as well as ((x << 8) & 0xff00).
3012   SDValue N0 = N.getOperand(0);
3013   if (Opc == ISD::AND) {
3014     if (Num == 0 || Num == 2) {
3015       // (x >> 8) & 0xff
3016       // (x >> 8) & 0xff0000
3017       if (N0.getOpcode() != ISD::SRL)
3018         return false;
3019       ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3020       if (!C || C->getZExtValue() != 8)
3021         return false;
3022     } else {
3023       // (x << 8) & 0xff00
3024       // (x << 8) & 0xff000000
3025       if (N0.getOpcode() != ISD::SHL)
3026         return false;
3027       ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3028       if (!C || C->getZExtValue() != 8)
3029         return false;
3030     }
3031   } else if (Opc == ISD::SHL) {
3032     // (x & 0xff) << 8
3033     // (x & 0xff0000) << 8
3034     if (Num != 0 && Num != 2)
3035       return false;
3036     ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3037     if (!C || C->getZExtValue() != 8)
3038       return false;
3039   } else { // Opc == ISD::SRL
3040     // (x & 0xff00) >> 8
3041     // (x & 0xff000000) >> 8
3042     if (Num != 1 && Num != 3)
3043       return false;
3044     ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3045     if (!C || C->getZExtValue() != 8)
3046       return false;
3047   }
3048
3049   if (Parts[Num])
3050     return false;
3051
3052   Parts[Num] = N0.getOperand(0).getNode();
3053   return true;
3054 }
3055
3056 /// MatchBSwapHWord - Match a 32-bit packed halfword bswap. That is
3057 /// ((x&0xff)<<8)|((x&0xff00)>>8)|((x&0x00ff0000)<<8)|((x&0xff000000)>>8)
3058 /// => (rotl (bswap x), 16)
3059 SDValue DAGCombiner::MatchBSwapHWord(SDNode *N, SDValue N0, SDValue N1) {
3060   if (!LegalOperations)
3061     return SDValue();
3062
3063   EVT VT = N->getValueType(0);
3064   if (VT != MVT::i32)
3065     return SDValue();
3066   if (!TLI.isOperationLegal(ISD::BSWAP, VT))
3067     return SDValue();
3068
3069   SmallVector<SDNode*,4> Parts(4, (SDNode*)0);
3070   // Look for either
3071   // (or (or (and), (and)), (or (and), (and)))
3072   // (or (or (or (and), (and)), (and)), (and))
3073   if (N0.getOpcode() != ISD::OR)
3074     return SDValue();
3075   SDValue N00 = N0.getOperand(0);
3076   SDValue N01 = N0.getOperand(1);
3077
3078   if (N1.getOpcode() == ISD::OR &&
3079       N00.getNumOperands() == 2 && N01.getNumOperands() == 2) {
3080     // (or (or (and), (and)), (or (and), (and)))
3081     SDValue N000 = N00.getOperand(0);
3082     if (!isBSwapHWordElement(N000, Parts))
3083       return SDValue();
3084
3085     SDValue N001 = N00.getOperand(1);
3086     if (!isBSwapHWordElement(N001, Parts))
3087       return SDValue();
3088     SDValue N010 = N01.getOperand(0);
3089     if (!isBSwapHWordElement(N010, Parts))
3090       return SDValue();
3091     SDValue N011 = N01.getOperand(1);
3092     if (!isBSwapHWordElement(N011, Parts))
3093       return SDValue();
3094   } else {
3095     // (or (or (or (and), (and)), (and)), (and))
3096     if (!isBSwapHWordElement(N1, Parts))
3097       return SDValue();
3098     if (!isBSwapHWordElement(N01, Parts))
3099       return SDValue();
3100     if (N00.getOpcode() != ISD::OR)
3101       return SDValue();
3102     SDValue N000 = N00.getOperand(0);
3103     if (!isBSwapHWordElement(N000, Parts))
3104       return SDValue();
3105     SDValue N001 = N00.getOperand(1);
3106     if (!isBSwapHWordElement(N001, Parts))
3107       return SDValue();
3108   }
3109
3110   // Make sure the parts are all coming from the same node.
3111   if (Parts[0] != Parts[1] || Parts[0] != Parts[2] || Parts[0] != Parts[3])
3112     return SDValue();
3113
3114   SDValue BSwap = DAG.getNode(ISD::BSWAP, SDLoc(N), VT,
3115                               SDValue(Parts[0],0));
3116
3117   // Result of the bswap should be rotated by 16. If it's not legal, then
3118   // do  (x << 16) | (x >> 16).
3119   SDValue ShAmt = DAG.getConstant(16, getShiftAmountTy(VT));
3120   if (TLI.isOperationLegalOrCustom(ISD::ROTL, VT))
3121     return DAG.getNode(ISD::ROTL, SDLoc(N), VT, BSwap, ShAmt);
3122   if (TLI.isOperationLegalOrCustom(ISD::ROTR, VT))
3123     return DAG.getNode(ISD::ROTR, SDLoc(N), VT, BSwap, ShAmt);
3124   return DAG.getNode(ISD::OR, SDLoc(N), VT,
3125                      DAG.getNode(ISD::SHL, SDLoc(N), VT, BSwap, ShAmt),
3126                      DAG.getNode(ISD::SRL, SDLoc(N), VT, BSwap, ShAmt));
3127 }
3128
3129 SDValue DAGCombiner::visitOR(SDNode *N) {
3130   SDValue N0 = N->getOperand(0);
3131   SDValue N1 = N->getOperand(1);
3132   SDValue LL, LR, RL, RR, CC0, CC1;
3133   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
3134   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
3135   EVT VT = N1.getValueType();
3136
3137   // fold vector ops
3138   if (VT.isVector()) {
3139     SDValue FoldedVOp = SimplifyVBinOp(N);
3140     if (FoldedVOp.getNode()) return FoldedVOp;
3141
3142     // fold (or x, 0) -> x, vector edition
3143     if (ISD::isBuildVectorAllZeros(N0.getNode()))
3144       return N1;
3145     if (ISD::isBuildVectorAllZeros(N1.getNode()))
3146       return N0;
3147
3148     // fold (or x, -1) -> -1, vector edition
3149     if (ISD::isBuildVectorAllOnes(N0.getNode()))
3150       return N0;
3151     if (ISD::isBuildVectorAllOnes(N1.getNode()))
3152       return N1;
3153   }
3154
3155   // fold (or x, undef) -> -1
3156   if (!LegalOperations &&
3157       (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)) {
3158     EVT EltVT = VT.isVector() ? VT.getVectorElementType() : VT;
3159     return DAG.getConstant(APInt::getAllOnesValue(EltVT.getSizeInBits()), VT);
3160   }
3161   // fold (or c1, c2) -> c1|c2
3162   if (N0C && N1C)
3163     return DAG.FoldConstantArithmetic(ISD::OR, VT, N0C, N1C);
3164   // canonicalize constant to RHS
3165   if (N0C && !N1C)
3166     return DAG.getNode(ISD::OR, SDLoc(N), VT, N1, N0);
3167   // fold (or x, 0) -> x
3168   if (N1C && N1C->isNullValue())
3169     return N0;
3170   // fold (or x, -1) -> -1
3171   if (N1C && N1C->isAllOnesValue())
3172     return N1;
3173   // fold (or x, c) -> c iff (x & ~c) == 0
3174   if (N1C && DAG.MaskedValueIsZero(N0, ~N1C->getAPIntValue()))
3175     return N1;
3176
3177   // Recognize halfword bswaps as (bswap + rotl 16) or (bswap + shl 16)
3178   SDValue BSwap = MatchBSwapHWord(N, N0, N1);
3179   if (BSwap.getNode() != 0)
3180     return BSwap;
3181   BSwap = MatchBSwapHWordLow(N, N0, N1);
3182   if (BSwap.getNode() != 0)
3183     return BSwap;
3184
3185   // reassociate or
3186   SDValue ROR = ReassociateOps(ISD::OR, SDLoc(N), N0, N1);
3187   if (ROR.getNode() != 0)
3188     return ROR;
3189   // Canonicalize (or (and X, c1), c2) -> (and (or X, c2), c1|c2)
3190   // iff (c1 & c2) == 0.
3191   if (N1C && N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() &&
3192              isa<ConstantSDNode>(N0.getOperand(1))) {
3193     ConstantSDNode *C1 = cast<ConstantSDNode>(N0.getOperand(1));
3194     if ((C1->getAPIntValue() & N1C->getAPIntValue()) != 0)
3195       return DAG.getNode(ISD::AND, SDLoc(N), VT,
3196                          DAG.getNode(ISD::OR, SDLoc(N0), VT,
3197                                      N0.getOperand(0), N1),
3198                          DAG.FoldConstantArithmetic(ISD::OR, VT, N1C, C1));
3199   }
3200   // fold (or (setcc x), (setcc y)) -> (setcc (or x, y))
3201   if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){
3202     ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get();
3203     ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get();
3204
3205     if (LR == RR && isa<ConstantSDNode>(LR) && Op0 == Op1 &&
3206         LL.getValueType().isInteger()) {
3207       // fold (or (setne X, 0), (setne Y, 0)) -> (setne (or X, Y), 0)
3208       // fold (or (setlt X, 0), (setlt Y, 0)) -> (setne (or X, Y), 0)
3209       if (cast<ConstantSDNode>(LR)->isNullValue() &&
3210           (Op1 == ISD::SETNE || Op1 == ISD::SETLT)) {
3211         SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(LR),
3212                                      LR.getValueType(), LL, RL);
3213         AddToWorkList(ORNode.getNode());
3214         return DAG.getSetCC(SDLoc(N), VT, ORNode, LR, Op1);
3215       }
3216       // fold (or (setne X, -1), (setne Y, -1)) -> (setne (and X, Y), -1)
3217       // fold (or (setgt X, -1), (setgt Y  -1)) -> (setgt (and X, Y), -1)
3218       if (cast<ConstantSDNode>(LR)->isAllOnesValue() &&
3219           (Op1 == ISD::SETNE || Op1 == ISD::SETGT)) {
3220         SDValue ANDNode = DAG.getNode(ISD::AND, SDLoc(LR),
3221                                       LR.getValueType(), LL, RL);
3222         AddToWorkList(ANDNode.getNode());
3223         return DAG.getSetCC(SDLoc(N), VT, ANDNode, LR, Op1);
3224       }
3225     }
3226     // canonicalize equivalent to ll == rl
3227     if (LL == RR && LR == RL) {
3228       Op1 = ISD::getSetCCSwappedOperands(Op1);
3229       std::swap(RL, RR);
3230     }
3231     if (LL == RL && LR == RR) {
3232       bool isInteger = LL.getValueType().isInteger();
3233       ISD::CondCode Result = ISD::getSetCCOrOperation(Op0, Op1, isInteger);
3234       if (Result != ISD::SETCC_INVALID &&
3235           (!LegalOperations ||
3236            (TLI.isCondCodeLegal(Result, LL.getSimpleValueType()) &&
3237             TLI.isOperationLegal(ISD::SETCC,
3238               getSetCCResultType(N0.getValueType())))))
3239         return DAG.getSetCC(SDLoc(N), N0.getValueType(),
3240                             LL, LR, Result);
3241     }
3242   }
3243
3244   // Simplify: (or (op x...), (op y...))  -> (op (or x, y))
3245   if (N0.getOpcode() == N1.getOpcode()) {
3246     SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
3247     if (Tmp.getNode()) return Tmp;
3248   }
3249
3250   // (or (and X, C1), (and Y, C2))  -> (and (or X, Y), C3) if possible.
3251   if (N0.getOpcode() == ISD::AND &&
3252       N1.getOpcode() == ISD::AND &&
3253       N0.getOperand(1).getOpcode() == ISD::Constant &&
3254       N1.getOperand(1).getOpcode() == ISD::Constant &&
3255       // Don't increase # computations.
3256       (N0.getNode()->hasOneUse() || N1.getNode()->hasOneUse())) {
3257     // We can only do this xform if we know that bits from X that are set in C2
3258     // but not in C1 are already zero.  Likewise for Y.
3259     const APInt &LHSMask =
3260       cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
3261     const APInt &RHSMask =
3262       cast<ConstantSDNode>(N1.getOperand(1))->getAPIntValue();
3263
3264     if (DAG.MaskedValueIsZero(N0.getOperand(0), RHSMask&~LHSMask) &&
3265         DAG.MaskedValueIsZero(N1.getOperand(0), LHSMask&~RHSMask)) {
3266       SDValue X = DAG.getNode(ISD::OR, SDLoc(N0), VT,
3267                               N0.getOperand(0), N1.getOperand(0));
3268       return DAG.getNode(ISD::AND, SDLoc(N), VT, X,
3269                          DAG.getConstant(LHSMask | RHSMask, VT));
3270     }
3271   }
3272
3273   // See if this is some rotate idiom.
3274   if (SDNode *Rot = MatchRotate(N0, N1, SDLoc(N)))
3275     return SDValue(Rot, 0);
3276
3277   // Simplify the operands using demanded-bits information.
3278   if (!VT.isVector() &&
3279       SimplifyDemandedBits(SDValue(N, 0)))
3280     return SDValue(N, 0);
3281
3282   return SDValue();
3283 }
3284
3285 /// MatchRotateHalf - Match "(X shl/srl V1) & V2" where V2 may not be present.
3286 static bool MatchRotateHalf(SDValue Op, SDValue &Shift, SDValue &Mask) {
3287   if (Op.getOpcode() == ISD::AND) {
3288     if (isa<ConstantSDNode>(Op.getOperand(1))) {
3289       Mask = Op.getOperand(1);
3290       Op = Op.getOperand(0);
3291     } else {
3292       return false;
3293     }
3294   }
3295
3296   if (Op.getOpcode() == ISD::SRL || Op.getOpcode() == ISD::SHL) {
3297     Shift = Op;
3298     return true;
3299   }
3300
3301   return false;
3302 }
3303
3304 // MatchRotate - Handle an 'or' of two operands.  If this is one of the many
3305 // idioms for rotate, and if the target supports rotation instructions, generate
3306 // a rot[lr].
3307 SDNode *DAGCombiner::MatchRotate(SDValue LHS, SDValue RHS, SDLoc DL) {
3308   // Must be a legal type.  Expanded 'n promoted things won't work with rotates.
3309   EVT VT = LHS.getValueType();
3310   if (!TLI.isTypeLegal(VT)) return 0;
3311
3312   // The target must have at least one rotate flavor.
3313   bool HasROTL = TLI.isOperationLegalOrCustom(ISD::ROTL, VT);
3314   bool HasROTR = TLI.isOperationLegalOrCustom(ISD::ROTR, VT);
3315   if (!HasROTL && !HasROTR) return 0;
3316
3317   // Match "(X shl/srl V1) & V2" where V2 may not be present.
3318   SDValue LHSShift;   // The shift.
3319   SDValue LHSMask;    // AND value if any.
3320   if (!MatchRotateHalf(LHS, LHSShift, LHSMask))
3321     return 0; // Not part of a rotate.
3322
3323   SDValue RHSShift;   // The shift.
3324   SDValue RHSMask;    // AND value if any.
3325   if (!MatchRotateHalf(RHS, RHSShift, RHSMask))
3326     return 0; // Not part of a rotate.
3327
3328   if (LHSShift.getOperand(0) != RHSShift.getOperand(0))
3329     return 0;   // Not shifting the same value.
3330
3331   if (LHSShift.getOpcode() == RHSShift.getOpcode())
3332     return 0;   // Shifts must disagree.
3333
3334   // Canonicalize shl to left side in a shl/srl pair.
3335   if (RHSShift.getOpcode() == ISD::SHL) {
3336     std::swap(LHS, RHS);
3337     std::swap(LHSShift, RHSShift);
3338     std::swap(LHSMask , RHSMask );
3339   }
3340
3341   unsigned OpSizeInBits = VT.getSizeInBits();
3342   SDValue LHSShiftArg = LHSShift.getOperand(0);
3343   SDValue LHSShiftAmt = LHSShift.getOperand(1);
3344   SDValue RHSShiftArg = RHSShift.getOperand(0);
3345   SDValue RHSShiftAmt = RHSShift.getOperand(1);
3346
3347   // fold (or (shl x, C1), (srl x, C2)) -> (rotl x, C1)
3348   // fold (or (shl x, C1), (srl x, C2)) -> (rotr x, C2)
3349   if (LHSShiftAmt.getOpcode() == ISD::Constant &&
3350       RHSShiftAmt.getOpcode() == ISD::Constant) {
3351     uint64_t LShVal = cast<ConstantSDNode>(LHSShiftAmt)->getZExtValue();
3352     uint64_t RShVal = cast<ConstantSDNode>(RHSShiftAmt)->getZExtValue();
3353     if ((LShVal + RShVal) != OpSizeInBits)
3354       return 0;
3355
3356     SDValue Rot = DAG.getNode(HasROTL ? ISD::ROTL : ISD::ROTR, DL, VT,
3357                               LHSShiftArg, HasROTL ? LHSShiftAmt : RHSShiftAmt);
3358
3359     // If there is an AND of either shifted operand, apply it to the result.
3360     if (LHSMask.getNode() || RHSMask.getNode()) {
3361       APInt Mask = APInt::getAllOnesValue(OpSizeInBits);
3362
3363       if (LHSMask.getNode()) {
3364         APInt RHSBits = APInt::getLowBitsSet(OpSizeInBits, LShVal);
3365         Mask &= cast<ConstantSDNode>(LHSMask)->getAPIntValue() | RHSBits;
3366       }
3367       if (RHSMask.getNode()) {
3368         APInt LHSBits = APInt::getHighBitsSet(OpSizeInBits, RShVal);
3369         Mask &= cast<ConstantSDNode>(RHSMask)->getAPIntValue() | LHSBits;
3370       }
3371
3372       Rot = DAG.getNode(ISD::AND, DL, VT, Rot, DAG.getConstant(Mask, VT));
3373     }
3374
3375     return Rot.getNode();
3376   }
3377
3378   // If there is a mask here, and we have a variable shift, we can't be sure
3379   // that we're masking out the right stuff.
3380   if (LHSMask.getNode() || RHSMask.getNode())
3381     return 0;
3382
3383   // If the shift amount is sign/zext/any-extended just peel it off.
3384   SDValue LExtOp0 = LHSShiftAmt;
3385   SDValue RExtOp0 = RHSShiftAmt;
3386   if ((LHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND ||
3387        LHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND ||
3388        LHSShiftAmt.getOpcode() == ISD::ANY_EXTEND ||
3389        LHSShiftAmt.getOpcode() == ISD::TRUNCATE) &&
3390       (RHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND ||
3391        RHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND ||
3392        RHSShiftAmt.getOpcode() == ISD::ANY_EXTEND ||
3393        RHSShiftAmt.getOpcode() == ISD::TRUNCATE)) {
3394     LExtOp0 = LHSShiftAmt.getOperand(0);
3395     RExtOp0 = RHSShiftAmt.getOperand(0);
3396   }
3397
3398   if (RExtOp0.getOpcode() == ISD::SUB && RExtOp0.getOperand(1) == LExtOp0) {
3399     // fold (or (shl x, (*ext y)), (srl x, (*ext (sub 32, y)))) ->
3400     //   (rotl x, y)
3401     // fold (or (shl x, (*ext y)), (srl x, (*ext (sub 32, y)))) ->
3402     //   (rotr x, (sub 32, y))
3403     if (ConstantSDNode *SUBC =
3404             dyn_cast<ConstantSDNode>(RExtOp0.getOperand(0))) {
3405       if (SUBC->getAPIntValue() == OpSizeInBits) {
3406         return DAG.getNode(HasROTL ? ISD::ROTL : ISD::ROTR, DL, VT, LHSShiftArg,
3407                            HasROTL ? LHSShiftAmt : RHSShiftAmt).getNode();
3408       } else if (LHSShiftArg.getOpcode() == ISD::ZERO_EXTEND ||
3409                  LHSShiftArg.getOpcode() == ISD::ANY_EXTEND) {
3410         // fold (or (shl (*ext x), (*ext y)),
3411         //          (srl (*ext x), (*ext (sub 32, y)))) ->
3412         //   (*ext (rotl x, y))
3413         // fold (or (shl (*ext x), (*ext y)),
3414         //          (srl (*ext x), (*ext (sub 32, y)))) ->
3415         //   (*ext (rotr x, (sub 32, y)))
3416         SDValue LArgExtOp0 = LHSShiftArg.getOperand(0);
3417         EVT LArgVT = LArgExtOp0.getValueType();
3418         if (LArgVT.getSizeInBits() == SUBC->getAPIntValue()) {
3419           SDValue V =
3420               DAG.getNode(HasROTL ? ISD::ROTL : ISD::ROTR, DL, LArgVT,
3421                           LArgExtOp0, HasROTL ? LHSShiftAmt : RHSShiftAmt);
3422           return DAG.getNode(LHSShiftArg.getOpcode(), DL, VT, V).getNode();
3423         }
3424       }
3425     }
3426   } else if (LExtOp0.getOpcode() == ISD::SUB &&
3427              RExtOp0 == LExtOp0.getOperand(1)) {
3428     // fold (or (shl x, (*ext (sub 32, y))), (srl x, (*ext y))) ->
3429     //   (rotr x, y)
3430     // fold (or (shl x, (*ext (sub 32, y))), (srl x, (*ext y))) ->
3431     //   (rotl x, (sub 32, y))
3432     if (ConstantSDNode *SUBC =
3433             dyn_cast<ConstantSDNode>(LExtOp0.getOperand(0))) {
3434       if (SUBC->getAPIntValue() == OpSizeInBits) {
3435         return DAG.getNode(HasROTR ? ISD::ROTR : ISD::ROTL, DL, VT, LHSShiftArg,
3436                            HasROTR ? RHSShiftAmt : LHSShiftAmt).getNode();
3437       } else if (RHSShiftArg.getOpcode() == ISD::ZERO_EXTEND ||
3438                  RHSShiftArg.getOpcode() == ISD::ANY_EXTEND) {
3439         // fold (or (shl (*ext x), (*ext (sub 32, y))),
3440         //          (srl (*ext x), (*ext y))) ->
3441         //   (*ext (rotl x, y))
3442         // fold (or (shl (*ext x), (*ext (sub 32, y))),
3443         //          (srl (*ext x), (*ext y))) ->
3444         //   (*ext (rotr x, (sub 32, y)))
3445         SDValue RArgExtOp0 = RHSShiftArg.getOperand(0);
3446         EVT RArgVT = RArgExtOp0.getValueType();
3447         if (RArgVT.getSizeInBits() == SUBC->getAPIntValue()) {
3448           SDValue V =
3449               DAG.getNode(HasROTR ? ISD::ROTR : ISD::ROTL, DL, RArgVT,
3450                           RArgExtOp0, HasROTR ? RHSShiftAmt : LHSShiftAmt);
3451           return DAG.getNode(RHSShiftArg.getOpcode(), DL, VT, V).getNode();
3452         }
3453       }
3454     }
3455   }
3456
3457   return 0;
3458 }
3459
3460 SDValue DAGCombiner::visitXOR(SDNode *N) {
3461   SDValue N0 = N->getOperand(0);
3462   SDValue N1 = N->getOperand(1);
3463   SDValue LHS, RHS, CC;
3464   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
3465   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
3466   EVT VT = N0.getValueType();
3467
3468   // fold vector ops
3469   if (VT.isVector()) {
3470     SDValue FoldedVOp = SimplifyVBinOp(N);
3471     if (FoldedVOp.getNode()) return FoldedVOp;
3472
3473     // fold (xor x, 0) -> x, vector edition
3474     if (ISD::isBuildVectorAllZeros(N0.getNode()))
3475       return N1;
3476     if (ISD::isBuildVectorAllZeros(N1.getNode()))
3477       return N0;
3478   }
3479
3480   // fold (xor undef, undef) -> 0. This is a common idiom (misuse).
3481   if (N0.getOpcode() == ISD::UNDEF && N1.getOpcode() == ISD::UNDEF)
3482     return DAG.getConstant(0, VT);
3483   // fold (xor x, undef) -> undef
3484   if (N0.getOpcode() == ISD::UNDEF)
3485     return N0;
3486   if (N1.getOpcode() == ISD::UNDEF)
3487     return N1;
3488   // fold (xor c1, c2) -> c1^c2
3489   if (N0C && N1C)
3490     return DAG.FoldConstantArithmetic(ISD::XOR, VT, N0C, N1C);
3491   // canonicalize constant to RHS
3492   if (N0C && !N1C)
3493     return DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0);
3494   // fold (xor x, 0) -> x
3495   if (N1C && N1C->isNullValue())
3496     return N0;
3497   // reassociate xor
3498   SDValue RXOR = ReassociateOps(ISD::XOR, SDLoc(N), N0, N1);
3499   if (RXOR.getNode() != 0)
3500     return RXOR;
3501
3502   // fold !(x cc y) -> (x !cc y)
3503   if (N1C && N1C->getAPIntValue() == 1 && isSetCCEquivalent(N0, LHS, RHS, CC)) {
3504     bool isInt = LHS.getValueType().isInteger();
3505     ISD::CondCode NotCC = ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(),
3506                                                isInt);
3507
3508     if (!LegalOperations ||
3509         TLI.isCondCodeLegal(NotCC, LHS.getSimpleValueType())) {
3510       switch (N0.getOpcode()) {
3511       default:
3512         llvm_unreachable("Unhandled SetCC Equivalent!");
3513       case ISD::SETCC:
3514         return DAG.getSetCC(SDLoc(N), VT, LHS, RHS, NotCC);
3515       case ISD::SELECT_CC:
3516         return DAG.getSelectCC(SDLoc(N), LHS, RHS, N0.getOperand(2),
3517                                N0.getOperand(3), NotCC);
3518       }
3519     }
3520   }
3521
3522   // fold (not (zext (setcc x, y))) -> (zext (not (setcc x, y)))
3523   if (N1C && N1C->getAPIntValue() == 1 && N0.getOpcode() == ISD::ZERO_EXTEND &&
3524       N0.getNode()->hasOneUse() &&
3525       isSetCCEquivalent(N0.getOperand(0), LHS, RHS, CC)){
3526     SDValue V = N0.getOperand(0);
3527     V = DAG.getNode(ISD::XOR, SDLoc(N0), V.getValueType(), V,
3528                     DAG.getConstant(1, V.getValueType()));
3529     AddToWorkList(V.getNode());
3530     return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, V);
3531   }
3532
3533   // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are setcc
3534   if (N1C && N1C->getAPIntValue() == 1 && VT == MVT::i1 &&
3535       (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
3536     SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
3537     if (isOneUseSetCC(RHS) || isOneUseSetCC(LHS)) {
3538       unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
3539       LHS = DAG.getNode(ISD::XOR, SDLoc(LHS), VT, LHS, N1); // LHS = ~LHS
3540       RHS = DAG.getNode(ISD::XOR, SDLoc(RHS), VT, RHS, N1); // RHS = ~RHS
3541       AddToWorkList(LHS.getNode()); AddToWorkList(RHS.getNode());
3542       return DAG.getNode(NewOpcode, SDLoc(N), VT, LHS, RHS);
3543     }
3544   }
3545   // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are constants
3546   if (N1C && N1C->isAllOnesValue() &&
3547       (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
3548     SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
3549     if (isa<ConstantSDNode>(RHS) || isa<ConstantSDNode>(LHS)) {
3550       unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
3551       LHS = DAG.getNode(ISD::XOR, SDLoc(LHS), VT, LHS, N1); // LHS = ~LHS
3552       RHS = DAG.getNode(ISD::XOR, SDLoc(RHS), VT, RHS, N1); // RHS = ~RHS
3553       AddToWorkList(LHS.getNode()); AddToWorkList(RHS.getNode());
3554       return DAG.getNode(NewOpcode, SDLoc(N), VT, LHS, RHS);
3555     }
3556   }
3557   // fold (xor (and x, y), y) -> (and (not x), y)
3558   if (N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() &&
3559       N0->getOperand(1) == N1) {
3560     SDValue X = N0->getOperand(0);
3561     SDValue NotX = DAG.getNOT(SDLoc(X), X, VT);
3562     AddToWorkList(NotX.getNode());
3563     return DAG.getNode(ISD::AND, SDLoc(N), VT, NotX, N1);
3564   }
3565   // fold (xor (xor x, c1), c2) -> (xor x, (xor c1, c2))
3566   if (N1C && N0.getOpcode() == ISD::XOR) {
3567     ConstantSDNode *N00C = dyn_cast<ConstantSDNode>(N0.getOperand(0));
3568     ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3569     if (N00C)
3570       return DAG.getNode(ISD::XOR, SDLoc(N), VT, N0.getOperand(1),
3571                          DAG.getConstant(N1C->getAPIntValue() ^
3572                                          N00C->getAPIntValue(), VT));
3573     if (N01C)
3574       return DAG.getNode(ISD::XOR, SDLoc(N), VT, N0.getOperand(0),
3575                          DAG.getConstant(N1C->getAPIntValue() ^
3576                                          N01C->getAPIntValue(), VT));
3577   }
3578   // fold (xor x, x) -> 0
3579   if (N0 == N1)
3580     return tryFoldToZero(SDLoc(N), TLI, VT, DAG, LegalOperations, LegalTypes);
3581
3582   // Simplify: xor (op x...), (op y...)  -> (op (xor x, y))
3583   if (N0.getOpcode() == N1.getOpcode()) {
3584     SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
3585     if (Tmp.getNode()) return Tmp;
3586   }
3587
3588   // Simplify the expression using non-local knowledge.
3589   if (!VT.isVector() &&
3590       SimplifyDemandedBits(SDValue(N, 0)))
3591     return SDValue(N, 0);
3592
3593   return SDValue();
3594 }
3595
3596 /// visitShiftByConstant - Handle transforms common to the three shifts, when
3597 /// the shift amount is a constant.
3598 SDValue DAGCombiner::visitShiftByConstant(SDNode *N, unsigned Amt) {
3599   SDNode *LHS = N->getOperand(0).getNode();
3600   if (!LHS->hasOneUse()) return SDValue();
3601
3602   // We want to pull some binops through shifts, so that we have (and (shift))
3603   // instead of (shift (and)), likewise for add, or, xor, etc.  This sort of
3604   // thing happens with address calculations, so it's important to canonicalize
3605   // it.
3606   bool HighBitSet = false;  // Can we transform this if the high bit is set?
3607
3608   switch (LHS->getOpcode()) {
3609   default: return SDValue();
3610   case ISD::OR:
3611   case ISD::XOR:
3612     HighBitSet = false; // We can only transform sra if the high bit is clear.
3613     break;
3614   case ISD::AND:
3615     HighBitSet = true;  // We can only transform sra if the high bit is set.
3616     break;
3617   case ISD::ADD:
3618     if (N->getOpcode() != ISD::SHL)
3619       return SDValue(); // only shl(add) not sr[al](add).
3620     HighBitSet = false; // We can only transform sra if the high bit is clear.
3621     break;
3622   }
3623
3624   // We require the RHS of the binop to be a constant as well.
3625   ConstantSDNode *BinOpCst = dyn_cast<ConstantSDNode>(LHS->getOperand(1));
3626   if (!BinOpCst) return SDValue();
3627
3628   // FIXME: disable this unless the input to the binop is a shift by a constant.
3629   // If it is not a shift, it pessimizes some common cases like:
3630   //
3631   //    void foo(int *X, int i) { X[i & 1235] = 1; }
3632   //    int bar(int *X, int i) { return X[i & 255]; }
3633   SDNode *BinOpLHSVal = LHS->getOperand(0).getNode();
3634   if ((BinOpLHSVal->getOpcode() != ISD::SHL &&
3635        BinOpLHSVal->getOpcode() != ISD::SRA &&
3636        BinOpLHSVal->getOpcode() != ISD::SRL) ||
3637       !isa<ConstantSDNode>(BinOpLHSVal->getOperand(1)))
3638     return SDValue();
3639
3640   EVT VT = N->getValueType(0);
3641
3642   // If this is a signed shift right, and the high bit is modified by the
3643   // logical operation, do not perform the transformation. The highBitSet
3644   // boolean indicates the value of the high bit of the constant which would
3645   // cause it to be modified for this operation.
3646   if (N->getOpcode() == ISD::SRA) {
3647     bool BinOpRHSSignSet = BinOpCst->getAPIntValue().isNegative();
3648     if (BinOpRHSSignSet != HighBitSet)
3649       return SDValue();
3650   }
3651
3652   // Fold the constants, shifting the binop RHS by the shift amount.
3653   SDValue NewRHS = DAG.getNode(N->getOpcode(), SDLoc(LHS->getOperand(1)),
3654                                N->getValueType(0),
3655                                LHS->getOperand(1), N->getOperand(1));
3656
3657   // Create the new shift.
3658   SDValue NewShift = DAG.getNode(N->getOpcode(),
3659                                  SDLoc(LHS->getOperand(0)),
3660                                  VT, LHS->getOperand(0), N->getOperand(1));
3661
3662   // Create the new binop.
3663   return DAG.getNode(LHS->getOpcode(), SDLoc(N), VT, NewShift, NewRHS);
3664 }
3665
3666 SDValue DAGCombiner::visitSHL(SDNode *N) {
3667   SDValue N0 = N->getOperand(0);
3668   SDValue N1 = N->getOperand(1);
3669   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
3670   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
3671   EVT VT = N0.getValueType();
3672   unsigned OpSizeInBits = VT.getScalarType().getSizeInBits();
3673
3674   // fold (shl c1, c2) -> c1<<c2
3675   if (N0C && N1C)
3676     return DAG.FoldConstantArithmetic(ISD::SHL, VT, N0C, N1C);
3677   // fold (shl 0, x) -> 0
3678   if (N0C && N0C->isNullValue())
3679     return N0;
3680   // fold (shl x, c >= size(x)) -> undef
3681   if (N1C && N1C->getZExtValue() >= OpSizeInBits)
3682     return DAG.getUNDEF(VT);
3683   // fold (shl x, 0) -> x
3684   if (N1C && N1C->isNullValue())
3685     return N0;
3686   // fold (shl undef, x) -> 0
3687   if (N0.getOpcode() == ISD::UNDEF)
3688     return DAG.getConstant(0, VT);
3689   // if (shl x, c) is known to be zero, return 0
3690   if (DAG.MaskedValueIsZero(SDValue(N, 0),
3691                             APInt::getAllOnesValue(OpSizeInBits)))
3692     return DAG.getConstant(0, VT);
3693   // fold (shl x, (trunc (and y, c))) -> (shl x, (and (trunc y), (trunc c))).
3694   if (N1.getOpcode() == ISD::TRUNCATE &&
3695       N1.getOperand(0).getOpcode() == ISD::AND &&
3696       N1.hasOneUse() && N1.getOperand(0).hasOneUse()) {
3697     SDValue N101 = N1.getOperand(0).getOperand(1);
3698     if (ConstantSDNode *N101C = dyn_cast<ConstantSDNode>(N101)) {
3699       EVT TruncVT = N1.getValueType();
3700       SDValue N100 = N1.getOperand(0).getOperand(0);
3701       APInt TruncC = N101C->getAPIntValue();
3702       TruncC = TruncC.trunc(TruncVT.getSizeInBits());
3703       return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0,
3704                          DAG.getNode(ISD::AND, SDLoc(N), TruncVT,
3705                                      DAG.getNode(ISD::TRUNCATE,
3706                                                  SDLoc(N),
3707                                                  TruncVT, N100),
3708                                      DAG.getConstant(TruncC, TruncVT)));
3709     }
3710   }
3711
3712   if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
3713     return SDValue(N, 0);
3714
3715   // fold (shl (shl x, c1), c2) -> 0 or (shl x, (add c1, c2))
3716   if (N1C && N0.getOpcode() == ISD::SHL &&
3717       N0.getOperand(1).getOpcode() == ISD::Constant) {
3718     uint64_t c1 = cast<ConstantSDNode>(N0.getOperand(1))->getZExtValue();
3719     uint64_t c2 = N1C->getZExtValue();
3720     if (c1 + c2 >= OpSizeInBits)
3721       return DAG.getConstant(0, VT);
3722     return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0.getOperand(0),
3723                        DAG.getConstant(c1 + c2, N1.getValueType()));
3724   }
3725
3726   // fold (shl (ext (shl x, c1)), c2) -> (ext (shl x, (add c1, c2)))
3727   // For this to be valid, the second form must not preserve any of the bits
3728   // that are shifted out by the inner shift in the first form.  This means
3729   // the outer shift size must be >= the number of bits added by the ext.
3730   // As a corollary, we don't care what kind of ext it is.
3731   if (N1C && (N0.getOpcode() == ISD::ZERO_EXTEND ||
3732               N0.getOpcode() == ISD::ANY_EXTEND ||
3733               N0.getOpcode() == ISD::SIGN_EXTEND) &&
3734       N0.getOperand(0).getOpcode() == ISD::SHL &&
3735       isa<ConstantSDNode>(N0.getOperand(0)->getOperand(1))) {
3736     uint64_t c1 =
3737       cast<ConstantSDNode>(N0.getOperand(0)->getOperand(1))->getZExtValue();
3738     uint64_t c2 = N1C->getZExtValue();
3739     EVT InnerShiftVT = N0.getOperand(0).getValueType();
3740     uint64_t InnerShiftSize = InnerShiftVT.getScalarType().getSizeInBits();
3741     if (c2 >= OpSizeInBits - InnerShiftSize) {
3742       if (c1 + c2 >= OpSizeInBits)
3743         return DAG.getConstant(0, VT);
3744       return DAG.getNode(ISD::SHL, SDLoc(N0), VT,
3745                          DAG.getNode(N0.getOpcode(), SDLoc(N0), VT,
3746                                      N0.getOperand(0)->getOperand(0)),
3747                          DAG.getConstant(c1 + c2, N1.getValueType()));
3748     }
3749   }
3750
3751   // fold (shl (zext (srl x, C)), C) -> (zext (shl (srl x, C), C))
3752   // Only fold this if the inner zext has no other uses to avoid increasing
3753   // the total number of instructions.
3754   if (N1C && N0.getOpcode() == ISD::ZERO_EXTEND && N0.hasOneUse() &&
3755       N0.getOperand(0).getOpcode() == ISD::SRL &&
3756       isa<ConstantSDNode>(N0.getOperand(0)->getOperand(1))) {
3757     uint64_t c1 =
3758       cast<ConstantSDNode>(N0.getOperand(0)->getOperand(1))->getZExtValue();
3759     if (c1 < VT.getSizeInBits()) {
3760       uint64_t c2 = N1C->getZExtValue();
3761       if (c1 == c2) {
3762         SDValue NewOp0 = N0.getOperand(0);
3763         EVT CountVT = NewOp0.getOperand(1).getValueType();
3764         SDValue NewSHL = DAG.getNode(ISD::SHL, SDLoc(N), NewOp0.getValueType(),
3765                                      NewOp0, DAG.getConstant(c2, CountVT));
3766         return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N0), VT, NewSHL);
3767       }
3768     }
3769   }
3770
3771   // fold (shl (srl x, c1), c2) -> (and (shl x, (sub c2, c1), MASK) or
3772   //                               (and (srl x, (sub c1, c2), MASK)
3773   // Only fold this if the inner shift has no other uses -- if it does, folding
3774   // this will increase the total number of instructions.
3775   if (N1C && N0.getOpcode() == ISD::SRL && N0.hasOneUse() &&
3776       N0.getOperand(1).getOpcode() == ISD::Constant) {
3777     uint64_t c1 = cast<ConstantSDNode>(N0.getOperand(1))->getZExtValue();
3778     if (c1 < VT.getSizeInBits()) {
3779       uint64_t c2 = N1C->getZExtValue();
3780       APInt Mask = APInt::getHighBitsSet(VT.getSizeInBits(),
3781                                          VT.getSizeInBits() - c1);
3782       SDValue Shift;
3783       if (c2 > c1) {
3784         Mask = Mask.shl(c2-c1);
3785         Shift = DAG.getNode(ISD::SHL, SDLoc(N), VT, N0.getOperand(0),
3786                             DAG.getConstant(c2-c1, N1.getValueType()));
3787       } else {
3788         Mask = Mask.lshr(c1-c2);
3789         Shift = DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0),
3790                             DAG.getConstant(c1-c2, N1.getValueType()));
3791       }
3792       return DAG.getNode(ISD::AND, SDLoc(N0), VT, Shift,
3793                          DAG.getConstant(Mask, VT));
3794     }
3795   }
3796   // fold (shl (sra x, c1), c1) -> (and x, (shl -1, c1))
3797   if (N1C && N0.getOpcode() == ISD::SRA && N1 == N0.getOperand(1)) {
3798     SDValue HiBitsMask =
3799       DAG.getConstant(APInt::getHighBitsSet(VT.getSizeInBits(),
3800                                             VT.getSizeInBits() -
3801                                               N1C->getZExtValue()),
3802                       VT);
3803     return DAG.getNode(ISD::AND, SDLoc(N), VT, N0.getOperand(0),
3804                        HiBitsMask);
3805   }
3806
3807   if (N1C) {
3808     SDValue NewSHL = visitShiftByConstant(N, N1C->getZExtValue());
3809     if (NewSHL.getNode())
3810       return NewSHL;
3811   }
3812
3813   return SDValue();
3814 }
3815
3816 SDValue DAGCombiner::visitSRA(SDNode *N) {
3817   SDValue N0 = N->getOperand(0);
3818   SDValue N1 = N->getOperand(1);
3819   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
3820   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
3821   EVT VT = N0.getValueType();
3822   unsigned OpSizeInBits = VT.getScalarType().getSizeInBits();
3823
3824   // fold (sra c1, c2) -> (sra c1, c2)
3825   if (N0C && N1C)
3826     return DAG.FoldConstantArithmetic(ISD::SRA, VT, N0C, N1C);
3827   // fold (sra 0, x) -> 0
3828   if (N0C && N0C->isNullValue())
3829     return N0;
3830   // fold (sra -1, x) -> -1
3831   if (N0C && N0C->isAllOnesValue())
3832     return N0;
3833   // fold (sra x, (setge c, size(x))) -> undef
3834   if (N1C && N1C->getZExtValue() >= OpSizeInBits)
3835     return DAG.getUNDEF(VT);
3836   // fold (sra x, 0) -> x
3837   if (N1C && N1C->isNullValue())
3838     return N0;
3839   // fold (sra (shl x, c1), c1) -> sext_inreg for some c1 and target supports
3840   // sext_inreg.
3841   if (N1C && N0.getOpcode() == ISD::SHL && N1 == N0.getOperand(1)) {
3842     unsigned LowBits = OpSizeInBits - (unsigned)N1C->getZExtValue();
3843     EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), LowBits);
3844     if (VT.isVector())
3845       ExtVT = EVT::getVectorVT(*DAG.getContext(),
3846                                ExtVT, VT.getVectorNumElements());
3847     if ((!LegalOperations ||
3848          TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, ExtVT)))
3849       return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
3850                          N0.getOperand(0), DAG.getValueType(ExtVT));
3851   }
3852
3853   // fold (sra (sra x, c1), c2) -> (sra x, (add c1, c2))
3854   if (N1C && N0.getOpcode() == ISD::SRA) {
3855     if (ConstantSDNode *C1 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
3856       unsigned Sum = N1C->getZExtValue() + C1->getZExtValue();
3857       if (Sum >= OpSizeInBits) Sum = OpSizeInBits-1;
3858       return DAG.getNode(ISD::SRA, SDLoc(N), VT, N0.getOperand(0),
3859                          DAG.getConstant(Sum, N1C->getValueType(0)));
3860     }
3861   }
3862
3863   // fold (sra (shl X, m), (sub result_size, n))
3864   // -> (sign_extend (trunc (shl X, (sub (sub result_size, n), m)))) for
3865   // result_size - n != m.
3866   // If truncate is free for the target sext(shl) is likely to result in better
3867   // code.
3868   if (N0.getOpcode() == ISD::SHL) {
3869     // Get the two constanst of the shifts, CN0 = m, CN = n.
3870     const ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3871     if (N01C && N1C) {
3872       // Determine what the truncate's result bitsize and type would be.
3873       EVT TruncVT =
3874         EVT::getIntegerVT(*DAG.getContext(),
3875                           OpSizeInBits - N1C->getZExtValue());
3876       // Determine the residual right-shift amount.
3877       signed ShiftAmt = N1C->getZExtValue() - N01C->getZExtValue();
3878
3879       // If the shift is not a no-op (in which case this should be just a sign
3880       // extend already), the truncated to type is legal, sign_extend is legal
3881       // on that type, and the truncate to that type is both legal and free,
3882       // perform the transform.
3883       if ((ShiftAmt > 0) &&
3884           TLI.isOperationLegalOrCustom(ISD::SIGN_EXTEND, TruncVT) &&
3885           TLI.isOperationLegalOrCustom(ISD::TRUNCATE, VT) &&
3886           TLI.isTruncateFree(VT, TruncVT)) {
3887
3888           SDValue Amt = DAG.getConstant(ShiftAmt,
3889               getShiftAmountTy(N0.getOperand(0).getValueType()));
3890           SDValue Shift = DAG.getNode(ISD::SRL, SDLoc(N0), VT,
3891                                       N0.getOperand(0), Amt);
3892           SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0), TruncVT,
3893                                       Shift);
3894           return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N),
3895                              N->getValueType(0), Trunc);
3896       }
3897     }
3898   }
3899
3900   // fold (sra x, (trunc (and y, c))) -> (sra x, (and (trunc y), (trunc c))).
3901   if (N1.getOpcode() == ISD::TRUNCATE &&
3902       N1.getOperand(0).getOpcode() == ISD::AND &&
3903       N1.hasOneUse() && N1.getOperand(0).hasOneUse()) {
3904     SDValue N101 = N1.getOperand(0).getOperand(1);
3905     if (ConstantSDNode *N101C = dyn_cast<ConstantSDNode>(N101)) {
3906       EVT TruncVT = N1.getValueType();
3907       SDValue N100 = N1.getOperand(0).getOperand(0);
3908       APInt TruncC = N101C->getAPIntValue();
3909       TruncC = TruncC.trunc(TruncVT.getScalarType().getSizeInBits());
3910       return DAG.getNode(ISD::SRA, SDLoc(N), VT, N0,
3911                          DAG.getNode(ISD::AND, SDLoc(N),
3912                                      TruncVT,
3913                                      DAG.getNode(ISD::TRUNCATE,
3914                                                  SDLoc(N),
3915                                                  TruncVT, N100),
3916                                      DAG.getConstant(TruncC, TruncVT)));
3917     }
3918   }
3919
3920   // fold (sra (trunc (sr x, c1)), c2) -> (trunc (sra x, c1+c2))
3921   //      if c1 is equal to the number of bits the trunc removes
3922   if (N0.getOpcode() == ISD::TRUNCATE &&
3923       (N0.getOperand(0).getOpcode() == ISD::SRL ||
3924        N0.getOperand(0).getOpcode() == ISD::SRA) &&
3925       N0.getOperand(0).hasOneUse() &&
3926       N0.getOperand(0).getOperand(1).hasOneUse() &&
3927       N1C && isa<ConstantSDNode>(N0.getOperand(0).getOperand(1))) {
3928     EVT LargeVT = N0.getOperand(0).getValueType();
3929     ConstantSDNode *LargeShiftAmt =
3930       cast<ConstantSDNode>(N0.getOperand(0).getOperand(1));
3931
3932     if (LargeVT.getScalarType().getSizeInBits() - OpSizeInBits ==
3933         LargeShiftAmt->getZExtValue()) {
3934       SDValue Amt =
3935         DAG.getConstant(LargeShiftAmt->getZExtValue() + N1C->getZExtValue(),
3936               getShiftAmountTy(N0.getOperand(0).getOperand(0).getValueType()));
3937       SDValue SRA = DAG.getNode(ISD::SRA, SDLoc(N), LargeVT,
3938                                 N0.getOperand(0).getOperand(0), Amt);
3939       return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, SRA);
3940     }
3941   }
3942
3943   // Simplify, based on bits shifted out of the LHS.
3944   if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
3945     return SDValue(N, 0);
3946
3947
3948   // If the sign bit is known to be zero, switch this to a SRL.
3949   if (DAG.SignBitIsZero(N0))
3950     return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, N1);
3951
3952   if (N1C) {
3953     SDValue NewSRA = visitShiftByConstant(N, N1C->getZExtValue());
3954     if (NewSRA.getNode())
3955       return NewSRA;
3956   }
3957
3958   return SDValue();
3959 }
3960
3961 SDValue DAGCombiner::visitSRL(SDNode *N) {
3962   SDValue N0 = N->getOperand(0);
3963   SDValue N1 = N->getOperand(1);
3964   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
3965   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
3966   EVT VT = N0.getValueType();
3967   unsigned OpSizeInBits = VT.getScalarType().getSizeInBits();
3968
3969   // fold (srl c1, c2) -> c1 >>u c2
3970   if (N0C && N1C)
3971     return DAG.FoldConstantArithmetic(ISD::SRL, VT, N0C, N1C);
3972   // fold (srl 0, x) -> 0
3973   if (N0C && N0C->isNullValue())
3974     return N0;
3975   // fold (srl x, c >= size(x)) -> undef
3976   if (N1C && N1C->getZExtValue() >= OpSizeInBits)
3977     return DAG.getUNDEF(VT);
3978   // fold (srl x, 0) -> x
3979   if (N1C && N1C->isNullValue())
3980     return N0;
3981   // if (srl x, c) is known to be zero, return 0
3982   if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0),
3983                                    APInt::getAllOnesValue(OpSizeInBits)))
3984     return DAG.getConstant(0, VT);
3985
3986   // fold (srl (srl x, c1), c2) -> 0 or (srl x, (add c1, c2))
3987   if (N1C && N0.getOpcode() == ISD::SRL &&
3988       N0.getOperand(1).getOpcode() == ISD::Constant) {
3989     uint64_t c1 = cast<ConstantSDNode>(N0.getOperand(1))->getZExtValue();
3990     uint64_t c2 = N1C->getZExtValue();
3991     if (c1 + c2 >= OpSizeInBits)
3992       return DAG.getConstant(0, VT);
3993     return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0),
3994                        DAG.getConstant(c1 + c2, N1.getValueType()));
3995   }
3996
3997   // fold (srl (trunc (srl x, c1)), c2) -> 0 or (trunc (srl x, (add c1, c2)))
3998   if (N1C && N0.getOpcode() == ISD::TRUNCATE &&
3999       N0.getOperand(0).getOpcode() == ISD::SRL &&
4000       isa<ConstantSDNode>(N0.getOperand(0)->getOperand(1))) {
4001     uint64_t c1 =
4002       cast<ConstantSDNode>(N0.getOperand(0)->getOperand(1))->getZExtValue();
4003     uint64_t c2 = N1C->getZExtValue();
4004     EVT InnerShiftVT = N0.getOperand(0).getValueType();
4005     EVT ShiftCountVT = N0.getOperand(0)->getOperand(1).getValueType();
4006     uint64_t InnerShiftSize = InnerShiftVT.getScalarType().getSizeInBits();
4007     // This is only valid if the OpSizeInBits + c1 = size of inner shift.
4008     if (c1 + OpSizeInBits == InnerShiftSize) {
4009       if (c1 + c2 >= InnerShiftSize)
4010         return DAG.getConstant(0, VT);
4011       return DAG.getNode(ISD::TRUNCATE, SDLoc(N0), VT,
4012                          DAG.getNode(ISD::SRL, SDLoc(N0), InnerShiftVT,
4013                                      N0.getOperand(0)->getOperand(0),
4014                                      DAG.getConstant(c1 + c2, ShiftCountVT)));
4015     }
4016   }
4017
4018   // fold (srl (shl x, c), c) -> (and x, cst2)
4019   if (N1C && N0.getOpcode() == ISD::SHL && N0.getOperand(1) == N1 &&
4020       N0.getValueSizeInBits() <= 64) {
4021     uint64_t ShAmt = N1C->getZExtValue()+64-N0.getValueSizeInBits();
4022     return DAG.getNode(ISD::AND, SDLoc(N), VT, N0.getOperand(0),
4023                        DAG.getConstant(~0ULL >> ShAmt, VT));
4024   }
4025
4026   // fold (srl (anyextend x), c) -> (and (anyextend (srl x, c)), mask)
4027   if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
4028     // Shifting in all undef bits?
4029     EVT SmallVT = N0.getOperand(0).getValueType();
4030     if (N1C->getZExtValue() >= SmallVT.getSizeInBits())
4031       return DAG.getUNDEF(VT);
4032
4033     if (!LegalTypes || TLI.isTypeDesirableForOp(ISD::SRL, SmallVT)) {
4034       uint64_t ShiftAmt = N1C->getZExtValue();
4035       SDValue SmallShift = DAG.getNode(ISD::SRL, SDLoc(N0), SmallVT,
4036                                        N0.getOperand(0),
4037                           DAG.getConstant(ShiftAmt, getShiftAmountTy(SmallVT)));
4038       AddToWorkList(SmallShift.getNode());
4039       APInt Mask = APInt::getAllOnesValue(VT.getSizeInBits()).lshr(ShiftAmt);
4040       return DAG.getNode(ISD::AND, SDLoc(N), VT,
4041                          DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, SmallShift),
4042                          DAG.getConstant(Mask, VT));
4043     }
4044   }
4045
4046   // fold (srl (sra X, Y), 31) -> (srl X, 31).  This srl only looks at the sign
4047   // bit, which is unmodified by sra.
4048   if (N1C && N1C->getZExtValue() + 1 == VT.getSizeInBits()) {
4049     if (N0.getOpcode() == ISD::SRA)
4050       return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0), N1);
4051   }
4052
4053   // fold (srl (ctlz x), "5") -> x  iff x has one bit set (the low bit).
4054   if (N1C && N0.getOpcode() == ISD::CTLZ &&
4055       N1C->getAPIntValue() == Log2_32(VT.getSizeInBits())) {
4056     APInt KnownZero, KnownOne;
4057     DAG.ComputeMaskedBits(N0.getOperand(0), KnownZero, KnownOne);
4058
4059     // If any of the input bits are KnownOne, then the input couldn't be all
4060     // zeros, thus the result of the srl will always be zero.
4061     if (KnownOne.getBoolValue()) return DAG.getConstant(0, VT);
4062
4063     // If all of the bits input the to ctlz node are known to be zero, then
4064     // the result of the ctlz is "32" and the result of the shift is one.
4065     APInt UnknownBits = ~KnownZero;
4066     if (UnknownBits == 0) return DAG.getConstant(1, VT);
4067
4068     // Otherwise, check to see if there is exactly one bit input to the ctlz.
4069     if ((UnknownBits & (UnknownBits - 1)) == 0) {
4070       // Okay, we know that only that the single bit specified by UnknownBits
4071       // could be set on input to the CTLZ node. If this bit is set, the SRL
4072       // will return 0, if it is clear, it returns 1. Change the CTLZ/SRL pair
4073       // to an SRL/XOR pair, which is likely to simplify more.
4074       unsigned ShAmt = UnknownBits.countTrailingZeros();
4075       SDValue Op = N0.getOperand(0);
4076
4077       if (ShAmt) {
4078         Op = DAG.getNode(ISD::SRL, SDLoc(N0), VT, Op,
4079                   DAG.getConstant(ShAmt, getShiftAmountTy(Op.getValueType())));
4080         AddToWorkList(Op.getNode());
4081       }
4082
4083       return DAG.getNode(ISD::XOR, SDLoc(N), VT,
4084                          Op, DAG.getConstant(1, VT));
4085     }
4086   }
4087
4088   // fold (srl x, (trunc (and y, c))) -> (srl x, (and (trunc y), (trunc c))).
4089   if (N1.getOpcode() == ISD::TRUNCATE &&
4090       N1.getOperand(0).getOpcode() == ISD::AND &&
4091       N1.hasOneUse() && N1.getOperand(0).hasOneUse()) {
4092     SDValue N101 = N1.getOperand(0).getOperand(1);
4093     if (ConstantSDNode *N101C = dyn_cast<ConstantSDNode>(N101)) {
4094       EVT TruncVT = N1.getValueType();
4095       SDValue N100 = N1.getOperand(0).getOperand(0);
4096       APInt TruncC = N101C->getAPIntValue();
4097       TruncC = TruncC.trunc(TruncVT.getSizeInBits());
4098       return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0,
4099                          DAG.getNode(ISD::AND, SDLoc(N),
4100                                      TruncVT,
4101                                      DAG.getNode(ISD::TRUNCATE,
4102                                                  SDLoc(N),
4103                                                  TruncVT, N100),
4104                                      DAG.getConstant(TruncC, TruncVT)));
4105     }
4106   }
4107
4108   // fold operands of srl based on knowledge that the low bits are not
4109   // demanded.
4110   if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
4111     return SDValue(N, 0);
4112
4113   if (N1C) {
4114     SDValue NewSRL = visitShiftByConstant(N, N1C->getZExtValue());
4115     if (NewSRL.getNode())
4116       return NewSRL;
4117   }
4118
4119   // Attempt to convert a srl of a load into a narrower zero-extending load.
4120   SDValue NarrowLoad = ReduceLoadWidth(N);
4121   if (NarrowLoad.getNode())
4122     return NarrowLoad;
4123
4124   // Here is a common situation. We want to optimize:
4125   //
4126   //   %a = ...
4127   //   %b = and i32 %a, 2
4128   //   %c = srl i32 %b, 1
4129   //   brcond i32 %c ...
4130   //
4131   // into
4132   //
4133   //   %a = ...
4134   //   %b = and %a, 2
4135   //   %c = setcc eq %b, 0
4136   //   brcond %c ...
4137   //
4138   // However when after the source operand of SRL is optimized into AND, the SRL
4139   // itself may not be optimized further. Look for it and add the BRCOND into
4140   // the worklist.
4141   if (N->hasOneUse()) {
4142     SDNode *Use = *N->use_begin();
4143     if (Use->getOpcode() == ISD::BRCOND)
4144       AddToWorkList(Use);
4145     else if (Use->getOpcode() == ISD::TRUNCATE && Use->hasOneUse()) {
4146       // Also look pass the truncate.
4147       Use = *Use->use_begin();
4148       if (Use->getOpcode() == ISD::BRCOND)
4149         AddToWorkList(Use);
4150     }
4151   }
4152
4153   return SDValue();
4154 }
4155
4156 SDValue DAGCombiner::visitCTLZ(SDNode *N) {
4157   SDValue N0 = N->getOperand(0);
4158   EVT VT = N->getValueType(0);
4159
4160   // fold (ctlz c1) -> c2
4161   if (isa<ConstantSDNode>(N0))
4162     return DAG.getNode(ISD::CTLZ, SDLoc(N), VT, N0);
4163   return SDValue();
4164 }
4165
4166 SDValue DAGCombiner::visitCTLZ_ZERO_UNDEF(SDNode *N) {
4167   SDValue N0 = N->getOperand(0);
4168   EVT VT = N->getValueType(0);
4169
4170   // fold (ctlz_zero_undef c1) -> c2
4171   if (isa<ConstantSDNode>(N0))
4172     return DAG.getNode(ISD::CTLZ_ZERO_UNDEF, SDLoc(N), VT, N0);
4173   return SDValue();
4174 }
4175
4176 SDValue DAGCombiner::visitCTTZ(SDNode *N) {
4177   SDValue N0 = N->getOperand(0);
4178   EVT VT = N->getValueType(0);
4179
4180   // fold (cttz c1) -> c2
4181   if (isa<ConstantSDNode>(N0))
4182     return DAG.getNode(ISD::CTTZ, SDLoc(N), VT, N0);
4183   return SDValue();
4184 }
4185
4186 SDValue DAGCombiner::visitCTTZ_ZERO_UNDEF(SDNode *N) {
4187   SDValue N0 = N->getOperand(0);
4188   EVT VT = N->getValueType(0);
4189
4190   // fold (cttz_zero_undef c1) -> c2
4191   if (isa<ConstantSDNode>(N0))
4192     return DAG.getNode(ISD::CTTZ_ZERO_UNDEF, SDLoc(N), VT, N0);
4193   return SDValue();
4194 }
4195
4196 SDValue DAGCombiner::visitCTPOP(SDNode *N) {
4197   SDValue N0 = N->getOperand(0);
4198   EVT VT = N->getValueType(0);
4199
4200   // fold (ctpop c1) -> c2
4201   if (isa<ConstantSDNode>(N0))
4202     return DAG.getNode(ISD::CTPOP, SDLoc(N), VT, N0);
4203   return SDValue();
4204 }
4205
4206 SDValue DAGCombiner::visitSELECT(SDNode *N) {
4207   SDValue N0 = N->getOperand(0);
4208   SDValue N1 = N->getOperand(1);
4209   SDValue N2 = N->getOperand(2);
4210   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
4211   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4212   ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2);
4213   EVT VT = N->getValueType(0);
4214   EVT VT0 = N0.getValueType();
4215
4216   // fold (select C, X, X) -> X
4217   if (N1 == N2)
4218     return N1;
4219   // fold (select true, X, Y) -> X
4220   if (N0C && !N0C->isNullValue())
4221     return N1;
4222   // fold (select false, X, Y) -> Y
4223   if (N0C && N0C->isNullValue())
4224     return N2;
4225   // fold (select C, 1, X) -> (or C, X)
4226   if (VT == MVT::i1 && N1C && N1C->getAPIntValue() == 1)
4227     return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N2);
4228   // fold (select C, 0, 1) -> (xor C, 1)
4229   if (VT.isInteger() &&
4230       (VT0 == MVT::i1 ||
4231        (VT0.isInteger() &&
4232         TLI.getBooleanContents(false) ==
4233         TargetLowering::ZeroOrOneBooleanContent)) &&
4234       N1C && N2C && N1C->isNullValue() && N2C->getAPIntValue() == 1) {
4235     SDValue XORNode;
4236     if (VT == VT0)
4237       return DAG.getNode(ISD::XOR, SDLoc(N), VT0,
4238                          N0, DAG.getConstant(1, VT0));
4239     XORNode = DAG.getNode(ISD::XOR, SDLoc(N0), VT0,
4240                           N0, DAG.getConstant(1, VT0));
4241     AddToWorkList(XORNode.getNode());
4242     if (VT.bitsGT(VT0))
4243       return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, XORNode);
4244     return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, XORNode);
4245   }
4246   // fold (select C, 0, X) -> (and (not C), X)
4247   if (VT == VT0 && VT == MVT::i1 && N1C && N1C->isNullValue()) {
4248     SDValue NOTNode = DAG.getNOT(SDLoc(N0), N0, VT);
4249     AddToWorkList(NOTNode.getNode());
4250     return DAG.getNode(ISD::AND, SDLoc(N), VT, NOTNode, N2);
4251   }
4252   // fold (select C, X, 1) -> (or (not C), X)
4253   if (VT == VT0 && VT == MVT::i1 && N2C && N2C->getAPIntValue() == 1) {
4254     SDValue NOTNode = DAG.getNOT(SDLoc(N0), N0, VT);
4255     AddToWorkList(NOTNode.getNode());
4256     return DAG.getNode(ISD::OR, SDLoc(N), VT, NOTNode, N1);
4257   }
4258   // fold (select C, X, 0) -> (and C, X)
4259   if (VT == MVT::i1 && N2C && N2C->isNullValue())
4260     return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, N1);
4261   // fold (select X, X, Y) -> (or X, Y)
4262   // fold (select X, 1, Y) -> (or X, Y)
4263   if (VT == MVT::i1 && (N0 == N1 || (N1C && N1C->getAPIntValue() == 1)))
4264     return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N2);
4265   // fold (select X, Y, X) -> (and X, Y)
4266   // fold (select X, Y, 0) -> (and X, Y)
4267   if (VT == MVT::i1 && (N0 == N2 || (N2C && N2C->getAPIntValue() == 0)))
4268     return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, N1);
4269
4270   // If we can fold this based on the true/false value, do so.
4271   if (SimplifySelectOps(N, N1, N2))
4272     return SDValue(N, 0);  // Don't revisit N.
4273
4274   // fold selects based on a setcc into other things, such as min/max/abs
4275   if (N0.getOpcode() == ISD::SETCC) {
4276     // FIXME:
4277     // Check against MVT::Other for SELECT_CC, which is a workaround for targets
4278     // having to say they don't support SELECT_CC on every type the DAG knows
4279     // about, since there is no way to mark an opcode illegal at all value types
4280     if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, MVT::Other) &&
4281         TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT))
4282       return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT,
4283                          N0.getOperand(0), N0.getOperand(1),
4284                          N1, N2, N0.getOperand(2));
4285     return SimplifySelect(SDLoc(N), N0, N1, N2);
4286   }
4287
4288   return SDValue();
4289 }
4290
4291 SDValue DAGCombiner::visitVSELECT(SDNode *N) {
4292   SDValue N0 = N->getOperand(0);
4293   SDValue N1 = N->getOperand(1);
4294   SDValue N2 = N->getOperand(2);
4295   SDLoc DL(N);
4296
4297   // Canonicalize integer abs.
4298   // vselect (setg[te] X,  0),  X, -X ->
4299   // vselect (setgt    X, -1),  X, -X ->
4300   // vselect (setl[te] X,  0), -X,  X ->
4301   // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
4302   if (N0.getOpcode() == ISD::SETCC) {
4303     SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
4304     ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
4305     bool isAbs = false;
4306     bool RHSIsAllZeros = ISD::isBuildVectorAllZeros(RHS.getNode());
4307
4308     if (((RHSIsAllZeros && (CC == ISD::SETGT || CC == ISD::SETGE)) ||
4309          (ISD::isBuildVectorAllOnes(RHS.getNode()) && CC == ISD::SETGT)) &&
4310         N1 == LHS && N2.getOpcode() == ISD::SUB && N1 == N2.getOperand(1))
4311       isAbs = ISD::isBuildVectorAllZeros(N2.getOperand(0).getNode());
4312     else if ((RHSIsAllZeros && (CC == ISD::SETLT || CC == ISD::SETLE)) &&
4313              N2 == LHS && N1.getOpcode() == ISD::SUB && N2 == N1.getOperand(1))
4314       isAbs = ISD::isBuildVectorAllZeros(N1.getOperand(0).getNode());
4315
4316     if (isAbs) {
4317       EVT VT = LHS.getValueType();
4318       SDValue Shift = DAG.getNode(
4319           ISD::SRA, DL, VT, LHS,
4320           DAG.getConstant(VT.getScalarType().getSizeInBits() - 1, VT));
4321       SDValue Add = DAG.getNode(ISD::ADD, DL, VT, LHS, Shift);
4322       AddToWorkList(Shift.getNode());
4323       AddToWorkList(Add.getNode());
4324       return DAG.getNode(ISD::XOR, DL, VT, Add, Shift);
4325     }
4326   }
4327
4328   return SDValue();
4329 }
4330
4331 SDValue DAGCombiner::visitSELECT_CC(SDNode *N) {
4332   SDValue N0 = N->getOperand(0);
4333   SDValue N1 = N->getOperand(1);
4334   SDValue N2 = N->getOperand(2);
4335   SDValue N3 = N->getOperand(3);
4336   SDValue N4 = N->getOperand(4);
4337   ISD::CondCode CC = cast<CondCodeSDNode>(N4)->get();
4338
4339   // fold select_cc lhs, rhs, x, x, cc -> x
4340   if (N2 == N3)
4341     return N2;
4342
4343   // Determine if the condition we're dealing with is constant
4344   SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()),
4345                               N0, N1, CC, SDLoc(N), false);
4346   if (SCC.getNode()) {
4347     AddToWorkList(SCC.getNode());
4348
4349     if (ConstantSDNode *SCCC = dyn_cast<ConstantSDNode>(SCC.getNode())) {
4350       if (!SCCC->isNullValue())
4351         return N2;    // cond always true -> true val
4352       else
4353         return N3;    // cond always false -> false val
4354     }
4355
4356     // Fold to a simpler select_cc
4357     if (SCC.getOpcode() == ISD::SETCC)
4358       return DAG.getNode(ISD::SELECT_CC, SDLoc(N), N2.getValueType(),
4359                          SCC.getOperand(0), SCC.getOperand(1), N2, N3,
4360                          SCC.getOperand(2));
4361   }
4362
4363   // If we can fold this based on the true/false value, do so.
4364   if (SimplifySelectOps(N, N2, N3))
4365     return SDValue(N, 0);  // Don't revisit N.
4366
4367   // fold select_cc into other things, such as min/max/abs
4368   return SimplifySelectCC(SDLoc(N), N0, N1, N2, N3, CC);
4369 }
4370
4371 SDValue DAGCombiner::visitSETCC(SDNode *N) {
4372   return SimplifySetCC(N->getValueType(0), N->getOperand(0), N->getOperand(1),
4373                        cast<CondCodeSDNode>(N->getOperand(2))->get(),
4374                        SDLoc(N));
4375 }
4376
4377 // ExtendUsesToFormExtLoad - Trying to extend uses of a load to enable this:
4378 // "fold ({s|z|a}ext (load x)) -> ({s|z|a}ext (truncate ({s|z|a}extload x)))"
4379 // transformation. Returns true if extension are possible and the above
4380 // mentioned transformation is profitable.
4381 static bool ExtendUsesToFormExtLoad(SDNode *N, SDValue N0,
4382                                     unsigned ExtOpc,
4383                                     SmallVectorImpl<SDNode *> &ExtendNodes,
4384                                     const TargetLowering &TLI) {
4385   bool HasCopyToRegUses = false;
4386   bool isTruncFree = TLI.isTruncateFree(N->getValueType(0), N0.getValueType());
4387   for (SDNode::use_iterator UI = N0.getNode()->use_begin(),
4388                             UE = N0.getNode()->use_end();
4389        UI != UE; ++UI) {
4390     SDNode *User = *UI;
4391     if (User == N)
4392       continue;
4393     if (UI.getUse().getResNo() != N0.getResNo())
4394       continue;
4395     // FIXME: Only extend SETCC N, N and SETCC N, c for now.
4396     if (ExtOpc != ISD::ANY_EXTEND && User->getOpcode() == ISD::SETCC) {
4397       ISD::CondCode CC = cast<CondCodeSDNode>(User->getOperand(2))->get();
4398       if (ExtOpc == ISD::ZERO_EXTEND && ISD::isSignedIntSetCC(CC))
4399         // Sign bits will be lost after a zext.
4400         return false;
4401       bool Add = false;
4402       for (unsigned i = 0; i != 2; ++i) {
4403         SDValue UseOp = User->getOperand(i);
4404         if (UseOp == N0)
4405           continue;
4406         if (!isa<ConstantSDNode>(UseOp))
4407           return false;
4408         Add = true;
4409       }
4410       if (Add)
4411         ExtendNodes.push_back(User);
4412       continue;
4413     }
4414     // If truncates aren't free and there are users we can't
4415     // extend, it isn't worthwhile.
4416     if (!isTruncFree)
4417       return false;
4418     // Remember if this value is live-out.
4419     if (User->getOpcode() == ISD::CopyToReg)
4420       HasCopyToRegUses = true;
4421   }
4422
4423   if (HasCopyToRegUses) {
4424     bool BothLiveOut = false;
4425     for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
4426          UI != UE; ++UI) {
4427       SDUse &Use = UI.getUse();
4428       if (Use.getResNo() == 0 && Use.getUser()->getOpcode() == ISD::CopyToReg) {
4429         BothLiveOut = true;
4430         break;
4431       }
4432     }
4433     if (BothLiveOut)
4434       // Both unextended and extended values are live out. There had better be
4435       // a good reason for the transformation.
4436       return ExtendNodes.size();
4437   }
4438   return true;
4439 }
4440
4441 void DAGCombiner::ExtendSetCCUses(const SmallVectorImpl<SDNode *> &SetCCs,
4442                                   SDValue Trunc, SDValue ExtLoad, SDLoc DL,
4443                                   ISD::NodeType ExtType) {
4444   // Extend SetCC uses if necessary.
4445   for (unsigned i = 0, e = SetCCs.size(); i != e; ++i) {
4446     SDNode *SetCC = SetCCs[i];
4447     SmallVector<SDValue, 4> Ops;
4448
4449     for (unsigned j = 0; j != 2; ++j) {
4450       SDValue SOp = SetCC->getOperand(j);
4451       if (SOp == Trunc)
4452         Ops.push_back(ExtLoad);
4453       else
4454         Ops.push_back(DAG.getNode(ExtType, DL, ExtLoad->getValueType(0), SOp));
4455     }
4456
4457     Ops.push_back(SetCC->getOperand(2));
4458     CombineTo(SetCC, DAG.getNode(ISD::SETCC, DL, SetCC->getValueType(0),
4459                                  &Ops[0], Ops.size()));
4460   }
4461 }
4462
4463 SDValue DAGCombiner::visitSIGN_EXTEND(SDNode *N) {
4464   SDValue N0 = N->getOperand(0);
4465   EVT VT = N->getValueType(0);
4466
4467   // fold (sext c1) -> c1
4468   if (isa<ConstantSDNode>(N0))
4469     return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, N0);
4470
4471   // fold (sext (sext x)) -> (sext x)
4472   // fold (sext (aext x)) -> (sext x)
4473   if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
4474     return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT,
4475                        N0.getOperand(0));
4476
4477   if (N0.getOpcode() == ISD::TRUNCATE) {
4478     // fold (sext (truncate (load x))) -> (sext (smaller load x))
4479     // fold (sext (truncate (srl (load x), c))) -> (sext (smaller load (x+c/n)))
4480     SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
4481     if (NarrowLoad.getNode()) {
4482       SDNode* oye = N0.getNode()->getOperand(0).getNode();
4483       if (NarrowLoad.getNode() != N0.getNode()) {
4484         CombineTo(N0.getNode(), NarrowLoad);
4485         // CombineTo deleted the truncate, if needed, but not what's under it.
4486         AddToWorkList(oye);
4487       }
4488       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
4489     }
4490
4491     // See if the value being truncated is already sign extended.  If so, just
4492     // eliminate the trunc/sext pair.
4493     SDValue Op = N0.getOperand(0);
4494     unsigned OpBits   = Op.getValueType().getScalarType().getSizeInBits();
4495     unsigned MidBits  = N0.getValueType().getScalarType().getSizeInBits();
4496     unsigned DestBits = VT.getScalarType().getSizeInBits();
4497     unsigned NumSignBits = DAG.ComputeNumSignBits(Op);
4498
4499     if (OpBits == DestBits) {
4500       // Op is i32, Mid is i8, and Dest is i32.  If Op has more than 24 sign
4501       // bits, it is already ready.
4502       if (NumSignBits > DestBits-MidBits)
4503         return Op;
4504     } else if (OpBits < DestBits) {
4505       // Op is i32, Mid is i8, and Dest is i64.  If Op has more than 24 sign
4506       // bits, just sext from i32.
4507       if (NumSignBits > OpBits-MidBits)
4508         return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, Op);
4509     } else {
4510       // Op is i64, Mid is i8, and Dest is i32.  If Op has more than 56 sign
4511       // bits, just truncate to i32.
4512       if (NumSignBits > OpBits-MidBits)
4513         return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
4514     }
4515
4516     // fold (sext (truncate x)) -> (sextinreg x).
4517     if (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG,
4518                                                  N0.getValueType())) {
4519       if (OpBits < DestBits)
4520         Op = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N0), VT, Op);
4521       else if (OpBits > DestBits)
4522         Op = DAG.getNode(ISD::TRUNCATE, SDLoc(N0), VT, Op);
4523       return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, Op,
4524                          DAG.getValueType(N0.getValueType()));
4525     }
4526   }
4527
4528   // fold (sext (load x)) -> (sext (truncate (sextload x)))
4529   // None of the supported targets knows how to perform load and sign extend
4530   // on vectors in one instruction.  We only perform this transformation on
4531   // scalars.
4532   if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() &&
4533       ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
4534        TLI.isLoadExtLegal(ISD::SEXTLOAD, N0.getValueType()))) {
4535     bool DoXform = true;
4536     SmallVector<SDNode*, 4> SetCCs;
4537     if (!N0.hasOneUse())
4538       DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::SIGN_EXTEND, SetCCs, TLI);
4539     if (DoXform) {
4540       LoadSDNode *LN0 = cast<LoadSDNode>(N0);
4541       SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
4542                                        LN0->getChain(),
4543                                        LN0->getBasePtr(), LN0->getPointerInfo(),
4544                                        N0.getValueType(),
4545                                        LN0->isVolatile(), LN0->isNonTemporal(),
4546                                        LN0->getAlignment());
4547       CombineTo(N, ExtLoad);
4548       SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
4549                                   N0.getValueType(), ExtLoad);
4550       CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
4551       ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
4552                       ISD::SIGN_EXTEND);
4553       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
4554     }
4555   }
4556
4557   // fold (sext (sextload x)) -> (sext (truncate (sextload x)))
4558   // fold (sext ( extload x)) -> (sext (truncate (sextload x)))
4559   if ((ISD::isSEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) &&
4560       ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) {
4561     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
4562     EVT MemVT = LN0->getMemoryVT();
4563     if ((!LegalOperations && !LN0->isVolatile()) ||
4564         TLI.isLoadExtLegal(ISD::SEXTLOAD, MemVT)) {
4565       SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
4566                                        LN0->getChain(),
4567                                        LN0->getBasePtr(), LN0->getPointerInfo(),
4568                                        MemVT,
4569                                        LN0->isVolatile(), LN0->isNonTemporal(),
4570                                        LN0->getAlignment());
4571       CombineTo(N, ExtLoad);
4572       CombineTo(N0.getNode(),
4573                 DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
4574                             N0.getValueType(), ExtLoad),
4575                 ExtLoad.getValue(1));
4576       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
4577     }
4578   }
4579
4580   // fold (sext (and/or/xor (load x), cst)) ->
4581   //      (and/or/xor (sextload x), (sext cst))
4582   if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR ||
4583        N0.getOpcode() == ISD::XOR) &&
4584       isa<LoadSDNode>(N0.getOperand(0)) &&
4585       N0.getOperand(1).getOpcode() == ISD::Constant &&
4586       TLI.isLoadExtLegal(ISD::SEXTLOAD, N0.getValueType()) &&
4587       (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) {
4588     LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0));
4589     if (LN0->getExtensionType() != ISD::ZEXTLOAD) {
4590       bool DoXform = true;
4591       SmallVector<SDNode*, 4> SetCCs;
4592       if (!N0.hasOneUse())
4593         DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0), ISD::SIGN_EXTEND,
4594                                           SetCCs, TLI);
4595       if (DoXform) {
4596         SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(LN0), VT,
4597                                          LN0->getChain(), LN0->getBasePtr(),
4598                                          LN0->getPointerInfo(),
4599                                          LN0->getMemoryVT(),
4600                                          LN0->isVolatile(),
4601                                          LN0->isNonTemporal(),
4602                                          LN0->getAlignment());
4603         APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
4604         Mask = Mask.sext(VT.getSizeInBits());
4605         SDValue And = DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
4606                                   ExtLoad, DAG.getConstant(Mask, VT));
4607         SDValue Trunc = DAG.getNode(ISD::TRUNCATE,
4608                                     SDLoc(N0.getOperand(0)),
4609                                     N0.getOperand(0).getValueType(), ExtLoad);
4610         CombineTo(N, And);
4611         CombineTo(N0.getOperand(0).getNode(), Trunc, ExtLoad.getValue(1));
4612         ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
4613                         ISD::SIGN_EXTEND);
4614         return SDValue(N, 0);   // Return N so it doesn't get rechecked!
4615       }
4616     }
4617   }
4618
4619   if (N0.getOpcode() == ISD::SETCC) {
4620     // sext(setcc) -> sext_in_reg(vsetcc) for vectors.
4621     // Only do this before legalize for now.
4622     if (VT.isVector() && !LegalOperations &&
4623         TLI.getBooleanContents(true) ==
4624           TargetLowering::ZeroOrNegativeOneBooleanContent) {
4625       EVT N0VT = N0.getOperand(0).getValueType();
4626       // On some architectures (such as SSE/NEON/etc) the SETCC result type is
4627       // of the same size as the compared operands. Only optimize sext(setcc())
4628       // if this is the case.
4629       EVT SVT = getSetCCResultType(N0VT);
4630
4631       // We know that the # elements of the results is the same as the
4632       // # elements of the compare (and the # elements of the compare result
4633       // for that matter).  Check to see that they are the same size.  If so,
4634       // we know that the element size of the sext'd result matches the
4635       // element size of the compare operands.
4636       if (VT.getSizeInBits() == SVT.getSizeInBits())
4637         return DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
4638                              N0.getOperand(1),
4639                              cast<CondCodeSDNode>(N0.getOperand(2))->get());
4640
4641       // If the desired elements are smaller or larger than the source
4642       // elements we can use a matching integer vector type and then
4643       // truncate/sign extend
4644       EVT MatchingVectorType = N0VT.changeVectorElementTypeToInteger();
4645       if (SVT == MatchingVectorType) {
4646         SDValue VsetCC = DAG.getSetCC(SDLoc(N), MatchingVectorType,
4647                                N0.getOperand(0), N0.getOperand(1),
4648                                cast<CondCodeSDNode>(N0.getOperand(2))->get());
4649         return DAG.getSExtOrTrunc(VsetCC, SDLoc(N), VT);
4650       }
4651     }
4652
4653     // sext(setcc x, y, cc) -> (select_cc x, y, -1, 0, cc)
4654     unsigned ElementWidth = VT.getScalarType().getSizeInBits();
4655     SDValue NegOne =
4656       DAG.getConstant(APInt::getAllOnesValue(ElementWidth), VT);
4657     SDValue SCC =
4658       SimplifySelectCC(SDLoc(N), N0.getOperand(0), N0.getOperand(1),
4659                        NegOne, DAG.getConstant(0, VT),
4660                        cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
4661     if (SCC.getNode()) return SCC;
4662     if (!VT.isVector() &&
4663         (!LegalOperations ||
4664          TLI.isOperationLegal(ISD::SETCC, getSetCCResultType(VT)))) {
4665       return DAG.getSelect(SDLoc(N), VT,
4666                            DAG.getSetCC(SDLoc(N),
4667                                         getSetCCResultType(VT),
4668                                         N0.getOperand(0), N0.getOperand(1),
4669                                         cast<CondCodeSDNode>(N0.getOperand(2))->get()),
4670                            NegOne, DAG.getConstant(0, VT));
4671     }
4672   }
4673
4674   // fold (sext x) -> (zext x) if the sign bit is known zero.
4675   if ((!LegalOperations || TLI.isOperationLegal(ISD::ZERO_EXTEND, VT)) &&
4676       DAG.SignBitIsZero(N0))
4677     return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, N0);
4678
4679   return SDValue();
4680 }
4681
4682 // isTruncateOf - If N is a truncate of some other value, return true, record
4683 // the value being truncated in Op and which of Op's bits are zero in KnownZero.
4684 // This function computes KnownZero to avoid a duplicated call to
4685 // ComputeMaskedBits in the caller.
4686 static bool isTruncateOf(SelectionDAG &DAG, SDValue N, SDValue &Op,
4687                          APInt &KnownZero) {
4688   APInt KnownOne;
4689   if (N->getOpcode() == ISD::TRUNCATE) {
4690     Op = N->getOperand(0);
4691     DAG.ComputeMaskedBits(Op, KnownZero, KnownOne);
4692     return true;
4693   }
4694
4695   if (N->getOpcode() != ISD::SETCC || N->getValueType(0) != MVT::i1 ||
4696       cast<CondCodeSDNode>(N->getOperand(2))->get() != ISD::SETNE)
4697     return false;
4698
4699   SDValue Op0 = N->getOperand(0);
4700   SDValue Op1 = N->getOperand(1);
4701   assert(Op0.getValueType() == Op1.getValueType());
4702
4703   ConstantSDNode *COp0 = dyn_cast<ConstantSDNode>(Op0);
4704   ConstantSDNode *COp1 = dyn_cast<ConstantSDNode>(Op1);
4705   if (COp0 && COp0->isNullValue())
4706     Op = Op1;
4707   else if (COp1 && COp1->isNullValue())
4708     Op = Op0;
4709   else
4710     return false;
4711
4712   DAG.ComputeMaskedBits(Op, KnownZero, KnownOne);
4713
4714   if (!(KnownZero | APInt(Op.getValueSizeInBits(), 1)).isAllOnesValue())
4715     return false;
4716
4717   return true;
4718 }
4719
4720 SDValue DAGCombiner::visitZERO_EXTEND(SDNode *N) {
4721   SDValue N0 = N->getOperand(0);
4722   EVT VT = N->getValueType(0);
4723
4724   // fold (zext c1) -> c1
4725   if (isa<ConstantSDNode>(N0))
4726     return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, N0);
4727   // fold (zext (zext x)) -> (zext x)
4728   // fold (zext (aext x)) -> (zext x)
4729   if (N0.getOpcode() == ISD::ZERO_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
4730     return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT,
4731                        N0.getOperand(0));
4732
4733   // fold (zext (truncate x)) -> (zext x) or
4734   //      (zext (truncate x)) -> (truncate x)
4735   // This is valid when the truncated bits of x are already zero.
4736   // FIXME: We should extend this to work for vectors too.
4737   SDValue Op;
4738   APInt KnownZero;
4739   if (!VT.isVector() && isTruncateOf(DAG, N0, Op, KnownZero)) {
4740     APInt TruncatedBits =
4741       (Op.getValueSizeInBits() == N0.getValueSizeInBits()) ?
4742       APInt(Op.getValueSizeInBits(), 0) :
4743       APInt::getBitsSet(Op.getValueSizeInBits(),
4744                         N0.getValueSizeInBits(),
4745                         std::min(Op.getValueSizeInBits(),
4746                                  VT.getSizeInBits()));
4747     if (TruncatedBits == (KnownZero & TruncatedBits)) {
4748       if (VT.bitsGT(Op.getValueType()))
4749         return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, Op);
4750       if (VT.bitsLT(Op.getValueType()))
4751         return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
4752
4753       return Op;
4754     }
4755   }
4756
4757   // fold (zext (truncate (load x))) -> (zext (smaller load x))
4758   // fold (zext (truncate (srl (load x), c))) -> (zext (small load (x+c/n)))
4759   if (N0.getOpcode() == ISD::TRUNCATE) {
4760     SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
4761     if (NarrowLoad.getNode()) {
4762       SDNode* oye = N0.getNode()->getOperand(0).getNode();
4763       if (NarrowLoad.getNode() != N0.getNode()) {
4764         CombineTo(N0.getNode(), NarrowLoad);
4765         // CombineTo deleted the truncate, if needed, but not what's under it.
4766         AddToWorkList(oye);
4767       }
4768       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
4769     }
4770   }
4771
4772   // fold (zext (truncate x)) -> (and x, mask)
4773   if (N0.getOpcode() == ISD::TRUNCATE &&
4774       (!LegalOperations || TLI.isOperationLegal(ISD::AND, VT))) {
4775
4776     // fold (zext (truncate (load x))) -> (zext (smaller load x))
4777     // fold (zext (truncate (srl (load x), c))) -> (zext (smaller load (x+c/n)))
4778     SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
4779     if (NarrowLoad.getNode()) {
4780       SDNode* oye = N0.getNode()->getOperand(0).getNode();
4781       if (NarrowLoad.getNode() != N0.getNode()) {
4782         CombineTo(N0.getNode(), NarrowLoad);
4783         // CombineTo deleted the truncate, if needed, but not what's under it.
4784         AddToWorkList(oye);
4785       }
4786       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
4787     }
4788
4789     SDValue Op = N0.getOperand(0);
4790     if (Op.getValueType().bitsLT(VT)) {
4791       Op = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, Op);
4792       AddToWorkList(Op.getNode());
4793     } else if (Op.getValueType().bitsGT(VT)) {
4794       Op = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
4795       AddToWorkList(Op.getNode());
4796     }
4797     return DAG.getZeroExtendInReg(Op, SDLoc(N),
4798                                   N0.getValueType().getScalarType());
4799   }
4800
4801   // Fold (zext (and (trunc x), cst)) -> (and x, cst),
4802   // if either of the casts is not free.
4803   if (N0.getOpcode() == ISD::AND &&
4804       N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
4805       N0.getOperand(1).getOpcode() == ISD::Constant &&
4806       (!TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(),
4807                            N0.getValueType()) ||
4808        !TLI.isZExtFree(N0.getValueType(), VT))) {
4809     SDValue X = N0.getOperand(0).getOperand(0);
4810     if (X.getValueType().bitsLT(VT)) {
4811       X = DAG.getNode(ISD::ANY_EXTEND, SDLoc(X), VT, X);
4812     } else if (X.getValueType().bitsGT(VT)) {
4813       X = DAG.getNode(ISD::TRUNCATE, SDLoc(X), VT, X);
4814     }
4815     APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
4816     Mask = Mask.zext(VT.getSizeInBits());
4817     return DAG.getNode(ISD::AND, SDLoc(N), VT,
4818                        X, DAG.getConstant(Mask, VT));
4819   }
4820
4821   // fold (zext (load x)) -> (zext (truncate (zextload x)))
4822   // None of the supported targets knows how to perform load and vector_zext
4823   // on vectors in one instruction.  We only perform this transformation on
4824   // scalars.
4825   if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() &&
4826       ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
4827        TLI.isLoadExtLegal(ISD::ZEXTLOAD, N0.getValueType()))) {
4828     bool DoXform = true;
4829     SmallVector<SDNode*, 4> SetCCs;
4830     if (!N0.hasOneUse())
4831       DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ZERO_EXTEND, SetCCs, TLI);
4832     if (DoXform) {
4833       LoadSDNode *LN0 = cast<LoadSDNode>(N0);
4834       SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT,
4835                                        LN0->getChain(),
4836                                        LN0->getBasePtr(), LN0->getPointerInfo(),
4837                                        N0.getValueType(),
4838                                        LN0->isVolatile(), LN0->isNonTemporal(),
4839                                        LN0->getAlignment());
4840       CombineTo(N, ExtLoad);
4841       SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
4842                                   N0.getValueType(), ExtLoad);
4843       CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
4844
4845       ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
4846                       ISD::ZERO_EXTEND);
4847       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
4848     }
4849   }
4850
4851   // fold (zext (and/or/xor (load x), cst)) ->
4852   //      (and/or/xor (zextload x), (zext cst))
4853   if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR ||
4854        N0.getOpcode() == ISD::XOR) &&
4855       isa<LoadSDNode>(N0.getOperand(0)) &&
4856       N0.getOperand(1).getOpcode() == ISD::Constant &&
4857       TLI.isLoadExtLegal(ISD::ZEXTLOAD, N0.getValueType()) &&
4858       (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) {
4859     LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0));
4860     if (LN0->getExtensionType() != ISD::SEXTLOAD) {
4861       bool DoXform = true;
4862       SmallVector<SDNode*, 4> SetCCs;
4863       if (!N0.hasOneUse())
4864         DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0), ISD::ZERO_EXTEND,
4865                                           SetCCs, TLI);
4866       if (DoXform) {
4867         SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), VT,
4868                                          LN0->getChain(), LN0->getBasePtr(),
4869                                          LN0->getPointerInfo(),
4870                                          LN0->getMemoryVT(),
4871                                          LN0->isVolatile(),
4872                                          LN0->isNonTemporal(),
4873                                          LN0->getAlignment());
4874         APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
4875         Mask = Mask.zext(VT.getSizeInBits());
4876         SDValue And = DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
4877                                   ExtLoad, DAG.getConstant(Mask, VT));
4878         SDValue Trunc = DAG.getNode(ISD::TRUNCATE,
4879                                     SDLoc(N0.getOperand(0)),
4880                                     N0.getOperand(0).getValueType(), ExtLoad);
4881         CombineTo(N, And);
4882         CombineTo(N0.getOperand(0).getNode(), Trunc, ExtLoad.getValue(1));
4883         ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
4884                         ISD::ZERO_EXTEND);
4885         return SDValue(N, 0);   // Return N so it doesn't get rechecked!
4886       }
4887     }
4888   }
4889
4890   // fold (zext (zextload x)) -> (zext (truncate (zextload x)))
4891   // fold (zext ( extload x)) -> (zext (truncate (zextload x)))
4892   if ((ISD::isZEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) &&
4893       ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) {
4894     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
4895     EVT MemVT = LN0->getMemoryVT();
4896     if ((!LegalOperations && !LN0->isVolatile()) ||
4897         TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT)) {
4898       SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT,
4899                                        LN0->getChain(),
4900                                        LN0->getBasePtr(), LN0->getPointerInfo(),
4901                                        MemVT,
4902                                        LN0->isVolatile(), LN0->isNonTemporal(),
4903                                        LN0->getAlignment());
4904       CombineTo(N, ExtLoad);
4905       CombineTo(N0.getNode(),
4906                 DAG.getNode(ISD::TRUNCATE, SDLoc(N0), N0.getValueType(),
4907                             ExtLoad),
4908                 ExtLoad.getValue(1));
4909       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
4910     }
4911   }
4912
4913   if (N0.getOpcode() == ISD::SETCC) {
4914     if (!LegalOperations && VT.isVector()) {
4915       // zext(setcc) -> (and (vsetcc), (1, 1, ...) for vectors.
4916       // Only do this before legalize for now.
4917       EVT N0VT = N0.getOperand(0).getValueType();
4918       EVT EltVT = VT.getVectorElementType();
4919       SmallVector<SDValue,8> OneOps(VT.getVectorNumElements(),
4920                                     DAG.getConstant(1, EltVT));
4921       if (VT.getSizeInBits() == N0VT.getSizeInBits())
4922         // We know that the # elements of the results is the same as the
4923         // # elements of the compare (and the # elements of the compare result
4924         // for that matter).  Check to see that they are the same size.  If so,
4925         // we know that the element size of the sext'd result matches the
4926         // element size of the compare operands.
4927         return DAG.getNode(ISD::AND, SDLoc(N), VT,
4928                            DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
4929                                          N0.getOperand(1),
4930                                  cast<CondCodeSDNode>(N0.getOperand(2))->get()),
4931                            DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT,
4932                                        &OneOps[0], OneOps.size()));
4933
4934       // If the desired elements are smaller or larger than the source
4935       // elements we can use a matching integer vector type and then
4936       // truncate/sign extend
4937       EVT MatchingElementType =
4938         EVT::getIntegerVT(*DAG.getContext(),
4939                           N0VT.getScalarType().getSizeInBits());
4940       EVT MatchingVectorType =
4941         EVT::getVectorVT(*DAG.getContext(), MatchingElementType,
4942                          N0VT.getVectorNumElements());
4943       SDValue VsetCC =
4944         DAG.getSetCC(SDLoc(N), MatchingVectorType, N0.getOperand(0),
4945                       N0.getOperand(1),
4946                       cast<CondCodeSDNode>(N0.getOperand(2))->get());
4947       return DAG.getNode(ISD::AND, SDLoc(N), VT,
4948                          DAG.getSExtOrTrunc(VsetCC, SDLoc(N), VT),
4949                          DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT,
4950                                      &OneOps[0], OneOps.size()));
4951     }
4952
4953     // zext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
4954     SDValue SCC =
4955       SimplifySelectCC(SDLoc(N), N0.getOperand(0), N0.getOperand(1),
4956                        DAG.getConstant(1, VT), DAG.getConstant(0, VT),
4957                        cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
4958     if (SCC.getNode()) return SCC;
4959   }
4960
4961   // (zext (shl (zext x), cst)) -> (shl (zext x), cst)
4962   if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL) &&
4963       isa<ConstantSDNode>(N0.getOperand(1)) &&
4964       N0.getOperand(0).getOpcode() == ISD::ZERO_EXTEND &&
4965       N0.hasOneUse()) {
4966     SDValue ShAmt = N0.getOperand(1);
4967     unsigned ShAmtVal = cast<ConstantSDNode>(ShAmt)->getZExtValue();
4968     if (N0.getOpcode() == ISD::SHL) {
4969       SDValue InnerZExt = N0.getOperand(0);
4970       // If the original shl may be shifting out bits, do not perform this
4971       // transformation.
4972       unsigned KnownZeroBits = InnerZExt.getValueType().getSizeInBits() -
4973         InnerZExt.getOperand(0).getValueType().getSizeInBits();
4974       if (ShAmtVal > KnownZeroBits)
4975         return SDValue();
4976     }
4977
4978     SDLoc DL(N);
4979
4980     // Ensure that the shift amount is wide enough for the shifted value.
4981     if (VT.getSizeInBits() >= 256)
4982       ShAmt = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, ShAmt);
4983
4984     return DAG.getNode(N0.getOpcode(), DL, VT,
4985                        DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0)),
4986                        ShAmt);
4987   }
4988
4989   return SDValue();
4990 }
4991
4992 SDValue DAGCombiner::visitANY_EXTEND(SDNode *N) {
4993   SDValue N0 = N->getOperand(0);
4994   EVT VT = N->getValueType(0);
4995
4996   // fold (aext c1) -> c1
4997   if (isa<ConstantSDNode>(N0))
4998     return DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, N0);
4999   // fold (aext (aext x)) -> (aext x)
5000   // fold (aext (zext x)) -> (zext x)
5001   // fold (aext (sext x)) -> (sext x)
5002   if (N0.getOpcode() == ISD::ANY_EXTEND  ||
5003       N0.getOpcode() == ISD::ZERO_EXTEND ||
5004       N0.getOpcode() == ISD::SIGN_EXTEND)
5005     return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, N0.getOperand(0));
5006
5007   // fold (aext (truncate (load x))) -> (aext (smaller load x))
5008   // fold (aext (truncate (srl (load x), c))) -> (aext (small load (x+c/n)))
5009   if (N0.getOpcode() == ISD::TRUNCATE) {
5010     SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
5011     if (NarrowLoad.getNode()) {
5012       SDNode* oye = N0.getNode()->getOperand(0).getNode();
5013       if (NarrowLoad.getNode() != N0.getNode()) {
5014         CombineTo(N0.getNode(), NarrowLoad);
5015         // CombineTo deleted the truncate, if needed, but not what's under it.
5016         AddToWorkList(oye);
5017       }
5018       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5019     }
5020   }
5021
5022   // fold (aext (truncate x))
5023   if (N0.getOpcode() == ISD::TRUNCATE) {
5024     SDValue TruncOp = N0.getOperand(0);
5025     if (TruncOp.getValueType() == VT)
5026       return TruncOp; // x iff x size == zext size.
5027     if (TruncOp.getValueType().bitsGT(VT))
5028       return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, TruncOp);
5029     return DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, TruncOp);
5030   }
5031
5032   // Fold (aext (and (trunc x), cst)) -> (and x, cst)
5033   // if the trunc is not free.
5034   if (N0.getOpcode() == ISD::AND &&
5035       N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
5036       N0.getOperand(1).getOpcode() == ISD::Constant &&
5037       !TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(),
5038                           N0.getValueType())) {
5039     SDValue X = N0.getOperand(0).getOperand(0);
5040     if (X.getValueType().bitsLT(VT)) {
5041       X = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, X);
5042     } else if (X.getValueType().bitsGT(VT)) {
5043       X = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, X);
5044     }
5045     APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
5046     Mask = Mask.zext(VT.getSizeInBits());
5047     return DAG.getNode(ISD::AND, SDLoc(N), VT,
5048                        X, DAG.getConstant(Mask, VT));
5049   }
5050
5051   // fold (aext (load x)) -> (aext (truncate (extload x)))
5052   // None of the supported targets knows how to perform load and any_ext
5053   // on vectors in one instruction.  We only perform this transformation on
5054   // scalars.
5055   if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() &&
5056       ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
5057        TLI.isLoadExtLegal(ISD::EXTLOAD, N0.getValueType()))) {
5058     bool DoXform = true;
5059     SmallVector<SDNode*, 4> SetCCs;
5060     if (!N0.hasOneUse())
5061       DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ANY_EXTEND, SetCCs, TLI);
5062     if (DoXform) {
5063       LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5064       SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT,
5065                                        LN0->getChain(),
5066                                        LN0->getBasePtr(), LN0->getPointerInfo(),
5067                                        N0.getValueType(),
5068                                        LN0->isVolatile(), LN0->isNonTemporal(),
5069                                        LN0->getAlignment());
5070       CombineTo(N, ExtLoad);
5071       SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
5072                                   N0.getValueType(), ExtLoad);
5073       CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
5074       ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
5075                       ISD::ANY_EXTEND);
5076       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5077     }
5078   }
5079
5080   // fold (aext (zextload x)) -> (aext (truncate (zextload x)))
5081   // fold (aext (sextload x)) -> (aext (truncate (sextload x)))
5082   // fold (aext ( extload x)) -> (aext (truncate (extload  x)))
5083   if (N0.getOpcode() == ISD::LOAD &&
5084       !ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
5085       N0.hasOneUse()) {
5086     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5087     EVT MemVT = LN0->getMemoryVT();
5088     SDValue ExtLoad = DAG.getExtLoad(LN0->getExtensionType(), SDLoc(N),
5089                                      VT, LN0->getChain(), LN0->getBasePtr(),
5090                                      LN0->getPointerInfo(), MemVT,
5091                                      LN0->isVolatile(), LN0->isNonTemporal(),
5092                                      LN0->getAlignment());
5093     CombineTo(N, ExtLoad);
5094     CombineTo(N0.getNode(),
5095               DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
5096                           N0.getValueType(), ExtLoad),
5097               ExtLoad.getValue(1));
5098     return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5099   }
5100
5101   if (N0.getOpcode() == ISD::SETCC) {
5102     // aext(setcc) -> sext_in_reg(vsetcc) for vectors.
5103     // Only do this before legalize for now.
5104     if (VT.isVector() && !LegalOperations) {
5105       EVT N0VT = N0.getOperand(0).getValueType();
5106         // We know that the # elements of the results is the same as the
5107         // # elements of the compare (and the # elements of the compare result
5108         // for that matter).  Check to see that they are the same size.  If so,
5109         // we know that the element size of the sext'd result matches the
5110         // element size of the compare operands.
5111       if (VT.getSizeInBits() == N0VT.getSizeInBits())
5112         return DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
5113                              N0.getOperand(1),
5114                              cast<CondCodeSDNode>(N0.getOperand(2))->get());
5115       // If the desired elements are smaller or larger than the source
5116       // elements we can use a matching integer vector type and then
5117       // truncate/sign extend
5118       else {
5119         EVT MatchingElementType =
5120           EVT::getIntegerVT(*DAG.getContext(),
5121                             N0VT.getScalarType().getSizeInBits());
5122         EVT MatchingVectorType =
5123           EVT::getVectorVT(*DAG.getContext(), MatchingElementType,
5124                            N0VT.getVectorNumElements());
5125         SDValue VsetCC =
5126           DAG.getSetCC(SDLoc(N), MatchingVectorType, N0.getOperand(0),
5127                         N0.getOperand(1),
5128                         cast<CondCodeSDNode>(N0.getOperand(2))->get());
5129         return DAG.getSExtOrTrunc(VsetCC, SDLoc(N), VT);
5130       }
5131     }
5132
5133     // aext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
5134     SDValue SCC =
5135       SimplifySelectCC(SDLoc(N), N0.getOperand(0), N0.getOperand(1),
5136                        DAG.getConstant(1, VT), DAG.getConstant(0, VT),
5137                        cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
5138     if (SCC.getNode())
5139       return SCC;
5140   }
5141
5142   return SDValue();
5143 }
5144
5145 /// GetDemandedBits - See if the specified operand can be simplified with the
5146 /// knowledge that only the bits specified by Mask are used.  If so, return the
5147 /// simpler operand, otherwise return a null SDValue.
5148 SDValue DAGCombiner::GetDemandedBits(SDValue V, const APInt &Mask) {
5149   switch (V.getOpcode()) {
5150   default: break;
5151   case ISD::Constant: {
5152     const ConstantSDNode *CV = cast<ConstantSDNode>(V.getNode());
5153     assert(CV != 0 && "Const value should be ConstSDNode.");
5154     const APInt &CVal = CV->getAPIntValue();
5155     APInt NewVal = CVal & Mask;
5156     if (NewVal != CVal)
5157       return DAG.getConstant(NewVal, V.getValueType());
5158     break;
5159   }
5160   case ISD::OR:
5161   case ISD::XOR:
5162     // If the LHS or RHS don't contribute bits to the or, drop them.
5163     if (DAG.MaskedValueIsZero(V.getOperand(0), Mask))
5164       return V.getOperand(1);
5165     if (DAG.MaskedValueIsZero(V.getOperand(1), Mask))
5166       return V.getOperand(0);
5167     break;
5168   case ISD::SRL:
5169     // Only look at single-use SRLs.
5170     if (!V.getNode()->hasOneUse())
5171       break;
5172     if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(V.getOperand(1))) {
5173       // See if we can recursively simplify the LHS.
5174       unsigned Amt = RHSC->getZExtValue();
5175
5176       // Watch out for shift count overflow though.
5177       if (Amt >= Mask.getBitWidth()) break;
5178       APInt NewMask = Mask << Amt;
5179       SDValue SimplifyLHS = GetDemandedBits(V.getOperand(0), NewMask);
5180       if (SimplifyLHS.getNode())
5181         return DAG.getNode(ISD::SRL, SDLoc(V), V.getValueType(),
5182                            SimplifyLHS, V.getOperand(1));
5183     }
5184   }
5185   return SDValue();
5186 }
5187
5188 /// ReduceLoadWidth - If the result of a wider load is shifted to right of N
5189 /// bits and then truncated to a narrower type and where N is a multiple
5190 /// of number of bits of the narrower type, transform it to a narrower load
5191 /// from address + N / num of bits of new type. If the result is to be
5192 /// extended, also fold the extension to form a extending load.
5193 SDValue DAGCombiner::ReduceLoadWidth(SDNode *N) {
5194   unsigned Opc = N->getOpcode();
5195
5196   ISD::LoadExtType ExtType = ISD::NON_EXTLOAD;
5197   SDValue N0 = N->getOperand(0);
5198   EVT VT = N->getValueType(0);
5199   EVT ExtVT = VT;
5200
5201   // This transformation isn't valid for vector loads.
5202   if (VT.isVector())
5203     return SDValue();
5204
5205   // Special case: SIGN_EXTEND_INREG is basically truncating to ExtVT then
5206   // extended to VT.
5207   if (Opc == ISD::SIGN_EXTEND_INREG) {
5208     ExtType = ISD::SEXTLOAD;
5209     ExtVT = cast<VTSDNode>(N->getOperand(1))->getVT();
5210   } else if (Opc == ISD::SRL) {
5211     // Another special-case: SRL is basically zero-extending a narrower value.
5212     ExtType = ISD::ZEXTLOAD;
5213     N0 = SDValue(N, 0);
5214     ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1));
5215     if (!N01) return SDValue();
5216     ExtVT = EVT::getIntegerVT(*DAG.getContext(),
5217                               VT.getSizeInBits() - N01->getZExtValue());
5218   }
5219   if (LegalOperations && !TLI.isLoadExtLegal(ExtType, ExtVT))
5220     return SDValue();
5221
5222   unsigned EVTBits = ExtVT.getSizeInBits();
5223
5224   // Do not generate loads of non-round integer types since these can
5225   // be expensive (and would be wrong if the type is not byte sized).
5226   if (!ExtVT.isRound())
5227     return SDValue();
5228
5229   unsigned ShAmt = 0;
5230   if (N0.getOpcode() == ISD::SRL && N0.hasOneUse()) {
5231     if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
5232       ShAmt = N01->getZExtValue();
5233       // Is the shift amount a multiple of size of VT?
5234       if ((ShAmt & (EVTBits-1)) == 0) {
5235         N0 = N0.getOperand(0);
5236         // Is the load width a multiple of size of VT?
5237         if ((N0.getValueType().getSizeInBits() & (EVTBits-1)) != 0)
5238           return SDValue();
5239       }
5240
5241       // At this point, we must have a load or else we can't do the transform.
5242       if (!isa<LoadSDNode>(N0)) return SDValue();
5243
5244       // Because a SRL must be assumed to *need* to zero-extend the high bits
5245       // (as opposed to anyext the high bits), we can't combine the zextload
5246       // lowering of SRL and an sextload.
5247       if (cast<LoadSDNode>(N0)->getExtensionType() == ISD::SEXTLOAD)
5248         return SDValue();
5249
5250       // If the shift amount is larger than the input type then we're not
5251       // accessing any of the loaded bytes.  If the load was a zextload/extload
5252       // then the result of the shift+trunc is zero/undef (handled elsewhere).
5253       if (ShAmt >= cast<LoadSDNode>(N0)->getMemoryVT().getSizeInBits())
5254         return SDValue();
5255     }
5256   }
5257
5258   // If the load is shifted left (and the result isn't shifted back right),
5259   // we can fold the truncate through the shift.
5260   unsigned ShLeftAmt = 0;
5261   if (ShAmt == 0 && N0.getOpcode() == ISD::SHL && N0.hasOneUse() &&
5262       ExtVT == VT && TLI.isNarrowingProfitable(N0.getValueType(), VT)) {
5263     if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
5264       ShLeftAmt = N01->getZExtValue();
5265       N0 = N0.getOperand(0);
5266     }
5267   }
5268
5269   // If we haven't found a load, we can't narrow it.  Don't transform one with
5270   // multiple uses, this would require adding a new load.
5271   if (!isa<LoadSDNode>(N0) || !N0.hasOneUse())
5272     return SDValue();
5273
5274   // Don't change the width of a volatile load.
5275   LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5276   if (LN0->isVolatile())
5277     return SDValue();
5278
5279   // Verify that we are actually reducing a load width here.
5280   if (LN0->getMemoryVT().getSizeInBits() < EVTBits)
5281     return SDValue();
5282
5283   // For the transform to be legal, the load must produce only two values
5284   // (the value loaded and the chain).  Don't transform a pre-increment
5285   // load, for example, which produces an extra value.  Otherwise the
5286   // transformation is not equivalent, and the downstream logic to replace
5287   // uses gets things wrong.
5288   if (LN0->getNumValues() > 2)
5289     return SDValue();
5290
5291   // If the load that we're shrinking is an extload and we're not just
5292   // discarding the extension we can't simply shrink the load. Bail.
5293   // TODO: It would be possible to merge the extensions in some cases.
5294   if (LN0->getExtensionType() != ISD::NON_EXTLOAD &&
5295       LN0->getMemoryVT().getSizeInBits() < ExtVT.getSizeInBits() + ShAmt)
5296     return SDValue();
5297
5298   EVT PtrType = N0.getOperand(1).getValueType();
5299
5300   if (PtrType == MVT::Untyped || PtrType.isExtended())
5301     // It's not possible to generate a constant of extended or untyped type.
5302     return SDValue();
5303
5304   // For big endian targets, we need to adjust the offset to the pointer to
5305   // load the correct bytes.
5306   if (TLI.isBigEndian()) {
5307     unsigned LVTStoreBits = LN0->getMemoryVT().getStoreSizeInBits();
5308     unsigned EVTStoreBits = ExtVT.getStoreSizeInBits();
5309     ShAmt = LVTStoreBits - EVTStoreBits - ShAmt;
5310   }
5311
5312   uint64_t PtrOff = ShAmt / 8;
5313   unsigned NewAlign = MinAlign(LN0->getAlignment(), PtrOff);
5314   SDValue NewPtr = DAG.getNode(ISD::ADD, SDLoc(LN0),
5315                                PtrType, LN0->getBasePtr(),
5316                                DAG.getConstant(PtrOff, PtrType));
5317   AddToWorkList(NewPtr.getNode());
5318
5319   SDValue Load;
5320   if (ExtType == ISD::NON_EXTLOAD)
5321     Load =  DAG.getLoad(VT, SDLoc(N0), LN0->getChain(), NewPtr,
5322                         LN0->getPointerInfo().getWithOffset(PtrOff),
5323                         LN0->isVolatile(), LN0->isNonTemporal(),
5324                         LN0->isInvariant(), NewAlign);
5325   else
5326     Load = DAG.getExtLoad(ExtType, SDLoc(N0), VT, LN0->getChain(),NewPtr,
5327                           LN0->getPointerInfo().getWithOffset(PtrOff),
5328                           ExtVT, LN0->isVolatile(), LN0->isNonTemporal(),
5329                           NewAlign);
5330
5331   // Replace the old load's chain with the new load's chain.
5332   WorkListRemover DeadNodes(*this);
5333   DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1));
5334
5335   // Shift the result left, if we've swallowed a left shift.
5336   SDValue Result = Load;
5337   if (ShLeftAmt != 0) {
5338     EVT ShImmTy = getShiftAmountTy(Result.getValueType());
5339     if (!isUIntN(ShImmTy.getSizeInBits(), ShLeftAmt))
5340       ShImmTy = VT;
5341     // If the shift amount is as large as the result size (but, presumably,
5342     // no larger than the source) then the useful bits of the result are
5343     // zero; we can't simply return the shortened shift, because the result
5344     // of that operation is undefined.
5345     if (ShLeftAmt >= VT.getSizeInBits())
5346       Result = DAG.getConstant(0, VT);
5347     else
5348       Result = DAG.getNode(ISD::SHL, SDLoc(N0), VT,
5349                           Result, DAG.getConstant(ShLeftAmt, ShImmTy));
5350   }
5351
5352   // Return the new loaded value.
5353   return Result;
5354 }
5355
5356 SDValue DAGCombiner::visitSIGN_EXTEND_INREG(SDNode *N) {
5357   SDValue N0 = N->getOperand(0);
5358   SDValue N1 = N->getOperand(1);
5359   EVT VT = N->getValueType(0);
5360   EVT EVT = cast<VTSDNode>(N1)->getVT();
5361   unsigned VTBits = VT.getScalarType().getSizeInBits();
5362   unsigned EVTBits = EVT.getScalarType().getSizeInBits();
5363
5364   // fold (sext_in_reg c1) -> c1
5365   if (isa<ConstantSDNode>(N0) || N0.getOpcode() == ISD::UNDEF)
5366     return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, N0, N1);
5367
5368   // If the input is already sign extended, just drop the extension.
5369   if (DAG.ComputeNumSignBits(N0) >= VTBits-EVTBits+1)
5370     return N0;
5371
5372   // fold (sext_in_reg (sext_in_reg x, VT2), VT1) -> (sext_in_reg x, minVT) pt2
5373   if (N0.getOpcode() == ISD::SIGN_EXTEND_INREG &&
5374       EVT.bitsLT(cast<VTSDNode>(N0.getOperand(1))->getVT()))
5375     return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
5376                        N0.getOperand(0), N1);
5377
5378   // fold (sext_in_reg (sext x)) -> (sext x)
5379   // fold (sext_in_reg (aext x)) -> (sext x)
5380   // if x is small enough.
5381   if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND) {
5382     SDValue N00 = N0.getOperand(0);
5383     if (N00.getValueType().getScalarType().getSizeInBits() <= EVTBits &&
5384         (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND, VT)))
5385       return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, N00, N1);
5386   }
5387
5388   // fold (sext_in_reg x) -> (zext_in_reg x) if the sign bit is known zero.
5389   if (DAG.MaskedValueIsZero(N0, APInt::getBitsSet(VTBits, EVTBits-1, EVTBits)))
5390     return DAG.getZeroExtendInReg(N0, SDLoc(N), EVT);
5391
5392   // fold operands of sext_in_reg based on knowledge that the top bits are not
5393   // demanded.
5394   if (SimplifyDemandedBits(SDValue(N, 0)))
5395     return SDValue(N, 0);
5396
5397   // fold (sext_in_reg (load x)) -> (smaller sextload x)
5398   // fold (sext_in_reg (srl (load x), c)) -> (smaller sextload (x+c/evtbits))
5399   SDValue NarrowLoad = ReduceLoadWidth(N);
5400   if (NarrowLoad.getNode())
5401     return NarrowLoad;
5402
5403   // fold (sext_in_reg (srl X, 24), i8) -> (sra X, 24)
5404   // fold (sext_in_reg (srl X, 23), i8) -> (sra X, 23) iff possible.
5405   // We already fold "(sext_in_reg (srl X, 25), i8) -> srl X, 25" above.
5406   if (N0.getOpcode() == ISD::SRL) {
5407     if (ConstantSDNode *ShAmt = dyn_cast<ConstantSDNode>(N0.getOperand(1)))
5408       if (ShAmt->getZExtValue()+EVTBits <= VTBits) {
5409         // We can turn this into an SRA iff the input to the SRL is already sign
5410         // extended enough.
5411         unsigned InSignBits = DAG.ComputeNumSignBits(N0.getOperand(0));
5412         if (VTBits-(ShAmt->getZExtValue()+EVTBits) < InSignBits)
5413           return DAG.getNode(ISD::SRA, SDLoc(N), VT,
5414                              N0.getOperand(0), N0.getOperand(1));
5415       }
5416   }
5417
5418   // fold (sext_inreg (extload x)) -> (sextload x)
5419   if (ISD::isEXTLoad(N0.getNode()) &&
5420       ISD::isUNINDEXEDLoad(N0.getNode()) &&
5421       EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
5422       ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
5423        TLI.isLoadExtLegal(ISD::SEXTLOAD, EVT))) {
5424     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5425     SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
5426                                      LN0->getChain(),
5427                                      LN0->getBasePtr(), LN0->getPointerInfo(),
5428                                      EVT,
5429                                      LN0->isVolatile(), LN0->isNonTemporal(),
5430                                      LN0->getAlignment());
5431     CombineTo(N, ExtLoad);
5432     CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
5433     AddToWorkList(ExtLoad.getNode());
5434     return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5435   }
5436   // fold (sext_inreg (zextload x)) -> (sextload x) iff load has one use
5437   if (ISD::isZEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
5438       N0.hasOneUse() &&
5439       EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
5440       ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
5441        TLI.isLoadExtLegal(ISD::SEXTLOAD, EVT))) {
5442     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5443     SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
5444                                      LN0->getChain(),
5445                                      LN0->getBasePtr(), LN0->getPointerInfo(),
5446                                      EVT,
5447                                      LN0->isVolatile(), LN0->isNonTemporal(),
5448                                      LN0->getAlignment());
5449     CombineTo(N, ExtLoad);
5450     CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
5451     return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5452   }
5453
5454   // Form (sext_inreg (bswap >> 16)) or (sext_inreg (rotl (bswap) 16))
5455   if (EVTBits <= 16 && N0.getOpcode() == ISD::OR) {
5456     SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0),
5457                                        N0.getOperand(1), false);
5458     if (BSwap.getNode() != 0)
5459       return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
5460                          BSwap, N1);
5461   }
5462
5463   return SDValue();
5464 }
5465
5466 SDValue DAGCombiner::visitTRUNCATE(SDNode *N) {
5467   SDValue N0 = N->getOperand(0);
5468   EVT VT = N->getValueType(0);
5469   bool isLE = TLI.isLittleEndian();
5470
5471   // noop truncate
5472   if (N0.getValueType() == N->getValueType(0))
5473     return N0;
5474   // fold (truncate c1) -> c1
5475   if (isa<ConstantSDNode>(N0))
5476     return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0);
5477   // fold (truncate (truncate x)) -> (truncate x)
5478   if (N0.getOpcode() == ISD::TRUNCATE)
5479     return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0));
5480   // fold (truncate (ext x)) -> (ext x) or (truncate x) or x
5481   if (N0.getOpcode() == ISD::ZERO_EXTEND ||
5482       N0.getOpcode() == ISD::SIGN_EXTEND ||
5483       N0.getOpcode() == ISD::ANY_EXTEND) {
5484     if (N0.getOperand(0).getValueType().bitsLT(VT))
5485       // if the source is smaller than the dest, we still need an extend
5486       return DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
5487                          N0.getOperand(0));
5488     if (N0.getOperand(0).getValueType().bitsGT(VT))
5489       // if the source is larger than the dest, than we just need the truncate
5490       return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0));
5491     // if the source and dest are the same type, we can drop both the extend
5492     // and the truncate.
5493     return N0.getOperand(0);
5494   }
5495
5496   // Fold extract-and-trunc into a narrow extract. For example:
5497   //   i64 x = EXTRACT_VECTOR_ELT(v2i64 val, i32 1)
5498   //   i32 y = TRUNCATE(i64 x)
5499   //        -- becomes --
5500   //   v16i8 b = BITCAST (v2i64 val)
5501   //   i8 x = EXTRACT_VECTOR_ELT(v16i8 b, i32 8)
5502   //
5503   // Note: We only run this optimization after type legalization (which often
5504   // creates this pattern) and before operation legalization after which
5505   // we need to be more careful about the vector instructions that we generate.
5506   if (N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
5507       LegalTypes && !LegalOperations && N0->hasOneUse()) {
5508
5509     EVT VecTy = N0.getOperand(0).getValueType();
5510     EVT ExTy = N0.getValueType();
5511     EVT TrTy = N->getValueType(0);
5512
5513     unsigned NumElem = VecTy.getVectorNumElements();
5514     unsigned SizeRatio = ExTy.getSizeInBits()/TrTy.getSizeInBits();
5515
5516     EVT NVT = EVT::getVectorVT(*DAG.getContext(), TrTy, SizeRatio * NumElem);
5517     assert(NVT.getSizeInBits() == VecTy.getSizeInBits() && "Invalid Size");
5518
5519     SDValue EltNo = N0->getOperand(1);
5520     if (isa<ConstantSDNode>(EltNo) && isTypeLegal(NVT)) {
5521       int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
5522       EVT IndexTy = TLI.getVectorIdxTy();
5523       int Index = isLE ? (Elt*SizeRatio) : (Elt*SizeRatio + (SizeRatio-1));
5524
5525       SDValue V = DAG.getNode(ISD::BITCAST, SDLoc(N),
5526                               NVT, N0.getOperand(0));
5527
5528       return DAG.getNode(ISD::EXTRACT_VECTOR_ELT,
5529                          SDLoc(N), TrTy, V,
5530                          DAG.getConstant(Index, IndexTy));
5531     }
5532   }
5533
5534   // Fold a series of buildvector, bitcast, and truncate if possible.
5535   // For example fold
5536   //   (2xi32 trunc (bitcast ((4xi32)buildvector x, x, y, y) 2xi64)) to
5537   //   (2xi32 (buildvector x, y)).
5538   if (Level == AfterLegalizeVectorOps && VT.isVector() &&
5539       N0.getOpcode() == ISD::BITCAST && N0.hasOneUse() &&
5540       N0.getOperand(0).getOpcode() == ISD::BUILD_VECTOR &&
5541       N0.getOperand(0).hasOneUse()) {
5542
5543     SDValue BuildVect = N0.getOperand(0);
5544     EVT BuildVectEltTy = BuildVect.getValueType().getVectorElementType();
5545     EVT TruncVecEltTy = VT.getVectorElementType();
5546
5547     // Check that the element types match.
5548     if (BuildVectEltTy == TruncVecEltTy) {
5549       // Now we only need to compute the offset of the truncated elements.
5550       unsigned BuildVecNumElts =  BuildVect.getNumOperands();
5551       unsigned TruncVecNumElts = VT.getVectorNumElements();
5552       unsigned TruncEltOffset = BuildVecNumElts / TruncVecNumElts;
5553
5554       assert((BuildVecNumElts % TruncVecNumElts) == 0 &&
5555              "Invalid number of elements");
5556
5557       SmallVector<SDValue, 8> Opnds;
5558       for (unsigned i = 0, e = BuildVecNumElts; i != e; i += TruncEltOffset)
5559         Opnds.push_back(BuildVect.getOperand(i));
5560
5561       return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, &Opnds[0],
5562                          Opnds.size());
5563     }
5564   }
5565
5566   // See if we can simplify the input to this truncate through knowledge that
5567   // only the low bits are being used.
5568   // For example "trunc (or (shl x, 8), y)" // -> trunc y
5569   // Currently we only perform this optimization on scalars because vectors
5570   // may have different active low bits.
5571   if (!VT.isVector()) {
5572     SDValue Shorter =
5573       GetDemandedBits(N0, APInt::getLowBitsSet(N0.getValueSizeInBits(),
5574                                                VT.getSizeInBits()));
5575     if (Shorter.getNode())
5576       return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Shorter);
5577   }
5578   // fold (truncate (load x)) -> (smaller load x)
5579   // fold (truncate (srl (load x), c)) -> (smaller load (x+c/evtbits))
5580   if (!LegalTypes || TLI.isTypeDesirableForOp(N0.getOpcode(), VT)) {
5581     SDValue Reduced = ReduceLoadWidth(N);
5582     if (Reduced.getNode())
5583       return Reduced;
5584   }
5585   // fold (trunc (concat ... x ...)) -> (concat ..., (trunc x), ...)),
5586   // where ... are all 'undef'.
5587   if (N0.getOpcode() == ISD::CONCAT_VECTORS && !LegalTypes) {
5588     SmallVector<EVT, 8> VTs;
5589     SDValue V;
5590     unsigned Idx = 0;
5591     unsigned NumDefs = 0;
5592
5593     for (unsigned i = 0, e = N0.getNumOperands(); i != e; ++i) {
5594       SDValue X = N0.getOperand(i);
5595       if (X.getOpcode() != ISD::UNDEF) {
5596         V = X;
5597         Idx = i;
5598         NumDefs++;
5599       }
5600       // Stop if more than one members are non-undef.
5601       if (NumDefs > 1)
5602         break;
5603       VTs.push_back(EVT::getVectorVT(*DAG.getContext(),
5604                                      VT.getVectorElementType(),
5605                                      X.getValueType().getVectorNumElements()));
5606     }
5607
5608     if (NumDefs == 0)
5609       return DAG.getUNDEF(VT);
5610
5611     if (NumDefs == 1) {
5612       assert(V.getNode() && "The single defined operand is empty!");
5613       SmallVector<SDValue, 8> Opnds;
5614       for (unsigned i = 0, e = VTs.size(); i != e; ++i) {
5615         if (i != Idx) {
5616           Opnds.push_back(DAG.getUNDEF(VTs[i]));
5617           continue;
5618         }
5619         SDValue NV = DAG.getNode(ISD::TRUNCATE, SDLoc(V), VTs[i], V);
5620         AddToWorkList(NV.getNode());
5621         Opnds.push_back(NV);
5622       }
5623       return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
5624                          &Opnds[0], Opnds.size());
5625     }
5626   }
5627
5628   // Simplify the operands using demanded-bits information.
5629   if (!VT.isVector() &&
5630       SimplifyDemandedBits(SDValue(N, 0)))
5631     return SDValue(N, 0);
5632
5633   return SDValue();
5634 }
5635
5636 static SDNode *getBuildPairElt(SDNode *N, unsigned i) {
5637   SDValue Elt = N->getOperand(i);
5638   if (Elt.getOpcode() != ISD::MERGE_VALUES)
5639     return Elt.getNode();
5640   return Elt.getOperand(Elt.getResNo()).getNode();
5641 }
5642
5643 /// CombineConsecutiveLoads - build_pair (load, load) -> load
5644 /// if load locations are consecutive.
5645 SDValue DAGCombiner::CombineConsecutiveLoads(SDNode *N, EVT VT) {
5646   assert(N->getOpcode() == ISD::BUILD_PAIR);
5647
5648   LoadSDNode *LD1 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 0));
5649   LoadSDNode *LD2 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 1));
5650   if (!LD1 || !LD2 || !ISD::isNON_EXTLoad(LD1) || !LD1->hasOneUse() ||
5651       LD1->getPointerInfo().getAddrSpace() !=
5652          LD2->getPointerInfo().getAddrSpace())
5653     return SDValue();
5654   EVT LD1VT = LD1->getValueType(0);
5655
5656   if (ISD::isNON_EXTLoad(LD2) &&
5657       LD2->hasOneUse() &&
5658       // If both are volatile this would reduce the number of volatile loads.
5659       // If one is volatile it might be ok, but play conservative and bail out.
5660       !LD1->isVolatile() &&
5661       !LD2->isVolatile() &&
5662       DAG.isConsecutiveLoad(LD2, LD1, LD1VT.getSizeInBits()/8, 1)) {
5663     unsigned Align = LD1->getAlignment();
5664     unsigned NewAlign = TLI.getDataLayout()->
5665       getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
5666
5667     if (NewAlign <= Align &&
5668         (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT)))
5669       return DAG.getLoad(VT, SDLoc(N), LD1->getChain(),
5670                          LD1->getBasePtr(), LD1->getPointerInfo(),
5671                          false, false, false, Align);
5672   }
5673
5674   return SDValue();
5675 }
5676
5677 SDValue DAGCombiner::visitBITCAST(SDNode *N) {
5678   SDValue N0 = N->getOperand(0);
5679   EVT VT = N->getValueType(0);
5680
5681   // If the input is a BUILD_VECTOR with all constant elements, fold this now.
5682   // Only do this before legalize, since afterward the target may be depending
5683   // on the bitconvert.
5684   // First check to see if this is all constant.
5685   if (!LegalTypes &&
5686       N0.getOpcode() == ISD::BUILD_VECTOR && N0.getNode()->hasOneUse() &&
5687       VT.isVector()) {
5688     bool isSimple = true;
5689     for (unsigned i = 0, e = N0.getNumOperands(); i != e; ++i)
5690       if (N0.getOperand(i).getOpcode() != ISD::UNDEF &&
5691           N0.getOperand(i).getOpcode() != ISD::Constant &&
5692           N0.getOperand(i).getOpcode() != ISD::ConstantFP) {
5693         isSimple = false;
5694         break;
5695       }
5696
5697     EVT DestEltVT = N->getValueType(0).getVectorElementType();
5698     assert(!DestEltVT.isVector() &&
5699            "Element type of vector ValueType must not be vector!");
5700     if (isSimple)
5701       return ConstantFoldBITCASTofBUILD_VECTOR(N0.getNode(), DestEltVT);
5702   }
5703
5704   // If the input is a constant, let getNode fold it.
5705   if (isa<ConstantSDNode>(N0) || isa<ConstantFPSDNode>(N0)) {
5706     SDValue Res = DAG.getNode(ISD::BITCAST, SDLoc(N), VT, N0);
5707     if (Res.getNode() != N) {
5708       if (!LegalOperations ||
5709           TLI.isOperationLegal(Res.getNode()->getOpcode(), VT))
5710         return Res;
5711
5712       // Folding it resulted in an illegal node, and it's too late to
5713       // do that. Clean up the old node and forego the transformation.
5714       // Ideally this won't happen very often, because instcombine
5715       // and the earlier dagcombine runs (where illegal nodes are
5716       // permitted) should have folded most of them already.
5717       DAG.DeleteNode(Res.getNode());
5718     }
5719   }
5720
5721   // (conv (conv x, t1), t2) -> (conv x, t2)
5722   if (N0.getOpcode() == ISD::BITCAST)
5723     return DAG.getNode(ISD::BITCAST, SDLoc(N), VT,
5724                        N0.getOperand(0));
5725
5726   // fold (conv (load x)) -> (load (conv*)x)
5727   // If the resultant load doesn't need a higher alignment than the original!
5728   if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
5729       // Do not change the width of a volatile load.
5730       !cast<LoadSDNode>(N0)->isVolatile() &&
5731       (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT))) {
5732     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5733     unsigned Align = TLI.getDataLayout()->
5734       getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
5735     unsigned OrigAlign = LN0->getAlignment();
5736
5737     if (Align <= OrigAlign) {
5738       SDValue Load = DAG.getLoad(VT, SDLoc(N), LN0->getChain(),
5739                                  LN0->getBasePtr(), LN0->getPointerInfo(),
5740                                  LN0->isVolatile(), LN0->isNonTemporal(),
5741                                  LN0->isInvariant(), OrigAlign);
5742       AddToWorkList(N);
5743       CombineTo(N0.getNode(),
5744                 DAG.getNode(ISD::BITCAST, SDLoc(N0),
5745                             N0.getValueType(), Load),
5746                 Load.getValue(1));
5747       return Load;
5748     }
5749   }
5750
5751   // fold (bitconvert (fneg x)) -> (xor (bitconvert x), signbit)
5752   // fold (bitconvert (fabs x)) -> (and (bitconvert x), (not signbit))
5753   // This often reduces constant pool loads.
5754   if (((N0.getOpcode() == ISD::FNEG && !TLI.isFNegFree(N0.getValueType())) ||
5755        (N0.getOpcode() == ISD::FABS && !TLI.isFAbsFree(N0.getValueType()))) &&
5756       N0.getNode()->hasOneUse() && VT.isInteger() &&
5757       !VT.isVector() && !N0.getValueType().isVector()) {
5758     SDValue NewConv = DAG.getNode(ISD::BITCAST, SDLoc(N0), VT,
5759                                   N0.getOperand(0));
5760     AddToWorkList(NewConv.getNode());
5761
5762     APInt SignBit = APInt::getSignBit(VT.getSizeInBits());
5763     if (N0.getOpcode() == ISD::FNEG)
5764       return DAG.getNode(ISD::XOR, SDLoc(N), VT,
5765                          NewConv, DAG.getConstant(SignBit, VT));
5766     assert(N0.getOpcode() == ISD::FABS);
5767     return DAG.getNode(ISD::AND, SDLoc(N), VT,
5768                        NewConv, DAG.getConstant(~SignBit, VT));
5769   }
5770
5771   // fold (bitconvert (fcopysign cst, x)) ->
5772   //         (or (and (bitconvert x), sign), (and cst, (not sign)))
5773   // Note that we don't handle (copysign x, cst) because this can always be
5774   // folded to an fneg or fabs.
5775   if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse() &&
5776       isa<ConstantFPSDNode>(N0.getOperand(0)) &&
5777       VT.isInteger() && !VT.isVector()) {
5778     unsigned OrigXWidth = N0.getOperand(1).getValueType().getSizeInBits();
5779     EVT IntXVT = EVT::getIntegerVT(*DAG.getContext(), OrigXWidth);
5780     if (isTypeLegal(IntXVT)) {
5781       SDValue X = DAG.getNode(ISD::BITCAST, SDLoc(N0),
5782                               IntXVT, N0.getOperand(1));
5783       AddToWorkList(X.getNode());
5784
5785       // If X has a different width than the result/lhs, sext it or truncate it.
5786       unsigned VTWidth = VT.getSizeInBits();
5787       if (OrigXWidth < VTWidth) {
5788         X = DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, X);
5789         AddToWorkList(X.getNode());
5790       } else if (OrigXWidth > VTWidth) {
5791         // To get the sign bit in the right place, we have to shift it right
5792         // before truncating.
5793         X = DAG.getNode(ISD::SRL, SDLoc(X),
5794                         X.getValueType(), X,
5795                         DAG.getConstant(OrigXWidth-VTWidth, X.getValueType()));
5796         AddToWorkList(X.getNode());
5797         X = DAG.getNode(ISD::TRUNCATE, SDLoc(X), VT, X);
5798         AddToWorkList(X.getNode());
5799       }
5800
5801       APInt SignBit = APInt::getSignBit(VT.getSizeInBits());
5802       X = DAG.getNode(ISD::AND, SDLoc(X), VT,
5803                       X, DAG.getConstant(SignBit, VT));
5804       AddToWorkList(X.getNode());
5805
5806       SDValue Cst = DAG.getNode(ISD::BITCAST, SDLoc(N0),
5807                                 VT, N0.getOperand(0));
5808       Cst = DAG.getNode(ISD::AND, SDLoc(Cst), VT,
5809                         Cst, DAG.getConstant(~SignBit, VT));
5810       AddToWorkList(Cst.getNode());
5811
5812       return DAG.getNode(ISD::OR, SDLoc(N), VT, X, Cst);
5813     }
5814   }
5815
5816   // bitconvert(build_pair(ld, ld)) -> ld iff load locations are consecutive.
5817   if (N0.getOpcode() == ISD::BUILD_PAIR) {
5818     SDValue CombineLD = CombineConsecutiveLoads(N0.getNode(), VT);
5819     if (CombineLD.getNode())
5820       return CombineLD;
5821   }
5822
5823   return SDValue();
5824 }
5825
5826 SDValue DAGCombiner::visitBUILD_PAIR(SDNode *N) {
5827   EVT VT = N->getValueType(0);
5828   return CombineConsecutiveLoads(N, VT);
5829 }
5830
5831 /// ConstantFoldBITCASTofBUILD_VECTOR - We know that BV is a build_vector
5832 /// node with Constant, ConstantFP or Undef operands.  DstEltVT indicates the
5833 /// destination element value type.
5834 SDValue DAGCombiner::
5835 ConstantFoldBITCASTofBUILD_VECTOR(SDNode *BV, EVT DstEltVT) {
5836   EVT SrcEltVT = BV->getValueType(0).getVectorElementType();
5837
5838   // If this is already the right type, we're done.
5839   if (SrcEltVT == DstEltVT) return SDValue(BV, 0);
5840
5841   unsigned SrcBitSize = SrcEltVT.getSizeInBits();
5842   unsigned DstBitSize = DstEltVT.getSizeInBits();
5843
5844   // If this is a conversion of N elements of one type to N elements of another
5845   // type, convert each element.  This handles FP<->INT cases.
5846   if (SrcBitSize == DstBitSize) {
5847     EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT,
5848                               BV->getValueType(0).getVectorNumElements());
5849
5850     // Due to the FP element handling below calling this routine recursively,
5851     // we can end up with a scalar-to-vector node here.
5852     if (BV->getOpcode() == ISD::SCALAR_TO_VECTOR)
5853       return DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(BV), VT,
5854                          DAG.getNode(ISD::BITCAST, SDLoc(BV),
5855                                      DstEltVT, BV->getOperand(0)));
5856
5857     SmallVector<SDValue, 8> Ops;
5858     for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) {
5859       SDValue Op = BV->getOperand(i);
5860       // If the vector element type is not legal, the BUILD_VECTOR operands
5861       // are promoted and implicitly truncated.  Make that explicit here.
5862       if (Op.getValueType() != SrcEltVT)
5863         Op = DAG.getNode(ISD::TRUNCATE, SDLoc(BV), SrcEltVT, Op);
5864       Ops.push_back(DAG.getNode(ISD::BITCAST, SDLoc(BV),
5865                                 DstEltVT, Op));
5866       AddToWorkList(Ops.back().getNode());
5867     }
5868     return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(BV), VT,
5869                        &Ops[0], Ops.size());
5870   }
5871
5872   // Otherwise, we're growing or shrinking the elements.  To avoid having to
5873   // handle annoying details of growing/shrinking FP values, we convert them to
5874   // int first.
5875   if (SrcEltVT.isFloatingPoint()) {
5876     // Convert the input float vector to a int vector where the elements are the
5877     // same sizes.
5878     assert((SrcEltVT == MVT::f32 || SrcEltVT == MVT::f64) && "Unknown FP VT!");
5879     EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), SrcEltVT.getSizeInBits());
5880     BV = ConstantFoldBITCASTofBUILD_VECTOR(BV, IntVT).getNode();
5881     SrcEltVT = IntVT;
5882   }
5883
5884   // Now we know the input is an integer vector.  If the output is a FP type,
5885   // convert to integer first, then to FP of the right size.
5886   if (DstEltVT.isFloatingPoint()) {
5887     assert((DstEltVT == MVT::f32 || DstEltVT == MVT::f64) && "Unknown FP VT!");
5888     EVT TmpVT = EVT::getIntegerVT(*DAG.getContext(), DstEltVT.getSizeInBits());
5889     SDNode *Tmp = ConstantFoldBITCASTofBUILD_VECTOR(BV, TmpVT).getNode();
5890
5891     // Next, convert to FP elements of the same size.
5892     return ConstantFoldBITCASTofBUILD_VECTOR(Tmp, DstEltVT);
5893   }
5894
5895   // Okay, we know the src/dst types are both integers of differing types.
5896   // Handling growing first.
5897   assert(SrcEltVT.isInteger() && DstEltVT.isInteger());
5898   if (SrcBitSize < DstBitSize) {
5899     unsigned NumInputsPerOutput = DstBitSize/SrcBitSize;
5900
5901     SmallVector<SDValue, 8> Ops;
5902     for (unsigned i = 0, e = BV->getNumOperands(); i != e;
5903          i += NumInputsPerOutput) {
5904       bool isLE = TLI.isLittleEndian();
5905       APInt NewBits = APInt(DstBitSize, 0);
5906       bool EltIsUndef = true;
5907       for (unsigned j = 0; j != NumInputsPerOutput; ++j) {
5908         // Shift the previously computed bits over.
5909         NewBits <<= SrcBitSize;
5910         SDValue Op = BV->getOperand(i+ (isLE ? (NumInputsPerOutput-j-1) : j));
5911         if (Op.getOpcode() == ISD::UNDEF) continue;
5912         EltIsUndef = false;
5913
5914         NewBits |= cast<ConstantSDNode>(Op)->getAPIntValue().
5915                    zextOrTrunc(SrcBitSize).zext(DstBitSize);
5916       }
5917
5918       if (EltIsUndef)
5919         Ops.push_back(DAG.getUNDEF(DstEltVT));
5920       else
5921         Ops.push_back(DAG.getConstant(NewBits, DstEltVT));
5922     }
5923
5924     EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT, Ops.size());
5925     return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(BV), VT,
5926                        &Ops[0], Ops.size());
5927   }
5928
5929   // Finally, this must be the case where we are shrinking elements: each input
5930   // turns into multiple outputs.
5931   bool isS2V = ISD::isScalarToVector(BV);
5932   unsigned NumOutputsPerInput = SrcBitSize/DstBitSize;
5933   EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT,
5934                             NumOutputsPerInput*BV->getNumOperands());
5935   SmallVector<SDValue, 8> Ops;
5936
5937   for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) {
5938     if (BV->getOperand(i).getOpcode() == ISD::UNDEF) {
5939       for (unsigned j = 0; j != NumOutputsPerInput; ++j)
5940         Ops.push_back(DAG.getUNDEF(DstEltVT));
5941       continue;
5942     }
5943
5944     APInt OpVal = cast<ConstantSDNode>(BV->getOperand(i))->
5945                   getAPIntValue().zextOrTrunc(SrcBitSize);
5946
5947     for (unsigned j = 0; j != NumOutputsPerInput; ++j) {
5948       APInt ThisVal = OpVal.trunc(DstBitSize);
5949       Ops.push_back(DAG.getConstant(ThisVal, DstEltVT));
5950       if (isS2V && i == 0 && j == 0 && ThisVal.zext(SrcBitSize) == OpVal)
5951         // Simply turn this into a SCALAR_TO_VECTOR of the new type.
5952         return DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(BV), VT,
5953                            Ops[0]);
5954       OpVal = OpVal.lshr(DstBitSize);
5955     }
5956
5957     // For big endian targets, swap the order of the pieces of each element.
5958     if (TLI.isBigEndian())
5959       std::reverse(Ops.end()-NumOutputsPerInput, Ops.end());
5960   }
5961
5962   return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(BV), VT,
5963                      &Ops[0], Ops.size());
5964 }
5965
5966 SDValue DAGCombiner::visitFADD(SDNode *N) {
5967   SDValue N0 = N->getOperand(0);
5968   SDValue N1 = N->getOperand(1);
5969   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
5970   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
5971   EVT VT = N->getValueType(0);
5972
5973   // fold vector ops
5974   if (VT.isVector()) {
5975     SDValue FoldedVOp = SimplifyVBinOp(N);
5976     if (FoldedVOp.getNode()) return FoldedVOp;
5977   }
5978
5979   // fold (fadd c1, c2) -> c1 + c2
5980   if (N0CFP && N1CFP)
5981     return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N1);
5982   // canonicalize constant to RHS
5983   if (N0CFP && !N1CFP)
5984     return DAG.getNode(ISD::FADD, SDLoc(N), VT, N1, N0);
5985   // fold (fadd A, 0) -> A
5986   if (DAG.getTarget().Options.UnsafeFPMath && N1CFP &&
5987       N1CFP->getValueAPF().isZero())
5988     return N0;
5989   // fold (fadd A, (fneg B)) -> (fsub A, B)
5990   if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) &&
5991     isNegatibleForFree(N1, LegalOperations, TLI, &DAG.getTarget().Options) == 2)
5992     return DAG.getNode(ISD::FSUB, SDLoc(N), VT, N0,
5993                        GetNegatedExpression(N1, DAG, LegalOperations));
5994   // fold (fadd (fneg A), B) -> (fsub B, A)
5995   if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) &&
5996     isNegatibleForFree(N0, LegalOperations, TLI, &DAG.getTarget().Options) == 2)
5997     return DAG.getNode(ISD::FSUB, SDLoc(N), VT, N1,
5998                        GetNegatedExpression(N0, DAG, LegalOperations));
5999
6000   // If allowed, fold (fadd (fadd x, c1), c2) -> (fadd x, (fadd c1, c2))
6001   if (DAG.getTarget().Options.UnsafeFPMath && N1CFP &&
6002       N0.getOpcode() == ISD::FADD && N0.getNode()->hasOneUse() &&
6003       isa<ConstantFPSDNode>(N0.getOperand(1)))
6004     return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0.getOperand(0),
6005                        DAG.getNode(ISD::FADD, SDLoc(N), VT,
6006                                    N0.getOperand(1), N1));
6007
6008   // No FP constant should be created after legalization as Instruction
6009   // Selection pass has hard time in dealing with FP constant.
6010   //
6011   // We don't need test this condition for transformation like following, as
6012   // the DAG being transformed implies it is legal to take FP constant as
6013   // operand.
6014   //
6015   //  (fadd (fmul c, x), x) -> (fmul c+1, x)
6016   //
6017   bool AllowNewFpConst = (Level < AfterLegalizeDAG);
6018
6019   // If allow, fold (fadd (fneg x), x) -> 0.0
6020   if (AllowNewFpConst && DAG.getTarget().Options.UnsafeFPMath &&
6021       N0.getOpcode() == ISD::FNEG && N0.getOperand(0) == N1)
6022     return DAG.getConstantFP(0.0, VT);
6023
6024     // If allow, fold (fadd x, (fneg x)) -> 0.0
6025   if (AllowNewFpConst && DAG.getTarget().Options.UnsafeFPMath &&
6026       N1.getOpcode() == ISD::FNEG && N1.getOperand(0) == N0)
6027     return DAG.getConstantFP(0.0, VT);
6028
6029   // In unsafe math mode, we can fold chains of FADD's of the same value
6030   // into multiplications.  This transform is not safe in general because
6031   // we are reducing the number of rounding steps.
6032   if (DAG.getTarget().Options.UnsafeFPMath &&
6033       TLI.isOperationLegalOrCustom(ISD::FMUL, VT) &&
6034       !N0CFP && !N1CFP) {
6035     if (N0.getOpcode() == ISD::FMUL) {
6036       ConstantFPSDNode *CFP00 = dyn_cast<ConstantFPSDNode>(N0.getOperand(0));
6037       ConstantFPSDNode *CFP01 = dyn_cast<ConstantFPSDNode>(N0.getOperand(1));
6038
6039       // (fadd (fmul c, x), x) -> (fmul x, c+1)
6040       if (CFP00 && !CFP01 && N0.getOperand(1) == N1) {
6041         SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6042                                      SDValue(CFP00, 0),
6043                                      DAG.getConstantFP(1.0, VT));
6044         return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6045                            N1, NewCFP);
6046       }
6047
6048       // (fadd (fmul x, c), x) -> (fmul x, c+1)
6049       if (CFP01 && !CFP00 && N0.getOperand(0) == N1) {
6050         SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6051                                      SDValue(CFP01, 0),
6052                                      DAG.getConstantFP(1.0, VT));
6053         return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6054                            N1, NewCFP);
6055       }
6056
6057       // (fadd (fmul c, x), (fadd x, x)) -> (fmul x, c+2)
6058       if (CFP00 && !CFP01 && N1.getOpcode() == ISD::FADD &&
6059           N1.getOperand(0) == N1.getOperand(1) &&
6060           N0.getOperand(1) == N1.getOperand(0)) {
6061         SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6062                                      SDValue(CFP00, 0),
6063                                      DAG.getConstantFP(2.0, VT));
6064         return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6065                            N0.getOperand(1), NewCFP);
6066       }
6067
6068       // (fadd (fmul x, c), (fadd x, x)) -> (fmul x, c+2)
6069       if (CFP01 && !CFP00 && N1.getOpcode() == ISD::FADD &&
6070           N1.getOperand(0) == N1.getOperand(1) &&
6071           N0.getOperand(0) == N1.getOperand(0)) {
6072         SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6073                                      SDValue(CFP01, 0),
6074                                      DAG.getConstantFP(2.0, VT));
6075         return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6076                            N0.getOperand(0), NewCFP);
6077       }
6078     }
6079
6080     if (N1.getOpcode() == ISD::FMUL) {
6081       ConstantFPSDNode *CFP10 = dyn_cast<ConstantFPSDNode>(N1.getOperand(0));
6082       ConstantFPSDNode *CFP11 = dyn_cast<ConstantFPSDNode>(N1.getOperand(1));
6083
6084       // (fadd x, (fmul c, x)) -> (fmul x, c+1)
6085       if (CFP10 && !CFP11 && N1.getOperand(1) == N0) {
6086         SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6087                                      SDValue(CFP10, 0),
6088                                      DAG.getConstantFP(1.0, VT));
6089         return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6090                            N0, NewCFP);
6091       }
6092
6093       // (fadd x, (fmul x, c)) -> (fmul x, c+1)
6094       if (CFP11 && !CFP10 && N1.getOperand(0) == N0) {
6095         SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6096                                      SDValue(CFP11, 0),
6097                                      DAG.getConstantFP(1.0, VT));
6098         return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6099                            N0, NewCFP);
6100       }
6101
6102
6103       // (fadd (fadd x, x), (fmul c, x)) -> (fmul x, c+2)
6104       if (CFP10 && !CFP11 && N0.getOpcode() == ISD::FADD &&
6105           N0.getOperand(0) == N0.getOperand(1) &&
6106           N1.getOperand(1) == N0.getOperand(0)) {
6107         SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6108                                      SDValue(CFP10, 0),
6109                                      DAG.getConstantFP(2.0, VT));
6110         return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6111                            N1.getOperand(1), NewCFP);
6112       }
6113
6114       // (fadd (fadd x, x), (fmul x, c)) -> (fmul x, c+2)
6115       if (CFP11 && !CFP10 && N0.getOpcode() == ISD::FADD &&
6116           N0.getOperand(0) == N0.getOperand(1) &&
6117           N1.getOperand(0) == N0.getOperand(0)) {
6118         SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6119                                      SDValue(CFP11, 0),
6120                                      DAG.getConstantFP(2.0, VT));
6121         return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6122                            N1.getOperand(0), NewCFP);
6123       }
6124     }
6125
6126     if (N0.getOpcode() == ISD::FADD && AllowNewFpConst) {
6127       ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N0.getOperand(0));
6128       // (fadd (fadd x, x), x) -> (fmul x, 3.0)
6129       if (!CFP && N0.getOperand(0) == N0.getOperand(1) &&
6130           (N0.getOperand(0) == N1))
6131         return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6132                            N1, DAG.getConstantFP(3.0, VT));
6133     }
6134
6135     if (N1.getOpcode() == ISD::FADD && AllowNewFpConst) {
6136       ConstantFPSDNode *CFP10 = dyn_cast<ConstantFPSDNode>(N1.getOperand(0));
6137       // (fadd x, (fadd x, x)) -> (fmul x, 3.0)
6138       if (!CFP10 && N1.getOperand(0) == N1.getOperand(1) &&
6139           N1.getOperand(0) == N0)
6140         return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6141                            N0, DAG.getConstantFP(3.0, VT));
6142     }
6143
6144     // (fadd (fadd x, x), (fadd x, x)) -> (fmul x, 4.0)
6145     if (AllowNewFpConst &&
6146         N0.getOpcode() == ISD::FADD && N1.getOpcode() == ISD::FADD &&
6147         N0.getOperand(0) == N0.getOperand(1) &&
6148         N1.getOperand(0) == N1.getOperand(1) &&
6149         N0.getOperand(0) == N1.getOperand(0))
6150       return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6151                          N0.getOperand(0),
6152                          DAG.getConstantFP(4.0, VT));
6153   }
6154
6155   // FADD -> FMA combines:
6156   if ((DAG.getTarget().Options.AllowFPOpFusion == FPOpFusion::Fast ||
6157        DAG.getTarget().Options.UnsafeFPMath) &&
6158       DAG.getTarget().getTargetLowering()->isFMAFasterThanFMulAndFAdd(VT) &&
6159       (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT))) {
6160
6161     // fold (fadd (fmul x, y), z) -> (fma x, y, z)
6162     if (N0.getOpcode() == ISD::FMUL && N0->hasOneUse())
6163       return DAG.getNode(ISD::FMA, SDLoc(N), VT,
6164                          N0.getOperand(0), N0.getOperand(1), N1);
6165
6166     // fold (fadd x, (fmul y, z)) -> (fma y, z, x)
6167     // Note: Commutes FADD operands.
6168     if (N1.getOpcode() == ISD::FMUL && N1->hasOneUse())
6169       return DAG.getNode(ISD::FMA, SDLoc(N), VT,
6170                          N1.getOperand(0), N1.getOperand(1), N0);
6171   }
6172
6173   return SDValue();
6174 }
6175
6176 SDValue DAGCombiner::visitFSUB(SDNode *N) {
6177   SDValue N0 = N->getOperand(0);
6178   SDValue N1 = N->getOperand(1);
6179   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6180   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6181   EVT VT = N->getValueType(0);
6182   SDLoc dl(N);
6183
6184   // fold vector ops
6185   if (VT.isVector()) {
6186     SDValue FoldedVOp = SimplifyVBinOp(N);
6187     if (FoldedVOp.getNode()) return FoldedVOp;
6188   }
6189
6190   // fold (fsub c1, c2) -> c1-c2
6191   if (N0CFP && N1CFP)
6192     return DAG.getNode(ISD::FSUB, SDLoc(N), VT, N0, N1);
6193   // fold (fsub A, 0) -> A
6194   if (DAG.getTarget().Options.UnsafeFPMath &&
6195       N1CFP && N1CFP->getValueAPF().isZero())
6196     return N0;
6197   // fold (fsub 0, B) -> -B
6198   if (DAG.getTarget().Options.UnsafeFPMath &&
6199       N0CFP && N0CFP->getValueAPF().isZero()) {
6200     if (isNegatibleForFree(N1, LegalOperations, TLI, &DAG.getTarget().Options))
6201       return GetNegatedExpression(N1, DAG, LegalOperations);
6202     if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
6203       return DAG.getNode(ISD::FNEG, dl, VT, N1);
6204   }
6205   // fold (fsub A, (fneg B)) -> (fadd A, B)
6206   if (isNegatibleForFree(N1, LegalOperations, TLI, &DAG.getTarget().Options))
6207     return DAG.getNode(ISD::FADD, dl, VT, N0,
6208                        GetNegatedExpression(N1, DAG, LegalOperations));
6209
6210   // If 'unsafe math' is enabled, fold
6211   //    (fsub x, x) -> 0.0 &
6212   //    (fsub x, (fadd x, y)) -> (fneg y) &
6213   //    (fsub x, (fadd y, x)) -> (fneg y)
6214   if (DAG.getTarget().Options.UnsafeFPMath) {
6215     if (N0 == N1)
6216       return DAG.getConstantFP(0.0f, VT);
6217
6218     if (N1.getOpcode() == ISD::FADD) {
6219       SDValue N10 = N1->getOperand(0);
6220       SDValue N11 = N1->getOperand(1);
6221
6222       if (N10 == N0 && isNegatibleForFree(N11, LegalOperations, TLI,
6223                                           &DAG.getTarget().Options))
6224         return GetNegatedExpression(N11, DAG, LegalOperations);
6225
6226       if (N11 == N0 && isNegatibleForFree(N10, LegalOperations, TLI,
6227                                           &DAG.getTarget().Options))
6228         return GetNegatedExpression(N10, DAG, LegalOperations);
6229     }
6230   }
6231
6232   // FSUB -> FMA combines:
6233   if ((DAG.getTarget().Options.AllowFPOpFusion == FPOpFusion::Fast ||
6234        DAG.getTarget().Options.UnsafeFPMath) &&
6235       DAG.getTarget().getTargetLowering()->isFMAFasterThanFMulAndFAdd(VT) &&
6236       (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT))) {
6237
6238     // fold (fsub (fmul x, y), z) -> (fma x, y, (fneg z))
6239     if (N0.getOpcode() == ISD::FMUL && N0->hasOneUse())
6240       return DAG.getNode(ISD::FMA, dl, VT,
6241                          N0.getOperand(0), N0.getOperand(1),
6242                          DAG.getNode(ISD::FNEG, dl, VT, N1));
6243
6244     // fold (fsub x, (fmul y, z)) -> (fma (fneg y), z, x)
6245     // Note: Commutes FSUB operands.
6246     if (N1.getOpcode() == ISD::FMUL && N1->hasOneUse())
6247       return DAG.getNode(ISD::FMA, dl, VT,
6248                          DAG.getNode(ISD::FNEG, dl, VT,
6249                          N1.getOperand(0)),
6250                          N1.getOperand(1), N0);
6251
6252     // fold (fsub (fneg (fmul, x, y)), z) -> (fma (fneg x), y, (fneg z))
6253     if (N0.getOpcode() == ISD::FNEG &&
6254         N0.getOperand(0).getOpcode() == ISD::FMUL &&
6255         N0->hasOneUse() && N0.getOperand(0).hasOneUse()) {
6256       SDValue N00 = N0.getOperand(0).getOperand(0);
6257       SDValue N01 = N0.getOperand(0).getOperand(1);
6258       return DAG.getNode(ISD::FMA, dl, VT,
6259                          DAG.getNode(ISD::FNEG, dl, VT, N00), N01,
6260                          DAG.getNode(ISD::FNEG, dl, VT, N1));
6261     }
6262   }
6263
6264   return SDValue();
6265 }
6266
6267 SDValue DAGCombiner::visitFMUL(SDNode *N) {
6268   SDValue N0 = N->getOperand(0);
6269   SDValue N1 = N->getOperand(1);
6270   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6271   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6272   EVT VT = N->getValueType(0);
6273   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6274
6275   // fold vector ops
6276   if (VT.isVector()) {
6277     SDValue FoldedVOp = SimplifyVBinOp(N);
6278     if (FoldedVOp.getNode()) return FoldedVOp;
6279   }
6280
6281   // fold (fmul c1, c2) -> c1*c2
6282   if (N0CFP && N1CFP)
6283     return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0, N1);
6284   // canonicalize constant to RHS
6285   if (N0CFP && !N1CFP)
6286     return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N1, N0);
6287   // fold (fmul A, 0) -> 0
6288   if (DAG.getTarget().Options.UnsafeFPMath &&
6289       N1CFP && N1CFP->getValueAPF().isZero())
6290     return N1;
6291   // fold (fmul A, 0) -> 0, vector edition.
6292   if (DAG.getTarget().Options.UnsafeFPMath &&
6293       ISD::isBuildVectorAllZeros(N1.getNode()))
6294     return N1;
6295   // fold (fmul A, 1.0) -> A
6296   if (N1CFP && N1CFP->isExactlyValue(1.0))
6297     return N0;
6298   // fold (fmul X, 2.0) -> (fadd X, X)
6299   if (N1CFP && N1CFP->isExactlyValue(+2.0))
6300     return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N0);
6301   // fold (fmul X, -1.0) -> (fneg X)
6302   if (N1CFP && N1CFP->isExactlyValue(-1.0))
6303     if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
6304       return DAG.getNode(ISD::FNEG, SDLoc(N), VT, N0);
6305
6306   // fold (fmul (fneg X), (fneg Y)) -> (fmul X, Y)
6307   if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI,
6308                                        &DAG.getTarget().Options)) {
6309     if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI,
6310                                          &DAG.getTarget().Options)) {
6311       // Both can be negated for free, check to see if at least one is cheaper
6312       // negated.
6313       if (LHSNeg == 2 || RHSNeg == 2)
6314         return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6315                            GetNegatedExpression(N0, DAG, LegalOperations),
6316                            GetNegatedExpression(N1, DAG, LegalOperations));
6317     }
6318   }
6319
6320   // If allowed, fold (fmul (fmul x, c1), c2) -> (fmul x, (fmul c1, c2))
6321   if (DAG.getTarget().Options.UnsafeFPMath &&
6322       N1CFP && N0.getOpcode() == ISD::FMUL &&
6323       N0.getNode()->hasOneUse() && isa<ConstantFPSDNode>(N0.getOperand(1)))
6324     return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0.getOperand(0),
6325                        DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6326                                    N0.getOperand(1), N1));
6327
6328   return SDValue();
6329 }
6330
6331 SDValue DAGCombiner::visitFMA(SDNode *N) {
6332   SDValue N0 = N->getOperand(0);
6333   SDValue N1 = N->getOperand(1);
6334   SDValue N2 = N->getOperand(2);
6335   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6336   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6337   EVT VT = N->getValueType(0);
6338   SDLoc dl(N);
6339
6340   if (DAG.getTarget().Options.UnsafeFPMath) {
6341     if (N0CFP && N0CFP->isZero())
6342       return N2;
6343     if (N1CFP && N1CFP->isZero())
6344       return N2;
6345   }
6346   if (N0CFP && N0CFP->isExactlyValue(1.0))
6347     return DAG.getNode(ISD::FADD, SDLoc(N), VT, N1, N2);
6348   if (N1CFP && N1CFP->isExactlyValue(1.0))
6349     return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N2);
6350
6351   // Canonicalize (fma c, x, y) -> (fma x, c, y)
6352   if (N0CFP && !N1CFP)
6353     return DAG.getNode(ISD::FMA, SDLoc(N), VT, N1, N0, N2);
6354
6355   // (fma x, c1, (fmul x, c2)) -> (fmul x, c1+c2)
6356   if (DAG.getTarget().Options.UnsafeFPMath && N1CFP &&
6357       N2.getOpcode() == ISD::FMUL &&
6358       N0 == N2.getOperand(0) &&
6359       N2.getOperand(1).getOpcode() == ISD::ConstantFP) {
6360     return DAG.getNode(ISD::FMUL, dl, VT, N0,
6361                        DAG.getNode(ISD::FADD, dl, VT, N1, N2.getOperand(1)));
6362   }
6363
6364
6365   // (fma (fmul x, c1), c2, y) -> (fma x, c1*c2, y)
6366   if (DAG.getTarget().Options.UnsafeFPMath &&
6367       N0.getOpcode() == ISD::FMUL && N1CFP &&
6368       N0.getOperand(1).getOpcode() == ISD::ConstantFP) {
6369     return DAG.getNode(ISD::FMA, dl, VT,
6370                        N0.getOperand(0),
6371                        DAG.getNode(ISD::FMUL, dl, VT, N1, N0.getOperand(1)),
6372                        N2);
6373   }
6374
6375   // (fma x, 1, y) -> (fadd x, y)
6376   // (fma x, -1, y) -> (fadd (fneg x), y)
6377   if (N1CFP) {
6378     if (N1CFP->isExactlyValue(1.0))
6379       return DAG.getNode(ISD::FADD, dl, VT, N0, N2);
6380
6381     if (N1CFP->isExactlyValue(-1.0) &&
6382         (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))) {
6383       SDValue RHSNeg = DAG.getNode(ISD::FNEG, dl, VT, N0);
6384       AddToWorkList(RHSNeg.getNode());
6385       return DAG.getNode(ISD::FADD, dl, VT, N2, RHSNeg);
6386     }
6387   }
6388
6389   // (fma x, c, x) -> (fmul x, (c+1))
6390   if (DAG.getTarget().Options.UnsafeFPMath && N1CFP && N0 == N2)
6391     return DAG.getNode(ISD::FMUL, dl, VT, N0,
6392                        DAG.getNode(ISD::FADD, dl, VT,
6393                                    N1, DAG.getConstantFP(1.0, VT)));
6394
6395   // (fma x, c, (fneg x)) -> (fmul x, (c-1))
6396   if (DAG.getTarget().Options.UnsafeFPMath && N1CFP &&
6397       N2.getOpcode() == ISD::FNEG && N2.getOperand(0) == N0)
6398     return DAG.getNode(ISD::FMUL, dl, VT, N0,
6399                        DAG.getNode(ISD::FADD, dl, VT,
6400                                    N1, DAG.getConstantFP(-1.0, VT)));
6401
6402
6403   return SDValue();
6404 }
6405
6406 SDValue DAGCombiner::visitFDIV(SDNode *N) {
6407   SDValue N0 = N->getOperand(0);
6408   SDValue N1 = N->getOperand(1);
6409   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6410   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6411   EVT VT = N->getValueType(0);
6412   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6413
6414   // fold vector ops
6415   if (VT.isVector()) {
6416     SDValue FoldedVOp = SimplifyVBinOp(N);
6417     if (FoldedVOp.getNode()) return FoldedVOp;
6418   }
6419
6420   // fold (fdiv c1, c2) -> c1/c2
6421   if (N0CFP && N1CFP)
6422     return DAG.getNode(ISD::FDIV, SDLoc(N), VT, N0, N1);
6423
6424   // fold (fdiv X, c2) -> fmul X, 1/c2 if losing precision is acceptable.
6425   if (N1CFP && DAG.getTarget().Options.UnsafeFPMath) {
6426     // Compute the reciprocal 1.0 / c2.
6427     APFloat N1APF = N1CFP->getValueAPF();
6428     APFloat Recip(N1APF.getSemantics(), 1); // 1.0
6429     APFloat::opStatus st = Recip.divide(N1APF, APFloat::rmNearestTiesToEven);
6430     // Only do the transform if the reciprocal is a legal fp immediate that
6431     // isn't too nasty (eg NaN, denormal, ...).
6432     if ((st == APFloat::opOK || st == APFloat::opInexact) && // Not too nasty
6433         (!LegalOperations ||
6434          // FIXME: custom lowering of ConstantFP might fail (see e.g. ARM
6435          // backend)... we should handle this gracefully after Legalize.
6436          // TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT) ||
6437          TLI.isOperationLegal(llvm::ISD::ConstantFP, VT) ||
6438          TLI.isFPImmLegal(Recip, VT)))
6439       return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0,
6440                          DAG.getConstantFP(Recip, VT));
6441   }
6442
6443   // (fdiv (fneg X), (fneg Y)) -> (fdiv X, Y)
6444   if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI,
6445                                        &DAG.getTarget().Options)) {
6446     if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI,
6447                                          &DAG.getTarget().Options)) {
6448       // Both can be negated for free, check to see if at least one is cheaper
6449       // negated.
6450       if (LHSNeg == 2 || RHSNeg == 2)
6451         return DAG.getNode(ISD::FDIV, SDLoc(N), VT,
6452                            GetNegatedExpression(N0, DAG, LegalOperations),
6453                            GetNegatedExpression(N1, DAG, LegalOperations));
6454     }
6455   }
6456
6457   return SDValue();
6458 }
6459
6460 SDValue DAGCombiner::visitFREM(SDNode *N) {
6461   SDValue N0 = N->getOperand(0);
6462   SDValue N1 = N->getOperand(1);
6463   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6464   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6465   EVT VT = N->getValueType(0);
6466
6467   // fold (frem c1, c2) -> fmod(c1,c2)
6468   if (N0CFP && N1CFP)
6469     return DAG.getNode(ISD::FREM, SDLoc(N), VT, N0, N1);
6470
6471   return SDValue();
6472 }
6473
6474 SDValue DAGCombiner::visitFCOPYSIGN(SDNode *N) {
6475   SDValue N0 = N->getOperand(0);
6476   SDValue N1 = N->getOperand(1);
6477   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6478   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6479   EVT VT = N->getValueType(0);
6480
6481   if (N0CFP && N1CFP)  // Constant fold
6482     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, N0, N1);
6483
6484   if (N1CFP) {
6485     const APFloat& V = N1CFP->getValueAPF();
6486     // copysign(x, c1) -> fabs(x)       iff ispos(c1)
6487     // copysign(x, c1) -> fneg(fabs(x)) iff isneg(c1)
6488     if (!V.isNegative()) {
6489       if (!LegalOperations || TLI.isOperationLegal(ISD::FABS, VT))
6490         return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
6491     } else {
6492       if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
6493         return DAG.getNode(ISD::FNEG, SDLoc(N), VT,
6494                            DAG.getNode(ISD::FABS, SDLoc(N0), VT, N0));
6495     }
6496   }
6497
6498   // copysign(fabs(x), y) -> copysign(x, y)
6499   // copysign(fneg(x), y) -> copysign(x, y)
6500   // copysign(copysign(x,z), y) -> copysign(x, y)
6501   if (N0.getOpcode() == ISD::FABS || N0.getOpcode() == ISD::FNEG ||
6502       N0.getOpcode() == ISD::FCOPYSIGN)
6503     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
6504                        N0.getOperand(0), N1);
6505
6506   // copysign(x, abs(y)) -> abs(x)
6507   if (N1.getOpcode() == ISD::FABS)
6508     return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
6509
6510   // copysign(x, copysign(y,z)) -> copysign(x, z)
6511   if (N1.getOpcode() == ISD::FCOPYSIGN)
6512     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
6513                        N0, N1.getOperand(1));
6514
6515   // copysign(x, fp_extend(y)) -> copysign(x, y)
6516   // copysign(x, fp_round(y)) -> copysign(x, y)
6517   if (N1.getOpcode() == ISD::FP_EXTEND || N1.getOpcode() == ISD::FP_ROUND)
6518     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
6519                        N0, N1.getOperand(0));
6520
6521   return SDValue();
6522 }
6523
6524 SDValue DAGCombiner::visitSINT_TO_FP(SDNode *N) {
6525   SDValue N0 = N->getOperand(0);
6526   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
6527   EVT VT = N->getValueType(0);
6528   EVT OpVT = N0.getValueType();
6529
6530   // fold (sint_to_fp c1) -> c1fp
6531   if (N0C &&
6532       // ...but only if the target supports immediate floating-point values
6533       (!LegalOperations ||
6534        TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT)))
6535     return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0);
6536
6537   // If the input is a legal type, and SINT_TO_FP is not legal on this target,
6538   // but UINT_TO_FP is legal on this target, try to convert.
6539   if (!TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT) &&
6540       TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT)) {
6541     // If the sign bit is known to be zero, we can change this to UINT_TO_FP.
6542     if (DAG.SignBitIsZero(N0))
6543       return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0);
6544   }
6545
6546   // The next optimizations are desireable only if SELECT_CC can be lowered.
6547   // Check against MVT::Other for SELECT_CC, which is a workaround for targets
6548   // having to say they don't support SELECT_CC on every type the DAG knows
6549   // about, since there is no way to mark an opcode illegal at all value types
6550   // (See also visitSELECT)
6551   if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, MVT::Other)) {
6552     // fold (sint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc)
6553     if (N0.getOpcode() == ISD::SETCC && N0.getValueType() == MVT::i1 &&
6554         !VT.isVector() &&
6555         (!LegalOperations ||
6556          TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
6557       SDValue Ops[] =
6558         { N0.getOperand(0), N0.getOperand(1),
6559           DAG.getConstantFP(-1.0, VT) , DAG.getConstantFP(0.0, VT),
6560           N0.getOperand(2) };
6561       return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT, Ops, 5);
6562     }
6563
6564     // fold (sint_to_fp (zext (setcc x, y, cc))) ->
6565     //      (select_cc x, y, 1.0, 0.0,, cc)
6566     if (N0.getOpcode() == ISD::ZERO_EXTEND &&
6567         N0.getOperand(0).getOpcode() == ISD::SETCC &&!VT.isVector() &&
6568         (!LegalOperations ||
6569          TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
6570       SDValue Ops[] =
6571         { N0.getOperand(0).getOperand(0), N0.getOperand(0).getOperand(1),
6572           DAG.getConstantFP(1.0, VT) , DAG.getConstantFP(0.0, VT),
6573           N0.getOperand(0).getOperand(2) };
6574       return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT, Ops, 5);
6575     }
6576   }
6577
6578   return SDValue();
6579 }
6580
6581 SDValue DAGCombiner::visitUINT_TO_FP(SDNode *N) {
6582   SDValue N0 = N->getOperand(0);
6583   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
6584   EVT VT = N->getValueType(0);
6585   EVT OpVT = N0.getValueType();
6586
6587   // fold (uint_to_fp c1) -> c1fp
6588   if (N0C &&
6589       // ...but only if the target supports immediate floating-point values
6590       (!LegalOperations ||
6591        TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT)))
6592     return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0);
6593
6594   // If the input is a legal type, and UINT_TO_FP is not legal on this target,
6595   // but SINT_TO_FP is legal on this target, try to convert.
6596   if (!TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT) &&
6597       TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT)) {
6598     // If the sign bit is known to be zero, we can change this to SINT_TO_FP.
6599     if (DAG.SignBitIsZero(N0))
6600       return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0);
6601   }
6602
6603   // The next optimizations are desireable only if SELECT_CC can be lowered.
6604   // Check against MVT::Other for SELECT_CC, which is a workaround for targets
6605   // having to say they don't support SELECT_CC on every type the DAG knows
6606   // about, since there is no way to mark an opcode illegal at all value types
6607   // (See also visitSELECT)
6608   if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, MVT::Other)) {
6609     // fold (uint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc)
6610
6611     if (N0.getOpcode() == ISD::SETCC && !VT.isVector() &&
6612         (!LegalOperations ||
6613          TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
6614       SDValue Ops[] =
6615         { N0.getOperand(0), N0.getOperand(1),
6616           DAG.getConstantFP(1.0, VT),  DAG.getConstantFP(0.0, VT),
6617           N0.getOperand(2) };
6618       return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT, Ops, 5);
6619     }
6620   }
6621
6622   return SDValue();
6623 }
6624
6625 SDValue DAGCombiner::visitFP_TO_SINT(SDNode *N) {
6626   SDValue N0 = N->getOperand(0);
6627   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6628   EVT VT = N->getValueType(0);
6629
6630   // fold (fp_to_sint c1fp) -> c1
6631   if (N0CFP)
6632     return DAG.getNode(ISD::FP_TO_SINT, SDLoc(N), VT, N0);
6633
6634   return SDValue();
6635 }
6636
6637 SDValue DAGCombiner::visitFP_TO_UINT(SDNode *N) {
6638   SDValue N0 = N->getOperand(0);
6639   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6640   EVT VT = N->getValueType(0);
6641
6642   // fold (fp_to_uint c1fp) -> c1
6643   if (N0CFP)
6644     return DAG.getNode(ISD::FP_TO_UINT, SDLoc(N), VT, N0);
6645
6646   return SDValue();
6647 }
6648
6649 SDValue DAGCombiner::visitFP_ROUND(SDNode *N) {
6650   SDValue N0 = N->getOperand(0);
6651   SDValue N1 = N->getOperand(1);
6652   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6653   EVT VT = N->getValueType(0);
6654
6655   // fold (fp_round c1fp) -> c1fp
6656   if (N0CFP)
6657     return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT, N0, N1);
6658
6659   // fold (fp_round (fp_extend x)) -> x
6660   if (N0.getOpcode() == ISD::FP_EXTEND && VT == N0.getOperand(0).getValueType())
6661     return N0.getOperand(0);
6662
6663   // fold (fp_round (fp_round x)) -> (fp_round x)
6664   if (N0.getOpcode() == ISD::FP_ROUND) {
6665     // This is a value preserving truncation if both round's are.
6666     bool IsTrunc = N->getConstantOperandVal(1) == 1 &&
6667                    N0.getNode()->getConstantOperandVal(1) == 1;
6668     return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT, N0.getOperand(0),
6669                        DAG.getIntPtrConstant(IsTrunc));
6670   }
6671
6672   // fold (fp_round (copysign X, Y)) -> (copysign (fp_round X), Y)
6673   if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse()) {
6674     SDValue Tmp = DAG.getNode(ISD::FP_ROUND, SDLoc(N0), VT,
6675                               N0.getOperand(0), N1);
6676     AddToWorkList(Tmp.getNode());
6677     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
6678                        Tmp, N0.getOperand(1));
6679   }
6680
6681   return SDValue();
6682 }
6683
6684 SDValue DAGCombiner::visitFP_ROUND_INREG(SDNode *N) {
6685   SDValue N0 = N->getOperand(0);
6686   EVT VT = N->getValueType(0);
6687   EVT EVT = cast<VTSDNode>(N->getOperand(1))->getVT();
6688   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6689
6690   // fold (fp_round_inreg c1fp) -> c1fp
6691   if (N0CFP && isTypeLegal(EVT)) {
6692     SDValue Round = DAG.getConstantFP(*N0CFP->getConstantFPValue(), EVT);
6693     return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, Round);
6694   }
6695
6696   return SDValue();
6697 }
6698
6699 SDValue DAGCombiner::visitFP_EXTEND(SDNode *N) {
6700   SDValue N0 = N->getOperand(0);
6701   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6702   EVT VT = N->getValueType(0);
6703
6704   // If this is fp_round(fpextend), don't fold it, allow ourselves to be folded.
6705   if (N->hasOneUse() &&
6706       N->use_begin()->getOpcode() == ISD::FP_ROUND)
6707     return SDValue();
6708
6709   // fold (fp_extend c1fp) -> c1fp
6710   if (N0CFP)
6711     return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, N0);
6712
6713   // Turn fp_extend(fp_round(X, 1)) -> x since the fp_round doesn't affect the
6714   // value of X.
6715   if (N0.getOpcode() == ISD::FP_ROUND
6716       && N0.getNode()->getConstantOperandVal(1) == 1) {
6717     SDValue In = N0.getOperand(0);
6718     if (In.getValueType() == VT) return In;
6719     if (VT.bitsLT(In.getValueType()))
6720       return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT,
6721                          In, N0.getOperand(1));
6722     return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, In);
6723   }
6724
6725   // fold (fpext (load x)) -> (fpext (fptrunc (extload x)))
6726   if (ISD::isNON_EXTLoad(N0.getNode()) && N0.hasOneUse() &&
6727       ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
6728        TLI.isLoadExtLegal(ISD::EXTLOAD, N0.getValueType()))) {
6729     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6730     SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT,
6731                                      LN0->getChain(),
6732                                      LN0->getBasePtr(), LN0->getPointerInfo(),
6733                                      N0.getValueType(),
6734                                      LN0->isVolatile(), LN0->isNonTemporal(),
6735                                      LN0->getAlignment());
6736     CombineTo(N, ExtLoad);
6737     CombineTo(N0.getNode(),
6738               DAG.getNode(ISD::FP_ROUND, SDLoc(N0),
6739                           N0.getValueType(), ExtLoad, DAG.getIntPtrConstant(1)),
6740               ExtLoad.getValue(1));
6741     return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6742   }
6743
6744   return SDValue();
6745 }
6746
6747 SDValue DAGCombiner::visitFNEG(SDNode *N) {
6748   SDValue N0 = N->getOperand(0);
6749   EVT VT = N->getValueType(0);
6750
6751   if (VT.isVector()) {
6752     SDValue FoldedVOp = SimplifyVUnaryOp(N);
6753     if (FoldedVOp.getNode()) return FoldedVOp;
6754   }
6755
6756   if (isNegatibleForFree(N0, LegalOperations, DAG.getTargetLoweringInfo(),
6757                          &DAG.getTarget().Options))
6758     return GetNegatedExpression(N0, DAG, LegalOperations);
6759
6760   // Transform fneg(bitconvert(x)) -> bitconvert(x^sign) to avoid loading
6761   // constant pool values.
6762   if (!TLI.isFNegFree(VT) && N0.getOpcode() == ISD::BITCAST &&
6763       !VT.isVector() &&
6764       N0.getNode()->hasOneUse() &&
6765       N0.getOperand(0).getValueType().isInteger()) {
6766     SDValue Int = N0.getOperand(0);
6767     EVT IntVT = Int.getValueType();
6768     if (IntVT.isInteger() && !IntVT.isVector()) {
6769       Int = DAG.getNode(ISD::XOR, SDLoc(N0), IntVT, Int,
6770               DAG.getConstant(APInt::getSignBit(IntVT.getSizeInBits()), IntVT));
6771       AddToWorkList(Int.getNode());
6772       return DAG.getNode(ISD::BITCAST, SDLoc(N),
6773                          VT, Int);
6774     }
6775   }
6776
6777   // (fneg (fmul c, x)) -> (fmul -c, x)
6778   if (N0.getOpcode() == ISD::FMUL) {
6779     ConstantFPSDNode *CFP1 = dyn_cast<ConstantFPSDNode>(N0.getOperand(1));
6780     if (CFP1)
6781       return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6782                          N0.getOperand(0),
6783                          DAG.getNode(ISD::FNEG, SDLoc(N), VT,
6784                                      N0.getOperand(1)));
6785   }
6786
6787   return SDValue();
6788 }
6789
6790 SDValue DAGCombiner::visitFCEIL(SDNode *N) {
6791   SDValue N0 = N->getOperand(0);
6792   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6793   EVT VT = N->getValueType(0);
6794
6795   // fold (fceil c1) -> fceil(c1)
6796   if (N0CFP)
6797     return DAG.getNode(ISD::FCEIL, SDLoc(N), VT, N0);
6798
6799   return SDValue();
6800 }
6801
6802 SDValue DAGCombiner::visitFTRUNC(SDNode *N) {
6803   SDValue N0 = N->getOperand(0);
6804   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6805   EVT VT = N->getValueType(0);
6806
6807   // fold (ftrunc c1) -> ftrunc(c1)
6808   if (N0CFP)
6809     return DAG.getNode(ISD::FTRUNC, SDLoc(N), VT, N0);
6810
6811   return SDValue();
6812 }
6813
6814 SDValue DAGCombiner::visitFFLOOR(SDNode *N) {
6815   SDValue N0 = N->getOperand(0);
6816   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6817   EVT VT = N->getValueType(0);
6818
6819   // fold (ffloor c1) -> ffloor(c1)
6820   if (N0CFP)
6821     return DAG.getNode(ISD::FFLOOR, SDLoc(N), VT, N0);
6822
6823   return SDValue();
6824 }
6825
6826 SDValue DAGCombiner::visitFABS(SDNode *N) {
6827   SDValue N0 = N->getOperand(0);
6828   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6829   EVT VT = N->getValueType(0);
6830
6831   if (VT.isVector()) {
6832     SDValue FoldedVOp = SimplifyVUnaryOp(N);
6833     if (FoldedVOp.getNode()) return FoldedVOp;
6834   }
6835
6836   // fold (fabs c1) -> fabs(c1)
6837   if (N0CFP)
6838     return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
6839   // fold (fabs (fabs x)) -> (fabs x)
6840   if (N0.getOpcode() == ISD::FABS)
6841     return N->getOperand(0);
6842   // fold (fabs (fneg x)) -> (fabs x)
6843   // fold (fabs (fcopysign x, y)) -> (fabs x)
6844   if (N0.getOpcode() == ISD::FNEG || N0.getOpcode() == ISD::FCOPYSIGN)
6845     return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0.getOperand(0));
6846
6847   // Transform fabs(bitconvert(x)) -> bitconvert(x&~sign) to avoid loading
6848   // constant pool values.
6849   if (!TLI.isFAbsFree(VT) &&
6850       N0.getOpcode() == ISD::BITCAST && N0.getNode()->hasOneUse() &&
6851       N0.getOperand(0).getValueType().isInteger() &&
6852       !N0.getOperand(0).getValueType().isVector()) {
6853     SDValue Int = N0.getOperand(0);
6854     EVT IntVT = Int.getValueType();
6855     if (IntVT.isInteger() && !IntVT.isVector()) {
6856       Int = DAG.getNode(ISD::AND, SDLoc(N0), IntVT, Int,
6857              DAG.getConstant(~APInt::getSignBit(IntVT.getSizeInBits()), IntVT));
6858       AddToWorkList(Int.getNode());
6859       return DAG.getNode(ISD::BITCAST, SDLoc(N),
6860                          N->getValueType(0), Int);
6861     }
6862   }
6863
6864   return SDValue();
6865 }
6866
6867 SDValue DAGCombiner::visitBRCOND(SDNode *N) {
6868   SDValue Chain = N->getOperand(0);
6869   SDValue N1 = N->getOperand(1);
6870   SDValue N2 = N->getOperand(2);
6871
6872   // If N is a constant we could fold this into a fallthrough or unconditional
6873   // branch. However that doesn't happen very often in normal code, because
6874   // Instcombine/SimplifyCFG should have handled the available opportunities.
6875   // If we did this folding here, it would be necessary to update the
6876   // MachineBasicBlock CFG, which is awkward.
6877
6878   // fold a brcond with a setcc condition into a BR_CC node if BR_CC is legal
6879   // on the target.
6880   if (N1.getOpcode() == ISD::SETCC &&
6881       TLI.isOperationLegalOrCustom(ISD::BR_CC,
6882                                    N1.getOperand(0).getValueType())) {
6883     return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other,
6884                        Chain, N1.getOperand(2),
6885                        N1.getOperand(0), N1.getOperand(1), N2);
6886   }
6887
6888   if ((N1.hasOneUse() && N1.getOpcode() == ISD::SRL) ||
6889       ((N1.getOpcode() == ISD::TRUNCATE && N1.hasOneUse()) &&
6890        (N1.getOperand(0).hasOneUse() &&
6891         N1.getOperand(0).getOpcode() == ISD::SRL))) {
6892     SDNode *Trunc = 0;
6893     if (N1.getOpcode() == ISD::TRUNCATE) {
6894       // Look pass the truncate.
6895       Trunc = N1.getNode();
6896       N1 = N1.getOperand(0);
6897     }
6898
6899     // Match this pattern so that we can generate simpler code:
6900     //
6901     //   %a = ...
6902     //   %b = and i32 %a, 2
6903     //   %c = srl i32 %b, 1
6904     //   brcond i32 %c ...
6905     //
6906     // into
6907     //
6908     //   %a = ...
6909     //   %b = and i32 %a, 2
6910     //   %c = setcc eq %b, 0
6911     //   brcond %c ...
6912     //
6913     // This applies only when the AND constant value has one bit set and the
6914     // SRL constant is equal to the log2 of the AND constant. The back-end is
6915     // smart enough to convert the result into a TEST/JMP sequence.
6916     SDValue Op0 = N1.getOperand(0);
6917     SDValue Op1 = N1.getOperand(1);
6918
6919     if (Op0.getOpcode() == ISD::AND &&
6920         Op1.getOpcode() == ISD::Constant) {
6921       SDValue AndOp1 = Op0.getOperand(1);
6922
6923       if (AndOp1.getOpcode() == ISD::Constant) {
6924         const APInt &AndConst = cast<ConstantSDNode>(AndOp1)->getAPIntValue();
6925
6926         if (AndConst.isPowerOf2() &&
6927             cast<ConstantSDNode>(Op1)->getAPIntValue()==AndConst.logBase2()) {
6928           SDValue SetCC =
6929             DAG.getSetCC(SDLoc(N),
6930                          getSetCCResultType(Op0.getValueType()),
6931                          Op0, DAG.getConstant(0, Op0.getValueType()),
6932                          ISD::SETNE);
6933
6934           SDValue NewBRCond = DAG.getNode(ISD::BRCOND, SDLoc(N),
6935                                           MVT::Other, Chain, SetCC, N2);
6936           // Don't add the new BRCond into the worklist or else SimplifySelectCC
6937           // will convert it back to (X & C1) >> C2.
6938           CombineTo(N, NewBRCond, false);
6939           // Truncate is dead.
6940           if (Trunc) {
6941             removeFromWorkList(Trunc);
6942             DAG.DeleteNode(Trunc);
6943           }
6944           // Replace the uses of SRL with SETCC
6945           WorkListRemover DeadNodes(*this);
6946           DAG.ReplaceAllUsesOfValueWith(N1, SetCC);
6947           removeFromWorkList(N1.getNode());
6948           DAG.DeleteNode(N1.getNode());
6949           return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6950         }
6951       }
6952     }
6953
6954     if (Trunc)
6955       // Restore N1 if the above transformation doesn't match.
6956       N1 = N->getOperand(1);
6957   }
6958
6959   // Transform br(xor(x, y)) -> br(x != y)
6960   // Transform br(xor(xor(x,y), 1)) -> br (x == y)
6961   if (N1.hasOneUse() && N1.getOpcode() == ISD::XOR) {
6962     SDNode *TheXor = N1.getNode();
6963     SDValue Op0 = TheXor->getOperand(0);
6964     SDValue Op1 = TheXor->getOperand(1);
6965     if (Op0.getOpcode() == Op1.getOpcode()) {
6966       // Avoid missing important xor optimizations.
6967       SDValue Tmp = visitXOR(TheXor);
6968       if (Tmp.getNode()) {
6969         if (Tmp.getNode() != TheXor) {
6970           DEBUG(dbgs() << "\nReplacing.8 ";
6971                 TheXor->dump(&DAG);
6972                 dbgs() << "\nWith: ";
6973                 Tmp.getNode()->dump(&DAG);
6974                 dbgs() << '\n');
6975           WorkListRemover DeadNodes(*this);
6976           DAG.ReplaceAllUsesOfValueWith(N1, Tmp);
6977           removeFromWorkList(TheXor);
6978           DAG.DeleteNode(TheXor);
6979           return DAG.getNode(ISD::BRCOND, SDLoc(N),
6980                              MVT::Other, Chain, Tmp, N2);
6981         }
6982
6983         // visitXOR has changed XOR's operands or replaced the XOR completely,
6984         // bail out.
6985         return SDValue(N, 0);
6986       }
6987     }
6988
6989     if (Op0.getOpcode() != ISD::SETCC && Op1.getOpcode() != ISD::SETCC) {
6990       bool Equal = false;
6991       if (ConstantSDNode *RHSCI = dyn_cast<ConstantSDNode>(Op0))
6992         if (RHSCI->getAPIntValue() == 1 && Op0.hasOneUse() &&
6993             Op0.getOpcode() == ISD::XOR) {
6994           TheXor = Op0.getNode();
6995           Equal = true;
6996         }
6997
6998       EVT SetCCVT = N1.getValueType();
6999       if (LegalTypes)
7000         SetCCVT = getSetCCResultType(SetCCVT);
7001       SDValue SetCC = DAG.getSetCC(SDLoc(TheXor),
7002                                    SetCCVT,
7003                                    Op0, Op1,
7004                                    Equal ? ISD::SETEQ : ISD::SETNE);
7005       // Replace the uses of XOR with SETCC
7006       WorkListRemover DeadNodes(*this);
7007       DAG.ReplaceAllUsesOfValueWith(N1, SetCC);
7008       removeFromWorkList(N1.getNode());
7009       DAG.DeleteNode(N1.getNode());
7010       return DAG.getNode(ISD::BRCOND, SDLoc(N),
7011                          MVT::Other, Chain, SetCC, N2);
7012     }
7013   }
7014
7015   return SDValue();
7016 }
7017
7018 // Operand List for BR_CC: Chain, CondCC, CondLHS, CondRHS, DestBB.
7019 //
7020 SDValue DAGCombiner::visitBR_CC(SDNode *N) {
7021   CondCodeSDNode *CC = cast<CondCodeSDNode>(N->getOperand(1));
7022   SDValue CondLHS = N->getOperand(2), CondRHS = N->getOperand(3);
7023
7024   // If N is a constant we could fold this into a fallthrough or unconditional
7025   // branch. However that doesn't happen very often in normal code, because
7026   // Instcombine/SimplifyCFG should have handled the available opportunities.
7027   // If we did this folding here, it would be necessary to update the
7028   // MachineBasicBlock CFG, which is awkward.
7029
7030   // Use SimplifySetCC to simplify SETCC's.
7031   SDValue Simp = SimplifySetCC(getSetCCResultType(CondLHS.getValueType()),
7032                                CondLHS, CondRHS, CC->get(), SDLoc(N),
7033                                false);
7034   if (Simp.getNode()) AddToWorkList(Simp.getNode());
7035
7036   // fold to a simpler setcc
7037   if (Simp.getNode() && Simp.getOpcode() == ISD::SETCC)
7038     return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other,
7039                        N->getOperand(0), Simp.getOperand(2),
7040                        Simp.getOperand(0), Simp.getOperand(1),
7041                        N->getOperand(4));
7042
7043   return SDValue();
7044 }
7045
7046 /// canFoldInAddressingMode - Return true if 'Use' is a load or a store that
7047 /// uses N as its base pointer and that N may be folded in the load / store
7048 /// addressing mode.
7049 static bool canFoldInAddressingMode(SDNode *N, SDNode *Use,
7050                                     SelectionDAG &DAG,
7051                                     const TargetLowering &TLI) {
7052   EVT VT;
7053   if (LoadSDNode *LD  = dyn_cast<LoadSDNode>(Use)) {
7054     if (LD->isIndexed() || LD->getBasePtr().getNode() != N)
7055       return false;
7056     VT = Use->getValueType(0);
7057   } else if (StoreSDNode *ST  = dyn_cast<StoreSDNode>(Use)) {
7058     if (ST->isIndexed() || ST->getBasePtr().getNode() != N)
7059       return false;
7060     VT = ST->getValue().getValueType();
7061   } else
7062     return false;
7063
7064   TargetLowering::AddrMode AM;
7065   if (N->getOpcode() == ISD::ADD) {
7066     ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1));
7067     if (Offset)
7068       // [reg +/- imm]
7069       AM.BaseOffs = Offset->getSExtValue();
7070     else
7071       // [reg +/- reg]
7072       AM.Scale = 1;
7073   } else if (N->getOpcode() == ISD::SUB) {
7074     ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1));
7075     if (Offset)
7076       // [reg +/- imm]
7077       AM.BaseOffs = -Offset->getSExtValue();
7078     else
7079       // [reg +/- reg]
7080       AM.Scale = 1;
7081   } else
7082     return false;
7083
7084   return TLI.isLegalAddressingMode(AM, VT.getTypeForEVT(*DAG.getContext()));
7085 }
7086
7087 /// CombineToPreIndexedLoadStore - Try turning a load / store into a
7088 /// pre-indexed load / store when the base pointer is an add or subtract
7089 /// and it has other uses besides the load / store. After the
7090 /// transformation, the new indexed load / store has effectively folded
7091 /// the add / subtract in and all of its other uses are redirected to the
7092 /// new load / store.
7093 bool DAGCombiner::CombineToPreIndexedLoadStore(SDNode *N) {
7094   if (Level < AfterLegalizeDAG)
7095     return false;
7096
7097   bool isLoad = true;
7098   SDValue Ptr;
7099   EVT VT;
7100   if (LoadSDNode *LD  = dyn_cast<LoadSDNode>(N)) {
7101     if (LD->isIndexed())
7102       return false;
7103     VT = LD->getMemoryVT();
7104     if (!TLI.isIndexedLoadLegal(ISD::PRE_INC, VT) &&
7105         !TLI.isIndexedLoadLegal(ISD::PRE_DEC, VT))
7106       return false;
7107     Ptr = LD->getBasePtr();
7108   } else if (StoreSDNode *ST  = dyn_cast<StoreSDNode>(N)) {
7109     if (ST->isIndexed())
7110       return false;
7111     VT = ST->getMemoryVT();
7112     if (!TLI.isIndexedStoreLegal(ISD::PRE_INC, VT) &&
7113         !TLI.isIndexedStoreLegal(ISD::PRE_DEC, VT))
7114       return false;
7115     Ptr = ST->getBasePtr();
7116     isLoad = false;
7117   } else {
7118     return false;
7119   }
7120
7121   // If the pointer is not an add/sub, or if it doesn't have multiple uses, bail
7122   // out.  There is no reason to make this a preinc/predec.
7123   if ((Ptr.getOpcode() != ISD::ADD && Ptr.getOpcode() != ISD::SUB) ||
7124       Ptr.getNode()->hasOneUse())
7125     return false;
7126
7127   // Ask the target to do addressing mode selection.
7128   SDValue BasePtr;
7129   SDValue Offset;
7130   ISD::MemIndexedMode AM = ISD::UNINDEXED;
7131   if (!TLI.getPreIndexedAddressParts(N, BasePtr, Offset, AM, DAG))
7132     return false;
7133
7134   // Backends without true r+i pre-indexed forms may need to pass a
7135   // constant base with a variable offset so that constant coercion
7136   // will work with the patterns in canonical form.
7137   bool Swapped = false;
7138   if (isa<ConstantSDNode>(BasePtr)) {
7139     std::swap(BasePtr, Offset);
7140     Swapped = true;
7141   }
7142
7143   // Don't create a indexed load / store with zero offset.
7144   if (isa<ConstantSDNode>(Offset) &&
7145       cast<ConstantSDNode>(Offset)->isNullValue())
7146     return false;
7147
7148   // Try turning it into a pre-indexed load / store except when:
7149   // 1) The new base ptr is a frame index.
7150   // 2) If N is a store and the new base ptr is either the same as or is a
7151   //    predecessor of the value being stored.
7152   // 3) Another use of old base ptr is a predecessor of N. If ptr is folded
7153   //    that would create a cycle.
7154   // 4) All uses are load / store ops that use it as old base ptr.
7155
7156   // Check #1.  Preinc'ing a frame index would require copying the stack pointer
7157   // (plus the implicit offset) to a register to preinc anyway.
7158   if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr))
7159     return false;
7160
7161   // Check #2.
7162   if (!isLoad) {
7163     SDValue Val = cast<StoreSDNode>(N)->getValue();
7164     if (Val == BasePtr || BasePtr.getNode()->isPredecessorOf(Val.getNode()))
7165       return false;
7166   }
7167
7168   // If the offset is a constant, there may be other adds of constants that
7169   // can be folded with this one. We should do this to avoid having to keep
7170   // a copy of the original base pointer.
7171   SmallVector<SDNode *, 16> OtherUses;
7172   if (isa<ConstantSDNode>(Offset))
7173     for (SDNode::use_iterator I = BasePtr.getNode()->use_begin(),
7174          E = BasePtr.getNode()->use_end(); I != E; ++I) {
7175       SDNode *Use = *I;
7176       if (Use == Ptr.getNode())
7177         continue;
7178
7179       if (Use->isPredecessorOf(N))
7180         continue;
7181
7182       if (Use->getOpcode() != ISD::ADD && Use->getOpcode() != ISD::SUB) {
7183         OtherUses.clear();
7184         break;
7185       }
7186
7187       SDValue Op0 = Use->getOperand(0), Op1 = Use->getOperand(1);
7188       if (Op1.getNode() == BasePtr.getNode())
7189         std::swap(Op0, Op1);
7190       assert(Op0.getNode() == BasePtr.getNode() &&
7191              "Use of ADD/SUB but not an operand");
7192
7193       if (!isa<ConstantSDNode>(Op1)) {
7194         OtherUses.clear();
7195         break;
7196       }
7197
7198       // FIXME: In some cases, we can be smarter about this.
7199       if (Op1.getValueType() != Offset.getValueType()) {
7200         OtherUses.clear();
7201         break;
7202       }
7203
7204       OtherUses.push_back(Use);
7205     }
7206
7207   if (Swapped)
7208     std::swap(BasePtr, Offset);
7209
7210   // Now check for #3 and #4.
7211   bool RealUse = false;
7212
7213   // Caches for hasPredecessorHelper
7214   SmallPtrSet<const SDNode *, 32> Visited;
7215   SmallVector<const SDNode *, 16> Worklist;
7216
7217   for (SDNode::use_iterator I = Ptr.getNode()->use_begin(),
7218          E = Ptr.getNode()->use_end(); I != E; ++I) {
7219     SDNode *Use = *I;
7220     if (Use == N)
7221       continue;
7222     if (N->hasPredecessorHelper(Use, Visited, Worklist))
7223       return false;
7224
7225     // If Ptr may be folded in addressing mode of other use, then it's
7226     // not profitable to do this transformation.
7227     if (!canFoldInAddressingMode(Ptr.getNode(), Use, DAG, TLI))
7228       RealUse = true;
7229   }
7230
7231   if (!RealUse)
7232     return false;
7233
7234   SDValue Result;
7235   if (isLoad)
7236     Result = DAG.getIndexedLoad(SDValue(N,0), SDLoc(N),
7237                                 BasePtr, Offset, AM);
7238   else
7239     Result = DAG.getIndexedStore(SDValue(N,0), SDLoc(N),
7240                                  BasePtr, Offset, AM);
7241   ++PreIndexedNodes;
7242   ++NodesCombined;
7243   DEBUG(dbgs() << "\nReplacing.4 ";
7244         N->dump(&DAG);
7245         dbgs() << "\nWith: ";
7246         Result.getNode()->dump(&DAG);
7247         dbgs() << '\n');
7248   WorkListRemover DeadNodes(*this);
7249   if (isLoad) {
7250     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0));
7251     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2));
7252   } else {
7253     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1));
7254   }
7255
7256   // Finally, since the node is now dead, remove it from the graph.
7257   DAG.DeleteNode(N);
7258
7259   if (Swapped)
7260     std::swap(BasePtr, Offset);
7261
7262   // Replace other uses of BasePtr that can be updated to use Ptr
7263   for (unsigned i = 0, e = OtherUses.size(); i != e; ++i) {
7264     unsigned OffsetIdx = 1;
7265     if (OtherUses[i]->getOperand(OffsetIdx).getNode() == BasePtr.getNode())
7266       OffsetIdx = 0;
7267     assert(OtherUses[i]->getOperand(!OffsetIdx).getNode() ==
7268            BasePtr.getNode() && "Expected BasePtr operand");
7269
7270     // We need to replace ptr0 in the following expression:
7271     //   x0 * offset0 + y0 * ptr0 = t0
7272     // knowing that
7273     //   x1 * offset1 + y1 * ptr0 = t1 (the indexed load/store)
7274     //
7275     // where x0, x1, y0 and y1 in {-1, 1} are given by the types of the
7276     // indexed load/store and the expresion that needs to be re-written.
7277     //
7278     // Therefore, we have:
7279     //   t0 = (x0 * offset0 - x1 * y0 * y1 *offset1) + (y0 * y1) * t1
7280
7281     ConstantSDNode *CN =
7282       cast<ConstantSDNode>(OtherUses[i]->getOperand(OffsetIdx));
7283     int X0, X1, Y0, Y1;
7284     APInt Offset0 = CN->getAPIntValue();
7285     APInt Offset1 = cast<ConstantSDNode>(Offset)->getAPIntValue();
7286
7287     X0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 1) ? -1 : 1;
7288     Y0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 0) ? -1 : 1;
7289     X1 = (AM == ISD::PRE_DEC && !Swapped) ? -1 : 1;
7290     Y1 = (AM == ISD::PRE_DEC && Swapped) ? -1 : 1;
7291
7292     unsigned Opcode = (Y0 * Y1 < 0) ? ISD::SUB : ISD::ADD;
7293
7294     APInt CNV = Offset0;
7295     if (X0 < 0) CNV = -CNV;
7296     if (X1 * Y0 * Y1 < 0) CNV = CNV + Offset1;
7297     else CNV = CNV - Offset1;
7298
7299     // We can now generate the new expression.
7300     SDValue NewOp1 = DAG.getConstant(CNV, CN->getValueType(0));
7301     SDValue NewOp2 = Result.getValue(isLoad ? 1 : 0);
7302
7303     SDValue NewUse = DAG.getNode(Opcode,
7304                                  SDLoc(OtherUses[i]),
7305                                  OtherUses[i]->getValueType(0), NewOp1, NewOp2);
7306     DAG.ReplaceAllUsesOfValueWith(SDValue(OtherUses[i], 0), NewUse);
7307     removeFromWorkList(OtherUses[i]);
7308     DAG.DeleteNode(OtherUses[i]);
7309   }
7310
7311   // Replace the uses of Ptr with uses of the updated base value.
7312   DAG.ReplaceAllUsesOfValueWith(Ptr, Result.getValue(isLoad ? 1 : 0));
7313   removeFromWorkList(Ptr.getNode());
7314   DAG.DeleteNode(Ptr.getNode());
7315
7316   return true;
7317 }
7318
7319 /// CombineToPostIndexedLoadStore - Try to combine a load / store with a
7320 /// add / sub of the base pointer node into a post-indexed load / store.
7321 /// The transformation folded the add / subtract into the new indexed
7322 /// load / store effectively and all of its uses are redirected to the
7323 /// new load / store.
7324 bool DAGCombiner::CombineToPostIndexedLoadStore(SDNode *N) {
7325   if (Level < AfterLegalizeDAG)
7326     return false;
7327
7328   bool isLoad = true;
7329   SDValue Ptr;
7330   EVT VT;
7331   if (LoadSDNode *LD  = dyn_cast<LoadSDNode>(N)) {
7332     if (LD->isIndexed())
7333       return false;
7334     VT = LD->getMemoryVT();
7335     if (!TLI.isIndexedLoadLegal(ISD::POST_INC, VT) &&
7336         !TLI.isIndexedLoadLegal(ISD::POST_DEC, VT))
7337       return false;
7338     Ptr = LD->getBasePtr();
7339   } else if (StoreSDNode *ST  = dyn_cast<StoreSDNode>(N)) {
7340     if (ST->isIndexed())
7341       return false;
7342     VT = ST->getMemoryVT();
7343     if (!TLI.isIndexedStoreLegal(ISD::POST_INC, VT) &&
7344         !TLI.isIndexedStoreLegal(ISD::POST_DEC, VT))
7345       return false;
7346     Ptr = ST->getBasePtr();
7347     isLoad = false;
7348   } else {
7349     return false;
7350   }
7351
7352   if (Ptr.getNode()->hasOneUse())
7353     return false;
7354
7355   for (SDNode::use_iterator I = Ptr.getNode()->use_begin(),
7356          E = Ptr.getNode()->use_end(); I != E; ++I) {
7357     SDNode *Op = *I;
7358     if (Op == N ||
7359         (Op->getOpcode() != ISD::ADD && Op->getOpcode() != ISD::SUB))
7360       continue;
7361
7362     SDValue BasePtr;
7363     SDValue Offset;
7364     ISD::MemIndexedMode AM = ISD::UNINDEXED;
7365     if (TLI.getPostIndexedAddressParts(N, Op, BasePtr, Offset, AM, DAG)) {
7366       // Don't create a indexed load / store with zero offset.
7367       if (isa<ConstantSDNode>(Offset) &&
7368           cast<ConstantSDNode>(Offset)->isNullValue())
7369         continue;
7370
7371       // Try turning it into a post-indexed load / store except when
7372       // 1) All uses are load / store ops that use it as base ptr (and
7373       //    it may be folded as addressing mmode).
7374       // 2) Op must be independent of N, i.e. Op is neither a predecessor
7375       //    nor a successor of N. Otherwise, if Op is folded that would
7376       //    create a cycle.
7377
7378       if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr))
7379         continue;
7380
7381       // Check for #1.
7382       bool TryNext = false;
7383       for (SDNode::use_iterator II = BasePtr.getNode()->use_begin(),
7384              EE = BasePtr.getNode()->use_end(); II != EE; ++II) {
7385         SDNode *Use = *II;
7386         if (Use == Ptr.getNode())
7387           continue;
7388
7389         // If all the uses are load / store addresses, then don't do the
7390         // transformation.
7391         if (Use->getOpcode() == ISD::ADD || Use->getOpcode() == ISD::SUB){
7392           bool RealUse = false;
7393           for (SDNode::use_iterator III = Use->use_begin(),
7394                  EEE = Use->use_end(); III != EEE; ++III) {
7395             SDNode *UseUse = *III;
7396             if (!canFoldInAddressingMode(Use, UseUse, DAG, TLI))
7397               RealUse = true;
7398           }
7399
7400           if (!RealUse) {
7401             TryNext = true;
7402             break;
7403           }
7404         }
7405       }
7406
7407       if (TryNext)
7408         continue;
7409
7410       // Check for #2
7411       if (!Op->isPredecessorOf(N) && !N->isPredecessorOf(Op)) {
7412         SDValue Result = isLoad
7413           ? DAG.getIndexedLoad(SDValue(N,0), SDLoc(N),
7414                                BasePtr, Offset, AM)
7415           : DAG.getIndexedStore(SDValue(N,0), SDLoc(N),
7416                                 BasePtr, Offset, AM);
7417         ++PostIndexedNodes;
7418         ++NodesCombined;
7419         DEBUG(dbgs() << "\nReplacing.5 ";
7420               N->dump(&DAG);
7421               dbgs() << "\nWith: ";
7422               Result.getNode()->dump(&DAG);
7423               dbgs() << '\n');
7424         WorkListRemover DeadNodes(*this);
7425         if (isLoad) {
7426           DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0));
7427           DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2));
7428         } else {
7429           DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1));
7430         }
7431
7432         // Finally, since the node is now dead, remove it from the graph.
7433         DAG.DeleteNode(N);
7434
7435         // Replace the uses of Use with uses of the updated base value.
7436         DAG.ReplaceAllUsesOfValueWith(SDValue(Op, 0),
7437                                       Result.getValue(isLoad ? 1 : 0));
7438         removeFromWorkList(Op);
7439         DAG.DeleteNode(Op);
7440         return true;
7441       }
7442     }
7443   }
7444
7445   return false;
7446 }
7447
7448 SDValue DAGCombiner::visitLOAD(SDNode *N) {
7449   LoadSDNode *LD  = cast<LoadSDNode>(N);
7450   SDValue Chain = LD->getChain();
7451   SDValue Ptr   = LD->getBasePtr();
7452
7453   // If load is not volatile and there are no uses of the loaded value (and
7454   // the updated indexed value in case of indexed loads), change uses of the
7455   // chain value into uses of the chain input (i.e. delete the dead load).
7456   if (!LD->isVolatile()) {
7457     if (N->getValueType(1) == MVT::Other) {
7458       // Unindexed loads.
7459       if (!N->hasAnyUseOfValue(0)) {
7460         // It's not safe to use the two value CombineTo variant here. e.g.
7461         // v1, chain2 = load chain1, loc
7462         // v2, chain3 = load chain2, loc
7463         // v3         = add v2, c
7464         // Now we replace use of chain2 with chain1.  This makes the second load
7465         // isomorphic to the one we are deleting, and thus makes this load live.
7466         DEBUG(dbgs() << "\nReplacing.6 ";
7467               N->dump(&DAG);
7468               dbgs() << "\nWith chain: ";
7469               Chain.getNode()->dump(&DAG);
7470               dbgs() << "\n");
7471         WorkListRemover DeadNodes(*this);
7472         DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain);
7473
7474         if (N->use_empty()) {
7475           removeFromWorkList(N);
7476           DAG.DeleteNode(N);
7477         }
7478
7479         return SDValue(N, 0);   // Return N so it doesn't get rechecked!
7480       }
7481     } else {
7482       // Indexed loads.
7483       assert(N->getValueType(2) == MVT::Other && "Malformed indexed loads?");
7484       if (!N->hasAnyUseOfValue(0) && !N->hasAnyUseOfValue(1)) {
7485         SDValue Undef = DAG.getUNDEF(N->getValueType(0));
7486         DEBUG(dbgs() << "\nReplacing.7 ";
7487               N->dump(&DAG);
7488               dbgs() << "\nWith: ";
7489               Undef.getNode()->dump(&DAG);
7490               dbgs() << " and 2 other values\n");
7491         WorkListRemover DeadNodes(*this);
7492         DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Undef);
7493         DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1),
7494                                       DAG.getUNDEF(N->getValueType(1)));
7495         DAG.ReplaceAllUsesOfValueWith(SDValue(N, 2), Chain);
7496         removeFromWorkList(N);
7497         DAG.DeleteNode(N);
7498         return SDValue(N, 0);   // Return N so it doesn't get rechecked!
7499       }
7500     }
7501   }
7502
7503   // If this load is directly stored, replace the load value with the stored
7504   // value.
7505   // TODO: Handle store large -> read small portion.
7506   // TODO: Handle TRUNCSTORE/LOADEXT
7507   if (ISD::isNormalLoad(N) && !LD->isVolatile()) {
7508     if (ISD::isNON_TRUNCStore(Chain.getNode())) {
7509       StoreSDNode *PrevST = cast<StoreSDNode>(Chain);
7510       if (PrevST->getBasePtr() == Ptr &&
7511           PrevST->getValue().getValueType() == N->getValueType(0))
7512       return CombineTo(N, Chain.getOperand(1), Chain);
7513     }
7514   }
7515
7516   // Try to infer better alignment information than the load already has.
7517   if (OptLevel != CodeGenOpt::None && LD->isUnindexed()) {
7518     if (unsigned Align = DAG.InferPtrAlignment(Ptr)) {
7519       if (Align > LD->getMemOperand()->getBaseAlignment()) {
7520         SDValue NewLoad =
7521                DAG.getExtLoad(LD->getExtensionType(), SDLoc(N),
7522                               LD->getValueType(0),
7523                               Chain, Ptr, LD->getPointerInfo(),
7524                               LD->getMemoryVT(),
7525                               LD->isVolatile(), LD->isNonTemporal(), Align);
7526         return CombineTo(N, NewLoad, SDValue(NewLoad.getNode(), 1), true);
7527       }
7528     }
7529   }
7530
7531   bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA :
7532     TLI.getTargetMachine().getSubtarget<TargetSubtargetInfo>().useAA();
7533   if (UseAA) {
7534     // Walk up chain skipping non-aliasing memory nodes.
7535     SDValue BetterChain = FindBetterChain(N, Chain);
7536
7537     // If there is a better chain.
7538     if (Chain != BetterChain) {
7539       SDValue ReplLoad;
7540
7541       // Replace the chain to void dependency.
7542       if (LD->getExtensionType() == ISD::NON_EXTLOAD) {
7543         ReplLoad = DAG.getLoad(N->getValueType(0), SDLoc(LD),
7544                                BetterChain, Ptr, LD->getPointerInfo(),
7545                                LD->isVolatile(), LD->isNonTemporal(),
7546                                LD->isInvariant(), LD->getAlignment());
7547       } else {
7548         ReplLoad = DAG.getExtLoad(LD->getExtensionType(), SDLoc(LD),
7549                                   LD->getValueType(0),
7550                                   BetterChain, Ptr, LD->getPointerInfo(),
7551                                   LD->getMemoryVT(),
7552                                   LD->isVolatile(),
7553                                   LD->isNonTemporal(),
7554                                   LD->getAlignment());
7555       }
7556
7557       // Create token factor to keep old chain connected.
7558       SDValue Token = DAG.getNode(ISD::TokenFactor, SDLoc(N),
7559                                   MVT::Other, Chain, ReplLoad.getValue(1));
7560
7561       // Make sure the new and old chains are cleaned up.
7562       AddToWorkList(Token.getNode());
7563
7564       // Replace uses with load result and token factor. Don't add users
7565       // to work list.
7566       return CombineTo(N, ReplLoad.getValue(0), Token, false);
7567     }
7568   }
7569
7570   // Try transforming N to an indexed load.
7571   if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
7572     return SDValue(N, 0);
7573
7574   return SDValue();
7575 }
7576
7577 /// CheckForMaskedLoad - Check to see if V is (and load (ptr), imm), where the
7578 /// load is having specific bytes cleared out.  If so, return the byte size
7579 /// being masked out and the shift amount.
7580 static std::pair<unsigned, unsigned>
7581 CheckForMaskedLoad(SDValue V, SDValue Ptr, SDValue Chain) {
7582   std::pair<unsigned, unsigned> Result(0, 0);
7583
7584   // Check for the structure we're looking for.
7585   if (V->getOpcode() != ISD::AND ||
7586       !isa<ConstantSDNode>(V->getOperand(1)) ||
7587       !ISD::isNormalLoad(V->getOperand(0).getNode()))
7588     return Result;
7589
7590   // Check the chain and pointer.
7591   LoadSDNode *LD = cast<LoadSDNode>(V->getOperand(0));
7592   if (LD->getBasePtr() != Ptr) return Result;  // Not from same pointer.
7593
7594   // The store should be chained directly to the load or be an operand of a
7595   // tokenfactor.
7596   if (LD == Chain.getNode())
7597     ; // ok.
7598   else if (Chain->getOpcode() != ISD::TokenFactor)
7599     return Result; // Fail.
7600   else {
7601     bool isOk = false;
7602     for (unsigned i = 0, e = Chain->getNumOperands(); i != e; ++i)
7603       if (Chain->getOperand(i).getNode() == LD) {
7604         isOk = true;
7605         break;
7606       }
7607     if (!isOk) return Result;
7608   }
7609
7610   // This only handles simple types.
7611   if (V.getValueType() != MVT::i16 &&
7612       V.getValueType() != MVT::i32 &&
7613       V.getValueType() != MVT::i64)
7614     return Result;
7615
7616   // Check the constant mask.  Invert it so that the bits being masked out are
7617   // 0 and the bits being kept are 1.  Use getSExtValue so that leading bits
7618   // follow the sign bit for uniformity.
7619   uint64_t NotMask = ~cast<ConstantSDNode>(V->getOperand(1))->getSExtValue();
7620   unsigned NotMaskLZ = countLeadingZeros(NotMask);
7621   if (NotMaskLZ & 7) return Result;  // Must be multiple of a byte.
7622   unsigned NotMaskTZ = countTrailingZeros(NotMask);
7623   if (NotMaskTZ & 7) return Result;  // Must be multiple of a byte.
7624   if (NotMaskLZ == 64) return Result;  // All zero mask.
7625
7626   // See if we have a continuous run of bits.  If so, we have 0*1+0*
7627   if (CountTrailingOnes_64(NotMask >> NotMaskTZ)+NotMaskTZ+NotMaskLZ != 64)
7628     return Result;
7629
7630   // Adjust NotMaskLZ down to be from the actual size of the int instead of i64.
7631   if (V.getValueType() != MVT::i64 && NotMaskLZ)
7632     NotMaskLZ -= 64-V.getValueSizeInBits();
7633
7634   unsigned MaskedBytes = (V.getValueSizeInBits()-NotMaskLZ-NotMaskTZ)/8;
7635   switch (MaskedBytes) {
7636   case 1:
7637   case 2:
7638   case 4: break;
7639   default: return Result; // All one mask, or 5-byte mask.
7640   }
7641
7642   // Verify that the first bit starts at a multiple of mask so that the access
7643   // is aligned the same as the access width.
7644   if (NotMaskTZ && NotMaskTZ/8 % MaskedBytes) return Result;
7645
7646   Result.first = MaskedBytes;
7647   Result.second = NotMaskTZ/8;
7648   return Result;
7649 }
7650
7651
7652 /// ShrinkLoadReplaceStoreWithStore - Check to see if IVal is something that
7653 /// provides a value as specified by MaskInfo.  If so, replace the specified
7654 /// store with a narrower store of truncated IVal.
7655 static SDNode *
7656 ShrinkLoadReplaceStoreWithStore(const std::pair<unsigned, unsigned> &MaskInfo,
7657                                 SDValue IVal, StoreSDNode *St,
7658                                 DAGCombiner *DC) {
7659   unsigned NumBytes = MaskInfo.first;
7660   unsigned ByteShift = MaskInfo.second;
7661   SelectionDAG &DAG = DC->getDAG();
7662
7663   // Check to see if IVal is all zeros in the part being masked in by the 'or'
7664   // that uses this.  If not, this is not a replacement.
7665   APInt Mask = ~APInt::getBitsSet(IVal.getValueSizeInBits(),
7666                                   ByteShift*8, (ByteShift+NumBytes)*8);
7667   if (!DAG.MaskedValueIsZero(IVal, Mask)) return 0;
7668
7669   // Check that it is legal on the target to do this.  It is legal if the new
7670   // VT we're shrinking to (i8/i16/i32) is legal or we're still before type
7671   // legalization.
7672   MVT VT = MVT::getIntegerVT(NumBytes*8);
7673   if (!DC->isTypeLegal(VT))
7674     return 0;
7675
7676   // Okay, we can do this!  Replace the 'St' store with a store of IVal that is
7677   // shifted by ByteShift and truncated down to NumBytes.
7678   if (ByteShift)
7679     IVal = DAG.getNode(ISD::SRL, SDLoc(IVal), IVal.getValueType(), IVal,
7680                        DAG.getConstant(ByteShift*8,
7681                                     DC->getShiftAmountTy(IVal.getValueType())));
7682
7683   // Figure out the offset for the store and the alignment of the access.
7684   unsigned StOffset;
7685   unsigned NewAlign = St->getAlignment();
7686
7687   if (DAG.getTargetLoweringInfo().isLittleEndian())
7688     StOffset = ByteShift;
7689   else
7690     StOffset = IVal.getValueType().getStoreSize() - ByteShift - NumBytes;
7691
7692   SDValue Ptr = St->getBasePtr();
7693   if (StOffset) {
7694     Ptr = DAG.getNode(ISD::ADD, SDLoc(IVal), Ptr.getValueType(),
7695                       Ptr, DAG.getConstant(StOffset, Ptr.getValueType()));
7696     NewAlign = MinAlign(NewAlign, StOffset);
7697   }
7698
7699   // Truncate down to the new size.
7700   IVal = DAG.getNode(ISD::TRUNCATE, SDLoc(IVal), VT, IVal);
7701
7702   ++OpsNarrowed;
7703   return DAG.getStore(St->getChain(), SDLoc(St), IVal, Ptr,
7704                       St->getPointerInfo().getWithOffset(StOffset),
7705                       false, false, NewAlign).getNode();
7706 }
7707
7708
7709 /// ReduceLoadOpStoreWidth - Look for sequence of load / op / store where op is
7710 /// one of 'or', 'xor', and 'and' of immediates. If 'op' is only touching some
7711 /// of the loaded bits, try narrowing the load and store if it would end up
7712 /// being a win for performance or code size.
7713 SDValue DAGCombiner::ReduceLoadOpStoreWidth(SDNode *N) {
7714   StoreSDNode *ST  = cast<StoreSDNode>(N);
7715   if (ST->isVolatile())
7716     return SDValue();
7717
7718   SDValue Chain = ST->getChain();
7719   SDValue Value = ST->getValue();
7720   SDValue Ptr   = ST->getBasePtr();
7721   EVT VT = Value.getValueType();
7722
7723   if (ST->isTruncatingStore() || VT.isVector() || !Value.hasOneUse())
7724     return SDValue();
7725
7726   unsigned Opc = Value.getOpcode();
7727
7728   // If this is "store (or X, Y), P" and X is "(and (load P), cst)", where cst
7729   // is a byte mask indicating a consecutive number of bytes, check to see if
7730   // Y is known to provide just those bytes.  If so, we try to replace the
7731   // load + replace + store sequence with a single (narrower) store, which makes
7732   // the load dead.
7733   if (Opc == ISD::OR) {
7734     std::pair<unsigned, unsigned> MaskedLoad;
7735     MaskedLoad = CheckForMaskedLoad(Value.getOperand(0), Ptr, Chain);
7736     if (MaskedLoad.first)
7737       if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad,
7738                                                   Value.getOperand(1), ST,this))
7739         return SDValue(NewST, 0);
7740
7741     // Or is commutative, so try swapping X and Y.
7742     MaskedLoad = CheckForMaskedLoad(Value.getOperand(1), Ptr, Chain);
7743     if (MaskedLoad.first)
7744       if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad,
7745                                                   Value.getOperand(0), ST,this))
7746         return SDValue(NewST, 0);
7747   }
7748
7749   if ((Opc != ISD::OR && Opc != ISD::XOR && Opc != ISD::AND) ||
7750       Value.getOperand(1).getOpcode() != ISD::Constant)
7751     return SDValue();
7752
7753   SDValue N0 = Value.getOperand(0);
7754   if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
7755       Chain == SDValue(N0.getNode(), 1)) {
7756     LoadSDNode *LD = cast<LoadSDNode>(N0);
7757     if (LD->getBasePtr() != Ptr ||
7758         LD->getPointerInfo().getAddrSpace() !=
7759         ST->getPointerInfo().getAddrSpace())
7760       return SDValue();
7761
7762     // Find the type to narrow it the load / op / store to.
7763     SDValue N1 = Value.getOperand(1);
7764     unsigned BitWidth = N1.getValueSizeInBits();
7765     APInt Imm = cast<ConstantSDNode>(N1)->getAPIntValue();
7766     if (Opc == ISD::AND)
7767       Imm ^= APInt::getAllOnesValue(BitWidth);
7768     if (Imm == 0 || Imm.isAllOnesValue())
7769       return SDValue();
7770     unsigned ShAmt = Imm.countTrailingZeros();
7771     unsigned MSB = BitWidth - Imm.countLeadingZeros() - 1;
7772     unsigned NewBW = NextPowerOf2(MSB - ShAmt);
7773     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW);
7774     while (NewBW < BitWidth &&
7775            !(TLI.isOperationLegalOrCustom(Opc, NewVT) &&
7776              TLI.isNarrowingProfitable(VT, NewVT))) {
7777       NewBW = NextPowerOf2(NewBW);
7778       NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW);
7779     }
7780     if (NewBW >= BitWidth)
7781       return SDValue();
7782
7783     // If the lsb changed does not start at the type bitwidth boundary,
7784     // start at the previous one.
7785     if (ShAmt % NewBW)
7786       ShAmt = (((ShAmt + NewBW - 1) / NewBW) * NewBW) - NewBW;
7787     APInt Mask = APInt::getBitsSet(BitWidth, ShAmt,
7788                                    std::min(BitWidth, ShAmt + NewBW));
7789     if ((Imm & Mask) == Imm) {
7790       APInt NewImm = (Imm & Mask).lshr(ShAmt).trunc(NewBW);
7791       if (Opc == ISD::AND)
7792         NewImm ^= APInt::getAllOnesValue(NewBW);
7793       uint64_t PtrOff = ShAmt / 8;
7794       // For big endian targets, we need to adjust the offset to the pointer to
7795       // load the correct bytes.
7796       if (TLI.isBigEndian())
7797         PtrOff = (BitWidth + 7 - NewBW) / 8 - PtrOff;
7798
7799       unsigned NewAlign = MinAlign(LD->getAlignment(), PtrOff);
7800       Type *NewVTTy = NewVT.getTypeForEVT(*DAG.getContext());
7801       if (NewAlign < TLI.getDataLayout()->getABITypeAlignment(NewVTTy))
7802         return SDValue();
7803
7804       SDValue NewPtr = DAG.getNode(ISD::ADD, SDLoc(LD),
7805                                    Ptr.getValueType(), Ptr,
7806                                    DAG.getConstant(PtrOff, Ptr.getValueType()));
7807       SDValue NewLD = DAG.getLoad(NewVT, SDLoc(N0),
7808                                   LD->getChain(), NewPtr,
7809                                   LD->getPointerInfo().getWithOffset(PtrOff),
7810                                   LD->isVolatile(), LD->isNonTemporal(),
7811                                   LD->isInvariant(), NewAlign);
7812       SDValue NewVal = DAG.getNode(Opc, SDLoc(Value), NewVT, NewLD,
7813                                    DAG.getConstant(NewImm, NewVT));
7814       SDValue NewST = DAG.getStore(Chain, SDLoc(N),
7815                                    NewVal, NewPtr,
7816                                    ST->getPointerInfo().getWithOffset(PtrOff),
7817                                    false, false, NewAlign);
7818
7819       AddToWorkList(NewPtr.getNode());
7820       AddToWorkList(NewLD.getNode());
7821       AddToWorkList(NewVal.getNode());
7822       WorkListRemover DeadNodes(*this);
7823       DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLD.getValue(1));
7824       ++OpsNarrowed;
7825       return NewST;
7826     }
7827   }
7828
7829   return SDValue();
7830 }
7831
7832 /// TransformFPLoadStorePair - For a given floating point load / store pair,
7833 /// if the load value isn't used by any other operations, then consider
7834 /// transforming the pair to integer load / store operations if the target
7835 /// deems the transformation profitable.
7836 SDValue DAGCombiner::TransformFPLoadStorePair(SDNode *N) {
7837   StoreSDNode *ST  = cast<StoreSDNode>(N);
7838   SDValue Chain = ST->getChain();
7839   SDValue Value = ST->getValue();
7840   if (ISD::isNormalStore(ST) && ISD::isNormalLoad(Value.getNode()) &&
7841       Value.hasOneUse() &&
7842       Chain == SDValue(Value.getNode(), 1)) {
7843     LoadSDNode *LD = cast<LoadSDNode>(Value);
7844     EVT VT = LD->getMemoryVT();
7845     if (!VT.isFloatingPoint() ||
7846         VT != ST->getMemoryVT() ||
7847         LD->isNonTemporal() ||
7848         ST->isNonTemporal() ||
7849         LD->getPointerInfo().getAddrSpace() != 0 ||
7850         ST->getPointerInfo().getAddrSpace() != 0)
7851       return SDValue();
7852
7853     EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), VT.getSizeInBits());
7854     if (!TLI.isOperationLegal(ISD::LOAD, IntVT) ||
7855         !TLI.isOperationLegal(ISD::STORE, IntVT) ||
7856         !TLI.isDesirableToTransformToIntegerOp(ISD::LOAD, VT) ||
7857         !TLI.isDesirableToTransformToIntegerOp(ISD::STORE, VT))
7858       return SDValue();
7859
7860     unsigned LDAlign = LD->getAlignment();
7861     unsigned STAlign = ST->getAlignment();
7862     Type *IntVTTy = IntVT.getTypeForEVT(*DAG.getContext());
7863     unsigned ABIAlign = TLI.getDataLayout()->getABITypeAlignment(IntVTTy);
7864     if (LDAlign < ABIAlign || STAlign < ABIAlign)
7865       return SDValue();
7866
7867     SDValue NewLD = DAG.getLoad(IntVT, SDLoc(Value),
7868                                 LD->getChain(), LD->getBasePtr(),
7869                                 LD->getPointerInfo(),
7870                                 false, false, false, LDAlign);
7871
7872     SDValue NewST = DAG.getStore(NewLD.getValue(1), SDLoc(N),
7873                                  NewLD, ST->getBasePtr(),
7874                                  ST->getPointerInfo(),
7875                                  false, false, STAlign);
7876
7877     AddToWorkList(NewLD.getNode());
7878     AddToWorkList(NewST.getNode());
7879     WorkListRemover DeadNodes(*this);
7880     DAG.ReplaceAllUsesOfValueWith(Value.getValue(1), NewLD.getValue(1));
7881     ++LdStFP2Int;
7882     return NewST;
7883   }
7884
7885   return SDValue();
7886 }
7887
7888 /// Helper struct to parse and store a memory address as base + index + offset.
7889 /// We ignore sign extensions when it is safe to do so.
7890 /// The following two expressions are not equivalent. To differentiate we need
7891 /// to store whether there was a sign extension involved in the index
7892 /// computation.
7893 ///  (load (i64 add (i64 copyfromreg %c)
7894 ///                 (i64 signextend (add (i8 load %index)
7895 ///                                      (i8 1))))
7896 /// vs
7897 ///
7898 /// (load (i64 add (i64 copyfromreg %c)
7899 ///                (i64 signextend (i32 add (i32 signextend (i8 load %index))
7900 ///                                         (i32 1)))))
7901 struct BaseIndexOffset {
7902   SDValue Base;
7903   SDValue Index;
7904   int64_t Offset;
7905   bool IsIndexSignExt;
7906
7907   BaseIndexOffset() : Offset(0), IsIndexSignExt(false) {}
7908
7909   BaseIndexOffset(SDValue Base, SDValue Index, int64_t Offset,
7910                   bool IsIndexSignExt) :
7911     Base(Base), Index(Index), Offset(Offset), IsIndexSignExt(IsIndexSignExt) {}
7912
7913   bool equalBaseIndex(const BaseIndexOffset &Other) {
7914     return Other.Base == Base && Other.Index == Index &&
7915       Other.IsIndexSignExt == IsIndexSignExt;
7916   }
7917
7918   /// Parses tree in Ptr for base, index, offset addresses.
7919   static BaseIndexOffset match(SDValue Ptr) {
7920     bool IsIndexSignExt = false;
7921
7922     // We only can pattern match BASE + INDEX + OFFSET. If Ptr is not an ADD
7923     // instruction, then it could be just the BASE or everything else we don't
7924     // know how to handle. Just use Ptr as BASE and give up.
7925     if (Ptr->getOpcode() != ISD::ADD)
7926       return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
7927
7928     // We know that we have at least an ADD instruction. Try to pattern match
7929     // the simple case of BASE + OFFSET.
7930     if (isa<ConstantSDNode>(Ptr->getOperand(1))) {
7931       int64_t Offset = cast<ConstantSDNode>(Ptr->getOperand(1))->getSExtValue();
7932       return  BaseIndexOffset(Ptr->getOperand(0), SDValue(), Offset,
7933                               IsIndexSignExt);
7934     }
7935
7936     // Inside a loop the current BASE pointer is calculated using an ADD and a
7937     // MUL instruction. In this case Ptr is the actual BASE pointer.
7938     // (i64 add (i64 %array_ptr)
7939     //          (i64 mul (i64 %induction_var)
7940     //                   (i64 %element_size)))
7941     if (Ptr->getOperand(1)->getOpcode() == ISD::MUL)
7942       return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
7943
7944     // Look at Base + Index + Offset cases.
7945     SDValue Base = Ptr->getOperand(0);
7946     SDValue IndexOffset = Ptr->getOperand(1);
7947
7948     // Skip signextends.
7949     if (IndexOffset->getOpcode() == ISD::SIGN_EXTEND) {
7950       IndexOffset = IndexOffset->getOperand(0);
7951       IsIndexSignExt = true;
7952     }
7953
7954     // Either the case of Base + Index (no offset) or something else.
7955     if (IndexOffset->getOpcode() != ISD::ADD)
7956       return BaseIndexOffset(Base, IndexOffset, 0, IsIndexSignExt);
7957
7958     // Now we have the case of Base + Index + offset.
7959     SDValue Index = IndexOffset->getOperand(0);
7960     SDValue Offset = IndexOffset->getOperand(1);
7961
7962     if (!isa<ConstantSDNode>(Offset))
7963       return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
7964
7965     // Ignore signextends.
7966     if (Index->getOpcode() == ISD::SIGN_EXTEND) {
7967       Index = Index->getOperand(0);
7968       IsIndexSignExt = true;
7969     } else IsIndexSignExt = false;
7970
7971     int64_t Off = cast<ConstantSDNode>(Offset)->getSExtValue();
7972     return BaseIndexOffset(Base, Index, Off, IsIndexSignExt);
7973   }
7974 };
7975
7976 /// Holds a pointer to an LSBaseSDNode as well as information on where it
7977 /// is located in a sequence of memory operations connected by a chain.
7978 struct MemOpLink {
7979   MemOpLink (LSBaseSDNode *N, int64_t Offset, unsigned Seq):
7980     MemNode(N), OffsetFromBase(Offset), SequenceNum(Seq) { }
7981   // Ptr to the mem node.
7982   LSBaseSDNode *MemNode;
7983   // Offset from the base ptr.
7984   int64_t OffsetFromBase;
7985   // What is the sequence number of this mem node.
7986   // Lowest mem operand in the DAG starts at zero.
7987   unsigned SequenceNum;
7988 };
7989
7990 /// Sorts store nodes in a link according to their offset from a shared
7991 // base ptr.
7992 struct ConsecutiveMemoryChainSorter {
7993   bool operator()(MemOpLink LHS, MemOpLink RHS) {
7994     return LHS.OffsetFromBase < RHS.OffsetFromBase;
7995   }
7996 };
7997
7998 bool DAGCombiner::MergeConsecutiveStores(StoreSDNode* St) {
7999   EVT MemVT = St->getMemoryVT();
8000   int64_t ElementSizeBytes = MemVT.getSizeInBits()/8;
8001   bool NoVectors = DAG.getMachineFunction().getFunction()->getAttributes().
8002     hasAttribute(AttributeSet::FunctionIndex, Attribute::NoImplicitFloat);
8003
8004   // Don't merge vectors into wider inputs.
8005   if (MemVT.isVector() || !MemVT.isSimple())
8006     return false;
8007
8008   // Perform an early exit check. Do not bother looking at stored values that
8009   // are not constants or loads.
8010   SDValue StoredVal = St->getValue();
8011   bool IsLoadSrc = isa<LoadSDNode>(StoredVal);
8012   if (!isa<ConstantSDNode>(StoredVal) && !isa<ConstantFPSDNode>(StoredVal) &&
8013       !IsLoadSrc)
8014     return false;
8015
8016   // Only look at ends of store sequences.
8017   SDValue Chain = SDValue(St, 1);
8018   if (Chain->hasOneUse() && Chain->use_begin()->getOpcode() == ISD::STORE)
8019     return false;
8020
8021   // This holds the base pointer, index, and the offset in bytes from the base
8022   // pointer.
8023   BaseIndexOffset BasePtr = BaseIndexOffset::match(St->getBasePtr());
8024
8025   // We must have a base and an offset.
8026   if (!BasePtr.Base.getNode())
8027     return false;
8028
8029   // Do not handle stores to undef base pointers.
8030   if (BasePtr.Base.getOpcode() == ISD::UNDEF)
8031     return false;
8032
8033   // Save the LoadSDNodes that we find in the chain.
8034   // We need to make sure that these nodes do not interfere with
8035   // any of the store nodes.
8036   SmallVector<LSBaseSDNode*, 8> AliasLoadNodes;
8037
8038   // Save the StoreSDNodes that we find in the chain.
8039   SmallVector<MemOpLink, 8> StoreNodes;
8040
8041   // Walk up the chain and look for nodes with offsets from the same
8042   // base pointer. Stop when reaching an instruction with a different kind
8043   // or instruction which has a different base pointer.
8044   unsigned Seq = 0;
8045   StoreSDNode *Index = St;
8046   while (Index) {
8047     // If the chain has more than one use, then we can't reorder the mem ops.
8048     if (Index != St && !SDValue(Index, 1)->hasOneUse())
8049       break;
8050
8051     // Find the base pointer and offset for this memory node.
8052     BaseIndexOffset Ptr = BaseIndexOffset::match(Index->getBasePtr());
8053
8054     // Check that the base pointer is the same as the original one.
8055     if (!Ptr.equalBaseIndex(BasePtr))
8056       break;
8057
8058     // Check that the alignment is the same.
8059     if (Index->getAlignment() != St->getAlignment())
8060       break;
8061
8062     // The memory operands must not be volatile.
8063     if (Index->isVolatile() || Index->isIndexed())
8064       break;
8065
8066     // No truncation.
8067     if (StoreSDNode *St = dyn_cast<StoreSDNode>(Index))
8068       if (St->isTruncatingStore())
8069         break;
8070
8071     // The stored memory type must be the same.
8072     if (Index->getMemoryVT() != MemVT)
8073       break;
8074
8075     // We do not allow unaligned stores because we want to prevent overriding
8076     // stores.
8077     if (Index->getAlignment()*8 != MemVT.getSizeInBits())
8078       break;
8079
8080     // We found a potential memory operand to merge.
8081     StoreNodes.push_back(MemOpLink(Index, Ptr.Offset, Seq++));
8082
8083     // Find the next memory operand in the chain. If the next operand in the
8084     // chain is a store then move up and continue the scan with the next
8085     // memory operand. If the next operand is a load save it and use alias
8086     // information to check if it interferes with anything.
8087     SDNode *NextInChain = Index->getChain().getNode();
8088     while (1) {
8089       if (StoreSDNode *STn = dyn_cast<StoreSDNode>(NextInChain)) {
8090         // We found a store node. Use it for the next iteration.
8091         Index = STn;
8092         break;
8093       } else if (LoadSDNode *Ldn = dyn_cast<LoadSDNode>(NextInChain)) {
8094         // Save the load node for later. Continue the scan.
8095         AliasLoadNodes.push_back(Ldn);
8096         NextInChain = Ldn->getChain().getNode();
8097         continue;
8098       } else {
8099         Index = NULL;
8100         break;
8101       }
8102     }
8103   }
8104
8105   // Check if there is anything to merge.
8106   if (StoreNodes.size() < 2)
8107     return false;
8108
8109   // Sort the memory operands according to their distance from the base pointer.
8110   std::sort(StoreNodes.begin(), StoreNodes.end(),
8111             ConsecutiveMemoryChainSorter());
8112
8113   // Scan the memory operations on the chain and find the first non-consecutive
8114   // store memory address.
8115   unsigned LastConsecutiveStore = 0;
8116   int64_t StartAddress = StoreNodes[0].OffsetFromBase;
8117   for (unsigned i = 0, e = StoreNodes.size(); i < e; ++i) {
8118
8119     // Check that the addresses are consecutive starting from the second
8120     // element in the list of stores.
8121     if (i > 0) {
8122       int64_t CurrAddress = StoreNodes[i].OffsetFromBase;
8123       if (CurrAddress - StartAddress != (ElementSizeBytes * i))
8124         break;
8125     }
8126
8127     bool Alias = false;
8128     // Check if this store interferes with any of the loads that we found.
8129     for (unsigned ld = 0, lde = AliasLoadNodes.size(); ld < lde; ++ld)
8130       if (isAlias(AliasLoadNodes[ld], StoreNodes[i].MemNode)) {
8131         Alias = true;
8132         break;
8133       }
8134     // We found a load that alias with this store. Stop the sequence.
8135     if (Alias)
8136       break;
8137
8138     // Mark this node as useful.
8139     LastConsecutiveStore = i;
8140   }
8141
8142   // The node with the lowest store address.
8143   LSBaseSDNode *FirstInChain = StoreNodes[0].MemNode;
8144
8145   // Store the constants into memory as one consecutive store.
8146   if (!IsLoadSrc) {
8147     unsigned LastLegalType = 0;
8148     unsigned LastLegalVectorType = 0;
8149     bool NonZero = false;
8150     for (unsigned i=0; i<LastConsecutiveStore+1; ++i) {
8151       StoreSDNode *St  = cast<StoreSDNode>(StoreNodes[i].MemNode);
8152       SDValue StoredVal = St->getValue();
8153
8154       if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(StoredVal)) {
8155         NonZero |= !C->isNullValue();
8156       } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(StoredVal)) {
8157         NonZero |= !C->getConstantFPValue()->isNullValue();
8158       } else {
8159         // Non constant.
8160         break;
8161       }
8162
8163       // Find a legal type for the constant store.
8164       unsigned StoreBW = (i+1) * ElementSizeBytes * 8;
8165       EVT StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
8166       if (TLI.isTypeLegal(StoreTy))
8167         LastLegalType = i+1;
8168       // Or check whether a truncstore is legal.
8169       else if (TLI.getTypeAction(*DAG.getContext(), StoreTy) ==
8170                TargetLowering::TypePromoteInteger) {
8171         EVT LegalizedStoredValueTy =
8172           TLI.getTypeToTransformTo(*DAG.getContext(), StoredVal.getValueType());
8173         if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy))
8174           LastLegalType = i+1;
8175       }
8176
8177       // Find a legal type for the vector store.
8178       EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT, i+1);
8179       if (TLI.isTypeLegal(Ty))
8180         LastLegalVectorType = i + 1;
8181     }
8182
8183     // We only use vectors if the constant is known to be zero and the
8184     // function is not marked with the noimplicitfloat attribute.
8185     if (NonZero || NoVectors)
8186       LastLegalVectorType = 0;
8187
8188     // Check if we found a legal integer type to store.
8189     if (LastLegalType == 0 && LastLegalVectorType == 0)
8190       return false;
8191
8192     bool UseVector = (LastLegalVectorType > LastLegalType) && !NoVectors;
8193     unsigned NumElem = UseVector ? LastLegalVectorType : LastLegalType;
8194
8195     // Make sure we have something to merge.
8196     if (NumElem < 2)
8197       return false;
8198
8199     unsigned EarliestNodeUsed = 0;
8200     for (unsigned i=0; i < NumElem; ++i) {
8201       // Find a chain for the new wide-store operand. Notice that some
8202       // of the store nodes that we found may not be selected for inclusion
8203       // in the wide store. The chain we use needs to be the chain of the
8204       // earliest store node which is *used* and replaced by the wide store.
8205       if (StoreNodes[i].SequenceNum > StoreNodes[EarliestNodeUsed].SequenceNum)
8206         EarliestNodeUsed = i;
8207     }
8208
8209     // The earliest Node in the DAG.
8210     LSBaseSDNode *EarliestOp = StoreNodes[EarliestNodeUsed].MemNode;
8211     SDLoc DL(StoreNodes[0].MemNode);
8212
8213     SDValue StoredVal;
8214     if (UseVector) {
8215       // Find a legal type for the vector store.
8216       EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT, NumElem);
8217       assert(TLI.isTypeLegal(Ty) && "Illegal vector store");
8218       StoredVal = DAG.getConstant(0, Ty);
8219     } else {
8220       unsigned StoreBW = NumElem * ElementSizeBytes * 8;
8221       APInt StoreInt(StoreBW, 0);
8222
8223       // Construct a single integer constant which is made of the smaller
8224       // constant inputs.
8225       bool IsLE = TLI.isLittleEndian();
8226       for (unsigned i = 0; i < NumElem ; ++i) {
8227         unsigned Idx = IsLE ?(NumElem - 1 - i) : i;
8228         StoreSDNode *St  = cast<StoreSDNode>(StoreNodes[Idx].MemNode);
8229         SDValue Val = St->getValue();
8230         StoreInt<<=ElementSizeBytes*8;
8231         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Val)) {
8232           StoreInt|=C->getAPIntValue().zext(StoreBW);
8233         } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Val)) {
8234           StoreInt|= C->getValueAPF().bitcastToAPInt().zext(StoreBW);
8235         } else {
8236           assert(false && "Invalid constant element type");
8237         }
8238       }
8239
8240       // Create the new Load and Store operations.
8241       EVT StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
8242       StoredVal = DAG.getConstant(StoreInt, StoreTy);
8243     }
8244
8245     SDValue NewStore = DAG.getStore(EarliestOp->getChain(), DL, StoredVal,
8246                                     FirstInChain->getBasePtr(),
8247                                     FirstInChain->getPointerInfo(),
8248                                     false, false,
8249                                     FirstInChain->getAlignment());
8250
8251     // Replace the first store with the new store
8252     CombineTo(EarliestOp, NewStore);
8253     // Erase all other stores.
8254     for (unsigned i = 0; i < NumElem ; ++i) {
8255       if (StoreNodes[i].MemNode == EarliestOp)
8256         continue;
8257       StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
8258       // ReplaceAllUsesWith will replace all uses that existed when it was
8259       // called, but graph optimizations may cause new ones to appear. For
8260       // example, the case in pr14333 looks like
8261       //
8262       //  St's chain -> St -> another store -> X
8263       //
8264       // And the only difference from St to the other store is the chain.
8265       // When we change it's chain to be St's chain they become identical,
8266       // get CSEed and the net result is that X is now a use of St.
8267       // Since we know that St is redundant, just iterate.
8268       while (!St->use_empty())
8269         DAG.ReplaceAllUsesWith(SDValue(St, 0), St->getChain());
8270       removeFromWorkList(St);
8271       DAG.DeleteNode(St);
8272     }
8273
8274     return true;
8275   }
8276
8277   // Below we handle the case of multiple consecutive stores that
8278   // come from multiple consecutive loads. We merge them into a single
8279   // wide load and a single wide store.
8280
8281   // Look for load nodes which are used by the stored values.
8282   SmallVector<MemOpLink, 8> LoadNodes;
8283
8284   // Find acceptable loads. Loads need to have the same chain (token factor),
8285   // must not be zext, volatile, indexed, and they must be consecutive.
8286   BaseIndexOffset LdBasePtr;
8287   for (unsigned i=0; i<LastConsecutiveStore+1; ++i) {
8288     StoreSDNode *St  = cast<StoreSDNode>(StoreNodes[i].MemNode);
8289     LoadSDNode *Ld = dyn_cast<LoadSDNode>(St->getValue());
8290     if (!Ld) break;
8291
8292     // Loads must only have one use.
8293     if (!Ld->hasNUsesOfValue(1, 0))
8294       break;
8295
8296     // Check that the alignment is the same as the stores.
8297     if (Ld->getAlignment() != St->getAlignment())
8298       break;
8299
8300     // The memory operands must not be volatile.
8301     if (Ld->isVolatile() || Ld->isIndexed())
8302       break;
8303
8304     // We do not accept ext loads.
8305     if (Ld->getExtensionType() != ISD::NON_EXTLOAD)
8306       break;
8307
8308     // The stored memory type must be the same.
8309     if (Ld->getMemoryVT() != MemVT)
8310       break;
8311
8312     BaseIndexOffset LdPtr = BaseIndexOffset::match(Ld->getBasePtr());
8313     // If this is not the first ptr that we check.
8314     if (LdBasePtr.Base.getNode()) {
8315       // The base ptr must be the same.
8316       if (!LdPtr.equalBaseIndex(LdBasePtr))
8317         break;
8318     } else {
8319       // Check that all other base pointers are the same as this one.
8320       LdBasePtr = LdPtr;
8321     }
8322
8323     // We found a potential memory operand to merge.
8324     LoadNodes.push_back(MemOpLink(Ld, LdPtr.Offset, 0));
8325   }
8326
8327   if (LoadNodes.size() < 2)
8328     return false;
8329
8330   // Scan the memory operations on the chain and find the first non-consecutive
8331   // load memory address. These variables hold the index in the store node
8332   // array.
8333   unsigned LastConsecutiveLoad = 0;
8334   // This variable refers to the size and not index in the array.
8335   unsigned LastLegalVectorType = 0;
8336   unsigned LastLegalIntegerType = 0;
8337   StartAddress = LoadNodes[0].OffsetFromBase;
8338   SDValue FirstChain = LoadNodes[0].MemNode->getChain();
8339   for (unsigned i = 1; i < LoadNodes.size(); ++i) {
8340     // All loads much share the same chain.
8341     if (LoadNodes[i].MemNode->getChain() != FirstChain)
8342       break;
8343
8344     int64_t CurrAddress = LoadNodes[i].OffsetFromBase;
8345     if (CurrAddress - StartAddress != (ElementSizeBytes * i))
8346       break;
8347     LastConsecutiveLoad = i;
8348
8349     // Find a legal type for the vector store.
8350     EVT StoreTy = EVT::getVectorVT(*DAG.getContext(), MemVT, i+1);
8351     if (TLI.isTypeLegal(StoreTy))
8352       LastLegalVectorType = i + 1;
8353
8354     // Find a legal type for the integer store.
8355     unsigned StoreBW = (i+1) * ElementSizeBytes * 8;
8356     StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
8357     if (TLI.isTypeLegal(StoreTy))
8358       LastLegalIntegerType = i + 1;
8359     // Or check whether a truncstore and extload is legal.
8360     else if (TLI.getTypeAction(*DAG.getContext(), StoreTy) ==
8361              TargetLowering::TypePromoteInteger) {
8362       EVT LegalizedStoredValueTy =
8363         TLI.getTypeToTransformTo(*DAG.getContext(), StoreTy);
8364       if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy) &&
8365           TLI.isLoadExtLegal(ISD::ZEXTLOAD, StoreTy) &&
8366           TLI.isLoadExtLegal(ISD::SEXTLOAD, StoreTy) &&
8367           TLI.isLoadExtLegal(ISD::EXTLOAD, StoreTy))
8368         LastLegalIntegerType = i+1;
8369     }
8370   }
8371
8372   // Only use vector types if the vector type is larger than the integer type.
8373   // If they are the same, use integers.
8374   bool UseVectorTy = LastLegalVectorType > LastLegalIntegerType && !NoVectors;
8375   unsigned LastLegalType = std::max(LastLegalVectorType, LastLegalIntegerType);
8376
8377   // We add +1 here because the LastXXX variables refer to location while
8378   // the NumElem refers to array/index size.
8379   unsigned NumElem = std::min(LastConsecutiveStore, LastConsecutiveLoad) + 1;
8380   NumElem = std::min(LastLegalType, NumElem);
8381
8382   if (NumElem < 2)
8383     return false;
8384
8385   // The earliest Node in the DAG.
8386   unsigned EarliestNodeUsed = 0;
8387   LSBaseSDNode *EarliestOp = StoreNodes[EarliestNodeUsed].MemNode;
8388   for (unsigned i=1; i<NumElem; ++i) {
8389     // Find a chain for the new wide-store operand. Notice that some
8390     // of the store nodes that we found may not be selected for inclusion
8391     // in the wide store. The chain we use needs to be the chain of the
8392     // earliest store node which is *used* and replaced by the wide store.
8393     if (StoreNodes[i].SequenceNum > StoreNodes[EarliestNodeUsed].SequenceNum)
8394       EarliestNodeUsed = i;
8395   }
8396
8397   // Find if it is better to use vectors or integers to load and store
8398   // to memory.
8399   EVT JointMemOpVT;
8400   if (UseVectorTy) {
8401     JointMemOpVT = EVT::getVectorVT(*DAG.getContext(), MemVT, NumElem);
8402   } else {
8403     unsigned StoreBW = NumElem * ElementSizeBytes * 8;
8404     JointMemOpVT = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
8405   }
8406
8407   SDLoc LoadDL(LoadNodes[0].MemNode);
8408   SDLoc StoreDL(StoreNodes[0].MemNode);
8409
8410   LoadSDNode *FirstLoad = cast<LoadSDNode>(LoadNodes[0].MemNode);
8411   SDValue NewLoad = DAG.getLoad(JointMemOpVT, LoadDL,
8412                                 FirstLoad->getChain(),
8413                                 FirstLoad->getBasePtr(),
8414                                 FirstLoad->getPointerInfo(),
8415                                 false, false, false,
8416                                 FirstLoad->getAlignment());
8417
8418   SDValue NewStore = DAG.getStore(EarliestOp->getChain(), StoreDL, NewLoad,
8419                                   FirstInChain->getBasePtr(),
8420                                   FirstInChain->getPointerInfo(), false, false,
8421                                   FirstInChain->getAlignment());
8422
8423   // Replace one of the loads with the new load.
8424   LoadSDNode *Ld = cast<LoadSDNode>(LoadNodes[0].MemNode);
8425   DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1),
8426                                 SDValue(NewLoad.getNode(), 1));
8427
8428   // Remove the rest of the load chains.
8429   for (unsigned i = 1; i < NumElem ; ++i) {
8430     // Replace all chain users of the old load nodes with the chain of the new
8431     // load node.
8432     LoadSDNode *Ld = cast<LoadSDNode>(LoadNodes[i].MemNode);
8433     DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), Ld->getChain());
8434   }
8435
8436   // Replace the first store with the new store.
8437   CombineTo(EarliestOp, NewStore);
8438   // Erase all other stores.
8439   for (unsigned i = 0; i < NumElem ; ++i) {
8440     // Remove all Store nodes.
8441     if (StoreNodes[i].MemNode == EarliestOp)
8442       continue;
8443     StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
8444     DAG.ReplaceAllUsesOfValueWith(SDValue(St, 0), St->getChain());
8445     removeFromWorkList(St);
8446     DAG.DeleteNode(St);
8447   }
8448
8449   return true;
8450 }
8451
8452 SDValue DAGCombiner::visitSTORE(SDNode *N) {
8453   StoreSDNode *ST  = cast<StoreSDNode>(N);
8454   SDValue Chain = ST->getChain();
8455   SDValue Value = ST->getValue();
8456   SDValue Ptr   = ST->getBasePtr();
8457
8458   // If this is a store of a bit convert, store the input value if the
8459   // resultant store does not need a higher alignment than the original.
8460   if (Value.getOpcode() == ISD::BITCAST && !ST->isTruncatingStore() &&
8461       ST->isUnindexed()) {
8462     unsigned OrigAlign = ST->getAlignment();
8463     EVT SVT = Value.getOperand(0).getValueType();
8464     unsigned Align = TLI.getDataLayout()->
8465       getABITypeAlignment(SVT.getTypeForEVT(*DAG.getContext()));
8466     if (Align <= OrigAlign &&
8467         ((!LegalOperations && !ST->isVolatile()) ||
8468          TLI.isOperationLegalOrCustom(ISD::STORE, SVT)))
8469       return DAG.getStore(Chain, SDLoc(N), Value.getOperand(0),
8470                           Ptr, ST->getPointerInfo(), ST->isVolatile(),
8471                           ST->isNonTemporal(), OrigAlign);
8472   }
8473
8474   // Turn 'store undef, Ptr' -> nothing.
8475   if (Value.getOpcode() == ISD::UNDEF && ST->isUnindexed())
8476     return Chain;
8477
8478   // Turn 'store float 1.0, Ptr' -> 'store int 0x12345678, Ptr'
8479   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Value)) {
8480     // NOTE: If the original store is volatile, this transform must not increase
8481     // the number of stores.  For example, on x86-32 an f64 can be stored in one
8482     // processor operation but an i64 (which is not legal) requires two.  So the
8483     // transform should not be done in this case.
8484     if (Value.getOpcode() != ISD::TargetConstantFP) {
8485       SDValue Tmp;
8486       switch (CFP->getSimpleValueType(0).SimpleTy) {
8487       default: llvm_unreachable("Unknown FP type");
8488       case MVT::f16:    // We don't do this for these yet.
8489       case MVT::f80:
8490       case MVT::f128:
8491       case MVT::ppcf128:
8492         break;
8493       case MVT::f32:
8494         if ((isTypeLegal(MVT::i32) && !LegalOperations && !ST->isVolatile()) ||
8495             TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) {
8496           Tmp = DAG.getConstant((uint32_t)CFP->getValueAPF().
8497                               bitcastToAPInt().getZExtValue(), MVT::i32);
8498           return DAG.getStore(Chain, SDLoc(N), Tmp,
8499                               Ptr, ST->getPointerInfo(), ST->isVolatile(),
8500                               ST->isNonTemporal(), ST->getAlignment());
8501         }
8502         break;
8503       case MVT::f64:
8504         if ((TLI.isTypeLegal(MVT::i64) && !LegalOperations &&
8505              !ST->isVolatile()) ||
8506             TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i64)) {
8507           Tmp = DAG.getConstant(CFP->getValueAPF().bitcastToAPInt().
8508                                 getZExtValue(), MVT::i64);
8509           return DAG.getStore(Chain, SDLoc(N), Tmp,
8510                               Ptr, ST->getPointerInfo(), ST->isVolatile(),
8511                               ST->isNonTemporal(), ST->getAlignment());
8512         }
8513
8514         if (!ST->isVolatile() &&
8515             TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) {
8516           // Many FP stores are not made apparent until after legalize, e.g. for
8517           // argument passing.  Since this is so common, custom legalize the
8518           // 64-bit integer store into two 32-bit stores.
8519           uint64_t Val = CFP->getValueAPF().bitcastToAPInt().getZExtValue();
8520           SDValue Lo = DAG.getConstant(Val & 0xFFFFFFFF, MVT::i32);
8521           SDValue Hi = DAG.getConstant(Val >> 32, MVT::i32);
8522           if (TLI.isBigEndian()) std::swap(Lo, Hi);
8523
8524           unsigned Alignment = ST->getAlignment();
8525           bool isVolatile = ST->isVolatile();
8526           bool isNonTemporal = ST->isNonTemporal();
8527
8528           SDValue St0 = DAG.getStore(Chain, SDLoc(ST), Lo,
8529                                      Ptr, ST->getPointerInfo(),
8530                                      isVolatile, isNonTemporal,
8531                                      ST->getAlignment());
8532           Ptr = DAG.getNode(ISD::ADD, SDLoc(N), Ptr.getValueType(), Ptr,
8533                             DAG.getConstant(4, Ptr.getValueType()));
8534           Alignment = MinAlign(Alignment, 4U);
8535           SDValue St1 = DAG.getStore(Chain, SDLoc(ST), Hi,
8536                                      Ptr, ST->getPointerInfo().getWithOffset(4),
8537                                      isVolatile, isNonTemporal,
8538                                      Alignment);
8539           return DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other,
8540                              St0, St1);
8541         }
8542
8543         break;
8544       }
8545     }
8546   }
8547
8548   // Try to infer better alignment information than the store already has.
8549   if (OptLevel != CodeGenOpt::None && ST->isUnindexed()) {
8550     if (unsigned Align = DAG.InferPtrAlignment(Ptr)) {
8551       if (Align > ST->getAlignment())
8552         return DAG.getTruncStore(Chain, SDLoc(N), Value,
8553                                  Ptr, ST->getPointerInfo(), ST->getMemoryVT(),
8554                                  ST->isVolatile(), ST->isNonTemporal(), Align);
8555     }
8556   }
8557
8558   // Try transforming a pair floating point load / store ops to integer
8559   // load / store ops.
8560   SDValue NewST = TransformFPLoadStorePair(N);
8561   if (NewST.getNode())
8562     return NewST;
8563
8564   bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA :
8565     TLI.getTargetMachine().getSubtarget<TargetSubtargetInfo>().useAA();
8566   if (UseAA) {
8567     // Walk up chain skipping non-aliasing memory nodes.
8568     SDValue BetterChain = FindBetterChain(N, Chain);
8569
8570     // If there is a better chain.
8571     if (Chain != BetterChain) {
8572       SDValue ReplStore;
8573
8574       // Replace the chain to avoid dependency.
8575       if (ST->isTruncatingStore()) {
8576         ReplStore = DAG.getTruncStore(BetterChain, SDLoc(N), Value, Ptr,
8577                                       ST->getPointerInfo(),
8578                                       ST->getMemoryVT(), ST->isVolatile(),
8579                                       ST->isNonTemporal(), ST->getAlignment());
8580       } else {
8581         ReplStore = DAG.getStore(BetterChain, SDLoc(N), Value, Ptr,
8582                                  ST->getPointerInfo(),
8583                                  ST->isVolatile(), ST->isNonTemporal(),
8584                                  ST->getAlignment());
8585       }
8586
8587       // Create token to keep both nodes around.
8588       SDValue Token = DAG.getNode(ISD::TokenFactor, SDLoc(N),
8589                                   MVT::Other, Chain, ReplStore);
8590
8591       // Make sure the new and old chains are cleaned up.
8592       AddToWorkList(Token.getNode());
8593
8594       // Don't add users to work list.
8595       return CombineTo(N, Token, false);
8596     }
8597   }
8598
8599   // Try transforming N to an indexed store.
8600   if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
8601     return SDValue(N, 0);
8602
8603   // FIXME: is there such a thing as a truncating indexed store?
8604   if (ST->isTruncatingStore() && ST->isUnindexed() &&
8605       Value.getValueType().isInteger()) {
8606     // See if we can simplify the input to this truncstore with knowledge that
8607     // only the low bits are being used.  For example:
8608     // "truncstore (or (shl x, 8), y), i8"  -> "truncstore y, i8"
8609     SDValue Shorter =
8610       GetDemandedBits(Value,
8611                       APInt::getLowBitsSet(
8612                         Value.getValueType().getScalarType().getSizeInBits(),
8613                         ST->getMemoryVT().getScalarType().getSizeInBits()));
8614     AddToWorkList(Value.getNode());
8615     if (Shorter.getNode())
8616       return DAG.getTruncStore(Chain, SDLoc(N), Shorter,
8617                                Ptr, ST->getPointerInfo(), ST->getMemoryVT(),
8618                                ST->isVolatile(), ST->isNonTemporal(),
8619                                ST->getAlignment());
8620
8621     // Otherwise, see if we can simplify the operation with
8622     // SimplifyDemandedBits, which only works if the value has a single use.
8623     if (SimplifyDemandedBits(Value,
8624                         APInt::getLowBitsSet(
8625                           Value.getValueType().getScalarType().getSizeInBits(),
8626                           ST->getMemoryVT().getScalarType().getSizeInBits())))
8627       return SDValue(N, 0);
8628   }
8629
8630   // If this is a load followed by a store to the same location, then the store
8631   // is dead/noop.
8632   if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Value)) {
8633     if (Ld->getBasePtr() == Ptr && ST->getMemoryVT() == Ld->getMemoryVT() &&
8634         ST->isUnindexed() && !ST->isVolatile() &&
8635         // There can't be any side effects between the load and store, such as
8636         // a call or store.
8637         Chain.reachesChainWithoutSideEffects(SDValue(Ld, 1))) {
8638       // The store is dead, remove it.
8639       return Chain;
8640     }
8641   }
8642
8643   // If this is an FP_ROUND or TRUNC followed by a store, fold this into a
8644   // truncating store.  We can do this even if this is already a truncstore.
8645   if ((Value.getOpcode() == ISD::FP_ROUND || Value.getOpcode() == ISD::TRUNCATE)
8646       && Value.getNode()->hasOneUse() && ST->isUnindexed() &&
8647       TLI.isTruncStoreLegal(Value.getOperand(0).getValueType(),
8648                             ST->getMemoryVT())) {
8649     return DAG.getTruncStore(Chain, SDLoc(N), Value.getOperand(0),
8650                              Ptr, ST->getPointerInfo(), ST->getMemoryVT(),
8651                              ST->isVolatile(), ST->isNonTemporal(),
8652                              ST->getAlignment());
8653   }
8654
8655   // Only perform this optimization before the types are legal, because we
8656   // don't want to perform this optimization on every DAGCombine invocation.
8657   if (!LegalTypes) {
8658     bool EverChanged = false;
8659
8660     do {
8661       // There can be multiple store sequences on the same chain.
8662       // Keep trying to merge store sequences until we are unable to do so
8663       // or until we merge the last store on the chain.
8664       bool Changed = MergeConsecutiveStores(ST);
8665       EverChanged |= Changed;
8666       if (!Changed) break;
8667     } while (ST->getOpcode() != ISD::DELETED_NODE);
8668
8669     if (EverChanged)
8670       return SDValue(N, 0);
8671   }
8672
8673   return ReduceLoadOpStoreWidth(N);
8674 }
8675
8676 SDValue DAGCombiner::visitINSERT_VECTOR_ELT(SDNode *N) {
8677   SDValue InVec = N->getOperand(0);
8678   SDValue InVal = N->getOperand(1);
8679   SDValue EltNo = N->getOperand(2);
8680   SDLoc dl(N);
8681
8682   // If the inserted element is an UNDEF, just use the input vector.
8683   if (InVal.getOpcode() == ISD::UNDEF)
8684     return InVec;
8685
8686   EVT VT = InVec.getValueType();
8687
8688   // If we can't generate a legal BUILD_VECTOR, exit
8689   if (LegalOperations && !TLI.isOperationLegal(ISD::BUILD_VECTOR, VT))
8690     return SDValue();
8691
8692   // Check that we know which element is being inserted
8693   if (!isa<ConstantSDNode>(EltNo))
8694     return SDValue();
8695   unsigned Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
8696
8697   // Check that the operand is a BUILD_VECTOR (or UNDEF, which can essentially
8698   // be converted to a BUILD_VECTOR).  Fill in the Ops vector with the
8699   // vector elements.
8700   SmallVector<SDValue, 8> Ops;
8701   // Do not combine these two vectors if the output vector will not replace
8702   // the input vector.
8703   if (InVec.getOpcode() == ISD::BUILD_VECTOR && InVec.hasOneUse()) {
8704     Ops.append(InVec.getNode()->op_begin(),
8705                InVec.getNode()->op_end());
8706   } else if (InVec.getOpcode() == ISD::UNDEF) {
8707     unsigned NElts = VT.getVectorNumElements();
8708     Ops.append(NElts, DAG.getUNDEF(InVal.getValueType()));
8709   } else {
8710     return SDValue();
8711   }
8712
8713   // Insert the element
8714   if (Elt < Ops.size()) {
8715     // All the operands of BUILD_VECTOR must have the same type;
8716     // we enforce that here.
8717     EVT OpVT = Ops[0].getValueType();
8718     if (InVal.getValueType() != OpVT)
8719       InVal = OpVT.bitsGT(InVal.getValueType()) ?
8720                 DAG.getNode(ISD::ANY_EXTEND, dl, OpVT, InVal) :
8721                 DAG.getNode(ISD::TRUNCATE, dl, OpVT, InVal);
8722     Ops[Elt] = InVal;
8723   }
8724
8725   // Return the new vector
8726   return DAG.getNode(ISD::BUILD_VECTOR, dl,
8727                      VT, &Ops[0], Ops.size());
8728 }
8729
8730 SDValue DAGCombiner::visitEXTRACT_VECTOR_ELT(SDNode *N) {
8731   // (vextract (scalar_to_vector val, 0) -> val
8732   SDValue InVec = N->getOperand(0);
8733   EVT VT = InVec.getValueType();
8734   EVT NVT = N->getValueType(0);
8735
8736   if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR) {
8737     // Check if the result type doesn't match the inserted element type. A
8738     // SCALAR_TO_VECTOR may truncate the inserted element and the
8739     // EXTRACT_VECTOR_ELT may widen the extracted vector.
8740     SDValue InOp = InVec.getOperand(0);
8741     if (InOp.getValueType() != NVT) {
8742       assert(InOp.getValueType().isInteger() && NVT.isInteger());
8743       return DAG.getSExtOrTrunc(InOp, SDLoc(InVec), NVT);
8744     }
8745     return InOp;
8746   }
8747
8748   SDValue EltNo = N->getOperand(1);
8749   bool ConstEltNo = isa<ConstantSDNode>(EltNo);
8750
8751   // Transform: (EXTRACT_VECTOR_ELT( VECTOR_SHUFFLE )) -> EXTRACT_VECTOR_ELT.
8752   // We only perform this optimization before the op legalization phase because
8753   // we may introduce new vector instructions which are not backed by TD
8754   // patterns. For example on AVX, extracting elements from a wide vector
8755   // without using extract_subvector.
8756   if (InVec.getOpcode() == ISD::VECTOR_SHUFFLE
8757       && ConstEltNo && !LegalOperations) {
8758     int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
8759     int NumElem = VT.getVectorNumElements();
8760     ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(InVec);
8761     // Find the new index to extract from.
8762     int OrigElt = SVOp->getMaskElt(Elt);
8763
8764     // Extracting an undef index is undef.
8765     if (OrigElt == -1)
8766       return DAG.getUNDEF(NVT);
8767
8768     // Select the right vector half to extract from.
8769     if (OrigElt < NumElem) {
8770       InVec = InVec->getOperand(0);
8771     } else {
8772       InVec = InVec->getOperand(1);
8773       OrigElt -= NumElem;
8774     }
8775
8776     EVT IndexTy = TLI.getVectorIdxTy();
8777     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SDLoc(N), NVT,
8778                        InVec, DAG.getConstant(OrigElt, IndexTy));
8779   }
8780
8781   // Perform only after legalization to ensure build_vector / vector_shuffle
8782   // optimizations have already been done.
8783   if (!LegalOperations) return SDValue();
8784
8785   // (vextract (v4f32 load $addr), c) -> (f32 load $addr+c*size)
8786   // (vextract (v4f32 s2v (f32 load $addr)), c) -> (f32 load $addr+c*size)
8787   // (vextract (v4f32 shuffle (load $addr), <1,u,u,u>), 0) -> (f32 load $addr)
8788
8789   if (ConstEltNo) {
8790     int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
8791     bool NewLoad = false;
8792     bool BCNumEltsChanged = false;
8793     EVT ExtVT = VT.getVectorElementType();
8794     EVT LVT = ExtVT;
8795
8796     // If the result of load has to be truncated, then it's not necessarily
8797     // profitable.
8798     if (NVT.bitsLT(LVT) && !TLI.isTruncateFree(LVT, NVT))
8799       return SDValue();
8800
8801     if (InVec.getOpcode() == ISD::BITCAST) {
8802       // Don't duplicate a load with other uses.
8803       if (!InVec.hasOneUse())
8804         return SDValue();
8805
8806       EVT BCVT = InVec.getOperand(0).getValueType();
8807       if (!BCVT.isVector() || ExtVT.bitsGT(BCVT.getVectorElementType()))
8808         return SDValue();
8809       if (VT.getVectorNumElements() != BCVT.getVectorNumElements())
8810         BCNumEltsChanged = true;
8811       InVec = InVec.getOperand(0);
8812       ExtVT = BCVT.getVectorElementType();
8813       NewLoad = true;
8814     }
8815
8816     LoadSDNode *LN0 = NULL;
8817     const ShuffleVectorSDNode *SVN = NULL;
8818     if (ISD::isNormalLoad(InVec.getNode())) {
8819       LN0 = cast<LoadSDNode>(InVec);
8820     } else if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR &&
8821                InVec.getOperand(0).getValueType() == ExtVT &&
8822                ISD::isNormalLoad(InVec.getOperand(0).getNode())) {
8823       // Don't duplicate a load with other uses.
8824       if (!InVec.hasOneUse())
8825         return SDValue();
8826
8827       LN0 = cast<LoadSDNode>(InVec.getOperand(0));
8828     } else if ((SVN = dyn_cast<ShuffleVectorSDNode>(InVec))) {
8829       // (vextract (vector_shuffle (load $addr), v2, <1, u, u, u>), 1)
8830       // =>
8831       // (load $addr+1*size)
8832
8833       // Don't duplicate a load with other uses.
8834       if (!InVec.hasOneUse())
8835         return SDValue();
8836
8837       // If the bit convert changed the number of elements, it is unsafe
8838       // to examine the mask.
8839       if (BCNumEltsChanged)
8840         return SDValue();
8841
8842       // Select the input vector, guarding against out of range extract vector.
8843       unsigned NumElems = VT.getVectorNumElements();
8844       int Idx = (Elt > (int)NumElems) ? -1 : SVN->getMaskElt(Elt);
8845       InVec = (Idx < (int)NumElems) ? InVec.getOperand(0) : InVec.getOperand(1);
8846
8847       if (InVec.getOpcode() == ISD::BITCAST) {
8848         // Don't duplicate a load with other uses.
8849         if (!InVec.hasOneUse())
8850           return SDValue();
8851
8852         InVec = InVec.getOperand(0);
8853       }
8854       if (ISD::isNormalLoad(InVec.getNode())) {
8855         LN0 = cast<LoadSDNode>(InVec);
8856         Elt = (Idx < (int)NumElems) ? Idx : Idx - (int)NumElems;
8857       }
8858     }
8859
8860     // Make sure we found a non-volatile load and the extractelement is
8861     // the only use.
8862     if (!LN0 || !LN0->hasNUsesOfValue(1,0) || LN0->isVolatile())
8863       return SDValue();
8864
8865     // If Idx was -1 above, Elt is going to be -1, so just return undef.
8866     if (Elt == -1)
8867       return DAG.getUNDEF(LVT);
8868
8869     unsigned Align = LN0->getAlignment();
8870     if (NewLoad) {
8871       // Check the resultant load doesn't need a higher alignment than the
8872       // original load.
8873       unsigned NewAlign =
8874         TLI.getDataLayout()
8875             ->getABITypeAlignment(LVT.getTypeForEVT(*DAG.getContext()));
8876
8877       if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, LVT))
8878         return SDValue();
8879
8880       Align = NewAlign;
8881     }
8882
8883     SDValue NewPtr = LN0->getBasePtr();
8884     unsigned PtrOff = 0;
8885
8886     if (Elt) {
8887       PtrOff = LVT.getSizeInBits() * Elt / 8;
8888       EVT PtrType = NewPtr.getValueType();
8889       if (TLI.isBigEndian())
8890         PtrOff = VT.getSizeInBits() / 8 - PtrOff;
8891       NewPtr = DAG.getNode(ISD::ADD, SDLoc(N), PtrType, NewPtr,
8892                            DAG.getConstant(PtrOff, PtrType));
8893     }
8894
8895     // The replacement we need to do here is a little tricky: we need to
8896     // replace an extractelement of a load with a load.
8897     // Use ReplaceAllUsesOfValuesWith to do the replacement.
8898     // Note that this replacement assumes that the extractvalue is the only
8899     // use of the load; that's okay because we don't want to perform this
8900     // transformation in other cases anyway.
8901     SDValue Load;
8902     SDValue Chain;
8903     if (NVT.bitsGT(LVT)) {
8904       // If the result type of vextract is wider than the load, then issue an
8905       // extending load instead.
8906       ISD::LoadExtType ExtType = TLI.isLoadExtLegal(ISD::ZEXTLOAD, LVT)
8907         ? ISD::ZEXTLOAD : ISD::EXTLOAD;
8908       Load = DAG.getExtLoad(ExtType, SDLoc(N), NVT, LN0->getChain(),
8909                             NewPtr, LN0->getPointerInfo().getWithOffset(PtrOff),
8910                             LVT, LN0->isVolatile(), LN0->isNonTemporal(),Align);
8911       Chain = Load.getValue(1);
8912     } else {
8913       Load = DAG.getLoad(LVT, SDLoc(N), LN0->getChain(), NewPtr,
8914                          LN0->getPointerInfo().getWithOffset(PtrOff),
8915                          LN0->isVolatile(), LN0->isNonTemporal(),
8916                          LN0->isInvariant(), Align);
8917       Chain = Load.getValue(1);
8918       if (NVT.bitsLT(LVT))
8919         Load = DAG.getNode(ISD::TRUNCATE, SDLoc(N), NVT, Load);
8920       else
8921         Load = DAG.getNode(ISD::BITCAST, SDLoc(N), NVT, Load);
8922     }
8923     WorkListRemover DeadNodes(*this);
8924     SDValue From[] = { SDValue(N, 0), SDValue(LN0,1) };
8925     SDValue To[] = { Load, Chain };
8926     DAG.ReplaceAllUsesOfValuesWith(From, To, 2);
8927     // Since we're explcitly calling ReplaceAllUses, add the new node to the
8928     // worklist explicitly as well.
8929     AddToWorkList(Load.getNode());
8930     AddUsersToWorkList(Load.getNode()); // Add users too
8931     // Make sure to revisit this node to clean it up; it will usually be dead.
8932     AddToWorkList(N);
8933     return SDValue(N, 0);
8934   }
8935
8936   return SDValue();
8937 }
8938
8939 // Simplify (build_vec (ext )) to (bitcast (build_vec ))
8940 SDValue DAGCombiner::reduceBuildVecExtToExtBuildVec(SDNode *N) {
8941   // We perform this optimization post type-legalization because
8942   // the type-legalizer often scalarizes integer-promoted vectors.
8943   // Performing this optimization before may create bit-casts which
8944   // will be type-legalized to complex code sequences.
8945   // We perform this optimization only before the operation legalizer because we
8946   // may introduce illegal operations.
8947   if (Level != AfterLegalizeVectorOps && Level != AfterLegalizeTypes)
8948     return SDValue();
8949
8950   unsigned NumInScalars = N->getNumOperands();
8951   SDLoc dl(N);
8952   EVT VT = N->getValueType(0);
8953
8954   // Check to see if this is a BUILD_VECTOR of a bunch of values
8955   // which come from any_extend or zero_extend nodes. If so, we can create
8956   // a new BUILD_VECTOR using bit-casts which may enable other BUILD_VECTOR
8957   // optimizations. We do not handle sign-extend because we can't fill the sign
8958   // using shuffles.
8959   EVT SourceType = MVT::Other;
8960   bool AllAnyExt = true;
8961
8962   for (unsigned i = 0; i != NumInScalars; ++i) {
8963     SDValue In = N->getOperand(i);
8964     // Ignore undef inputs.
8965     if (In.getOpcode() == ISD::UNDEF) continue;
8966
8967     bool AnyExt  = In.getOpcode() == ISD::ANY_EXTEND;
8968     bool ZeroExt = In.getOpcode() == ISD::ZERO_EXTEND;
8969
8970     // Abort if the element is not an extension.
8971     if (!ZeroExt && !AnyExt) {
8972       SourceType = MVT::Other;
8973       break;
8974     }
8975
8976     // The input is a ZeroExt or AnyExt. Check the original type.
8977     EVT InTy = In.getOperand(0).getValueType();
8978
8979     // Check that all of the widened source types are the same.
8980     if (SourceType == MVT::Other)
8981       // First time.
8982       SourceType = InTy;
8983     else if (InTy != SourceType) {
8984       // Multiple income types. Abort.
8985       SourceType = MVT::Other;
8986       break;
8987     }
8988
8989     // Check if all of the extends are ANY_EXTENDs.
8990     AllAnyExt &= AnyExt;
8991   }
8992
8993   // In order to have valid types, all of the inputs must be extended from the
8994   // same source type and all of the inputs must be any or zero extend.
8995   // Scalar sizes must be a power of two.
8996   EVT OutScalarTy = VT.getScalarType();
8997   bool ValidTypes = SourceType != MVT::Other &&
8998                  isPowerOf2_32(OutScalarTy.getSizeInBits()) &&
8999                  isPowerOf2_32(SourceType.getSizeInBits());
9000
9001   // Create a new simpler BUILD_VECTOR sequence which other optimizations can
9002   // turn into a single shuffle instruction.
9003   if (!ValidTypes)
9004     return SDValue();
9005
9006   bool isLE = TLI.isLittleEndian();
9007   unsigned ElemRatio = OutScalarTy.getSizeInBits()/SourceType.getSizeInBits();
9008   assert(ElemRatio > 1 && "Invalid element size ratio");
9009   SDValue Filler = AllAnyExt ? DAG.getUNDEF(SourceType):
9010                                DAG.getConstant(0, SourceType);
9011
9012   unsigned NewBVElems = ElemRatio * VT.getVectorNumElements();
9013   SmallVector<SDValue, 8> Ops(NewBVElems, Filler);
9014
9015   // Populate the new build_vector
9016   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
9017     SDValue Cast = N->getOperand(i);
9018     assert((Cast.getOpcode() == ISD::ANY_EXTEND ||
9019             Cast.getOpcode() == ISD::ZERO_EXTEND ||
9020             Cast.getOpcode() == ISD::UNDEF) && "Invalid cast opcode");
9021     SDValue In;
9022     if (Cast.getOpcode() == ISD::UNDEF)
9023       In = DAG.getUNDEF(SourceType);
9024     else
9025       In = Cast->getOperand(0);
9026     unsigned Index = isLE ? (i * ElemRatio) :
9027                             (i * ElemRatio + (ElemRatio - 1));
9028
9029     assert(Index < Ops.size() && "Invalid index");
9030     Ops[Index] = In;
9031   }
9032
9033   // The type of the new BUILD_VECTOR node.
9034   EVT VecVT = EVT::getVectorVT(*DAG.getContext(), SourceType, NewBVElems);
9035   assert(VecVT.getSizeInBits() == VT.getSizeInBits() &&
9036          "Invalid vector size");
9037   // Check if the new vector type is legal.
9038   if (!isTypeLegal(VecVT)) return SDValue();
9039
9040   // Make the new BUILD_VECTOR.
9041   SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, VecVT, &Ops[0], Ops.size());
9042
9043   // The new BUILD_VECTOR node has the potential to be further optimized.
9044   AddToWorkList(BV.getNode());
9045   // Bitcast to the desired type.
9046   return DAG.getNode(ISD::BITCAST, dl, VT, BV);
9047 }
9048
9049 SDValue DAGCombiner::reduceBuildVecConvertToConvertBuildVec(SDNode *N) {
9050   EVT VT = N->getValueType(0);
9051
9052   unsigned NumInScalars = N->getNumOperands();
9053   SDLoc dl(N);
9054
9055   EVT SrcVT = MVT::Other;
9056   unsigned Opcode = ISD::DELETED_NODE;
9057   unsigned NumDefs = 0;
9058
9059   for (unsigned i = 0; i != NumInScalars; ++i) {
9060     SDValue In = N->getOperand(i);
9061     unsigned Opc = In.getOpcode();
9062
9063     if (Opc == ISD::UNDEF)
9064       continue;
9065
9066     // If all scalar values are floats and converted from integers.
9067     if (Opcode == ISD::DELETED_NODE &&
9068         (Opc == ISD::UINT_TO_FP || Opc == ISD::SINT_TO_FP)) {
9069       Opcode = Opc;
9070     }
9071
9072     if (Opc != Opcode)
9073       return SDValue();
9074
9075     EVT InVT = In.getOperand(0).getValueType();
9076
9077     // If all scalar values are typed differently, bail out. It's chosen to
9078     // simplify BUILD_VECTOR of integer types.
9079     if (SrcVT == MVT::Other)
9080       SrcVT = InVT;
9081     if (SrcVT != InVT)
9082       return SDValue();
9083     NumDefs++;
9084   }
9085
9086   // If the vector has just one element defined, it's not worth to fold it into
9087   // a vectorized one.
9088   if (NumDefs < 2)
9089     return SDValue();
9090
9091   assert((Opcode == ISD::UINT_TO_FP || Opcode == ISD::SINT_TO_FP)
9092          && "Should only handle conversion from integer to float.");
9093   assert(SrcVT != MVT::Other && "Cannot determine source type!");
9094
9095   EVT NVT = EVT::getVectorVT(*DAG.getContext(), SrcVT, NumInScalars);
9096
9097   if (!TLI.isOperationLegalOrCustom(Opcode, NVT))
9098     return SDValue();
9099
9100   SmallVector<SDValue, 8> Opnds;
9101   for (unsigned i = 0; i != NumInScalars; ++i) {
9102     SDValue In = N->getOperand(i);
9103
9104     if (In.getOpcode() == ISD::UNDEF)
9105       Opnds.push_back(DAG.getUNDEF(SrcVT));
9106     else
9107       Opnds.push_back(In.getOperand(0));
9108   }
9109   SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, NVT,
9110                            &Opnds[0], Opnds.size());
9111   AddToWorkList(BV.getNode());
9112
9113   return DAG.getNode(Opcode, dl, VT, BV);
9114 }
9115
9116 SDValue DAGCombiner::visitBUILD_VECTOR(SDNode *N) {
9117   unsigned NumInScalars = N->getNumOperands();
9118   SDLoc dl(N);
9119   EVT VT = N->getValueType(0);
9120
9121   // A vector built entirely of undefs is undef.
9122   if (ISD::allOperandsUndef(N))
9123     return DAG.getUNDEF(VT);
9124
9125   SDValue V = reduceBuildVecExtToExtBuildVec(N);
9126   if (V.getNode())
9127     return V;
9128
9129   V = reduceBuildVecConvertToConvertBuildVec(N);
9130   if (V.getNode())
9131     return V;
9132
9133   // Check to see if this is a BUILD_VECTOR of a bunch of EXTRACT_VECTOR_ELT
9134   // operations.  If so, and if the EXTRACT_VECTOR_ELT vector inputs come from
9135   // at most two distinct vectors, turn this into a shuffle node.
9136
9137   // May only combine to shuffle after legalize if shuffle is legal.
9138   if (LegalOperations &&
9139       !TLI.isOperationLegalOrCustom(ISD::VECTOR_SHUFFLE, VT))
9140     return SDValue();
9141
9142   SDValue VecIn1, VecIn2;
9143   for (unsigned i = 0; i != NumInScalars; ++i) {
9144     // Ignore undef inputs.
9145     if (N->getOperand(i).getOpcode() == ISD::UNDEF) continue;
9146
9147     // If this input is something other than a EXTRACT_VECTOR_ELT with a
9148     // constant index, bail out.
9149     if (N->getOperand(i).getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
9150         !isa<ConstantSDNode>(N->getOperand(i).getOperand(1))) {
9151       VecIn1 = VecIn2 = SDValue(0, 0);
9152       break;
9153     }
9154
9155     // We allow up to two distinct input vectors.
9156     SDValue ExtractedFromVec = N->getOperand(i).getOperand(0);
9157     if (ExtractedFromVec == VecIn1 || ExtractedFromVec == VecIn2)
9158       continue;
9159
9160     if (VecIn1.getNode() == 0) {
9161       VecIn1 = ExtractedFromVec;
9162     } else if (VecIn2.getNode() == 0) {
9163       VecIn2 = ExtractedFromVec;
9164     } else {
9165       // Too many inputs.
9166       VecIn1 = VecIn2 = SDValue(0, 0);
9167       break;
9168     }
9169   }
9170
9171     // If everything is good, we can make a shuffle operation.
9172   if (VecIn1.getNode()) {
9173     SmallVector<int, 8> Mask;
9174     for (unsigned i = 0; i != NumInScalars; ++i) {
9175       if (N->getOperand(i).getOpcode() == ISD::UNDEF) {
9176         Mask.push_back(-1);
9177         continue;
9178       }
9179
9180       // If extracting from the first vector, just use the index directly.
9181       SDValue Extract = N->getOperand(i);
9182       SDValue ExtVal = Extract.getOperand(1);
9183       if (Extract.getOperand(0) == VecIn1) {
9184         unsigned ExtIndex = cast<ConstantSDNode>(ExtVal)->getZExtValue();
9185         if (ExtIndex > VT.getVectorNumElements())
9186           return SDValue();
9187
9188         Mask.push_back(ExtIndex);
9189         continue;
9190       }
9191
9192       // Otherwise, use InIdx + VecSize
9193       unsigned Idx = cast<ConstantSDNode>(ExtVal)->getZExtValue();
9194       Mask.push_back(Idx+NumInScalars);
9195     }
9196
9197     // We can't generate a shuffle node with mismatched input and output types.
9198     // Attempt to transform a single input vector to the correct type.
9199     if ((VT != VecIn1.getValueType())) {
9200       // We don't support shuffeling between TWO values of different types.
9201       if (VecIn2.getNode() != 0)
9202         return SDValue();
9203
9204       // We only support widening of vectors which are half the size of the
9205       // output registers. For example XMM->YMM widening on X86 with AVX.
9206       if (VecIn1.getValueType().getSizeInBits()*2 != VT.getSizeInBits())
9207         return SDValue();
9208
9209       // If the input vector type has a different base type to the output
9210       // vector type, bail out.
9211       if (VecIn1.getValueType().getVectorElementType() !=
9212           VT.getVectorElementType())
9213         return SDValue();
9214
9215       // Widen the input vector by adding undef values.
9216       VecIn1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
9217                            VecIn1, DAG.getUNDEF(VecIn1.getValueType()));
9218     }
9219
9220     // If VecIn2 is unused then change it to undef.
9221     VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(VT);
9222
9223     // Check that we were able to transform all incoming values to the same
9224     // type.
9225     if (VecIn2.getValueType() != VecIn1.getValueType() ||
9226         VecIn1.getValueType() != VT)
9227           return SDValue();
9228
9229     // Only type-legal BUILD_VECTOR nodes are converted to shuffle nodes.
9230     if (!isTypeLegal(VT))
9231       return SDValue();
9232
9233     // Return the new VECTOR_SHUFFLE node.
9234     SDValue Ops[2];
9235     Ops[0] = VecIn1;
9236     Ops[1] = VecIn2;
9237     return DAG.getVectorShuffle(VT, dl, Ops[0], Ops[1], &Mask[0]);
9238   }
9239
9240   return SDValue();
9241 }
9242
9243 SDValue DAGCombiner::visitCONCAT_VECTORS(SDNode *N) {
9244   // TODO: Check to see if this is a CONCAT_VECTORS of a bunch of
9245   // EXTRACT_SUBVECTOR operations.  If so, and if the EXTRACT_SUBVECTOR vector
9246   // inputs come from at most two distinct vectors, turn this into a shuffle
9247   // node.
9248
9249   // If we only have one input vector, we don't need to do any concatenation.
9250   if (N->getNumOperands() == 1)
9251     return N->getOperand(0);
9252
9253   // Check if all of the operands are undefs.
9254   if (ISD::allOperandsUndef(N))
9255     return DAG.getUNDEF(N->getValueType(0));
9256
9257   // Type legalization of vectors and DAG canonicalization of SHUFFLE_VECTOR
9258   // nodes often generate nop CONCAT_VECTOR nodes.
9259   // Scan the CONCAT_VECTOR operands and look for a CONCAT operations that
9260   // place the incoming vectors at the exact same location.
9261   SDValue SingleSource = SDValue();
9262   unsigned PartNumElem = N->getOperand(0).getValueType().getVectorNumElements();
9263
9264   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
9265     SDValue Op = N->getOperand(i);
9266
9267     if (Op.getOpcode() == ISD::UNDEF)
9268       continue;
9269
9270     // Check if this is the identity extract:
9271     if (Op.getOpcode() != ISD::EXTRACT_SUBVECTOR)
9272       return SDValue();
9273
9274     // Find the single incoming vector for the extract_subvector.
9275     if (SingleSource.getNode()) {
9276       if (Op.getOperand(0) != SingleSource)
9277         return SDValue();
9278     } else {
9279       SingleSource = Op.getOperand(0);
9280
9281       // Check the source type is the same as the type of the result.
9282       // If not, this concat may extend the vector, so we can not
9283       // optimize it away.
9284       if (SingleSource.getValueType() != N->getValueType(0))
9285         return SDValue();
9286     }
9287
9288     unsigned IdentityIndex = i * PartNumElem;
9289     ConstantSDNode *CS = dyn_cast<ConstantSDNode>(Op.getOperand(1));
9290     // The extract index must be constant.
9291     if (!CS)
9292       return SDValue();
9293
9294     // Check that we are reading from the identity index.
9295     if (CS->getZExtValue() != IdentityIndex)
9296       return SDValue();
9297   }
9298
9299   if (SingleSource.getNode())
9300     return SingleSource;
9301
9302   return SDValue();
9303 }
9304
9305 SDValue DAGCombiner::visitEXTRACT_SUBVECTOR(SDNode* N) {
9306   EVT NVT = N->getValueType(0);
9307   SDValue V = N->getOperand(0);
9308
9309   if (V->getOpcode() == ISD::CONCAT_VECTORS) {
9310     // Combine:
9311     //    (extract_subvec (concat V1, V2, ...), i)
9312     // Into:
9313     //    Vi if possible
9314     // Only operand 0 is checked as 'concat' assumes all inputs of the same type.
9315     if (V->getOperand(0).getValueType() != NVT)
9316       return SDValue();
9317     unsigned Idx = dyn_cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
9318     unsigned NumElems = NVT.getVectorNumElements();
9319     assert((Idx % NumElems) == 0 &&
9320            "IDX in concat is not a multiple of the result vector length.");
9321     return V->getOperand(Idx / NumElems);
9322   }
9323
9324   // Skip bitcasting
9325   if (V->getOpcode() == ISD::BITCAST)
9326     V = V.getOperand(0);
9327
9328   if (V->getOpcode() == ISD::INSERT_SUBVECTOR) {
9329     SDLoc dl(N);
9330     // Handle only simple case where vector being inserted and vector
9331     // being extracted are of same type, and are half size of larger vectors.
9332     EVT BigVT = V->getOperand(0).getValueType();
9333     EVT SmallVT = V->getOperand(1).getValueType();
9334     if (!NVT.bitsEq(SmallVT) || NVT.getSizeInBits()*2 != BigVT.getSizeInBits())
9335       return SDValue();
9336
9337     // Only handle cases where both indexes are constants with the same type.
9338     ConstantSDNode *ExtIdx = dyn_cast<ConstantSDNode>(N->getOperand(1));
9339     ConstantSDNode *InsIdx = dyn_cast<ConstantSDNode>(V->getOperand(2));
9340
9341     if (InsIdx && ExtIdx &&
9342         InsIdx->getValueType(0).getSizeInBits() <= 64 &&
9343         ExtIdx->getValueType(0).getSizeInBits() <= 64) {
9344       // Combine:
9345       //    (extract_subvec (insert_subvec V1, V2, InsIdx), ExtIdx)
9346       // Into:
9347       //    indices are equal or bit offsets are equal => V1
9348       //    otherwise => (extract_subvec V1, ExtIdx)
9349       if (InsIdx->getZExtValue() * SmallVT.getScalarType().getSizeInBits() ==
9350           ExtIdx->getZExtValue() * NVT.getScalarType().getSizeInBits())
9351         return DAG.getNode(ISD::BITCAST, dl, NVT, V->getOperand(1));
9352       return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, NVT,
9353                          DAG.getNode(ISD::BITCAST, dl,
9354                                      N->getOperand(0).getValueType(),
9355                                      V->getOperand(0)), N->getOperand(1));
9356     }
9357   }
9358
9359   return SDValue();
9360 }
9361
9362 // Tries to turn a shuffle of two CONCAT_VECTORS into a single concat.
9363 static SDValue partitionShuffleOfConcats(SDNode *N, SelectionDAG &DAG) {
9364   EVT VT = N->getValueType(0);
9365   unsigned NumElts = VT.getVectorNumElements();
9366
9367   SDValue N0 = N->getOperand(0);
9368   SDValue N1 = N->getOperand(1);
9369   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
9370
9371   SmallVector<SDValue, 4> Ops;
9372   EVT ConcatVT = N0.getOperand(0).getValueType();
9373   unsigned NumElemsPerConcat = ConcatVT.getVectorNumElements();
9374   unsigned NumConcats = NumElts / NumElemsPerConcat;
9375
9376   // Look at every vector that's inserted. We're looking for exact
9377   // subvector-sized copies from a concatenated vector
9378   for (unsigned I = 0; I != NumConcats; ++I) {
9379     // Make sure we're dealing with a copy.
9380     unsigned Begin = I * NumElemsPerConcat;
9381     bool AllUndef = true, NoUndef = true;
9382     for (unsigned J = Begin; J != Begin + NumElemsPerConcat; ++J) {
9383       if (SVN->getMaskElt(J) >= 0)
9384         AllUndef = false;
9385       else
9386         NoUndef = false;
9387     }
9388
9389     if (NoUndef) {
9390       if (SVN->getMaskElt(Begin) % NumElemsPerConcat != 0)
9391         return SDValue();
9392
9393       for (unsigned J = 1; J != NumElemsPerConcat; ++J)
9394         if (SVN->getMaskElt(Begin + J - 1) + 1 != SVN->getMaskElt(Begin + J))
9395           return SDValue();
9396
9397       unsigned FirstElt = SVN->getMaskElt(Begin) / NumElemsPerConcat;
9398       if (FirstElt < N0.getNumOperands())
9399         Ops.push_back(N0.getOperand(FirstElt));
9400       else
9401         Ops.push_back(N1.getOperand(FirstElt - N0.getNumOperands()));
9402
9403     } else if (AllUndef) {
9404       Ops.push_back(DAG.getUNDEF(N0.getOperand(0).getValueType()));
9405     } else { // Mixed with general masks and undefs, can't do optimization.
9406       return SDValue();
9407     }
9408   }
9409
9410   return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Ops.data(),
9411                      Ops.size());
9412 }
9413
9414 SDValue DAGCombiner::visitVECTOR_SHUFFLE(SDNode *N) {
9415   EVT VT = N->getValueType(0);
9416   unsigned NumElts = VT.getVectorNumElements();
9417
9418   SDValue N0 = N->getOperand(0);
9419   SDValue N1 = N->getOperand(1);
9420
9421   assert(N0.getValueType() == VT && "Vector shuffle must be normalized in DAG");
9422
9423   // Canonicalize shuffle undef, undef -> undef
9424   if (N0.getOpcode() == ISD::UNDEF && N1.getOpcode() == ISD::UNDEF)
9425     return DAG.getUNDEF(VT);
9426
9427   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
9428
9429   // Canonicalize shuffle v, v -> v, undef
9430   if (N0 == N1) {
9431     SmallVector<int, 8> NewMask;
9432     for (unsigned i = 0; i != NumElts; ++i) {
9433       int Idx = SVN->getMaskElt(i);
9434       if (Idx >= (int)NumElts) Idx -= NumElts;
9435       NewMask.push_back(Idx);
9436     }
9437     return DAG.getVectorShuffle(VT, SDLoc(N), N0, DAG.getUNDEF(VT),
9438                                 &NewMask[0]);
9439   }
9440
9441   // Canonicalize shuffle undef, v -> v, undef.  Commute the shuffle mask.
9442   if (N0.getOpcode() == ISD::UNDEF) {
9443     SmallVector<int, 8> NewMask;
9444     for (unsigned i = 0; i != NumElts; ++i) {
9445       int Idx = SVN->getMaskElt(i);
9446       if (Idx >= 0) {
9447         if (Idx >= (int)NumElts)
9448           Idx -= NumElts;
9449         else
9450           Idx = -1; // remove reference to lhs
9451       }
9452       NewMask.push_back(Idx);
9453     }
9454     return DAG.getVectorShuffle(VT, SDLoc(N), N1, DAG.getUNDEF(VT),
9455                                 &NewMask[0]);
9456   }
9457
9458   // Remove references to rhs if it is undef
9459   if (N1.getOpcode() == ISD::UNDEF) {
9460     bool Changed = false;
9461     SmallVector<int, 8> NewMask;
9462     for (unsigned i = 0; i != NumElts; ++i) {
9463       int Idx = SVN->getMaskElt(i);
9464       if (Idx >= (int)NumElts) {
9465         Idx = -1;
9466         Changed = true;
9467       }
9468       NewMask.push_back(Idx);
9469     }
9470     if (Changed)
9471       return DAG.getVectorShuffle(VT, SDLoc(N), N0, N1, &NewMask[0]);
9472   }
9473
9474   // If it is a splat, check if the argument vector is another splat or a
9475   // build_vector with all scalar elements the same.
9476   if (SVN->isSplat() && SVN->getSplatIndex() < (int)NumElts) {
9477     SDNode *V = N0.getNode();
9478
9479     // If this is a bit convert that changes the element type of the vector but
9480     // not the number of vector elements, look through it.  Be careful not to
9481     // look though conversions that change things like v4f32 to v2f64.
9482     if (V->getOpcode() == ISD::BITCAST) {
9483       SDValue ConvInput = V->getOperand(0);
9484       if (ConvInput.getValueType().isVector() &&
9485           ConvInput.getValueType().getVectorNumElements() == NumElts)
9486         V = ConvInput.getNode();
9487     }
9488
9489     if (V->getOpcode() == ISD::BUILD_VECTOR) {
9490       assert(V->getNumOperands() == NumElts &&
9491              "BUILD_VECTOR has wrong number of operands");
9492       SDValue Base;
9493       bool AllSame = true;
9494       for (unsigned i = 0; i != NumElts; ++i) {
9495         if (V->getOperand(i).getOpcode() != ISD::UNDEF) {
9496           Base = V->getOperand(i);
9497           break;
9498         }
9499       }
9500       // Splat of <u, u, u, u>, return <u, u, u, u>
9501       if (!Base.getNode())
9502         return N0;
9503       for (unsigned i = 0; i != NumElts; ++i) {
9504         if (V->getOperand(i) != Base) {
9505           AllSame = false;
9506           break;
9507         }
9508       }
9509       // Splat of <x, x, x, x>, return <x, x, x, x>
9510       if (AllSame)
9511         return N0;
9512     }
9513   }
9514
9515   if (N0.getOpcode() == ISD::CONCAT_VECTORS &&
9516       Level < AfterLegalizeVectorOps &&
9517       (N1.getOpcode() == ISD::UNDEF ||
9518       (N1.getOpcode() == ISD::CONCAT_VECTORS &&
9519        N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType()))) {
9520     SDValue V = partitionShuffleOfConcats(N, DAG);
9521
9522     if (V.getNode())
9523       return V;
9524   }
9525
9526   // If this shuffle node is simply a swizzle of another shuffle node,
9527   // and it reverses the swizzle of the previous shuffle then we can
9528   // optimize shuffle(shuffle(x, undef), undef) -> x.
9529   if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG &&
9530       N1.getOpcode() == ISD::UNDEF) {
9531
9532     ShuffleVectorSDNode *OtherSV = cast<ShuffleVectorSDNode>(N0);
9533
9534     // Shuffle nodes can only reverse shuffles with a single non-undef value.
9535     if (N0.getOperand(1).getOpcode() != ISD::UNDEF)
9536       return SDValue();
9537
9538     // The incoming shuffle must be of the same type as the result of the
9539     // current shuffle.
9540     assert(OtherSV->getOperand(0).getValueType() == VT &&
9541            "Shuffle types don't match");
9542
9543     for (unsigned i = 0; i != NumElts; ++i) {
9544       int Idx = SVN->getMaskElt(i);
9545       assert(Idx < (int)NumElts && "Index references undef operand");
9546       // Next, this index comes from the first value, which is the incoming
9547       // shuffle. Adopt the incoming index.
9548       if (Idx >= 0)
9549         Idx = OtherSV->getMaskElt(Idx);
9550
9551       // The combined shuffle must map each index to itself.
9552       if (Idx >= 0 && (unsigned)Idx != i)
9553         return SDValue();
9554     }
9555
9556     return OtherSV->getOperand(0);
9557   }
9558
9559   return SDValue();
9560 }
9561
9562 /// XformToShuffleWithZero - Returns a vector_shuffle if it able to transform
9563 /// an AND to a vector_shuffle with the destination vector and a zero vector.
9564 /// e.g. AND V, <0xffffffff, 0, 0xffffffff, 0>. ==>
9565 ///      vector_shuffle V, Zero, <0, 4, 2, 4>
9566 SDValue DAGCombiner::XformToShuffleWithZero(SDNode *N) {
9567   EVT VT = N->getValueType(0);
9568   SDLoc dl(N);
9569   SDValue LHS = N->getOperand(0);
9570   SDValue RHS = N->getOperand(1);
9571   if (N->getOpcode() == ISD::AND) {
9572     if (RHS.getOpcode() == ISD::BITCAST)
9573       RHS = RHS.getOperand(0);
9574     if (RHS.getOpcode() == ISD::BUILD_VECTOR) {
9575       SmallVector<int, 8> Indices;
9576       unsigned NumElts = RHS.getNumOperands();
9577       for (unsigned i = 0; i != NumElts; ++i) {
9578         SDValue Elt = RHS.getOperand(i);
9579         if (!isa<ConstantSDNode>(Elt))
9580           return SDValue();
9581
9582         if (cast<ConstantSDNode>(Elt)->isAllOnesValue())
9583           Indices.push_back(i);
9584         else if (cast<ConstantSDNode>(Elt)->isNullValue())
9585           Indices.push_back(NumElts);
9586         else
9587           return SDValue();
9588       }
9589
9590       // Let's see if the target supports this vector_shuffle.
9591       EVT RVT = RHS.getValueType();
9592       if (!TLI.isVectorClearMaskLegal(Indices, RVT))
9593         return SDValue();
9594
9595       // Return the new VECTOR_SHUFFLE node.
9596       EVT EltVT = RVT.getVectorElementType();
9597       SmallVector<SDValue,8> ZeroOps(RVT.getVectorNumElements(),
9598                                      DAG.getConstant(0, EltVT));
9599       SDValue Zero = DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N),
9600                                  RVT, &ZeroOps[0], ZeroOps.size());
9601       LHS = DAG.getNode(ISD::BITCAST, dl, RVT, LHS);
9602       SDValue Shuf = DAG.getVectorShuffle(RVT, dl, LHS, Zero, &Indices[0]);
9603       return DAG.getNode(ISD::BITCAST, dl, VT, Shuf);
9604     }
9605   }
9606
9607   return SDValue();
9608 }
9609
9610 /// SimplifyVBinOp - Visit a binary vector operation, like ADD.
9611 SDValue DAGCombiner::SimplifyVBinOp(SDNode *N) {
9612   assert(N->getValueType(0).isVector() &&
9613          "SimplifyVBinOp only works on vectors!");
9614
9615   SDValue LHS = N->getOperand(0);
9616   SDValue RHS = N->getOperand(1);
9617   SDValue Shuffle = XformToShuffleWithZero(N);
9618   if (Shuffle.getNode()) return Shuffle;
9619
9620   // If the LHS and RHS are BUILD_VECTOR nodes, see if we can constant fold
9621   // this operation.
9622   if (LHS.getOpcode() == ISD::BUILD_VECTOR &&
9623       RHS.getOpcode() == ISD::BUILD_VECTOR) {
9624     SmallVector<SDValue, 8> Ops;
9625     for (unsigned i = 0, e = LHS.getNumOperands(); i != e; ++i) {
9626       SDValue LHSOp = LHS.getOperand(i);
9627       SDValue RHSOp = RHS.getOperand(i);
9628       // If these two elements can't be folded, bail out.
9629       if ((LHSOp.getOpcode() != ISD::UNDEF &&
9630            LHSOp.getOpcode() != ISD::Constant &&
9631            LHSOp.getOpcode() != ISD::ConstantFP) ||
9632           (RHSOp.getOpcode() != ISD::UNDEF &&
9633            RHSOp.getOpcode() != ISD::Constant &&
9634            RHSOp.getOpcode() != ISD::ConstantFP))
9635         break;
9636
9637       // Can't fold divide by zero.
9638       if (N->getOpcode() == ISD::SDIV || N->getOpcode() == ISD::UDIV ||
9639           N->getOpcode() == ISD::FDIV) {
9640         if ((RHSOp.getOpcode() == ISD::Constant &&
9641              cast<ConstantSDNode>(RHSOp.getNode())->isNullValue()) ||
9642             (RHSOp.getOpcode() == ISD::ConstantFP &&
9643              cast<ConstantFPSDNode>(RHSOp.getNode())->getValueAPF().isZero()))
9644           break;
9645       }
9646
9647       EVT VT = LHSOp.getValueType();
9648       EVT RVT = RHSOp.getValueType();
9649       if (RVT != VT) {
9650         // Integer BUILD_VECTOR operands may have types larger than the element
9651         // size (e.g., when the element type is not legal).  Prior to type
9652         // legalization, the types may not match between the two BUILD_VECTORS.
9653         // Truncate one of the operands to make them match.
9654         if (RVT.getSizeInBits() > VT.getSizeInBits()) {
9655           RHSOp = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, RHSOp);
9656         } else {
9657           LHSOp = DAG.getNode(ISD::TRUNCATE, SDLoc(N), RVT, LHSOp);
9658           VT = RVT;
9659         }
9660       }
9661       SDValue FoldOp = DAG.getNode(N->getOpcode(), SDLoc(LHS), VT,
9662                                    LHSOp, RHSOp);
9663       if (FoldOp.getOpcode() != ISD::UNDEF &&
9664           FoldOp.getOpcode() != ISD::Constant &&
9665           FoldOp.getOpcode() != ISD::ConstantFP)
9666         break;
9667       Ops.push_back(FoldOp);
9668       AddToWorkList(FoldOp.getNode());
9669     }
9670
9671     if (Ops.size() == LHS.getNumOperands())
9672       return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N),
9673                          LHS.getValueType(), &Ops[0], Ops.size());
9674   }
9675
9676   return SDValue();
9677 }
9678
9679 /// SimplifyVUnaryOp - Visit a binary vector operation, like FABS/FNEG.
9680 SDValue DAGCombiner::SimplifyVUnaryOp(SDNode *N) {
9681   assert(N->getValueType(0).isVector() &&
9682          "SimplifyVUnaryOp only works on vectors!");
9683
9684   SDValue N0 = N->getOperand(0);
9685
9686   if (N0.getOpcode() != ISD::BUILD_VECTOR)
9687     return SDValue();
9688
9689   // Operand is a BUILD_VECTOR node, see if we can constant fold it.
9690   SmallVector<SDValue, 8> Ops;
9691   for (unsigned i = 0, e = N0.getNumOperands(); i != e; ++i) {
9692     SDValue Op = N0.getOperand(i);
9693     if (Op.getOpcode() != ISD::UNDEF &&
9694         Op.getOpcode() != ISD::ConstantFP)
9695       break;
9696     EVT EltVT = Op.getValueType();
9697     SDValue FoldOp = DAG.getNode(N->getOpcode(), SDLoc(N0), EltVT, Op);
9698     if (FoldOp.getOpcode() != ISD::UNDEF &&
9699         FoldOp.getOpcode() != ISD::ConstantFP)
9700       break;
9701     Ops.push_back(FoldOp);
9702     AddToWorkList(FoldOp.getNode());
9703   }
9704
9705   if (Ops.size() != N0.getNumOperands())
9706     return SDValue();
9707
9708   return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N),
9709                      N0.getValueType(), &Ops[0], Ops.size());
9710 }
9711
9712 SDValue DAGCombiner::SimplifySelect(SDLoc DL, SDValue N0,
9713                                     SDValue N1, SDValue N2){
9714   assert(N0.getOpcode() ==ISD::SETCC && "First argument must be a SetCC node!");
9715
9716   SDValue SCC = SimplifySelectCC(DL, N0.getOperand(0), N0.getOperand(1), N1, N2,
9717                                  cast<CondCodeSDNode>(N0.getOperand(2))->get());
9718
9719   // If we got a simplified select_cc node back from SimplifySelectCC, then
9720   // break it down into a new SETCC node, and a new SELECT node, and then return
9721   // the SELECT node, since we were called with a SELECT node.
9722   if (SCC.getNode()) {
9723     // Check to see if we got a select_cc back (to turn into setcc/select).
9724     // Otherwise, just return whatever node we got back, like fabs.
9725     if (SCC.getOpcode() == ISD::SELECT_CC) {
9726       SDValue SETCC = DAG.getNode(ISD::SETCC, SDLoc(N0),
9727                                   N0.getValueType(),
9728                                   SCC.getOperand(0), SCC.getOperand(1),
9729                                   SCC.getOperand(4));
9730       AddToWorkList(SETCC.getNode());
9731       return DAG.getSelect(SDLoc(SCC), SCC.getValueType(),
9732                            SCC.getOperand(2), SCC.getOperand(3), SETCC);
9733     }
9734
9735     return SCC;
9736   }
9737   return SDValue();
9738 }
9739
9740 /// SimplifySelectOps - Given a SELECT or a SELECT_CC node, where LHS and RHS
9741 /// are the two values being selected between, see if we can simplify the
9742 /// select.  Callers of this should assume that TheSelect is deleted if this
9743 /// returns true.  As such, they should return the appropriate thing (e.g. the
9744 /// node) back to the top-level of the DAG combiner loop to avoid it being
9745 /// looked at.
9746 bool DAGCombiner::SimplifySelectOps(SDNode *TheSelect, SDValue LHS,
9747                                     SDValue RHS) {
9748
9749   // Cannot simplify select with vector condition
9750   if (TheSelect->getOperand(0).getValueType().isVector()) return false;
9751
9752   // If this is a select from two identical things, try to pull the operation
9753   // through the select.
9754   if (LHS.getOpcode() != RHS.getOpcode() ||
9755       !LHS.hasOneUse() || !RHS.hasOneUse())
9756     return false;
9757
9758   // If this is a load and the token chain is identical, replace the select
9759   // of two loads with a load through a select of the address to load from.
9760   // This triggers in things like "select bool X, 10.0, 123.0" after the FP
9761   // constants have been dropped into the constant pool.
9762   if (LHS.getOpcode() == ISD::LOAD) {
9763     LoadSDNode *LLD = cast<LoadSDNode>(LHS);
9764     LoadSDNode *RLD = cast<LoadSDNode>(RHS);
9765
9766     // Token chains must be identical.
9767     if (LHS.getOperand(0) != RHS.getOperand(0) ||
9768         // Do not let this transformation reduce the number of volatile loads.
9769         LLD->isVolatile() || RLD->isVolatile() ||
9770         // If this is an EXTLOAD, the VT's must match.
9771         LLD->getMemoryVT() != RLD->getMemoryVT() ||
9772         // If this is an EXTLOAD, the kind of extension must match.
9773         (LLD->getExtensionType() != RLD->getExtensionType() &&
9774          // The only exception is if one of the extensions is anyext.
9775          LLD->getExtensionType() != ISD::EXTLOAD &&
9776          RLD->getExtensionType() != ISD::EXTLOAD) ||
9777         // FIXME: this discards src value information.  This is
9778         // over-conservative. It would be beneficial to be able to remember
9779         // both potential memory locations.  Since we are discarding
9780         // src value info, don't do the transformation if the memory
9781         // locations are not in the default address space.
9782         LLD->getPointerInfo().getAddrSpace() != 0 ||
9783         RLD->getPointerInfo().getAddrSpace() != 0 ||
9784         !TLI.isOperationLegalOrCustom(TheSelect->getOpcode(),
9785                                       LLD->getBasePtr().getValueType()))
9786       return false;
9787
9788     // Check that the select condition doesn't reach either load.  If so,
9789     // folding this will induce a cycle into the DAG.  If not, this is safe to
9790     // xform, so create a select of the addresses.
9791     SDValue Addr;
9792     if (TheSelect->getOpcode() == ISD::SELECT) {
9793       SDNode *CondNode = TheSelect->getOperand(0).getNode();
9794       if ((LLD->hasAnyUseOfValue(1) && LLD->isPredecessorOf(CondNode)) ||
9795           (RLD->hasAnyUseOfValue(1) && RLD->isPredecessorOf(CondNode)))
9796         return false;
9797       // The loads must not depend on one another.
9798       if (LLD->isPredecessorOf(RLD) ||
9799           RLD->isPredecessorOf(LLD))
9800         return false;
9801       Addr = DAG.getSelect(SDLoc(TheSelect),
9802                            LLD->getBasePtr().getValueType(),
9803                            TheSelect->getOperand(0), LLD->getBasePtr(),
9804                            RLD->getBasePtr());
9805     } else {  // Otherwise SELECT_CC
9806       SDNode *CondLHS = TheSelect->getOperand(0).getNode();
9807       SDNode *CondRHS = TheSelect->getOperand(1).getNode();
9808
9809       if ((LLD->hasAnyUseOfValue(1) &&
9810            (LLD->isPredecessorOf(CondLHS) || LLD->isPredecessorOf(CondRHS))) ||
9811           (RLD->hasAnyUseOfValue(1) &&
9812            (RLD->isPredecessorOf(CondLHS) || RLD->isPredecessorOf(CondRHS))))
9813         return false;
9814
9815       Addr = DAG.getNode(ISD::SELECT_CC, SDLoc(TheSelect),
9816                          LLD->getBasePtr().getValueType(),
9817                          TheSelect->getOperand(0),
9818                          TheSelect->getOperand(1),
9819                          LLD->getBasePtr(), RLD->getBasePtr(),
9820                          TheSelect->getOperand(4));
9821     }
9822
9823     SDValue Load;
9824     if (LLD->getExtensionType() == ISD::NON_EXTLOAD) {
9825       Load = DAG.getLoad(TheSelect->getValueType(0),
9826                          SDLoc(TheSelect),
9827                          // FIXME: Discards pointer info.
9828                          LLD->getChain(), Addr, MachinePointerInfo(),
9829                          LLD->isVolatile(), LLD->isNonTemporal(),
9830                          LLD->isInvariant(), LLD->getAlignment());
9831     } else {
9832       Load = DAG.getExtLoad(LLD->getExtensionType() == ISD::EXTLOAD ?
9833                             RLD->getExtensionType() : LLD->getExtensionType(),
9834                             SDLoc(TheSelect),
9835                             TheSelect->getValueType(0),
9836                             // FIXME: Discards pointer info.
9837                             LLD->getChain(), Addr, MachinePointerInfo(),
9838                             LLD->getMemoryVT(), LLD->isVolatile(),
9839                             LLD->isNonTemporal(), LLD->getAlignment());
9840     }
9841
9842     // Users of the select now use the result of the load.
9843     CombineTo(TheSelect, Load);
9844
9845     // Users of the old loads now use the new load's chain.  We know the
9846     // old-load value is dead now.
9847     CombineTo(LHS.getNode(), Load.getValue(0), Load.getValue(1));
9848     CombineTo(RHS.getNode(), Load.getValue(0), Load.getValue(1));
9849     return true;
9850   }
9851
9852   return false;
9853 }
9854
9855 /// SimplifySelectCC - Simplify an expression of the form (N0 cond N1) ? N2 : N3
9856 /// where 'cond' is the comparison specified by CC.
9857 SDValue DAGCombiner::SimplifySelectCC(SDLoc DL, SDValue N0, SDValue N1,
9858                                       SDValue N2, SDValue N3,
9859                                       ISD::CondCode CC, bool NotExtCompare) {
9860   // (x ? y : y) -> y.
9861   if (N2 == N3) return N2;
9862
9863   EVT VT = N2.getValueType();
9864   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
9865   ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2.getNode());
9866   ConstantSDNode *N3C = dyn_cast<ConstantSDNode>(N3.getNode());
9867
9868   // Determine if the condition we're dealing with is constant
9869   SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()),
9870                               N0, N1, CC, DL, false);
9871   if (SCC.getNode()) AddToWorkList(SCC.getNode());
9872   ConstantSDNode *SCCC = dyn_cast_or_null<ConstantSDNode>(SCC.getNode());
9873
9874   // fold select_cc true, x, y -> x
9875   if (SCCC && !SCCC->isNullValue())
9876     return N2;
9877   // fold select_cc false, x, y -> y
9878   if (SCCC && SCCC->isNullValue())
9879     return N3;
9880
9881   // Check to see if we can simplify the select into an fabs node
9882   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N1)) {
9883     // Allow either -0.0 or 0.0
9884     if (CFP->getValueAPF().isZero()) {
9885       // select (setg[te] X, +/-0.0), X, fneg(X) -> fabs
9886       if ((CC == ISD::SETGE || CC == ISD::SETGT) &&
9887           N0 == N2 && N3.getOpcode() == ISD::FNEG &&
9888           N2 == N3.getOperand(0))
9889         return DAG.getNode(ISD::FABS, DL, VT, N0);
9890
9891       // select (setl[te] X, +/-0.0), fneg(X), X -> fabs
9892       if ((CC == ISD::SETLT || CC == ISD::SETLE) &&
9893           N0 == N3 && N2.getOpcode() == ISD::FNEG &&
9894           N2.getOperand(0) == N3)
9895         return DAG.getNode(ISD::FABS, DL, VT, N3);
9896     }
9897   }
9898
9899   // Turn "(a cond b) ? 1.0f : 2.0f" into "load (tmp + ((a cond b) ? 0 : 4)"
9900   // where "tmp" is a constant pool entry containing an array with 1.0 and 2.0
9901   // in it.  This is a win when the constant is not otherwise available because
9902   // it replaces two constant pool loads with one.  We only do this if the FP
9903   // type is known to be legal, because if it isn't, then we are before legalize
9904   // types an we want the other legalization to happen first (e.g. to avoid
9905   // messing with soft float) and if the ConstantFP is not legal, because if
9906   // it is legal, we may not need to store the FP constant in a constant pool.
9907   if (ConstantFPSDNode *TV = dyn_cast<ConstantFPSDNode>(N2))
9908     if (ConstantFPSDNode *FV = dyn_cast<ConstantFPSDNode>(N3)) {
9909       if (TLI.isTypeLegal(N2.getValueType()) &&
9910           (TLI.getOperationAction(ISD::ConstantFP, N2.getValueType()) !=
9911            TargetLowering::Legal) &&
9912           // If both constants have multiple uses, then we won't need to do an
9913           // extra load, they are likely around in registers for other users.
9914           (TV->hasOneUse() || FV->hasOneUse())) {
9915         Constant *Elts[] = {
9916           const_cast<ConstantFP*>(FV->getConstantFPValue()),
9917           const_cast<ConstantFP*>(TV->getConstantFPValue())
9918         };
9919         Type *FPTy = Elts[0]->getType();
9920         const DataLayout &TD = *TLI.getDataLayout();
9921
9922         // Create a ConstantArray of the two constants.
9923         Constant *CA = ConstantArray::get(ArrayType::get(FPTy, 2), Elts);
9924         SDValue CPIdx = DAG.getConstantPool(CA, TLI.getPointerTy(),
9925                                             TD.getPrefTypeAlignment(FPTy));
9926         unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
9927
9928         // Get the offsets to the 0 and 1 element of the array so that we can
9929         // select between them.
9930         SDValue Zero = DAG.getIntPtrConstant(0);
9931         unsigned EltSize = (unsigned)TD.getTypeAllocSize(Elts[0]->getType());
9932         SDValue One = DAG.getIntPtrConstant(EltSize);
9933
9934         SDValue Cond = DAG.getSetCC(DL,
9935                                     getSetCCResultType(N0.getValueType()),
9936                                     N0, N1, CC);
9937         AddToWorkList(Cond.getNode());
9938         SDValue CstOffset = DAG.getSelect(DL, Zero.getValueType(),
9939                                           Cond, One, Zero);
9940         AddToWorkList(CstOffset.getNode());
9941         CPIdx = DAG.getNode(ISD::ADD, DL, CPIdx.getValueType(), CPIdx,
9942                             CstOffset);
9943         AddToWorkList(CPIdx.getNode());
9944         return DAG.getLoad(TV->getValueType(0), DL, DAG.getEntryNode(), CPIdx,
9945                            MachinePointerInfo::getConstantPool(), false,
9946                            false, false, Alignment);
9947
9948       }
9949     }
9950
9951   // Check to see if we can perform the "gzip trick", transforming
9952   // (select_cc setlt X, 0, A, 0) -> (and (sra X, (sub size(X), 1), A)
9953   if (N1C && N3C && N3C->isNullValue() && CC == ISD::SETLT &&
9954       (N1C->isNullValue() ||                         // (a < 0) ? b : 0
9955        (N1C->getAPIntValue() == 1 && N0 == N2))) {   // (a < 1) ? a : 0
9956     EVT XType = N0.getValueType();
9957     EVT AType = N2.getValueType();
9958     if (XType.bitsGE(AType)) {
9959       // and (sra X, size(X)-1, A) -> "and (srl X, C2), A" iff A is a
9960       // single-bit constant.
9961       if (N2C && ((N2C->getAPIntValue() & (N2C->getAPIntValue()-1)) == 0)) {
9962         unsigned ShCtV = N2C->getAPIntValue().logBase2();
9963         ShCtV = XType.getSizeInBits()-ShCtV-1;
9964         SDValue ShCt = DAG.getConstant(ShCtV,
9965                                        getShiftAmountTy(N0.getValueType()));
9966         SDValue Shift = DAG.getNode(ISD::SRL, SDLoc(N0),
9967                                     XType, N0, ShCt);
9968         AddToWorkList(Shift.getNode());
9969
9970         if (XType.bitsGT(AType)) {
9971           Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift);
9972           AddToWorkList(Shift.getNode());
9973         }
9974
9975         return DAG.getNode(ISD::AND, DL, AType, Shift, N2);
9976       }
9977
9978       SDValue Shift = DAG.getNode(ISD::SRA, SDLoc(N0),
9979                                   XType, N0,
9980                                   DAG.getConstant(XType.getSizeInBits()-1,
9981                                          getShiftAmountTy(N0.getValueType())));
9982       AddToWorkList(Shift.getNode());
9983
9984       if (XType.bitsGT(AType)) {
9985         Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift);
9986         AddToWorkList(Shift.getNode());
9987       }
9988
9989       return DAG.getNode(ISD::AND, DL, AType, Shift, N2);
9990     }
9991   }
9992
9993   // fold (select_cc seteq (and x, y), 0, 0, A) -> (and (shr (shl x)) A)
9994   // where y is has a single bit set.
9995   // A plaintext description would be, we can turn the SELECT_CC into an AND
9996   // when the condition can be materialized as an all-ones register.  Any
9997   // single bit-test can be materialized as an all-ones register with
9998   // shift-left and shift-right-arith.
9999   if (CC == ISD::SETEQ && N0->getOpcode() == ISD::AND &&
10000       N0->getValueType(0) == VT &&
10001       N1C && N1C->isNullValue() &&
10002       N2C && N2C->isNullValue()) {
10003     SDValue AndLHS = N0->getOperand(0);
10004     ConstantSDNode *ConstAndRHS = dyn_cast<ConstantSDNode>(N0->getOperand(1));
10005     if (ConstAndRHS && ConstAndRHS->getAPIntValue().countPopulation() == 1) {
10006       // Shift the tested bit over the sign bit.
10007       APInt AndMask = ConstAndRHS->getAPIntValue();
10008       SDValue ShlAmt =
10009         DAG.getConstant(AndMask.countLeadingZeros(),
10010                         getShiftAmountTy(AndLHS.getValueType()));
10011       SDValue Shl = DAG.getNode(ISD::SHL, SDLoc(N0), VT, AndLHS, ShlAmt);
10012
10013       // Now arithmetic right shift it all the way over, so the result is either
10014       // all-ones, or zero.
10015       SDValue ShrAmt =
10016         DAG.getConstant(AndMask.getBitWidth()-1,
10017                         getShiftAmountTy(Shl.getValueType()));
10018       SDValue Shr = DAG.getNode(ISD::SRA, SDLoc(N0), VT, Shl, ShrAmt);
10019
10020       return DAG.getNode(ISD::AND, DL, VT, Shr, N3);
10021     }
10022   }
10023
10024   // fold select C, 16, 0 -> shl C, 4
10025   if (N2C && N3C && N3C->isNullValue() && N2C->getAPIntValue().isPowerOf2() &&
10026     TLI.getBooleanContents(N0.getValueType().isVector()) ==
10027       TargetLowering::ZeroOrOneBooleanContent) {
10028
10029     // If the caller doesn't want us to simplify this into a zext of a compare,
10030     // don't do it.
10031     if (NotExtCompare && N2C->getAPIntValue() == 1)
10032       return SDValue();
10033
10034     // Get a SetCC of the condition
10035     // NOTE: Don't create a SETCC if it's not legal on this target.
10036     if (!LegalOperations ||
10037         TLI.isOperationLegal(ISD::SETCC,
10038           LegalTypes ? getSetCCResultType(N0.getValueType()) : MVT::i1)) {
10039       SDValue Temp, SCC;
10040       // cast from setcc result type to select result type
10041       if (LegalTypes) {
10042         SCC  = DAG.getSetCC(DL, getSetCCResultType(N0.getValueType()),
10043                             N0, N1, CC);
10044         if (N2.getValueType().bitsLT(SCC.getValueType()))
10045           Temp = DAG.getZeroExtendInReg(SCC, SDLoc(N2),
10046                                         N2.getValueType());
10047         else
10048           Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2),
10049                              N2.getValueType(), SCC);
10050       } else {
10051         SCC  = DAG.getSetCC(SDLoc(N0), MVT::i1, N0, N1, CC);
10052         Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2),
10053                            N2.getValueType(), SCC);
10054       }
10055
10056       AddToWorkList(SCC.getNode());
10057       AddToWorkList(Temp.getNode());
10058
10059       if (N2C->getAPIntValue() == 1)
10060         return Temp;
10061
10062       // shl setcc result by log2 n2c
10063       return DAG.getNode(ISD::SHL, DL, N2.getValueType(), Temp,
10064                          DAG.getConstant(N2C->getAPIntValue().logBase2(),
10065                                          getShiftAmountTy(Temp.getValueType())));
10066     }
10067   }
10068
10069   // Check to see if this is the equivalent of setcc
10070   // FIXME: Turn all of these into setcc if setcc if setcc is legal
10071   // otherwise, go ahead with the folds.
10072   if (0 && N3C && N3C->isNullValue() && N2C && (N2C->getAPIntValue() == 1ULL)) {
10073     EVT XType = N0.getValueType();
10074     if (!LegalOperations ||
10075         TLI.isOperationLegal(ISD::SETCC, getSetCCResultType(XType))) {
10076       SDValue Res = DAG.getSetCC(DL, getSetCCResultType(XType), N0, N1, CC);
10077       if (Res.getValueType() != VT)
10078         Res = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, Res);
10079       return Res;
10080     }
10081
10082     // fold (seteq X, 0) -> (srl (ctlz X, log2(size(X))))
10083     if (N1C && N1C->isNullValue() && CC == ISD::SETEQ &&
10084         (!LegalOperations ||
10085          TLI.isOperationLegal(ISD::CTLZ, XType))) {
10086       SDValue Ctlz = DAG.getNode(ISD::CTLZ, SDLoc(N0), XType, N0);
10087       return DAG.getNode(ISD::SRL, DL, XType, Ctlz,
10088                          DAG.getConstant(Log2_32(XType.getSizeInBits()),
10089                                        getShiftAmountTy(Ctlz.getValueType())));
10090     }
10091     // fold (setgt X, 0) -> (srl (and (-X, ~X), size(X)-1))
10092     if (N1C && N1C->isNullValue() && CC == ISD::SETGT) {
10093       SDValue NegN0 = DAG.getNode(ISD::SUB, SDLoc(N0),
10094                                   XType, DAG.getConstant(0, XType), N0);
10095       SDValue NotN0 = DAG.getNOT(SDLoc(N0), N0, XType);
10096       return DAG.getNode(ISD::SRL, DL, XType,
10097                          DAG.getNode(ISD::AND, DL, XType, NegN0, NotN0),
10098                          DAG.getConstant(XType.getSizeInBits()-1,
10099                                          getShiftAmountTy(XType)));
10100     }
10101     // fold (setgt X, -1) -> (xor (srl (X, size(X)-1), 1))
10102     if (N1C && N1C->isAllOnesValue() && CC == ISD::SETGT) {
10103       SDValue Sign = DAG.getNode(ISD::SRL, SDLoc(N0), XType, N0,
10104                                  DAG.getConstant(XType.getSizeInBits()-1,
10105                                          getShiftAmountTy(N0.getValueType())));
10106       return DAG.getNode(ISD::XOR, DL, XType, Sign, DAG.getConstant(1, XType));
10107     }
10108   }
10109
10110   // Check to see if this is an integer abs.
10111   // select_cc setg[te] X,  0,  X, -X ->
10112   // select_cc setgt    X, -1,  X, -X ->
10113   // select_cc setl[te] X,  0, -X,  X ->
10114   // select_cc setlt    X,  1, -X,  X ->
10115   // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
10116   if (N1C) {
10117     ConstantSDNode *SubC = NULL;
10118     if (((N1C->isNullValue() && (CC == ISD::SETGT || CC == ISD::SETGE)) ||
10119          (N1C->isAllOnesValue() && CC == ISD::SETGT)) &&
10120         N0 == N2 && N3.getOpcode() == ISD::SUB && N0 == N3.getOperand(1))
10121       SubC = dyn_cast<ConstantSDNode>(N3.getOperand(0));
10122     else if (((N1C->isNullValue() && (CC == ISD::SETLT || CC == ISD::SETLE)) ||
10123               (N1C->isOne() && CC == ISD::SETLT)) &&
10124              N0 == N3 && N2.getOpcode() == ISD::SUB && N0 == N2.getOperand(1))
10125       SubC = dyn_cast<ConstantSDNode>(N2.getOperand(0));
10126
10127     EVT XType = N0.getValueType();
10128     if (SubC && SubC->isNullValue() && XType.isInteger()) {
10129       SDValue Shift = DAG.getNode(ISD::SRA, SDLoc(N0), XType,
10130                                   N0,
10131                                   DAG.getConstant(XType.getSizeInBits()-1,
10132                                          getShiftAmountTy(N0.getValueType())));
10133       SDValue Add = DAG.getNode(ISD::ADD, SDLoc(N0),
10134                                 XType, N0, Shift);
10135       AddToWorkList(Shift.getNode());
10136       AddToWorkList(Add.getNode());
10137       return DAG.getNode(ISD::XOR, DL, XType, Add, Shift);
10138     }
10139   }
10140
10141   return SDValue();
10142 }
10143
10144 /// SimplifySetCC - This is a stub for TargetLowering::SimplifySetCC.
10145 SDValue DAGCombiner::SimplifySetCC(EVT VT, SDValue N0,
10146                                    SDValue N1, ISD::CondCode Cond,
10147                                    SDLoc DL, bool foldBooleans) {
10148   TargetLowering::DAGCombinerInfo
10149     DagCombineInfo(DAG, Level, false, this);
10150   return TLI.SimplifySetCC(VT, N0, N1, Cond, foldBooleans, DagCombineInfo, DL);
10151 }
10152
10153 /// BuildSDIVSequence - Given an ISD::SDIV node expressing a divide by constant,
10154 /// return a DAG expression to select that will generate the same value by
10155 /// multiplying by a magic number.  See:
10156 /// <http://the.wall.riscom.net/books/proc/ppc/cwg/code2.html>
10157 SDValue DAGCombiner::BuildSDIV(SDNode *N) {
10158   std::vector<SDNode*> Built;
10159   SDValue S = TLI.BuildSDIV(N, DAG, LegalOperations, &Built);
10160
10161   for (std::vector<SDNode*>::iterator ii = Built.begin(), ee = Built.end();
10162        ii != ee; ++ii)
10163     AddToWorkList(*ii);
10164   return S;
10165 }
10166
10167 /// BuildUDIVSequence - Given an ISD::UDIV node expressing a divide by constant,
10168 /// return a DAG expression to select that will generate the same value by
10169 /// multiplying by a magic number.  See:
10170 /// <http://the.wall.riscom.net/books/proc/ppc/cwg/code2.html>
10171 SDValue DAGCombiner::BuildUDIV(SDNode *N) {
10172   std::vector<SDNode*> Built;
10173   SDValue S = TLI.BuildUDIV(N, DAG, LegalOperations, &Built);
10174
10175   for (std::vector<SDNode*>::iterator ii = Built.begin(), ee = Built.end();
10176        ii != ee; ++ii)
10177     AddToWorkList(*ii);
10178   return S;
10179 }
10180
10181 /// FindBaseOffset - Return true if base is a frame index, which is known not
10182 // to alias with anything but itself.  Provides base object and offset as
10183 // results.
10184 static bool FindBaseOffset(SDValue Ptr, SDValue &Base, int64_t &Offset,
10185                            const GlobalValue *&GV, const void *&CV) {
10186   // Assume it is a primitive operation.
10187   Base = Ptr; Offset = 0; GV = 0; CV = 0;
10188
10189   // If it's an adding a simple constant then integrate the offset.
10190   if (Base.getOpcode() == ISD::ADD) {
10191     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Base.getOperand(1))) {
10192       Base = Base.getOperand(0);
10193       Offset += C->getZExtValue();
10194     }
10195   }
10196
10197   // Return the underlying GlobalValue, and update the Offset.  Return false
10198   // for GlobalAddressSDNode since the same GlobalAddress may be represented
10199   // by multiple nodes with different offsets.
10200   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Base)) {
10201     GV = G->getGlobal();
10202     Offset += G->getOffset();
10203     return false;
10204   }
10205
10206   // Return the underlying Constant value, and update the Offset.  Return false
10207   // for ConstantSDNodes since the same constant pool entry may be represented
10208   // by multiple nodes with different offsets.
10209   if (ConstantPoolSDNode *C = dyn_cast<ConstantPoolSDNode>(Base)) {
10210     CV = C->isMachineConstantPoolEntry() ? (const void *)C->getMachineCPVal()
10211                                          : (const void *)C->getConstVal();
10212     Offset += C->getOffset();
10213     return false;
10214   }
10215   // If it's any of the following then it can't alias with anything but itself.
10216   return isa<FrameIndexSDNode>(Base);
10217 }
10218
10219 /// isAlias - Return true if there is any possibility that the two addresses
10220 /// overlap.
10221 bool DAGCombiner::isAlias(SDValue Ptr1, int64_t Size1,
10222                           const Value *SrcValue1, int SrcValueOffset1,
10223                           unsigned SrcValueAlign1,
10224                           const MDNode *TBAAInfo1,
10225                           SDValue Ptr2, int64_t Size2,
10226                           const Value *SrcValue2, int SrcValueOffset2,
10227                           unsigned SrcValueAlign2,
10228                           const MDNode *TBAAInfo2) const {
10229   // If they are the same then they must be aliases.
10230   if (Ptr1 == Ptr2) return true;
10231
10232   // Gather base node and offset information.
10233   SDValue Base1, Base2;
10234   int64_t Offset1, Offset2;
10235   const GlobalValue *GV1, *GV2;
10236   const void *CV1, *CV2;
10237   bool isFrameIndex1 = FindBaseOffset(Ptr1, Base1, Offset1, GV1, CV1);
10238   bool isFrameIndex2 = FindBaseOffset(Ptr2, Base2, Offset2, GV2, CV2);
10239
10240   // If they have a same base address then check to see if they overlap.
10241   if (Base1 == Base2 || (GV1 && (GV1 == GV2)) || (CV1 && (CV1 == CV2)))
10242     return !((Offset1 + Size1) <= Offset2 || (Offset2 + Size2) <= Offset1);
10243
10244   // It is possible for different frame indices to alias each other, mostly
10245   // when tail call optimization reuses return address slots for arguments.
10246   // To catch this case, look up the actual index of frame indices to compute
10247   // the real alias relationship.
10248   if (isFrameIndex1 && isFrameIndex2) {
10249     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
10250     Offset1 += MFI->getObjectOffset(cast<FrameIndexSDNode>(Base1)->getIndex());
10251     Offset2 += MFI->getObjectOffset(cast<FrameIndexSDNode>(Base2)->getIndex());
10252     return !((Offset1 + Size1) <= Offset2 || (Offset2 + Size2) <= Offset1);
10253   }
10254
10255   // Otherwise, if we know what the bases are, and they aren't identical, then
10256   // we know they cannot alias.
10257   if ((isFrameIndex1 || CV1 || GV1) && (isFrameIndex2 || CV2 || GV2))
10258     return false;
10259
10260   // If we know required SrcValue1 and SrcValue2 have relatively large alignment
10261   // compared to the size and offset of the access, we may be able to prove they
10262   // do not alias.  This check is conservative for now to catch cases created by
10263   // splitting vector types.
10264   if ((SrcValueAlign1 == SrcValueAlign2) &&
10265       (SrcValueOffset1 != SrcValueOffset2) &&
10266       (Size1 == Size2) && (SrcValueAlign1 > Size1)) {
10267     int64_t OffAlign1 = SrcValueOffset1 % SrcValueAlign1;
10268     int64_t OffAlign2 = SrcValueOffset2 % SrcValueAlign1;
10269
10270     // There is no overlap between these relatively aligned accesses of similar
10271     // size, return no alias.
10272     if ((OffAlign1 + Size1) <= OffAlign2 || (OffAlign2 + Size2) <= OffAlign1)
10273       return false;
10274   }
10275
10276   bool UseAA = CombinerGlobalAA.getNumOccurrences() > 0 ? CombinerGlobalAA :
10277     TLI.getTargetMachine().getSubtarget<TargetSubtargetInfo>().useAA();
10278   if (UseAA && SrcValue1 && SrcValue2) {
10279     // Use alias analysis information.
10280     int64_t MinOffset = std::min(SrcValueOffset1, SrcValueOffset2);
10281     int64_t Overlap1 = Size1 + SrcValueOffset1 - MinOffset;
10282     int64_t Overlap2 = Size2 + SrcValueOffset2 - MinOffset;
10283     AliasAnalysis::AliasResult AAResult =
10284       AA.alias(AliasAnalysis::Location(SrcValue1, Overlap1, TBAAInfo1),
10285                AliasAnalysis::Location(SrcValue2, Overlap2, TBAAInfo2));
10286     if (AAResult == AliasAnalysis::NoAlias)
10287       return false;
10288   }
10289
10290   // Otherwise we have to assume they alias.
10291   return true;
10292 }
10293
10294 bool DAGCombiner::isAlias(LSBaseSDNode *Op0, LSBaseSDNode *Op1) {
10295   SDValue Ptr0, Ptr1;
10296   int64_t Size0, Size1;
10297   const Value *SrcValue0, *SrcValue1;
10298   int SrcValueOffset0, SrcValueOffset1;
10299   unsigned SrcValueAlign0, SrcValueAlign1;
10300   const MDNode *SrcTBAAInfo0, *SrcTBAAInfo1;
10301   FindAliasInfo(Op0, Ptr0, Size0, SrcValue0, SrcValueOffset0,
10302                 SrcValueAlign0, SrcTBAAInfo0);
10303   FindAliasInfo(Op1, Ptr1, Size1, SrcValue1, SrcValueOffset1,
10304                 SrcValueAlign1, SrcTBAAInfo1);
10305   return isAlias(Ptr0, Size0, SrcValue0, SrcValueOffset0,
10306                  SrcValueAlign0, SrcTBAAInfo0,
10307                  Ptr1, Size1, SrcValue1, SrcValueOffset1,
10308                  SrcValueAlign1, SrcTBAAInfo1);
10309 }
10310
10311 /// FindAliasInfo - Extracts the relevant alias information from the memory
10312 /// node.  Returns true if the operand was a load.
10313 bool DAGCombiner::FindAliasInfo(SDNode *N,
10314                                 SDValue &Ptr, int64_t &Size,
10315                                 const Value *&SrcValue,
10316                                 int &SrcValueOffset,
10317                                 unsigned &SrcValueAlign,
10318                                 const MDNode *&TBAAInfo) const {
10319   LSBaseSDNode *LS = cast<LSBaseSDNode>(N);
10320
10321   Ptr = LS->getBasePtr();
10322   Size = LS->getMemoryVT().getSizeInBits() >> 3;
10323   SrcValue = LS->getSrcValue();
10324   SrcValueOffset = LS->getSrcValueOffset();
10325   SrcValueAlign = LS->getOriginalAlignment();
10326   TBAAInfo = LS->getTBAAInfo();
10327   return isa<LoadSDNode>(LS);
10328 }
10329
10330 /// GatherAllAliases - Walk up chain skipping non-aliasing memory nodes,
10331 /// looking for aliasing nodes and adding them to the Aliases vector.
10332 void DAGCombiner::GatherAllAliases(SDNode *N, SDValue OriginalChain,
10333                                    SmallVectorImpl<SDValue> &Aliases) {
10334   SmallVector<SDValue, 8> Chains;     // List of chains to visit.
10335   SmallPtrSet<SDNode *, 16> Visited;  // Visited node set.
10336
10337   // Get alias information for node.
10338   SDValue Ptr;
10339   int64_t Size;
10340   const Value *SrcValue;
10341   int SrcValueOffset;
10342   unsigned SrcValueAlign;
10343   const MDNode *SrcTBAAInfo;
10344   bool IsLoad = FindAliasInfo(N, Ptr, Size, SrcValue, SrcValueOffset,
10345                               SrcValueAlign, SrcTBAAInfo);
10346
10347   // Starting off.
10348   Chains.push_back(OriginalChain);
10349   unsigned Depth = 0;
10350
10351   // Look at each chain and determine if it is an alias.  If so, add it to the
10352   // aliases list.  If not, then continue up the chain looking for the next
10353   // candidate.
10354   while (!Chains.empty()) {
10355     SDValue Chain = Chains.back();
10356     Chains.pop_back();
10357
10358     // For TokenFactor nodes, look at each operand and only continue up the
10359     // chain until we find two aliases.  If we've seen two aliases, assume we'll
10360     // find more and revert to original chain since the xform is unlikely to be
10361     // profitable.
10362     //
10363     // FIXME: The depth check could be made to return the last non-aliasing
10364     // chain we found before we hit a tokenfactor rather than the original
10365     // chain.
10366     if (Depth > 6 || Aliases.size() == 2) {
10367       Aliases.clear();
10368       Aliases.push_back(OriginalChain);
10369       break;
10370     }
10371
10372     // Don't bother if we've been before.
10373     if (!Visited.insert(Chain.getNode()))
10374       continue;
10375
10376     switch (Chain.getOpcode()) {
10377     case ISD::EntryToken:
10378       // Entry token is ideal chain operand, but handled in FindBetterChain.
10379       break;
10380
10381     case ISD::LOAD:
10382     case ISD::STORE: {
10383       // Get alias information for Chain.
10384       SDValue OpPtr;
10385       int64_t OpSize;
10386       const Value *OpSrcValue;
10387       int OpSrcValueOffset;
10388       unsigned OpSrcValueAlign;
10389       const MDNode *OpSrcTBAAInfo;
10390       bool IsOpLoad = FindAliasInfo(Chain.getNode(), OpPtr, OpSize,
10391                                     OpSrcValue, OpSrcValueOffset,
10392                                     OpSrcValueAlign,
10393                                     OpSrcTBAAInfo);
10394
10395       // If chain is alias then stop here.
10396       if (!(IsLoad && IsOpLoad) &&
10397           isAlias(Ptr, Size, SrcValue, SrcValueOffset, SrcValueAlign,
10398                   SrcTBAAInfo,
10399                   OpPtr, OpSize, OpSrcValue, OpSrcValueOffset,
10400                   OpSrcValueAlign, OpSrcTBAAInfo)) {
10401         Aliases.push_back(Chain);
10402       } else {
10403         // Look further up the chain.
10404         Chains.push_back(Chain.getOperand(0));
10405         ++Depth;
10406       }
10407       break;
10408     }
10409
10410     case ISD::TokenFactor:
10411       // We have to check each of the operands of the token factor for "small"
10412       // token factors, so we queue them up.  Adding the operands to the queue
10413       // (stack) in reverse order maintains the original order and increases the
10414       // likelihood that getNode will find a matching token factor (CSE.)
10415       if (Chain.getNumOperands() > 16) {
10416         Aliases.push_back(Chain);
10417         break;
10418       }
10419       for (unsigned n = Chain.getNumOperands(); n;)
10420         Chains.push_back(Chain.getOperand(--n));
10421       ++Depth;
10422       break;
10423
10424     default:
10425       // For all other instructions we will just have to take what we can get.
10426       Aliases.push_back(Chain);
10427       break;
10428     }
10429   }
10430 }
10431
10432 /// FindBetterChain - Walk up chain skipping non-aliasing memory nodes, looking
10433 /// for a better chain (aliasing node.)
10434 SDValue DAGCombiner::FindBetterChain(SDNode *N, SDValue OldChain) {
10435   SmallVector<SDValue, 8> Aliases;  // Ops for replacing token factor.
10436
10437   // Accumulate all the aliases to this node.
10438   GatherAllAliases(N, OldChain, Aliases);
10439
10440   // If no operands then chain to entry token.
10441   if (Aliases.size() == 0)
10442     return DAG.getEntryNode();
10443
10444   // If a single operand then chain to it.  We don't need to revisit it.
10445   if (Aliases.size() == 1)
10446     return Aliases[0];
10447
10448   // Construct a custom tailored token factor.
10449   return DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other,
10450                      &Aliases[0], Aliases.size());
10451 }
10452
10453 // SelectionDAG::Combine - This is the entry point for the file.
10454 //
10455 void SelectionDAG::Combine(CombineLevel Level, AliasAnalysis &AA,
10456                            CodeGenOpt::Level OptLevel) {
10457   /// run - This is the main entry point to this class.
10458   ///
10459   DAGCombiner(*this, AA, OptLevel).Run(Level);
10460 }