b9d841e9d8dc5c728f9c1a8533fd01b4b0945c7d
[oota-llvm.git] / lib / CodeGen / SelectionDAG / LegalizeDAG.cpp
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/Analysis/DebugInfo.h"
15 #include "llvm/CodeGen/Analysis.h"
16 #include "llvm/CodeGen/MachineFunction.h"
17 #include "llvm/CodeGen/MachineJumpTableInfo.h"
18 #include "llvm/CodeGen/SelectionDAG.h"
19 #include "llvm/Target/TargetFrameLowering.h"
20 #include "llvm/Target/TargetLowering.h"
21 #include "llvm/Target/TargetData.h"
22 #include "llvm/Target/TargetMachine.h"
23 #include "llvm/CallingConv.h"
24 #include "llvm/Constants.h"
25 #include "llvm/DerivedTypes.h"
26 #include "llvm/LLVMContext.h"
27 #include "llvm/Support/Debug.h"
28 #include "llvm/Support/ErrorHandling.h"
29 #include "llvm/Support/MathExtras.h"
30 #include "llvm/Support/raw_ostream.h"
31 #include "llvm/ADT/DenseMap.h"
32 #include "llvm/ADT/SmallVector.h"
33 #include "llvm/ADT/SmallPtrSet.h"
34 using namespace llvm;
35
36 //===----------------------------------------------------------------------===//
37 /// SelectionDAGLegalize - This takes an arbitrary SelectionDAG as input and
38 /// hacks on it until the target machine can handle it.  This involves
39 /// eliminating value sizes the machine cannot handle (promoting small sizes to
40 /// large sizes or splitting up large values into small values) as well as
41 /// eliminating operations the machine cannot handle.
42 ///
43 /// This code also does a small amount of optimization and recognition of idioms
44 /// as part of its processing.  For example, if a target does not support a
45 /// 'setcc' instruction efficiently, but does support 'brcc' instruction, this
46 /// will attempt merge setcc and brc instructions into brcc's.
47 ///
48 namespace {
49 class SelectionDAGLegalize {
50   const TargetMachine &TM;
51   const TargetLowering &TLI;
52   SelectionDAG &DAG;
53
54   // Libcall insertion helpers.
55
56   /// LastCALLSEQ_END - This keeps track of the CALLSEQ_END node that has been
57   /// legalized.  We use this to ensure that calls are properly serialized
58   /// against each other, including inserted libcalls.
59   SDValue LastCALLSEQ_END;
60
61   /// IsLegalizingCall - This member is used *only* for purposes of providing
62   /// helpful assertions that a libcall isn't created while another call is
63   /// being legalized (which could lead to non-serialized call sequences).
64   bool IsLegalizingCall;
65
66   /// LegalizedNodes - For nodes that are of legal width, and that have more
67   /// than one use, this map indicates what regularized operand to use.  This
68   /// allows us to avoid legalizing the same thing more than once.
69   DenseMap<SDValue, SDValue> LegalizedNodes;
70
71   void AddLegalizedOperand(SDValue From, SDValue To) {
72     LegalizedNodes.insert(std::make_pair(From, To));
73     // If someone requests legalization of the new node, return itself.
74     if (From != To)
75       LegalizedNodes.insert(std::make_pair(To, To));
76
77     // Transfer SDDbgValues.
78     DAG.TransferDbgValues(From, To);
79   }
80
81 public:
82   explicit SelectionDAGLegalize(SelectionDAG &DAG);
83
84   void LegalizeDAG();
85
86 private:
87   /// LegalizeOp - Return a legal replacement for the given operation, with
88   /// all legal operands.
89   SDValue LegalizeOp(SDValue O);
90
91   SDValue OptimizeFloatStore(StoreSDNode *ST);
92
93   /// PerformInsertVectorEltInMemory - Some target cannot handle a variable
94   /// insertion index for the INSERT_VECTOR_ELT instruction.  In this case, it
95   /// is necessary to spill the vector being inserted into to memory, perform
96   /// the insert there, and then read the result back.
97   SDValue PerformInsertVectorEltInMemory(SDValue Vec, SDValue Val,
98                                          SDValue Idx, DebugLoc dl);
99   SDValue ExpandINSERT_VECTOR_ELT(SDValue Vec, SDValue Val,
100                                   SDValue Idx, DebugLoc dl);
101
102   /// ShuffleWithNarrowerEltType - Return a vector shuffle operation which
103   /// performs the same shuffe in terms of order or result bytes, but on a type
104   /// whose vector element type is narrower than the original shuffle type.
105   /// e.g. <v4i32> <0, 1, 0, 1> -> v8i16 <0, 1, 2, 3, 0, 1, 2, 3>
106   SDValue ShuffleWithNarrowerEltType(EVT NVT, EVT VT, DebugLoc dl,
107                                      SDValue N1, SDValue N2,
108                                      SmallVectorImpl<int> &Mask) const;
109
110   bool LegalizeAllNodesNotLeadingTo(SDNode *N, SDNode *Dest,
111                                     SmallPtrSet<SDNode*, 32> &NodesLeadingTo);
112
113   void LegalizeSetCCCondCode(EVT VT, SDValue &LHS, SDValue &RHS, SDValue &CC,
114                              DebugLoc dl);
115
116   SDValue ExpandLibCall(RTLIB::Libcall LC, SDNode *Node, bool isSigned);
117   SDValue ExpandLibCall(RTLIB::Libcall LC, EVT RetVT, const SDValue *Ops,
118                         unsigned NumOps, bool isSigned, DebugLoc dl);
119
120   std::pair<SDValue, SDValue> ExpandChainLibCall(RTLIB::Libcall LC,
121                                                  SDNode *Node, bool isSigned);
122   SDValue ExpandFPLibCall(SDNode *Node, RTLIB::Libcall Call_F32,
123                           RTLIB::Libcall Call_F64, RTLIB::Libcall Call_F80,
124                           RTLIB::Libcall Call_PPCF128);
125   SDValue ExpandIntLibCall(SDNode *Node, bool isSigned,
126                            RTLIB::Libcall Call_I8,
127                            RTLIB::Libcall Call_I16,
128                            RTLIB::Libcall Call_I32,
129                            RTLIB::Libcall Call_I64,
130                            RTLIB::Libcall Call_I128);
131   void ExpandDivRemLibCall(SDNode *Node, SmallVectorImpl<SDValue> &Results);
132
133   SDValue EmitStackConvert(SDValue SrcOp, EVT SlotVT, EVT DestVT, DebugLoc dl);
134   SDValue ExpandBUILD_VECTOR(SDNode *Node);
135   SDValue ExpandSCALAR_TO_VECTOR(SDNode *Node);
136   void ExpandDYNAMIC_STACKALLOC(SDNode *Node,
137                                 SmallVectorImpl<SDValue> &Results);
138   SDValue ExpandFCOPYSIGN(SDNode *Node);
139   SDValue ExpandLegalINT_TO_FP(bool isSigned, SDValue LegalOp, EVT DestVT,
140                                DebugLoc dl);
141   SDValue PromoteLegalINT_TO_FP(SDValue LegalOp, EVT DestVT, bool isSigned,
142                                 DebugLoc dl);
143   SDValue PromoteLegalFP_TO_INT(SDValue LegalOp, EVT DestVT, bool isSigned,
144                                 DebugLoc dl);
145
146   SDValue ExpandBSWAP(SDValue Op, DebugLoc dl);
147   SDValue ExpandBitCount(unsigned Opc, SDValue Op, DebugLoc dl);
148
149   SDValue ExpandExtractFromVectorThroughStack(SDValue Op);
150   SDValue ExpandInsertToVectorThroughStack(SDValue Op);
151   SDValue ExpandVectorBuildThroughStack(SDNode* Node);
152
153   std::pair<SDValue, SDValue> ExpandAtomic(SDNode *Node);
154
155   void ExpandNode(SDNode *Node, SmallVectorImpl<SDValue> &Results);
156   void PromoteNode(SDNode *Node, SmallVectorImpl<SDValue> &Results);
157 };
158 }
159
160 /// ShuffleWithNarrowerEltType - Return a vector shuffle operation which
161 /// performs the same shuffe in terms of order or result bytes, but on a type
162 /// whose vector element type is narrower than the original shuffle type.
163 /// e.g. <v4i32> <0, 1, 0, 1> -> v8i16 <0, 1, 2, 3, 0, 1, 2, 3>
164 SDValue
165 SelectionDAGLegalize::ShuffleWithNarrowerEltType(EVT NVT, EVT VT,  DebugLoc dl,
166                                                  SDValue N1, SDValue N2,
167                                              SmallVectorImpl<int> &Mask) const {
168   unsigned NumMaskElts = VT.getVectorNumElements();
169   unsigned NumDestElts = NVT.getVectorNumElements();
170   unsigned NumEltsGrowth = NumDestElts / NumMaskElts;
171
172   assert(NumEltsGrowth && "Cannot promote to vector type with fewer elts!");
173
174   if (NumEltsGrowth == 1)
175     return DAG.getVectorShuffle(NVT, dl, N1, N2, &Mask[0]);
176
177   SmallVector<int, 8> NewMask;
178   for (unsigned i = 0; i != NumMaskElts; ++i) {
179     int Idx = Mask[i];
180     for (unsigned j = 0; j != NumEltsGrowth; ++j) {
181       if (Idx < 0)
182         NewMask.push_back(-1);
183       else
184         NewMask.push_back(Idx * NumEltsGrowth + j);
185     }
186   }
187   assert(NewMask.size() == NumDestElts && "Non-integer NumEltsGrowth?");
188   assert(TLI.isShuffleMaskLegal(NewMask, NVT) && "Shuffle not legal?");
189   return DAG.getVectorShuffle(NVT, dl, N1, N2, &NewMask[0]);
190 }
191
192 SelectionDAGLegalize::SelectionDAGLegalize(SelectionDAG &dag)
193   : TM(dag.getTarget()), TLI(dag.getTargetLoweringInfo()),
194     DAG(dag) {
195 }
196
197 void SelectionDAGLegalize::LegalizeDAG() {
198   LastCALLSEQ_END = DAG.getEntryNode();
199   IsLegalizingCall = false;
200
201   // The legalize process is inherently a bottom-up recursive process (users
202   // legalize their uses before themselves).  Given infinite stack space, we
203   // could just start legalizing on the root and traverse the whole graph.  In
204   // practice however, this causes us to run out of stack space on large basic
205   // blocks.  To avoid this problem, compute an ordering of the nodes where each
206   // node is only legalized after all of its operands are legalized.
207   DAG.AssignTopologicalOrder();
208   for (SelectionDAG::allnodes_iterator I = DAG.allnodes_begin(),
209        E = prior(DAG.allnodes_end()); I != llvm::next(E); ++I)
210     LegalizeOp(SDValue(I, 0));
211
212   // Finally, it's possible the root changed.  Get the new root.
213   SDValue OldRoot = DAG.getRoot();
214   assert(LegalizedNodes.count(OldRoot) && "Root didn't get legalized?");
215   DAG.setRoot(LegalizedNodes[OldRoot]);
216
217   LegalizedNodes.clear();
218
219   // Remove dead nodes now.
220   DAG.RemoveDeadNodes();
221 }
222
223
224 /// FindCallEndFromCallStart - Given a chained node that is part of a call
225 /// sequence, find the CALLSEQ_END node that terminates the call sequence.
226 static SDNode *FindCallEndFromCallStart(SDNode *Node, int depth = 0) {
227   // Nested CALLSEQ_START/END constructs aren't yet legal,
228   // but we can DTRT and handle them correctly here.
229   if (Node->getOpcode() == ISD::CALLSEQ_START)
230     depth++;
231   else if (Node->getOpcode() == ISD::CALLSEQ_END) {
232     depth--;
233     if (depth == 0)
234       return Node;
235   }
236   if (Node->use_empty())
237     return 0;   // No CallSeqEnd
238
239   // The chain is usually at the end.
240   SDValue TheChain(Node, Node->getNumValues()-1);
241   if (TheChain.getValueType() != MVT::Other) {
242     // Sometimes it's at the beginning.
243     TheChain = SDValue(Node, 0);
244     if (TheChain.getValueType() != MVT::Other) {
245       // Otherwise, hunt for it.
246       for (unsigned i = 1, e = Node->getNumValues(); i != e; ++i)
247         if (Node->getValueType(i) == MVT::Other) {
248           TheChain = SDValue(Node, i);
249           break;
250         }
251
252       // Otherwise, we walked into a node without a chain.
253       if (TheChain.getValueType() != MVT::Other)
254         return 0;
255     }
256   }
257
258   for (SDNode::use_iterator UI = Node->use_begin(),
259        E = Node->use_end(); UI != E; ++UI) {
260
261     // Make sure to only follow users of our token chain.
262     SDNode *User = *UI;
263     for (unsigned i = 0, e = User->getNumOperands(); i != e; ++i)
264       if (User->getOperand(i) == TheChain)
265         if (SDNode *Result = FindCallEndFromCallStart(User, depth))
266           return Result;
267   }
268   return 0;
269 }
270
271 /// FindCallStartFromCallEnd - Given a chained node that is part of a call
272 /// sequence, find the CALLSEQ_START node that initiates the call sequence.
273 static SDNode *FindCallStartFromCallEnd(SDNode *Node) {
274   int nested = 0;
275   assert(Node && "Didn't find callseq_start for a call??");
276   while (Node->getOpcode() != ISD::CALLSEQ_START || nested) {
277     Node = Node->getOperand(0).getNode();
278     assert(Node->getOperand(0).getValueType() == MVT::Other &&
279            "Node doesn't have a token chain argument!");
280     switch (Node->getOpcode()) {
281     default:
282       break;
283     case ISD::CALLSEQ_START:
284       if (!nested)
285         return Node;
286       nested--;
287       break;
288     case ISD::CALLSEQ_END:
289       nested++;
290       break;
291     }
292   }
293   return 0;
294 }
295
296 /// LegalizeAllNodesNotLeadingTo - Recursively walk the uses of N, looking to
297 /// see if any uses can reach Dest.  If no dest operands can get to dest,
298 /// legalize them, legalize ourself, and return false, otherwise, return true.
299 ///
300 /// Keep track of the nodes we fine that actually do lead to Dest in
301 /// NodesLeadingTo.  This avoids retraversing them exponential number of times.
302 ///
303 bool SelectionDAGLegalize::LegalizeAllNodesNotLeadingTo(SDNode *N, SDNode *Dest,
304                                      SmallPtrSet<SDNode*, 32> &NodesLeadingTo) {
305   if (N == Dest) return true;  // N certainly leads to Dest :)
306
307   // If we've already processed this node and it does lead to Dest, there is no
308   // need to reprocess it.
309   if (NodesLeadingTo.count(N)) return true;
310
311   // If the first result of this node has been already legalized, then it cannot
312   // reach N.
313   if (LegalizedNodes.count(SDValue(N, 0))) return false;
314
315   // Okay, this node has not already been legalized.  Check and legalize all
316   // operands.  If none lead to Dest, then we can legalize this node.
317   bool OperandsLeadToDest = false;
318   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
319     OperandsLeadToDest |=     // If an operand leads to Dest, so do we.
320       LegalizeAllNodesNotLeadingTo(N->getOperand(i).getNode(), Dest,
321                                    NodesLeadingTo);
322
323   if (OperandsLeadToDest) {
324     NodesLeadingTo.insert(N);
325     return true;
326   }
327
328   // Okay, this node looks safe, legalize it and return false.
329   LegalizeOp(SDValue(N, 0));
330   return false;
331 }
332
333 /// ExpandConstantFP - Expands the ConstantFP node to an integer constant or
334 /// a load from the constant pool.
335 static SDValue ExpandConstantFP(ConstantFPSDNode *CFP, bool UseCP,
336                                 SelectionDAG &DAG, const TargetLowering &TLI) {
337   bool Extend = false;
338   DebugLoc dl = CFP->getDebugLoc();
339
340   // If a FP immediate is precise when represented as a float and if the
341   // target can do an extending load from float to double, we put it into
342   // the constant pool as a float, even if it's is statically typed as a
343   // double.  This shrinks FP constants and canonicalizes them for targets where
344   // an FP extending load is the same cost as a normal load (such as on the x87
345   // fp stack or PPC FP unit).
346   EVT VT = CFP->getValueType(0);
347   ConstantFP *LLVMC = const_cast<ConstantFP*>(CFP->getConstantFPValue());
348   if (!UseCP) {
349     assert((VT == MVT::f64 || VT == MVT::f32) && "Invalid type expansion");
350     return DAG.getConstant(LLVMC->getValueAPF().bitcastToAPInt(),
351                            (VT == MVT::f64) ? MVT::i64 : MVT::i32);
352   }
353
354   EVT OrigVT = VT;
355   EVT SVT = VT;
356   while (SVT != MVT::f32) {
357     SVT = (MVT::SimpleValueType)(SVT.getSimpleVT().SimpleTy - 1);
358     if (ConstantFPSDNode::isValueValidForType(SVT, CFP->getValueAPF()) &&
359         // Only do this if the target has a native EXTLOAD instruction from
360         // smaller type.
361         TLI.isLoadExtLegal(ISD::EXTLOAD, SVT) &&
362         TLI.ShouldShrinkFPConstant(OrigVT)) {
363       Type *SType = SVT.getTypeForEVT(*DAG.getContext());
364       LLVMC = cast<ConstantFP>(ConstantExpr::getFPTrunc(LLVMC, SType));
365       VT = SVT;
366       Extend = true;
367     }
368   }
369
370   SDValue CPIdx = DAG.getConstantPool(LLVMC, TLI.getPointerTy());
371   unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
372   if (Extend)
373     return DAG.getExtLoad(ISD::EXTLOAD, dl, OrigVT,
374                           DAG.getEntryNode(),
375                           CPIdx, MachinePointerInfo::getConstantPool(),
376                           VT, false, false, Alignment);
377   return DAG.getLoad(OrigVT, dl, DAG.getEntryNode(), CPIdx,
378                      MachinePointerInfo::getConstantPool(), false, false,
379                      Alignment);
380 }
381
382 /// ExpandUnalignedStore - Expands an unaligned store to 2 half-size stores.
383 static
384 SDValue ExpandUnalignedStore(StoreSDNode *ST, SelectionDAG &DAG,
385                              const TargetLowering &TLI) {
386   SDValue Chain = ST->getChain();
387   SDValue Ptr = ST->getBasePtr();
388   SDValue Val = ST->getValue();
389   EVT VT = Val.getValueType();
390   int Alignment = ST->getAlignment();
391   DebugLoc dl = ST->getDebugLoc();
392   if (ST->getMemoryVT().isFloatingPoint() ||
393       ST->getMemoryVT().isVector()) {
394     EVT intVT = EVT::getIntegerVT(*DAG.getContext(), VT.getSizeInBits());
395     if (TLI.isTypeLegal(intVT)) {
396       // Expand to a bitconvert of the value to the integer type of the
397       // same size, then a (misaligned) int store.
398       // FIXME: Does not handle truncating floating point stores!
399       SDValue Result = DAG.getNode(ISD::BITCAST, dl, intVT, Val);
400       return DAG.getStore(Chain, dl, Result, Ptr, ST->getPointerInfo(),
401                           ST->isVolatile(), ST->isNonTemporal(), Alignment);
402     }
403     // Do a (aligned) store to a stack slot, then copy from the stack slot
404     // to the final destination using (unaligned) integer loads and stores.
405     EVT StoredVT = ST->getMemoryVT();
406     EVT RegVT =
407       TLI.getRegisterType(*DAG.getContext(),
408                           EVT::getIntegerVT(*DAG.getContext(),
409                                             StoredVT.getSizeInBits()));
410     unsigned StoredBytes = StoredVT.getSizeInBits() / 8;
411     unsigned RegBytes = RegVT.getSizeInBits() / 8;
412     unsigned NumRegs = (StoredBytes + RegBytes - 1) / RegBytes;
413
414     // Make sure the stack slot is also aligned for the register type.
415     SDValue StackPtr = DAG.CreateStackTemporary(StoredVT, RegVT);
416
417     // Perform the original store, only redirected to the stack slot.
418     SDValue Store = DAG.getTruncStore(Chain, dl,
419                                       Val, StackPtr, MachinePointerInfo(),
420                                       StoredVT, false, false, 0);
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,
429                                  MachinePointerInfo(),
430                                  false, false, 0);
431       // Store it to the final location.  Remember the store.
432       Stores.push_back(DAG.getStore(Load.getValue(1), dl, Load, Ptr,
433                                   ST->getPointerInfo().getWithOffset(Offset),
434                                     ST->isVolatile(), ST->isNonTemporal(),
435                                     MinAlign(ST->getAlignment(), Offset)));
436       // Increment the pointers.
437       Offset += RegBytes;
438       StackPtr = DAG.getNode(ISD::ADD, dl, StackPtr.getValueType(), StackPtr,
439                              Increment);
440       Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
441     }
442
443     // The last store may be partial.  Do a truncating store.  On big-endian
444     // machines this requires an extending load from the stack slot to ensure
445     // that the bits are in the right place.
446     EVT MemVT = EVT::getIntegerVT(*DAG.getContext(),
447                                   8 * (StoredBytes - Offset));
448
449     // Load from the stack slot.
450     SDValue Load = DAG.getExtLoad(ISD::EXTLOAD, dl, RegVT, Store, StackPtr,
451                                   MachinePointerInfo(),
452                                   MemVT, false, false, 0);
453
454     Stores.push_back(DAG.getTruncStore(Load.getValue(1), dl, Load, Ptr,
455                                        ST->getPointerInfo()
456                                          .getWithOffset(Offset),
457                                        MemVT, ST->isVolatile(),
458                                        ST->isNonTemporal(),
459                                        MinAlign(ST->getAlignment(), Offset)));
460     // The order of the stores doesn't matter - say it with a TokenFactor.
461     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, &Stores[0],
462                        Stores.size());
463   }
464   assert(ST->getMemoryVT().isInteger() &&
465          !ST->getMemoryVT().isVector() &&
466          "Unaligned store of unknown type.");
467   // Get the half-size VT
468   EVT NewStoredVT = ST->getMemoryVT().getHalfSizedIntegerVT(*DAG.getContext());
469   int NumBits = NewStoredVT.getSizeInBits();
470   int IncrementSize = NumBits / 8;
471
472   // Divide the stored value in two parts.
473   SDValue ShiftAmount = DAG.getConstant(NumBits,
474                                       TLI.getShiftAmountTy(Val.getValueType()));
475   SDValue Lo = Val;
476   SDValue Hi = DAG.getNode(ISD::SRL, dl, VT, Val, ShiftAmount);
477
478   // Store the two parts
479   SDValue Store1, Store2;
480   Store1 = DAG.getTruncStore(Chain, dl, TLI.isLittleEndian()?Lo:Hi, Ptr,
481                              ST->getPointerInfo(), NewStoredVT,
482                              ST->isVolatile(), ST->isNonTemporal(), Alignment);
483   Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr,
484                     DAG.getConstant(IncrementSize, TLI.getPointerTy()));
485   Alignment = MinAlign(Alignment, IncrementSize);
486   Store2 = DAG.getTruncStore(Chain, dl, TLI.isLittleEndian()?Hi:Lo, Ptr,
487                              ST->getPointerInfo().getWithOffset(IncrementSize),
488                              NewStoredVT, ST->isVolatile(), ST->isNonTemporal(),
489                              Alignment);
490
491   return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Store1, Store2);
492 }
493
494 /// ExpandUnalignedLoad - Expands an unaligned load to 2 half-size loads.
495 static
496 SDValue ExpandUnalignedLoad(LoadSDNode *LD, SelectionDAG &DAG,
497                             const TargetLowering &TLI) {
498   SDValue Chain = LD->getChain();
499   SDValue Ptr = LD->getBasePtr();
500   EVT VT = LD->getValueType(0);
501   EVT LoadedVT = LD->getMemoryVT();
502   DebugLoc dl = LD->getDebugLoc();
503   if (VT.isFloatingPoint() || VT.isVector()) {
504     EVT intVT = EVT::getIntegerVT(*DAG.getContext(), LoadedVT.getSizeInBits());
505     if (TLI.isTypeLegal(intVT)) {
506       // Expand to a (misaligned) integer load of the same size,
507       // then bitconvert to floating point or vector.
508       SDValue newLoad = DAG.getLoad(intVT, dl, Chain, Ptr, LD->getPointerInfo(),
509                                     LD->isVolatile(),
510                                     LD->isNonTemporal(), LD->getAlignment());
511       SDValue Result = DAG.getNode(ISD::BITCAST, dl, LoadedVT, newLoad);
512       if (VT.isFloatingPoint() && LoadedVT != VT)
513         Result = DAG.getNode(ISD::FP_EXTEND, dl, VT, Result);
514
515       SDValue Ops[] = { Result, Chain };
516       return DAG.getMergeValues(Ops, 2, dl);
517     }
518
519     // Copy the value to a (aligned) stack slot using (unaligned) integer
520     // loads and stores, then do a (aligned) load from the stack slot.
521     EVT RegVT = TLI.getRegisterType(*DAG.getContext(), intVT);
522     unsigned LoadedBytes = LoadedVT.getSizeInBits() / 8;
523     unsigned RegBytes = RegVT.getSizeInBits() / 8;
524     unsigned NumRegs = (LoadedBytes + RegBytes - 1) / RegBytes;
525
526     // Make sure the stack slot is also aligned for the register type.
527     SDValue StackBase = DAG.CreateStackTemporary(LoadedVT, RegVT);
528
529     SDValue Increment = DAG.getConstant(RegBytes, TLI.getPointerTy());
530     SmallVector<SDValue, 8> Stores;
531     SDValue StackPtr = StackBase;
532     unsigned Offset = 0;
533
534     // Do all but one copies using the full register width.
535     for (unsigned i = 1; i < NumRegs; i++) {
536       // Load one integer register's worth from the original location.
537       SDValue Load = DAG.getLoad(RegVT, dl, Chain, Ptr,
538                                  LD->getPointerInfo().getWithOffset(Offset),
539                                  LD->isVolatile(), LD->isNonTemporal(),
540                                  MinAlign(LD->getAlignment(), Offset));
541       // Follow the load with a store to the stack slot.  Remember the store.
542       Stores.push_back(DAG.getStore(Load.getValue(1), dl, Load, StackPtr,
543                                     MachinePointerInfo(), false, false, 0));
544       // Increment the pointers.
545       Offset += RegBytes;
546       Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
547       StackPtr = DAG.getNode(ISD::ADD, dl, StackPtr.getValueType(), StackPtr,
548                              Increment);
549     }
550
551     // The last copy may be partial.  Do an extending load.
552     EVT MemVT = EVT::getIntegerVT(*DAG.getContext(),
553                                   8 * (LoadedBytes - Offset));
554     SDValue Load = DAG.getExtLoad(ISD::EXTLOAD, dl, RegVT, Chain, Ptr,
555                                   LD->getPointerInfo().getWithOffset(Offset),
556                                   MemVT, LD->isVolatile(),
557                                   LD->isNonTemporal(),
558                                   MinAlign(LD->getAlignment(), Offset));
559     // Follow the load with a store to the stack slot.  Remember the store.
560     // On big-endian machines this requires a truncating store to ensure
561     // that the bits end up in the right place.
562     Stores.push_back(DAG.getTruncStore(Load.getValue(1), dl, Load, StackPtr,
563                                        MachinePointerInfo(), MemVT,
564                                        false, false, 0));
565
566     // The order of the stores doesn't matter - say it with a TokenFactor.
567     SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, &Stores[0],
568                              Stores.size());
569
570     // Finally, perform the original load only redirected to the stack slot.
571     Load = DAG.getExtLoad(LD->getExtensionType(), dl, VT, TF, StackBase,
572                           MachinePointerInfo(), LoadedVT, false, false, 0);
573
574     // Callers expect a MERGE_VALUES node.
575     SDValue Ops[] = { Load, TF };
576     return DAG.getMergeValues(Ops, 2, dl);
577   }
578   assert(LoadedVT.isInteger() && !LoadedVT.isVector() &&
579          "Unaligned load of unsupported type.");
580
581   // Compute the new VT that is half the size of the old one.  This is an
582   // integer MVT.
583   unsigned NumBits = LoadedVT.getSizeInBits();
584   EVT NewLoadedVT;
585   NewLoadedVT = EVT::getIntegerVT(*DAG.getContext(), NumBits/2);
586   NumBits >>= 1;
587
588   unsigned Alignment = LD->getAlignment();
589   unsigned IncrementSize = NumBits / 8;
590   ISD::LoadExtType HiExtType = LD->getExtensionType();
591
592   // If the original load is NON_EXTLOAD, the hi part load must be ZEXTLOAD.
593   if (HiExtType == ISD::NON_EXTLOAD)
594     HiExtType = ISD::ZEXTLOAD;
595
596   // Load the value in two parts
597   SDValue Lo, Hi;
598   if (TLI.isLittleEndian()) {
599     Lo = DAG.getExtLoad(ISD::ZEXTLOAD, dl, VT, Chain, Ptr, LD->getPointerInfo(),
600                         NewLoadedVT, LD->isVolatile(),
601                         LD->isNonTemporal(), Alignment);
602     Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr,
603                       DAG.getConstant(IncrementSize, TLI.getPointerTy()));
604     Hi = DAG.getExtLoad(HiExtType, dl, VT, Chain, Ptr,
605                         LD->getPointerInfo().getWithOffset(IncrementSize),
606                         NewLoadedVT, LD->isVolatile(),
607                         LD->isNonTemporal(), MinAlign(Alignment,IncrementSize));
608   } else {
609     Hi = DAG.getExtLoad(HiExtType, dl, VT, Chain, Ptr, LD->getPointerInfo(),
610                         NewLoadedVT, LD->isVolatile(),
611                         LD->isNonTemporal(), Alignment);
612     Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr,
613                       DAG.getConstant(IncrementSize, TLI.getPointerTy()));
614     Lo = DAG.getExtLoad(ISD::ZEXTLOAD, dl, VT, Chain, Ptr,
615                         LD->getPointerInfo().getWithOffset(IncrementSize),
616                         NewLoadedVT, LD->isVolatile(),
617                         LD->isNonTemporal(), MinAlign(Alignment,IncrementSize));
618   }
619
620   // aggregate the two parts
621   SDValue ShiftAmount = DAG.getConstant(NumBits,
622                                        TLI.getShiftAmountTy(Hi.getValueType()));
623   SDValue Result = DAG.getNode(ISD::SHL, dl, VT, Hi, ShiftAmount);
624   Result = DAG.getNode(ISD::OR, dl, VT, Result, Lo);
625
626   SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Lo.getValue(1),
627                              Hi.getValue(1));
628
629   SDValue Ops[] = { Result, TF };
630   return DAG.getMergeValues(Ops, 2, dl);
631 }
632
633 /// PerformInsertVectorEltInMemory - Some target cannot handle a variable
634 /// insertion index for the INSERT_VECTOR_ELT instruction.  In this case, it
635 /// is necessary to spill the vector being inserted into to memory, perform
636 /// the insert there, and then read the result back.
637 SDValue SelectionDAGLegalize::
638 PerformInsertVectorEltInMemory(SDValue Vec, SDValue Val, SDValue Idx,
639                                DebugLoc dl) {
640   SDValue Tmp1 = Vec;
641   SDValue Tmp2 = Val;
642   SDValue Tmp3 = Idx;
643
644   // If the target doesn't support this, we have to spill the input vector
645   // to a temporary stack slot, update the element, then reload it.  This is
646   // badness.  We could also load the value into a vector register (either
647   // with a "move to register" or "extload into register" instruction, then
648   // permute it into place, if the idx is a constant and if the idx is
649   // supported by the target.
650   EVT VT    = Tmp1.getValueType();
651   EVT EltVT = VT.getVectorElementType();
652   EVT IdxVT = Tmp3.getValueType();
653   EVT PtrVT = TLI.getPointerTy();
654   SDValue StackPtr = DAG.CreateStackTemporary(VT);
655
656   int SPFI = cast<FrameIndexSDNode>(StackPtr.getNode())->getIndex();
657
658   // Store the vector.
659   SDValue Ch = DAG.getStore(DAG.getEntryNode(), dl, Tmp1, StackPtr,
660                             MachinePointerInfo::getFixedStack(SPFI),
661                             false, false, 0);
662
663   // Truncate or zero extend offset to target pointer type.
664   unsigned CastOpc = IdxVT.bitsGT(PtrVT) ? ISD::TRUNCATE : ISD::ZERO_EXTEND;
665   Tmp3 = DAG.getNode(CastOpc, dl, PtrVT, Tmp3);
666   // Add the offset to the index.
667   unsigned EltSize = EltVT.getSizeInBits()/8;
668   Tmp3 = DAG.getNode(ISD::MUL, dl, IdxVT, Tmp3,DAG.getConstant(EltSize, IdxVT));
669   SDValue StackPtr2 = DAG.getNode(ISD::ADD, dl, IdxVT, Tmp3, StackPtr);
670   // Store the scalar value.
671   Ch = DAG.getTruncStore(Ch, dl, Tmp2, StackPtr2, MachinePointerInfo(), EltVT,
672                          false, false, 0);
673   // Load the updated vector.
674   return DAG.getLoad(VT, dl, Ch, StackPtr,
675                      MachinePointerInfo::getFixedStack(SPFI), false, false, 0);
676 }
677
678
679 SDValue SelectionDAGLegalize::
680 ExpandINSERT_VECTOR_ELT(SDValue Vec, SDValue Val, SDValue Idx, DebugLoc dl) {
681   if (ConstantSDNode *InsertPos = dyn_cast<ConstantSDNode>(Idx)) {
682     // SCALAR_TO_VECTOR requires that the type of the value being inserted
683     // match the element type of the vector being created, except for
684     // integers in which case the inserted value can be over width.
685     EVT EltVT = Vec.getValueType().getVectorElementType();
686     if (Val.getValueType() == EltVT ||
687         (EltVT.isInteger() && Val.getValueType().bitsGE(EltVT))) {
688       SDValue ScVec = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
689                                   Vec.getValueType(), Val);
690
691       unsigned NumElts = Vec.getValueType().getVectorNumElements();
692       // We generate a shuffle of InVec and ScVec, so the shuffle mask
693       // should be 0,1,2,3,4,5... with the appropriate element replaced with
694       // elt 0 of the RHS.
695       SmallVector<int, 8> ShufOps;
696       for (unsigned i = 0; i != NumElts; ++i)
697         ShufOps.push_back(i != InsertPos->getZExtValue() ? i : NumElts);
698
699       return DAG.getVectorShuffle(Vec.getValueType(), dl, Vec, ScVec,
700                                   &ShufOps[0]);
701     }
702   }
703   return PerformInsertVectorEltInMemory(Vec, Val, Idx, dl);
704 }
705
706 SDValue SelectionDAGLegalize::OptimizeFloatStore(StoreSDNode* ST) {
707   // Turn 'store float 1.0, Ptr' -> 'store int 0x12345678, Ptr'
708   // FIXME: We shouldn't do this for TargetConstantFP's.
709   // FIXME: move this to the DAG Combiner!  Note that we can't regress due
710   // to phase ordering between legalized code and the dag combiner.  This
711   // probably means that we need to integrate dag combiner and legalizer
712   // together.
713   // We generally can't do this one for long doubles.
714   SDValue Tmp1 = ST->getChain();
715   SDValue Tmp2 = ST->getBasePtr();
716   SDValue Tmp3;
717   unsigned Alignment = ST->getAlignment();
718   bool isVolatile = ST->isVolatile();
719   bool isNonTemporal = ST->isNonTemporal();
720   DebugLoc dl = ST->getDebugLoc();
721   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(ST->getValue())) {
722     if (CFP->getValueType(0) == MVT::f32 &&
723         TLI.isTypeLegal(MVT::i32)) {
724       Tmp3 = DAG.getConstant(CFP->getValueAPF().
725                                       bitcastToAPInt().zextOrTrunc(32),
726                               MVT::i32);
727       return DAG.getStore(Tmp1, dl, Tmp3, Tmp2, ST->getPointerInfo(),
728                           isVolatile, isNonTemporal, Alignment);
729     }
730
731     if (CFP->getValueType(0) == MVT::f64) {
732       // If this target supports 64-bit registers, do a single 64-bit store.
733       if (TLI.isTypeLegal(MVT::i64)) {
734         Tmp3 = DAG.getConstant(CFP->getValueAPF().bitcastToAPInt().
735                                   zextOrTrunc(64), MVT::i64);
736         return DAG.getStore(Tmp1, dl, Tmp3, Tmp2, ST->getPointerInfo(),
737                             isVolatile, isNonTemporal, Alignment);
738       }
739
740       if (TLI.isTypeLegal(MVT::i32) && !ST->isVolatile()) {
741         // Otherwise, if the target supports 32-bit registers, use 2 32-bit
742         // stores.  If the target supports neither 32- nor 64-bits, this
743         // xform is certainly not worth it.
744         const APInt &IntVal =CFP->getValueAPF().bitcastToAPInt();
745         SDValue Lo = DAG.getConstant(IntVal.trunc(32), MVT::i32);
746         SDValue Hi = DAG.getConstant(IntVal.lshr(32).trunc(32), MVT::i32);
747         if (TLI.isBigEndian()) std::swap(Lo, Hi);
748
749         Lo = DAG.getStore(Tmp1, dl, Lo, Tmp2, ST->getPointerInfo(), isVolatile,
750                           isNonTemporal, Alignment);
751         Tmp2 = DAG.getNode(ISD::ADD, dl, Tmp2.getValueType(), Tmp2,
752                             DAG.getIntPtrConstant(4));
753         Hi = DAG.getStore(Tmp1, dl, Hi, Tmp2,
754                           ST->getPointerInfo().getWithOffset(4),
755                           isVolatile, isNonTemporal, MinAlign(Alignment, 4U));
756
757         return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Lo, Hi);
758       }
759     }
760   }
761   return SDValue(0, 0);
762 }
763
764 /// LegalizeOp - Return a legal replacement for the given operation, with
765 /// all legal operands.
766 SDValue SelectionDAGLegalize::LegalizeOp(SDValue Op) {
767   if (Op.getOpcode() == ISD::TargetConstant) // Allow illegal target nodes.
768     return Op;
769
770   SDNode *Node = Op.getNode();
771   DebugLoc dl = Node->getDebugLoc();
772
773   for (unsigned i = 0, e = Node->getNumValues(); i != e; ++i)
774     assert(TLI.getTypeAction(*DAG.getContext(), Node->getValueType(i)) ==
775              TargetLowering::TypeLegal &&
776            "Unexpected illegal type!");
777
778   for (unsigned i = 0, e = Node->getNumOperands(); i != e; ++i)
779     assert((TLI.getTypeAction(*DAG.getContext(),
780                               Node->getOperand(i).getValueType()) ==
781               TargetLowering::TypeLegal ||
782             Node->getOperand(i).getOpcode() == ISD::TargetConstant) &&
783            "Unexpected illegal type!");
784
785   // Note that LegalizeOp may be reentered even from single-use nodes, which
786   // means that we always must cache transformed nodes.
787   DenseMap<SDValue, SDValue>::iterator I = LegalizedNodes.find(Op);
788   if (I != LegalizedNodes.end()) return I->second;
789
790   SDValue Tmp1, Tmp2, Tmp3, Tmp4;
791   SDValue Result = Op;
792   bool isCustom = false;
793
794   // Figure out the correct action; the way to query this varies by opcode
795   TargetLowering::LegalizeAction Action = TargetLowering::Legal;
796   bool SimpleFinishLegalizing = true;
797   switch (Node->getOpcode()) {
798   case ISD::INTRINSIC_W_CHAIN:
799   case ISD::INTRINSIC_WO_CHAIN:
800   case ISD::INTRINSIC_VOID:
801   case ISD::VAARG:
802   case ISD::STACKSAVE:
803     Action = TLI.getOperationAction(Node->getOpcode(), MVT::Other);
804     break;
805   case ISD::SINT_TO_FP:
806   case ISD::UINT_TO_FP:
807   case ISD::EXTRACT_VECTOR_ELT:
808     Action = TLI.getOperationAction(Node->getOpcode(),
809                                     Node->getOperand(0).getValueType());
810     break;
811   case ISD::FP_ROUND_INREG:
812   case ISD::SIGN_EXTEND_INREG: {
813     EVT InnerType = cast<VTSDNode>(Node->getOperand(1))->getVT();
814     Action = TLI.getOperationAction(Node->getOpcode(), InnerType);
815     break;
816   }
817   case ISD::ATOMIC_STORE: {
818     Action = TLI.getOperationAction(Node->getOpcode(),
819                                     Node->getOperand(2).getValueType());
820     break;
821   }
822   case ISD::SELECT_CC:
823   case ISD::SETCC:
824   case ISD::BR_CC: {
825     unsigned CCOperand = Node->getOpcode() == ISD::SELECT_CC ? 4 :
826                          Node->getOpcode() == ISD::SETCC ? 2 : 1;
827     unsigned CompareOperand = Node->getOpcode() == ISD::BR_CC ? 2 : 0;
828     EVT OpVT = Node->getOperand(CompareOperand).getValueType();
829     ISD::CondCode CCCode =
830         cast<CondCodeSDNode>(Node->getOperand(CCOperand))->get();
831     Action = TLI.getCondCodeAction(CCCode, OpVT);
832     if (Action == TargetLowering::Legal) {
833       if (Node->getOpcode() == ISD::SELECT_CC)
834         Action = TLI.getOperationAction(Node->getOpcode(),
835                                         Node->getValueType(0));
836       else
837         Action = TLI.getOperationAction(Node->getOpcode(), OpVT);
838     }
839     break;
840   }
841   case ISD::LOAD:
842   case ISD::STORE:
843     // FIXME: Model these properly.  LOAD and STORE are complicated, and
844     // STORE expects the unlegalized operand in some cases.
845     SimpleFinishLegalizing = false;
846     break;
847   case ISD::CALLSEQ_START:
848   case ISD::CALLSEQ_END:
849     // FIXME: This shouldn't be necessary.  These nodes have special properties
850     // dealing with the recursive nature of legalization.  Removing this
851     // special case should be done as part of making LegalizeDAG non-recursive.
852     SimpleFinishLegalizing = false;
853     break;
854   case ISD::EXTRACT_ELEMENT:
855   case ISD::FLT_ROUNDS_:
856   case ISD::SADDO:
857   case ISD::SSUBO:
858   case ISD::UADDO:
859   case ISD::USUBO:
860   case ISD::SMULO:
861   case ISD::UMULO:
862   case ISD::FPOWI:
863   case ISD::MERGE_VALUES:
864   case ISD::EH_RETURN:
865   case ISD::FRAME_TO_ARGS_OFFSET:
866   case ISD::EH_SJLJ_SETJMP:
867   case ISD::EH_SJLJ_LONGJMP:
868   case ISD::EH_SJLJ_DISPATCHSETUP:
869     // These operations lie about being legal: when they claim to be legal,
870     // they should actually be expanded.
871     Action = TLI.getOperationAction(Node->getOpcode(), Node->getValueType(0));
872     if (Action == TargetLowering::Legal)
873       Action = TargetLowering::Expand;
874     break;
875   case ISD::TRAMPOLINE:
876   case ISD::FRAMEADDR:
877   case ISD::RETURNADDR:
878     // These operations lie about being legal: when they claim to be legal,
879     // they should actually be custom-lowered.
880     Action = TLI.getOperationAction(Node->getOpcode(), Node->getValueType(0));
881     if (Action == TargetLowering::Legal)
882       Action = TargetLowering::Custom;
883     break;
884   case ISD::BUILD_VECTOR:
885     // A weird case: legalization for BUILD_VECTOR never legalizes the
886     // operands!
887     // FIXME: This really sucks... changing it isn't semantically incorrect,
888     // but it massively pessimizes the code for floating-point BUILD_VECTORs
889     // because ConstantFP operands get legalized into constant pool loads
890     // before the BUILD_VECTOR code can see them.  It doesn't usually bite,
891     // though, because BUILD_VECTORS usually get lowered into other nodes
892     // which get legalized properly.
893     SimpleFinishLegalizing = false;
894     break;
895   default:
896     if (Node->getOpcode() >= ISD::BUILTIN_OP_END) {
897       Action = TargetLowering::Legal;
898     } else {
899       Action = TLI.getOperationAction(Node->getOpcode(), Node->getValueType(0));
900     }
901     break;
902   }
903
904   if (SimpleFinishLegalizing) {
905     SmallVector<SDValue, 8> Ops, ResultVals;
906     for (unsigned i = 0, e = Node->getNumOperands(); i != e; ++i)
907       Ops.push_back(LegalizeOp(Node->getOperand(i)));
908     switch (Node->getOpcode()) {
909     default: break;
910     case ISD::BR:
911     case ISD::BRIND:
912     case ISD::BR_JT:
913     case ISD::BR_CC:
914     case ISD::BRCOND:
915       // Branches tweak the chain to include LastCALLSEQ_END
916       Ops[0] = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Ops[0],
917                            LastCALLSEQ_END);
918       Ops[0] = LegalizeOp(Ops[0]);
919       LastCALLSEQ_END = DAG.getEntryNode();
920       break;
921     case ISD::SHL:
922     case ISD::SRL:
923     case ISD::SRA:
924     case ISD::ROTL:
925     case ISD::ROTR:
926       // Legalizing shifts/rotates requires adjusting the shift amount
927       // to the appropriate width.
928       if (!Ops[1].getValueType().isVector())
929         Ops[1] = LegalizeOp(DAG.getShiftAmountOperand(Ops[0].getValueType(),
930                                                       Ops[1]));
931       break;
932     case ISD::SRL_PARTS:
933     case ISD::SRA_PARTS:
934     case ISD::SHL_PARTS:
935       // Legalizing shifts/rotates requires adjusting the shift amount
936       // to the appropriate width.
937       if (!Ops[2].getValueType().isVector())
938         Ops[2] = LegalizeOp(DAG.getShiftAmountOperand(Ops[0].getValueType(),
939                                                       Ops[2]));
940       break;
941     }
942
943     Result = SDValue(DAG.UpdateNodeOperands(Result.getNode(), Ops.data(),
944                                             Ops.size()), 0);
945     switch (Action) {
946     case TargetLowering::Legal:
947       for (unsigned i = 0, e = Node->getNumValues(); i != e; ++i)
948         ResultVals.push_back(Result.getValue(i));
949       break;
950     case TargetLowering::Custom:
951       // FIXME: The handling for custom lowering with multiple results is
952       // a complete mess.
953       Tmp1 = TLI.LowerOperation(Result, DAG);
954       if (Tmp1.getNode()) {
955         for (unsigned i = 0, e = Node->getNumValues(); i != e; ++i) {
956           if (e == 1)
957             ResultVals.push_back(Tmp1);
958           else
959             ResultVals.push_back(Tmp1.getValue(i));
960         }
961         break;
962       }
963
964       // FALL THROUGH
965     case TargetLowering::Expand:
966       ExpandNode(Result.getNode(), ResultVals);
967       break;
968     case TargetLowering::Promote:
969       PromoteNode(Result.getNode(), ResultVals);
970       break;
971     }
972     if (!ResultVals.empty()) {
973       for (unsigned i = 0, e = ResultVals.size(); i != e; ++i) {
974         if (ResultVals[i] != SDValue(Node, i))
975           ResultVals[i] = LegalizeOp(ResultVals[i]);
976         AddLegalizedOperand(SDValue(Node, i), ResultVals[i]);
977       }
978       return ResultVals[Op.getResNo()];
979     }
980   }
981
982   switch (Node->getOpcode()) {
983   default:
984 #ifndef NDEBUG
985     dbgs() << "NODE: ";
986     Node->dump( &DAG);
987     dbgs() << "\n";
988 #endif
989     assert(0 && "Do not know how to legalize this operator!");
990
991   case ISD::BUILD_VECTOR:
992     switch (TLI.getOperationAction(ISD::BUILD_VECTOR, Node->getValueType(0))) {
993     default: assert(0 && "This action is not supported yet!");
994     case TargetLowering::Custom:
995       Tmp3 = TLI.LowerOperation(Result, DAG);
996       if (Tmp3.getNode()) {
997         Result = Tmp3;
998         break;
999       }
1000       // FALLTHROUGH
1001     case TargetLowering::Expand:
1002       Result = ExpandBUILD_VECTOR(Result.getNode());
1003       break;
1004     }
1005     break;
1006   case ISD::CALLSEQ_START: {
1007     SDNode *CallEnd = FindCallEndFromCallStart(Node);
1008
1009     // Recursively Legalize all of the inputs of the call end that do not lead
1010     // to this call start.  This ensures that any libcalls that need be inserted
1011     // are inserted *before* the CALLSEQ_START.
1012     {SmallPtrSet<SDNode*, 32> NodesLeadingTo;
1013     for (unsigned i = 0, e = CallEnd->getNumOperands(); i != e; ++i)
1014       LegalizeAllNodesNotLeadingTo(CallEnd->getOperand(i).getNode(), Node,
1015                                    NodesLeadingTo);
1016     }
1017
1018     // Now that we have legalized all of the inputs (which may have inserted
1019     // libcalls), create the new CALLSEQ_START node.
1020     Tmp1 = LegalizeOp(Node->getOperand(0));  // Legalize the chain.
1021
1022     // Merge in the last call to ensure that this call starts after the last
1023     // call ended.
1024     if (LastCALLSEQ_END.getOpcode() != ISD::EntryToken) {
1025       Tmp1 = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
1026                          Tmp1, LastCALLSEQ_END);
1027       Tmp1 = LegalizeOp(Tmp1);
1028     }
1029
1030     // Do not try to legalize the target-specific arguments (#1+).
1031     if (Tmp1 != Node->getOperand(0)) {
1032       SmallVector<SDValue, 8> Ops(Node->op_begin(), Node->op_end());
1033       Ops[0] = Tmp1;
1034       Result = SDValue(DAG.UpdateNodeOperands(Result.getNode(), &Ops[0],
1035                                               Ops.size()), Result.getResNo());
1036     }
1037
1038     // Remember that the CALLSEQ_START is legalized.
1039     AddLegalizedOperand(Op.getValue(0), Result);
1040     if (Node->getNumValues() == 2)    // If this has a flag result, remember it.
1041       AddLegalizedOperand(Op.getValue(1), Result.getValue(1));
1042
1043     // Now that the callseq_start and all of the non-call nodes above this call
1044     // sequence have been legalized, legalize the call itself.  During this
1045     // process, no libcalls can/will be inserted, guaranteeing that no calls
1046     // can overlap.
1047     assert(!IsLegalizingCall && "Inconsistent sequentialization of calls!");
1048     // Note that we are selecting this call!
1049     LastCALLSEQ_END = SDValue(CallEnd, 0);
1050     IsLegalizingCall = true;
1051
1052     // Legalize the call, starting from the CALLSEQ_END.
1053     LegalizeOp(LastCALLSEQ_END);
1054     assert(!IsLegalizingCall && "CALLSEQ_END should have cleared this!");
1055     return Result;
1056   }
1057   case ISD::CALLSEQ_END:
1058     // If the CALLSEQ_START node hasn't been legalized first, legalize it.  This
1059     // will cause this node to be legalized as well as handling libcalls right.
1060     if (LastCALLSEQ_END.getNode() != Node) {
1061       LegalizeOp(SDValue(FindCallStartFromCallEnd(Node), 0));
1062       DenseMap<SDValue, SDValue>::iterator I = LegalizedNodes.find(Op);
1063       assert(I != LegalizedNodes.end() &&
1064              "Legalizing the call start should have legalized this node!");
1065       return I->second;
1066     }
1067
1068     // Otherwise, the call start has been legalized and everything is going
1069     // according to plan.  Just legalize ourselves normally here.
1070     Tmp1 = LegalizeOp(Node->getOperand(0));  // Legalize the chain.
1071     // Do not try to legalize the target-specific arguments (#1+), except for
1072     // an optional flag input.
1073     if (Node->getOperand(Node->getNumOperands()-1).getValueType() != MVT::Glue){
1074       if (Tmp1 != Node->getOperand(0)) {
1075         SmallVector<SDValue, 8> Ops(Node->op_begin(), Node->op_end());
1076         Ops[0] = Tmp1;
1077         Result = SDValue(DAG.UpdateNodeOperands(Result.getNode(),
1078                                                 &Ops[0], Ops.size()),
1079                          Result.getResNo());
1080       }
1081     } else {
1082       Tmp2 = LegalizeOp(Node->getOperand(Node->getNumOperands()-1));
1083       if (Tmp1 != Node->getOperand(0) ||
1084           Tmp2 != Node->getOperand(Node->getNumOperands()-1)) {
1085         SmallVector<SDValue, 8> Ops(Node->op_begin(), Node->op_end());
1086         Ops[0] = Tmp1;
1087         Ops.back() = Tmp2;
1088         Result = SDValue(DAG.UpdateNodeOperands(Result.getNode(),
1089                                                 &Ops[0], Ops.size()),
1090                          Result.getResNo());
1091       }
1092     }
1093     assert(IsLegalizingCall && "Call sequence imbalance between start/end?");
1094     // This finishes up call legalization.
1095     IsLegalizingCall = false;
1096
1097     // If the CALLSEQ_END node has a flag, remember that we legalized it.
1098     AddLegalizedOperand(SDValue(Node, 0), Result.getValue(0));
1099     if (Node->getNumValues() == 2)
1100       AddLegalizedOperand(SDValue(Node, 1), Result.getValue(1));
1101     return Result.getValue(Op.getResNo());
1102   case ISD::LOAD: {
1103     LoadSDNode *LD = cast<LoadSDNode>(Node);
1104     Tmp1 = LegalizeOp(LD->getChain());   // Legalize the chain.
1105     Tmp2 = LegalizeOp(LD->getBasePtr()); // Legalize the base pointer.
1106
1107     ISD::LoadExtType ExtType = LD->getExtensionType();
1108     if (ExtType == ISD::NON_EXTLOAD) {
1109       EVT VT = Node->getValueType(0);
1110       Result = SDValue(DAG.UpdateNodeOperands(Result.getNode(),
1111                                               Tmp1, Tmp2, LD->getOffset()),
1112                        Result.getResNo());
1113       Tmp3 = Result.getValue(0);
1114       Tmp4 = Result.getValue(1);
1115
1116       switch (TLI.getOperationAction(Node->getOpcode(), VT)) {
1117       default: assert(0 && "This action is not supported yet!");
1118       case TargetLowering::Legal:
1119         // If this is an unaligned load and the target doesn't support it,
1120         // expand it.
1121         if (!TLI.allowsUnalignedMemoryAccesses(LD->getMemoryVT())) {
1122           Type *Ty = LD->getMemoryVT().getTypeForEVT(*DAG.getContext());
1123           unsigned ABIAlignment = TLI.getTargetData()->getABITypeAlignment(Ty);
1124           if (LD->getAlignment() < ABIAlignment){
1125             Result = ExpandUnalignedLoad(cast<LoadSDNode>(Result.getNode()),
1126                                          DAG, TLI);
1127             Tmp3 = Result.getOperand(0);
1128             Tmp4 = Result.getOperand(1);
1129             Tmp3 = LegalizeOp(Tmp3);
1130             Tmp4 = LegalizeOp(Tmp4);
1131           }
1132         }
1133         break;
1134       case TargetLowering::Custom:
1135         Tmp1 = TLI.LowerOperation(Tmp3, DAG);
1136         if (Tmp1.getNode()) {
1137           Tmp3 = LegalizeOp(Tmp1);
1138           Tmp4 = LegalizeOp(Tmp1.getValue(1));
1139         }
1140         break;
1141       case TargetLowering::Promote: {
1142         // Only promote a load of vector type to another.
1143         assert(VT.isVector() && "Cannot promote this load!");
1144         // Change base type to a different vector type.
1145         EVT NVT = TLI.getTypeToPromoteTo(Node->getOpcode(), VT);
1146
1147         Tmp1 = DAG.getLoad(NVT, dl, Tmp1, Tmp2, LD->getPointerInfo(),
1148                            LD->isVolatile(), LD->isNonTemporal(),
1149                            LD->getAlignment());
1150         Tmp3 = LegalizeOp(DAG.getNode(ISD::BITCAST, dl, VT, Tmp1));
1151         Tmp4 = LegalizeOp(Tmp1.getValue(1));
1152         break;
1153       }
1154       }
1155       // Since loads produce two values, make sure to remember that we
1156       // legalized both of them.
1157       AddLegalizedOperand(SDValue(Node, 0), Tmp3);
1158       AddLegalizedOperand(SDValue(Node, 1), Tmp4);
1159       return Op.getResNo() ? Tmp4 : Tmp3;
1160     }
1161
1162     EVT SrcVT = LD->getMemoryVT();
1163     unsigned SrcWidth = SrcVT.getSizeInBits();
1164     unsigned Alignment = LD->getAlignment();
1165     bool isVolatile = LD->isVolatile();
1166     bool isNonTemporal = LD->isNonTemporal();
1167
1168     if (SrcWidth != SrcVT.getStoreSizeInBits() &&
1169         // Some targets pretend to have an i1 loading operation, and actually
1170         // load an i8.  This trick is correct for ZEXTLOAD because the top 7
1171         // bits are guaranteed to be zero; it helps the optimizers understand
1172         // that these bits are zero.  It is also useful for EXTLOAD, since it
1173         // tells the optimizers that those bits are undefined.  It would be
1174         // nice to have an effective generic way of getting these benefits...
1175         // Until such a way is found, don't insist on promoting i1 here.
1176         (SrcVT != MVT::i1 ||
1177          TLI.getLoadExtAction(ExtType, MVT::i1) == TargetLowering::Promote)) {
1178       // Promote to a byte-sized load if not loading an integral number of
1179       // bytes.  For example, promote EXTLOAD:i20 -> EXTLOAD:i24.
1180       unsigned NewWidth = SrcVT.getStoreSizeInBits();
1181       EVT NVT = EVT::getIntegerVT(*DAG.getContext(), NewWidth);
1182       SDValue Ch;
1183
1184       // The extra bits are guaranteed to be zero, since we stored them that
1185       // way.  A zext load from NVT thus automatically gives zext from SrcVT.
1186
1187       ISD::LoadExtType NewExtType =
1188         ExtType == ISD::ZEXTLOAD ? ISD::ZEXTLOAD : ISD::EXTLOAD;
1189
1190       Result = DAG.getExtLoad(NewExtType, dl, Node->getValueType(0),
1191                               Tmp1, Tmp2, LD->getPointerInfo(),
1192                               NVT, isVolatile, isNonTemporal, Alignment);
1193
1194       Ch = Result.getValue(1); // The chain.
1195
1196       if (ExtType == ISD::SEXTLOAD)
1197         // Having the top bits zero doesn't help when sign extending.
1198         Result = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl,
1199                              Result.getValueType(),
1200                              Result, DAG.getValueType(SrcVT));
1201       else if (ExtType == ISD::ZEXTLOAD || NVT == Result.getValueType())
1202         // All the top bits are guaranteed to be zero - inform the optimizers.
1203         Result = DAG.getNode(ISD::AssertZext, dl,
1204                              Result.getValueType(), Result,
1205                              DAG.getValueType(SrcVT));
1206
1207       Tmp1 = LegalizeOp(Result);
1208       Tmp2 = LegalizeOp(Ch);
1209     } else if (SrcWidth & (SrcWidth - 1)) {
1210       // If not loading a power-of-2 number of bits, expand as two loads.
1211       assert(!SrcVT.isVector() && "Unsupported extload!");
1212       unsigned RoundWidth = 1 << Log2_32(SrcWidth);
1213       assert(RoundWidth < SrcWidth);
1214       unsigned ExtraWidth = SrcWidth - RoundWidth;
1215       assert(ExtraWidth < RoundWidth);
1216       assert(!(RoundWidth % 8) && !(ExtraWidth % 8) &&
1217              "Load size not an integral number of bytes!");
1218       EVT RoundVT = EVT::getIntegerVT(*DAG.getContext(), RoundWidth);
1219       EVT ExtraVT = EVT::getIntegerVT(*DAG.getContext(), ExtraWidth);
1220       SDValue Lo, Hi, Ch;
1221       unsigned IncrementSize;
1222
1223       if (TLI.isLittleEndian()) {
1224         // EXTLOAD:i24 -> ZEXTLOAD:i16 | (shl EXTLOAD@+2:i8, 16)
1225         // Load the bottom RoundWidth bits.
1226         Lo = DAG.getExtLoad(ISD::ZEXTLOAD, dl, Node->getValueType(0),
1227                             Tmp1, Tmp2,
1228                             LD->getPointerInfo(), RoundVT, isVolatile,
1229                             isNonTemporal, Alignment);
1230
1231         // Load the remaining ExtraWidth bits.
1232         IncrementSize = RoundWidth / 8;
1233         Tmp2 = DAG.getNode(ISD::ADD, dl, Tmp2.getValueType(), Tmp2,
1234                            DAG.getIntPtrConstant(IncrementSize));
1235         Hi = DAG.getExtLoad(ExtType, dl, Node->getValueType(0), Tmp1, Tmp2,
1236                             LD->getPointerInfo().getWithOffset(IncrementSize),
1237                             ExtraVT, isVolatile, isNonTemporal,
1238                             MinAlign(Alignment, IncrementSize));
1239
1240         // Build a factor node to remember that this load is independent of
1241         // the other one.
1242         Ch = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Lo.getValue(1),
1243                          Hi.getValue(1));
1244
1245         // Move the top bits to the right place.
1246         Hi = DAG.getNode(ISD::SHL, dl, Hi.getValueType(), Hi,
1247                          DAG.getConstant(RoundWidth,
1248                                       TLI.getShiftAmountTy(Hi.getValueType())));
1249
1250         // Join the hi and lo parts.
1251         Result = DAG.getNode(ISD::OR, dl, Node->getValueType(0), Lo, Hi);
1252       } else {
1253         // Big endian - avoid unaligned loads.
1254         // EXTLOAD:i24 -> (shl EXTLOAD:i16, 8) | ZEXTLOAD@+2:i8
1255         // Load the top RoundWidth bits.
1256         Hi = DAG.getExtLoad(ExtType, dl, Node->getValueType(0), Tmp1, Tmp2,
1257                             LD->getPointerInfo(), RoundVT, isVolatile,
1258                             isNonTemporal, Alignment);
1259
1260         // Load the remaining ExtraWidth bits.
1261         IncrementSize = RoundWidth / 8;
1262         Tmp2 = DAG.getNode(ISD::ADD, dl, Tmp2.getValueType(), Tmp2,
1263                            DAG.getIntPtrConstant(IncrementSize));
1264         Lo = DAG.getExtLoad(ISD::ZEXTLOAD,
1265                             dl, Node->getValueType(0), Tmp1, Tmp2,
1266                             LD->getPointerInfo().getWithOffset(IncrementSize),
1267                             ExtraVT, isVolatile, isNonTemporal,
1268                             MinAlign(Alignment, IncrementSize));
1269
1270         // Build a factor node to remember that this load is independent of
1271         // the other one.
1272         Ch = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Lo.getValue(1),
1273                          Hi.getValue(1));
1274
1275         // Move the top bits to the right place.
1276         Hi = DAG.getNode(ISD::SHL, dl, Hi.getValueType(), Hi,
1277                          DAG.getConstant(ExtraWidth,
1278                                       TLI.getShiftAmountTy(Hi.getValueType())));
1279
1280         // Join the hi and lo parts.
1281         Result = DAG.getNode(ISD::OR, dl, Node->getValueType(0), Lo, Hi);
1282       }
1283
1284       Tmp1 = LegalizeOp(Result);
1285       Tmp2 = LegalizeOp(Ch);
1286     } else {
1287       switch (TLI.getLoadExtAction(ExtType, SrcVT)) {
1288       default: assert(0 && "This action is not supported yet!");
1289       case TargetLowering::Custom:
1290         isCustom = true;
1291         // FALLTHROUGH
1292       case TargetLowering::Legal:
1293         Result = SDValue(DAG.UpdateNodeOperands(Result.getNode(),
1294                                                 Tmp1, Tmp2, LD->getOffset()),
1295                          Result.getResNo());
1296         Tmp1 = Result.getValue(0);
1297         Tmp2 = Result.getValue(1);
1298
1299         if (isCustom) {
1300           Tmp3 = TLI.LowerOperation(Result, DAG);
1301           if (Tmp3.getNode()) {
1302             Tmp1 = LegalizeOp(Tmp3);
1303             Tmp2 = LegalizeOp(Tmp3.getValue(1));
1304           }
1305         } else {
1306           // If this is an unaligned load and the target doesn't support it,
1307           // expand it.
1308           if (!TLI.allowsUnalignedMemoryAccesses(LD->getMemoryVT())) {
1309             Type *Ty =
1310               LD->getMemoryVT().getTypeForEVT(*DAG.getContext());
1311             unsigned ABIAlignment =
1312               TLI.getTargetData()->getABITypeAlignment(Ty);
1313             if (LD->getAlignment() < ABIAlignment){
1314               Result = ExpandUnalignedLoad(cast<LoadSDNode>(Result.getNode()),
1315                                            DAG, TLI);
1316               Tmp1 = Result.getOperand(0);
1317               Tmp2 = Result.getOperand(1);
1318               Tmp1 = LegalizeOp(Tmp1);
1319               Tmp2 = LegalizeOp(Tmp2);
1320             }
1321           }
1322         }
1323         break;
1324       case TargetLowering::Expand:
1325         if (!TLI.isLoadExtLegal(ISD::EXTLOAD, SrcVT) && TLI.isTypeLegal(SrcVT)) {
1326           SDValue Load = DAG.getLoad(SrcVT, dl, Tmp1, Tmp2,
1327                                      LD->getPointerInfo(),
1328                                      LD->isVolatile(), LD->isNonTemporal(),
1329                                      LD->getAlignment());
1330           unsigned ExtendOp;
1331           switch (ExtType) {
1332           case ISD::EXTLOAD:
1333             ExtendOp = (SrcVT.isFloatingPoint() ?
1334                         ISD::FP_EXTEND : ISD::ANY_EXTEND);
1335             break;
1336           case ISD::SEXTLOAD: ExtendOp = ISD::SIGN_EXTEND; break;
1337           case ISD::ZEXTLOAD: ExtendOp = ISD::ZERO_EXTEND; break;
1338           default: llvm_unreachable("Unexpected extend load type!");
1339           }
1340           Result = DAG.getNode(ExtendOp, dl, Node->getValueType(0), Load);
1341           Tmp1 = LegalizeOp(Result);  // Relegalize new nodes.
1342           Tmp2 = LegalizeOp(Load.getValue(1));
1343           break;
1344         }
1345
1346         // If this is a promoted vector load, and the vector element types are
1347         // legal, then scalarize it.
1348         if (ExtType == ISD::EXTLOAD && SrcVT.isVector() &&
1349           TLI.isTypeLegal(Node->getValueType(0).getScalarType())) {
1350           SmallVector<SDValue, 8> LoadVals;
1351           SmallVector<SDValue, 8> LoadChains;
1352           unsigned NumElem = SrcVT.getVectorNumElements();
1353           unsigned Stride = SrcVT.getScalarType().getSizeInBits()/8;
1354
1355           for (unsigned Idx=0; Idx<NumElem; Idx++) {
1356             Tmp2 = DAG.getNode(ISD::ADD, dl, Tmp2.getValueType(), Tmp2,
1357                                 DAG.getIntPtrConstant(Stride));
1358             SDValue ScalarLoad = DAG.getExtLoad(ISD::EXTLOAD, dl,
1359                   Node->getValueType(0).getScalarType(),
1360                   Tmp1, Tmp2, LD->getPointerInfo().getWithOffset(Idx * Stride),
1361                   SrcVT.getScalarType(),
1362                   LD->isVolatile(), LD->isNonTemporal(),
1363                   LD->getAlignment());
1364
1365             LoadVals.push_back(ScalarLoad.getValue(0));
1366             LoadChains.push_back(ScalarLoad.getValue(1));
1367           }
1368           Result = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
1369             &LoadChains[0], LoadChains.size());
1370           SDValue ValRes = DAG.getNode(ISD::BUILD_VECTOR, dl,
1371             Node->getValueType(0), &LoadVals[0], LoadVals.size());
1372
1373           Tmp1 = LegalizeOp(ValRes);  // Relegalize new nodes.
1374           Tmp2 = LegalizeOp(Result.getValue(0));  // Relegalize new nodes.
1375           break;
1376         }
1377
1378         // If this is a promoted vector load, and the vector element types are
1379         // illegal, create the promoted vector from bitcasted segments.
1380         if (ExtType == ISD::EXTLOAD && SrcVT.isVector()) {
1381           EVT MemElemTy = Node->getValueType(0).getScalarType();
1382           EVT SrcSclrTy = SrcVT.getScalarType();
1383           unsigned SizeRatio =
1384             (MemElemTy.getSizeInBits() / SrcSclrTy.getSizeInBits());
1385
1386           SmallVector<SDValue, 8> LoadVals;
1387           SmallVector<SDValue, 8> LoadChains;
1388           unsigned NumElem = SrcVT.getVectorNumElements();
1389           unsigned Stride = SrcVT.getScalarType().getSizeInBits()/8;
1390
1391           for (unsigned Idx=0; Idx<NumElem; Idx++) {
1392             Tmp2 = DAG.getNode(ISD::ADD, dl, Tmp2.getValueType(), Tmp2,
1393                                 DAG.getIntPtrConstant(Stride));
1394             SDValue ScalarLoad = DAG.getExtLoad(ISD::EXTLOAD, dl,
1395                   SrcVT.getScalarType(),
1396                   Tmp1, Tmp2, LD->getPointerInfo().getWithOffset(Idx * Stride),
1397                   SrcVT.getScalarType(),
1398                   LD->isVolatile(), LD->isNonTemporal(),
1399                   LD->getAlignment());
1400             if (TLI.isBigEndian()) {
1401               // MSB (which is garbage, comes first)
1402               LoadVals.push_back(ScalarLoad.getValue(0));
1403               for (unsigned i = 0; i<SizeRatio-1; ++i)
1404                 LoadVals.push_back(DAG.getUNDEF(SrcVT.getScalarType()));
1405             } else {
1406               // LSB (which is data, comes first)
1407               for (unsigned i = 0; i<SizeRatio-1; ++i)
1408                 LoadVals.push_back(DAG.getUNDEF(SrcVT.getScalarType()));
1409               LoadVals.push_back(ScalarLoad.getValue(0));
1410             }
1411             LoadChains.push_back(ScalarLoad.getValue(1));
1412           }
1413
1414           Result = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
1415             &LoadChains[0], LoadChains.size());
1416           EVT TempWideVector = EVT::getVectorVT(*DAG.getContext(),
1417             SrcVT.getScalarType(), NumElem*SizeRatio);
1418           SDValue ValRes = DAG.getNode(ISD::BUILD_VECTOR, dl, 
1419             TempWideVector, &LoadVals[0], LoadVals.size());
1420
1421           // Cast to the correct type
1422           ValRes = DAG.getNode(ISD::BITCAST, dl, Node->getValueType(0), ValRes);
1423
1424           Tmp1 = LegalizeOp(ValRes);  // Relegalize new nodes.
1425           Tmp2 = LegalizeOp(Result.getValue(0));  // Relegalize new nodes.
1426           break;
1427
1428         }
1429
1430         // FIXME: This does not work for vectors on most targets.  Sign- and
1431         // zero-extend operations are currently folded into extending loads,
1432         // whether they are legal or not, and then we end up here without any
1433         // support for legalizing them.
1434         assert(ExtType != ISD::EXTLOAD &&
1435                "EXTLOAD should always be supported!");
1436         // Turn the unsupported load into an EXTLOAD followed by an explicit
1437         // zero/sign extend inreg.
1438         Result = DAG.getExtLoad(ISD::EXTLOAD, dl, Node->getValueType(0),
1439                                 Tmp1, Tmp2, LD->getPointerInfo(), SrcVT,
1440                                 LD->isVolatile(), LD->isNonTemporal(),
1441                                 LD->getAlignment());
1442         SDValue ValRes;
1443         if (ExtType == ISD::SEXTLOAD)
1444           ValRes = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl,
1445                                Result.getValueType(),
1446                                Result, DAG.getValueType(SrcVT));
1447         else
1448           ValRes = DAG.getZeroExtendInReg(Result, dl, SrcVT.getScalarType());
1449         Tmp1 = LegalizeOp(ValRes);  // Relegalize new nodes.
1450         Tmp2 = LegalizeOp(Result.getValue(1));  // Relegalize new nodes.
1451         break;
1452       }
1453     }
1454
1455     // Since loads produce two values, make sure to remember that we legalized
1456     // both of them.
1457     AddLegalizedOperand(SDValue(Node, 0), Tmp1);
1458     AddLegalizedOperand(SDValue(Node, 1), Tmp2);
1459     return Op.getResNo() ? Tmp2 : Tmp1;
1460   }
1461   case ISD::STORE: {
1462     StoreSDNode *ST = cast<StoreSDNode>(Node);
1463     Tmp1 = LegalizeOp(ST->getChain());    // Legalize the chain.
1464     Tmp2 = LegalizeOp(ST->getBasePtr());  // Legalize the pointer.
1465     unsigned Alignment = ST->getAlignment();
1466     bool isVolatile = ST->isVolatile();
1467     bool isNonTemporal = ST->isNonTemporal();
1468
1469     if (!ST->isTruncatingStore()) {
1470       if (SDNode *OptStore = OptimizeFloatStore(ST).getNode()) {
1471         Result = SDValue(OptStore, 0);
1472         break;
1473       }
1474
1475       {
1476         Tmp3 = LegalizeOp(ST->getValue());
1477         Result = SDValue(DAG.UpdateNodeOperands(Result.getNode(),
1478                                                 Tmp1, Tmp3, Tmp2,
1479                                                 ST->getOffset()),
1480                          Result.getResNo());
1481
1482         EVT VT = Tmp3.getValueType();
1483         switch (TLI.getOperationAction(ISD::STORE, VT)) {
1484         default: assert(0 && "This action is not supported yet!");
1485         case TargetLowering::Legal:
1486           // If this is an unaligned store and the target doesn't support it,
1487           // expand it.
1488           if (!TLI.allowsUnalignedMemoryAccesses(ST->getMemoryVT())) {
1489             Type *Ty = ST->getMemoryVT().getTypeForEVT(*DAG.getContext());
1490             unsigned ABIAlignment= TLI.getTargetData()->getABITypeAlignment(Ty);
1491             if (ST->getAlignment() < ABIAlignment)
1492               Result = ExpandUnalignedStore(cast<StoreSDNode>(Result.getNode()),
1493                                             DAG, TLI);
1494           }
1495           break;
1496         case TargetLowering::Custom:
1497           Tmp1 = TLI.LowerOperation(Result, DAG);
1498           if (Tmp1.getNode()) Result = Tmp1;
1499           break;
1500         case TargetLowering::Promote:
1501           assert(VT.isVector() && "Unknown legal promote case!");
1502           Tmp3 = DAG.getNode(ISD::BITCAST, dl,
1503                              TLI.getTypeToPromoteTo(ISD::STORE, VT), Tmp3);
1504           Result = DAG.getStore(Tmp1, dl, Tmp3, Tmp2,
1505                                 ST->getPointerInfo(), isVolatile,
1506                                 isNonTemporal, Alignment);
1507           break;
1508         }
1509         break;
1510       }
1511     } else {
1512       Tmp3 = LegalizeOp(ST->getValue());
1513
1514       EVT StVT = ST->getMemoryVT();
1515       unsigned StWidth = StVT.getSizeInBits();
1516
1517       if (StWidth != StVT.getStoreSizeInBits()) {
1518         // Promote to a byte-sized store with upper bits zero if not
1519         // storing an integral number of bytes.  For example, promote
1520         // TRUNCSTORE:i1 X -> TRUNCSTORE:i8 (and X, 1)
1521         EVT NVT = EVT::getIntegerVT(*DAG.getContext(),
1522                                     StVT.getStoreSizeInBits());
1523         Tmp3 = DAG.getZeroExtendInReg(Tmp3, dl, StVT);
1524         Result = DAG.getTruncStore(Tmp1, dl, Tmp3, Tmp2, ST->getPointerInfo(),
1525                                    NVT, isVolatile, isNonTemporal, Alignment);
1526       } else if (StWidth & (StWidth - 1)) {
1527         // If not storing a power-of-2 number of bits, expand as two stores.
1528         assert(!StVT.isVector() && "Unsupported truncstore!");
1529         unsigned RoundWidth = 1 << Log2_32(StWidth);
1530         assert(RoundWidth < StWidth);
1531         unsigned ExtraWidth = StWidth - RoundWidth;
1532         assert(ExtraWidth < RoundWidth);
1533         assert(!(RoundWidth % 8) && !(ExtraWidth % 8) &&
1534                "Store size not an integral number of bytes!");
1535         EVT RoundVT = EVT::getIntegerVT(*DAG.getContext(), RoundWidth);
1536         EVT ExtraVT = EVT::getIntegerVT(*DAG.getContext(), ExtraWidth);
1537         SDValue Lo, Hi;
1538         unsigned IncrementSize;
1539
1540         if (TLI.isLittleEndian()) {
1541           // TRUNCSTORE:i24 X -> TRUNCSTORE:i16 X, TRUNCSTORE@+2:i8 (srl X, 16)
1542           // Store the bottom RoundWidth bits.
1543           Lo = DAG.getTruncStore(Tmp1, dl, Tmp3, Tmp2, ST->getPointerInfo(),
1544                                  RoundVT,
1545                                  isVolatile, isNonTemporal, Alignment);
1546
1547           // Store the remaining ExtraWidth bits.
1548           IncrementSize = RoundWidth / 8;
1549           Tmp2 = DAG.getNode(ISD::ADD, dl, Tmp2.getValueType(), Tmp2,
1550                              DAG.getIntPtrConstant(IncrementSize));
1551           Hi = DAG.getNode(ISD::SRL, dl, Tmp3.getValueType(), Tmp3,
1552                            DAG.getConstant(RoundWidth,
1553                                     TLI.getShiftAmountTy(Tmp3.getValueType())));
1554           Hi = DAG.getTruncStore(Tmp1, dl, Hi, Tmp2,
1555                              ST->getPointerInfo().getWithOffset(IncrementSize),
1556                                  ExtraVT, isVolatile, isNonTemporal,
1557                                  MinAlign(Alignment, IncrementSize));
1558         } else {
1559           // Big endian - avoid unaligned stores.
1560           // TRUNCSTORE:i24 X -> TRUNCSTORE:i16 (srl X, 8), TRUNCSTORE@+2:i8 X
1561           // Store the top RoundWidth bits.
1562           Hi = DAG.getNode(ISD::SRL, dl, Tmp3.getValueType(), Tmp3,
1563                            DAG.getConstant(ExtraWidth,
1564                                     TLI.getShiftAmountTy(Tmp3.getValueType())));
1565           Hi = DAG.getTruncStore(Tmp1, dl, Hi, Tmp2, ST->getPointerInfo(),
1566                                  RoundVT, isVolatile, isNonTemporal, Alignment);
1567
1568           // Store the remaining ExtraWidth bits.
1569           IncrementSize = RoundWidth / 8;
1570           Tmp2 = DAG.getNode(ISD::ADD, dl, Tmp2.getValueType(), Tmp2,
1571                              DAG.getIntPtrConstant(IncrementSize));
1572           Lo = DAG.getTruncStore(Tmp1, dl, Tmp3, Tmp2,
1573                               ST->getPointerInfo().getWithOffset(IncrementSize),
1574                                  ExtraVT, isVolatile, isNonTemporal,
1575                                  MinAlign(Alignment, IncrementSize));
1576         }
1577
1578         // The order of the stores doesn't matter.
1579         Result = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Lo, Hi);
1580       } else {
1581         if (Tmp1 != ST->getChain() || Tmp3 != ST->getValue() ||
1582             Tmp2 != ST->getBasePtr())
1583           Result = SDValue(DAG.UpdateNodeOperands(Result.getNode(),
1584                                                   Tmp1, Tmp3, Tmp2,
1585                                                   ST->getOffset()),
1586                            Result.getResNo());
1587
1588         switch (TLI.getTruncStoreAction(ST->getValue().getValueType(), StVT)) {
1589         default: assert(0 && "This action is not supported yet!");
1590         case TargetLowering::Legal:
1591           // If this is an unaligned store and the target doesn't support it,
1592           // expand it.
1593           if (!TLI.allowsUnalignedMemoryAccesses(ST->getMemoryVT())) {
1594             Type *Ty = ST->getMemoryVT().getTypeForEVT(*DAG.getContext());
1595             unsigned ABIAlignment= TLI.getTargetData()->getABITypeAlignment(Ty);
1596             if (ST->getAlignment() < ABIAlignment)
1597               Result = ExpandUnalignedStore(cast<StoreSDNode>(Result.getNode()),
1598                                             DAG, TLI);
1599           }
1600           break;
1601         case TargetLowering::Custom:
1602           Result = TLI.LowerOperation(Result, DAG);
1603           break;
1604         case TargetLowering::Expand:
1605
1606           EVT WideScalarVT = Tmp3.getValueType().getScalarType();
1607           EVT NarrowScalarVT = StVT.getScalarType();
1608
1609           // The Store type is illegal, must scalarize the vector store.
1610           SmallVector<SDValue, 8> Stores;
1611           bool ScalarLegal = TLI.isTypeLegal(WideScalarVT);
1612           if (!TLI.isTypeLegal(StVT) && StVT.isVector() && ScalarLegal) {
1613             unsigned NumElem = StVT.getVectorNumElements();
1614
1615             unsigned ScalarSize = StVT.getScalarType().getSizeInBits();
1616             // Round odd types to the next pow of two.
1617             if (!isPowerOf2_32(ScalarSize))
1618               ScalarSize = NextPowerOf2(ScalarSize);
1619             // Types smaller than 8 bits are promoted to 8 bits.
1620             ScalarSize = std::max<unsigned>(ScalarSize, 8);
1621             // Store stride
1622             unsigned Stride = ScalarSize/8;
1623             assert(isPowerOf2_32(Stride) && "Stride must be a power of two");
1624
1625             for (unsigned Idx=0; Idx<NumElem; Idx++) {
1626               SDValue Ex = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
1627                                        WideScalarVT, Tmp3, DAG.getIntPtrConstant(Idx));
1628
1629
1630               EVT NVT = EVT::getIntegerVT(*DAG.getContext(), ScalarSize);
1631
1632               Ex = DAG.getNode(ISD::TRUNCATE, dl, NVT, Ex);
1633               Tmp2 = DAG.getNode(ISD::ADD, dl, Tmp2.getValueType(), Tmp2,
1634                                  DAG.getIntPtrConstant(Stride));
1635               SDValue Store = DAG.getStore(Tmp1, dl, Ex, Tmp2,
1636                                            ST->getPointerInfo().getWithOffset(Idx*Stride),
1637                                            isVolatile, isNonTemporal, Alignment);
1638               Stores.push_back(Store);
1639             }
1640             Result = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
1641                                  &Stores[0], Stores.size());
1642             break;
1643           }
1644
1645           // The Store type is illegal, must scalarize the vector store.
1646           // However, the scalar type is illegal. Must bitcast the result
1647           // and store it in smaller parts.
1648           if (!TLI.isTypeLegal(StVT) && StVT.isVector()) {
1649             unsigned WideNumElem = StVT.getVectorNumElements();
1650             unsigned Stride = NarrowScalarVT.getSizeInBits()/8;
1651
1652             unsigned SizeRatio =
1653               (WideScalarVT.getSizeInBits() / NarrowScalarVT.getSizeInBits());
1654
1655             EVT CastValueVT = EVT::getVectorVT(*DAG.getContext(), NarrowScalarVT,
1656                                                SizeRatio*WideNumElem);
1657
1658             // Cast the wide elem vector to wider vec with smaller elem type.
1659             // Example <2 x i64> -> <4 x i32>
1660             Tmp3 = DAG.getNode(ISD::BITCAST, dl, CastValueVT, Tmp3);
1661
1662             for (unsigned Idx=0; Idx<WideNumElem*SizeRatio; Idx++) {
1663               // Extract elment i
1664               SDValue Ex = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
1665                                        NarrowScalarVT, Tmp3, DAG.getIntPtrConstant(Idx));
1666               // bump pointer.
1667               Tmp2 = DAG.getNode(ISD::ADD, dl, Tmp2.getValueType(), Tmp2,
1668                                  DAG.getIntPtrConstant(Stride));
1669
1670               // Store if, this element is:
1671               //  - First element on big endian, or
1672               //  - Last element on little endian
1673               if (( TLI.isBigEndian() && (Idx%SizeRatio == 0)) ||
1674                   ((!TLI.isBigEndian() && (Idx%SizeRatio == SizeRatio-1)))) {
1675                 SDValue Store = DAG.getStore(Tmp1, dl, Ex, Tmp2,
1676                                              ST->getPointerInfo().getWithOffset(Idx*Stride),
1677                                              isVolatile, isNonTemporal, Alignment);
1678                 Stores.push_back(Store);
1679               }
1680             }
1681             Result = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
1682                                  &Stores[0], Stores.size());
1683             break;
1684           }
1685
1686
1687           // TRUNCSTORE:i16 i32 -> STORE i16
1688           assert(TLI.isTypeLegal(StVT) && "Do not know how to expand this store!");
1689           Tmp3 = DAG.getNode(ISD::TRUNCATE, dl, StVT, Tmp3);
1690           Result = DAG.getStore(Tmp1, dl, Tmp3, Tmp2, ST->getPointerInfo(),
1691                                 isVolatile, isNonTemporal, Alignment);
1692           break;
1693         }
1694       }
1695     }
1696     break;
1697   }
1698   }
1699   assert(Result.getValueType() == Op.getValueType() &&
1700          "Bad legalization!");
1701
1702   // Make sure that the generated code is itself legal.
1703   if (Result != Op)
1704     Result = LegalizeOp(Result);
1705
1706   // Note that LegalizeOp may be reentered even from single-use nodes, which
1707   // means that we always must cache transformed nodes.
1708   AddLegalizedOperand(Op, Result);
1709   return Result;
1710 }
1711
1712 SDValue SelectionDAGLegalize::ExpandExtractFromVectorThroughStack(SDValue Op) {
1713   SDValue Vec = Op.getOperand(0);
1714   SDValue Idx = Op.getOperand(1);
1715   DebugLoc dl = Op.getDebugLoc();
1716   // Store the value to a temporary stack slot, then LOAD the returned part.
1717   SDValue StackPtr = DAG.CreateStackTemporary(Vec.getValueType());
1718   SDValue Ch = DAG.getStore(DAG.getEntryNode(), dl, Vec, StackPtr,
1719                             MachinePointerInfo(), false, false, 0);
1720
1721   // Add the offset to the index.
1722   unsigned EltSize =
1723       Vec.getValueType().getVectorElementType().getSizeInBits()/8;
1724   Idx = DAG.getNode(ISD::MUL, dl, Idx.getValueType(), Idx,
1725                     DAG.getConstant(EltSize, Idx.getValueType()));
1726
1727   if (Idx.getValueType().bitsGT(TLI.getPointerTy()))
1728     Idx = DAG.getNode(ISD::TRUNCATE, dl, TLI.getPointerTy(), Idx);
1729   else
1730     Idx = DAG.getNode(ISD::ZERO_EXTEND, dl, TLI.getPointerTy(), Idx);
1731
1732   StackPtr = DAG.getNode(ISD::ADD, dl, Idx.getValueType(), Idx, StackPtr);
1733
1734   if (Op.getValueType().isVector())
1735     return DAG.getLoad(Op.getValueType(), dl, Ch, StackPtr,MachinePointerInfo(),
1736                        false, false, 0);
1737   return DAG.getExtLoad(ISD::EXTLOAD, dl, Op.getValueType(), Ch, StackPtr,
1738                         MachinePointerInfo(),
1739                         Vec.getValueType().getVectorElementType(),
1740                         false, false, 0);
1741 }
1742
1743 SDValue SelectionDAGLegalize::ExpandInsertToVectorThroughStack(SDValue Op) {
1744   assert(Op.getValueType().isVector() && "Non-vector insert subvector!");
1745
1746   SDValue Vec  = Op.getOperand(0);
1747   SDValue Part = Op.getOperand(1);
1748   SDValue Idx  = Op.getOperand(2);
1749   DebugLoc dl  = Op.getDebugLoc();
1750
1751   // Store the value to a temporary stack slot, then LOAD the returned part.
1752
1753   SDValue StackPtr = DAG.CreateStackTemporary(Vec.getValueType());
1754   int FI = cast<FrameIndexSDNode>(StackPtr.getNode())->getIndex();
1755   MachinePointerInfo PtrInfo = MachinePointerInfo::getFixedStack(FI);
1756
1757   // First store the whole vector.
1758   SDValue Ch = DAG.getStore(DAG.getEntryNode(), dl, Vec, StackPtr, PtrInfo,
1759                             false, false, 0);
1760
1761   // Then store the inserted part.
1762
1763   // Add the offset to the index.
1764   unsigned EltSize =
1765       Vec.getValueType().getVectorElementType().getSizeInBits()/8;
1766
1767   Idx = DAG.getNode(ISD::MUL, dl, Idx.getValueType(), Idx,
1768                     DAG.getConstant(EltSize, Idx.getValueType()));
1769
1770   if (Idx.getValueType().bitsGT(TLI.getPointerTy()))
1771     Idx = DAG.getNode(ISD::TRUNCATE, dl, TLI.getPointerTy(), Idx);
1772   else
1773     Idx = DAG.getNode(ISD::ZERO_EXTEND, dl, TLI.getPointerTy(), Idx);
1774
1775   SDValue SubStackPtr = DAG.getNode(ISD::ADD, dl, Idx.getValueType(), Idx,
1776                                     StackPtr);
1777
1778   // Store the subvector.
1779   Ch = DAG.getStore(DAG.getEntryNode(), dl, Part, SubStackPtr,
1780                     MachinePointerInfo(), false, false, 0);
1781
1782   // Finally, load the updated vector.
1783   return DAG.getLoad(Op.getValueType(), dl, Ch, StackPtr, PtrInfo,
1784                      false, false, 0);
1785 }
1786
1787 SDValue SelectionDAGLegalize::ExpandVectorBuildThroughStack(SDNode* Node) {
1788   // We can't handle this case efficiently.  Allocate a sufficiently
1789   // aligned object on the stack, store each element into it, then load
1790   // the result as a vector.
1791   // Create the stack frame object.
1792   EVT VT = Node->getValueType(0);
1793   EVT EltVT = VT.getVectorElementType();
1794   DebugLoc dl = Node->getDebugLoc();
1795   SDValue FIPtr = DAG.CreateStackTemporary(VT);
1796   int FI = cast<FrameIndexSDNode>(FIPtr.getNode())->getIndex();
1797   MachinePointerInfo PtrInfo = MachinePointerInfo::getFixedStack(FI);
1798
1799   // Emit a store of each element to the stack slot.
1800   SmallVector<SDValue, 8> Stores;
1801   unsigned TypeByteSize = EltVT.getSizeInBits() / 8;
1802   // Store (in the right endianness) the elements to memory.
1803   for (unsigned i = 0, e = Node->getNumOperands(); i != e; ++i) {
1804     // Ignore undef elements.
1805     if (Node->getOperand(i).getOpcode() == ISD::UNDEF) continue;
1806
1807     unsigned Offset = TypeByteSize*i;
1808
1809     SDValue Idx = DAG.getConstant(Offset, FIPtr.getValueType());
1810     Idx = DAG.getNode(ISD::ADD, dl, FIPtr.getValueType(), FIPtr, Idx);
1811
1812     // If the destination vector element type is narrower than the source
1813     // element type, only store the bits necessary.
1814     if (EltVT.bitsLT(Node->getOperand(i).getValueType().getScalarType())) {
1815       Stores.push_back(DAG.getTruncStore(DAG.getEntryNode(), dl,
1816                                          Node->getOperand(i), Idx,
1817                                          PtrInfo.getWithOffset(Offset),
1818                                          EltVT, false, false, 0));
1819     } else
1820       Stores.push_back(DAG.getStore(DAG.getEntryNode(), dl,
1821                                     Node->getOperand(i), Idx,
1822                                     PtrInfo.getWithOffset(Offset),
1823                                     false, false, 0));
1824   }
1825
1826   SDValue StoreChain;
1827   if (!Stores.empty())    // Not all undef elements?
1828     StoreChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
1829                              &Stores[0], Stores.size());
1830   else
1831     StoreChain = DAG.getEntryNode();
1832
1833   // Result is a load from the stack slot.
1834   return DAG.getLoad(VT, dl, StoreChain, FIPtr, PtrInfo, false, false, 0);
1835 }
1836
1837 SDValue SelectionDAGLegalize::ExpandFCOPYSIGN(SDNode* Node) {
1838   DebugLoc dl = Node->getDebugLoc();
1839   SDValue Tmp1 = Node->getOperand(0);
1840   SDValue Tmp2 = Node->getOperand(1);
1841
1842   // Get the sign bit of the RHS.  First obtain a value that has the same
1843   // sign as the sign bit, i.e. negative if and only if the sign bit is 1.
1844   SDValue SignBit;
1845   EVT FloatVT = Tmp2.getValueType();
1846   EVT IVT = EVT::getIntegerVT(*DAG.getContext(), FloatVT.getSizeInBits());
1847   if (TLI.isTypeLegal(IVT)) {
1848     // Convert to an integer with the same sign bit.
1849     SignBit = DAG.getNode(ISD::BITCAST, dl, IVT, Tmp2);
1850   } else {
1851     // Store the float to memory, then load the sign part out as an integer.
1852     MVT LoadTy = TLI.getPointerTy();
1853     // First create a temporary that is aligned for both the load and store.
1854     SDValue StackPtr = DAG.CreateStackTemporary(FloatVT, LoadTy);
1855     // Then store the float to it.
1856     SDValue Ch =
1857       DAG.getStore(DAG.getEntryNode(), dl, Tmp2, StackPtr, MachinePointerInfo(),
1858                    false, false, 0);
1859     if (TLI.isBigEndian()) {
1860       assert(FloatVT.isByteSized() && "Unsupported floating point type!");
1861       // Load out a legal integer with the same sign bit as the float.
1862       SignBit = DAG.getLoad(LoadTy, dl, Ch, StackPtr, MachinePointerInfo(),
1863                             false, false, 0);
1864     } else { // Little endian
1865       SDValue LoadPtr = StackPtr;
1866       // The float may be wider than the integer we are going to load.  Advance
1867       // the pointer so that the loaded integer will contain the sign bit.
1868       unsigned Strides = (FloatVT.getSizeInBits()-1)/LoadTy.getSizeInBits();
1869       unsigned ByteOffset = (Strides * LoadTy.getSizeInBits()) / 8;
1870       LoadPtr = DAG.getNode(ISD::ADD, dl, LoadPtr.getValueType(),
1871                             LoadPtr, DAG.getIntPtrConstant(ByteOffset));
1872       // Load a legal integer containing the sign bit.
1873       SignBit = DAG.getLoad(LoadTy, dl, Ch, LoadPtr, MachinePointerInfo(),
1874                             false, false, 0);
1875       // Move the sign bit to the top bit of the loaded integer.
1876       unsigned BitShift = LoadTy.getSizeInBits() -
1877         (FloatVT.getSizeInBits() - 8 * ByteOffset);
1878       assert(BitShift < LoadTy.getSizeInBits() && "Pointer advanced wrong?");
1879       if (BitShift)
1880         SignBit = DAG.getNode(ISD::SHL, dl, LoadTy, SignBit,
1881                               DAG.getConstant(BitShift,
1882                                  TLI.getShiftAmountTy(SignBit.getValueType())));
1883     }
1884   }
1885   // Now get the sign bit proper, by seeing whether the value is negative.
1886   SignBit = DAG.getSetCC(dl, TLI.getSetCCResultType(SignBit.getValueType()),
1887                          SignBit, DAG.getConstant(0, SignBit.getValueType()),
1888                          ISD::SETLT);
1889   // Get the absolute value of the result.
1890   SDValue AbsVal = DAG.getNode(ISD::FABS, dl, Tmp1.getValueType(), Tmp1);
1891   // Select between the nabs and abs value based on the sign bit of
1892   // the input.
1893   return DAG.getNode(ISD::SELECT, dl, AbsVal.getValueType(), SignBit,
1894                      DAG.getNode(ISD::FNEG, dl, AbsVal.getValueType(), AbsVal),
1895                      AbsVal);
1896 }
1897
1898 void SelectionDAGLegalize::ExpandDYNAMIC_STACKALLOC(SDNode* Node,
1899                                            SmallVectorImpl<SDValue> &Results) {
1900   unsigned SPReg = TLI.getStackPointerRegisterToSaveRestore();
1901   assert(SPReg && "Target cannot require DYNAMIC_STACKALLOC expansion and"
1902           " not tell us which reg is the stack pointer!");
1903   DebugLoc dl = Node->getDebugLoc();
1904   EVT VT = Node->getValueType(0);
1905   SDValue Tmp1 = SDValue(Node, 0);
1906   SDValue Tmp2 = SDValue(Node, 1);
1907   SDValue Tmp3 = Node->getOperand(2);
1908   SDValue Chain = Tmp1.getOperand(0);
1909
1910   // Chain the dynamic stack allocation so that it doesn't modify the stack
1911   // pointer when other instructions are using the stack.
1912   Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(0, true));
1913
1914   SDValue Size  = Tmp2.getOperand(1);
1915   SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, VT);
1916   Chain = SP.getValue(1);
1917   unsigned Align = cast<ConstantSDNode>(Tmp3)->getZExtValue();
1918   unsigned StackAlign = TM.getFrameLowering()->getStackAlignment();
1919   if (Align > StackAlign)
1920     SP = DAG.getNode(ISD::AND, dl, VT, SP,
1921                       DAG.getConstant(-(uint64_t)Align, VT));
1922   Tmp1 = DAG.getNode(ISD::SUB, dl, VT, SP, Size);       // Value
1923   Chain = DAG.getCopyToReg(Chain, dl, SPReg, Tmp1);     // Output chain
1924
1925   Tmp2 = DAG.getCALLSEQ_END(Chain,  DAG.getIntPtrConstant(0, true),
1926                             DAG.getIntPtrConstant(0, true), SDValue());
1927
1928   Results.push_back(Tmp1);
1929   Results.push_back(Tmp2);
1930 }
1931
1932 /// LegalizeSetCCCondCode - Legalize a SETCC with given LHS and RHS and
1933 /// condition code CC on the current target. This routine expands SETCC with
1934 /// illegal condition code into AND / OR of multiple SETCC values.
1935 void SelectionDAGLegalize::LegalizeSetCCCondCode(EVT VT,
1936                                                  SDValue &LHS, SDValue &RHS,
1937                                                  SDValue &CC,
1938                                                  DebugLoc dl) {
1939   EVT OpVT = LHS.getValueType();
1940   ISD::CondCode CCCode = cast<CondCodeSDNode>(CC)->get();
1941   switch (TLI.getCondCodeAction(CCCode, OpVT)) {
1942   default: assert(0 && "Unknown condition code action!");
1943   case TargetLowering::Legal:
1944     // Nothing to do.
1945     break;
1946   case TargetLowering::Expand: {
1947     ISD::CondCode CC1 = ISD::SETCC_INVALID, CC2 = ISD::SETCC_INVALID;
1948     unsigned Opc = 0;
1949     switch (CCCode) {
1950     default: assert(0 && "Don't know how to expand this condition!");
1951     case ISD::SETOEQ: CC1 = ISD::SETEQ; CC2 = ISD::SETO;  Opc = ISD::AND; break;
1952     case ISD::SETOGT: CC1 = ISD::SETGT; CC2 = ISD::SETO;  Opc = ISD::AND; break;
1953     case ISD::SETOGE: CC1 = ISD::SETGE; CC2 = ISD::SETO;  Opc = ISD::AND; break;
1954     case ISD::SETOLT: CC1 = ISD::SETLT; CC2 = ISD::SETO;  Opc = ISD::AND; break;
1955     case ISD::SETOLE: CC1 = ISD::SETLE; CC2 = ISD::SETO;  Opc = ISD::AND; break;
1956     case ISD::SETONE: CC1 = ISD::SETNE; CC2 = ISD::SETO;  Opc = ISD::AND; break;
1957     case ISD::SETUEQ: CC1 = ISD::SETEQ; CC2 = ISD::SETUO; Opc = ISD::OR;  break;
1958     case ISD::SETUGT: CC1 = ISD::SETGT; CC2 = ISD::SETUO; Opc = ISD::OR;  break;
1959     case ISD::SETUGE: CC1 = ISD::SETGE; CC2 = ISD::SETUO; Opc = ISD::OR;  break;
1960     case ISD::SETULT: CC1 = ISD::SETLT; CC2 = ISD::SETUO; Opc = ISD::OR;  break;
1961     case ISD::SETULE: CC1 = ISD::SETLE; CC2 = ISD::SETUO; Opc = ISD::OR;  break;
1962     case ISD::SETUNE: CC1 = ISD::SETNE; CC2 = ISD::SETUO; Opc = ISD::OR;  break;
1963     // FIXME: Implement more expansions.
1964     }
1965
1966     SDValue SetCC1 = DAG.getSetCC(dl, VT, LHS, RHS, CC1);
1967     SDValue SetCC2 = DAG.getSetCC(dl, VT, LHS, RHS, CC2);
1968     LHS = DAG.getNode(Opc, dl, VT, SetCC1, SetCC2);
1969     RHS = SDValue();
1970     CC  = SDValue();
1971     break;
1972   }
1973   }
1974 }
1975
1976 /// EmitStackConvert - Emit a store/load combination to the stack.  This stores
1977 /// SrcOp to a stack slot of type SlotVT, truncating it if needed.  It then does
1978 /// a load from the stack slot to DestVT, extending it if needed.
1979 /// The resultant code need not be legal.
1980 SDValue SelectionDAGLegalize::EmitStackConvert(SDValue SrcOp,
1981                                                EVT SlotVT,
1982                                                EVT DestVT,
1983                                                DebugLoc dl) {
1984   // Create the stack frame object.
1985   unsigned SrcAlign =
1986     TLI.getTargetData()->getPrefTypeAlignment(SrcOp.getValueType().
1987                                               getTypeForEVT(*DAG.getContext()));
1988   SDValue FIPtr = DAG.CreateStackTemporary(SlotVT, SrcAlign);
1989
1990   FrameIndexSDNode *StackPtrFI = cast<FrameIndexSDNode>(FIPtr);
1991   int SPFI = StackPtrFI->getIndex();
1992   MachinePointerInfo PtrInfo = MachinePointerInfo::getFixedStack(SPFI);
1993
1994   unsigned SrcSize = SrcOp.getValueType().getSizeInBits();
1995   unsigned SlotSize = SlotVT.getSizeInBits();
1996   unsigned DestSize = DestVT.getSizeInBits();
1997   Type *DestType = DestVT.getTypeForEVT(*DAG.getContext());
1998   unsigned DestAlign = TLI.getTargetData()->getPrefTypeAlignment(DestType);
1999
2000   // Emit a store to the stack slot.  Use a truncstore if the input value is
2001   // later than DestVT.
2002   SDValue Store;
2003
2004   if (SrcSize > SlotSize)
2005     Store = DAG.getTruncStore(DAG.getEntryNode(), dl, SrcOp, FIPtr,
2006                               PtrInfo, SlotVT, false, false, SrcAlign);
2007   else {
2008     assert(SrcSize == SlotSize && "Invalid store");
2009     Store = DAG.getStore(DAG.getEntryNode(), dl, SrcOp, FIPtr,
2010                          PtrInfo, false, false, SrcAlign);
2011   }
2012
2013   // Result is a load from the stack slot.
2014   if (SlotSize == DestSize)
2015     return DAG.getLoad(DestVT, dl, Store, FIPtr, PtrInfo,
2016                        false, false, DestAlign);
2017
2018   assert(SlotSize < DestSize && "Unknown extension!");
2019   return DAG.getExtLoad(ISD::EXTLOAD, dl, DestVT, Store, FIPtr,
2020                         PtrInfo, SlotVT, false, false, DestAlign);
2021 }
2022
2023 SDValue SelectionDAGLegalize::ExpandSCALAR_TO_VECTOR(SDNode *Node) {
2024   DebugLoc dl = Node->getDebugLoc();
2025   // Create a vector sized/aligned stack slot, store the value to element #0,
2026   // then load the whole vector back out.
2027   SDValue StackPtr = DAG.CreateStackTemporary(Node->getValueType(0));
2028
2029   FrameIndexSDNode *StackPtrFI = cast<FrameIndexSDNode>(StackPtr);
2030   int SPFI = StackPtrFI->getIndex();
2031
2032   SDValue Ch = DAG.getTruncStore(DAG.getEntryNode(), dl, Node->getOperand(0),
2033                                  StackPtr,
2034                                  MachinePointerInfo::getFixedStack(SPFI),
2035                                  Node->getValueType(0).getVectorElementType(),
2036                                  false, false, 0);
2037   return DAG.getLoad(Node->getValueType(0), dl, Ch, StackPtr,
2038                      MachinePointerInfo::getFixedStack(SPFI),
2039                      false, false, 0);
2040 }
2041
2042
2043 /// ExpandBUILD_VECTOR - Expand a BUILD_VECTOR node on targets that don't
2044 /// support the operation, but do support the resultant vector type.
2045 SDValue SelectionDAGLegalize::ExpandBUILD_VECTOR(SDNode *Node) {
2046   unsigned NumElems = Node->getNumOperands();
2047   SDValue Value1, Value2;
2048   DebugLoc dl = Node->getDebugLoc();
2049   EVT VT = Node->getValueType(0);
2050   EVT OpVT = Node->getOperand(0).getValueType();
2051   EVT EltVT = VT.getVectorElementType();
2052
2053   // If the only non-undef value is the low element, turn this into a
2054   // SCALAR_TO_VECTOR node.  If this is { X, X, X, X }, determine X.
2055   bool isOnlyLowElement = true;
2056   bool MoreThanTwoValues = false;
2057   bool isConstant = true;
2058   for (unsigned i = 0; i < NumElems; ++i) {
2059     SDValue V = Node->getOperand(i);
2060     if (V.getOpcode() == ISD::UNDEF)
2061       continue;
2062     if (i > 0)
2063       isOnlyLowElement = false;
2064     if (!isa<ConstantFPSDNode>(V) && !isa<ConstantSDNode>(V))
2065       isConstant = false;
2066
2067     if (!Value1.getNode()) {
2068       Value1 = V;
2069     } else if (!Value2.getNode()) {
2070       if (V != Value1)
2071         Value2 = V;
2072     } else if (V != Value1 && V != Value2) {
2073       MoreThanTwoValues = true;
2074     }
2075   }
2076
2077   if (!Value1.getNode())
2078     return DAG.getUNDEF(VT);
2079
2080   if (isOnlyLowElement)
2081     return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Node->getOperand(0));
2082
2083   // If all elements are constants, create a load from the constant pool.
2084   if (isConstant) {
2085     std::vector<Constant*> CV;
2086     for (unsigned i = 0, e = NumElems; i != e; ++i) {
2087       if (ConstantFPSDNode *V =
2088           dyn_cast<ConstantFPSDNode>(Node->getOperand(i))) {
2089         CV.push_back(const_cast<ConstantFP *>(V->getConstantFPValue()));
2090       } else if (ConstantSDNode *V =
2091                  dyn_cast<ConstantSDNode>(Node->getOperand(i))) {
2092         if (OpVT==EltVT)
2093           CV.push_back(const_cast<ConstantInt *>(V->getConstantIntValue()));
2094         else {
2095           // If OpVT and EltVT don't match, EltVT is not legal and the
2096           // element values have been promoted/truncated earlier.  Undo this;
2097           // we don't want a v16i8 to become a v16i32 for example.
2098           const ConstantInt *CI = V->getConstantIntValue();
2099           CV.push_back(ConstantInt::get(EltVT.getTypeForEVT(*DAG.getContext()),
2100                                         CI->getZExtValue()));
2101         }
2102       } else {
2103         assert(Node->getOperand(i).getOpcode() == ISD::UNDEF);
2104         Type *OpNTy = EltVT.getTypeForEVT(*DAG.getContext());
2105         CV.push_back(UndefValue::get(OpNTy));
2106       }
2107     }
2108     Constant *CP = ConstantVector::get(CV);
2109     SDValue CPIdx = DAG.getConstantPool(CP, TLI.getPointerTy());
2110     unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
2111     return DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
2112                        MachinePointerInfo::getConstantPool(),
2113                        false, false, Alignment);
2114   }
2115
2116   if (!MoreThanTwoValues) {
2117     SmallVector<int, 8> ShuffleVec(NumElems, -1);
2118     for (unsigned i = 0; i < NumElems; ++i) {
2119       SDValue V = Node->getOperand(i);
2120       if (V.getOpcode() == ISD::UNDEF)
2121         continue;
2122       ShuffleVec[i] = V == Value1 ? 0 : NumElems;
2123     }
2124     if (TLI.isShuffleMaskLegal(ShuffleVec, Node->getValueType(0))) {
2125       // Get the splatted value into the low element of a vector register.
2126       SDValue Vec1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Value1);
2127       SDValue Vec2;
2128       if (Value2.getNode())
2129         Vec2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Value2);
2130       else
2131         Vec2 = DAG.getUNDEF(VT);
2132
2133       // Return shuffle(LowValVec, undef, <0,0,0,0>)
2134       return DAG.getVectorShuffle(VT, dl, Vec1, Vec2, ShuffleVec.data());
2135     }
2136   }
2137
2138   // Otherwise, we can't handle this case efficiently.
2139   return ExpandVectorBuildThroughStack(Node);
2140 }
2141
2142 // ExpandLibCall - Expand a node into a call to a libcall.  If the result value
2143 // does not fit into a register, return the lo part and set the hi part to the
2144 // by-reg argument.  If it does fit into a single register, return the result
2145 // and leave the Hi part unset.
2146 SDValue SelectionDAGLegalize::ExpandLibCall(RTLIB::Libcall LC, SDNode *Node,
2147                                             bool isSigned) {
2148   assert(!IsLegalizingCall && "Cannot overlap legalization of calls!");
2149   // The input chain to this libcall is the entry node of the function.
2150   // Legalizing the call will automatically add the previous call to the
2151   // dependence.
2152   SDValue InChain = DAG.getEntryNode();
2153
2154   TargetLowering::ArgListTy Args;
2155   TargetLowering::ArgListEntry Entry;
2156   for (unsigned i = 0, e = Node->getNumOperands(); i != e; ++i) {
2157     EVT ArgVT = Node->getOperand(i).getValueType();
2158     Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
2159     Entry.Node = Node->getOperand(i); Entry.Ty = ArgTy;
2160     Entry.isSExt = isSigned;
2161     Entry.isZExt = !isSigned;
2162     Args.push_back(Entry);
2163   }
2164   SDValue Callee = DAG.getExternalSymbol(TLI.getLibcallName(LC),
2165                                          TLI.getPointerTy());
2166
2167   // Splice the libcall in wherever FindInputOutputChains tells us to.
2168   Type *RetTy = Node->getValueType(0).getTypeForEVT(*DAG.getContext());
2169
2170   // isTailCall may be true since the callee does not reference caller stack
2171   // frame. Check if it's in the right position.
2172   bool isTailCall = isInTailCallPosition(DAG, Node, TLI);
2173   std::pair<SDValue, SDValue> CallInfo =
2174     TLI.LowerCallTo(InChain, RetTy, isSigned, !isSigned, false, false,
2175                     0, TLI.getLibcallCallingConv(LC), isTailCall,
2176                     /*isReturnValueUsed=*/true,
2177                     Callee, Args, DAG, Node->getDebugLoc());
2178
2179   if (!CallInfo.second.getNode())
2180     // It's a tailcall, return the chain (which is the DAG root).
2181     return DAG.getRoot();
2182
2183   // Legalize the call sequence, starting with the chain.  This will advance
2184   // the LastCALLSEQ_END to the legalized version of the CALLSEQ_END node that
2185   // was added by LowerCallTo (guaranteeing proper serialization of calls).
2186   LegalizeOp(CallInfo.second);
2187   return CallInfo.first;
2188 }
2189
2190 /// ExpandLibCall - Generate a libcall taking the given operands as arguments
2191 /// and returning a result of type RetVT.
2192 SDValue SelectionDAGLegalize::ExpandLibCall(RTLIB::Libcall LC, EVT RetVT,
2193                                             const SDValue *Ops, unsigned NumOps,
2194                                             bool isSigned, DebugLoc dl) {
2195   TargetLowering::ArgListTy Args;
2196   Args.reserve(NumOps);
2197
2198   TargetLowering::ArgListEntry Entry;
2199   for (unsigned i = 0; i != NumOps; ++i) {
2200     Entry.Node = Ops[i];
2201     Entry.Ty = Entry.Node.getValueType().getTypeForEVT(*DAG.getContext());
2202     Entry.isSExt = isSigned;
2203     Entry.isZExt = !isSigned;
2204     Args.push_back(Entry);
2205   }
2206   SDValue Callee = DAG.getExternalSymbol(TLI.getLibcallName(LC),
2207                                          TLI.getPointerTy());
2208
2209   Type *RetTy = RetVT.getTypeForEVT(*DAG.getContext());
2210   std::pair<SDValue,SDValue> CallInfo =
2211   TLI.LowerCallTo(DAG.getEntryNode(), RetTy, isSigned, !isSigned, false,
2212                   false, 0, TLI.getLibcallCallingConv(LC), false,
2213                   /*isReturnValueUsed=*/true,
2214                   Callee, Args, DAG, dl);
2215
2216   // Legalize the call sequence, starting with the chain.  This will advance
2217   // the LastCALLSEQ_END to the legalized version of the CALLSEQ_END node that
2218   // was added by LowerCallTo (guaranteeing proper serialization of calls).
2219   LegalizeOp(CallInfo.second);
2220
2221   return CallInfo.first;
2222 }
2223
2224 // ExpandChainLibCall - Expand a node into a call to a libcall. Similar to
2225 // ExpandLibCall except that the first operand is the in-chain.
2226 std::pair<SDValue, SDValue>
2227 SelectionDAGLegalize::ExpandChainLibCall(RTLIB::Libcall LC,
2228                                          SDNode *Node,
2229                                          bool isSigned) {
2230   assert(!IsLegalizingCall && "Cannot overlap legalization of calls!");
2231   SDValue InChain = Node->getOperand(0);
2232
2233   TargetLowering::ArgListTy Args;
2234   TargetLowering::ArgListEntry Entry;
2235   for (unsigned i = 1, e = Node->getNumOperands(); i != e; ++i) {
2236     EVT ArgVT = Node->getOperand(i).getValueType();
2237     Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
2238     Entry.Node = Node->getOperand(i);
2239     Entry.Ty = ArgTy;
2240     Entry.isSExt = isSigned;
2241     Entry.isZExt = !isSigned;
2242     Args.push_back(Entry);
2243   }
2244   SDValue Callee = DAG.getExternalSymbol(TLI.getLibcallName(LC),
2245                                          TLI.getPointerTy());
2246
2247   // Splice the libcall in wherever FindInputOutputChains tells us to.
2248   Type *RetTy = Node->getValueType(0).getTypeForEVT(*DAG.getContext());
2249   std::pair<SDValue, SDValue> CallInfo =
2250     TLI.LowerCallTo(InChain, RetTy, isSigned, !isSigned, false, false,
2251                     0, TLI.getLibcallCallingConv(LC), /*isTailCall=*/false,
2252                     /*isReturnValueUsed=*/true,
2253                     Callee, Args, DAG, Node->getDebugLoc());
2254
2255   // Legalize the call sequence, starting with the chain.  This will advance
2256   // the LastCALLSEQ_END to the legalized version of the CALLSEQ_END node that
2257   // was added by LowerCallTo (guaranteeing proper serialization of calls).
2258   LegalizeOp(CallInfo.second);
2259   return CallInfo;
2260 }
2261
2262 SDValue SelectionDAGLegalize::ExpandFPLibCall(SDNode* Node,
2263                                               RTLIB::Libcall Call_F32,
2264                                               RTLIB::Libcall Call_F64,
2265                                               RTLIB::Libcall Call_F80,
2266                                               RTLIB::Libcall Call_PPCF128) {
2267   RTLIB::Libcall LC;
2268   switch (Node->getValueType(0).getSimpleVT().SimpleTy) {
2269   default: assert(0 && "Unexpected request for libcall!");
2270   case MVT::f32: LC = Call_F32; break;
2271   case MVT::f64: LC = Call_F64; break;
2272   case MVT::f80: LC = Call_F80; break;
2273   case MVT::ppcf128: LC = Call_PPCF128; break;
2274   }
2275   return ExpandLibCall(LC, Node, false);
2276 }
2277
2278 SDValue SelectionDAGLegalize::ExpandIntLibCall(SDNode* Node, bool isSigned,
2279                                                RTLIB::Libcall Call_I8,
2280                                                RTLIB::Libcall Call_I16,
2281                                                RTLIB::Libcall Call_I32,
2282                                                RTLIB::Libcall Call_I64,
2283                                                RTLIB::Libcall Call_I128) {
2284   RTLIB::Libcall LC;
2285   switch (Node->getValueType(0).getSimpleVT().SimpleTy) {
2286   default: assert(0 && "Unexpected request for libcall!");
2287   case MVT::i8:   LC = Call_I8; break;
2288   case MVT::i16:  LC = Call_I16; break;
2289   case MVT::i32:  LC = Call_I32; break;
2290   case MVT::i64:  LC = Call_I64; break;
2291   case MVT::i128: LC = Call_I128; break;
2292   }
2293   return ExpandLibCall(LC, Node, isSigned);
2294 }
2295
2296 /// isDivRemLibcallAvailable - Return true if divmod libcall is available.
2297 static bool isDivRemLibcallAvailable(SDNode *Node, bool isSigned,
2298                                      const TargetLowering &TLI) {
2299   RTLIB::Libcall LC;
2300   switch (Node->getValueType(0).getSimpleVT().SimpleTy) {
2301   default: assert(0 && "Unexpected request for libcall!");
2302   case MVT::i8:   LC= isSigned ? RTLIB::SDIVREM_I8  : RTLIB::UDIVREM_I8;  break;
2303   case MVT::i16:  LC= isSigned ? RTLIB::SDIVREM_I16 : RTLIB::UDIVREM_I16; break;
2304   case MVT::i32:  LC= isSigned ? RTLIB::SDIVREM_I32 : RTLIB::UDIVREM_I32; break;
2305   case MVT::i64:  LC= isSigned ? RTLIB::SDIVREM_I64 : RTLIB::UDIVREM_I64; break;
2306   case MVT::i128: LC= isSigned ? RTLIB::SDIVREM_I128:RTLIB::UDIVREM_I128; break;
2307   }
2308
2309   return TLI.getLibcallName(LC) != 0;
2310 }
2311
2312 /// UseDivRem - Only issue divrem libcall if both quotient and remainder are
2313 /// needed.
2314 static bool UseDivRem(SDNode *Node, bool isSigned, bool isDIV) {
2315   unsigned OtherOpcode = 0;
2316   if (isSigned)
2317     OtherOpcode = isDIV ? ISD::SREM : ISD::SDIV;
2318   else
2319     OtherOpcode = isDIV ? ISD::UREM : ISD::UDIV;
2320
2321   SDValue Op0 = Node->getOperand(0);
2322   SDValue Op1 = Node->getOperand(1);
2323   for (SDNode::use_iterator UI = Op0.getNode()->use_begin(),
2324          UE = Op0.getNode()->use_end(); UI != UE; ++UI) {
2325     SDNode *User = *UI;
2326     if (User == Node)
2327       continue;
2328     if (User->getOpcode() == OtherOpcode &&
2329         User->getOperand(0) == Op0 &&
2330         User->getOperand(1) == Op1)
2331       return true;
2332   }
2333   return false;
2334 }
2335
2336 /// ExpandDivRemLibCall - Issue libcalls to __{u}divmod to compute div / rem
2337 /// pairs.
2338 void
2339 SelectionDAGLegalize::ExpandDivRemLibCall(SDNode *Node,
2340                                           SmallVectorImpl<SDValue> &Results) {
2341   unsigned Opcode = Node->getOpcode();
2342   bool isSigned = Opcode == ISD::SDIVREM;
2343
2344   RTLIB::Libcall LC;
2345   switch (Node->getValueType(0).getSimpleVT().SimpleTy) {
2346   default: assert(0 && "Unexpected request for libcall!");
2347   case MVT::i8:   LC= isSigned ? RTLIB::SDIVREM_I8  : RTLIB::UDIVREM_I8;  break;
2348   case MVT::i16:  LC= isSigned ? RTLIB::SDIVREM_I16 : RTLIB::UDIVREM_I16; break;
2349   case MVT::i32:  LC= isSigned ? RTLIB::SDIVREM_I32 : RTLIB::UDIVREM_I32; break;
2350   case MVT::i64:  LC= isSigned ? RTLIB::SDIVREM_I64 : RTLIB::UDIVREM_I64; break;
2351   case MVT::i128: LC= isSigned ? RTLIB::SDIVREM_I128:RTLIB::UDIVREM_I128; break;
2352   }
2353
2354   // The input chain to this libcall is the entry node of the function.
2355   // Legalizing the call will automatically add the previous call to the
2356   // dependence.
2357   SDValue InChain = DAG.getEntryNode();
2358
2359   EVT RetVT = Node->getValueType(0);
2360   Type *RetTy = RetVT.getTypeForEVT(*DAG.getContext());
2361
2362   TargetLowering::ArgListTy Args;
2363   TargetLowering::ArgListEntry Entry;
2364   for (unsigned i = 0, e = Node->getNumOperands(); i != e; ++i) {
2365     EVT ArgVT = Node->getOperand(i).getValueType();
2366     Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
2367     Entry.Node = Node->getOperand(i); Entry.Ty = ArgTy;
2368     Entry.isSExt = isSigned;
2369     Entry.isZExt = !isSigned;
2370     Args.push_back(Entry);
2371   }
2372
2373   // Also pass the return address of the remainder.
2374   SDValue FIPtr = DAG.CreateStackTemporary(RetVT);
2375   Entry.Node = FIPtr;
2376   Entry.Ty = RetTy->getPointerTo();
2377   Entry.isSExt = isSigned;
2378   Entry.isZExt = !isSigned;
2379   Args.push_back(Entry);
2380
2381   SDValue Callee = DAG.getExternalSymbol(TLI.getLibcallName(LC),
2382                                          TLI.getPointerTy());
2383
2384   // Splice the libcall in wherever FindInputOutputChains tells us to.
2385   DebugLoc dl = Node->getDebugLoc();
2386   std::pair<SDValue, SDValue> CallInfo =
2387     TLI.LowerCallTo(InChain, RetTy, isSigned, !isSigned, false, false,
2388                     0, TLI.getLibcallCallingConv(LC), /*isTailCall=*/false,
2389                     /*isReturnValueUsed=*/true, Callee, Args, DAG, dl);
2390
2391   // Legalize the call sequence, starting with the chain.  This will advance
2392   // the LastCALLSEQ to the legalized version of the CALLSEQ_END node that
2393   // was added by LowerCallTo (guaranteeing proper serialization of calls).
2394   LegalizeOp(CallInfo.second);
2395
2396   // Remainder is loaded back from the stack frame.
2397   SDValue Rem = DAG.getLoad(RetVT, dl, LastCALLSEQ_END, FIPtr,
2398                             MachinePointerInfo(), false, false, 0);
2399   Results.push_back(CallInfo.first);
2400   Results.push_back(Rem);
2401 }
2402
2403 /// ExpandLegalINT_TO_FP - This function is responsible for legalizing a
2404 /// INT_TO_FP operation of the specified operand when the target requests that
2405 /// we expand it.  At this point, we know that the result and operand types are
2406 /// legal for the target.
2407 SDValue SelectionDAGLegalize::ExpandLegalINT_TO_FP(bool isSigned,
2408                                                    SDValue Op0,
2409                                                    EVT DestVT,
2410                                                    DebugLoc dl) {
2411   if (Op0.getValueType() == MVT::i32) {
2412     // simple 32-bit [signed|unsigned] integer to float/double expansion
2413
2414     // Get the stack frame index of a 8 byte buffer.
2415     SDValue StackSlot = DAG.CreateStackTemporary(MVT::f64);
2416
2417     // word offset constant for Hi/Lo address computation
2418     SDValue WordOff = DAG.getConstant(sizeof(int), TLI.getPointerTy());
2419     // set up Hi and Lo (into buffer) address based on endian
2420     SDValue Hi = StackSlot;
2421     SDValue Lo = DAG.getNode(ISD::ADD, dl,
2422                              TLI.getPointerTy(), StackSlot, WordOff);
2423     if (TLI.isLittleEndian())
2424       std::swap(Hi, Lo);
2425
2426     // if signed map to unsigned space
2427     SDValue Op0Mapped;
2428     if (isSigned) {
2429       // constant used to invert sign bit (signed to unsigned mapping)
2430       SDValue SignBit = DAG.getConstant(0x80000000u, MVT::i32);
2431       Op0Mapped = DAG.getNode(ISD::XOR, dl, MVT::i32, Op0, SignBit);
2432     } else {
2433       Op0Mapped = Op0;
2434     }
2435     // store the lo of the constructed double - based on integer input
2436     SDValue Store1 = DAG.getStore(DAG.getEntryNode(), dl,
2437                                   Op0Mapped, Lo, MachinePointerInfo(),
2438                                   false, false, 0);
2439     // initial hi portion of constructed double
2440     SDValue InitialHi = DAG.getConstant(0x43300000u, MVT::i32);
2441     // store the hi of the constructed double - biased exponent
2442     SDValue Store2 = DAG.getStore(Store1, dl, InitialHi, Hi,
2443                                   MachinePointerInfo(),
2444                                   false, false, 0);
2445     // load the constructed double
2446     SDValue Load = DAG.getLoad(MVT::f64, dl, Store2, StackSlot,
2447                                MachinePointerInfo(), false, false, 0);
2448     // FP constant to bias correct the final result
2449     SDValue Bias = DAG.getConstantFP(isSigned ?
2450                                      BitsToDouble(0x4330000080000000ULL) :
2451                                      BitsToDouble(0x4330000000000000ULL),
2452                                      MVT::f64);
2453     // subtract the bias
2454     SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::f64, Load, Bias);
2455     // final result
2456     SDValue Result;
2457     // handle final rounding
2458     if (DestVT == MVT::f64) {
2459       // do nothing
2460       Result = Sub;
2461     } else if (DestVT.bitsLT(MVT::f64)) {
2462       Result = DAG.getNode(ISD::FP_ROUND, dl, DestVT, Sub,
2463                            DAG.getIntPtrConstant(0));
2464     } else if (DestVT.bitsGT(MVT::f64)) {
2465       Result = DAG.getNode(ISD::FP_EXTEND, dl, DestVT, Sub);
2466     }
2467     return Result;
2468   }
2469   assert(!isSigned && "Legalize cannot Expand SINT_TO_FP for i64 yet");
2470   // Code below here assumes !isSigned without checking again.
2471
2472   // Implementation of unsigned i64 to f64 following the algorithm in
2473   // __floatundidf in compiler_rt. This implementation has the advantage
2474   // of performing rounding correctly, both in the default rounding mode
2475   // and in all alternate rounding modes.
2476   // TODO: Generalize this for use with other types.
2477   if (Op0.getValueType() == MVT::i64 && DestVT == MVT::f64) {
2478     SDValue TwoP52 =
2479       DAG.getConstant(UINT64_C(0x4330000000000000), MVT::i64);
2480     SDValue TwoP84PlusTwoP52 =
2481       DAG.getConstantFP(BitsToDouble(UINT64_C(0x4530000000100000)), MVT::f64);
2482     SDValue TwoP84 =
2483       DAG.getConstant(UINT64_C(0x4530000000000000), MVT::i64);
2484
2485     SDValue Lo = DAG.getZeroExtendInReg(Op0, dl, MVT::i32);
2486     SDValue Hi = DAG.getNode(ISD::SRL, dl, MVT::i64, Op0,
2487                              DAG.getConstant(32, MVT::i64));
2488     SDValue LoOr = DAG.getNode(ISD::OR, dl, MVT::i64, Lo, TwoP52);
2489     SDValue HiOr = DAG.getNode(ISD::OR, dl, MVT::i64, Hi, TwoP84);
2490     SDValue LoFlt = DAG.getNode(ISD::BITCAST, dl, MVT::f64, LoOr);
2491     SDValue HiFlt = DAG.getNode(ISD::BITCAST, dl, MVT::f64, HiOr);
2492     SDValue HiSub = DAG.getNode(ISD::FSUB, dl, MVT::f64, HiFlt,
2493                                 TwoP84PlusTwoP52);
2494     return DAG.getNode(ISD::FADD, dl, MVT::f64, LoFlt, HiSub);
2495   }
2496
2497   // Implementation of unsigned i64 to f32.
2498   // TODO: Generalize this for use with other types.
2499   if (Op0.getValueType() == MVT::i64 && DestVT == MVT::f32) {
2500     // For unsigned conversions, convert them to signed conversions using the
2501     // algorithm from the x86_64 __floatundidf in compiler_rt.
2502     if (!isSigned) {
2503       SDValue Fast = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, Op0);
2504
2505       SDValue ShiftConst =
2506           DAG.getConstant(1, TLI.getShiftAmountTy(Op0.getValueType()));
2507       SDValue Shr = DAG.getNode(ISD::SRL, dl, MVT::i64, Op0, ShiftConst);
2508       SDValue AndConst = DAG.getConstant(1, MVT::i64);
2509       SDValue And = DAG.getNode(ISD::AND, dl, MVT::i64, Op0, AndConst);
2510       SDValue Or = DAG.getNode(ISD::OR, dl, MVT::i64, And, Shr);
2511
2512       SDValue SignCvt = DAG.getNode(ISD::SINT_TO_FP, dl, MVT::f32, Or);
2513       SDValue Slow = DAG.getNode(ISD::FADD, dl, MVT::f32, SignCvt, SignCvt);
2514
2515       // TODO: This really should be implemented using a branch rather than a
2516       // select.  We happen to get lucky and machinesink does the right
2517       // thing most of the time.  This would be a good candidate for a
2518       //pseudo-op, or, even better, for whole-function isel.
2519       SDValue SignBitTest = DAG.getSetCC(dl, TLI.getSetCCResultType(MVT::i64),
2520         Op0, DAG.getConstant(0, MVT::i64), ISD::SETLT);
2521       return DAG.getNode(ISD::SELECT, dl, MVT::f32, SignBitTest, Slow, Fast);
2522     }
2523
2524     // Otherwise, implement the fully general conversion.
2525
2526     SDValue And = DAG.getNode(ISD::AND, dl, MVT::i64, Op0,
2527          DAG.getConstant(UINT64_C(0xfffffffffffff800), MVT::i64));
2528     SDValue Or = DAG.getNode(ISD::OR, dl, MVT::i64, And,
2529          DAG.getConstant(UINT64_C(0x800), MVT::i64));
2530     SDValue And2 = DAG.getNode(ISD::AND, dl, MVT::i64, Op0,
2531          DAG.getConstant(UINT64_C(0x7ff), MVT::i64));
2532     SDValue Ne = DAG.getSetCC(dl, TLI.getSetCCResultType(MVT::i64),
2533                    And2, DAG.getConstant(UINT64_C(0), MVT::i64), ISD::SETNE);
2534     SDValue Sel = DAG.getNode(ISD::SELECT, dl, MVT::i64, Ne, Or, Op0);
2535     SDValue Ge = DAG.getSetCC(dl, TLI.getSetCCResultType(MVT::i64),
2536                    Op0, DAG.getConstant(UINT64_C(0x0020000000000000), MVT::i64),
2537                    ISD::SETUGE);
2538     SDValue Sel2 = DAG.getNode(ISD::SELECT, dl, MVT::i64, Ge, Sel, Op0);
2539     EVT SHVT = TLI.getShiftAmountTy(Sel2.getValueType());
2540
2541     SDValue Sh = DAG.getNode(ISD::SRL, dl, MVT::i64, Sel2,
2542                              DAG.getConstant(32, SHVT));
2543     SDValue Trunc = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Sh);
2544     SDValue Fcvt = DAG.getNode(ISD::UINT_TO_FP, dl, MVT::f64, Trunc);
2545     SDValue TwoP32 =
2546       DAG.getConstantFP(BitsToDouble(UINT64_C(0x41f0000000000000)), MVT::f64);
2547     SDValue Fmul = DAG.getNode(ISD::FMUL, dl, MVT::f64, TwoP32, Fcvt);
2548     SDValue Lo = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Sel2);
2549     SDValue Fcvt2 = DAG.getNode(ISD::UINT_TO_FP, dl, MVT::f64, Lo);
2550     SDValue Fadd = DAG.getNode(ISD::FADD, dl, MVT::f64, Fmul, Fcvt2);
2551     return DAG.getNode(ISD::FP_ROUND, dl, MVT::f32, Fadd,
2552                        DAG.getIntPtrConstant(0));
2553   }
2554
2555   SDValue Tmp1 = DAG.getNode(ISD::SINT_TO_FP, dl, DestVT, Op0);
2556
2557   SDValue SignSet = DAG.getSetCC(dl, TLI.getSetCCResultType(Op0.getValueType()),
2558                                  Op0, DAG.getConstant(0, Op0.getValueType()),
2559                                  ISD::SETLT);
2560   SDValue Zero = DAG.getIntPtrConstant(0), Four = DAG.getIntPtrConstant(4);
2561   SDValue CstOffset = DAG.getNode(ISD::SELECT, dl, Zero.getValueType(),
2562                                     SignSet, Four, Zero);
2563
2564   // If the sign bit of the integer is set, the large number will be treated
2565   // as a negative number.  To counteract this, the dynamic code adds an
2566   // offset depending on the data type.
2567   uint64_t FF;
2568   switch (Op0.getValueType().getSimpleVT().SimpleTy) {
2569   default: assert(0 && "Unsupported integer type!");
2570   case MVT::i8 : FF = 0x43800000ULL; break;  // 2^8  (as a float)
2571   case MVT::i16: FF = 0x47800000ULL; break;  // 2^16 (as a float)
2572   case MVT::i32: FF = 0x4F800000ULL; break;  // 2^32 (as a float)
2573   case MVT::i64: FF = 0x5F800000ULL; break;  // 2^64 (as a float)
2574   }
2575   if (TLI.isLittleEndian()) FF <<= 32;
2576   Constant *FudgeFactor = ConstantInt::get(
2577                                        Type::getInt64Ty(*DAG.getContext()), FF);
2578
2579   SDValue CPIdx = DAG.getConstantPool(FudgeFactor, TLI.getPointerTy());
2580   unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
2581   CPIdx = DAG.getNode(ISD::ADD, dl, TLI.getPointerTy(), CPIdx, CstOffset);
2582   Alignment = std::min(Alignment, 4u);
2583   SDValue FudgeInReg;
2584   if (DestVT == MVT::f32)
2585     FudgeInReg = DAG.getLoad(MVT::f32, dl, DAG.getEntryNode(), CPIdx,
2586                              MachinePointerInfo::getConstantPool(),
2587                              false, false, Alignment);
2588   else {
2589     FudgeInReg =
2590       LegalizeOp(DAG.getExtLoad(ISD::EXTLOAD, dl, DestVT,
2591                                 DAG.getEntryNode(), CPIdx,
2592                                 MachinePointerInfo::getConstantPool(),
2593                                 MVT::f32, false, false, Alignment));
2594   }
2595
2596   return DAG.getNode(ISD::FADD, dl, DestVT, Tmp1, FudgeInReg);
2597 }
2598
2599 /// PromoteLegalINT_TO_FP - This function is responsible for legalizing a
2600 /// *INT_TO_FP operation of the specified operand when the target requests that
2601 /// we promote it.  At this point, we know that the result and operand types are
2602 /// legal for the target, and that there is a legal UINT_TO_FP or SINT_TO_FP
2603 /// operation that takes a larger input.
2604 SDValue SelectionDAGLegalize::PromoteLegalINT_TO_FP(SDValue LegalOp,
2605                                                     EVT DestVT,
2606                                                     bool isSigned,
2607                                                     DebugLoc dl) {
2608   // First step, figure out the appropriate *INT_TO_FP operation to use.
2609   EVT NewInTy = LegalOp.getValueType();
2610
2611   unsigned OpToUse = 0;
2612
2613   // Scan for the appropriate larger type to use.
2614   while (1) {
2615     NewInTy = (MVT::SimpleValueType)(NewInTy.getSimpleVT().SimpleTy+1);
2616     assert(NewInTy.isInteger() && "Ran out of possibilities!");
2617
2618     // If the target supports SINT_TO_FP of this type, use it.
2619     if (TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, NewInTy)) {
2620       OpToUse = ISD::SINT_TO_FP;
2621       break;
2622     }
2623     if (isSigned) continue;
2624
2625     // If the target supports UINT_TO_FP of this type, use it.
2626     if (TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, NewInTy)) {
2627       OpToUse = ISD::UINT_TO_FP;
2628       break;
2629     }
2630
2631     // Otherwise, try a larger type.
2632   }
2633
2634   // Okay, we found the operation and type to use.  Zero extend our input to the
2635   // desired type then run the operation on it.
2636   return DAG.getNode(OpToUse, dl, DestVT,
2637                      DAG.getNode(isSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND,
2638                                  dl, NewInTy, LegalOp));
2639 }
2640
2641 /// PromoteLegalFP_TO_INT - This function is responsible for legalizing a
2642 /// FP_TO_*INT operation of the specified operand when the target requests that
2643 /// we promote it.  At this point, we know that the result and operand types are
2644 /// legal for the target, and that there is a legal FP_TO_UINT or FP_TO_SINT
2645 /// operation that returns a larger result.
2646 SDValue SelectionDAGLegalize::PromoteLegalFP_TO_INT(SDValue LegalOp,
2647                                                     EVT DestVT,
2648                                                     bool isSigned,
2649                                                     DebugLoc dl) {
2650   // First step, figure out the appropriate FP_TO*INT operation to use.
2651   EVT NewOutTy = DestVT;
2652
2653   unsigned OpToUse = 0;
2654
2655   // Scan for the appropriate larger type to use.
2656   while (1) {
2657     NewOutTy = (MVT::SimpleValueType)(NewOutTy.getSimpleVT().SimpleTy+1);
2658     assert(NewOutTy.isInteger() && "Ran out of possibilities!");
2659
2660     if (TLI.isOperationLegalOrCustom(ISD::FP_TO_SINT, NewOutTy)) {
2661       OpToUse = ISD::FP_TO_SINT;
2662       break;
2663     }
2664
2665     if (TLI.isOperationLegalOrCustom(ISD::FP_TO_UINT, NewOutTy)) {
2666       OpToUse = ISD::FP_TO_UINT;
2667       break;
2668     }
2669
2670     // Otherwise, try a larger type.
2671   }
2672
2673
2674   // Okay, we found the operation and type to use.
2675   SDValue Operation = DAG.getNode(OpToUse, dl, NewOutTy, LegalOp);
2676
2677   // Truncate the result of the extended FP_TO_*INT operation to the desired
2678   // size.
2679   return DAG.getNode(ISD::TRUNCATE, dl, DestVT, Operation);
2680 }
2681
2682 /// ExpandBSWAP - Open code the operations for BSWAP of the specified operation.
2683 ///
2684 SDValue SelectionDAGLegalize::ExpandBSWAP(SDValue Op, DebugLoc dl) {
2685   EVT VT = Op.getValueType();
2686   EVT SHVT = TLI.getShiftAmountTy(VT);
2687   SDValue Tmp1, Tmp2, Tmp3, Tmp4, Tmp5, Tmp6, Tmp7, Tmp8;
2688   switch (VT.getSimpleVT().SimpleTy) {
2689   default: assert(0 && "Unhandled Expand type in BSWAP!");
2690   case MVT::i16:
2691     Tmp2 = DAG.getNode(ISD::SHL, dl, VT, Op, DAG.getConstant(8, SHVT));
2692     Tmp1 = DAG.getNode(ISD::SRL, dl, VT, Op, DAG.getConstant(8, SHVT));
2693     return DAG.getNode(ISD::OR, dl, VT, Tmp1, Tmp2);
2694   case MVT::i32:
2695     Tmp4 = DAG.getNode(ISD::SHL, dl, VT, Op, DAG.getConstant(24, SHVT));
2696     Tmp3 = DAG.getNode(ISD::SHL, dl, VT, Op, DAG.getConstant(8, SHVT));
2697     Tmp2 = DAG.getNode(ISD::SRL, dl, VT, Op, DAG.getConstant(8, SHVT));
2698     Tmp1 = DAG.getNode(ISD::SRL, dl, VT, Op, DAG.getConstant(24, SHVT));
2699     Tmp3 = DAG.getNode(ISD::AND, dl, VT, Tmp3, DAG.getConstant(0xFF0000, VT));
2700     Tmp2 = DAG.getNode(ISD::AND, dl, VT, Tmp2, DAG.getConstant(0xFF00, VT));
2701     Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp3);
2702     Tmp2 = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp1);
2703     return DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp2);
2704   case MVT::i64:
2705     Tmp8 = DAG.getNode(ISD::SHL, dl, VT, Op, DAG.getConstant(56, SHVT));
2706     Tmp7 = DAG.getNode(ISD::SHL, dl, VT, Op, DAG.getConstant(40, SHVT));
2707     Tmp6 = DAG.getNode(ISD::SHL, dl, VT, Op, DAG.getConstant(24, SHVT));
2708     Tmp5 = DAG.getNode(ISD::SHL, dl, VT, Op, DAG.getConstant(8, SHVT));
2709     Tmp4 = DAG.getNode(ISD::SRL, dl, VT, Op, DAG.getConstant(8, SHVT));
2710     Tmp3 = DAG.getNode(ISD::SRL, dl, VT, Op, DAG.getConstant(24, SHVT));
2711     Tmp2 = DAG.getNode(ISD::SRL, dl, VT, Op, DAG.getConstant(40, SHVT));
2712     Tmp1 = DAG.getNode(ISD::SRL, dl, VT, Op, DAG.getConstant(56, SHVT));
2713     Tmp7 = DAG.getNode(ISD::AND, dl, VT, Tmp7, DAG.getConstant(255ULL<<48, VT));
2714     Tmp6 = DAG.getNode(ISD::AND, dl, VT, Tmp6, DAG.getConstant(255ULL<<40, VT));
2715     Tmp5 = DAG.getNode(ISD::AND, dl, VT, Tmp5, DAG.getConstant(255ULL<<32, VT));
2716     Tmp4 = DAG.getNode(ISD::AND, dl, VT, Tmp4, DAG.getConstant(255ULL<<24, VT));
2717     Tmp3 = DAG.getNode(ISD::AND, dl, VT, Tmp3, DAG.getConstant(255ULL<<16, VT));
2718     Tmp2 = DAG.getNode(ISD::AND, dl, VT, Tmp2, DAG.getConstant(255ULL<<8 , VT));
2719     Tmp8 = DAG.getNode(ISD::OR, dl, VT, Tmp8, Tmp7);
2720     Tmp6 = DAG.getNode(ISD::OR, dl, VT, Tmp6, Tmp5);
2721     Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp3);
2722     Tmp2 = DAG.getNode(ISD::OR, dl, VT, Tmp2, Tmp1);
2723     Tmp8 = DAG.getNode(ISD::OR, dl, VT, Tmp8, Tmp6);
2724     Tmp4 = DAG.getNode(ISD::OR, dl, VT, Tmp4, Tmp2);
2725     return DAG.getNode(ISD::OR, dl, VT, Tmp8, Tmp4);
2726   }
2727 }
2728
2729 /// SplatByte - Distribute ByteVal over NumBits bits.
2730 // FIXME: Move this helper to a common place.
2731 static APInt SplatByte(unsigned NumBits, uint8_t ByteVal) {
2732   APInt Val = APInt(NumBits, ByteVal);
2733   unsigned Shift = 8;
2734   for (unsigned i = NumBits; i > 8; i >>= 1) {
2735     Val = (Val << Shift) | Val;
2736     Shift <<= 1;
2737   }
2738   return Val;
2739 }
2740
2741 /// ExpandBitCount - Expand the specified bitcount instruction into operations.
2742 ///
2743 SDValue SelectionDAGLegalize::ExpandBitCount(unsigned Opc, SDValue Op,
2744                                              DebugLoc dl) {
2745   switch (Opc) {
2746   default: assert(0 && "Cannot expand this yet!");
2747   case ISD::CTPOP: {
2748     EVT VT = Op.getValueType();
2749     EVT ShVT = TLI.getShiftAmountTy(VT);
2750     unsigned Len = VT.getSizeInBits();
2751
2752     assert(VT.isInteger() && Len <= 128 && Len % 8 == 0 &&
2753            "CTPOP not implemented for this type.");
2754
2755     // This is the "best" algorithm from
2756     // http://graphics.stanford.edu/~seander/bithacks.html#CountBitsSetParallel
2757
2758     SDValue Mask55 = DAG.getConstant(SplatByte(Len, 0x55), VT);
2759     SDValue Mask33 = DAG.getConstant(SplatByte(Len, 0x33), VT);
2760     SDValue Mask0F = DAG.getConstant(SplatByte(Len, 0x0F), VT);
2761     SDValue Mask01 = DAG.getConstant(SplatByte(Len, 0x01), VT);
2762
2763     // v = v - ((v >> 1) & 0x55555555...)
2764     Op = DAG.getNode(ISD::SUB, dl, VT, Op,
2765                      DAG.getNode(ISD::AND, dl, VT,
2766                                  DAG.getNode(ISD::SRL, dl, VT, Op,
2767                                              DAG.getConstant(1, ShVT)),
2768                                  Mask55));
2769     // v = (v & 0x33333333...) + ((v >> 2) & 0x33333333...)
2770     Op = DAG.getNode(ISD::ADD, dl, VT,
2771                      DAG.getNode(ISD::AND, dl, VT, Op, Mask33),
2772                      DAG.getNode(ISD::AND, dl, VT,
2773                                  DAG.getNode(ISD::SRL, dl, VT, Op,
2774                                              DAG.getConstant(2, ShVT)),
2775                                  Mask33));
2776     // v = (v + (v >> 4)) & 0x0F0F0F0F...
2777     Op = DAG.getNode(ISD::AND, dl, VT,
2778                      DAG.getNode(ISD::ADD, dl, VT, Op,
2779                                  DAG.getNode(ISD::SRL, dl, VT, Op,
2780                                              DAG.getConstant(4, ShVT))),
2781                      Mask0F);
2782     // v = (v * 0x01010101...) >> (Len - 8)
2783     Op = DAG.getNode(ISD::SRL, dl, VT,
2784                      DAG.getNode(ISD::MUL, dl, VT, Op, Mask01),
2785                      DAG.getConstant(Len - 8, ShVT));
2786
2787     return Op;
2788   }
2789   case ISD::CTLZ: {
2790     // for now, we do this:
2791     // x = x | (x >> 1);
2792     // x = x | (x >> 2);
2793     // ...
2794     // x = x | (x >>16);
2795     // x = x | (x >>32); // for 64-bit input
2796     // return popcount(~x);
2797     //
2798     // but see also: http://www.hackersdelight.org/HDcode/nlz.cc
2799     EVT VT = Op.getValueType();
2800     EVT ShVT = TLI.getShiftAmountTy(VT);
2801     unsigned len = VT.getSizeInBits();
2802     for (unsigned i = 0; (1U << i) <= (len / 2); ++i) {
2803       SDValue Tmp3 = DAG.getConstant(1ULL << i, ShVT);
2804       Op = DAG.getNode(ISD::OR, dl, VT, Op,
2805                        DAG.getNode(ISD::SRL, dl, VT, Op, Tmp3));
2806     }
2807     Op = DAG.getNOT(dl, Op, VT);
2808     return DAG.getNode(ISD::CTPOP, dl, VT, Op);
2809   }
2810   case ISD::CTTZ: {
2811     // for now, we use: { return popcount(~x & (x - 1)); }
2812     // unless the target has ctlz but not ctpop, in which case we use:
2813     // { return 32 - nlz(~x & (x-1)); }
2814     // see also http://www.hackersdelight.org/HDcode/ntz.cc
2815     EVT VT = Op.getValueType();
2816     SDValue Tmp3 = DAG.getNode(ISD::AND, dl, VT,
2817                                DAG.getNOT(dl, Op, VT),
2818                                DAG.getNode(ISD::SUB, dl, VT, Op,
2819                                            DAG.getConstant(1, VT)));
2820     // If ISD::CTLZ is legal and CTPOP isn't, then do that instead.
2821     if (!TLI.isOperationLegalOrCustom(ISD::CTPOP, VT) &&
2822         TLI.isOperationLegalOrCustom(ISD::CTLZ, VT))
2823       return DAG.getNode(ISD::SUB, dl, VT,
2824                          DAG.getConstant(VT.getSizeInBits(), VT),
2825                          DAG.getNode(ISD::CTLZ, dl, VT, Tmp3));
2826     return DAG.getNode(ISD::CTPOP, dl, VT, Tmp3);
2827   }
2828   }
2829 }
2830
2831 std::pair <SDValue, SDValue> SelectionDAGLegalize::ExpandAtomic(SDNode *Node) {
2832   unsigned Opc = Node->getOpcode();
2833   MVT VT = cast<AtomicSDNode>(Node)->getMemoryVT().getSimpleVT();
2834   RTLIB::Libcall LC;
2835
2836   switch (Opc) {
2837   default:
2838     llvm_unreachable("Unhandled atomic intrinsic Expand!");
2839     break;
2840   case ISD::ATOMIC_SWAP:
2841     switch (VT.SimpleTy) {
2842     default: llvm_unreachable("Unexpected value type for atomic!");
2843     case MVT::i8:  LC = RTLIB::SYNC_LOCK_TEST_AND_SET_1; break;
2844     case MVT::i16: LC = RTLIB::SYNC_LOCK_TEST_AND_SET_2; break;
2845     case MVT::i32: LC = RTLIB::SYNC_LOCK_TEST_AND_SET_4; break;
2846     case MVT::i64: LC = RTLIB::SYNC_LOCK_TEST_AND_SET_8; break;
2847     }
2848     break;
2849   case ISD::ATOMIC_CMP_SWAP:
2850     switch (VT.SimpleTy) {
2851     default: llvm_unreachable("Unexpected value type for atomic!");
2852     case MVT::i8:  LC = RTLIB::SYNC_VAL_COMPARE_AND_SWAP_1; break;
2853     case MVT::i16: LC = RTLIB::SYNC_VAL_COMPARE_AND_SWAP_2; break;
2854     case MVT::i32: LC = RTLIB::SYNC_VAL_COMPARE_AND_SWAP_4; break;
2855     case MVT::i64: LC = RTLIB::SYNC_VAL_COMPARE_AND_SWAP_8; break;
2856     }
2857     break;
2858   case ISD::ATOMIC_LOAD_ADD:
2859     switch (VT.SimpleTy) {
2860     default: llvm_unreachable("Unexpected value type for atomic!");
2861     case MVT::i8:  LC = RTLIB::SYNC_FETCH_AND_ADD_1; break;
2862     case MVT::i16: LC = RTLIB::SYNC_FETCH_AND_ADD_2; break;
2863     case MVT::i32: LC = RTLIB::SYNC_FETCH_AND_ADD_4; break;
2864     case MVT::i64: LC = RTLIB::SYNC_FETCH_AND_ADD_8; break;
2865     }
2866     break;
2867   case ISD::ATOMIC_LOAD_SUB:
2868     switch (VT.SimpleTy) {
2869     default: llvm_unreachable("Unexpected value type for atomic!");
2870     case MVT::i8:  LC = RTLIB::SYNC_FETCH_AND_SUB_1; break;
2871     case MVT::i16: LC = RTLIB::SYNC_FETCH_AND_SUB_2; break;
2872     case MVT::i32: LC = RTLIB::SYNC_FETCH_AND_SUB_4; break;
2873     case MVT::i64: LC = RTLIB::SYNC_FETCH_AND_SUB_8; break;
2874     }
2875     break;
2876   case ISD::ATOMIC_LOAD_AND:
2877     switch (VT.SimpleTy) {
2878     default: llvm_unreachable("Unexpected value type for atomic!");
2879     case MVT::i8:  LC = RTLIB::SYNC_FETCH_AND_AND_1; break;
2880     case MVT::i16: LC = RTLIB::SYNC_FETCH_AND_AND_2; break;
2881     case MVT::i32: LC = RTLIB::SYNC_FETCH_AND_AND_4; break;
2882     case MVT::i64: LC = RTLIB::SYNC_FETCH_AND_AND_8; break;
2883     }
2884     break;
2885   case ISD::ATOMIC_LOAD_OR:
2886     switch (VT.SimpleTy) {
2887     default: llvm_unreachable("Unexpected value type for atomic!");
2888     case MVT::i8:  LC = RTLIB::SYNC_FETCH_AND_OR_1; break;
2889     case MVT::i16: LC = RTLIB::SYNC_FETCH_AND_OR_2; break;
2890     case MVT::i32: LC = RTLIB::SYNC_FETCH_AND_OR_4; break;
2891     case MVT::i64: LC = RTLIB::SYNC_FETCH_AND_OR_8; break;
2892     }
2893     break;
2894   case ISD::ATOMIC_LOAD_XOR:
2895     switch (VT.SimpleTy) {
2896     default: llvm_unreachable("Unexpected value type for atomic!");
2897     case MVT::i8:  LC = RTLIB::SYNC_FETCH_AND_XOR_1; break;
2898     case MVT::i16: LC = RTLIB::SYNC_FETCH_AND_XOR_2; break;
2899     case MVT::i32: LC = RTLIB::SYNC_FETCH_AND_XOR_4; break;
2900     case MVT::i64: LC = RTLIB::SYNC_FETCH_AND_XOR_8; break;
2901     }
2902     break;
2903   case ISD::ATOMIC_LOAD_NAND:
2904     switch (VT.SimpleTy) {
2905     default: llvm_unreachable("Unexpected value type for atomic!");
2906     case MVT::i8:  LC = RTLIB::SYNC_FETCH_AND_NAND_1; break;
2907     case MVT::i16: LC = RTLIB::SYNC_FETCH_AND_NAND_2; break;
2908     case MVT::i32: LC = RTLIB::SYNC_FETCH_AND_NAND_4; break;
2909     case MVT::i64: LC = RTLIB::SYNC_FETCH_AND_NAND_8; break;
2910     }
2911     break;
2912   }
2913
2914   return ExpandChainLibCall(LC, Node, false);
2915 }
2916
2917 void SelectionDAGLegalize::ExpandNode(SDNode *Node,
2918                                       SmallVectorImpl<SDValue> &Results) {
2919   DebugLoc dl = Node->getDebugLoc();
2920   SDValue Tmp1, Tmp2, Tmp3, Tmp4;
2921   switch (Node->getOpcode()) {
2922   case ISD::CTPOP:
2923   case ISD::CTLZ:
2924   case ISD::CTTZ:
2925     Tmp1 = ExpandBitCount(Node->getOpcode(), Node->getOperand(0), dl);
2926     Results.push_back(Tmp1);
2927     break;
2928   case ISD::BSWAP:
2929     Results.push_back(ExpandBSWAP(Node->getOperand(0), dl));
2930     break;
2931   case ISD::FRAMEADDR:
2932   case ISD::RETURNADDR:
2933   case ISD::FRAME_TO_ARGS_OFFSET:
2934     Results.push_back(DAG.getConstant(0, Node->getValueType(0)));
2935     break;
2936   case ISD::FLT_ROUNDS_:
2937     Results.push_back(DAG.getConstant(1, Node->getValueType(0)));
2938     break;
2939   case ISD::EH_RETURN:
2940   case ISD::EH_LABEL:
2941   case ISD::PREFETCH:
2942   case ISD::VAEND:
2943   case ISD::EH_SJLJ_LONGJMP:
2944   case ISD::EH_SJLJ_DISPATCHSETUP:
2945     // If the target didn't expand these, there's nothing to do, so just
2946     // preserve the chain and be done.
2947     Results.push_back(Node->getOperand(0));
2948     break;
2949   case ISD::EH_SJLJ_SETJMP:
2950     // If the target didn't expand this, just return 'zero' and preserve the
2951     // chain.
2952     Results.push_back(DAG.getConstant(0, MVT::i32));
2953     Results.push_back(Node->getOperand(0));
2954     break;
2955   case ISD::ATOMIC_FENCE:
2956   case ISD::MEMBARRIER: {
2957     // If the target didn't lower this, lower it to '__sync_synchronize()' call
2958     // FIXME: handle "fence singlethread" more efficiently.
2959     TargetLowering::ArgListTy Args;
2960     std::pair<SDValue, SDValue> CallResult =
2961       TLI.LowerCallTo(Node->getOperand(0), Type::getVoidTy(*DAG.getContext()),
2962                       false, false, false, false, 0, CallingConv::C,
2963                       /*isTailCall=*/false,
2964                       /*isReturnValueUsed=*/true,
2965                       DAG.getExternalSymbol("__sync_synchronize",
2966                                             TLI.getPointerTy()),
2967                       Args, DAG, dl);
2968     Results.push_back(CallResult.second);
2969     break;
2970   }
2971   case ISD::ATOMIC_LOAD: {
2972     // There is no libcall for atomic load; fake it with ATOMIC_CMP_SWAP.
2973     SDValue Zero = DAG.getConstant(0, cast<AtomicSDNode>(Node)->getMemoryVT());
2974     SDValue Swap = DAG.getAtomic(ISD::ATOMIC_CMP_SWAP, dl,
2975                                  cast<AtomicSDNode>(Node)->getMemoryVT(),
2976                                  Node->getOperand(0),
2977                                  Node->getOperand(1), Zero, Zero,
2978                                  cast<AtomicSDNode>(Node)->getMemOperand(),
2979                                  cast<AtomicSDNode>(Node)->getOrdering(),
2980                                  cast<AtomicSDNode>(Node)->getSynchScope());
2981     Results.push_back(Swap.getValue(0));
2982     Results.push_back(Swap.getValue(1));
2983     break;
2984   }
2985   case ISD::ATOMIC_STORE: {
2986     // There is no libcall for atomic store; fake it with ATOMIC_SWAP.
2987     SDValue Swap = DAG.getAtomic(ISD::ATOMIC_SWAP, dl,
2988                                  cast<AtomicSDNode>(Node)->getMemoryVT(),
2989                                  Node->getOperand(0),
2990                                  Node->getOperand(1), Node->getOperand(2),
2991                                  cast<AtomicSDNode>(Node)->getMemOperand(),
2992                                  cast<AtomicSDNode>(Node)->getOrdering(),
2993                                  cast<AtomicSDNode>(Node)->getSynchScope());
2994     Results.push_back(Swap.getValue(1));
2995     break;
2996   }
2997   // By default, atomic intrinsics are marked Legal and lowered. Targets
2998   // which don't support them directly, however, may want libcalls, in which
2999   // case they mark them Expand, and we get here.
3000   case ISD::ATOMIC_SWAP:
3001   case ISD::ATOMIC_LOAD_ADD:
3002   case ISD::ATOMIC_LOAD_SUB:
3003   case ISD::ATOMIC_LOAD_AND:
3004   case ISD::ATOMIC_LOAD_OR:
3005   case ISD::ATOMIC_LOAD_XOR:
3006   case ISD::ATOMIC_LOAD_NAND:
3007   case ISD::ATOMIC_LOAD_MIN:
3008   case ISD::ATOMIC_LOAD_MAX:
3009   case ISD::ATOMIC_LOAD_UMIN:
3010   case ISD::ATOMIC_LOAD_UMAX:
3011   case ISD::ATOMIC_CMP_SWAP: {
3012     std::pair<SDValue, SDValue> Tmp = ExpandAtomic(Node);
3013     Results.push_back(Tmp.first);
3014     Results.push_back(Tmp.second);
3015     break;
3016   }
3017   case ISD::DYNAMIC_STACKALLOC:
3018     ExpandDYNAMIC_STACKALLOC(Node, Results);
3019     break;
3020   case ISD::MERGE_VALUES:
3021     for (unsigned i = 0; i < Node->getNumValues(); i++)
3022       Results.push_back(Node->getOperand(i));
3023     break;
3024   case ISD::UNDEF: {
3025     EVT VT = Node->getValueType(0);
3026     if (VT.isInteger())
3027       Results.push_back(DAG.getConstant(0, VT));
3028     else {
3029       assert(VT.isFloatingPoint() && "Unknown value type!");
3030       Results.push_back(DAG.getConstantFP(0, VT));
3031     }
3032     break;
3033   }
3034   case ISD::TRAP: {
3035     // If this operation is not supported, lower it to 'abort()' call
3036     TargetLowering::ArgListTy Args;
3037     std::pair<SDValue, SDValue> CallResult =
3038       TLI.LowerCallTo(Node->getOperand(0), Type::getVoidTy(*DAG.getContext()),
3039                       false, false, false, false, 0, CallingConv::C,
3040                       /*isTailCall=*/false,
3041                       /*isReturnValueUsed=*/true,
3042                       DAG.getExternalSymbol("abort", TLI.getPointerTy()),
3043                       Args, DAG, dl);
3044     Results.push_back(CallResult.second);
3045     break;
3046   }
3047   case ISD::FP_ROUND:
3048   case ISD::BITCAST:
3049     Tmp1 = EmitStackConvert(Node->getOperand(0), Node->getValueType(0),
3050                             Node->getValueType(0), dl);
3051     Results.push_back(Tmp1);
3052     break;
3053   case ISD::FP_EXTEND:
3054     Tmp1 = EmitStackConvert(Node->getOperand(0),
3055                             Node->getOperand(0).getValueType(),
3056                             Node->getValueType(0), dl);
3057     Results.push_back(Tmp1);
3058     break;
3059   case ISD::SIGN_EXTEND_INREG: {
3060     // NOTE: we could fall back on load/store here too for targets without
3061     // SAR.  However, it is doubtful that any exist.
3062     EVT ExtraVT = cast<VTSDNode>(Node->getOperand(1))->getVT();
3063     EVT VT = Node->getValueType(0);
3064     EVT ShiftAmountTy = TLI.getShiftAmountTy(VT);
3065     if (VT.isVector())
3066       ShiftAmountTy = VT;
3067     unsigned BitsDiff = VT.getScalarType().getSizeInBits() -
3068                         ExtraVT.getScalarType().getSizeInBits();
3069     SDValue ShiftCst = DAG.getConstant(BitsDiff, ShiftAmountTy);
3070     Tmp1 = DAG.getNode(ISD::SHL, dl, Node->getValueType(0),
3071                        Node->getOperand(0), ShiftCst);
3072     Tmp1 = DAG.getNode(ISD::SRA, dl, Node->getValueType(0), Tmp1, ShiftCst);
3073     Results.push_back(Tmp1);
3074     break;
3075   }
3076   case ISD::FP_ROUND_INREG: {
3077     // The only way we can lower this is to turn it into a TRUNCSTORE,
3078     // EXTLOAD pair, targeting a temporary location (a stack slot).
3079
3080     // NOTE: there is a choice here between constantly creating new stack
3081     // slots and always reusing the same one.  We currently always create
3082     // new ones, as reuse may inhibit scheduling.
3083     EVT ExtraVT = cast<VTSDNode>(Node->getOperand(1))->getVT();
3084     Tmp1 = EmitStackConvert(Node->getOperand(0), ExtraVT,
3085                             Node->getValueType(0), dl);
3086     Results.push_back(Tmp1);
3087     break;
3088   }
3089   case ISD::SINT_TO_FP:
3090   case ISD::UINT_TO_FP:
3091     Tmp1 = ExpandLegalINT_TO_FP(Node->getOpcode() == ISD::SINT_TO_FP,
3092                                 Node->getOperand(0), Node->getValueType(0), dl);
3093     Results.push_back(Tmp1);
3094     break;
3095   case ISD::FP_TO_UINT: {
3096     SDValue True, False;
3097     EVT VT =  Node->getOperand(0).getValueType();
3098     EVT NVT = Node->getValueType(0);
3099     APFloat apf(APInt::getNullValue(VT.getSizeInBits()));
3100     APInt x = APInt::getSignBit(NVT.getSizeInBits());
3101     (void)apf.convertFromAPInt(x, false, APFloat::rmNearestTiesToEven);
3102     Tmp1 = DAG.getConstantFP(apf, VT);
3103     Tmp2 = DAG.getSetCC(dl, TLI.getSetCCResultType(VT),
3104                         Node->getOperand(0),
3105                         Tmp1, ISD::SETLT);
3106     True = DAG.getNode(ISD::FP_TO_SINT, dl, NVT, Node->getOperand(0));
3107     False = DAG.getNode(ISD::FP_TO_SINT, dl, NVT,
3108                         DAG.getNode(ISD::FSUB, dl, VT,
3109                                     Node->getOperand(0), Tmp1));
3110     False = DAG.getNode(ISD::XOR, dl, NVT, False,
3111                         DAG.getConstant(x, NVT));
3112     Tmp1 = DAG.getNode(ISD::SELECT, dl, NVT, Tmp2, True, False);
3113     Results.push_back(Tmp1);
3114     break;
3115   }
3116   case ISD::VAARG: {
3117     const Value *V = cast<SrcValueSDNode>(Node->getOperand(2))->getValue();
3118     EVT VT = Node->getValueType(0);
3119     Tmp1 = Node->getOperand(0);
3120     Tmp2 = Node->getOperand(1);
3121     unsigned Align = Node->getConstantOperandVal(3);
3122
3123     SDValue VAListLoad = DAG.getLoad(TLI.getPointerTy(), dl, Tmp1, Tmp2,
3124                                      MachinePointerInfo(V), false, false, 0);
3125     SDValue VAList = VAListLoad;
3126
3127     if (Align > TLI.getMinStackArgumentAlignment()) {
3128       assert(((Align & (Align-1)) == 0) && "Expected Align to be a power of 2");
3129
3130       VAList = DAG.getNode(ISD::ADD, dl, TLI.getPointerTy(), VAList,
3131                            DAG.getConstant(Align - 1,
3132                                            TLI.getPointerTy()));
3133
3134       VAList = DAG.getNode(ISD::AND, dl, TLI.getPointerTy(), VAList,
3135                            DAG.getConstant(-(int64_t)Align,
3136                                            TLI.getPointerTy()));
3137     }
3138
3139     // Increment the pointer, VAList, to the next vaarg
3140     Tmp3 = DAG.getNode(ISD::ADD, dl, TLI.getPointerTy(), VAList,
3141                        DAG.getConstant(TLI.getTargetData()->
3142                           getTypeAllocSize(VT.getTypeForEVT(*DAG.getContext())),
3143                                        TLI.getPointerTy()));
3144     // Store the incremented VAList to the legalized pointer
3145     Tmp3 = DAG.getStore(VAListLoad.getValue(1), dl, Tmp3, Tmp2,
3146                         MachinePointerInfo(V), false, false, 0);
3147     // Load the actual argument out of the pointer VAList
3148     Results.push_back(DAG.getLoad(VT, dl, Tmp3, VAList, MachinePointerInfo(),
3149                                   false, false, 0));
3150     Results.push_back(Results[0].getValue(1));
3151     break;
3152   }
3153   case ISD::VACOPY: {
3154     // This defaults to loading a pointer from the input and storing it to the
3155     // output, returning the chain.
3156     const Value *VD = cast<SrcValueSDNode>(Node->getOperand(3))->getValue();
3157     const Value *VS = cast<SrcValueSDNode>(Node->getOperand(4))->getValue();
3158     Tmp1 = DAG.getLoad(TLI.getPointerTy(), dl, Node->getOperand(0),
3159                        Node->getOperand(2), MachinePointerInfo(VS),
3160                        false, false, 0);
3161     Tmp1 = DAG.getStore(Tmp1.getValue(1), dl, Tmp1, Node->getOperand(1),
3162                         MachinePointerInfo(VD), false, false, 0);
3163     Results.push_back(Tmp1);
3164     break;
3165   }
3166   case ISD::EXTRACT_VECTOR_ELT:
3167     if (Node->getOperand(0).getValueType().getVectorNumElements() == 1)
3168       // This must be an access of the only element.  Return it.
3169       Tmp1 = DAG.getNode(ISD::BITCAST, dl, Node->getValueType(0),
3170                          Node->getOperand(0));
3171     else
3172       Tmp1 = ExpandExtractFromVectorThroughStack(SDValue(Node, 0));
3173     Results.push_back(Tmp1);
3174     break;
3175   case ISD::EXTRACT_SUBVECTOR:
3176     Results.push_back(ExpandExtractFromVectorThroughStack(SDValue(Node, 0)));
3177     break;
3178   case ISD::INSERT_SUBVECTOR:
3179     Results.push_back(ExpandInsertToVectorThroughStack(SDValue(Node, 0)));
3180     break;
3181   case ISD::CONCAT_VECTORS: {
3182     Results.push_back(ExpandVectorBuildThroughStack(Node));
3183     break;
3184   }
3185   case ISD::SCALAR_TO_VECTOR:
3186     Results.push_back(ExpandSCALAR_TO_VECTOR(Node));
3187     break;
3188   case ISD::INSERT_VECTOR_ELT:
3189     Results.push_back(ExpandINSERT_VECTOR_ELT(Node->getOperand(0),
3190                                               Node->getOperand(1),
3191                                               Node->getOperand(2), dl));
3192     break;
3193   case ISD::VECTOR_SHUFFLE: {
3194     SmallVector<int, 8> Mask;
3195     cast<ShuffleVectorSDNode>(Node)->getMask(Mask);
3196
3197     EVT VT = Node->getValueType(0);
3198     EVT EltVT = VT.getVectorElementType();
3199     if (!TLI.isTypeLegal(EltVT))
3200       EltVT = TLI.getTypeToTransformTo(*DAG.getContext(), EltVT);
3201     unsigned NumElems = VT.getVectorNumElements();
3202     SmallVector<SDValue, 8> Ops;
3203     for (unsigned i = 0; i != NumElems; ++i) {
3204       if (Mask[i] < 0) {
3205         Ops.push_back(DAG.getUNDEF(EltVT));
3206         continue;
3207       }
3208       unsigned Idx = Mask[i];
3209       if (Idx < NumElems)
3210         Ops.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT,
3211                                   Node->getOperand(0),
3212                                   DAG.getIntPtrConstant(Idx)));
3213       else
3214         Ops.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT,
3215                                   Node->getOperand(1),
3216                                   DAG.getIntPtrConstant(Idx - NumElems)));
3217     }
3218     Tmp1 = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, &Ops[0], Ops.size());
3219     Results.push_back(Tmp1);
3220     break;
3221   }
3222   case ISD::EXTRACT_ELEMENT: {
3223     EVT OpTy = Node->getOperand(0).getValueType();
3224     if (cast<ConstantSDNode>(Node->getOperand(1))->getZExtValue()) {
3225       // 1 -> Hi
3226       Tmp1 = DAG.getNode(ISD::SRL, dl, OpTy, Node->getOperand(0),
3227                          DAG.getConstant(OpTy.getSizeInBits()/2,
3228                     TLI.getShiftAmountTy(Node->getOperand(0).getValueType())));
3229       Tmp1 = DAG.getNode(ISD::TRUNCATE, dl, Node->getValueType(0), Tmp1);
3230     } else {
3231       // 0 -> Lo
3232       Tmp1 = DAG.getNode(ISD::TRUNCATE, dl, Node->getValueType(0),
3233                          Node->getOperand(0));
3234     }
3235     Results.push_back(Tmp1);
3236     break;
3237   }
3238   case ISD::STACKSAVE:
3239     // Expand to CopyFromReg if the target set
3240     // StackPointerRegisterToSaveRestore.
3241     if (unsigned SP = TLI.getStackPointerRegisterToSaveRestore()) {
3242       Results.push_back(DAG.getCopyFromReg(Node->getOperand(0), dl, SP,
3243                                            Node->getValueType(0)));
3244       Results.push_back(Results[0].getValue(1));
3245     } else {
3246       Results.push_back(DAG.getUNDEF(Node->getValueType(0)));
3247       Results.push_back(Node->getOperand(0));
3248     }
3249     break;
3250   case ISD::STACKRESTORE:
3251     // Expand to CopyToReg if the target set
3252     // StackPointerRegisterToSaveRestore.
3253     if (unsigned SP = TLI.getStackPointerRegisterToSaveRestore()) {
3254       Results.push_back(DAG.getCopyToReg(Node->getOperand(0), dl, SP,
3255                                          Node->getOperand(1)));
3256     } else {
3257       Results.push_back(Node->getOperand(0));
3258     }
3259     break;
3260   case ISD::FCOPYSIGN:
3261     Results.push_back(ExpandFCOPYSIGN(Node));
3262     break;
3263   case ISD::FNEG:
3264     // Expand Y = FNEG(X) ->  Y = SUB -0.0, X
3265     Tmp1 = DAG.getConstantFP(-0.0, Node->getValueType(0));
3266     Tmp1 = DAG.getNode(ISD::FSUB, dl, Node->getValueType(0), Tmp1,
3267                        Node->getOperand(0));
3268     Results.push_back(Tmp1);
3269     break;
3270   case ISD::FABS: {
3271     // Expand Y = FABS(X) -> Y = (X >u 0.0) ? X : fneg(X).
3272     EVT VT = Node->getValueType(0);
3273     Tmp1 = Node->getOperand(0);
3274     Tmp2 = DAG.getConstantFP(0.0, VT);
3275     Tmp2 = DAG.getSetCC(dl, TLI.getSetCCResultType(Tmp1.getValueType()),
3276                         Tmp1, Tmp2, ISD::SETUGT);
3277     Tmp3 = DAG.getNode(ISD::FNEG, dl, VT, Tmp1);
3278     Tmp1 = DAG.getNode(ISD::SELECT, dl, VT, Tmp2, Tmp1, Tmp3);
3279     Results.push_back(Tmp1);
3280     break;
3281   }
3282   case ISD::FSQRT:
3283     Results.push_back(ExpandFPLibCall(Node, RTLIB::SQRT_F32, RTLIB::SQRT_F64,
3284                                       RTLIB::SQRT_F80, RTLIB::SQRT_PPCF128));
3285     break;
3286   case ISD::FSIN:
3287     Results.push_back(ExpandFPLibCall(Node, RTLIB::SIN_F32, RTLIB::SIN_F64,
3288                                       RTLIB::SIN_F80, RTLIB::SIN_PPCF128));
3289     break;
3290   case ISD::FCOS:
3291     Results.push_back(ExpandFPLibCall(Node, RTLIB::COS_F32, RTLIB::COS_F64,
3292                                       RTLIB::COS_F80, RTLIB::COS_PPCF128));
3293     break;
3294   case ISD::FLOG:
3295     Results.push_back(ExpandFPLibCall(Node, RTLIB::LOG_F32, RTLIB::LOG_F64,
3296                                       RTLIB::LOG_F80, RTLIB::LOG_PPCF128));
3297     break;
3298   case ISD::FLOG2:
3299     Results.push_back(ExpandFPLibCall(Node, RTLIB::LOG2_F32, RTLIB::LOG2_F64,
3300                                       RTLIB::LOG2_F80, RTLIB::LOG2_PPCF128));
3301     break;
3302   case ISD::FLOG10:
3303     Results.push_back(ExpandFPLibCall(Node, RTLIB::LOG10_F32, RTLIB::LOG10_F64,
3304                                       RTLIB::LOG10_F80, RTLIB::LOG10_PPCF128));
3305     break;
3306   case ISD::FEXP:
3307     Results.push_back(ExpandFPLibCall(Node, RTLIB::EXP_F32, RTLIB::EXP_F64,
3308                                       RTLIB::EXP_F80, RTLIB::EXP_PPCF128));
3309     break;
3310   case ISD::FEXP2:
3311     Results.push_back(ExpandFPLibCall(Node, RTLIB::EXP2_F32, RTLIB::EXP2_F64,
3312                                       RTLIB::EXP2_F80, RTLIB::EXP2_PPCF128));
3313     break;
3314   case ISD::FTRUNC:
3315     Results.push_back(ExpandFPLibCall(Node, RTLIB::TRUNC_F32, RTLIB::TRUNC_F64,
3316                                       RTLIB::TRUNC_F80, RTLIB::TRUNC_PPCF128));
3317     break;
3318   case ISD::FFLOOR:
3319     Results.push_back(ExpandFPLibCall(Node, RTLIB::FLOOR_F32, RTLIB::FLOOR_F64,
3320                                       RTLIB::FLOOR_F80, RTLIB::FLOOR_PPCF128));
3321     break;
3322   case ISD::FCEIL:
3323     Results.push_back(ExpandFPLibCall(Node, RTLIB::CEIL_F32, RTLIB::CEIL_F64,
3324                                       RTLIB::CEIL_F80, RTLIB::CEIL_PPCF128));
3325     break;
3326   case ISD::FRINT:
3327     Results.push_back(ExpandFPLibCall(Node, RTLIB::RINT_F32, RTLIB::RINT_F64,
3328                                       RTLIB::RINT_F80, RTLIB::RINT_PPCF128));
3329     break;
3330   case ISD::FNEARBYINT:
3331     Results.push_back(ExpandFPLibCall(Node, RTLIB::NEARBYINT_F32,
3332                                       RTLIB::NEARBYINT_F64,
3333                                       RTLIB::NEARBYINT_F80,
3334                                       RTLIB::NEARBYINT_PPCF128));
3335     break;
3336   case ISD::FPOWI:
3337     Results.push_back(ExpandFPLibCall(Node, RTLIB::POWI_F32, RTLIB::POWI_F64,
3338                                       RTLIB::POWI_F80, RTLIB::POWI_PPCF128));
3339     break;
3340   case ISD::FPOW:
3341     Results.push_back(ExpandFPLibCall(Node, RTLIB::POW_F32, RTLIB::POW_F64,
3342                                       RTLIB::POW_F80, RTLIB::POW_PPCF128));
3343     break;
3344   case ISD::FDIV:
3345     Results.push_back(ExpandFPLibCall(Node, RTLIB::DIV_F32, RTLIB::DIV_F64,
3346                                       RTLIB::DIV_F80, RTLIB::DIV_PPCF128));
3347     break;
3348   case ISD::FREM:
3349     Results.push_back(ExpandFPLibCall(Node, RTLIB::REM_F32, RTLIB::REM_F64,
3350                                       RTLIB::REM_F80, RTLIB::REM_PPCF128));
3351     break;
3352   case ISD::FMA:
3353     Results.push_back(ExpandFPLibCall(Node, RTLIB::FMA_F32, RTLIB::FMA_F64,
3354                                       RTLIB::FMA_F80, RTLIB::FMA_PPCF128));
3355     break;
3356   case ISD::FP16_TO_FP32:
3357     Results.push_back(ExpandLibCall(RTLIB::FPEXT_F16_F32, Node, false));
3358     break;
3359   case ISD::FP32_TO_FP16:
3360     Results.push_back(ExpandLibCall(RTLIB::FPROUND_F32_F16, Node, false));
3361     break;
3362   case ISD::ConstantFP: {
3363     ConstantFPSDNode *CFP = cast<ConstantFPSDNode>(Node);
3364     // Check to see if this FP immediate is already legal.
3365     // If this is a legal constant, turn it into a TargetConstantFP node.
3366     if (TLI.isFPImmLegal(CFP->getValueAPF(), Node->getValueType(0)))
3367       Results.push_back(SDValue(Node, 0));
3368     else
3369       Results.push_back(ExpandConstantFP(CFP, true, DAG, TLI));
3370     break;
3371   }
3372   case ISD::EHSELECTION: {
3373     unsigned Reg = TLI.getExceptionSelectorRegister();
3374     assert(Reg && "Can't expand to unknown register!");
3375     Results.push_back(DAG.getCopyFromReg(Node->getOperand(1), dl, Reg,
3376                                          Node->getValueType(0)));
3377     Results.push_back(Results[0].getValue(1));
3378     break;
3379   }
3380   case ISD::EXCEPTIONADDR: {
3381     unsigned Reg = TLI.getExceptionAddressRegister();
3382     assert(Reg && "Can't expand to unknown register!");
3383     Results.push_back(DAG.getCopyFromReg(Node->getOperand(0), dl, Reg,
3384                                          Node->getValueType(0)));
3385     Results.push_back(Results[0].getValue(1));
3386     break;
3387   }
3388   case ISD::SUB: {
3389     EVT VT = Node->getValueType(0);
3390     assert(TLI.isOperationLegalOrCustom(ISD::ADD, VT) &&
3391            TLI.isOperationLegalOrCustom(ISD::XOR, VT) &&
3392            "Don't know how to expand this subtraction!");
3393     Tmp1 = DAG.getNode(ISD::XOR, dl, VT, Node->getOperand(1),
3394                DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()), VT));
3395     Tmp1 = DAG.getNode(ISD::ADD, dl, VT, Tmp2, DAG.getConstant(1, VT));
3396     Results.push_back(DAG.getNode(ISD::ADD, dl, VT, Node->getOperand(0), Tmp1));
3397     break;
3398   }
3399   case ISD::UREM:
3400   case ISD::SREM: {
3401     EVT VT = Node->getValueType(0);
3402     SDVTList VTs = DAG.getVTList(VT, VT);
3403     bool isSigned = Node->getOpcode() == ISD::SREM;
3404     unsigned DivOpc = isSigned ? ISD::SDIV : ISD::UDIV;
3405     unsigned DivRemOpc = isSigned ? ISD::SDIVREM : ISD::UDIVREM;
3406     Tmp2 = Node->getOperand(0);
3407     Tmp3 = Node->getOperand(1);
3408     if (TLI.isOperationLegalOrCustom(DivRemOpc, VT) ||
3409         (isDivRemLibcallAvailable(Node, isSigned, TLI) &&
3410          UseDivRem(Node, isSigned, false))) {
3411       Tmp1 = DAG.getNode(DivRemOpc, dl, VTs, Tmp2, Tmp3).getValue(1);
3412     } else if (TLI.isOperationLegalOrCustom(DivOpc, VT)) {
3413       // X % Y -> X-X/Y*Y
3414       Tmp1 = DAG.getNode(DivOpc, dl, VT, Tmp2, Tmp3);
3415       Tmp1 = DAG.getNode(ISD::MUL, dl, VT, Tmp1, Tmp3);
3416       Tmp1 = DAG.getNode(ISD::SUB, dl, VT, Tmp2, Tmp1);
3417     } else if (isSigned)
3418       Tmp1 = ExpandIntLibCall(Node, true,
3419                               RTLIB::SREM_I8,
3420                               RTLIB::SREM_I16, RTLIB::SREM_I32,
3421                               RTLIB::SREM_I64, RTLIB::SREM_I128);
3422     else
3423       Tmp1 = ExpandIntLibCall(Node, false,
3424                               RTLIB::UREM_I8,
3425                               RTLIB::UREM_I16, RTLIB::UREM_I32,
3426                               RTLIB::UREM_I64, RTLIB::UREM_I128);
3427     Results.push_back(Tmp1);
3428     break;
3429   }
3430   case ISD::UDIV:
3431   case ISD::SDIV: {
3432     bool isSigned = Node->getOpcode() == ISD::SDIV;
3433     unsigned DivRemOpc = isSigned ? ISD::SDIVREM : ISD::UDIVREM;
3434     EVT VT = Node->getValueType(0);
3435     SDVTList VTs = DAG.getVTList(VT, VT);
3436     if (TLI.isOperationLegalOrCustom(DivRemOpc, VT) ||
3437         (isDivRemLibcallAvailable(Node, isSigned, TLI) &&
3438          UseDivRem(Node, isSigned, true)))
3439       Tmp1 = DAG.getNode(DivRemOpc, dl, VTs, Node->getOperand(0),
3440                          Node->getOperand(1));
3441     else if (isSigned)
3442       Tmp1 = ExpandIntLibCall(Node, true,
3443                               RTLIB::SDIV_I8,
3444                               RTLIB::SDIV_I16, RTLIB::SDIV_I32,
3445                               RTLIB::SDIV_I64, RTLIB::SDIV_I128);
3446     else
3447       Tmp1 = ExpandIntLibCall(Node, false,
3448                               RTLIB::UDIV_I8,
3449                               RTLIB::UDIV_I16, RTLIB::UDIV_I32,
3450                               RTLIB::UDIV_I64, RTLIB::UDIV_I128);
3451     Results.push_back(Tmp1);
3452     break;
3453   }
3454   case ISD::MULHU:
3455   case ISD::MULHS: {
3456     unsigned ExpandOpcode = Node->getOpcode() == ISD::MULHU ? ISD::UMUL_LOHI :
3457                                                               ISD::SMUL_LOHI;
3458     EVT VT = Node->getValueType(0);
3459     SDVTList VTs = DAG.getVTList(VT, VT);
3460     assert(TLI.isOperationLegalOrCustom(ExpandOpcode, VT) &&
3461            "If this wasn't legal, it shouldn't have been created!");
3462     Tmp1 = DAG.getNode(ExpandOpcode, dl, VTs, Node->getOperand(0),
3463                        Node->getOperand(1));
3464     Results.push_back(Tmp1.getValue(1));
3465     break;
3466   }
3467   case ISD::SDIVREM:
3468   case ISD::UDIVREM:
3469     // Expand into divrem libcall
3470     ExpandDivRemLibCall(Node, Results);
3471     break;
3472   case ISD::MUL: {
3473     EVT VT = Node->getValueType(0);
3474     SDVTList VTs = DAG.getVTList(VT, VT);
3475     // See if multiply or divide can be lowered using two-result operations.
3476     // We just need the low half of the multiply; try both the signed
3477     // and unsigned forms. If the target supports both SMUL_LOHI and
3478     // UMUL_LOHI, form a preference by checking which forms of plain
3479     // MULH it supports.
3480     bool HasSMUL_LOHI = TLI.isOperationLegalOrCustom(ISD::SMUL_LOHI, VT);
3481     bool HasUMUL_LOHI = TLI.isOperationLegalOrCustom(ISD::UMUL_LOHI, VT);
3482     bool HasMULHS = TLI.isOperationLegalOrCustom(ISD::MULHS, VT);
3483     bool HasMULHU = TLI.isOperationLegalOrCustom(ISD::MULHU, VT);
3484     unsigned OpToUse = 0;
3485     if (HasSMUL_LOHI && !HasMULHS) {
3486       OpToUse = ISD::SMUL_LOHI;
3487     } else if (HasUMUL_LOHI && !HasMULHU) {
3488       OpToUse = ISD::UMUL_LOHI;
3489     } else if (HasSMUL_LOHI) {
3490       OpToUse = ISD::SMUL_LOHI;
3491     } else if (HasUMUL_LOHI) {
3492       OpToUse = ISD::UMUL_LOHI;
3493     }
3494     if (OpToUse) {
3495       Results.push_back(DAG.getNode(OpToUse, dl, VTs, Node->getOperand(0),
3496                                     Node->getOperand(1)));
3497       break;
3498     }
3499     Tmp1 = ExpandIntLibCall(Node, false,
3500                             RTLIB::MUL_I8,
3501                             RTLIB::MUL_I16, RTLIB::MUL_I32,
3502                             RTLIB::MUL_I64, RTLIB::MUL_I128);
3503     Results.push_back(Tmp1);
3504     break;
3505   }
3506   case ISD::SADDO:
3507   case ISD::SSUBO: {
3508     SDValue LHS = Node->getOperand(0);
3509     SDValue RHS = Node->getOperand(1);
3510     SDValue Sum = DAG.getNode(Node->getOpcode() == ISD::SADDO ?
3511                               ISD::ADD : ISD::SUB, dl, LHS.getValueType(),
3512                               LHS, RHS);
3513     Results.push_back(Sum);
3514     EVT OType = Node->getValueType(1);
3515
3516     SDValue Zero = DAG.getConstant(0, LHS.getValueType());
3517
3518     //   LHSSign -> LHS >= 0
3519     //   RHSSign -> RHS >= 0
3520     //   SumSign -> Sum >= 0
3521     //
3522     //   Add:
3523     //   Overflow -> (LHSSign == RHSSign) && (LHSSign != SumSign)
3524     //   Sub:
3525     //   Overflow -> (LHSSign != RHSSign) && (LHSSign != SumSign)
3526     //
3527     SDValue LHSSign = DAG.getSetCC(dl, OType, LHS, Zero, ISD::SETGE);
3528     SDValue RHSSign = DAG.getSetCC(dl, OType, RHS, Zero, ISD::SETGE);
3529     SDValue SignsMatch = DAG.getSetCC(dl, OType, LHSSign, RHSSign,
3530                                       Node->getOpcode() == ISD::SADDO ?
3531                                       ISD::SETEQ : ISD::SETNE);
3532
3533     SDValue SumSign = DAG.getSetCC(dl, OType, Sum, Zero, ISD::SETGE);
3534     SDValue SumSignNE = DAG.getSetCC(dl, OType, LHSSign, SumSign, ISD::SETNE);
3535
3536     SDValue Cmp = DAG.getNode(ISD::AND, dl, OType, SignsMatch, SumSignNE);
3537     Results.push_back(Cmp);
3538     break;
3539   }
3540   case ISD::UADDO:
3541   case ISD::USUBO: {
3542     SDValue LHS = Node->getOperand(0);
3543     SDValue RHS = Node->getOperand(1);
3544     SDValue Sum = DAG.getNode(Node->getOpcode() == ISD::UADDO ?
3545                               ISD::ADD : ISD::SUB, dl, LHS.getValueType(),
3546                               LHS, RHS);
3547     Results.push_back(Sum);
3548     Results.push_back(DAG.getSetCC(dl, Node->getValueType(1), Sum, LHS,
3549                                    Node->getOpcode () == ISD::UADDO ?
3550                                    ISD::SETULT : ISD::SETUGT));
3551     break;
3552   }
3553   case ISD::UMULO:
3554   case ISD::SMULO: {
3555     EVT VT = Node->getValueType(0);
3556     EVT WideVT = EVT::getIntegerVT(*DAG.getContext(), VT.getSizeInBits() * 2);
3557     SDValue LHS = Node->getOperand(0);
3558     SDValue RHS = Node->getOperand(1);
3559     SDValue BottomHalf;
3560     SDValue TopHalf;
3561     static const unsigned Ops[2][3] =
3562         { { ISD::MULHU, ISD::UMUL_LOHI, ISD::ZERO_EXTEND },
3563           { ISD::MULHS, ISD::SMUL_LOHI, ISD::SIGN_EXTEND }};
3564     bool isSigned = Node->getOpcode() == ISD::SMULO;
3565     if (TLI.isOperationLegalOrCustom(Ops[isSigned][0], VT)) {
3566       BottomHalf = DAG.getNode(ISD::MUL, dl, VT, LHS, RHS);
3567       TopHalf = DAG.getNode(Ops[isSigned][0], dl, VT, LHS, RHS);
3568     } else if (TLI.isOperationLegalOrCustom(Ops[isSigned][1], VT)) {
3569       BottomHalf = DAG.getNode(Ops[isSigned][1], dl, DAG.getVTList(VT, VT), LHS,
3570                                RHS);
3571       TopHalf = BottomHalf.getValue(1);
3572     } else if (TLI.isTypeLegal(EVT::getIntegerVT(*DAG.getContext(),
3573                                                  VT.getSizeInBits() * 2))) {
3574       LHS = DAG.getNode(Ops[isSigned][2], dl, WideVT, LHS);
3575       RHS = DAG.getNode(Ops[isSigned][2], dl, WideVT, RHS);
3576       Tmp1 = DAG.getNode(ISD::MUL, dl, WideVT, LHS, RHS);
3577       BottomHalf = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, VT, Tmp1,
3578                                DAG.getIntPtrConstant(0));
3579       TopHalf = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, VT, Tmp1,
3580                             DAG.getIntPtrConstant(1));
3581     } else {
3582       // We can fall back to a libcall with an illegal type for the MUL if we
3583       // have a libcall big enough.
3584       // Also, we can fall back to a division in some cases, but that's a big
3585       // performance hit in the general case.
3586       RTLIB::Libcall LC = RTLIB::UNKNOWN_LIBCALL;
3587       if (WideVT == MVT::i16)
3588         LC = RTLIB::MUL_I16;
3589       else if (WideVT == MVT::i32)
3590         LC = RTLIB::MUL_I32;
3591       else if (WideVT == MVT::i64)
3592         LC = RTLIB::MUL_I64;
3593       else if (WideVT == MVT::i128)
3594         LC = RTLIB::MUL_I128;
3595       assert(LC != RTLIB::UNKNOWN_LIBCALL && "Cannot expand this operation!");
3596
3597       // The high part is obtained by SRA'ing all but one of the bits of low
3598       // part.
3599       unsigned LoSize = VT.getSizeInBits();
3600       SDValue HiLHS = DAG.getNode(ISD::SRA, dl, VT, RHS,
3601                                 DAG.getConstant(LoSize-1, TLI.getPointerTy()));
3602       SDValue HiRHS = DAG.getNode(ISD::SRA, dl, VT, LHS,
3603                                 DAG.getConstant(LoSize-1, TLI.getPointerTy()));
3604
3605       // Here we're passing the 2 arguments explicitly as 4 arguments that are
3606       // pre-lowered to the correct types. This all depends upon WideVT not
3607       // being a legal type for the architecture and thus has to be split to
3608       // two arguments.
3609       SDValue Args[] = { LHS, HiLHS, RHS, HiRHS };
3610       SDValue Ret = ExpandLibCall(LC, WideVT, Args, 4, isSigned, dl);
3611       BottomHalf = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, VT, Ret,
3612                                DAG.getIntPtrConstant(0));
3613       TopHalf = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, VT, Ret,
3614                             DAG.getIntPtrConstant(1));
3615     }
3616
3617     if (isSigned) {
3618       Tmp1 = DAG.getConstant(VT.getSizeInBits() - 1,
3619                              TLI.getShiftAmountTy(BottomHalf.getValueType()));
3620       Tmp1 = DAG.getNode(ISD::SRA, dl, VT, BottomHalf, Tmp1);
3621       TopHalf = DAG.getSetCC(dl, TLI.getSetCCResultType(VT), TopHalf, Tmp1,
3622                              ISD::SETNE);
3623     } else {
3624       TopHalf = DAG.getSetCC(dl, TLI.getSetCCResultType(VT), TopHalf,
3625                              DAG.getConstant(0, VT), ISD::SETNE);
3626     }
3627     Results.push_back(BottomHalf);
3628     Results.push_back(TopHalf);
3629     break;
3630   }
3631   case ISD::BUILD_PAIR: {
3632     EVT PairTy = Node->getValueType(0);
3633     Tmp1 = DAG.getNode(ISD::ZERO_EXTEND, dl, PairTy, Node->getOperand(0));
3634     Tmp2 = DAG.getNode(ISD::ANY_EXTEND, dl, PairTy, Node->getOperand(1));
3635     Tmp2 = DAG.getNode(ISD::SHL, dl, PairTy, Tmp2,
3636                        DAG.getConstant(PairTy.getSizeInBits()/2,
3637                                        TLI.getShiftAmountTy(PairTy)));
3638     Results.push_back(DAG.getNode(ISD::OR, dl, PairTy, Tmp1, Tmp2));
3639     break;
3640   }
3641   case ISD::SELECT:
3642     Tmp1 = Node->getOperand(0);
3643     Tmp2 = Node->getOperand(1);
3644     Tmp3 = Node->getOperand(2);
3645     if (Tmp1.getOpcode() == ISD::SETCC) {
3646       Tmp1 = DAG.getSelectCC(dl, Tmp1.getOperand(0), Tmp1.getOperand(1),
3647                              Tmp2, Tmp3,
3648                              cast<CondCodeSDNode>(Tmp1.getOperand(2))->get());
3649     } else {
3650       Tmp1 = DAG.getSelectCC(dl, Tmp1,
3651                              DAG.getConstant(0, Tmp1.getValueType()),
3652                              Tmp2, Tmp3, ISD::SETNE);
3653     }
3654     Results.push_back(Tmp1);
3655     break;
3656   case ISD::BR_JT: {
3657     SDValue Chain = Node->getOperand(0);
3658     SDValue Table = Node->getOperand(1);
3659     SDValue Index = Node->getOperand(2);
3660
3661     EVT PTy = TLI.getPointerTy();
3662
3663     const TargetData &TD = *TLI.getTargetData();
3664     unsigned EntrySize =
3665       DAG.getMachineFunction().getJumpTableInfo()->getEntrySize(TD);
3666
3667     Index = DAG.getNode(ISD::MUL, dl, PTy,
3668                         Index, DAG.getConstant(EntrySize, PTy));
3669     SDValue Addr = DAG.getNode(ISD::ADD, dl, PTy, Index, Table);
3670
3671     EVT MemVT = EVT::getIntegerVT(*DAG.getContext(), EntrySize * 8);
3672     SDValue LD = DAG.getExtLoad(ISD::SEXTLOAD, dl, PTy, Chain, Addr,
3673                                 MachinePointerInfo::getJumpTable(), MemVT,
3674                                 false, false, 0);
3675     Addr = LD;
3676     if (TM.getRelocationModel() == Reloc::PIC_) {
3677       // For PIC, the sequence is:
3678       // BRIND(load(Jumptable + index) + RelocBase)
3679       // RelocBase can be JumpTable, GOT or some sort of global base.
3680       Addr = DAG.getNode(ISD::ADD, dl, PTy, Addr,
3681                           TLI.getPICJumpTableRelocBase(Table, DAG));
3682     }
3683     Tmp1 = DAG.getNode(ISD::BRIND, dl, MVT::Other, LD.getValue(1), Addr);
3684     Results.push_back(Tmp1);
3685     break;
3686   }
3687   case ISD::BRCOND:
3688     // Expand brcond's setcc into its constituent parts and create a BR_CC
3689     // Node.
3690     Tmp1 = Node->getOperand(0);
3691     Tmp2 = Node->getOperand(1);
3692     if (Tmp2.getOpcode() == ISD::SETCC) {
3693       Tmp1 = DAG.getNode(ISD::BR_CC, dl, MVT::Other,
3694                          Tmp1, Tmp2.getOperand(2),
3695                          Tmp2.getOperand(0), Tmp2.getOperand(1),
3696                          Node->getOperand(2));
3697     } else {
3698       // We test only the i1 bit.  Skip the AND if UNDEF.
3699       Tmp3 = (Tmp2.getOpcode() == ISD::UNDEF) ? Tmp2 :
3700         DAG.getNode(ISD::AND, dl, Tmp2.getValueType(), Tmp2,
3701                     DAG.getConstant(1, Tmp2.getValueType()));
3702       Tmp1 = DAG.getNode(ISD::BR_CC, dl, MVT::Other, Tmp1,
3703                          DAG.getCondCode(ISD::SETNE), Tmp3,
3704                          DAG.getConstant(0, Tmp3.getValueType()),
3705                          Node->getOperand(2));
3706     }
3707     Results.push_back(Tmp1);
3708     break;
3709   case ISD::SETCC: {
3710     Tmp1 = Node->getOperand(0);
3711     Tmp2 = Node->getOperand(1);
3712     Tmp3 = Node->getOperand(2);
3713     LegalizeSetCCCondCode(Node->getValueType(0), Tmp1, Tmp2, Tmp3, dl);
3714
3715     // If we expanded the SETCC into an AND/OR, return the new node
3716     if (Tmp2.getNode() == 0) {
3717       Results.push_back(Tmp1);
3718       break;
3719     }
3720
3721     // Otherwise, SETCC for the given comparison type must be completely
3722     // illegal; expand it into a SELECT_CC.
3723     EVT VT = Node->getValueType(0);
3724     Tmp1 = DAG.getNode(ISD::SELECT_CC, dl, VT, Tmp1, Tmp2,
3725                        DAG.getConstant(1, VT), DAG.getConstant(0, VT), Tmp3);
3726     Results.push_back(Tmp1);
3727     break;
3728   }
3729   case ISD::SELECT_CC: {
3730     Tmp1 = Node->getOperand(0);   // LHS
3731     Tmp2 = Node->getOperand(1);   // RHS
3732     Tmp3 = Node->getOperand(2);   // True
3733     Tmp4 = Node->getOperand(3);   // False
3734     SDValue CC = Node->getOperand(4);
3735
3736     LegalizeSetCCCondCode(TLI.getSetCCResultType(Tmp1.getValueType()),
3737                           Tmp1, Tmp2, CC, dl);
3738
3739     assert(!Tmp2.getNode() && "Can't legalize SELECT_CC with legal condition!");
3740     Tmp2 = DAG.getConstant(0, Tmp1.getValueType());
3741     CC = DAG.getCondCode(ISD::SETNE);
3742     Tmp1 = DAG.getNode(ISD::SELECT_CC, dl, Node->getValueType(0), Tmp1, Tmp2,
3743                        Tmp3, Tmp4, CC);
3744     Results.push_back(Tmp1);
3745     break;
3746   }
3747   case ISD::BR_CC: {
3748     Tmp1 = Node->getOperand(0);              // Chain
3749     Tmp2 = Node->getOperand(2);              // LHS
3750     Tmp3 = Node->getOperand(3);              // RHS
3751     Tmp4 = Node->getOperand(1);              // CC
3752
3753     LegalizeSetCCCondCode(TLI.getSetCCResultType(Tmp2.getValueType()),
3754                           Tmp2, Tmp3, Tmp4, dl);
3755     LastCALLSEQ_END = DAG.getEntryNode();
3756
3757     assert(!Tmp3.getNode() && "Can't legalize BR_CC with legal condition!");
3758     Tmp3 = DAG.getConstant(0, Tmp2.getValueType());
3759     Tmp4 = DAG.getCondCode(ISD::SETNE);
3760     Tmp1 = DAG.getNode(ISD::BR_CC, dl, Node->getValueType(0), Tmp1, Tmp4, Tmp2,
3761                        Tmp3, Node->getOperand(4));
3762     Results.push_back(Tmp1);
3763     break;
3764   }
3765   case ISD::GLOBAL_OFFSET_TABLE:
3766   case ISD::GlobalAddress:
3767   case ISD::GlobalTLSAddress:
3768   case ISD::ExternalSymbol:
3769   case ISD::ConstantPool:
3770   case ISD::JumpTable:
3771   case ISD::INTRINSIC_W_CHAIN:
3772   case ISD::INTRINSIC_WO_CHAIN:
3773   case ISD::INTRINSIC_VOID:
3774     // FIXME: Custom lowering for these operations shouldn't return null!
3775     for (unsigned i = 0, e = Node->getNumValues(); i != e; ++i)
3776       Results.push_back(SDValue(Node, i));
3777     break;
3778   }
3779 }
3780 void SelectionDAGLegalize::PromoteNode(SDNode *Node,
3781                                        SmallVectorImpl<SDValue> &Results) {
3782   EVT OVT = Node->getValueType(0);
3783   if (Node->getOpcode() == ISD::UINT_TO_FP ||
3784       Node->getOpcode() == ISD::SINT_TO_FP ||
3785       Node->getOpcode() == ISD::SETCC) {
3786     OVT = Node->getOperand(0).getValueType();
3787   }
3788   EVT NVT = TLI.getTypeToPromoteTo(Node->getOpcode(), OVT);
3789   DebugLoc dl = Node->getDebugLoc();
3790   SDValue Tmp1, Tmp2, Tmp3;
3791   switch (Node->getOpcode()) {
3792   case ISD::CTTZ:
3793   case ISD::CTLZ:
3794   case ISD::CTPOP:
3795     // Zero extend the argument.
3796     Tmp1 = DAG.getNode(ISD::ZERO_EXTEND, dl, NVT, Node->getOperand(0));
3797     // Perform the larger operation.
3798     Tmp1 = DAG.getNode(Node->getOpcode(), dl, NVT, Tmp1);
3799     if (Node->getOpcode() == ISD::CTTZ) {
3800       //if Tmp1 == sizeinbits(NVT) then Tmp1 = sizeinbits(Old VT)
3801       Tmp2 = DAG.getSetCC(dl, TLI.getSetCCResultType(NVT),
3802                           Tmp1, DAG.getConstant(NVT.getSizeInBits(), NVT),
3803                           ISD::SETEQ);
3804       Tmp1 = DAG.getNode(ISD::SELECT, dl, NVT, Tmp2,
3805                           DAG.getConstant(OVT.getSizeInBits(), NVT), Tmp1);
3806     } else if (Node->getOpcode() == ISD::CTLZ) {
3807       // Tmp1 = Tmp1 - (sizeinbits(NVT) - sizeinbits(Old VT))
3808       Tmp1 = DAG.getNode(ISD::SUB, dl, NVT, Tmp1,
3809                           DAG.getConstant(NVT.getSizeInBits() -
3810                                           OVT.getSizeInBits(), NVT));
3811     }
3812     Results.push_back(DAG.getNode(ISD::TRUNCATE, dl, OVT, Tmp1));
3813     break;
3814   case ISD::BSWAP: {
3815     unsigned DiffBits = NVT.getSizeInBits() - OVT.getSizeInBits();
3816     Tmp1 = DAG.getNode(ISD::ZERO_EXTEND, dl, NVT, Node->getOperand(0));
3817     Tmp1 = DAG.getNode(ISD::BSWAP, dl, NVT, Tmp1);
3818     Tmp1 = DAG.getNode(ISD::SRL, dl, NVT, Tmp1,
3819                           DAG.getConstant(DiffBits, TLI.getShiftAmountTy(NVT)));
3820     Results.push_back(Tmp1);
3821     break;
3822   }
3823   case ISD::FP_TO_UINT:
3824   case ISD::FP_TO_SINT:
3825     Tmp1 = PromoteLegalFP_TO_INT(Node->getOperand(0), Node->getValueType(0),
3826                                  Node->getOpcode() == ISD::FP_TO_SINT, dl);
3827     Results.push_back(Tmp1);
3828     break;
3829   case ISD::UINT_TO_FP:
3830   case ISD::SINT_TO_FP:
3831     Tmp1 = PromoteLegalINT_TO_FP(Node->getOperand(0), Node->getValueType(0),
3832                                  Node->getOpcode() == ISD::SINT_TO_FP, dl);
3833     Results.push_back(Tmp1);
3834     break;
3835   case ISD::AND:
3836   case ISD::OR:
3837   case ISD::XOR: {
3838     unsigned ExtOp, TruncOp;
3839     if (OVT.isVector()) {
3840       ExtOp   = ISD::BITCAST;
3841       TruncOp = ISD::BITCAST;
3842     } else {
3843       assert(OVT.isInteger() && "Cannot promote logic operation");
3844       ExtOp   = ISD::ANY_EXTEND;
3845       TruncOp = ISD::TRUNCATE;
3846     }
3847     // Promote each of the values to the new type.
3848     Tmp1 = DAG.getNode(ExtOp, dl, NVT, Node->getOperand(0));
3849     Tmp2 = DAG.getNode(ExtOp, dl, NVT, Node->getOperand(1));
3850     // Perform the larger operation, then convert back
3851     Tmp1 = DAG.getNode(Node->getOpcode(), dl, NVT, Tmp1, Tmp2);
3852     Results.push_back(DAG.getNode(TruncOp, dl, OVT, Tmp1));
3853     break;
3854   }
3855   case ISD::SELECT: {
3856     unsigned ExtOp, TruncOp;
3857     if (Node->getValueType(0).isVector()) {
3858       ExtOp   = ISD::BITCAST;
3859       TruncOp = ISD::BITCAST;
3860     } else if (Node->getValueType(0).isInteger()) {
3861       ExtOp   = ISD::ANY_EXTEND;
3862       TruncOp = ISD::TRUNCATE;
3863     } else {
3864       ExtOp   = ISD::FP_EXTEND;
3865       TruncOp = ISD::FP_ROUND;
3866     }
3867     Tmp1 = Node->getOperand(0);
3868     // Promote each of the values to the new type.
3869     Tmp2 = DAG.getNode(ExtOp, dl, NVT, Node->getOperand(1));
3870     Tmp3 = DAG.getNode(ExtOp, dl, NVT, Node->getOperand(2));
3871     // Perform the larger operation, then round down.
3872     Tmp1 = DAG.getNode(ISD::SELECT, dl, NVT, Tmp1, Tmp2, Tmp3);
3873     if (TruncOp != ISD::FP_ROUND)
3874       Tmp1 = DAG.getNode(TruncOp, dl, Node->getValueType(0), Tmp1);
3875     else
3876       Tmp1 = DAG.getNode(TruncOp, dl, Node->getValueType(0), Tmp1,
3877                          DAG.getIntPtrConstant(0));
3878     Results.push_back(Tmp1);
3879     break;
3880   }
3881   case ISD::VECTOR_SHUFFLE: {
3882     SmallVector<int, 8> Mask;
3883     cast<ShuffleVectorSDNode>(Node)->getMask(Mask);
3884
3885     // Cast the two input vectors.
3886     Tmp1 = DAG.getNode(ISD::BITCAST, dl, NVT, Node->getOperand(0));
3887     Tmp2 = DAG.getNode(ISD::BITCAST, dl, NVT, Node->getOperand(1));
3888
3889     // Convert the shuffle mask to the right # elements.
3890     Tmp1 = ShuffleWithNarrowerEltType(NVT, OVT, dl, Tmp1, Tmp2, Mask);
3891     Tmp1 = DAG.getNode(ISD::BITCAST, dl, OVT, Tmp1);
3892     Results.push_back(Tmp1);
3893     break;
3894   }
3895   case ISD::SETCC: {
3896     unsigned ExtOp = ISD::FP_EXTEND;
3897     if (NVT.isInteger()) {
3898       ISD::CondCode CCCode =
3899         cast<CondCodeSDNode>(Node->getOperand(2))->get();
3900       ExtOp = isSignedIntSetCC(CCCode) ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
3901     }
3902     Tmp1 = DAG.getNode(ExtOp, dl, NVT, Node->getOperand(0));
3903     Tmp2 = DAG.getNode(ExtOp, dl, NVT, Node->getOperand(1));
3904     Results.push_back(DAG.getNode(ISD::SETCC, dl, Node->getValueType(0),
3905                                   Tmp1, Tmp2, Node->getOperand(2)));
3906     break;
3907   }
3908   }
3909 }
3910
3911 // SelectionDAG::Legalize - This is the entry point for the file.
3912 //
3913 void SelectionDAG::Legalize() {
3914   /// run - This is the main entry point to this class.
3915   ///
3916   SelectionDAGLegalize(*this).LegalizeDAG();
3917 }