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