LegalizeDAG.cpp revision 1c39965342453ce33a3b3f9a863c38fdb45fd6ef
1//===-- LegalizeDAG.cpp - Implement SelectionDAG::Legalize ----------------===//
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 file implements the SelectionDAG::Legalize method.
11//
12//===----------------------------------------------------------------------===//
13
14#include "llvm/CodeGen/SelectionDAG.h"
15#include "llvm/CodeGen/MachineFunction.h"
16#include "llvm/CodeGen/MachineFrameInfo.h"
17#include "llvm/CodeGen/MachineJumpTableInfo.h"
18#include "llvm/CodeGen/MachineModuleInfo.h"
19#include "llvm/CodeGen/DwarfWriter.h"
20#include "llvm/Analysis/DebugInfo.h"
21#include "llvm/CodeGen/PseudoSourceValue.h"
22#include "llvm/Target/TargetFrameInfo.h"
23#include "llvm/Target/TargetLowering.h"
24#include "llvm/Target/TargetData.h"
25#include "llvm/Target/TargetMachine.h"
26#include "llvm/Target/TargetOptions.h"
27#include "llvm/Target/TargetSubtarget.h"
28#include "llvm/CallingConv.h"
29#include "llvm/Constants.h"
30#include "llvm/DerivedTypes.h"
31#include "llvm/Function.h"
32#include "llvm/GlobalVariable.h"
33#include "llvm/Support/CommandLine.h"
34#include "llvm/Support/Compiler.h"
35#include "llvm/Support/MathExtras.h"
36#include "llvm/ADT/DenseMap.h"
37#include "llvm/ADT/SmallVector.h"
38#include "llvm/ADT/SmallPtrSet.h"
39#include <map>
40using namespace llvm;
41
42//===----------------------------------------------------------------------===//
43/// SelectionDAGLegalize - This takes an arbitrary SelectionDAG as input and
44/// hacks on it until the target machine can handle it.  This involves
45/// eliminating value sizes the machine cannot handle (promoting small sizes to
46/// large sizes or splitting up large values into small values) as well as
47/// eliminating operations the machine cannot handle.
48///
49/// This code also does a small amount of optimization and recognition of idioms
50/// as part of its processing.  For example, if a target does not support a
51/// 'setcc' instruction efficiently, but does support 'brcc' instruction, this
52/// will attempt merge setcc and brc instructions into brcc's.
53///
54namespace {
55class VISIBILITY_HIDDEN SelectionDAGLegalize {
56  TargetLowering &TLI;
57  SelectionDAG &DAG;
58  CodeGenOpt::Level OptLevel;
59
60  // Libcall insertion helpers.
61
62  /// LastCALLSEQ_END - This keeps track of the CALLSEQ_END node that has been
63  /// legalized.  We use this to ensure that calls are properly serialized
64  /// against each other, including inserted libcalls.
65  SDValue LastCALLSEQ_END;
66
67  /// IsLegalizingCall - This member is used *only* for purposes of providing
68  /// helpful assertions that a libcall isn't created while another call is
69  /// being legalized (which could lead to non-serialized call sequences).
70  bool IsLegalizingCall;
71
72  enum LegalizeAction {
73    Legal,      // The target natively supports this operation.
74    Promote,    // This operation should be executed in a larger type.
75    Expand      // Try to expand this to other ops, otherwise use a libcall.
76  };
77
78  /// ValueTypeActions - This is a bitvector that contains two bits for each
79  /// value type, where the two bits correspond to the LegalizeAction enum.
80  /// This can be queried with "getTypeAction(VT)".
81  TargetLowering::ValueTypeActionImpl ValueTypeActions;
82
83  /// LegalizedNodes - For nodes that are of legal width, and that have more
84  /// than one use, this map indicates what regularized operand to use.  This
85  /// allows us to avoid legalizing the same thing more than once.
86  DenseMap<SDValue, SDValue> LegalizedNodes;
87
88  void AddLegalizedOperand(SDValue From, SDValue To) {
89    LegalizedNodes.insert(std::make_pair(From, To));
90    // If someone requests legalization of the new node, return itself.
91    if (From != To)
92      LegalizedNodes.insert(std::make_pair(To, To));
93  }
94
95public:
96  SelectionDAGLegalize(SelectionDAG &DAG, CodeGenOpt::Level ol);
97
98  /// getTypeAction - Return how we should legalize values of this type, either
99  /// it is already legal or we need to expand it into multiple registers of
100  /// smaller integer type, or we need to promote it to a larger type.
101  LegalizeAction getTypeAction(MVT VT) const {
102    return (LegalizeAction)ValueTypeActions.getTypeAction(VT);
103  }
104
105  /// isTypeLegal - Return true if this type is legal on this target.
106  ///
107  bool isTypeLegal(MVT VT) const {
108    return getTypeAction(VT) == Legal;
109  }
110
111  void LegalizeDAG();
112
113private:
114  /// LegalizeOp - We know that the specified value has a legal type.
115  /// Recursively ensure that the operands have legal types, then return the
116  /// result.
117  SDValue LegalizeOp(SDValue O);
118
119  /// PerformInsertVectorEltInMemory - Some target cannot handle a variable
120  /// insertion index for the INSERT_VECTOR_ELT instruction.  In this case, it
121  /// is necessary to spill the vector being inserted into to memory, perform
122  /// the insert there, and then read the result back.
123  SDValue PerformInsertVectorEltInMemory(SDValue Vec, SDValue Val,
124                                         SDValue Idx, DebugLoc dl);
125  SDValue ExpandINSERT_VECTOR_ELT(SDValue Vec, SDValue Val,
126                                  SDValue Idx, DebugLoc dl);
127
128  /// ShuffleWithNarrowerEltType - Return a vector shuffle operation which
129  /// performs the same shuffe in terms of order or result bytes, but on a type
130  /// whose vector element type is narrower than the original shuffle type.
131  /// e.g. <v4i32> <0, 1, 0, 1> -> v8i16 <0, 1, 2, 3, 0, 1, 2, 3>
132  SDValue ShuffleWithNarrowerEltType(MVT NVT, MVT VT, DebugLoc dl,
133                                     SDValue N1, SDValue N2,
134                                     SmallVectorImpl<int> &Mask) const;
135
136  bool LegalizeAllNodesNotLeadingTo(SDNode *N, SDNode *Dest,
137                                    SmallPtrSet<SDNode*, 32> &NodesLeadingTo);
138
139  void LegalizeSetCCOperands(SDValue &LHS, SDValue &RHS, SDValue &CC,
140                             DebugLoc dl);
141  void LegalizeSetCCCondCode(MVT VT, SDValue &LHS, SDValue &RHS, SDValue &CC,
142                             DebugLoc dl);
143  void LegalizeSetCC(MVT VT, SDValue &LHS, SDValue &RHS, SDValue &CC,
144                     DebugLoc dl) {
145    LegalizeSetCCOperands(LHS, RHS, CC, dl);
146    LegalizeSetCCCondCode(VT, LHS, RHS, CC, dl);
147  }
148
149  SDValue ExpandLibCall(RTLIB::Libcall LC, SDNode *Node, bool isSigned);
150  SDValue ExpandFPLibCall(SDNode *Node, RTLIB::Libcall Call_F32,
151                          RTLIB::Libcall Call_F64, RTLIB::Libcall Call_F80,
152                          RTLIB::Libcall Call_PPCF128);
153  SDValue ExpandIntLibCall(SDNode *Node, bool isSigned, RTLIB::Libcall Call_I16,
154                           RTLIB::Libcall Call_I32, RTLIB::Libcall Call_I64,
155                           RTLIB::Libcall Call_I128);
156
157  SDValue EmitStackConvert(SDValue SrcOp, MVT SlotVT, MVT DestVT, DebugLoc dl);
158  SDValue ExpandBUILD_VECTOR(SDNode *Node);
159  SDValue ExpandSCALAR_TO_VECTOR(SDNode *Node);
160  SDValue ExpandDBG_STOPPOINT(SDNode *Node);
161  void ExpandDYNAMIC_STACKALLOC(SDNode *Node,
162                                SmallVectorImpl<SDValue> &Results);
163  SDValue ExpandFCOPYSIGN(SDNode *Node);
164  SDValue ExpandLegalINT_TO_FP(bool isSigned, SDValue LegalOp, MVT DestVT,
165                               DebugLoc dl);
166  SDValue PromoteLegalINT_TO_FP(SDValue LegalOp, MVT DestVT, bool isSigned,
167                                DebugLoc dl);
168  SDValue PromoteLegalFP_TO_INT(SDValue LegalOp, MVT DestVT, bool isSigned,
169                                DebugLoc dl);
170
171  SDValue ExpandBSWAP(SDValue Op, DebugLoc dl);
172  SDValue ExpandBitCount(unsigned Opc, SDValue Op, DebugLoc dl);
173
174  SDValue ExpandExtractFromVectorThroughStack(SDValue Op);
175
176  void ExpandNode(SDNode *Node, SmallVectorImpl<SDValue> &Results);
177  void PromoteNode(SDNode *Node, SmallVectorImpl<SDValue> &Results);
178};
179}
180
181/// ShuffleWithNarrowerEltType - Return a vector shuffle operation which
182/// performs the same shuffe in terms of order or result bytes, but on a type
183/// whose vector element type is narrower than the original shuffle type.
184/// e.g. <v4i32> <0, 1, 0, 1> -> v8i16 <0, 1, 2, 3, 0, 1, 2, 3>
185SDValue
186SelectionDAGLegalize::ShuffleWithNarrowerEltType(MVT NVT, MVT VT,  DebugLoc dl,
187                                                 SDValue N1, SDValue N2,
188                                             SmallVectorImpl<int> &Mask) const {
189  MVT EltVT = NVT.getVectorElementType();
190  unsigned NumMaskElts = VT.getVectorNumElements();
191  unsigned NumDestElts = NVT.getVectorNumElements();
192  unsigned NumEltsGrowth = NumDestElts / NumMaskElts;
193
194  assert(NumEltsGrowth && "Cannot promote to vector type with fewer elts!");
195
196  if (NumEltsGrowth == 1)
197    return DAG.getVectorShuffle(NVT, dl, N1, N2, &Mask[0]);
198
199  SmallVector<int, 8> NewMask;
200  for (unsigned i = 0; i != NumMaskElts; ++i) {
201    int Idx = Mask[i];
202    for (unsigned j = 0; j != NumEltsGrowth; ++j) {
203      if (Idx < 0)
204        NewMask.push_back(-1);
205      else
206        NewMask.push_back(Idx * NumEltsGrowth + j);
207    }
208  }
209  assert(NewMask.size() == NumDestElts && "Non-integer NumEltsGrowth?");
210  assert(TLI.isShuffleMaskLegal(NewMask, NVT) && "Shuffle not legal?");
211  return DAG.getVectorShuffle(NVT, dl, N1, N2, &NewMask[0]);
212}
213
214SelectionDAGLegalize::SelectionDAGLegalize(SelectionDAG &dag,
215                                           CodeGenOpt::Level ol)
216  : TLI(dag.getTargetLoweringInfo()), DAG(dag), OptLevel(ol),
217    ValueTypeActions(TLI.getValueTypeActions()) {
218  assert(MVT::LAST_VALUETYPE <= 32 &&
219         "Too many value types for ValueTypeActions to hold!");
220}
221
222void SelectionDAGLegalize::LegalizeDAG() {
223  LastCALLSEQ_END = DAG.getEntryNode();
224  IsLegalizingCall = false;
225
226  // The legalize process is inherently a bottom-up recursive process (users
227  // legalize their uses before themselves).  Given infinite stack space, we
228  // could just start legalizing on the root and traverse the whole graph.  In
229  // practice however, this causes us to run out of stack space on large basic
230  // blocks.  To avoid this problem, compute an ordering of the nodes where each
231  // node is only legalized after all of its operands are legalized.
232  DAG.AssignTopologicalOrder();
233  for (SelectionDAG::allnodes_iterator I = DAG.allnodes_begin(),
234       E = prior(DAG.allnodes_end()); I != next(E); ++I)
235    LegalizeOp(SDValue(I, 0));
236
237  // Finally, it's possible the root changed.  Get the new root.
238  SDValue OldRoot = DAG.getRoot();
239  assert(LegalizedNodes.count(OldRoot) && "Root didn't get legalized?");
240  DAG.setRoot(LegalizedNodes[OldRoot]);
241
242  LegalizedNodes.clear();
243
244  // Remove dead nodes now.
245  DAG.RemoveDeadNodes();
246}
247
248
249/// FindCallEndFromCallStart - Given a chained node that is part of a call
250/// sequence, find the CALLSEQ_END node that terminates the call sequence.
251static SDNode *FindCallEndFromCallStart(SDNode *Node) {
252  if (Node->getOpcode() == ISD::CALLSEQ_END)
253    return Node;
254  if (Node->use_empty())
255    return 0;   // No CallSeqEnd
256
257  // The chain is usually at the end.
258  SDValue TheChain(Node, Node->getNumValues()-1);
259  if (TheChain.getValueType() != MVT::Other) {
260    // Sometimes it's at the beginning.
261    TheChain = SDValue(Node, 0);
262    if (TheChain.getValueType() != MVT::Other) {
263      // Otherwise, hunt for it.
264      for (unsigned i = 1, e = Node->getNumValues(); i != e; ++i)
265        if (Node->getValueType(i) == MVT::Other) {
266          TheChain = SDValue(Node, i);
267          break;
268        }
269
270      // Otherwise, we walked into a node without a chain.
271      if (TheChain.getValueType() != MVT::Other)
272        return 0;
273    }
274  }
275
276  for (SDNode::use_iterator UI = Node->use_begin(),
277       E = Node->use_end(); UI != E; ++UI) {
278
279    // Make sure to only follow users of our token chain.
280    SDNode *User = *UI;
281    for (unsigned i = 0, e = User->getNumOperands(); i != e; ++i)
282      if (User->getOperand(i) == TheChain)
283        if (SDNode *Result = FindCallEndFromCallStart(User))
284          return Result;
285  }
286  return 0;
287}
288
289/// FindCallStartFromCallEnd - Given a chained node that is part of a call
290/// sequence, find the CALLSEQ_START node that initiates the call sequence.
291static SDNode *FindCallStartFromCallEnd(SDNode *Node) {
292  assert(Node && "Didn't find callseq_start for a call??");
293  if (Node->getOpcode() == ISD::CALLSEQ_START) return Node;
294
295  assert(Node->getOperand(0).getValueType() == MVT::Other &&
296         "Node doesn't have a token chain argument!");
297  return FindCallStartFromCallEnd(Node->getOperand(0).getNode());
298}
299
300/// LegalizeAllNodesNotLeadingTo - Recursively walk the uses of N, looking to
301/// see if any uses can reach Dest.  If no dest operands can get to dest,
302/// legalize them, legalize ourself, and return false, otherwise, return true.
303///
304/// Keep track of the nodes we fine that actually do lead to Dest in
305/// NodesLeadingTo.  This avoids retraversing them exponential number of times.
306///
307bool SelectionDAGLegalize::LegalizeAllNodesNotLeadingTo(SDNode *N, SDNode *Dest,
308                                     SmallPtrSet<SDNode*, 32> &NodesLeadingTo) {
309  if (N == Dest) return true;  // N certainly leads to Dest :)
310
311  // If we've already processed this node and it does lead to Dest, there is no
312  // need to reprocess it.
313  if (NodesLeadingTo.count(N)) return true;
314
315  // If the first result of this node has been already legalized, then it cannot
316  // reach N.
317  if (LegalizedNodes.count(SDValue(N, 0))) return false;
318
319  // Okay, this node has not already been legalized.  Check and legalize all
320  // operands.  If none lead to Dest, then we can legalize this node.
321  bool OperandsLeadToDest = false;
322  for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
323    OperandsLeadToDest |=     // If an operand leads to Dest, so do we.
324      LegalizeAllNodesNotLeadingTo(N->getOperand(i).getNode(), Dest, NodesLeadingTo);
325
326  if (OperandsLeadToDest) {
327    NodesLeadingTo.insert(N);
328    return true;
329  }
330
331  // Okay, this node looks safe, legalize it and return false.
332  LegalizeOp(SDValue(N, 0));
333  return false;
334}
335
336/// ExpandConstantFP - Expands the ConstantFP node to an integer constant or
337/// a load from the constant pool.
338static SDValue ExpandConstantFP(ConstantFPSDNode *CFP, bool UseCP,
339                                SelectionDAG &DAG, const TargetLowering &TLI) {
340  bool Extend = false;
341  DebugLoc dl = CFP->getDebugLoc();
342
343  // If a FP immediate is precise when represented as a float and if the
344  // target can do an extending load from float to double, we put it into
345  // the constant pool as a float, even if it's is statically typed as a
346  // double.  This shrinks FP constants and canonicalizes them for targets where
347  // an FP extending load is the same cost as a normal load (such as on the x87
348  // fp stack or PPC FP unit).
349  MVT VT = CFP->getValueType(0);
350  ConstantFP *LLVMC = const_cast<ConstantFP*>(CFP->getConstantFPValue());
351  if (!UseCP) {
352    assert((VT == MVT::f64 || VT == MVT::f32) && "Invalid type expansion");
353    return DAG.getConstant(LLVMC->getValueAPF().bitcastToAPInt(),
354                           (VT == MVT::f64) ? MVT::i64 : MVT::i32);
355  }
356
357  MVT OrigVT = VT;
358  MVT SVT = VT;
359  while (SVT != MVT::f32) {
360    SVT = (MVT::SimpleValueType)(SVT.getSimpleVT() - 1);
361    if (CFP->isValueValidForType(SVT, CFP->getValueAPF()) &&
362        // Only do this if the target has a native EXTLOAD instruction from
363        // smaller type.
364        TLI.isLoadExtLegal(ISD::EXTLOAD, SVT) &&
365        TLI.ShouldShrinkFPConstant(OrigVT)) {
366      const Type *SType = SVT.getTypeForMVT();
367      LLVMC = cast<ConstantFP>(ConstantExpr::getFPTrunc(LLVMC, SType));
368      VT = SVT;
369      Extend = true;
370    }
371  }
372
373  SDValue CPIdx = DAG.getConstantPool(LLVMC, TLI.getPointerTy());
374  unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
375  if (Extend)
376    return DAG.getExtLoad(ISD::EXTLOAD, dl,
377                          OrigVT, DAG.getEntryNode(),
378                          CPIdx, PseudoSourceValue::getConstantPool(),
379                          0, VT, false, Alignment);
380  return DAG.getLoad(OrigVT, dl, DAG.getEntryNode(), CPIdx,
381                     PseudoSourceValue::getConstantPool(), 0, false, Alignment);
382}
383
384/// ExpandUnalignedStore - Expands an unaligned store to 2 half-size stores.
385static
386SDValue ExpandUnalignedStore(StoreSDNode *ST, SelectionDAG &DAG,
387                             const TargetLowering &TLI) {
388  SDValue Chain = ST->getChain();
389  SDValue Ptr = ST->getBasePtr();
390  SDValue Val = ST->getValue();
391  MVT VT = Val.getValueType();
392  int Alignment = ST->getAlignment();
393  int SVOffset = ST->getSrcValueOffset();
394  DebugLoc dl = ST->getDebugLoc();
395  if (ST->getMemoryVT().isFloatingPoint() ||
396      ST->getMemoryVT().isVector()) {
397    MVT intVT = MVT::getIntegerVT(VT.getSizeInBits());
398    if (TLI.isTypeLegal(intVT)) {
399      // Expand to a bitconvert of the value to the integer type of the
400      // same size, then a (misaligned) int store.
401      // FIXME: Does not handle truncating floating point stores!
402      SDValue Result = DAG.getNode(ISD::BIT_CONVERT, dl, intVT, Val);
403      return DAG.getStore(Chain, dl, Result, Ptr, ST->getSrcValue(),
404                          SVOffset, ST->isVolatile(), Alignment);
405    } else {
406      // Do a (aligned) store to a stack slot, then copy from the stack slot
407      // to the final destination using (unaligned) integer loads and stores.
408      MVT StoredVT = ST->getMemoryVT();
409      MVT RegVT =
410        TLI.getRegisterType(MVT::getIntegerVT(StoredVT.getSizeInBits()));
411      unsigned StoredBytes = StoredVT.getSizeInBits() / 8;
412      unsigned RegBytes = RegVT.getSizeInBits() / 8;
413      unsigned NumRegs = (StoredBytes + RegBytes - 1) / RegBytes;
414
415      // Make sure the stack slot is also aligned for the register type.
416      SDValue StackPtr = DAG.CreateStackTemporary(StoredVT, RegVT);
417
418      // Perform the original store, only redirected to the stack slot.
419      SDValue Store = DAG.getTruncStore(Chain, dl,
420                                        Val, StackPtr, NULL, 0, StoredVT);
421      SDValue Increment = DAG.getConstant(RegBytes, TLI.getPointerTy());
422      SmallVector<SDValue, 8> Stores;
423      unsigned Offset = 0;
424
425      // Do all but one copies using the full register width.
426      for (unsigned i = 1; i < NumRegs; i++) {
427        // Load one integer register's worth from the stack slot.
428        SDValue Load = DAG.getLoad(RegVT, dl, Store, StackPtr, NULL, 0);
429        // Store it to the final location.  Remember the store.
430        Stores.push_back(DAG.getStore(Load.getValue(1), dl, Load, Ptr,
431                                      ST->getSrcValue(), SVOffset + Offset,
432                                      ST->isVolatile(),
433                                      MinAlign(ST->getAlignment(), Offset)));
434        // Increment the pointers.
435        Offset += RegBytes;
436        StackPtr = DAG.getNode(ISD::ADD, dl, StackPtr.getValueType(), StackPtr,
437                               Increment);
438        Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
439      }
440
441      // The last store may be partial.  Do a truncating store.  On big-endian
442      // machines this requires an extending load from the stack slot to ensure
443      // that the bits are in the right place.
444      MVT MemVT = MVT::getIntegerVT(8 * (StoredBytes - Offset));
445
446      // Load from the stack slot.
447      SDValue Load = DAG.getExtLoad(ISD::EXTLOAD, dl, RegVT, Store, StackPtr,
448                                    NULL, 0, MemVT);
449
450      Stores.push_back(DAG.getTruncStore(Load.getValue(1), dl, Load, Ptr,
451                                         ST->getSrcValue(), SVOffset + Offset,
452                                         MemVT, ST->isVolatile(),
453                                         MinAlign(ST->getAlignment(), Offset)));
454      // The order of the stores doesn't matter - say it with a TokenFactor.
455      return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, &Stores[0],
456                         Stores.size());
457    }
458  }
459  assert(ST->getMemoryVT().isInteger() &&
460         !ST->getMemoryVT().isVector() &&
461         "Unaligned store of unknown type.");
462  // Get the half-size VT
463  MVT NewStoredVT =
464    (MVT::SimpleValueType)(ST->getMemoryVT().getSimpleVT() - 1);
465  int NumBits = NewStoredVT.getSizeInBits();
466  int IncrementSize = NumBits / 8;
467
468  // Divide the stored value in two parts.
469  SDValue ShiftAmount = DAG.getConstant(NumBits, TLI.getShiftAmountTy());
470  SDValue Lo = Val;
471  SDValue Hi = DAG.getNode(ISD::SRL, dl, VT, Val, ShiftAmount);
472
473  // Store the two parts
474  SDValue Store1, Store2;
475  Store1 = DAG.getTruncStore(Chain, dl, TLI.isLittleEndian()?Lo:Hi, Ptr,
476                             ST->getSrcValue(), SVOffset, NewStoredVT,
477                             ST->isVolatile(), Alignment);
478  Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr,
479                    DAG.getConstant(IncrementSize, TLI.getPointerTy()));
480  Alignment = MinAlign(Alignment, IncrementSize);
481  Store2 = DAG.getTruncStore(Chain, dl, TLI.isLittleEndian()?Hi:Lo, Ptr,
482                             ST->getSrcValue(), SVOffset + IncrementSize,
483                             NewStoredVT, ST->isVolatile(), Alignment);
484
485  return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Store1, Store2);
486}
487
488/// ExpandUnalignedLoad - Expands an unaligned load to 2 half-size loads.
489static
490SDValue ExpandUnalignedLoad(LoadSDNode *LD, SelectionDAG &DAG,
491                            const TargetLowering &TLI) {
492  int SVOffset = LD->getSrcValueOffset();
493  SDValue Chain = LD->getChain();
494  SDValue Ptr = LD->getBasePtr();
495  MVT VT = LD->getValueType(0);
496  MVT LoadedVT = LD->getMemoryVT();
497  DebugLoc dl = LD->getDebugLoc();
498  if (VT.isFloatingPoint() || VT.isVector()) {
499    MVT intVT = MVT::getIntegerVT(LoadedVT.getSizeInBits());
500    if (TLI.isTypeLegal(intVT)) {
501      // Expand to a (misaligned) integer load of the same size,
502      // then bitconvert to floating point or vector.
503      SDValue newLoad = DAG.getLoad(intVT, dl, Chain, Ptr, LD->getSrcValue(),
504                                    SVOffset, LD->isVolatile(),
505                                    LD->getAlignment());
506      SDValue Result = DAG.getNode(ISD::BIT_CONVERT, dl, LoadedVT, newLoad);
507      if (VT.isFloatingPoint() && LoadedVT != VT)
508        Result = DAG.getNode(ISD::FP_EXTEND, dl, VT, Result);
509
510      SDValue Ops[] = { Result, Chain };
511      return DAG.getMergeValues(Ops, 2, dl);
512    } else {
513      // Copy the value to a (aligned) stack slot using (unaligned) integer
514      // loads and stores, then do a (aligned) load from the stack slot.
515      MVT RegVT = TLI.getRegisterType(intVT);
516      unsigned LoadedBytes = LoadedVT.getSizeInBits() / 8;
517      unsigned RegBytes = RegVT.getSizeInBits() / 8;
518      unsigned NumRegs = (LoadedBytes + RegBytes - 1) / RegBytes;
519
520      // Make sure the stack slot is also aligned for the register type.
521      SDValue StackBase = DAG.CreateStackTemporary(LoadedVT, RegVT);
522
523      SDValue Increment = DAG.getConstant(RegBytes, TLI.getPointerTy());
524      SmallVector<SDValue, 8> Stores;
525      SDValue StackPtr = StackBase;
526      unsigned Offset = 0;
527
528      // Do all but one copies using the full register width.
529      for (unsigned i = 1; i < NumRegs; i++) {
530        // Load one integer register's worth from the original location.
531        SDValue Load = DAG.getLoad(RegVT, dl, Chain, Ptr, LD->getSrcValue(),
532                                   SVOffset + Offset, LD->isVolatile(),
533                                   MinAlign(LD->getAlignment(), Offset));
534        // Follow the load with a store to the stack slot.  Remember the store.
535        Stores.push_back(DAG.getStore(Load.getValue(1), dl, Load, StackPtr,
536                                      NULL, 0));
537        // Increment the pointers.
538        Offset += RegBytes;
539        Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
540        StackPtr = DAG.getNode(ISD::ADD, dl, StackPtr.getValueType(), StackPtr,
541                               Increment);
542      }
543
544      // The last copy may be partial.  Do an extending load.
545      MVT MemVT = MVT::getIntegerVT(8 * (LoadedBytes - Offset));
546      SDValue Load = DAG.getExtLoad(ISD::EXTLOAD, dl, RegVT, Chain, Ptr,
547                                    LD->getSrcValue(), SVOffset + Offset,
548                                    MemVT, LD->isVolatile(),
549                                    MinAlign(LD->getAlignment(), Offset));
550      // Follow the load with a store to the stack slot.  Remember the store.
551      // On big-endian machines this requires a truncating store to ensure
552      // that the bits end up in the right place.
553      Stores.push_back(DAG.getTruncStore(Load.getValue(1), dl, Load, StackPtr,
554                                         NULL, 0, MemVT));
555
556      // The order of the stores doesn't matter - say it with a TokenFactor.
557      SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, &Stores[0],
558                               Stores.size());
559
560      // Finally, perform the original load only redirected to the stack slot.
561      Load = DAG.getExtLoad(LD->getExtensionType(), dl, VT, TF, StackBase,
562                            NULL, 0, LoadedVT);
563
564      // Callers expect a MERGE_VALUES node.
565      SDValue Ops[] = { Load, TF };
566      return DAG.getMergeValues(Ops, 2, dl);
567    }
568  }
569  assert(LoadedVT.isInteger() && !LoadedVT.isVector() &&
570         "Unaligned load of unsupported type.");
571
572  // Compute the new VT that is half the size of the old one.  This is an
573  // integer MVT.
574  unsigned NumBits = LoadedVT.getSizeInBits();
575  MVT NewLoadedVT;
576  NewLoadedVT = MVT::getIntegerVT(NumBits/2);
577  NumBits >>= 1;
578
579  unsigned Alignment = LD->getAlignment();
580  unsigned IncrementSize = NumBits / 8;
581  ISD::LoadExtType HiExtType = LD->getExtensionType();
582
583  // If the original load is NON_EXTLOAD, the hi part load must be ZEXTLOAD.
584  if (HiExtType == ISD::NON_EXTLOAD)
585    HiExtType = ISD::ZEXTLOAD;
586
587  // Load the value in two parts
588  SDValue Lo, Hi;
589  if (TLI.isLittleEndian()) {
590    Lo = DAG.getExtLoad(ISD::ZEXTLOAD, dl, VT, Chain, Ptr, LD->getSrcValue(),
591                        SVOffset, NewLoadedVT, LD->isVolatile(), Alignment);
592    Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr,
593                      DAG.getConstant(IncrementSize, TLI.getPointerTy()));
594    Hi = DAG.getExtLoad(HiExtType, dl, VT, Chain, Ptr, LD->getSrcValue(),
595                        SVOffset + IncrementSize, NewLoadedVT, LD->isVolatile(),
596                        MinAlign(Alignment, IncrementSize));
597  } else {
598    Hi = DAG.getExtLoad(HiExtType, dl, VT, Chain, Ptr, LD->getSrcValue(),
599                        SVOffset, NewLoadedVT, LD->isVolatile(), Alignment);
600    Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr,
601                      DAG.getConstant(IncrementSize, TLI.getPointerTy()));
602    Lo = DAG.getExtLoad(ISD::ZEXTLOAD, dl, VT, Chain, Ptr, LD->getSrcValue(),
603                        SVOffset + IncrementSize, NewLoadedVT, LD->isVolatile(),
604                        MinAlign(Alignment, IncrementSize));
605  }
606
607  // aggregate the two parts
608  SDValue ShiftAmount = DAG.getConstant(NumBits, TLI.getShiftAmountTy());
609  SDValue Result = DAG.getNode(ISD::SHL, dl, VT, Hi, ShiftAmount);
610  Result = DAG.getNode(ISD::OR, dl, VT, Result, Lo);
611
612  SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Lo.getValue(1),
613                             Hi.getValue(1));
614
615  SDValue Ops[] = { Result, TF };
616  return DAG.getMergeValues(Ops, 2, dl);
617}
618
619/// PerformInsertVectorEltInMemory - Some target cannot handle a variable
620/// insertion index for the INSERT_VECTOR_ELT instruction.  In this case, it
621/// is necessary to spill the vector being inserted into to memory, perform
622/// the insert there, and then read the result back.
623SDValue SelectionDAGLegalize::
624PerformInsertVectorEltInMemory(SDValue Vec, SDValue Val, SDValue Idx,
625                               DebugLoc dl) {
626  SDValue Tmp1 = Vec;
627  SDValue Tmp2 = Val;
628  SDValue Tmp3 = Idx;
629
630  // If the target doesn't support this, we have to spill the input vector
631  // to a temporary stack slot, update the element, then reload it.  This is
632  // badness.  We could also load the value into a vector register (either
633  // with a "move to register" or "extload into register" instruction, then
634  // permute it into place, if the idx is a constant and if the idx is
635  // supported by the target.
636  MVT VT    = Tmp1.getValueType();
637  MVT EltVT = VT.getVectorElementType();
638  MVT IdxVT = Tmp3.getValueType();
639  MVT PtrVT = TLI.getPointerTy();
640  SDValue StackPtr = DAG.CreateStackTemporary(VT);
641
642  int SPFI = cast<FrameIndexSDNode>(StackPtr.getNode())->getIndex();
643
644  // Store the vector.
645  SDValue Ch = DAG.getStore(DAG.getEntryNode(), dl, Tmp1, StackPtr,
646                            PseudoSourceValue::getFixedStack(SPFI), 0);
647
648  // Truncate or zero extend offset to target pointer type.
649  unsigned CastOpc = IdxVT.bitsGT(PtrVT) ? ISD::TRUNCATE : ISD::ZERO_EXTEND;
650  Tmp3 = DAG.getNode(CastOpc, dl, PtrVT, Tmp3);
651  // Add the offset to the index.
652  unsigned EltSize = EltVT.getSizeInBits()/8;
653  Tmp3 = DAG.getNode(ISD::MUL, dl, IdxVT, Tmp3,DAG.getConstant(EltSize, IdxVT));
654  SDValue StackPtr2 = DAG.getNode(ISD::ADD, dl, IdxVT, Tmp3, StackPtr);
655  // Store the scalar value.
656  Ch = DAG.getTruncStore(Ch, dl, Tmp2, StackPtr2,
657                         PseudoSourceValue::getFixedStack(SPFI), 0, EltVT);
658  // Load the updated vector.
659  return DAG.getLoad(VT, dl, Ch, StackPtr,
660                     PseudoSourceValue::getFixedStack(SPFI), 0);
661}
662
663
664SDValue SelectionDAGLegalize::
665ExpandINSERT_VECTOR_ELT(SDValue Vec, SDValue Val, SDValue Idx, DebugLoc dl) {
666  if (ConstantSDNode *InsertPos = dyn_cast<ConstantSDNode>(Idx)) {
667    // SCALAR_TO_VECTOR requires that the type of the value being inserted
668    // match the element type of the vector being created, except for
669    // integers in which case the inserted value can be over width.
670    MVT EltVT = Vec.getValueType().getVectorElementType();
671    if (Val.getValueType() == EltVT ||
672        (EltVT.isInteger() && Val.getValueType().bitsGE(EltVT))) {
673      SDValue ScVec = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
674                                  Vec.getValueType(), Val);
675
676      unsigned NumElts = Vec.getValueType().getVectorNumElements();
677      // We generate a shuffle of InVec and ScVec, so the shuffle mask
678      // should be 0,1,2,3,4,5... with the appropriate element replaced with
679      // elt 0 of the RHS.
680      SmallVector<int, 8> ShufOps;
681      for (unsigned i = 0; i != NumElts; ++i)
682        ShufOps.push_back(i != InsertPos->getZExtValue() ? i : NumElts);
683
684      return DAG.getVectorShuffle(Vec.getValueType(), dl, Vec, ScVec,
685                                  &ShufOps[0]);
686    }
687  }
688  return PerformInsertVectorEltInMemory(Vec, Val, Idx, dl);
689}
690
691/// LegalizeOp - We know that the specified value has a legal type, and
692/// that its operands are legal.  Now ensure that the operation itself
693/// is legal, recursively ensuring that the operands' operations remain
694/// legal.
695SDValue SelectionDAGLegalize::LegalizeOp(SDValue Op) {
696  if (Op.getOpcode() == ISD::TargetConstant) // Allow illegal target nodes.
697    return Op;
698
699  SDNode *Node = Op.getNode();
700  DebugLoc dl = Node->getDebugLoc();
701
702  for (unsigned i = 0, e = Node->getNumValues(); i != e; ++i)
703    assert(getTypeAction(Node->getValueType(i)) == Legal &&
704           "Unexpected illegal type!");
705
706  for (unsigned i = 0, e = Node->getNumOperands(); i != e; ++i)
707    assert((isTypeLegal(Node->getOperand(i).getValueType()) ||
708            Node->getOperand(i).getOpcode() == ISD::TargetConstant) &&
709           "Unexpected illegal type!");
710
711  // Note that LegalizeOp may be reentered even from single-use nodes, which
712  // means that we always must cache transformed nodes.
713  DenseMap<SDValue, SDValue>::iterator I = LegalizedNodes.find(Op);
714  if (I != LegalizedNodes.end()) return I->second;
715
716  SDValue Tmp1, Tmp2, Tmp3, Tmp4;
717  SDValue Result = Op;
718  bool isCustom = false;
719
720  // Figure out the correct action; the way to query this varies by opcode
721  TargetLowering::LegalizeAction Action;
722  bool SimpleFinishLegalizing = true;
723  switch (Node->getOpcode()) {
724  case ISD::INTRINSIC_W_CHAIN:
725  case ISD::INTRINSIC_WO_CHAIN:
726  case ISD::INTRINSIC_VOID:
727  case ISD::VAARG:
728  case ISD::STACKSAVE:
729    Action = TLI.getOperationAction(Node->getOpcode(), MVT::Other);
730    break;
731  case ISD::SINT_TO_FP:
732  case ISD::UINT_TO_FP:
733  case ISD::EXTRACT_VECTOR_ELT:
734    Action = TLI.getOperationAction(Node->getOpcode(),
735                                    Node->getOperand(0).getValueType());
736    break;
737  case ISD::FP_ROUND_INREG:
738  case ISD::SIGN_EXTEND_INREG: {
739    MVT InnerType = cast<VTSDNode>(Node->getOperand(1))->getVT();
740    Action = TLI.getOperationAction(Node->getOpcode(), InnerType);
741    break;
742  }
743  case ISD::SELECT_CC:
744  case ISD::SETCC:
745  case ISD::BR_CC: {
746    unsigned CCOperand = Node->getOpcode() == ISD::SELECT_CC ? 4 :
747                         Node->getOpcode() == ISD::SETCC ? 2 : 1;
748    unsigned CompareOperand = Node->getOpcode() == ISD::BR_CC ? 2 : 0;
749    MVT OpVT = Node->getOperand(CompareOperand).getValueType();
750    ISD::CondCode CCCode =
751        cast<CondCodeSDNode>(Node->getOperand(CCOperand))->get();
752    Action = TLI.getCondCodeAction(CCCode, OpVT);
753    if (Action == TargetLowering::Legal) {
754      if (Node->getOpcode() == ISD::SELECT_CC)
755        Action = TLI.getOperationAction(Node->getOpcode(),
756                                        Node->getValueType(0));
757      else
758        Action = TLI.getOperationAction(Node->getOpcode(), OpVT);
759    }
760    break;
761  }
762  case ISD::LOAD:
763  case ISD::STORE:
764    // FIXME: Model these properly.  LOAD and STORE are complicated, and
765    // STORE expects the unlegalized operand in some cases.
766    SimpleFinishLegalizing = false;
767    break;
768  case ISD::CALLSEQ_START:
769  case ISD::CALLSEQ_END:
770    // FIXME: This shouldn't be necessary.  These nodes have special properties
771    // dealing with the recursive nature of legalization.  Removing this
772    // special case should be done as part of making LegalizeDAG non-recursive.
773    SimpleFinishLegalizing = false;
774    break;
775  case ISD::CALL:
776    // FIXME: Legalization for calls requires custom-lowering the call before
777    // legalizing the operands!  (I haven't looked into precisely why.)
778    SimpleFinishLegalizing = false;
779    break;
780  case ISD::EXTRACT_ELEMENT:
781  case ISD::FLT_ROUNDS_:
782  case ISD::SADDO:
783  case ISD::SSUBO:
784  case ISD::UADDO:
785  case ISD::USUBO:
786  case ISD::SMULO:
787  case ISD::UMULO:
788  case ISD::FPOWI:
789  case ISD::MERGE_VALUES:
790  case ISD::EH_RETURN:
791  case ISD::FRAME_TO_ARGS_OFFSET:
792    // These operations lie about being legal: when they claim to be legal,
793    // they should actually be expanded.
794    Action = TLI.getOperationAction(Node->getOpcode(), Node->getValueType(0));
795    if (Action == TargetLowering::Legal)
796      Action = TargetLowering::Expand;
797    break;
798  case ISD::TRAMPOLINE:
799  case ISD::FRAMEADDR:
800  case ISD::RETURNADDR:
801  case ISD::FORMAL_ARGUMENTS:
802    // These operations lie about being legal: when they claim to be legal,
803    // they should actually be custom-lowered.
804    Action = TLI.getOperationAction(Node->getOpcode(), Node->getValueType(0));
805    if (Action == TargetLowering::Legal)
806      Action = TargetLowering::Custom;
807    break;
808  case ISD::BUILD_VECTOR:
809    // A weird case: legalization for BUILD_VECTOR never legalizes the
810    // operands!
811    // FIXME: This really sucks... changing it isn't semantically incorrect,
812    // but it massively pessimizes the code for floating-point BUILD_VECTORs
813    // because ConstantFP operands get legalized into constant pool loads
814    // before the BUILD_VECTOR code can see them.  It doesn't usually bite,
815    // though, because BUILD_VECTORS usually get lowered into other nodes
816    // which get legalized properly.
817    SimpleFinishLegalizing = false;
818    break;
819  default:
820    if (Node->getOpcode() >= ISD::BUILTIN_OP_END) {
821      Action = TargetLowering::Legal;
822    } else {
823      Action = TLI.getOperationAction(Node->getOpcode(), Node->getValueType(0));
824    }
825    break;
826  }
827
828  if (SimpleFinishLegalizing) {
829    SmallVector<SDValue, 8> Ops, ResultVals;
830    for (unsigned i = 0, e = Node->getNumOperands(); i != e; ++i)
831      Ops.push_back(LegalizeOp(Node->getOperand(i)));
832    switch (Node->getOpcode()) {
833    default: break;
834    case ISD::BR:
835    case ISD::BRIND:
836    case ISD::BR_JT:
837    case ISD::BR_CC:
838    case ISD::BRCOND:
839    case ISD::RET:
840      // Branches tweak the chain to include LastCALLSEQ_END
841      Ops[0] = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Ops[0],
842                            LastCALLSEQ_END);
843      Ops[0] = LegalizeOp(Ops[0]);
844      LastCALLSEQ_END = DAG.getEntryNode();
845      break;
846    case ISD::SHL:
847    case ISD::SRL:
848    case ISD::SRA:
849    case ISD::ROTL:
850    case ISD::ROTR:
851      // Legalizing shifts/rotates requires adjusting the shift amount
852      // to the appropriate width.
853      if (!Ops[1].getValueType().isVector())
854        Ops[1] = LegalizeOp(DAG.getShiftAmountOperand(Ops[1]));
855      break;
856    }
857
858    Result = DAG.UpdateNodeOperands(Result.getValue(0), Ops.data(),
859                                    Ops.size());
860    switch (Action) {
861    case TargetLowering::Legal:
862      for (unsigned i = 0, e = Node->getNumValues(); i != e; ++i)
863        ResultVals.push_back(Result.getValue(i));
864      break;
865    case TargetLowering::Custom:
866      // FIXME: The handling for custom lowering with multiple results is
867      // a complete mess.
868      Tmp1 = TLI.LowerOperation(Result, DAG);
869      if (Tmp1.getNode()) {
870        for (unsigned i = 0, e = Node->getNumValues(); i != e; ++i) {
871          if (e == 1)
872            ResultVals.push_back(Tmp1);
873          else
874            ResultVals.push_back(Tmp1.getValue(i));
875        }
876        break;
877      }
878
879      // FALL THROUGH
880    case TargetLowering::Expand:
881      ExpandNode(Result.getNode(), ResultVals);
882      break;
883    case TargetLowering::Promote:
884      PromoteNode(Result.getNode(), ResultVals);
885      break;
886    }
887    if (!ResultVals.empty()) {
888      for (unsigned i = 0, e = ResultVals.size(); i != e; ++i) {
889        if (ResultVals[i] != SDValue(Node, i))
890          ResultVals[i] = LegalizeOp(ResultVals[i]);
891        AddLegalizedOperand(SDValue(Node, i), ResultVals[i]);
892      }
893      return ResultVals[Op.getResNo()];
894    }
895  }
896
897  switch (Node->getOpcode()) {
898  default:
899#ifndef NDEBUG
900    cerr << "NODE: "; Node->dump(&DAG); cerr << "\n";
901#endif
902    assert(0 && "Do not know how to legalize this operator!");
903    abort();
904  case ISD::CALL:
905    // The only option for this is to custom lower it.
906    Tmp3 = TLI.LowerOperation(Result.getValue(0), DAG);
907    assert(Tmp3.getNode() && "Target didn't custom lower this node!");
908    // A call within a calling sequence must be legalized to something
909    // other than the normal CALLSEQ_END.  Violating this gets Legalize
910    // into an infinite loop.
911    assert ((!IsLegalizingCall ||
912             Node->getOpcode() != ISD::CALL ||
913             Tmp3.getNode()->getOpcode() != ISD::CALLSEQ_END) &&
914            "Nested CALLSEQ_START..CALLSEQ_END not supported.");
915
916    // The number of incoming and outgoing values should match; unless the final
917    // outgoing value is a flag.
918    assert((Tmp3.getNode()->getNumValues() == Result.getNode()->getNumValues() ||
919            (Tmp3.getNode()->getNumValues() == Result.getNode()->getNumValues() + 1 &&
920             Tmp3.getNode()->getValueType(Tmp3.getNode()->getNumValues() - 1) ==
921               MVT::Flag)) &&
922           "Lowering call/formal_arguments produced unexpected # results!");
923
924    // Since CALL/FORMAL_ARGUMENTS nodes produce multiple values, make sure to
925    // remember that we legalized all of them, so it doesn't get relegalized.
926    for (unsigned i = 0, e = Tmp3.getNode()->getNumValues(); i != e; ++i) {
927      if (Tmp3.getNode()->getValueType(i) == MVT::Flag)
928        continue;
929      Tmp1 = LegalizeOp(Tmp3.getValue(i));
930      if (Op.getResNo() == i)
931        Tmp2 = Tmp1;
932      AddLegalizedOperand(SDValue(Node, i), Tmp1);
933    }
934    return Tmp2;
935  case ISD::BUILD_VECTOR:
936    switch (TLI.getOperationAction(ISD::BUILD_VECTOR, Node->getValueType(0))) {
937    default: assert(0 && "This action is not supported yet!");
938    case TargetLowering::Custom:
939      Tmp3 = TLI.LowerOperation(Result, DAG);
940      if (Tmp3.getNode()) {
941        Result = Tmp3;
942        break;
943      }
944      // FALLTHROUGH
945    case TargetLowering::Expand:
946      Result = ExpandBUILD_VECTOR(Result.getNode());
947      break;
948    }
949    break;
950  case ISD::CALLSEQ_START: {
951    SDNode *CallEnd = FindCallEndFromCallStart(Node);
952
953    // Recursively Legalize all of the inputs of the call end that do not lead
954    // to this call start.  This ensures that any libcalls that need be inserted
955    // are inserted *before* the CALLSEQ_START.
956    {SmallPtrSet<SDNode*, 32> NodesLeadingTo;
957    for (unsigned i = 0, e = CallEnd->getNumOperands(); i != e; ++i)
958      LegalizeAllNodesNotLeadingTo(CallEnd->getOperand(i).getNode(), Node,
959                                   NodesLeadingTo);
960    }
961
962    // Now that we legalized all of the inputs (which may have inserted
963    // libcalls) create the new CALLSEQ_START node.
964    Tmp1 = LegalizeOp(Node->getOperand(0));  // Legalize the chain.
965
966    // Merge in the last call, to ensure that this call start after the last
967    // call ended.
968    if (LastCALLSEQ_END.getOpcode() != ISD::EntryToken) {
969      Tmp1 = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
970                         Tmp1, LastCALLSEQ_END);
971      Tmp1 = LegalizeOp(Tmp1);
972    }
973
974    // Do not try to legalize the target-specific arguments (#1+).
975    if (Tmp1 != Node->getOperand(0)) {
976      SmallVector<SDValue, 8> Ops(Node->op_begin(), Node->op_end());
977      Ops[0] = Tmp1;
978      Result = DAG.UpdateNodeOperands(Result, &Ops[0], Ops.size());
979    }
980
981    // Remember that the CALLSEQ_START is legalized.
982    AddLegalizedOperand(Op.getValue(0), Result);
983    if (Node->getNumValues() == 2)    // If this has a flag result, remember it.
984      AddLegalizedOperand(Op.getValue(1), Result.getValue(1));
985
986    // Now that the callseq_start and all of the non-call nodes above this call
987    // sequence have been legalized, legalize the call itself.  During this
988    // process, no libcalls can/will be inserted, guaranteeing that no calls
989    // can overlap.
990    assert(!IsLegalizingCall && "Inconsistent sequentialization of calls!");
991    // Note that we are selecting this call!
992    LastCALLSEQ_END = SDValue(CallEnd, 0);
993    IsLegalizingCall = true;
994
995    // Legalize the call, starting from the CALLSEQ_END.
996    LegalizeOp(LastCALLSEQ_END);
997    assert(!IsLegalizingCall && "CALLSEQ_END should have cleared this!");
998    return Result;
999  }
1000  case ISD::CALLSEQ_END:
1001    // If the CALLSEQ_START node hasn't been legalized first, legalize it.  This
1002    // will cause this node to be legalized as well as handling libcalls right.
1003    if (LastCALLSEQ_END.getNode() != Node) {
1004      LegalizeOp(SDValue(FindCallStartFromCallEnd(Node), 0));
1005      DenseMap<SDValue, SDValue>::iterator I = LegalizedNodes.find(Op);
1006      assert(I != LegalizedNodes.end() &&
1007             "Legalizing the call start should have legalized this node!");
1008      return I->second;
1009    }
1010
1011    // Otherwise, the call start has been legalized and everything is going
1012    // according to plan.  Just legalize ourselves normally here.
1013    Tmp1 = LegalizeOp(Node->getOperand(0));  // Legalize the chain.
1014    // Do not try to legalize the target-specific arguments (#1+), except for
1015    // an optional flag input.
1016    if (Node->getOperand(Node->getNumOperands()-1).getValueType() != MVT::Flag){
1017      if (Tmp1 != Node->getOperand(0)) {
1018        SmallVector<SDValue, 8> Ops(Node->op_begin(), Node->op_end());
1019        Ops[0] = Tmp1;
1020        Result = DAG.UpdateNodeOperands(Result, &Ops[0], Ops.size());
1021      }
1022    } else {
1023      Tmp2 = LegalizeOp(Node->getOperand(Node->getNumOperands()-1));
1024      if (Tmp1 != Node->getOperand(0) ||
1025          Tmp2 != Node->getOperand(Node->getNumOperands()-1)) {
1026        SmallVector<SDValue, 8> Ops(Node->op_begin(), Node->op_end());
1027        Ops[0] = Tmp1;
1028        Ops.back() = Tmp2;
1029        Result = DAG.UpdateNodeOperands(Result, &Ops[0], Ops.size());
1030      }
1031    }
1032    assert(IsLegalizingCall && "Call sequence imbalance between start/end?");
1033    // This finishes up call legalization.
1034    IsLegalizingCall = false;
1035
1036    // If the CALLSEQ_END node has a flag, remember that we legalized it.
1037    AddLegalizedOperand(SDValue(Node, 0), Result.getValue(0));
1038    if (Node->getNumValues() == 2)
1039      AddLegalizedOperand(SDValue(Node, 1), Result.getValue(1));
1040    return Result.getValue(Op.getResNo());
1041  case ISD::LOAD: {
1042    LoadSDNode *LD = cast<LoadSDNode>(Node);
1043    Tmp1 = LegalizeOp(LD->getChain());   // Legalize the chain.
1044    Tmp2 = LegalizeOp(LD->getBasePtr()); // Legalize the base pointer.
1045
1046    ISD::LoadExtType ExtType = LD->getExtensionType();
1047    if (ExtType == ISD::NON_EXTLOAD) {
1048      MVT VT = Node->getValueType(0);
1049      Result = DAG.UpdateNodeOperands(Result, Tmp1, Tmp2, LD->getOffset());
1050      Tmp3 = Result.getValue(0);
1051      Tmp4 = Result.getValue(1);
1052
1053      switch (TLI.getOperationAction(Node->getOpcode(), VT)) {
1054      default: assert(0 && "This action is not supported yet!");
1055      case TargetLowering::Legal:
1056        // If this is an unaligned load and the target doesn't support it,
1057        // expand it.
1058        if (!TLI.allowsUnalignedMemoryAccesses()) {
1059          unsigned ABIAlignment = TLI.getTargetData()->
1060            getABITypeAlignment(LD->getMemoryVT().getTypeForMVT());
1061          if (LD->getAlignment() < ABIAlignment){
1062            Result = ExpandUnalignedLoad(cast<LoadSDNode>(Result.getNode()), DAG,
1063                                         TLI);
1064            Tmp3 = Result.getOperand(0);
1065            Tmp4 = Result.getOperand(1);
1066            Tmp3 = LegalizeOp(Tmp3);
1067            Tmp4 = LegalizeOp(Tmp4);
1068          }
1069        }
1070        break;
1071      case TargetLowering::Custom:
1072        Tmp1 = TLI.LowerOperation(Tmp3, DAG);
1073        if (Tmp1.getNode()) {
1074          Tmp3 = LegalizeOp(Tmp1);
1075          Tmp4 = LegalizeOp(Tmp1.getValue(1));
1076        }
1077        break;
1078      case TargetLowering::Promote: {
1079        // Only promote a load of vector type to another.
1080        assert(VT.isVector() && "Cannot promote this load!");
1081        // Change base type to a different vector type.
1082        MVT NVT = TLI.getTypeToPromoteTo(Node->getOpcode(), VT);
1083
1084        Tmp1 = DAG.getLoad(NVT, dl, Tmp1, Tmp2, LD->getSrcValue(),
1085                           LD->getSrcValueOffset(),
1086                           LD->isVolatile(), LD->getAlignment());
1087        Tmp3 = LegalizeOp(DAG.getNode(ISD::BIT_CONVERT, dl, VT, Tmp1));
1088        Tmp4 = LegalizeOp(Tmp1.getValue(1));
1089        break;
1090      }
1091      }
1092      // Since loads produce two values, make sure to remember that we
1093      // legalized both of them.
1094      AddLegalizedOperand(SDValue(Node, 0), Tmp3);
1095      AddLegalizedOperand(SDValue(Node, 1), Tmp4);
1096      return Op.getResNo() ? Tmp4 : Tmp3;
1097    } else {
1098      MVT SrcVT = LD->getMemoryVT();
1099      unsigned SrcWidth = SrcVT.getSizeInBits();
1100      int SVOffset = LD->getSrcValueOffset();
1101      unsigned Alignment = LD->getAlignment();
1102      bool isVolatile = LD->isVolatile();
1103
1104      if (SrcWidth != SrcVT.getStoreSizeInBits() &&
1105          // Some targets pretend to have an i1 loading operation, and actually
1106          // load an i8.  This trick is correct for ZEXTLOAD because the top 7
1107          // bits are guaranteed to be zero; it helps the optimizers understand
1108          // that these bits are zero.  It is also useful for EXTLOAD, since it
1109          // tells the optimizers that those bits are undefined.  It would be
1110          // nice to have an effective generic way of getting these benefits...
1111          // Until such a way is found, don't insist on promoting i1 here.
1112          (SrcVT != MVT::i1 ||
1113           TLI.getLoadExtAction(ExtType, MVT::i1) == TargetLowering::Promote)) {
1114        // Promote to a byte-sized load if not loading an integral number of
1115        // bytes.  For example, promote EXTLOAD:i20 -> EXTLOAD:i24.
1116        unsigned NewWidth = SrcVT.getStoreSizeInBits();
1117        MVT NVT = MVT::getIntegerVT(NewWidth);
1118        SDValue Ch;
1119
1120        // The extra bits are guaranteed to be zero, since we stored them that
1121        // way.  A zext load from NVT thus automatically gives zext from SrcVT.
1122
1123        ISD::LoadExtType NewExtType =
1124          ExtType == ISD::ZEXTLOAD ? ISD::ZEXTLOAD : ISD::EXTLOAD;
1125
1126        Result = DAG.getExtLoad(NewExtType, dl, Node->getValueType(0),
1127                                Tmp1, Tmp2, LD->getSrcValue(), SVOffset,
1128                                NVT, isVolatile, Alignment);
1129
1130        Ch = Result.getValue(1); // The chain.
1131
1132        if (ExtType == ISD::SEXTLOAD)
1133          // Having the top bits zero doesn't help when sign extending.
1134          Result = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl,
1135                               Result.getValueType(),
1136                               Result, DAG.getValueType(SrcVT));
1137        else if (ExtType == ISD::ZEXTLOAD || NVT == Result.getValueType())
1138          // All the top bits are guaranteed to be zero - inform the optimizers.
1139          Result = DAG.getNode(ISD::AssertZext, dl,
1140                               Result.getValueType(), Result,
1141                               DAG.getValueType(SrcVT));
1142
1143        Tmp1 = LegalizeOp(Result);
1144        Tmp2 = LegalizeOp(Ch);
1145      } else if (SrcWidth & (SrcWidth - 1)) {
1146        // If not loading a power-of-2 number of bits, expand as two loads.
1147        assert(SrcVT.isExtended() && !SrcVT.isVector() &&
1148               "Unsupported extload!");
1149        unsigned RoundWidth = 1 << Log2_32(SrcWidth);
1150        assert(RoundWidth < SrcWidth);
1151        unsigned ExtraWidth = SrcWidth - RoundWidth;
1152        assert(ExtraWidth < RoundWidth);
1153        assert(!(RoundWidth % 8) && !(ExtraWidth % 8) &&
1154               "Load size not an integral number of bytes!");
1155        MVT RoundVT = MVT::getIntegerVT(RoundWidth);
1156        MVT ExtraVT = MVT::getIntegerVT(ExtraWidth);
1157        SDValue Lo, Hi, Ch;
1158        unsigned IncrementSize;
1159
1160        if (TLI.isLittleEndian()) {
1161          // EXTLOAD:i24 -> ZEXTLOAD:i16 | (shl EXTLOAD@+2:i8, 16)
1162          // Load the bottom RoundWidth bits.
1163          Lo = DAG.getExtLoad(ISD::ZEXTLOAD, dl,
1164                              Node->getValueType(0), Tmp1, Tmp2,
1165                              LD->getSrcValue(), SVOffset, RoundVT, isVolatile,
1166                              Alignment);
1167
1168          // Load the remaining ExtraWidth bits.
1169          IncrementSize = RoundWidth / 8;
1170          Tmp2 = DAG.getNode(ISD::ADD, dl, Tmp2.getValueType(), Tmp2,
1171                             DAG.getIntPtrConstant(IncrementSize));
1172          Hi = DAG.getExtLoad(ExtType, dl, Node->getValueType(0), Tmp1, Tmp2,
1173                              LD->getSrcValue(), SVOffset + IncrementSize,
1174                              ExtraVT, isVolatile,
1175                              MinAlign(Alignment, IncrementSize));
1176
1177          // Build a factor node to remember that this load is independent of the
1178          // other one.
1179          Ch = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Lo.getValue(1),
1180                           Hi.getValue(1));
1181
1182          // Move the top bits to the right place.
1183          Hi = DAG.getNode(ISD::SHL, dl, Hi.getValueType(), Hi,
1184                           DAG.getConstant(RoundWidth, TLI.getShiftAmountTy()));
1185
1186          // Join the hi and lo parts.
1187          Result = DAG.getNode(ISD::OR, dl, Node->getValueType(0), Lo, Hi);
1188        } else {
1189          // Big endian - avoid unaligned loads.
1190          // EXTLOAD:i24 -> (shl EXTLOAD:i16, 8) | ZEXTLOAD@+2:i8
1191          // Load the top RoundWidth bits.
1192          Hi = DAG.getExtLoad(ExtType, dl, Node->getValueType(0), Tmp1, Tmp2,
1193                              LD->getSrcValue(), SVOffset, RoundVT, isVolatile,
1194                              Alignment);
1195
1196          // Load the remaining ExtraWidth bits.
1197          IncrementSize = RoundWidth / 8;
1198          Tmp2 = DAG.getNode(ISD::ADD, dl, Tmp2.getValueType(), Tmp2,
1199                             DAG.getIntPtrConstant(IncrementSize));
1200          Lo = DAG.getExtLoad(ISD::ZEXTLOAD, dl,
1201                              Node->getValueType(0), Tmp1, Tmp2,
1202                              LD->getSrcValue(), SVOffset + IncrementSize,
1203                              ExtraVT, isVolatile,
1204                              MinAlign(Alignment, IncrementSize));
1205
1206          // Build a factor node to remember that this load is independent of the
1207          // other one.
1208          Ch = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Lo.getValue(1),
1209                           Hi.getValue(1));
1210
1211          // Move the top bits to the right place.
1212          Hi = DAG.getNode(ISD::SHL, dl, Hi.getValueType(), Hi,
1213                           DAG.getConstant(ExtraWidth, TLI.getShiftAmountTy()));
1214
1215          // Join the hi and lo parts.
1216          Result = DAG.getNode(ISD::OR, dl, Node->getValueType(0), Lo, Hi);
1217        }
1218
1219        Tmp1 = LegalizeOp(Result);
1220        Tmp2 = LegalizeOp(Ch);
1221      } else {
1222        switch (TLI.getLoadExtAction(ExtType, SrcVT)) {
1223        default: assert(0 && "This action is not supported yet!");
1224        case TargetLowering::Custom:
1225          isCustom = true;
1226          // FALLTHROUGH
1227        case TargetLowering::Legal:
1228          Result = DAG.UpdateNodeOperands(Result, Tmp1, Tmp2, LD->getOffset());
1229          Tmp1 = Result.getValue(0);
1230          Tmp2 = Result.getValue(1);
1231
1232          if (isCustom) {
1233            Tmp3 = TLI.LowerOperation(Result, DAG);
1234            if (Tmp3.getNode()) {
1235              Tmp1 = LegalizeOp(Tmp3);
1236              Tmp2 = LegalizeOp(Tmp3.getValue(1));
1237            }
1238          } else {
1239            // If this is an unaligned load and the target doesn't support it,
1240            // expand it.
1241            if (!TLI.allowsUnalignedMemoryAccesses()) {
1242              unsigned ABIAlignment = TLI.getTargetData()->
1243                getABITypeAlignment(LD->getMemoryVT().getTypeForMVT());
1244              if (LD->getAlignment() < ABIAlignment){
1245                Result = ExpandUnalignedLoad(cast<LoadSDNode>(Result.getNode()), DAG,
1246                                             TLI);
1247                Tmp1 = Result.getOperand(0);
1248                Tmp2 = Result.getOperand(1);
1249                Tmp1 = LegalizeOp(Tmp1);
1250                Tmp2 = LegalizeOp(Tmp2);
1251              }
1252            }
1253          }
1254          break;
1255        case TargetLowering::Expand:
1256          // f64 = EXTLOAD f32 should expand to LOAD, FP_EXTEND
1257          if (SrcVT == MVT::f32 && Node->getValueType(0) == MVT::f64) {
1258            SDValue Load = DAG.getLoad(SrcVT, dl, Tmp1, Tmp2, LD->getSrcValue(),
1259                                         LD->getSrcValueOffset(),
1260                                         LD->isVolatile(), LD->getAlignment());
1261            Result = DAG.getNode(ISD::FP_EXTEND, dl,
1262                                 Node->getValueType(0), Load);
1263            Tmp1 = LegalizeOp(Result);  // Relegalize new nodes.
1264            Tmp2 = LegalizeOp(Load.getValue(1));
1265            break;
1266          }
1267          assert(ExtType != ISD::EXTLOAD &&"EXTLOAD should always be supported!");
1268          // Turn the unsupported load into an EXTLOAD followed by an explicit
1269          // zero/sign extend inreg.
1270          Result = DAG.getExtLoad(ISD::EXTLOAD, dl, Node->getValueType(0),
1271                                  Tmp1, Tmp2, LD->getSrcValue(),
1272                                  LD->getSrcValueOffset(), SrcVT,
1273                                  LD->isVolatile(), LD->getAlignment());
1274          SDValue ValRes;
1275          if (ExtType == ISD::SEXTLOAD)
1276            ValRes = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl,
1277                                 Result.getValueType(),
1278                                 Result, DAG.getValueType(SrcVT));
1279          else
1280            ValRes = DAG.getZeroExtendInReg(Result, dl, SrcVT);
1281          Tmp1 = LegalizeOp(ValRes);  // Relegalize new nodes.
1282          Tmp2 = LegalizeOp(Result.getValue(1));  // Relegalize new nodes.
1283          break;
1284        }
1285      }
1286
1287      // Since loads produce two values, make sure to remember that we legalized
1288      // both of them.
1289      AddLegalizedOperand(SDValue(Node, 0), Tmp1);
1290      AddLegalizedOperand(SDValue(Node, 1), Tmp2);
1291      return Op.getResNo() ? Tmp2 : Tmp1;
1292    }
1293  }
1294  case ISD::STORE: {
1295    StoreSDNode *ST = cast<StoreSDNode>(Node);
1296    Tmp1 = LegalizeOp(ST->getChain());    // Legalize the chain.
1297    Tmp2 = LegalizeOp(ST->getBasePtr());  // Legalize the pointer.
1298    int SVOffset = ST->getSrcValueOffset();
1299    unsigned Alignment = ST->getAlignment();
1300    bool isVolatile = ST->isVolatile();
1301
1302    if (!ST->isTruncatingStore()) {
1303      // Turn 'store float 1.0, Ptr' -> 'store int 0x12345678, Ptr'
1304      // FIXME: We shouldn't do this for TargetConstantFP's.
1305      // FIXME: move this to the DAG Combiner!  Note that we can't regress due
1306      // to phase ordering between legalized code and the dag combiner.  This
1307      // probably means that we need to integrate dag combiner and legalizer
1308      // together.
1309      // We generally can't do this one for long doubles.
1310      if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(ST->getValue())) {
1311        if (CFP->getValueType(0) == MVT::f32 &&
1312            getTypeAction(MVT::i32) == Legal) {
1313          Tmp3 = DAG.getConstant(CFP->getValueAPF().
1314                                          bitcastToAPInt().zextOrTrunc(32),
1315                                  MVT::i32);
1316          Result = DAG.getStore(Tmp1, dl, Tmp3, Tmp2, ST->getSrcValue(),
1317                                SVOffset, isVolatile, Alignment);
1318          break;
1319        } else if (CFP->getValueType(0) == MVT::f64) {
1320          // If this target supports 64-bit registers, do a single 64-bit store.
1321          if (getTypeAction(MVT::i64) == Legal) {
1322            Tmp3 = DAG.getConstant(CFP->getValueAPF().bitcastToAPInt().
1323                                     zextOrTrunc(64), MVT::i64);
1324            Result = DAG.getStore(Tmp1, dl, Tmp3, Tmp2, ST->getSrcValue(),
1325                                  SVOffset, isVolatile, Alignment);
1326            break;
1327          } else if (getTypeAction(MVT::i32) == Legal && !ST->isVolatile()) {
1328            // Otherwise, if the target supports 32-bit registers, use 2 32-bit
1329            // stores.  If the target supports neither 32- nor 64-bits, this
1330            // xform is certainly not worth it.
1331            const APInt &IntVal =CFP->getValueAPF().bitcastToAPInt();
1332            SDValue Lo = DAG.getConstant(APInt(IntVal).trunc(32), MVT::i32);
1333            SDValue Hi = DAG.getConstant(IntVal.lshr(32).trunc(32), MVT::i32);
1334            if (TLI.isBigEndian()) std::swap(Lo, Hi);
1335
1336            Lo = DAG.getStore(Tmp1, dl, Lo, Tmp2, ST->getSrcValue(),
1337                              SVOffset, isVolatile, Alignment);
1338            Tmp2 = DAG.getNode(ISD::ADD, dl, Tmp2.getValueType(), Tmp2,
1339                               DAG.getIntPtrConstant(4));
1340            Hi = DAG.getStore(Tmp1, dl, Hi, Tmp2, ST->getSrcValue(), SVOffset+4,
1341                              isVolatile, MinAlign(Alignment, 4U));
1342
1343            Result = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Lo, Hi);
1344            break;
1345          }
1346        }
1347      }
1348
1349      {
1350        Tmp3 = LegalizeOp(ST->getValue());
1351        Result = DAG.UpdateNodeOperands(Result, Tmp1, Tmp3, Tmp2,
1352                                        ST->getOffset());
1353
1354        MVT VT = Tmp3.getValueType();
1355        switch (TLI.getOperationAction(ISD::STORE, VT)) {
1356        default: assert(0 && "This action is not supported yet!");
1357        case TargetLowering::Legal:
1358          // If this is an unaligned store and the target doesn't support it,
1359          // expand it.
1360          if (!TLI.allowsUnalignedMemoryAccesses()) {
1361            unsigned ABIAlignment = TLI.getTargetData()->
1362              getABITypeAlignment(ST->getMemoryVT().getTypeForMVT());
1363            if (ST->getAlignment() < ABIAlignment)
1364              Result = ExpandUnalignedStore(cast<StoreSDNode>(Result.getNode()), DAG,
1365                                            TLI);
1366          }
1367          break;
1368        case TargetLowering::Custom:
1369          Tmp1 = TLI.LowerOperation(Result, DAG);
1370          if (Tmp1.getNode()) Result = Tmp1;
1371          break;
1372        case TargetLowering::Promote:
1373          assert(VT.isVector() && "Unknown legal promote case!");
1374          Tmp3 = DAG.getNode(ISD::BIT_CONVERT, dl,
1375                             TLI.getTypeToPromoteTo(ISD::STORE, VT), Tmp3);
1376          Result = DAG.getStore(Tmp1, dl, Tmp3, Tmp2,
1377                                ST->getSrcValue(), SVOffset, isVolatile,
1378                                Alignment);
1379          break;
1380        }
1381        break;
1382      }
1383    } else {
1384      Tmp3 = LegalizeOp(ST->getValue());
1385
1386      MVT StVT = ST->getMemoryVT();
1387      unsigned StWidth = StVT.getSizeInBits();
1388
1389      if (StWidth != StVT.getStoreSizeInBits()) {
1390        // Promote to a byte-sized store with upper bits zero if not
1391        // storing an integral number of bytes.  For example, promote
1392        // TRUNCSTORE:i1 X -> TRUNCSTORE:i8 (and X, 1)
1393        MVT NVT = MVT::getIntegerVT(StVT.getStoreSizeInBits());
1394        Tmp3 = DAG.getZeroExtendInReg(Tmp3, dl, StVT);
1395        Result = DAG.getTruncStore(Tmp1, dl, Tmp3, Tmp2, ST->getSrcValue(),
1396                                   SVOffset, NVT, isVolatile, Alignment);
1397      } else if (StWidth & (StWidth - 1)) {
1398        // If not storing a power-of-2 number of bits, expand as two stores.
1399        assert(StVT.isExtended() && !StVT.isVector() &&
1400               "Unsupported truncstore!");
1401        unsigned RoundWidth = 1 << Log2_32(StWidth);
1402        assert(RoundWidth < StWidth);
1403        unsigned ExtraWidth = StWidth - RoundWidth;
1404        assert(ExtraWidth < RoundWidth);
1405        assert(!(RoundWidth % 8) && !(ExtraWidth % 8) &&
1406               "Store size not an integral number of bytes!");
1407        MVT RoundVT = MVT::getIntegerVT(RoundWidth);
1408        MVT ExtraVT = MVT::getIntegerVT(ExtraWidth);
1409        SDValue Lo, Hi;
1410        unsigned IncrementSize;
1411
1412        if (TLI.isLittleEndian()) {
1413          // TRUNCSTORE:i24 X -> TRUNCSTORE:i16 X, TRUNCSTORE@+2:i8 (srl X, 16)
1414          // Store the bottom RoundWidth bits.
1415          Lo = DAG.getTruncStore(Tmp1, dl, Tmp3, Tmp2, ST->getSrcValue(),
1416                                 SVOffset, RoundVT,
1417                                 isVolatile, Alignment);
1418
1419          // Store the remaining ExtraWidth bits.
1420          IncrementSize = RoundWidth / 8;
1421          Tmp2 = DAG.getNode(ISD::ADD, dl, Tmp2.getValueType(), Tmp2,
1422                             DAG.getIntPtrConstant(IncrementSize));
1423          Hi = DAG.getNode(ISD::SRL, dl, Tmp3.getValueType(), Tmp3,
1424                           DAG.getConstant(RoundWidth, TLI.getShiftAmountTy()));
1425          Hi = DAG.getTruncStore(Tmp1, dl, Hi, Tmp2, ST->getSrcValue(),
1426                                 SVOffset + IncrementSize, ExtraVT, isVolatile,
1427                                 MinAlign(Alignment, IncrementSize));
1428        } else {
1429          // Big endian - avoid unaligned stores.
1430          // TRUNCSTORE:i24 X -> TRUNCSTORE:i16 (srl X, 8), TRUNCSTORE@+2:i8 X
1431          // Store the top RoundWidth bits.
1432          Hi = DAG.getNode(ISD::SRL, dl, Tmp3.getValueType(), Tmp3,
1433                           DAG.getConstant(ExtraWidth, TLI.getShiftAmountTy()));
1434          Hi = DAG.getTruncStore(Tmp1, dl, Hi, Tmp2, ST->getSrcValue(),
1435                                 SVOffset, RoundVT, isVolatile, Alignment);
1436
1437          // Store the remaining ExtraWidth bits.
1438          IncrementSize = RoundWidth / 8;
1439          Tmp2 = DAG.getNode(ISD::ADD, dl, Tmp2.getValueType(), Tmp2,
1440                             DAG.getIntPtrConstant(IncrementSize));
1441          Lo = DAG.getTruncStore(Tmp1, dl, Tmp3, Tmp2, ST->getSrcValue(),
1442                                 SVOffset + IncrementSize, ExtraVT, isVolatile,
1443                                 MinAlign(Alignment, IncrementSize));
1444        }
1445
1446        // The order of the stores doesn't matter.
1447        Result = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Lo, Hi);
1448      } else {
1449        if (Tmp1 != ST->getChain() || Tmp3 != ST->getValue() ||
1450            Tmp2 != ST->getBasePtr())
1451          Result = DAG.UpdateNodeOperands(Result, Tmp1, Tmp3, Tmp2,
1452                                          ST->getOffset());
1453
1454        switch (TLI.getTruncStoreAction(ST->getValue().getValueType(), StVT)) {
1455        default: assert(0 && "This action is not supported yet!");
1456        case TargetLowering::Legal:
1457          // If this is an unaligned store and the target doesn't support it,
1458          // expand it.
1459          if (!TLI.allowsUnalignedMemoryAccesses()) {
1460            unsigned ABIAlignment = TLI.getTargetData()->
1461              getABITypeAlignment(ST->getMemoryVT().getTypeForMVT());
1462            if (ST->getAlignment() < ABIAlignment)
1463              Result = ExpandUnalignedStore(cast<StoreSDNode>(Result.getNode()), DAG,
1464                                            TLI);
1465          }
1466          break;
1467        case TargetLowering::Custom:
1468          Result = TLI.LowerOperation(Result, DAG);
1469          break;
1470        case Expand:
1471          // TRUNCSTORE:i16 i32 -> STORE i16
1472          assert(isTypeLegal(StVT) && "Do not know how to expand this store!");
1473          Tmp3 = DAG.getNode(ISD::TRUNCATE, dl, StVT, Tmp3);
1474          Result = DAG.getStore(Tmp1, dl, Tmp3, Tmp2, ST->getSrcValue(),
1475                                SVOffset, isVolatile, Alignment);
1476          break;
1477        }
1478      }
1479    }
1480    break;
1481  }
1482  }
1483  assert(Result.getValueType() == Op.getValueType() &&
1484         "Bad legalization!");
1485
1486  // Make sure that the generated code is itself legal.
1487  if (Result != Op)
1488    Result = LegalizeOp(Result);
1489
1490  // Note that LegalizeOp may be reentered even from single-use nodes, which
1491  // means that we always must cache transformed nodes.
1492  AddLegalizedOperand(Op, Result);
1493  return Result;
1494}
1495
1496SDValue SelectionDAGLegalize::ExpandExtractFromVectorThroughStack(SDValue Op) {
1497  SDValue Vec = Op.getOperand(0);
1498  SDValue Idx = Op.getOperand(1);
1499  DebugLoc dl = Op.getDebugLoc();
1500  // Store the value to a temporary stack slot, then LOAD the returned part.
1501  SDValue StackPtr = DAG.CreateStackTemporary(Vec.getValueType());
1502  SDValue Ch = DAG.getStore(DAG.getEntryNode(), dl, Vec, StackPtr, NULL, 0);
1503
1504  // Add the offset to the index.
1505  unsigned EltSize =
1506      Vec.getValueType().getVectorElementType().getSizeInBits()/8;
1507  Idx = DAG.getNode(ISD::MUL, dl, Idx.getValueType(), Idx,
1508                    DAG.getConstant(EltSize, Idx.getValueType()));
1509
1510  if (Idx.getValueType().bitsGT(TLI.getPointerTy()))
1511    Idx = DAG.getNode(ISD::TRUNCATE, dl, TLI.getPointerTy(), Idx);
1512  else
1513    Idx = DAG.getNode(ISD::ZERO_EXTEND, dl, TLI.getPointerTy(), Idx);
1514
1515  StackPtr = DAG.getNode(ISD::ADD, dl, Idx.getValueType(), Idx, StackPtr);
1516
1517  return DAG.getLoad(Op.getValueType(), dl, Ch, StackPtr, NULL, 0);
1518}
1519
1520SDValue SelectionDAGLegalize::ExpandFCOPYSIGN(SDNode* Node) {
1521  DebugLoc dl = Node->getDebugLoc();
1522  SDValue Tmp1 = Node->getOperand(0);
1523  SDValue Tmp2 = Node->getOperand(1);
1524  assert((Tmp2.getValueType() == MVT::f32 ||
1525          Tmp2.getValueType() == MVT::f64) &&
1526          "Ugly special-cased code!");
1527  // Get the sign bit of the RHS.
1528  SDValue SignBit;
1529  MVT IVT = Tmp2.getValueType() == MVT::f64 ? MVT::i64 : MVT::i32;
1530  if (isTypeLegal(IVT)) {
1531    SignBit = DAG.getNode(ISD::BIT_CONVERT, dl, IVT, Tmp2);
1532  } else {
1533    assert(isTypeLegal(TLI.getPointerTy()) &&
1534            (TLI.getPointerTy() == MVT::i32 ||
1535            TLI.getPointerTy() == MVT::i64) &&
1536            "Legal type for load?!");
1537    SDValue StackPtr = DAG.CreateStackTemporary(Tmp2.getValueType());
1538    SDValue StorePtr = StackPtr, LoadPtr = StackPtr;
1539    SDValue Ch =
1540        DAG.getStore(DAG.getEntryNode(), dl, Tmp2, StorePtr, NULL, 0);
1541    if (Tmp2.getValueType() == MVT::f64 && TLI.isLittleEndian())
1542      LoadPtr = DAG.getNode(ISD::ADD, dl, StackPtr.getValueType(),
1543                            LoadPtr, DAG.getIntPtrConstant(4));
1544    SignBit = DAG.getExtLoad(ISD::SEXTLOAD, dl, TLI.getPointerTy(),
1545                              Ch, LoadPtr, NULL, 0, MVT::i32);
1546  }
1547  SignBit =
1548      DAG.getSetCC(dl, TLI.getSetCCResultType(SignBit.getValueType()),
1549                    SignBit, DAG.getConstant(0, SignBit.getValueType()),
1550                    ISD::SETLT);
1551  // Get the absolute value of the result.
1552  SDValue AbsVal = DAG.getNode(ISD::FABS, dl, Tmp1.getValueType(), Tmp1);
1553  // Select between the nabs and abs value based on the sign bit of
1554  // the input.
1555  return DAG.getNode(ISD::SELECT, dl, AbsVal.getValueType(), SignBit,
1556                     DAG.getNode(ISD::FNEG, dl, AbsVal.getValueType(), AbsVal),
1557                     AbsVal);
1558}
1559
1560SDValue SelectionDAGLegalize::ExpandDBG_STOPPOINT(SDNode* Node) {
1561  DebugLoc dl = Node->getDebugLoc();
1562  DwarfWriter *DW = DAG.getDwarfWriter();
1563  bool useDEBUG_LOC = TLI.isOperationLegalOrCustom(ISD::DEBUG_LOC,
1564                                                    MVT::Other);
1565  bool useLABEL = TLI.isOperationLegalOrCustom(ISD::DBG_LABEL, MVT::Other);
1566
1567  const DbgStopPointSDNode *DSP = cast<DbgStopPointSDNode>(Node);
1568  GlobalVariable *CU_GV = cast<GlobalVariable>(DSP->getCompileUnit());
1569  if (DW && (useDEBUG_LOC || useLABEL) && !CU_GV->isDeclaration()) {
1570    DICompileUnit CU(cast<GlobalVariable>(DSP->getCompileUnit()));
1571
1572    unsigned Line = DSP->getLine();
1573    unsigned Col = DSP->getColumn();
1574
1575    if (OptLevel == CodeGenOpt::None) {
1576      // A bit self-referential to have DebugLoc on Debug_Loc nodes, but it
1577      // won't hurt anything.
1578      if (useDEBUG_LOC) {
1579        return DAG.getNode(ISD::DEBUG_LOC, dl, MVT::Other, Node->getOperand(0),
1580                           DAG.getConstant(Line, MVT::i32),
1581                           DAG.getConstant(Col, MVT::i32),
1582                           DAG.getSrcValue(CU.getGV()));
1583      } else {
1584        unsigned ID = DW->RecordSourceLine(Line, Col, CU);
1585        return DAG.getLabel(ISD::DBG_LABEL, dl, Node->getOperand(0), ID);
1586      }
1587    }
1588  }
1589  return Node->getOperand(0);
1590}
1591
1592void SelectionDAGLegalize::ExpandDYNAMIC_STACKALLOC(SDNode* Node,
1593                                           SmallVectorImpl<SDValue> &Results) {
1594  unsigned SPReg = TLI.getStackPointerRegisterToSaveRestore();
1595  assert(SPReg && "Target cannot require DYNAMIC_STACKALLOC expansion and"
1596          " not tell us which reg is the stack pointer!");
1597  DebugLoc dl = Node->getDebugLoc();
1598  MVT VT = Node->getValueType(0);
1599  SDValue Tmp1 = SDValue(Node, 0);
1600  SDValue Tmp2 = SDValue(Node, 1);
1601  SDValue Tmp3 = Node->getOperand(2);
1602  SDValue Chain = Tmp1.getOperand(0);
1603
1604  // Chain the dynamic stack allocation so that it doesn't modify the stack
1605  // pointer when other instructions are using the stack.
1606  Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(0, true));
1607
1608  SDValue Size  = Tmp2.getOperand(1);
1609  SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, VT);
1610  Chain = SP.getValue(1);
1611  unsigned Align = cast<ConstantSDNode>(Tmp3)->getZExtValue();
1612  unsigned StackAlign =
1613    TLI.getTargetMachine().getFrameInfo()->getStackAlignment();
1614  if (Align > StackAlign)
1615    SP = DAG.getNode(ISD::AND, dl, VT, SP,
1616                      DAG.getConstant(-(uint64_t)Align, VT));
1617  Tmp1 = DAG.getNode(ISD::SUB, dl, VT, SP, Size);       // Value
1618  Chain = DAG.getCopyToReg(Chain, dl, SPReg, Tmp1);     // Output chain
1619
1620  Tmp2 = DAG.getCALLSEQ_END(Chain,  DAG.getIntPtrConstant(0, true),
1621                            DAG.getIntPtrConstant(0, true), SDValue());
1622
1623  Results.push_back(Tmp1);
1624  Results.push_back(Tmp2);
1625}
1626
1627/// LegalizeSetCCOperands - Attempts to create a legal LHS and RHS for a SETCC
1628/// with condition CC on the current target.  This usually involves legalizing
1629/// or promoting the arguments.  In the case where LHS and RHS must be expanded,
1630/// there may be no choice but to create a new SetCC node to represent the
1631/// legalized value of setcc lhs, rhs.  In this case, the value is returned in
1632/// LHS, and the SDValue returned in RHS has a nil SDNode value.
1633void SelectionDAGLegalize::LegalizeSetCCOperands(SDValue &LHS,
1634                                                 SDValue &RHS,
1635                                                 SDValue &CC,
1636                                                 DebugLoc dl) {
1637  LHS = LegalizeOp(LHS);
1638  RHS = LegalizeOp(RHS);
1639}
1640
1641/// LegalizeSetCCCondCode - Legalize a SETCC with given LHS and RHS and
1642/// condition code CC on the current target. This routine assumes LHS and rHS
1643/// have already been legalized by LegalizeSetCCOperands. It expands SETCC with
1644/// illegal condition code into AND / OR of multiple SETCC values.
1645void SelectionDAGLegalize::LegalizeSetCCCondCode(MVT VT,
1646                                                 SDValue &LHS, SDValue &RHS,
1647                                                 SDValue &CC,
1648                                                 DebugLoc dl) {
1649  MVT OpVT = LHS.getValueType();
1650  ISD::CondCode CCCode = cast<CondCodeSDNode>(CC)->get();
1651  switch (TLI.getCondCodeAction(CCCode, OpVT)) {
1652  default: assert(0 && "Unknown condition code action!");
1653  case TargetLowering::Legal:
1654    // Nothing to do.
1655    break;
1656  case TargetLowering::Expand: {
1657    ISD::CondCode CC1 = ISD::SETCC_INVALID, CC2 = ISD::SETCC_INVALID;
1658    unsigned Opc = 0;
1659    switch (CCCode) {
1660    default: assert(0 && "Don't know how to expand this condition!"); abort();
1661    case ISD::SETOEQ: CC1 = ISD::SETEQ; CC2 = ISD::SETO;  Opc = ISD::AND; break;
1662    case ISD::SETOGT: CC1 = ISD::SETGT; CC2 = ISD::SETO;  Opc = ISD::AND; break;
1663    case ISD::SETOGE: CC1 = ISD::SETGE; CC2 = ISD::SETO;  Opc = ISD::AND; break;
1664    case ISD::SETOLT: CC1 = ISD::SETLT; CC2 = ISD::SETO;  Opc = ISD::AND; break;
1665    case ISD::SETOLE: CC1 = ISD::SETLE; CC2 = ISD::SETO;  Opc = ISD::AND; break;
1666    case ISD::SETONE: CC1 = ISD::SETNE; CC2 = ISD::SETO;  Opc = ISD::AND; break;
1667    case ISD::SETUEQ: CC1 = ISD::SETEQ; CC2 = ISD::SETUO; Opc = ISD::OR;  break;
1668    case ISD::SETUGT: CC1 = ISD::SETGT; CC2 = ISD::SETUO; Opc = ISD::OR;  break;
1669    case ISD::SETUGE: CC1 = ISD::SETGE; CC2 = ISD::SETUO; Opc = ISD::OR;  break;
1670    case ISD::SETULT: CC1 = ISD::SETLT; CC2 = ISD::SETUO; Opc = ISD::OR;  break;
1671    case ISD::SETULE: CC1 = ISD::SETLE; CC2 = ISD::SETUO; Opc = ISD::OR;  break;
1672    case ISD::SETUNE: CC1 = ISD::SETNE; CC2 = ISD::SETUO; Opc = ISD::OR;  break;
1673    // FIXME: Implement more expansions.
1674    }
1675
1676    SDValue SetCC1 = DAG.getSetCC(dl, VT, LHS, RHS, CC1);
1677    SDValue SetCC2 = DAG.getSetCC(dl, VT, LHS, RHS, CC2);
1678    LHS = DAG.getNode(Opc, dl, VT, SetCC1, SetCC2);
1679    RHS = SDValue();
1680    CC  = SDValue();
1681    break;
1682  }
1683  }
1684}
1685
1686/// EmitStackConvert - Emit a store/load combination to the stack.  This stores
1687/// SrcOp to a stack slot of type SlotVT, truncating it if needed.  It then does
1688/// a load from the stack slot to DestVT, extending it if needed.
1689/// The resultant code need not be legal.
1690SDValue SelectionDAGLegalize::EmitStackConvert(SDValue SrcOp,
1691                                               MVT SlotVT,
1692                                               MVT DestVT,
1693                                               DebugLoc dl) {
1694  // Create the stack frame object.
1695  unsigned SrcAlign =
1696    TLI.getTargetData()->getPrefTypeAlignment(SrcOp.getValueType().
1697                                              getTypeForMVT());
1698  SDValue FIPtr = DAG.CreateStackTemporary(SlotVT, SrcAlign);
1699
1700  FrameIndexSDNode *StackPtrFI = cast<FrameIndexSDNode>(FIPtr);
1701  int SPFI = StackPtrFI->getIndex();
1702  const Value *SV = PseudoSourceValue::getFixedStack(SPFI);
1703
1704  unsigned SrcSize = SrcOp.getValueType().getSizeInBits();
1705  unsigned SlotSize = SlotVT.getSizeInBits();
1706  unsigned DestSize = DestVT.getSizeInBits();
1707  unsigned DestAlign =
1708    TLI.getTargetData()->getPrefTypeAlignment(DestVT.getTypeForMVT());
1709
1710  // Emit a store to the stack slot.  Use a truncstore if the input value is
1711  // later than DestVT.
1712  SDValue Store;
1713
1714  if (SrcSize > SlotSize)
1715    Store = DAG.getTruncStore(DAG.getEntryNode(), dl, SrcOp, FIPtr,
1716                              SV, 0, SlotVT, false, SrcAlign);
1717  else {
1718    assert(SrcSize == SlotSize && "Invalid store");
1719    Store = DAG.getStore(DAG.getEntryNode(), dl, SrcOp, FIPtr,
1720                         SV, 0, false, SrcAlign);
1721  }
1722
1723  // Result is a load from the stack slot.
1724  if (SlotSize == DestSize)
1725    return DAG.getLoad(DestVT, dl, Store, FIPtr, SV, 0, false, DestAlign);
1726
1727  assert(SlotSize < DestSize && "Unknown extension!");
1728  return DAG.getExtLoad(ISD::EXTLOAD, dl, DestVT, Store, FIPtr, SV, 0, SlotVT,
1729                        false, DestAlign);
1730}
1731
1732SDValue SelectionDAGLegalize::ExpandSCALAR_TO_VECTOR(SDNode *Node) {
1733  DebugLoc dl = Node->getDebugLoc();
1734  // Create a vector sized/aligned stack slot, store the value to element #0,
1735  // then load the whole vector back out.
1736  SDValue StackPtr = DAG.CreateStackTemporary(Node->getValueType(0));
1737
1738  FrameIndexSDNode *StackPtrFI = cast<FrameIndexSDNode>(StackPtr);
1739  int SPFI = StackPtrFI->getIndex();
1740
1741  SDValue Ch = DAG.getTruncStore(DAG.getEntryNode(), dl, Node->getOperand(0),
1742                                 StackPtr,
1743                                 PseudoSourceValue::getFixedStack(SPFI), 0,
1744                                 Node->getValueType(0).getVectorElementType());
1745  return DAG.getLoad(Node->getValueType(0), dl, Ch, StackPtr,
1746                     PseudoSourceValue::getFixedStack(SPFI), 0);
1747}
1748
1749
1750/// ExpandBUILD_VECTOR - Expand a BUILD_VECTOR node on targets that don't
1751/// support the operation, but do support the resultant vector type.
1752SDValue SelectionDAGLegalize::ExpandBUILD_VECTOR(SDNode *Node) {
1753  unsigned NumElems = Node->getNumOperands();
1754  SDValue SplatValue = Node->getOperand(0);
1755  DebugLoc dl = Node->getDebugLoc();
1756  MVT VT = Node->getValueType(0);
1757  MVT OpVT = SplatValue.getValueType();
1758  MVT EltVT = VT.getVectorElementType();
1759
1760  // If the only non-undef value is the low element, turn this into a
1761  // SCALAR_TO_VECTOR node.  If this is { X, X, X, X }, determine X.
1762  bool isOnlyLowElement = true;
1763
1764  // FIXME: it would be far nicer to change this into map<SDValue,uint64_t>
1765  // and use a bitmask instead of a list of elements.
1766  // FIXME: this doesn't treat <0, u, 0, u> for example, as a splat.
1767  std::map<SDValue, std::vector<unsigned> > Values;
1768  Values[SplatValue].push_back(0);
1769  bool isConstant = true;
1770  if (!isa<ConstantFPSDNode>(SplatValue) && !isa<ConstantSDNode>(SplatValue) &&
1771      SplatValue.getOpcode() != ISD::UNDEF)
1772    isConstant = false;
1773
1774  for (unsigned i = 1; i < NumElems; ++i) {
1775    SDValue V = Node->getOperand(i);
1776    Values[V].push_back(i);
1777    if (V.getOpcode() != ISD::UNDEF)
1778      isOnlyLowElement = false;
1779    if (SplatValue != V)
1780      SplatValue = SDValue(0, 0);
1781
1782    // If this isn't a constant element or an undef, we can't use a constant
1783    // pool load.
1784    if (!isa<ConstantFPSDNode>(V) && !isa<ConstantSDNode>(V) &&
1785        V.getOpcode() != ISD::UNDEF)
1786      isConstant = false;
1787  }
1788
1789  if (isOnlyLowElement) {
1790    // If the low element is an undef too, then this whole things is an undef.
1791    if (Node->getOperand(0).getOpcode() == ISD::UNDEF)
1792      return DAG.getUNDEF(VT);
1793    // Otherwise, turn this into a scalar_to_vector node.
1794    return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Node->getOperand(0));
1795  }
1796
1797  // If all elements are constants, create a load from the constant pool.
1798  if (isConstant) {
1799    std::vector<Constant*> CV;
1800    for (unsigned i = 0, e = NumElems; i != e; ++i) {
1801      if (ConstantFPSDNode *V =
1802          dyn_cast<ConstantFPSDNode>(Node->getOperand(i))) {
1803        CV.push_back(const_cast<ConstantFP *>(V->getConstantFPValue()));
1804      } else if (ConstantSDNode *V =
1805                 dyn_cast<ConstantSDNode>(Node->getOperand(i))) {
1806        CV.push_back(const_cast<ConstantInt *>(V->getConstantIntValue()));
1807      } else {
1808        assert(Node->getOperand(i).getOpcode() == ISD::UNDEF);
1809        const Type *OpNTy = OpVT.getTypeForMVT();
1810        CV.push_back(UndefValue::get(OpNTy));
1811      }
1812    }
1813    Constant *CP = ConstantVector::get(CV);
1814    SDValue CPIdx = DAG.getConstantPool(CP, TLI.getPointerTy());
1815    unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
1816    return DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
1817                       PseudoSourceValue::getConstantPool(), 0,
1818                       false, Alignment);
1819  }
1820
1821  if (SplatValue.getNode()) {   // Splat of one value?
1822    // Build the shuffle constant vector: <0, 0, 0, 0>
1823    SmallVector<int, 8> ZeroVec(NumElems, 0);
1824
1825    // If the target supports VECTOR_SHUFFLE and this shuffle mask, use it.
1826    if (TLI.isShuffleMaskLegal(ZeroVec, Node->getValueType(0))) {
1827      // Get the splatted value into the low element of a vector register.
1828      SDValue LowValVec =
1829        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, SplatValue);
1830
1831      // Return shuffle(LowValVec, undef, <0,0,0,0>)
1832      return DAG.getVectorShuffle(VT, dl, LowValVec, DAG.getUNDEF(VT),
1833                                  &ZeroVec[0]);
1834    }
1835  }
1836
1837  // If there are only two unique elements, we may be able to turn this into a
1838  // vector shuffle.
1839  if (Values.size() == 2) {
1840    // Get the two values in deterministic order.
1841    SDValue Val1 = Node->getOperand(1);
1842    SDValue Val2;
1843    std::map<SDValue, std::vector<unsigned> >::iterator MI = Values.begin();
1844    if (MI->first != Val1)
1845      Val2 = MI->first;
1846    else
1847      Val2 = (++MI)->first;
1848
1849    // If Val1 is an undef, make sure it ends up as Val2, to ensure that our
1850    // vector shuffle has the undef vector on the RHS.
1851    if (Val1.getOpcode() == ISD::UNDEF)
1852      std::swap(Val1, Val2);
1853
1854    // Build the shuffle constant vector: e.g. <0, 4, 0, 4>
1855    SmallVector<int, 8> ShuffleMask(NumElems, -1);
1856
1857    // Set elements of the shuffle mask for Val1.
1858    std::vector<unsigned> &Val1Elts = Values[Val1];
1859    for (unsigned i = 0, e = Val1Elts.size(); i != e; ++i)
1860      ShuffleMask[Val1Elts[i]] = 0;
1861
1862    // Set elements of the shuffle mask for Val2.
1863    std::vector<unsigned> &Val2Elts = Values[Val2];
1864    for (unsigned i = 0, e = Val2Elts.size(); i != e; ++i)
1865      if (Val2.getOpcode() != ISD::UNDEF)
1866        ShuffleMask[Val2Elts[i]] = NumElems;
1867
1868    // If the target supports SCALAR_TO_VECTOR and this shuffle mask, use it.
1869    if (TLI.isOperationLegalOrCustom(ISD::SCALAR_TO_VECTOR, VT) &&
1870        TLI.isShuffleMaskLegal(ShuffleMask, VT)) {
1871      Val1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Val1);
1872      Val2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Val2);
1873      return DAG.getVectorShuffle(VT, dl, Val1, Val2, &ShuffleMask[0]);
1874    }
1875  }
1876
1877  // Otherwise, we can't handle this case efficiently.  Allocate a sufficiently
1878  // aligned object on the stack, store each element into it, then load
1879  // the result as a vector.
1880  // Create the stack frame object.
1881  SDValue FIPtr = DAG.CreateStackTemporary(VT);
1882  int FI = cast<FrameIndexSDNode>(FIPtr.getNode())->getIndex();
1883  const Value *SV = PseudoSourceValue::getFixedStack(FI);
1884
1885  // Emit a store of each element to the stack slot.
1886  SmallVector<SDValue, 8> Stores;
1887  unsigned TypeByteSize = OpVT.getSizeInBits() / 8;
1888  // Store (in the right endianness) the elements to memory.
1889  for (unsigned i = 0, e = Node->getNumOperands(); i != e; ++i) {
1890    // Ignore undef elements.
1891    if (Node->getOperand(i).getOpcode() == ISD::UNDEF) continue;
1892
1893    unsigned Offset = TypeByteSize*i;
1894
1895    SDValue Idx = DAG.getConstant(Offset, FIPtr.getValueType());
1896    Idx = DAG.getNode(ISD::ADD, dl, FIPtr.getValueType(), FIPtr, Idx);
1897
1898    Stores.push_back(DAG.getStore(DAG.getEntryNode(), dl, Node->getOperand(i),
1899                                  Idx, SV, Offset));
1900  }
1901
1902  SDValue StoreChain;
1903  if (!Stores.empty())    // Not all undef elements?
1904    StoreChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
1905                             &Stores[0], Stores.size());
1906  else
1907    StoreChain = DAG.getEntryNode();
1908
1909  // Result is a load from the stack slot.
1910  return DAG.getLoad(VT, dl, StoreChain, FIPtr, SV, 0);
1911}
1912
1913// ExpandLibCall - Expand a node into a call to a libcall.  If the result value
1914// does not fit into a register, return the lo part and set the hi part to the
1915// by-reg argument.  If it does fit into a single register, return the result
1916// and leave the Hi part unset.
1917SDValue SelectionDAGLegalize::ExpandLibCall(RTLIB::Libcall LC, SDNode *Node,
1918                                            bool isSigned) {
1919  assert(!IsLegalizingCall && "Cannot overlap legalization of calls!");
1920  // The input chain to this libcall is the entry node of the function.
1921  // Legalizing the call will automatically add the previous call to the
1922  // dependence.
1923  SDValue InChain = DAG.getEntryNode();
1924
1925  TargetLowering::ArgListTy Args;
1926  TargetLowering::ArgListEntry Entry;
1927  for (unsigned i = 0, e = Node->getNumOperands(); i != e; ++i) {
1928    MVT ArgVT = Node->getOperand(i).getValueType();
1929    const Type *ArgTy = ArgVT.getTypeForMVT();
1930    Entry.Node = Node->getOperand(i); Entry.Ty = ArgTy;
1931    Entry.isSExt = isSigned;
1932    Entry.isZExt = !isSigned;
1933    Args.push_back(Entry);
1934  }
1935  SDValue Callee = DAG.getExternalSymbol(TLI.getLibcallName(LC),
1936                                         TLI.getPointerTy());
1937
1938  // Splice the libcall in wherever FindInputOutputChains tells us to.
1939  const Type *RetTy = Node->getValueType(0).getTypeForMVT();
1940  std::pair<SDValue, SDValue> CallInfo =
1941    TLI.LowerCallTo(InChain, RetTy, isSigned, !isSigned, false, false,
1942                    CallingConv::C, false, Callee, Args, DAG,
1943                    Node->getDebugLoc());
1944
1945  // Legalize the call sequence, starting with the chain.  This will advance
1946  // the LastCALLSEQ_END to the legalized version of the CALLSEQ_END node that
1947  // was added by LowerCallTo (guaranteeing proper serialization of calls).
1948  LegalizeOp(CallInfo.second);
1949  return CallInfo.first;
1950}
1951
1952SDValue SelectionDAGLegalize::ExpandFPLibCall(SDNode* Node,
1953                                              RTLIB::Libcall Call_F32,
1954                                              RTLIB::Libcall Call_F64,
1955                                              RTLIB::Libcall Call_F80,
1956                                              RTLIB::Libcall Call_PPCF128) {
1957  RTLIB::Libcall LC;
1958  switch (Node->getValueType(0).getSimpleVT()) {
1959  default: assert(0 && "Unexpected request for libcall!");
1960  case MVT::f32: LC = Call_F32; break;
1961  case MVT::f64: LC = Call_F64; break;
1962  case MVT::f80: LC = Call_F80; break;
1963  case MVT::ppcf128: LC = Call_PPCF128; break;
1964  }
1965  return ExpandLibCall(LC, Node, false);
1966}
1967
1968SDValue SelectionDAGLegalize::ExpandIntLibCall(SDNode* Node, bool isSigned,
1969                                               RTLIB::Libcall Call_I16,
1970                                               RTLIB::Libcall Call_I32,
1971                                               RTLIB::Libcall Call_I64,
1972                                               RTLIB::Libcall Call_I128) {
1973  RTLIB::Libcall LC;
1974  switch (Node->getValueType(0).getSimpleVT()) {
1975  default: assert(0 && "Unexpected request for libcall!");
1976  case MVT::i16: LC = Call_I16; break;
1977  case MVT::i32: LC = Call_I32; break;
1978  case MVT::i64: LC = Call_I64; break;
1979  case MVT::i128: LC = Call_I128; break;
1980  }
1981  return ExpandLibCall(LC, Node, isSigned);
1982}
1983
1984/// ExpandLegalINT_TO_FP - This function is responsible for legalizing a
1985/// INT_TO_FP operation of the specified operand when the target requests that
1986/// we expand it.  At this point, we know that the result and operand types are
1987/// legal for the target.
1988SDValue SelectionDAGLegalize::ExpandLegalINT_TO_FP(bool isSigned,
1989                                                   SDValue Op0,
1990                                                   MVT DestVT,
1991                                                   DebugLoc dl) {
1992  if (Op0.getValueType() == MVT::i32) {
1993    // simple 32-bit [signed|unsigned] integer to float/double expansion
1994
1995    // Get the stack frame index of a 8 byte buffer.
1996    SDValue StackSlot = DAG.CreateStackTemporary(MVT::f64);
1997
1998    // word offset constant for Hi/Lo address computation
1999    SDValue WordOff = DAG.getConstant(sizeof(int), TLI.getPointerTy());
2000    // set up Hi and Lo (into buffer) address based on endian
2001    SDValue Hi = StackSlot;
2002    SDValue Lo = DAG.getNode(ISD::ADD, dl,
2003                             TLI.getPointerTy(), StackSlot, WordOff);
2004    if (TLI.isLittleEndian())
2005      std::swap(Hi, Lo);
2006
2007    // if signed map to unsigned space
2008    SDValue Op0Mapped;
2009    if (isSigned) {
2010      // constant used to invert sign bit (signed to unsigned mapping)
2011      SDValue SignBit = DAG.getConstant(0x80000000u, MVT::i32);
2012      Op0Mapped = DAG.getNode(ISD::XOR, dl, MVT::i32, Op0, SignBit);
2013    } else {
2014      Op0Mapped = Op0;
2015    }
2016    // store the lo of the constructed double - based on integer input
2017    SDValue Store1 = DAG.getStore(DAG.getEntryNode(), dl,
2018                                  Op0Mapped, Lo, NULL, 0);
2019    // initial hi portion of constructed double
2020    SDValue InitialHi = DAG.getConstant(0x43300000u, MVT::i32);
2021    // store the hi of the constructed double - biased exponent
2022    SDValue Store2=DAG.getStore(Store1, dl, InitialHi, Hi, NULL, 0);
2023    // load the constructed double
2024    SDValue Load = DAG.getLoad(MVT::f64, dl, Store2, StackSlot, NULL, 0);
2025    // FP constant to bias correct the final result
2026    SDValue Bias = DAG.getConstantFP(isSigned ?
2027                                     BitsToDouble(0x4330000080000000ULL) :
2028                                     BitsToDouble(0x4330000000000000ULL),
2029                                     MVT::f64);
2030    // subtract the bias
2031    SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::f64, Load, Bias);
2032    // final result
2033    SDValue Result;
2034    // handle final rounding
2035    if (DestVT == MVT::f64) {
2036      // do nothing
2037      Result = Sub;
2038    } else if (DestVT.bitsLT(MVT::f64)) {
2039      Result = DAG.getNode(ISD::FP_ROUND, dl, DestVT, Sub,
2040                           DAG.getIntPtrConstant(0));
2041    } else if (DestVT.bitsGT(MVT::f64)) {
2042      Result = DAG.getNode(ISD::FP_EXTEND, dl, DestVT, Sub);
2043    }
2044    return Result;
2045  }
2046  assert(!isSigned && "Legalize cannot Expand SINT_TO_FP for i64 yet");
2047  SDValue Tmp1 = DAG.getNode(ISD::SINT_TO_FP, dl, DestVT, Op0);
2048
2049  SDValue SignSet = DAG.getSetCC(dl, TLI.getSetCCResultType(Op0.getValueType()),
2050                                 Op0, DAG.getConstant(0, Op0.getValueType()),
2051                                 ISD::SETLT);
2052  SDValue Zero = DAG.getIntPtrConstant(0), Four = DAG.getIntPtrConstant(4);
2053  SDValue CstOffset = DAG.getNode(ISD::SELECT, dl, Zero.getValueType(),
2054                                    SignSet, Four, Zero);
2055
2056  // If the sign bit of the integer is set, the large number will be treated
2057  // as a negative number.  To counteract this, the dynamic code adds an
2058  // offset depending on the data type.
2059  uint64_t FF;
2060  switch (Op0.getValueType().getSimpleVT()) {
2061  default: assert(0 && "Unsupported integer type!");
2062  case MVT::i8 : FF = 0x43800000ULL; break;  // 2^8  (as a float)
2063  case MVT::i16: FF = 0x47800000ULL; break;  // 2^16 (as a float)
2064  case MVT::i32: FF = 0x4F800000ULL; break;  // 2^32 (as a float)
2065  case MVT::i64: FF = 0x5F800000ULL; break;  // 2^64 (as a float)
2066  }
2067  if (TLI.isLittleEndian()) FF <<= 32;
2068  Constant *FudgeFactor = ConstantInt::get(Type::Int64Ty, FF);
2069
2070  SDValue CPIdx = DAG.getConstantPool(FudgeFactor, TLI.getPointerTy());
2071  unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
2072  CPIdx = DAG.getNode(ISD::ADD, dl, TLI.getPointerTy(), CPIdx, CstOffset);
2073  Alignment = std::min(Alignment, 4u);
2074  SDValue FudgeInReg;
2075  if (DestVT == MVT::f32)
2076    FudgeInReg = DAG.getLoad(MVT::f32, dl, DAG.getEntryNode(), CPIdx,
2077                             PseudoSourceValue::getConstantPool(), 0,
2078                             false, Alignment);
2079  else {
2080    FudgeInReg =
2081      LegalizeOp(DAG.getExtLoad(ISD::EXTLOAD, dl, DestVT,
2082                                DAG.getEntryNode(), CPIdx,
2083                                PseudoSourceValue::getConstantPool(), 0,
2084                                MVT::f32, false, Alignment));
2085  }
2086
2087  return DAG.getNode(ISD::FADD, dl, DestVT, Tmp1, FudgeInReg);
2088}
2089
2090/// PromoteLegalINT_TO_FP - This function is responsible for legalizing a
2091/// *INT_TO_FP operation of the specified operand when the target requests that
2092/// we promote it.  At this point, we know that the result and operand types are
2093/// legal for the target, and that there is a legal UINT_TO_FP or SINT_TO_FP
2094/// operation that takes a larger input.
2095SDValue SelectionDAGLegalize::PromoteLegalINT_TO_FP(SDValue LegalOp,
2096                                                    MVT DestVT,
2097                                                    bool isSigned,
2098                                                    DebugLoc dl) {
2099  // First step, figure out the appropriate *INT_TO_FP operation to use.
2100  MVT NewInTy = LegalOp.getValueType();
2101
2102  unsigned OpToUse = 0;
2103
2104  // Scan for the appropriate larger type to use.
2105  while (1) {
2106    NewInTy = (MVT::SimpleValueType)(NewInTy.getSimpleVT()+1);
2107    assert(NewInTy.isInteger() && "Ran out of possibilities!");
2108
2109    // If the target supports SINT_TO_FP of this type, use it.
2110    if (TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, NewInTy)) {
2111      OpToUse = ISD::SINT_TO_FP;
2112      break;
2113    }
2114    if (isSigned) continue;
2115
2116    // If the target supports UINT_TO_FP of this type, use it.
2117    if (TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, NewInTy)) {
2118      OpToUse = ISD::UINT_TO_FP;
2119      break;
2120    }
2121
2122    // Otherwise, try a larger type.
2123  }
2124
2125  // Okay, we found the operation and type to use.  Zero extend our input to the
2126  // desired type then run the operation on it.
2127  return DAG.getNode(OpToUse, dl, DestVT,
2128                     DAG.getNode(isSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND,
2129                                 dl, NewInTy, LegalOp));
2130}
2131
2132/// PromoteLegalFP_TO_INT - This function is responsible for legalizing a
2133/// FP_TO_*INT operation of the specified operand when the target requests that
2134/// we promote it.  At this point, we know that the result and operand types are
2135/// legal for the target, and that there is a legal FP_TO_UINT or FP_TO_SINT
2136/// operation that returns a larger result.
2137SDValue SelectionDAGLegalize::PromoteLegalFP_TO_INT(SDValue LegalOp,
2138                                                    MVT DestVT,
2139                                                    bool isSigned,
2140                                                    DebugLoc dl) {
2141  // First step, figure out the appropriate FP_TO*INT operation to use.
2142  MVT NewOutTy = DestVT;
2143
2144  unsigned OpToUse = 0;
2145
2146  // Scan for the appropriate larger type to use.
2147  while (1) {
2148    NewOutTy = (MVT::SimpleValueType)(NewOutTy.getSimpleVT()+1);
2149    assert(NewOutTy.isInteger() && "Ran out of possibilities!");
2150
2151    if (TLI.isOperationLegalOrCustom(ISD::FP_TO_SINT, NewOutTy)) {
2152      OpToUse = ISD::FP_TO_SINT;
2153      break;
2154    }
2155
2156    if (TLI.isOperationLegalOrCustom(ISD::FP_TO_UINT, NewOutTy)) {
2157      OpToUse = ISD::FP_TO_UINT;
2158      break;
2159    }
2160
2161    // Otherwise, try a larger type.
2162  }
2163
2164
2165  // Okay, we found the operation and type to use.
2166  SDValue Operation = DAG.getNode(OpToUse, dl, NewOutTy, LegalOp);
2167
2168  // Truncate the result of the extended FP_TO_*INT operation to the desired
2169  // size.
2170  return DAG.getNode(ISD::TRUNCATE, dl, DestVT, Operation);
2171}
2172
2173/// ExpandBSWAP - Open code the operations for BSWAP of the specified operation.
2174///
2175SDValue SelectionDAGLegalize::ExpandBSWAP(SDValue Op, DebugLoc dl) {
2176  MVT VT = Op.getValueType();
2177  MVT SHVT = TLI.getShiftAmountTy();
2178  SDValue Tmp1, Tmp2, Tmp3, Tmp4, Tmp5, Tmp6, Tmp7, Tmp8;
2179  switch (VT.getSimpleVT()) {
2180  default: assert(0 && "Unhandled Expand type in BSWAP!"); abort();
2181  case MVT::i16:
2182    Tmp2 = DAG.getNode(ISD::SHL, dl, VT, Op, DAG.getConstant(8, SHVT));
2183    Tmp1 = DAG.getNode(ISD::SRL, dl, VT, Op, DAG.getConstant(8, SHVT));
2184    return DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2);
2185  case MVT::i32:
2186    Tmp4 = DAG.getNode(ISD::SHL, dl, VT, Op, DAG.getConstant(24, SHVT));
2187    Tmp3 = DAG.getNode(ISD::SHL, dl, VT, Op, DAG.getConstant(8, SHVT));
2188    Tmp2 = DAG.getNode(ISD::SRL, dl, VT, Op, DAG.getConstant(8, SHVT));
2189    Tmp1 = DAG.getNode(ISD::SRL, dl, VT, Op, DAG.getConstant(24, SHVT));
2190    Tmp3 = DAG.getNode(ISD::AND, dl, VT, Tmp3, DAG.getConstant(0xFF0000, VT));
2191    Tmp2 = DAG.getNode(ISD::AND, dl, VT, Tmp2, DAG.getConstant(0xFF00, VT));
2192    Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp3);
2193    Tmp2 = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp1);
2194    return DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp2);
2195  case MVT::i64:
2196    Tmp8 = DAG.getNode(ISD::SHL, dl, VT, Op, DAG.getConstant(56, SHVT));
2197    Tmp7 = DAG.getNode(ISD::SHL, dl, VT, Op, DAG.getConstant(40, SHVT));
2198    Tmp6 = DAG.getNode(ISD::SHL, dl, VT, Op, DAG.getConstant(24, SHVT));
2199    Tmp5 = DAG.getNode(ISD::SHL, dl, VT, Op, DAG.getConstant(8, SHVT));
2200    Tmp4 = DAG.getNode(ISD::SRL, dl, VT, Op, DAG.getConstant(8, SHVT));
2201    Tmp3 = DAG.getNode(ISD::SRL, dl, VT, Op, DAG.getConstant(24, SHVT));
2202    Tmp2 = DAG.getNode(ISD::SRL, dl, VT, Op, DAG.getConstant(40, SHVT));
2203    Tmp1 = DAG.getNode(ISD::SRL, dl, VT, Op, DAG.getConstant(56, SHVT));
2204    Tmp7 = DAG.getNode(ISD::AND, dl, VT, Tmp7, DAG.getConstant(255ULL<<48, VT));
2205    Tmp6 = DAG.getNode(ISD::AND, dl, VT, Tmp6, DAG.getConstant(255ULL<<40, VT));
2206    Tmp5 = DAG.getNode(ISD::AND, dl, VT, Tmp5, DAG.getConstant(255ULL<<32, VT));
2207    Tmp4 = DAG.getNode(ISD::AND, dl, VT, Tmp4, DAG.getConstant(255ULL<<24, VT));
2208    Tmp3 = DAG.getNode(ISD::AND, dl, VT, Tmp3, DAG.getConstant(255ULL<<16, VT));
2209    Tmp2 = DAG.getNode(ISD::AND, dl, VT, Tmp2, DAG.getConstant(255ULL<<8 , VT));
2210    Tmp8 = DAG.getNode(ISD::OR, dl, VT, Tmp8, Tmp7);
2211    Tmp6 = DAG.getNode(ISD::OR, dl, VT, Tmp6, Tmp5);
2212    Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp3);
2213    Tmp2 = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp1);
2214    Tmp8 = DAG.getNode(ISD::OR, dl, VT, Tmp8, Tmp6);
2215    Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp2);
2216    return DAG.getNode(ISD::OR, dl, VT, Tmp8, Tmp4);
2217  }
2218}
2219
2220/// ExpandBitCount - Expand the specified bitcount instruction into operations.
2221///
2222SDValue SelectionDAGLegalize::ExpandBitCount(unsigned Opc, SDValue Op,
2223                                             DebugLoc dl) {
2224  switch (Opc) {
2225  default: assert(0 && "Cannot expand this yet!");
2226  case ISD::CTPOP: {
2227    static const uint64_t mask[6] = {
2228      0x5555555555555555ULL, 0x3333333333333333ULL,
2229      0x0F0F0F0F0F0F0F0FULL, 0x00FF00FF00FF00FFULL,
2230      0x0000FFFF0000FFFFULL, 0x00000000FFFFFFFFULL
2231    };
2232    MVT VT = Op.getValueType();
2233    MVT ShVT = TLI.getShiftAmountTy();
2234    unsigned len = VT.getSizeInBits();
2235    for (unsigned i = 0; (1U << i) <= (len / 2); ++i) {
2236      //x = (x & mask[i][len/8]) + (x >> (1 << i) & mask[i][len/8])
2237      unsigned EltSize = VT.isVector() ?
2238        VT.getVectorElementType().getSizeInBits() : len;
2239      SDValue Tmp2 = DAG.getConstant(APInt(EltSize, mask[i]), VT);
2240      SDValue Tmp3 = DAG.getConstant(1ULL << i, ShVT);
2241      Op = DAG.getNode(ISD::ADD, dl, VT,
2242                       DAG.getNode(ISD::AND, dl, VT, Op, Tmp2),
2243                       DAG.getNode(ISD::AND, dl, VT,
2244                                   DAG.getNode(ISD::SRL, dl, VT, Op, Tmp3),
2245                                   Tmp2));
2246    }
2247    return Op;
2248  }
2249  case ISD::CTLZ: {
2250    // for now, we do this:
2251    // x = x | (x >> 1);
2252    // x = x | (x >> 2);
2253    // ...
2254    // x = x | (x >>16);
2255    // x = x | (x >>32); // for 64-bit input
2256    // return popcount(~x);
2257    //
2258    // but see also: http://www.hackersdelight.org/HDcode/nlz.cc
2259    MVT VT = Op.getValueType();
2260    MVT ShVT = TLI.getShiftAmountTy();
2261    unsigned len = VT.getSizeInBits();
2262    for (unsigned i = 0; (1U << i) <= (len / 2); ++i) {
2263      SDValue Tmp3 = DAG.getConstant(1ULL << i, ShVT);
2264      Op = DAG.getNode(ISD::OR, dl, VT, Op,
2265                       DAG.getNode(ISD::SRL, dl, VT, Op, Tmp3));
2266    }
2267    Op = DAG.getNOT(dl, Op, VT);
2268    return DAG.getNode(ISD::CTPOP, dl, VT, Op);
2269  }
2270  case ISD::CTTZ: {
2271    // for now, we use: { return popcount(~x & (x - 1)); }
2272    // unless the target has ctlz but not ctpop, in which case we use:
2273    // { return 32 - nlz(~x & (x-1)); }
2274    // see also http://www.hackersdelight.org/HDcode/ntz.cc
2275    MVT VT = Op.getValueType();
2276    SDValue Tmp3 = DAG.getNode(ISD::AND, dl, VT,
2277                               DAG.getNOT(dl, Op, VT),
2278                               DAG.getNode(ISD::SUB, dl, VT, Op,
2279                                           DAG.getConstant(1, VT)));
2280    // If ISD::CTLZ is legal and CTPOP isn't, then do that instead.
2281    if (!TLI.isOperationLegalOrCustom(ISD::CTPOP, VT) &&
2282        TLI.isOperationLegalOrCustom(ISD::CTLZ, VT))
2283      return DAG.getNode(ISD::SUB, dl, VT,
2284                         DAG.getConstant(VT.getSizeInBits(), VT),
2285                         DAG.getNode(ISD::CTLZ, dl, VT, Tmp3));
2286    return DAG.getNode(ISD::CTPOP, dl, VT, Tmp3);
2287  }
2288  }
2289}
2290
2291void SelectionDAGLegalize::ExpandNode(SDNode *Node,
2292                                      SmallVectorImpl<SDValue> &Results) {
2293  DebugLoc dl = Node->getDebugLoc();
2294  SDValue Tmp1, Tmp2, Tmp3, Tmp4;
2295  switch (Node->getOpcode()) {
2296  case ISD::CTPOP:
2297  case ISD::CTLZ:
2298  case ISD::CTTZ:
2299    Tmp1 = ExpandBitCount(Node->getOpcode(), Node->getOperand(0), dl);
2300    Results.push_back(Tmp1);
2301    break;
2302  case ISD::BSWAP:
2303    Results.push_back(ExpandBSWAP(Node->getOperand(0), dl));
2304    break;
2305  case ISD::FRAMEADDR:
2306  case ISD::RETURNADDR:
2307  case ISD::FRAME_TO_ARGS_OFFSET:
2308    Results.push_back(DAG.getConstant(0, Node->getValueType(0)));
2309    break;
2310  case ISD::FLT_ROUNDS_:
2311    Results.push_back(DAG.getConstant(1, Node->getValueType(0)));
2312    break;
2313  case ISD::EH_RETURN:
2314  case ISD::DECLARE:
2315  case ISD::DBG_LABEL:
2316  case ISD::EH_LABEL:
2317  case ISD::PREFETCH:
2318  case ISD::MEMBARRIER:
2319  case ISD::VAEND:
2320    Results.push_back(Node->getOperand(0));
2321    break;
2322  case ISD::DBG_STOPPOINT:
2323    Results.push_back(ExpandDBG_STOPPOINT(Node));
2324    break;
2325  case ISD::DYNAMIC_STACKALLOC:
2326    ExpandDYNAMIC_STACKALLOC(Node, Results);
2327    break;
2328  case ISD::MERGE_VALUES:
2329    for (unsigned i = 0; i < Node->getNumValues(); i++)
2330      Results.push_back(Node->getOperand(i));
2331    break;
2332  case ISD::UNDEF: {
2333    MVT VT = Node->getValueType(0);
2334    if (VT.isInteger())
2335      Results.push_back(DAG.getConstant(0, VT));
2336    else if (VT.isFloatingPoint())
2337      Results.push_back(DAG.getConstantFP(0, VT));
2338    else
2339      assert(0 && "Unknown value type!");
2340    break;
2341  }
2342  case ISD::TRAP: {
2343    // If this operation is not supported, lower it to 'abort()' call
2344    TargetLowering::ArgListTy Args;
2345    std::pair<SDValue, SDValue> CallResult =
2346      TLI.LowerCallTo(Node->getOperand(0), Type::VoidTy,
2347                      false, false, false, false, CallingConv::C, false,
2348                      DAG.getExternalSymbol("abort", TLI.getPointerTy()),
2349                      Args, DAG, dl);
2350    Results.push_back(CallResult.second);
2351    break;
2352  }
2353  case ISD::FP_ROUND:
2354  case ISD::BIT_CONVERT:
2355    Tmp1 = EmitStackConvert(Node->getOperand(0), Node->getValueType(0),
2356                            Node->getValueType(0), dl);
2357    Results.push_back(Tmp1);
2358    break;
2359  case ISD::FP_EXTEND:
2360    Tmp1 = EmitStackConvert(Node->getOperand(0),
2361                            Node->getOperand(0).getValueType(),
2362                            Node->getValueType(0), dl);
2363    Results.push_back(Tmp1);
2364    break;
2365  case ISD::SIGN_EXTEND_INREG: {
2366    // NOTE: we could fall back on load/store here too for targets without
2367    // SAR.  However, it is doubtful that any exist.
2368    MVT ExtraVT = cast<VTSDNode>(Node->getOperand(1))->getVT();
2369    unsigned BitsDiff = Node->getValueType(0).getSizeInBits() -
2370                        ExtraVT.getSizeInBits();
2371    SDValue ShiftCst = DAG.getConstant(BitsDiff, TLI.getShiftAmountTy());
2372    Tmp1 = DAG.getNode(ISD::SHL, dl, Node->getValueType(0),
2373                       Node->getOperand(0), ShiftCst);
2374    Tmp1 = DAG.getNode(ISD::SRA, dl, Node->getValueType(0), Tmp1, ShiftCst);
2375    Results.push_back(Tmp1);
2376    break;
2377  }
2378  case ISD::FP_ROUND_INREG: {
2379    // The only way we can lower this is to turn it into a TRUNCSTORE,
2380    // EXTLOAD pair, targetting a temporary location (a stack slot).
2381
2382    // NOTE: there is a choice here between constantly creating new stack
2383    // slots and always reusing the same one.  We currently always create
2384    // new ones, as reuse may inhibit scheduling.
2385    MVT ExtraVT = cast<VTSDNode>(Node->getOperand(1))->getVT();
2386    Tmp1 = EmitStackConvert(Node->getOperand(0), ExtraVT,
2387                            Node->getValueType(0), dl);
2388    Results.push_back(Tmp1);
2389    break;
2390  }
2391  case ISD::SINT_TO_FP:
2392  case ISD::UINT_TO_FP:
2393    Tmp1 = ExpandLegalINT_TO_FP(Node->getOpcode() == ISD::SINT_TO_FP,
2394                                Node->getOperand(0), Node->getValueType(0), dl);
2395    Results.push_back(Tmp1);
2396    break;
2397  case ISD::FP_TO_UINT: {
2398    SDValue True, False;
2399    MVT VT =  Node->getOperand(0).getValueType();
2400    MVT NVT = Node->getValueType(0);
2401    const uint64_t zero[] = {0, 0};
2402    APFloat apf = APFloat(APInt(VT.getSizeInBits(), 2, zero));
2403    APInt x = APInt::getSignBit(NVT.getSizeInBits());
2404    (void)apf.convertFromAPInt(x, false, APFloat::rmNearestTiesToEven);
2405    Tmp1 = DAG.getConstantFP(apf, VT);
2406    Tmp2 = DAG.getSetCC(dl, TLI.getSetCCResultType(VT),
2407                        Node->getOperand(0),
2408                        Tmp1, ISD::SETLT);
2409    True = DAG.getNode(ISD::FP_TO_SINT, dl, NVT, Node->getOperand(0));
2410    False = DAG.getNode(ISD::FP_TO_SINT, dl, NVT,
2411                        DAG.getNode(ISD::FSUB, dl, VT,
2412                                    Node->getOperand(0), Tmp1));
2413    False = DAG.getNode(ISD::XOR, dl, NVT, False,
2414                        DAG.getConstant(x, NVT));
2415    Tmp1 = DAG.getNode(ISD::SELECT, dl, NVT, Tmp2, True, False);
2416    Results.push_back(Tmp1);
2417    break;
2418  }
2419  case ISD::VAARG: {
2420    const Value *V = cast<SrcValueSDNode>(Node->getOperand(2))->getValue();
2421    MVT VT = Node->getValueType(0);
2422    Tmp1 = Node->getOperand(0);
2423    Tmp2 = Node->getOperand(1);
2424    SDValue VAList = DAG.getLoad(TLI.getPointerTy(), dl, Tmp1, Tmp2, V, 0);
2425    // Increment the pointer, VAList, to the next vaarg
2426    Tmp3 = DAG.getNode(ISD::ADD, dl, TLI.getPointerTy(), VAList,
2427                       DAG.getConstant(TLI.getTargetData()->
2428                                       getTypeAllocSize(VT.getTypeForMVT()),
2429                                       TLI.getPointerTy()));
2430    // Store the incremented VAList to the legalized pointer
2431    Tmp3 = DAG.getStore(VAList.getValue(1), dl, Tmp3, Tmp2, V, 0);
2432    // Load the actual argument out of the pointer VAList
2433    Results.push_back(DAG.getLoad(VT, dl, Tmp3, VAList, NULL, 0));
2434    Results.push_back(Results[0].getValue(1));
2435    break;
2436  }
2437  case ISD::VACOPY: {
2438    // This defaults to loading a pointer from the input and storing it to the
2439    // output, returning the chain.
2440    const Value *VD = cast<SrcValueSDNode>(Node->getOperand(3))->getValue();
2441    const Value *VS = cast<SrcValueSDNode>(Node->getOperand(4))->getValue();
2442    Tmp1 = DAG.getLoad(TLI.getPointerTy(), dl, Node->getOperand(0),
2443                       Node->getOperand(2), VS, 0);
2444    Tmp1 = DAG.getStore(Tmp1.getValue(1), dl, Tmp1, Node->getOperand(1), VD, 0);
2445    Results.push_back(Tmp1);
2446    break;
2447  }
2448  case ISD::EXTRACT_VECTOR_ELT:
2449    if (Node->getOperand(0).getValueType().getVectorNumElements() == 1)
2450      // This must be an access of the only element.  Return it.
2451      Tmp1 = DAG.getNode(ISD::BIT_CONVERT, dl, Node->getValueType(0),
2452                         Node->getOperand(0));
2453    else
2454      Tmp1 = ExpandExtractFromVectorThroughStack(SDValue(Node, 0));
2455    Results.push_back(Tmp1);
2456    break;
2457  case ISD::EXTRACT_SUBVECTOR:
2458    Results.push_back(ExpandExtractFromVectorThroughStack(SDValue(Node, 0)));
2459    break;
2460  case ISD::CONCAT_VECTORS: {
2461    // Use extract/insert/build vector for now. We might try to be
2462    // more clever later.
2463    SmallVector<SDValue, 8> Ops;
2464    unsigned NumOperands = Node->getNumOperands();
2465    for (unsigned i=0; i < NumOperands; ++i) {
2466      SDValue SubOp = Node->getOperand(i);
2467      MVT VVT = SubOp.getNode()->getValueType(0);
2468      MVT EltVT = VVT.getVectorElementType();
2469      unsigned NumSubElem = VVT.getVectorNumElements();
2470      for (unsigned j=0; j < NumSubElem; ++j) {
2471        Ops.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT, SubOp,
2472                                  DAG.getIntPtrConstant(j)));
2473      }
2474    }
2475    Tmp1 = DAG.getNode(ISD::BUILD_VECTOR, dl, Node->getValueType(0),
2476                       &Ops[0], Ops.size());
2477    Results.push_back(Tmp1);
2478    break;
2479  }
2480  case ISD::SCALAR_TO_VECTOR:
2481    Results.push_back(ExpandSCALAR_TO_VECTOR(Node));
2482    break;
2483  case ISD::INSERT_VECTOR_ELT:
2484    Results.push_back(ExpandINSERT_VECTOR_ELT(Node->getOperand(0),
2485                                              Node->getOperand(1),
2486                                              Node->getOperand(2), dl));
2487    break;
2488  case ISD::VECTOR_SHUFFLE: {
2489    SmallVector<int, 8> Mask;
2490    cast<ShuffleVectorSDNode>(Node)->getMask(Mask);
2491
2492    MVT VT = Node->getValueType(0);
2493    MVT EltVT = VT.getVectorElementType();
2494    unsigned NumElems = VT.getVectorNumElements();
2495    SmallVector<SDValue, 8> Ops;
2496    for (unsigned i = 0; i != NumElems; ++i) {
2497      if (Mask[i] < 0) {
2498        Ops.push_back(DAG.getUNDEF(EltVT));
2499        continue;
2500      }
2501      unsigned Idx = Mask[i];
2502      if (Idx < NumElems)
2503        Ops.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT,
2504                                  Node->getOperand(0),
2505                                  DAG.getIntPtrConstant(Idx)));
2506      else
2507        Ops.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT,
2508                                  Node->getOperand(1),
2509                                  DAG.getIntPtrConstant(Idx - NumElems)));
2510    }
2511    Tmp1 = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &Ops[0], Ops.size());
2512    Results.push_back(Tmp1);
2513    break;
2514  }
2515  case ISD::EXTRACT_ELEMENT: {
2516    MVT OpTy = Node->getOperand(0).getValueType();
2517    if (cast<ConstantSDNode>(Node->getOperand(1))->getZExtValue()) {
2518      // 1 -> Hi
2519      Tmp1 = DAG.getNode(ISD::SRL, dl, OpTy, Node->getOperand(0),
2520                         DAG.getConstant(OpTy.getSizeInBits()/2,
2521                                         TLI.getShiftAmountTy()));
2522      Tmp1 = DAG.getNode(ISD::TRUNCATE, dl, Node->getValueType(0), Tmp1);
2523    } else {
2524      // 0 -> Lo
2525      Tmp1 = DAG.getNode(ISD::TRUNCATE, dl, Node->getValueType(0),
2526                         Node->getOperand(0));
2527    }
2528    Results.push_back(Tmp1);
2529    break;
2530  }
2531  case ISD::STACKSAVE:
2532    // Expand to CopyFromReg if the target set
2533    // StackPointerRegisterToSaveRestore.
2534    if (unsigned SP = TLI.getStackPointerRegisterToSaveRestore()) {
2535      Results.push_back(DAG.getCopyFromReg(Node->getOperand(0), dl, SP,
2536                                           Node->getValueType(0)));
2537      Results.push_back(Results[0].getValue(1));
2538    } else {
2539      Results.push_back(DAG.getUNDEF(Node->getValueType(0)));
2540      Results.push_back(Node->getOperand(0));
2541    }
2542    break;
2543  case ISD::STACKRESTORE:
2544    // Expand to CopyToReg if the target set
2545    // StackPointerRegisterToSaveRestore.
2546    if (unsigned SP = TLI.getStackPointerRegisterToSaveRestore()) {
2547      Results.push_back(DAG.getCopyToReg(Node->getOperand(0), dl, SP,
2548                                         Node->getOperand(1)));
2549    } else {
2550      Results.push_back(Node->getOperand(0));
2551    }
2552    break;
2553  case ISD::FCOPYSIGN:
2554    Results.push_back(ExpandFCOPYSIGN(Node));
2555    break;
2556  case ISD::FNEG:
2557    // Expand Y = FNEG(X) ->  Y = SUB -0.0, X
2558    Tmp1 = DAG.getConstantFP(-0.0, Node->getValueType(0));
2559    Tmp1 = DAG.getNode(ISD::FSUB, dl, Node->getValueType(0), Tmp1,
2560                       Node->getOperand(0));
2561    Results.push_back(Tmp1);
2562    break;
2563  case ISD::FABS: {
2564    // Expand Y = FABS(X) -> Y = (X >u 0.0) ? X : fneg(X).
2565    MVT VT = Node->getValueType(0);
2566    Tmp1 = Node->getOperand(0);
2567    Tmp2 = DAG.getConstantFP(0.0, VT);
2568    Tmp2 = DAG.getSetCC(dl, TLI.getSetCCResultType(Tmp1.getValueType()),
2569                        Tmp1, Tmp2, ISD::SETUGT);
2570    Tmp3 = DAG.getNode(ISD::FNEG, dl, VT, Tmp1);
2571    Tmp1 = DAG.getNode(ISD::SELECT, dl, VT, Tmp2, Tmp1, Tmp3);
2572    Results.push_back(Tmp1);
2573    break;
2574  }
2575  case ISD::FSQRT:
2576    Results.push_back(ExpandFPLibCall(Node, RTLIB::SQRT_F32, RTLIB::SQRT_F64,
2577                                      RTLIB::SQRT_F80, RTLIB::SQRT_PPCF128));
2578    break;
2579  case ISD::FSIN:
2580    Results.push_back(ExpandFPLibCall(Node, RTLIB::SIN_F32, RTLIB::SIN_F64,
2581                                      RTLIB::SIN_F80, RTLIB::SIN_PPCF128));
2582    break;
2583  case ISD::FCOS:
2584    Results.push_back(ExpandFPLibCall(Node, RTLIB::COS_F32, RTLIB::COS_F64,
2585                                      RTLIB::COS_F80, RTLIB::COS_PPCF128));
2586    break;
2587  case ISD::FLOG:
2588    Results.push_back(ExpandFPLibCall(Node, RTLIB::LOG_F32, RTLIB::LOG_F64,
2589                                      RTLIB::LOG_F80, RTLIB::LOG_PPCF128));
2590    break;
2591  case ISD::FLOG2:
2592    Results.push_back(ExpandFPLibCall(Node, RTLIB::LOG2_F32, RTLIB::LOG2_F64,
2593                                      RTLIB::LOG2_F80, RTLIB::LOG2_PPCF128));
2594    break;
2595  case ISD::FLOG10:
2596    Results.push_back(ExpandFPLibCall(Node, RTLIB::LOG10_F32, RTLIB::LOG10_F64,
2597                                      RTLIB::LOG10_F80, RTLIB::LOG10_PPCF128));
2598    break;
2599  case ISD::FEXP:
2600    Results.push_back(ExpandFPLibCall(Node, RTLIB::EXP_F32, RTLIB::EXP_F64,
2601                                      RTLIB::EXP_F80, RTLIB::EXP_PPCF128));
2602    break;
2603  case ISD::FEXP2:
2604    Results.push_back(ExpandFPLibCall(Node, RTLIB::EXP2_F32, RTLIB::EXP2_F64,
2605                                      RTLIB::EXP2_F80, RTLIB::EXP2_PPCF128));
2606    break;
2607  case ISD::FTRUNC:
2608    Results.push_back(ExpandFPLibCall(Node, RTLIB::TRUNC_F32, RTLIB::TRUNC_F64,
2609                                      RTLIB::TRUNC_F80, RTLIB::TRUNC_PPCF128));
2610    break;
2611  case ISD::FFLOOR:
2612    Results.push_back(ExpandFPLibCall(Node, RTLIB::FLOOR_F32, RTLIB::FLOOR_F64,
2613                                      RTLIB::FLOOR_F80, RTLIB::FLOOR_PPCF128));
2614    break;
2615  case ISD::FCEIL:
2616    Results.push_back(ExpandFPLibCall(Node, RTLIB::CEIL_F32, RTLIB::CEIL_F64,
2617                                      RTLIB::CEIL_F80, RTLIB::CEIL_PPCF128));
2618    break;
2619  case ISD::FRINT:
2620    Results.push_back(ExpandFPLibCall(Node, RTLIB::RINT_F32, RTLIB::RINT_F64,
2621                                      RTLIB::RINT_F80, RTLIB::RINT_PPCF128));
2622    break;
2623  case ISD::FNEARBYINT:
2624    Results.push_back(ExpandFPLibCall(Node, RTLIB::NEARBYINT_F32,
2625                                      RTLIB::NEARBYINT_F64,
2626                                      RTLIB::NEARBYINT_F80,
2627                                      RTLIB::NEARBYINT_PPCF128));
2628    break;
2629  case ISD::FPOWI:
2630    Results.push_back(ExpandFPLibCall(Node, RTLIB::POWI_F32, RTLIB::POWI_F64,
2631                                      RTLIB::POWI_F80, RTLIB::POWI_PPCF128));
2632    break;
2633  case ISD::FPOW:
2634    Results.push_back(ExpandFPLibCall(Node, RTLIB::POW_F32, RTLIB::POW_F64,
2635                                      RTLIB::POW_F80, RTLIB::POW_PPCF128));
2636    break;
2637  case ISD::FDIV:
2638    Results.push_back(ExpandFPLibCall(Node, RTLIB::DIV_F32, RTLIB::DIV_F64,
2639                                      RTLIB::DIV_F80, RTLIB::DIV_PPCF128));
2640    break;
2641  case ISD::FREM:
2642    Results.push_back(ExpandFPLibCall(Node, RTLIB::REM_F32, RTLIB::REM_F64,
2643                                      RTLIB::REM_F80, RTLIB::REM_PPCF128));
2644    break;
2645  case ISD::ConstantFP: {
2646    ConstantFPSDNode *CFP = cast<ConstantFPSDNode>(Node);
2647    // Check to see if this FP immediate is already legal.
2648    bool isLegal = false;
2649    for (TargetLowering::legal_fpimm_iterator I = TLI.legal_fpimm_begin(),
2650            E = TLI.legal_fpimm_end(); I != E; ++I) {
2651      if (CFP->isExactlyValue(*I)) {
2652        isLegal = true;
2653        break;
2654      }
2655    }
2656    // If this is a legal constant, turn it into a TargetConstantFP node.
2657    if (isLegal)
2658      Results.push_back(SDValue(Node, 0));
2659    else
2660      Results.push_back(ExpandConstantFP(CFP, true, DAG, TLI));
2661    break;
2662  }
2663  case ISD::EHSELECTION: {
2664    unsigned Reg = TLI.getExceptionSelectorRegister();
2665    assert(Reg && "Can't expand to unknown register!");
2666    Results.push_back(DAG.getCopyFromReg(Node->getOperand(1), dl, Reg,
2667                                         Node->getValueType(0)));
2668    Results.push_back(Results[0].getValue(1));
2669    break;
2670  }
2671  case ISD::EXCEPTIONADDR: {
2672    unsigned Reg = TLI.getExceptionAddressRegister();
2673    assert(Reg && "Can't expand to unknown register!");
2674    Results.push_back(DAG.getCopyFromReg(Node->getOperand(0), dl, Reg,
2675                                         Node->getValueType(0)));
2676    Results.push_back(Results[0].getValue(1));
2677    break;
2678  }
2679  case ISD::SUB: {
2680    MVT VT = Node->getValueType(0);
2681    assert(TLI.isOperationLegalOrCustom(ISD::ADD, VT) &&
2682           TLI.isOperationLegalOrCustom(ISD::XOR, VT) &&
2683           "Don't know how to expand this subtraction!");
2684    Tmp1 = DAG.getNode(ISD::XOR, dl, VT, Node->getOperand(1),
2685               DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()), VT));
2686    Tmp1 = DAG.getNode(ISD::ADD, dl, VT, Tmp2, DAG.getConstant(1, VT));
2687    Results.push_back(DAG.getNode(ISD::ADD, dl, VT, Node->getOperand(0), Tmp1));
2688    break;
2689  }
2690  case ISD::UREM:
2691  case ISD::SREM: {
2692    MVT VT = Node->getValueType(0);
2693    SDVTList VTs = DAG.getVTList(VT, VT);
2694    bool isSigned = Node->getOpcode() == ISD::SREM;
2695    unsigned DivOpc = isSigned ? ISD::SDIV : ISD::UDIV;
2696    unsigned DivRemOpc = isSigned ? ISD::SDIVREM : ISD::UDIVREM;
2697    Tmp2 = Node->getOperand(0);
2698    Tmp3 = Node->getOperand(1);
2699    if (TLI.isOperationLegalOrCustom(DivRemOpc, VT)) {
2700      Tmp1 = DAG.getNode(DivRemOpc, dl, VTs, Tmp2, Tmp3).getValue(1);
2701    } else if (TLI.isOperationLegalOrCustom(DivOpc, VT)) {
2702      // X % Y -> X-X/Y*Y
2703      Tmp1 = DAG.getNode(DivOpc, dl, VT, Tmp2, Tmp3);
2704      Tmp1 = DAG.getNode(ISD::MUL, dl, VT, Tmp1, Tmp3);
2705      Tmp1 = DAG.getNode(ISD::SUB, dl, VT, Tmp2, Tmp1);
2706    } else if (isSigned) {
2707      Tmp1 = ExpandIntLibCall(Node, true, RTLIB::SREM_I16, RTLIB::SREM_I32,
2708                              RTLIB::SREM_I64, RTLIB::SREM_I128);
2709    } else {
2710      Tmp1 = ExpandIntLibCall(Node, false, RTLIB::UREM_I16, RTLIB::UREM_I32,
2711                              RTLIB::UREM_I64, RTLIB::UREM_I128);
2712    }
2713    Results.push_back(Tmp1);
2714    break;
2715  }
2716  case ISD::UDIV:
2717  case ISD::SDIV: {
2718    bool isSigned = Node->getOpcode() == ISD::SDIV;
2719    unsigned DivRemOpc = isSigned ? ISD::SDIVREM : ISD::UDIVREM;
2720    MVT VT = Node->getValueType(0);
2721    SDVTList VTs = DAG.getVTList(VT, VT);
2722    if (TLI.isOperationLegalOrCustom(DivRemOpc, VT))
2723      Tmp1 = DAG.getNode(DivRemOpc, dl, VTs, Node->getOperand(0),
2724                         Node->getOperand(1));
2725    else if (isSigned)
2726      Tmp1 = ExpandIntLibCall(Node, true, RTLIB::SDIV_I16, RTLIB::SDIV_I32,
2727                              RTLIB::SDIV_I64, RTLIB::SDIV_I128);
2728    else
2729      Tmp1 = ExpandIntLibCall(Node, false, RTLIB::UDIV_I16, RTLIB::UDIV_I32,
2730                              RTLIB::UDIV_I64, RTLIB::UDIV_I128);
2731    Results.push_back(Tmp1);
2732    break;
2733  }
2734  case ISD::MULHU:
2735  case ISD::MULHS: {
2736    unsigned ExpandOpcode = Node->getOpcode() == ISD::MULHU ? ISD::UMUL_LOHI :
2737                                                              ISD::SMUL_LOHI;
2738    MVT VT = Node->getValueType(0);
2739    SDVTList VTs = DAG.getVTList(VT, VT);
2740    assert(TLI.isOperationLegalOrCustom(ExpandOpcode, VT) &&
2741           "If this wasn't legal, it shouldn't have been created!");
2742    Tmp1 = DAG.getNode(ExpandOpcode, dl, VTs, Node->getOperand(0),
2743                       Node->getOperand(1));
2744    Results.push_back(Tmp1.getValue(1));
2745    break;
2746  }
2747  case ISD::MUL: {
2748    MVT VT = Node->getValueType(0);
2749    SDVTList VTs = DAG.getVTList(VT, VT);
2750    // See if multiply or divide can be lowered using two-result operations.
2751    // We just need the low half of the multiply; try both the signed
2752    // and unsigned forms. If the target supports both SMUL_LOHI and
2753    // UMUL_LOHI, form a preference by checking which forms of plain
2754    // MULH it supports.
2755    bool HasSMUL_LOHI = TLI.isOperationLegalOrCustom(ISD::SMUL_LOHI, VT);
2756    bool HasUMUL_LOHI = TLI.isOperationLegalOrCustom(ISD::UMUL_LOHI, VT);
2757    bool HasMULHS = TLI.isOperationLegalOrCustom(ISD::MULHS, VT);
2758    bool HasMULHU = TLI.isOperationLegalOrCustom(ISD::MULHU, VT);
2759    unsigned OpToUse = 0;
2760    if (HasSMUL_LOHI && !HasMULHS) {
2761      OpToUse = ISD::SMUL_LOHI;
2762    } else if (HasUMUL_LOHI && !HasMULHU) {
2763      OpToUse = ISD::UMUL_LOHI;
2764    } else if (HasSMUL_LOHI) {
2765      OpToUse = ISD::SMUL_LOHI;
2766    } else if (HasUMUL_LOHI) {
2767      OpToUse = ISD::UMUL_LOHI;
2768    }
2769    if (OpToUse) {
2770      Results.push_back(DAG.getNode(OpToUse, dl, VTs, Node->getOperand(0),
2771                                    Node->getOperand(1)));
2772      break;
2773    }
2774    Tmp1 = ExpandIntLibCall(Node, false, RTLIB::MUL_I16, RTLIB::MUL_I32,
2775                            RTLIB::MUL_I64, RTLIB::MUL_I128);
2776    Results.push_back(Tmp1);
2777    break;
2778  }
2779  case ISD::SADDO:
2780  case ISD::SSUBO: {
2781    SDValue LHS = Node->getOperand(0);
2782    SDValue RHS = Node->getOperand(1);
2783    SDValue Sum = DAG.getNode(Node->getOpcode() == ISD::SADDO ?
2784                              ISD::ADD : ISD::SUB, dl, LHS.getValueType(),
2785                              LHS, RHS);
2786    Results.push_back(Sum);
2787    MVT OType = Node->getValueType(1);
2788
2789    SDValue Zero = DAG.getConstant(0, LHS.getValueType());
2790
2791    //   LHSSign -> LHS >= 0
2792    //   RHSSign -> RHS >= 0
2793    //   SumSign -> Sum >= 0
2794    //
2795    //   Add:
2796    //   Overflow -> (LHSSign == RHSSign) && (LHSSign != SumSign)
2797    //   Sub:
2798    //   Overflow -> (LHSSign != RHSSign) && (LHSSign != SumSign)
2799    //
2800    SDValue LHSSign = DAG.getSetCC(dl, OType, LHS, Zero, ISD::SETGE);
2801    SDValue RHSSign = DAG.getSetCC(dl, OType, RHS, Zero, ISD::SETGE);
2802    SDValue SignsMatch = DAG.getSetCC(dl, OType, LHSSign, RHSSign,
2803                                      Node->getOpcode() == ISD::SADDO ?
2804                                      ISD::SETEQ : ISD::SETNE);
2805
2806    SDValue SumSign = DAG.getSetCC(dl, OType, Sum, Zero, ISD::SETGE);
2807    SDValue SumSignNE = DAG.getSetCC(dl, OType, LHSSign, SumSign, ISD::SETNE);
2808
2809    SDValue Cmp = DAG.getNode(ISD::AND, dl, OType, SignsMatch, SumSignNE);
2810    Results.push_back(Cmp);
2811    break;
2812  }
2813  case ISD::UADDO:
2814  case ISD::USUBO: {
2815    SDValue LHS = Node->getOperand(0);
2816    SDValue RHS = Node->getOperand(1);
2817    SDValue Sum = DAG.getNode(Node->getOpcode() == ISD::UADDO ?
2818                              ISD::ADD : ISD::SUB, dl, LHS.getValueType(),
2819                              LHS, RHS);
2820    Results.push_back(Sum);
2821    Results.push_back(DAG.getSetCC(dl, Node->getValueType(1), Sum, LHS,
2822                                   Node->getOpcode () == ISD::UADDO ?
2823                                   ISD::SETULT : ISD::SETUGT));
2824    break;
2825  }
2826  case ISD::BUILD_PAIR: {
2827    MVT PairTy = Node->getValueType(0);
2828    Tmp1 = DAG.getNode(ISD::ZERO_EXTEND, dl, PairTy, Node->getOperand(0));
2829    Tmp2 = DAG.getNode(ISD::ANY_EXTEND, dl, PairTy, Node->getOperand(1));
2830    Tmp2 = DAG.getNode(ISD::SHL, dl, PairTy, Tmp2,
2831                       DAG.getConstant(PairTy.getSizeInBits()/2,
2832                                       TLI.getShiftAmountTy()));
2833    Results.push_back(DAG.getNode(ISD::OR, dl, PairTy, Tmp1, Tmp2));
2834    break;
2835  }
2836  case ISD::SELECT:
2837    Tmp1 = Node->getOperand(0);
2838    Tmp2 = Node->getOperand(1);
2839    Tmp3 = Node->getOperand(2);
2840    if (Tmp1.getOpcode() == ISD::SETCC) {
2841      Tmp1 = DAG.getSelectCC(dl, Tmp1.getOperand(0), Tmp1.getOperand(1),
2842                             Tmp2, Tmp3,
2843                             cast<CondCodeSDNode>(Tmp1.getOperand(2))->get());
2844    } else {
2845      Tmp1 = DAG.getSelectCC(dl, Tmp1,
2846                             DAG.getConstant(0, Tmp1.getValueType()),
2847                             Tmp2, Tmp3, ISD::SETNE);
2848    }
2849    Results.push_back(Tmp1);
2850    break;
2851  case ISD::BR_JT: {
2852    SDValue Chain = Node->getOperand(0);
2853    SDValue Table = Node->getOperand(1);
2854    SDValue Index = Node->getOperand(2);
2855
2856    MVT PTy = TLI.getPointerTy();
2857    MachineFunction &MF = DAG.getMachineFunction();
2858    unsigned EntrySize = MF.getJumpTableInfo()->getEntrySize();
2859    Index= DAG.getNode(ISD::MUL, dl, PTy,
2860                        Index, DAG.getConstant(EntrySize, PTy));
2861    SDValue Addr = DAG.getNode(ISD::ADD, dl, PTy, Index, Table);
2862
2863    MVT MemVT = MVT::getIntegerVT(EntrySize * 8);
2864    SDValue LD = DAG.getExtLoad(ISD::SEXTLOAD, dl, PTy, Chain, Addr,
2865                                PseudoSourceValue::getJumpTable(), 0, MemVT);
2866    Addr = LD;
2867    if (TLI.getTargetMachine().getRelocationModel() == Reloc::PIC_) {
2868      // For PIC, the sequence is:
2869      // BRIND(load(Jumptable + index) + RelocBase)
2870      // RelocBase can be JumpTable, GOT or some sort of global base.
2871      Addr = DAG.getNode(ISD::ADD, dl, PTy, Addr,
2872                          TLI.getPICJumpTableRelocBase(Table, DAG));
2873    }
2874    Tmp1 = DAG.getNode(ISD::BRIND, dl, MVT::Other, LD.getValue(1), Addr);
2875    Results.push_back(Tmp1);
2876    break;
2877  }
2878  case ISD::BRCOND:
2879    // Expand brcond's setcc into its constituent parts and create a BR_CC
2880    // Node.
2881    Tmp1 = Node->getOperand(0);
2882    Tmp2 = Node->getOperand(1);
2883    if (Tmp2.getOpcode() == ISD::SETCC) {
2884      Tmp1 = DAG.getNode(ISD::BR_CC, dl, MVT::Other,
2885                         Tmp1, Tmp2.getOperand(2),
2886                         Tmp2.getOperand(0), Tmp2.getOperand(1),
2887                         Node->getOperand(2));
2888    } else {
2889      Tmp1 = DAG.getNode(ISD::BR_CC, dl, MVT::Other, Tmp1,
2890                         DAG.getCondCode(ISD::SETNE), Tmp2,
2891                         DAG.getConstant(0, Tmp2.getValueType()),
2892                         Node->getOperand(2));
2893    }
2894    Results.push_back(Tmp1);
2895    break;
2896  case ISD::SETCC: {
2897    Tmp1 = Node->getOperand(0);
2898    Tmp2 = Node->getOperand(1);
2899    Tmp3 = Node->getOperand(2);
2900    LegalizeSetCC(Node->getValueType(0), Tmp1, Tmp2, Tmp3, dl);
2901
2902    // If we expanded the SETCC into an AND/OR, return the new node
2903    if (Tmp2.getNode() == 0) {
2904      Results.push_back(Tmp1);
2905      break;
2906    }
2907
2908    // Otherwise, SETCC for the given comparison type must be completely
2909    // illegal; expand it into a SELECT_CC.
2910    MVT VT = Node->getValueType(0);
2911    Tmp1 = DAG.getNode(ISD::SELECT_CC, dl, VT, Tmp1, Tmp2,
2912                       DAG.getConstant(1, VT), DAG.getConstant(0, VT), Tmp3);
2913    Results.push_back(Tmp1);
2914    break;
2915  }
2916  case ISD::SELECT_CC: {
2917    Tmp1 = Node->getOperand(0);   // LHS
2918    Tmp2 = Node->getOperand(1);   // RHS
2919    Tmp3 = Node->getOperand(2);   // True
2920    Tmp4 = Node->getOperand(3);   // False
2921    SDValue CC = Node->getOperand(4);
2922
2923    LegalizeSetCC(TLI.getSetCCResultType(Tmp1.getValueType()),
2924                  Tmp1, Tmp2, CC, dl);
2925
2926    assert(!Tmp2.getNode() && "Can't legalize SELECT_CC with legal condition!");
2927    Tmp2 = DAG.getConstant(0, Tmp1.getValueType());
2928    CC = DAG.getCondCode(ISD::SETNE);
2929    Tmp1 = DAG.getNode(ISD::SELECT_CC, dl, Node->getValueType(0), Tmp1, Tmp2,
2930                       Tmp3, Tmp4, CC);
2931    Results.push_back(Tmp1);
2932    break;
2933  }
2934  case ISD::BR_CC: {
2935    Tmp1 = Node->getOperand(0);              // Chain
2936    Tmp2 = Node->getOperand(2);              // LHS
2937    Tmp3 = Node->getOperand(3);              // RHS
2938    Tmp4 = Node->getOperand(1);              // CC
2939
2940    LegalizeSetCC(TLI.getSetCCResultType(Tmp2.getValueType()),
2941                  Tmp2, Tmp3, Tmp4, dl);
2942    LastCALLSEQ_END = DAG.getEntryNode();
2943
2944    // If we didn't get both a LHS and RHS back from LegalizeSetCC,
2945    // the LHS is a legal SETCC itself.  In this case, we need to compare
2946    // the result against zero to select between true and false values.
2947    if (Tmp3.getNode() == 0) {
2948      Tmp3 = DAG.getConstant(0, Tmp2.getValueType());
2949      Tmp4 = DAG.getCondCode(ISD::SETNE);
2950    }
2951
2952    Tmp1 = DAG.getNode(ISD::BR_CC, dl, Node->getValueType(0), Tmp1, Tmp4, Tmp2,
2953                       Tmp3, Node->getOperand(4));
2954    Results.push_back(Tmp1);
2955    break;
2956  }
2957  case ISD::GLOBAL_OFFSET_TABLE:
2958  case ISD::GlobalAddress:
2959  case ISD::GlobalTLSAddress:
2960  case ISD::ExternalSymbol:
2961  case ISD::ConstantPool:
2962  case ISD::JumpTable:
2963  case ISD::INTRINSIC_W_CHAIN:
2964  case ISD::INTRINSIC_WO_CHAIN:
2965  case ISD::INTRINSIC_VOID:
2966    // FIXME: Custom lowering for these operations shouldn't return null!
2967    for (unsigned i = 0, e = Node->getNumValues(); i != e; ++i)
2968      Results.push_back(SDValue(Node, i));
2969    break;
2970  }
2971}
2972void SelectionDAGLegalize::PromoteNode(SDNode *Node,
2973                                       SmallVectorImpl<SDValue> &Results) {
2974  MVT OVT = Node->getValueType(0);
2975  if (Node->getOpcode() == ISD::UINT_TO_FP ||
2976      Node->getOpcode() == ISD::SINT_TO_FP) {
2977    OVT = Node->getOperand(0).getValueType();
2978  }
2979  MVT NVT = TLI.getTypeToPromoteTo(Node->getOpcode(), OVT);
2980  DebugLoc dl = Node->getDebugLoc();
2981  SDValue Tmp1, Tmp2, Tmp3;
2982  switch (Node->getOpcode()) {
2983  case ISD::CTTZ:
2984  case ISD::CTLZ:
2985  case ISD::CTPOP:
2986    // Zero extend the argument.
2987    Tmp1 = DAG.getNode(ISD::ZERO_EXTEND, dl, NVT, Node->getOperand(0));
2988    // Perform the larger operation.
2989    Tmp1 = DAG.getNode(Node->getOpcode(), dl, Node->getValueType(0), Tmp1);
2990    if (Node->getOpcode() == ISD::CTTZ) {
2991      //if Tmp1 == sizeinbits(NVT) then Tmp1 = sizeinbits(Old VT)
2992      Tmp2 = DAG.getSetCC(dl, TLI.getSetCCResultType(Tmp1.getValueType()),
2993                          Tmp1, DAG.getConstant(NVT.getSizeInBits(), NVT),
2994                          ISD::SETEQ);
2995      Tmp1 = DAG.getNode(ISD::SELECT, dl, NVT, Tmp2,
2996                          DAG.getConstant(OVT.getSizeInBits(), NVT), Tmp1);
2997    } else if (Node->getOpcode() == ISD::CTLZ) {
2998      // Tmp1 = Tmp1 - (sizeinbits(NVT) - sizeinbits(Old VT))
2999      Tmp1 = DAG.getNode(ISD::SUB, dl, NVT, Tmp1,
3000                          DAG.getConstant(NVT.getSizeInBits() -
3001                                          OVT.getSizeInBits(), NVT));
3002    }
3003    Results.push_back(Tmp1);
3004    break;
3005  case ISD::BSWAP: {
3006    unsigned DiffBits = NVT.getSizeInBits() - OVT.getSizeInBits();
3007    Tmp1 = DAG.getNode(ISD::ZERO_EXTEND, dl, NVT, Tmp1);
3008    Tmp1 = DAG.getNode(ISD::BSWAP, dl, NVT, Tmp1);
3009    Tmp1 = DAG.getNode(ISD::SRL, dl, NVT, Tmp1,
3010                          DAG.getConstant(DiffBits, TLI.getShiftAmountTy()));
3011    Results.push_back(Tmp1);
3012    break;
3013  }
3014  case ISD::FP_TO_UINT:
3015  case ISD::FP_TO_SINT:
3016    Tmp1 = PromoteLegalFP_TO_INT(Node->getOperand(0), Node->getValueType(0),
3017                                 Node->getOpcode() == ISD::FP_TO_SINT, dl);
3018    Results.push_back(Tmp1);
3019    break;
3020  case ISD::UINT_TO_FP:
3021  case ISD::SINT_TO_FP:
3022    Tmp1 = PromoteLegalINT_TO_FP(Node->getOperand(0), Node->getValueType(0),
3023                                 Node->getOpcode() == ISD::SINT_TO_FP, dl);
3024    Results.push_back(Tmp1);
3025    break;
3026  case ISD::AND:
3027  case ISD::OR:
3028  case ISD::XOR:
3029    assert(OVT.isVector() && "Don't know how to promote scalar logic ops");
3030    // Bit convert each of the values to the new type.
3031    Tmp1 = DAG.getNode(ISD::BIT_CONVERT, dl, NVT, Node->getOperand(0));
3032    Tmp2 = DAG.getNode(ISD::BIT_CONVERT, dl, NVT, Node->getOperand(1));
3033    Tmp1 = DAG.getNode(Node->getOpcode(), dl, NVT, Tmp1, Tmp2);
3034    // Bit convert the result back the original type.
3035    Results.push_back(DAG.getNode(ISD::BIT_CONVERT, dl, OVT, Tmp1));
3036    break;
3037  case ISD::SELECT:
3038    unsigned ExtOp, TruncOp;
3039    if (Node->getValueType(0).isVector()) {
3040      ExtOp   = ISD::BIT_CONVERT;
3041      TruncOp = ISD::BIT_CONVERT;
3042    } else if (Node->getValueType(0).isInteger()) {
3043      ExtOp   = ISD::ANY_EXTEND;
3044      TruncOp = ISD::TRUNCATE;
3045    } else {
3046      ExtOp   = ISD::FP_EXTEND;
3047      TruncOp = ISD::FP_ROUND;
3048    }
3049    Tmp1 = Node->getOperand(0);
3050    // Promote each of the values to the new type.
3051    Tmp2 = DAG.getNode(ExtOp, dl, NVT, Node->getOperand(1));
3052    Tmp3 = DAG.getNode(ExtOp, dl, NVT, Node->getOperand(2));
3053    // Perform the larger operation, then round down.
3054    Tmp1 = DAG.getNode(ISD::SELECT, dl, NVT, Tmp1, Tmp2, Tmp3);
3055    if (TruncOp != ISD::FP_ROUND)
3056      Tmp1 = DAG.getNode(TruncOp, dl, Node->getValueType(0), Tmp1);
3057    else
3058      Tmp1 = DAG.getNode(TruncOp, dl, Node->getValueType(0), Tmp1,
3059                         DAG.getIntPtrConstant(0));
3060    Results.push_back(Tmp1);
3061    break;
3062  case ISD::VECTOR_SHUFFLE: {
3063    SmallVector<int, 8> Mask;
3064    cast<ShuffleVectorSDNode>(Node)->getMask(Mask);
3065
3066    // Cast the two input vectors.
3067    Tmp1 = DAG.getNode(ISD::BIT_CONVERT, dl, NVT, Node->getOperand(0));
3068    Tmp2 = DAG.getNode(ISD::BIT_CONVERT, dl, NVT, Node->getOperand(1));
3069
3070    // Convert the shuffle mask to the right # elements.
3071    Tmp1 = ShuffleWithNarrowerEltType(NVT, OVT, dl, Tmp1, Tmp2, Mask);
3072    Tmp1 = DAG.getNode(ISD::BIT_CONVERT, dl, OVT, Tmp1);
3073    Results.push_back(Tmp1);
3074    break;
3075  }
3076  case ISD::SETCC: {
3077    // First step, figure out the appropriate operation to use.
3078    // Allow SETCC to not be supported for all legal data types
3079    // Mostly this targets FP
3080    MVT NewInTy = Node->getOperand(0).getValueType();
3081    MVT OldVT = NewInTy; OldVT = OldVT;
3082
3083    // Scan for the appropriate larger type to use.
3084    while (1) {
3085      NewInTy = (MVT::SimpleValueType)(NewInTy.getSimpleVT()+1);
3086
3087      assert(NewInTy.isInteger() == OldVT.isInteger() &&
3088              "Fell off of the edge of the integer world");
3089      assert(NewInTy.isFloatingPoint() == OldVT.isFloatingPoint() &&
3090              "Fell off of the edge of the floating point world");
3091
3092      // If the target supports SETCC of this type, use it.
3093      if (TLI.isOperationLegalOrCustom(ISD::SETCC, NewInTy))
3094        break;
3095    }
3096    if (NewInTy.isInteger())
3097      assert(0 && "Cannot promote Legal Integer SETCC yet");
3098    else {
3099      Tmp1 = DAG.getNode(ISD::FP_EXTEND, dl, NewInTy, Tmp1);
3100      Tmp2 = DAG.getNode(ISD::FP_EXTEND, dl, NewInTy, Tmp2);
3101    }
3102    Results.push_back(DAG.getNode(ISD::SETCC, dl, Node->getValueType(0),
3103                                  Tmp1, Tmp2, Node->getOperand(2)));
3104    break;
3105  }
3106  }
3107}
3108
3109// SelectionDAG::Legalize - This is the entry point for the file.
3110//
3111void SelectionDAG::Legalize(bool TypesNeedLegalizing,
3112                            CodeGenOpt::Level OptLevel) {
3113  /// run - This is the main entry point to this class.
3114  ///
3115  SelectionDAGLegalize(*this, OptLevel).LegalizeDAG();
3116}
3117
3118