Tweak the handling of MERGE_VALUES nodes: remove the need for
[oota-llvm.git] / lib / CodeGen / SelectionDAG / LegalizeIntegerTypes.cpp
1 //===----- LegalizeIntegerTypes.cpp - Legalization of integer types -------===//
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 integer type expansion and promotion for LegalizeTypes.
11 // Promotion is the act of changing a computation in an illegal type into a
12 // computation in a larger type.  For example, implementing i8 arithmetic in an
13 // i32 register (often needed on powerpc).
14 // Expansion is the act of changing a computation in an illegal type into a
15 // computation in two identical registers of a smaller type.  For example,
16 // implementing i64 arithmetic in two i32 registers (often needed on 32-bit
17 // targets).
18 //
19 //===----------------------------------------------------------------------===//
20
21 #include "LegalizeTypes.h"
22 #include "llvm/DerivedTypes.h"
23 #include "llvm/CodeGen/PseudoSourceValue.h"
24 #include "llvm/Support/ErrorHandling.h"
25 #include "llvm/Support/raw_ostream.h"
26 using namespace llvm;
27
28 //===----------------------------------------------------------------------===//
29 //  Integer Result Promotion
30 //===----------------------------------------------------------------------===//
31
32 /// PromoteIntegerResult - This method is called when a result of a node is
33 /// found to be in need of promotion to a larger type.  At this point, the node
34 /// may also have invalid operands or may have other results that need
35 /// expansion, we just know that (at least) one result needs promotion.
36 void DAGTypeLegalizer::PromoteIntegerResult(SDNode *N, unsigned ResNo) {
37   DEBUG(dbgs() << "Promote integer result: "; N->dump(&DAG); dbgs() << "\n");
38   SDValue Res = SDValue();
39
40   // See if the target wants to custom expand this node.
41   if (CustomLowerNode(N, N->getValueType(ResNo), true))
42     return;
43
44   switch (N->getOpcode()) {
45   default:
46 #ifndef NDEBUG
47     dbgs() << "PromoteIntegerResult #" << ResNo << ": ";
48     N->dump(&DAG); dbgs() << "\n";
49 #endif
50     llvm_unreachable("Do not know how to promote this operator!");
51   case ISD::MERGE_VALUES:Res = PromoteIntRes_MERGE_VALUES(N, ResNo); break;
52   case ISD::AssertSext:  Res = PromoteIntRes_AssertSext(N); break;
53   case ISD::AssertZext:  Res = PromoteIntRes_AssertZext(N); break;
54   case ISD::BITCAST:     Res = PromoteIntRes_BITCAST(N); break;
55   case ISD::BSWAP:       Res = PromoteIntRes_BSWAP(N); break;
56   case ISD::BUILD_PAIR:  Res = PromoteIntRes_BUILD_PAIR(N); break;
57   case ISD::Constant:    Res = PromoteIntRes_Constant(N); break;
58   case ISD::CONVERT_RNDSAT:
59                          Res = PromoteIntRes_CONVERT_RNDSAT(N); break;
60   case ISD::CTLZ:        Res = PromoteIntRes_CTLZ(N); break;
61   case ISD::CTPOP:       Res = PromoteIntRes_CTPOP(N); break;
62   case ISD::CTTZ:        Res = PromoteIntRes_CTTZ(N); break;
63   case ISD::EXTRACT_VECTOR_ELT:
64                          Res = PromoteIntRes_EXTRACT_VECTOR_ELT(N); break;
65   case ISD::LOAD:        Res = PromoteIntRes_LOAD(cast<LoadSDNode>(N));break;
66   case ISD::SELECT:      Res = PromoteIntRes_SELECT(N); break;
67   case ISD::VSELECT:     Res = PromoteIntRes_VSELECT(N); break;
68   case ISD::SELECT_CC:   Res = PromoteIntRes_SELECT_CC(N); break;
69   case ISD::SETCC:       Res = PromoteIntRes_SETCC(N); break;
70   case ISD::SHL:         Res = PromoteIntRes_SHL(N); break;
71   case ISD::SIGN_EXTEND_INREG:
72                          Res = PromoteIntRes_SIGN_EXTEND_INREG(N); break;
73   case ISD::SRA:         Res = PromoteIntRes_SRA(N); break;
74   case ISD::SRL:         Res = PromoteIntRes_SRL(N); break;
75   case ISD::TRUNCATE:    Res = PromoteIntRes_TRUNCATE(N); break;
76   case ISD::UNDEF:       Res = PromoteIntRes_UNDEF(N); break;
77   case ISD::VAARG:       Res = PromoteIntRes_VAARG(N); break;
78
79   case ISD::EXTRACT_SUBVECTOR:
80                          Res = PromoteIntRes_EXTRACT_SUBVECTOR(N); break;
81   case ISD::VECTOR_SHUFFLE:
82                          Res = PromoteIntRes_VECTOR_SHUFFLE(N); break;
83   case ISD::INSERT_VECTOR_ELT:
84                          Res = PromoteIntRes_INSERT_VECTOR_ELT(N); break;
85   case ISD::BUILD_VECTOR:
86                          Res = PromoteIntRes_BUILD_VECTOR(N); break;
87   case ISD::SCALAR_TO_VECTOR:
88                          Res = PromoteIntRes_SCALAR_TO_VECTOR(N); break;
89   case ISD::CONCAT_VECTORS:
90                          Res = PromoteIntRes_CONCAT_VECTORS(N); break;
91
92   case ISD::SIGN_EXTEND:
93   case ISD::ZERO_EXTEND:
94   case ISD::ANY_EXTEND:  Res = PromoteIntRes_INT_EXTEND(N); break;
95
96   case ISD::FP_TO_SINT:
97   case ISD::FP_TO_UINT:  Res = PromoteIntRes_FP_TO_XINT(N); break;
98
99   case ISD::FP32_TO_FP16:Res = PromoteIntRes_FP32_TO_FP16(N); break;
100
101   case ISD::AND:
102   case ISD::OR:
103   case ISD::XOR:
104   case ISD::ADD:
105   case ISD::SUB:
106   case ISD::MUL:         Res = PromoteIntRes_SimpleIntBinOp(N); break;
107
108   case ISD::SDIV:
109   case ISD::SREM:        Res = PromoteIntRes_SDIV(N); break;
110
111   case ISD::UDIV:
112   case ISD::UREM:        Res = PromoteIntRes_UDIV(N); break;
113
114   case ISD::SADDO:
115   case ISD::SSUBO:       Res = PromoteIntRes_SADDSUBO(N, ResNo); break;
116   case ISD::UADDO:
117   case ISD::USUBO:       Res = PromoteIntRes_UADDSUBO(N, ResNo); break;
118   case ISD::SMULO:
119   case ISD::UMULO:       Res = PromoteIntRes_XMULO(N, ResNo); break;
120
121   case ISD::ATOMIC_LOAD:
122     Res = PromoteIntRes_Atomic0(cast<AtomicSDNode>(N)); break;
123
124   case ISD::ATOMIC_LOAD_ADD:
125   case ISD::ATOMIC_LOAD_SUB:
126   case ISD::ATOMIC_LOAD_AND:
127   case ISD::ATOMIC_LOAD_OR:
128   case ISD::ATOMIC_LOAD_XOR:
129   case ISD::ATOMIC_LOAD_NAND:
130   case ISD::ATOMIC_LOAD_MIN:
131   case ISD::ATOMIC_LOAD_MAX:
132   case ISD::ATOMIC_LOAD_UMIN:
133   case ISD::ATOMIC_LOAD_UMAX:
134   case ISD::ATOMIC_SWAP:
135     Res = PromoteIntRes_Atomic1(cast<AtomicSDNode>(N)); break;
136
137   case ISD::ATOMIC_CMP_SWAP:
138     Res = PromoteIntRes_Atomic2(cast<AtomicSDNode>(N)); break;
139   }
140
141   // If the result is null then the sub-method took care of registering it.
142   if (Res.getNode())
143     SetPromotedInteger(SDValue(N, ResNo), Res);
144 }
145
146 SDValue DAGTypeLegalizer::PromoteIntRes_MERGE_VALUES(SDNode *N,
147                                                      unsigned ResNo) {
148   SDValue Op = DisintegrateMERGE_VALUES(N, ResNo);
149   return GetPromotedInteger(Op);
150 }
151
152 SDValue DAGTypeLegalizer::PromoteIntRes_AssertSext(SDNode *N) {
153   // Sign-extend the new bits, and continue the assertion.
154   SDValue Op = SExtPromotedInteger(N->getOperand(0));
155   return DAG.getNode(ISD::AssertSext, N->getDebugLoc(),
156                      Op.getValueType(), Op, N->getOperand(1));
157 }
158
159 SDValue DAGTypeLegalizer::PromoteIntRes_AssertZext(SDNode *N) {
160   // Zero the new bits, and continue the assertion.
161   SDValue Op = ZExtPromotedInteger(N->getOperand(0));
162   return DAG.getNode(ISD::AssertZext, N->getDebugLoc(),
163                      Op.getValueType(), Op, N->getOperand(1));
164 }
165
166 SDValue DAGTypeLegalizer::PromoteIntRes_Atomic0(AtomicSDNode *N) {
167   EVT ResVT = TLI.getTypeToTransformTo(*DAG.getContext(), N->getValueType(0));
168   SDValue Res = DAG.getAtomic(N->getOpcode(), N->getDebugLoc(),
169                               N->getMemoryVT(), ResVT,
170                               N->getChain(), N->getBasePtr(),
171                               N->getMemOperand(), N->getOrdering(),
172                               N->getSynchScope());
173   // Legalized the chain result - switch anything that used the old chain to
174   // use the new one.
175   ReplaceValueWith(SDValue(N, 1), Res.getValue(1));
176   return Res;
177 }
178
179 SDValue DAGTypeLegalizer::PromoteIntRes_Atomic1(AtomicSDNode *N) {
180   SDValue Op2 = GetPromotedInteger(N->getOperand(2));
181   SDValue Res = DAG.getAtomic(N->getOpcode(), N->getDebugLoc(),
182                               N->getMemoryVT(),
183                               N->getChain(), N->getBasePtr(),
184                               Op2, N->getMemOperand(), N->getOrdering(),
185                               N->getSynchScope());
186   // Legalized the chain result - switch anything that used the old chain to
187   // use the new one.
188   ReplaceValueWith(SDValue(N, 1), Res.getValue(1));
189   return Res;
190 }
191
192 SDValue DAGTypeLegalizer::PromoteIntRes_Atomic2(AtomicSDNode *N) {
193   SDValue Op2 = GetPromotedInteger(N->getOperand(2));
194   SDValue Op3 = GetPromotedInteger(N->getOperand(3));
195   SDValue Res = DAG.getAtomic(N->getOpcode(), N->getDebugLoc(),
196                               N->getMemoryVT(), N->getChain(), N->getBasePtr(),
197                               Op2, Op3, N->getMemOperand(), N->getOrdering(),
198                               N->getSynchScope());
199   // Legalized the chain result - switch anything that used the old chain to
200   // use the new one.
201   ReplaceValueWith(SDValue(N, 1), Res.getValue(1));
202   return Res;
203 }
204
205 SDValue DAGTypeLegalizer::PromoteIntRes_BITCAST(SDNode *N) {
206   SDValue InOp = N->getOperand(0);
207   EVT InVT = InOp.getValueType();
208   EVT NInVT = TLI.getTypeToTransformTo(*DAG.getContext(), InVT);
209   EVT OutVT = N->getValueType(0);
210   EVT NOutVT = TLI.getTypeToTransformTo(*DAG.getContext(), OutVT);
211   DebugLoc dl = N->getDebugLoc();
212
213   switch (getTypeAction(InVT)) {
214   default:
215     assert(false && "Unknown type action!");
216     break;
217   case TargetLowering::TypeLegal:
218     break;
219   case TargetLowering::TypePromoteInteger:
220     if (NOutVT.bitsEq(NInVT))
221       // The input promotes to the same size.  Convert the promoted value.
222       return DAG.getNode(ISD::BITCAST, dl, NOutVT, GetPromotedInteger(InOp));
223     break;
224   case TargetLowering::TypeSoftenFloat:
225     // Promote the integer operand by hand.
226     return DAG.getNode(ISD::ANY_EXTEND, dl, NOutVT, GetSoftenedFloat(InOp));
227   case TargetLowering::TypeExpandInteger:
228   case TargetLowering::TypeExpandFloat:
229     break;
230   case TargetLowering::TypeScalarizeVector:
231     // Convert the element to an integer and promote it by hand.
232     if (!NOutVT.isVector())
233       return DAG.getNode(ISD::ANY_EXTEND, dl, NOutVT,
234                          BitConvertToInteger(GetScalarizedVector(InOp)));
235     break;
236   case TargetLowering::TypeSplitVector: {
237     // For example, i32 = BITCAST v2i16 on alpha.  Convert the split
238     // pieces of the input into integers and reassemble in the final type.
239     SDValue Lo, Hi;
240     GetSplitVector(N->getOperand(0), Lo, Hi);
241     Lo = BitConvertToInteger(Lo);
242     Hi = BitConvertToInteger(Hi);
243
244     if (TLI.isBigEndian())
245       std::swap(Lo, Hi);
246
247     InOp = DAG.getNode(ISD::ANY_EXTEND, dl,
248                        EVT::getIntegerVT(*DAG.getContext(),
249                                          NOutVT.getSizeInBits()),
250                        JoinIntegers(Lo, Hi));
251     return DAG.getNode(ISD::BITCAST, dl, NOutVT, InOp);
252   }
253   case TargetLowering::TypeWidenVector:
254     if (OutVT.bitsEq(NInVT))
255       // The input is widened to the same size.  Convert to the widened value.
256       return DAG.getNode(ISD::BITCAST, dl, OutVT, GetWidenedVector(InOp));
257   }
258
259   return DAG.getNode(ISD::ANY_EXTEND, dl, NOutVT,
260                      CreateStackStoreLoad(InOp, OutVT));
261 }
262
263 SDValue DAGTypeLegalizer::PromoteIntRes_BSWAP(SDNode *N) {
264   SDValue Op = GetPromotedInteger(N->getOperand(0));
265   EVT OVT = N->getValueType(0);
266   EVT NVT = Op.getValueType();
267   DebugLoc dl = N->getDebugLoc();
268
269   unsigned DiffBits = NVT.getSizeInBits() - OVT.getSizeInBits();
270   return DAG.getNode(ISD::SRL, dl, NVT, DAG.getNode(ISD::BSWAP, dl, NVT, Op),
271                      DAG.getConstant(DiffBits, TLI.getPointerTy()));
272 }
273
274 SDValue DAGTypeLegalizer::PromoteIntRes_BUILD_PAIR(SDNode *N) {
275   // The pair element type may be legal, or may not promote to the same type as
276   // the result, for example i14 = BUILD_PAIR (i7, i7).  Handle all cases.
277   return DAG.getNode(ISD::ANY_EXTEND, N->getDebugLoc(),
278                      TLI.getTypeToTransformTo(*DAG.getContext(),
279                      N->getValueType(0)), JoinIntegers(N->getOperand(0),
280                      N->getOperand(1)));
281 }
282
283 SDValue DAGTypeLegalizer::PromoteIntRes_Constant(SDNode *N) {
284   EVT VT = N->getValueType(0);
285   // FIXME there is no actual debug info here
286   DebugLoc dl = N->getDebugLoc();
287   // Zero extend things like i1, sign extend everything else.  It shouldn't
288   // matter in theory which one we pick, but this tends to give better code?
289   unsigned Opc = VT.isByteSized() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
290   SDValue Result = DAG.getNode(Opc, dl,
291                                TLI.getTypeToTransformTo(*DAG.getContext(), VT),
292                                SDValue(N, 0));
293   assert(isa<ConstantSDNode>(Result) && "Didn't constant fold ext?");
294   return Result;
295 }
296
297 SDValue DAGTypeLegalizer::PromoteIntRes_CONVERT_RNDSAT(SDNode *N) {
298   ISD::CvtCode CvtCode = cast<CvtRndSatSDNode>(N)->getCvtCode();
299   assert ((CvtCode == ISD::CVT_SS || CvtCode == ISD::CVT_SU ||
300            CvtCode == ISD::CVT_US || CvtCode == ISD::CVT_UU ||
301            CvtCode == ISD::CVT_SF || CvtCode == ISD::CVT_UF) &&
302           "can only promote integers");
303   EVT OutVT = TLI.getTypeToTransformTo(*DAG.getContext(), N->getValueType(0));
304   return DAG.getConvertRndSat(OutVT, N->getDebugLoc(), N->getOperand(0),
305                               N->getOperand(1), N->getOperand(2),
306                               N->getOperand(3), N->getOperand(4), CvtCode);
307 }
308
309 SDValue DAGTypeLegalizer::PromoteIntRes_CTLZ(SDNode *N) {
310   // Zero extend to the promoted type and do the count there.
311   SDValue Op = ZExtPromotedInteger(N->getOperand(0));
312   DebugLoc dl = N->getDebugLoc();
313   EVT OVT = N->getValueType(0);
314   EVT NVT = Op.getValueType();
315   Op = DAG.getNode(ISD::CTLZ, dl, NVT, Op);
316   // Subtract off the extra leading bits in the bigger type.
317   return DAG.getNode(ISD::SUB, dl, NVT, Op,
318                      DAG.getConstant(NVT.getSizeInBits() -
319                                      OVT.getSizeInBits(), NVT));
320 }
321
322 SDValue DAGTypeLegalizer::PromoteIntRes_CTPOP(SDNode *N) {
323   // Zero extend to the promoted type and do the count there.
324   SDValue Op = ZExtPromotedInteger(N->getOperand(0));
325   return DAG.getNode(ISD::CTPOP, N->getDebugLoc(), Op.getValueType(), Op);
326 }
327
328 SDValue DAGTypeLegalizer::PromoteIntRes_CTTZ(SDNode *N) {
329   SDValue Op = GetPromotedInteger(N->getOperand(0));
330   EVT OVT = N->getValueType(0);
331   EVT NVT = Op.getValueType();
332   DebugLoc dl = N->getDebugLoc();
333   // The count is the same in the promoted type except if the original
334   // value was zero.  This can be handled by setting the bit just off
335   // the top of the original type.
336   APInt TopBit(NVT.getSizeInBits(), 0);
337   TopBit.setBit(OVT.getSizeInBits());
338   Op = DAG.getNode(ISD::OR, dl, NVT, Op, DAG.getConstant(TopBit, NVT));
339   return DAG.getNode(ISD::CTTZ, dl, NVT, Op);
340 }
341
342 SDValue DAGTypeLegalizer::PromoteIntRes_EXTRACT_VECTOR_ELT(SDNode *N) {
343   DebugLoc dl = N->getDebugLoc();
344   EVT NVT = TLI.getTypeToTransformTo(*DAG.getContext(), N->getValueType(0));
345   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, NVT, N->getOperand(0),
346                      N->getOperand(1));
347 }
348
349 SDValue DAGTypeLegalizer::PromoteIntRes_FP_TO_XINT(SDNode *N) {
350   EVT NVT = TLI.getTypeToTransformTo(*DAG.getContext(), N->getValueType(0));
351   unsigned NewOpc = N->getOpcode();
352   DebugLoc dl = N->getDebugLoc();
353
354   // If we're promoting a UINT to a larger size and the larger FP_TO_UINT is
355   // not Legal, check to see if we can use FP_TO_SINT instead.  (If both UINT
356   // and SINT conversions are Custom, there is no way to tell which is
357   // preferable. We choose SINT because that's the right thing on PPC.)
358   if (N->getOpcode() == ISD::FP_TO_UINT &&
359       !TLI.isOperationLegal(ISD::FP_TO_UINT, NVT) &&
360       TLI.isOperationLegalOrCustom(ISD::FP_TO_SINT, NVT))
361     NewOpc = ISD::FP_TO_SINT;
362
363   SDValue Res = DAG.getNode(NewOpc, dl, NVT, N->getOperand(0));
364
365   // Assert that the converted value fits in the original type.  If it doesn't
366   // (eg: because the value being converted is too big), then the result of the
367   // original operation was undefined anyway, so the assert is still correct.
368   return DAG.getNode(N->getOpcode() == ISD::FP_TO_UINT ?
369                      ISD::AssertZext : ISD::AssertSext, dl, NVT, Res,
370                      DAG.getValueType(N->getValueType(0).getScalarType()));
371 }
372
373 SDValue DAGTypeLegalizer::PromoteIntRes_FP32_TO_FP16(SDNode *N) {
374   EVT NVT = TLI.getTypeToTransformTo(*DAG.getContext(), N->getValueType(0));
375   DebugLoc dl = N->getDebugLoc();
376
377   SDValue Res = DAG.getNode(N->getOpcode(), dl, NVT, N->getOperand(0));
378
379   return DAG.getNode(ISD::AssertZext, dl,
380                      NVT, Res, DAG.getValueType(N->getValueType(0)));
381 }
382
383 SDValue DAGTypeLegalizer::PromoteIntRes_INT_EXTEND(SDNode *N) {
384   EVT NVT = TLI.getTypeToTransformTo(*DAG.getContext(), N->getValueType(0));
385   DebugLoc dl = N->getDebugLoc();
386
387   if (getTypeAction(N->getOperand(0).getValueType())
388       == TargetLowering::TypePromoteInteger) {
389     SDValue Res = GetPromotedInteger(N->getOperand(0));
390     assert(Res.getValueType().bitsLE(NVT) && "Extension doesn't make sense!");
391
392     // If the result and operand types are the same after promotion, simplify
393     // to an in-register extension.
394     if (NVT == Res.getValueType()) {
395       // The high bits are not guaranteed to be anything.  Insert an extend.
396       if (N->getOpcode() == ISD::SIGN_EXTEND)
397         return DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, NVT, Res,
398                            DAG.getValueType(N->getOperand(0).getValueType()));
399       if (N->getOpcode() == ISD::ZERO_EXTEND)
400         return DAG.getZeroExtendInReg(Res, dl,
401                       N->getOperand(0).getValueType().getScalarType());
402       assert(N->getOpcode() == ISD::ANY_EXTEND && "Unknown integer extension!");
403       return Res;
404     }
405   }
406
407   // Otherwise, just extend the original operand all the way to the larger type.
408   return DAG.getNode(N->getOpcode(), dl, NVT, N->getOperand(0));
409 }
410
411 SDValue DAGTypeLegalizer::PromoteIntRes_LOAD(LoadSDNode *N) {
412   assert(ISD::isUNINDEXEDLoad(N) && "Indexed load during type legalization!");
413   EVT NVT = TLI.getTypeToTransformTo(*DAG.getContext(), N->getValueType(0));
414   ISD::LoadExtType ExtType =
415     ISD::isNON_EXTLoad(N) ? ISD::EXTLOAD : N->getExtensionType();
416   DebugLoc dl = N->getDebugLoc();
417   SDValue Res = DAG.getExtLoad(ExtType, dl, NVT, N->getChain(), N->getBasePtr(),
418                                N->getPointerInfo(),
419                                N->getMemoryVT(), N->isVolatile(),
420                                N->isNonTemporal(), N->getAlignment());
421
422   // Legalized the chain result - switch anything that used the old chain to
423   // use the new one.
424   ReplaceValueWith(SDValue(N, 1), Res.getValue(1));
425   return Res;
426 }
427
428 /// Promote the overflow flag of an overflowing arithmetic node.
429 SDValue DAGTypeLegalizer::PromoteIntRes_Overflow(SDNode *N) {
430   // Simply change the return type of the boolean result.
431   EVT NVT = TLI.getTypeToTransformTo(*DAG.getContext(), N->getValueType(1));
432   EVT ValueVTs[] = { N->getValueType(0), NVT };
433   SDValue Ops[] = { N->getOperand(0), N->getOperand(1) };
434   SDValue Res = DAG.getNode(N->getOpcode(), N->getDebugLoc(),
435                             DAG.getVTList(ValueVTs, 2), Ops, 2);
436
437   // Modified the sum result - switch anything that used the old sum to use
438   // the new one.
439   ReplaceValueWith(SDValue(N, 0), Res);
440
441   return SDValue(Res.getNode(), 1);
442 }
443
444 SDValue DAGTypeLegalizer::PromoteIntRes_SADDSUBO(SDNode *N, unsigned ResNo) {
445   if (ResNo == 1)
446     return PromoteIntRes_Overflow(N);
447
448   // The operation overflowed iff the result in the larger type is not the
449   // sign extension of its truncation to the original type.
450   SDValue LHS = SExtPromotedInteger(N->getOperand(0));
451   SDValue RHS = SExtPromotedInteger(N->getOperand(1));
452   EVT OVT = N->getOperand(0).getValueType();
453   EVT NVT = LHS.getValueType();
454   DebugLoc dl = N->getDebugLoc();
455
456   // Do the arithmetic in the larger type.
457   unsigned Opcode = N->getOpcode() == ISD::SADDO ? ISD::ADD : ISD::SUB;
458   SDValue Res = DAG.getNode(Opcode, dl, NVT, LHS, RHS);
459
460   // Calculate the overflow flag: sign extend the arithmetic result from
461   // the original type.
462   SDValue Ofl = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, NVT, Res,
463                             DAG.getValueType(OVT));
464   // Overflowed if and only if this is not equal to Res.
465   Ofl = DAG.getSetCC(dl, N->getValueType(1), Ofl, Res, ISD::SETNE);
466
467   // Use the calculated overflow everywhere.
468   ReplaceValueWith(SDValue(N, 1), Ofl);
469
470   return Res;
471 }
472
473 SDValue DAGTypeLegalizer::PromoteIntRes_SDIV(SDNode *N) {
474   // Sign extend the input.
475   SDValue LHS = SExtPromotedInteger(N->getOperand(0));
476   SDValue RHS = SExtPromotedInteger(N->getOperand(1));
477   return DAG.getNode(N->getOpcode(), N->getDebugLoc(),
478                      LHS.getValueType(), LHS, RHS);
479 }
480
481 SDValue DAGTypeLegalizer::PromoteIntRes_SELECT(SDNode *N) {
482   SDValue LHS = GetPromotedInteger(N->getOperand(1));
483   SDValue RHS = GetPromotedInteger(N->getOperand(2));
484   return DAG.getNode(ISD::SELECT, N->getDebugLoc(),
485                      LHS.getValueType(), N->getOperand(0),LHS,RHS);
486 }
487
488 SDValue DAGTypeLegalizer::PromoteIntRes_VSELECT(SDNode *N) {
489   SDValue Mask = GetPromotedInteger(N->getOperand(0));
490   SDValue LHS = GetPromotedInteger(N->getOperand(1));
491   SDValue RHS = GetPromotedInteger(N->getOperand(2));
492   return DAG.getNode(ISD::VSELECT, N->getDebugLoc(),
493                      LHS.getValueType(), Mask, LHS, RHS);
494 }
495
496 SDValue DAGTypeLegalizer::PromoteIntRes_SELECT_CC(SDNode *N) {
497   SDValue LHS = GetPromotedInteger(N->getOperand(2));
498   SDValue RHS = GetPromotedInteger(N->getOperand(3));
499   return DAG.getNode(ISD::SELECT_CC, N->getDebugLoc(),
500                      LHS.getValueType(), N->getOperand(0),
501                      N->getOperand(1), LHS, RHS, N->getOperand(4));
502 }
503
504 SDValue DAGTypeLegalizer::PromoteIntRes_SETCC(SDNode *N) {
505   EVT SVT = TLI.getSetCCResultType(N->getOperand(0).getValueType());
506   // Vector setcc result types need to be leglized.
507   SVT = TLI.getTypeToTransformTo(*DAG.getContext(), SVT);
508
509   DebugLoc dl = N->getDebugLoc();
510   assert(SVT.isVector() == N->getOperand(0).getValueType().isVector() &&
511          "Vector compare must return a vector result!");
512
513   // Get the SETCC result using the canonical SETCC type.
514   SDValue SetCC = DAG.getNode(N->getOpcode(), dl, SVT, N->getOperand(0),
515                               N->getOperand(1), N->getOperand(2));
516
517   // Convert to the expected type.
518   EVT NVT = TLI.getTypeToTransformTo(*DAG.getContext(), N->getValueType(0));
519   assert(NVT.bitsLE(SVT) && "Integer type overpromoted?");
520   return DAG.getNode(ISD::TRUNCATE, dl, NVT, SetCC);
521 }
522
523 SDValue DAGTypeLegalizer::PromoteIntRes_SHL(SDNode *N) {
524   return DAG.getNode(ISD::SHL, N->getDebugLoc(),
525                 TLI.getTypeToTransformTo(*DAG.getContext(), N->getValueType(0)),
526                      GetPromotedInteger(N->getOperand(0)), N->getOperand(1));
527 }
528
529 SDValue DAGTypeLegalizer::PromoteIntRes_SIGN_EXTEND_INREG(SDNode *N) {
530   SDValue Op = GetPromotedInteger(N->getOperand(0));
531   return DAG.getNode(ISD::SIGN_EXTEND_INREG, N->getDebugLoc(),
532                      Op.getValueType(), Op, N->getOperand(1));
533 }
534
535 SDValue DAGTypeLegalizer::PromoteIntRes_SimpleIntBinOp(SDNode *N) {
536   // The input may have strange things in the top bits of the registers, but
537   // these operations don't care.  They may have weird bits going out, but
538   // that too is okay if they are integer operations.
539   SDValue LHS = GetPromotedInteger(N->getOperand(0));
540   SDValue RHS = GetPromotedInteger(N->getOperand(1));
541   return DAG.getNode(N->getOpcode(), N->getDebugLoc(),
542                     LHS.getValueType(), LHS, RHS);
543 }
544
545 SDValue DAGTypeLegalizer::PromoteIntRes_SRA(SDNode *N) {
546   // The input value must be properly sign extended.
547   SDValue Res = SExtPromotedInteger(N->getOperand(0));
548   return DAG.getNode(ISD::SRA, N->getDebugLoc(),
549                      Res.getValueType(), Res, N->getOperand(1));
550 }
551
552 SDValue DAGTypeLegalizer::PromoteIntRes_SRL(SDNode *N) {
553   // The input value must be properly zero extended.
554   EVT VT = N->getValueType(0);
555   EVT NVT = TLI.getTypeToTransformTo(*DAG.getContext(), VT);
556   SDValue Res = ZExtPromotedInteger(N->getOperand(0));
557   return DAG.getNode(ISD::SRL, N->getDebugLoc(), NVT, Res, N->getOperand(1));
558 }
559
560 SDValue DAGTypeLegalizer::PromoteIntRes_TRUNCATE(SDNode *N) {
561   EVT NVT = TLI.getTypeToTransformTo(*DAG.getContext(), N->getValueType(0));
562   SDValue Res;
563   SDValue InOp = N->getOperand(0);
564   DebugLoc dl = N->getDebugLoc();
565
566   switch (getTypeAction(InOp.getValueType())) {
567   default: llvm_unreachable("Unknown type action!");
568   case TargetLowering::TypeLegal:
569   case TargetLowering::TypeExpandInteger:
570     Res = InOp;
571     break;
572   case TargetLowering::TypePromoteInteger:
573     Res = GetPromotedInteger(InOp);
574     break;
575   case TargetLowering::TypeSplitVector:
576     EVT InVT = InOp.getValueType();
577     assert(InVT.isVector() && "Cannot split scalar types");
578     unsigned NumElts = InVT.getVectorNumElements();
579     assert(NumElts == NVT.getVectorNumElements() &&
580            "Dst and Src must have the same number of elements");
581     EVT EltVT = InVT.getScalarType();
582     assert(isPowerOf2_32(NumElts) &&
583            "Promoted vector type must be a power of two");
584
585     EVT HalfVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumElts/2);
586     EVT HalfNVT = EVT::getVectorVT(*DAG.getContext(), NVT.getScalarType(),
587                                    NumElts/2);
588
589     SDValue EOp1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, HalfVT, InOp,
590                                DAG.getIntPtrConstant(0));
591     SDValue EOp2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, HalfVT, InOp,
592                                DAG.getIntPtrConstant(NumElts/2));
593     EOp1 = DAG.getNode(ISD::TRUNCATE, dl, HalfNVT, EOp1);
594     EOp2 = DAG.getNode(ISD::TRUNCATE, dl, HalfNVT, EOp2);
595
596     return DAG.getNode(ISD::CONCAT_VECTORS, dl, NVT, EOp1, EOp2);
597   }
598
599   // Truncate to NVT instead of VT
600   return DAG.getNode(ISD::TRUNCATE, dl, NVT, Res);
601 }
602
603 SDValue DAGTypeLegalizer::PromoteIntRes_UADDSUBO(SDNode *N, unsigned ResNo) {
604   if (ResNo == 1)
605     return PromoteIntRes_Overflow(N);
606
607   // The operation overflowed iff the result in the larger type is not the
608   // zero extension of its truncation to the original type.
609   SDValue LHS = ZExtPromotedInteger(N->getOperand(0));
610   SDValue RHS = ZExtPromotedInteger(N->getOperand(1));
611   EVT OVT = N->getOperand(0).getValueType();
612   EVT NVT = LHS.getValueType();
613   DebugLoc dl = N->getDebugLoc();
614
615   // Do the arithmetic in the larger type.
616   unsigned Opcode = N->getOpcode() == ISD::UADDO ? ISD::ADD : ISD::SUB;
617   SDValue Res = DAG.getNode(Opcode, dl, NVT, LHS, RHS);
618
619   // Calculate the overflow flag: zero extend the arithmetic result from
620   // the original type.
621   SDValue Ofl = DAG.getZeroExtendInReg(Res, dl, OVT);
622   // Overflowed if and only if this is not equal to Res.
623   Ofl = DAG.getSetCC(dl, N->getValueType(1), Ofl, Res, ISD::SETNE);
624
625   // Use the calculated overflow everywhere.
626   ReplaceValueWith(SDValue(N, 1), Ofl);
627
628   return Res;
629 }
630
631 SDValue DAGTypeLegalizer::PromoteIntRes_XMULO(SDNode *N, unsigned ResNo) {
632   // Promote the overflow bit trivially.
633   if (ResNo == 1)
634     return PromoteIntRes_Overflow(N);
635
636   SDValue LHS = N->getOperand(0), RHS = N->getOperand(1);
637   DebugLoc DL = N->getDebugLoc();
638   EVT SmallVT = LHS.getValueType();
639
640   // To determine if the result overflowed in a larger type, we extend the
641   // input to the larger type, do the multiply, then check the high bits of
642   // the result to see if the overflow happened.
643   if (N->getOpcode() == ISD::SMULO) {
644     LHS = SExtPromotedInteger(LHS);
645     RHS = SExtPromotedInteger(RHS);
646   } else {
647     LHS = ZExtPromotedInteger(LHS);
648     RHS = ZExtPromotedInteger(RHS);
649   }
650   SDValue Mul = DAG.getNode(ISD::MUL, DL, LHS.getValueType(), LHS, RHS);
651
652   // Overflow occurred iff the high part of the result does not
653   // zero/sign-extend the low part.
654   SDValue Overflow;
655   if (N->getOpcode() == ISD::UMULO) {
656     // Unsigned overflow occurred iff the high part is non-zero.
657     SDValue Hi = DAG.getNode(ISD::SRL, DL, Mul.getValueType(), Mul,
658                              DAG.getIntPtrConstant(SmallVT.getSizeInBits()));
659     Overflow = DAG.getSetCC(DL, N->getValueType(1), Hi,
660                             DAG.getConstant(0, Hi.getValueType()), ISD::SETNE);
661   } else {
662     // Signed overflow occurred iff the high part does not sign extend the low.
663     SDValue SExt = DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, Mul.getValueType(),
664                                Mul, DAG.getValueType(SmallVT));
665     Overflow = DAG.getSetCC(DL, N->getValueType(1), SExt, Mul, ISD::SETNE);
666   }
667
668   // Use the calculated overflow everywhere.
669   ReplaceValueWith(SDValue(N, 1), Overflow);
670   return Mul;
671 }
672
673 SDValue DAGTypeLegalizer::PromoteIntRes_UDIV(SDNode *N) {
674   // Zero extend the input.
675   SDValue LHS = ZExtPromotedInteger(N->getOperand(0));
676   SDValue RHS = ZExtPromotedInteger(N->getOperand(1));
677   return DAG.getNode(N->getOpcode(), N->getDebugLoc(),
678                      LHS.getValueType(), LHS, RHS);
679 }
680
681 SDValue DAGTypeLegalizer::PromoteIntRes_UNDEF(SDNode *N) {
682   return DAG.getUNDEF(TLI.getTypeToTransformTo(*DAG.getContext(),
683                                                N->getValueType(0)));
684 }
685
686 SDValue DAGTypeLegalizer::PromoteIntRes_VAARG(SDNode *N) {
687   SDValue Chain = N->getOperand(0); // Get the chain.
688   SDValue Ptr = N->getOperand(1); // Get the pointer.
689   EVT VT = N->getValueType(0);
690   DebugLoc dl = N->getDebugLoc();
691
692   EVT RegVT = TLI.getRegisterType(*DAG.getContext(), VT);
693   unsigned NumRegs = TLI.getNumRegisters(*DAG.getContext(), VT);
694   // The argument is passed as NumRegs registers of type RegVT.
695
696   SmallVector<SDValue, 8> Parts(NumRegs);
697   for (unsigned i = 0; i < NumRegs; ++i) {
698     Parts[i] = DAG.getVAArg(RegVT, dl, Chain, Ptr, N->getOperand(2),
699                             N->getConstantOperandVal(3));
700     Chain = Parts[i].getValue(1);
701   }
702
703   // Handle endianness of the load.
704   if (TLI.isBigEndian())
705     std::reverse(Parts.begin(), Parts.end());
706
707   // Assemble the parts in the promoted type.
708   EVT NVT = TLI.getTypeToTransformTo(*DAG.getContext(), N->getValueType(0));
709   SDValue Res = DAG.getNode(ISD::ZERO_EXTEND, dl, NVT, Parts[0]);
710   for (unsigned i = 1; i < NumRegs; ++i) {
711     SDValue Part = DAG.getNode(ISD::ZERO_EXTEND, dl, NVT, Parts[i]);
712     // Shift it to the right position and "or" it in.
713     Part = DAG.getNode(ISD::SHL, dl, NVT, Part,
714                        DAG.getConstant(i * RegVT.getSizeInBits(),
715                                        TLI.getPointerTy()));
716     Res = DAG.getNode(ISD::OR, dl, NVT, Res, Part);
717   }
718
719   // Modified the chain result - switch anything that used the old chain to
720   // use the new one.
721   ReplaceValueWith(SDValue(N, 1), Chain);
722
723   return Res;
724 }
725
726 //===----------------------------------------------------------------------===//
727 //  Integer Operand Promotion
728 //===----------------------------------------------------------------------===//
729
730 /// PromoteIntegerOperand - This method is called when the specified operand of
731 /// the specified node is found to need promotion.  At this point, all of the
732 /// result types of the node are known to be legal, but other operands of the
733 /// node may need promotion or expansion as well as the specified one.
734 bool DAGTypeLegalizer::PromoteIntegerOperand(SDNode *N, unsigned OpNo) {
735   DEBUG(dbgs() << "Promote integer operand: "; N->dump(&DAG); dbgs() << "\n");
736   SDValue Res = SDValue();
737
738   if (CustomLowerNode(N, N->getOperand(OpNo).getValueType(), false))
739     return false;
740
741   switch (N->getOpcode()) {
742     default:
743   #ifndef NDEBUG
744     dbgs() << "PromoteIntegerOperand Op #" << OpNo << ": ";
745     N->dump(&DAG); dbgs() << "\n";
746   #endif
747     llvm_unreachable("Do not know how to promote this operator's operand!");
748
749   case ISD::ANY_EXTEND:   Res = PromoteIntOp_ANY_EXTEND(N); break;
750   case ISD::ATOMIC_STORE:
751     Res = PromoteIntOp_ATOMIC_STORE(cast<AtomicSDNode>(N));
752     break;
753   case ISD::BITCAST:      Res = PromoteIntOp_BITCAST(N); break;
754   case ISD::BR_CC:        Res = PromoteIntOp_BR_CC(N, OpNo); break;
755   case ISD::BRCOND:       Res = PromoteIntOp_BRCOND(N, OpNo); break;
756   case ISD::BUILD_PAIR:   Res = PromoteIntOp_BUILD_PAIR(N); break;
757   case ISD::BUILD_VECTOR: Res = PromoteIntOp_BUILD_VECTOR(N); break;
758   case ISD::CONCAT_VECTORS: Res = PromoteIntOp_CONCAT_VECTORS(N); break;
759   case ISD::EXTRACT_VECTOR_ELT: Res = PromoteIntOp_EXTRACT_VECTOR_ELT(N); break;
760   case ISD::CONVERT_RNDSAT:
761                           Res = PromoteIntOp_CONVERT_RNDSAT(N); break;
762   case ISD::INSERT_VECTOR_ELT:
763                           Res = PromoteIntOp_INSERT_VECTOR_ELT(N, OpNo);break;
764   case ISD::MEMBARRIER:   Res = PromoteIntOp_MEMBARRIER(N); break;
765   case ISD::SCALAR_TO_VECTOR:
766                           Res = PromoteIntOp_SCALAR_TO_VECTOR(N); break;
767   case ISD::VSELECT:
768   case ISD::SELECT:       Res = PromoteIntOp_SELECT(N, OpNo); break;
769   case ISD::SELECT_CC:    Res = PromoteIntOp_SELECT_CC(N, OpNo); break;
770   case ISD::SETCC:        Res = PromoteIntOp_SETCC(N, OpNo); break;
771   case ISD::SIGN_EXTEND:  Res = PromoteIntOp_SIGN_EXTEND(N); break;
772   case ISD::SINT_TO_FP:   Res = PromoteIntOp_SINT_TO_FP(N); break;
773   case ISD::STORE:        Res = PromoteIntOp_STORE(cast<StoreSDNode>(N),
774                                                    OpNo); break;
775   case ISD::TRUNCATE:     Res = PromoteIntOp_TRUNCATE(N); break;
776   case ISD::FP16_TO_FP32:
777   case ISD::UINT_TO_FP:   Res = PromoteIntOp_UINT_TO_FP(N); break;
778   case ISD::ZERO_EXTEND:  Res = PromoteIntOp_ZERO_EXTEND(N); break;
779
780   case ISD::SHL:
781   case ISD::SRA:
782   case ISD::SRL:
783   case ISD::ROTL:
784   case ISD::ROTR: Res = PromoteIntOp_Shift(N); break;
785   }
786
787   // If the result is null, the sub-method took care of registering results etc.
788   if (!Res.getNode()) return false;
789
790   // If the result is N, the sub-method updated N in place.  Tell the legalizer
791   // core about this.
792   if (Res.getNode() == N)
793     return true;
794
795   assert(Res.getValueType() == N->getValueType(0) && N->getNumValues() == 1 &&
796          "Invalid operand expansion");
797
798   ReplaceValueWith(SDValue(N, 0), Res);
799   return false;
800 }
801
802 /// PromoteSetCCOperands - Promote the operands of a comparison.  This code is
803 /// shared among BR_CC, SELECT_CC, and SETCC handlers.
804 void DAGTypeLegalizer::PromoteSetCCOperands(SDValue &NewLHS,SDValue &NewRHS,
805                                             ISD::CondCode CCCode) {
806   // We have to insert explicit sign or zero extends.  Note that we could
807   // insert sign extends for ALL conditions, but zero extend is cheaper on
808   // many machines (an AND instead of two shifts), so prefer it.
809   switch (CCCode) {
810   default: llvm_unreachable("Unknown integer comparison!");
811   case ISD::SETEQ:
812   case ISD::SETNE:
813   case ISD::SETUGE:
814   case ISD::SETUGT:
815   case ISD::SETULE:
816   case ISD::SETULT:
817     // ALL of these operations will work if we either sign or zero extend
818     // the operands (including the unsigned comparisons!).  Zero extend is
819     // usually a simpler/cheaper operation, so prefer it.
820     NewLHS = ZExtPromotedInteger(NewLHS);
821     NewRHS = ZExtPromotedInteger(NewRHS);
822     break;
823   case ISD::SETGE:
824   case ISD::SETGT:
825   case ISD::SETLT:
826   case ISD::SETLE:
827     NewLHS = SExtPromotedInteger(NewLHS);
828     NewRHS = SExtPromotedInteger(NewRHS);
829     break;
830   }
831 }
832
833 SDValue DAGTypeLegalizer::PromoteIntOp_ANY_EXTEND(SDNode *N) {
834   SDValue Op = GetPromotedInteger(N->getOperand(0));
835   return DAG.getNode(ISD::ANY_EXTEND, N->getDebugLoc(), N->getValueType(0), Op);
836 }
837
838 SDValue DAGTypeLegalizer::PromoteIntOp_ATOMIC_STORE(AtomicSDNode *N) {
839   SDValue Op2 = GetPromotedInteger(N->getOperand(2));
840   return DAG.getAtomic(N->getOpcode(), N->getDebugLoc(), N->getMemoryVT(),
841                        N->getChain(), N->getBasePtr(), Op2, N->getMemOperand(),
842                        N->getOrdering(), N->getSynchScope());
843 }
844
845 SDValue DAGTypeLegalizer::PromoteIntOp_BITCAST(SDNode *N) {
846   // This should only occur in unusual situations like bitcasting to an
847   // x86_fp80, so just turn it into a store+load
848   return CreateStackStoreLoad(N->getOperand(0), N->getValueType(0));
849 }
850
851 SDValue DAGTypeLegalizer::PromoteIntOp_BR_CC(SDNode *N, unsigned OpNo) {
852   assert(OpNo == 2 && "Don't know how to promote this operand!");
853
854   SDValue LHS = N->getOperand(2);
855   SDValue RHS = N->getOperand(3);
856   PromoteSetCCOperands(LHS, RHS, cast<CondCodeSDNode>(N->getOperand(1))->get());
857
858   // The chain (Op#0), CC (#1) and basic block destination (Op#4) are always
859   // legal types.
860   return SDValue(DAG.UpdateNodeOperands(N, N->getOperand(0),
861                                 N->getOperand(1), LHS, RHS, N->getOperand(4)),
862                  0);
863 }
864
865 SDValue DAGTypeLegalizer::PromoteIntOp_BRCOND(SDNode *N, unsigned OpNo) {
866   assert(OpNo == 1 && "only know how to promote condition");
867
868   // Promote all the way up to the canonical SetCC type.
869   EVT SVT = TLI.getSetCCResultType(MVT::Other);
870   SDValue Cond = PromoteTargetBoolean(N->getOperand(1), SVT);
871
872   // The chain (Op#0) and basic block destination (Op#2) are always legal types.
873   return SDValue(DAG.UpdateNodeOperands(N, N->getOperand(0), Cond,
874                                         N->getOperand(2)), 0);
875 }
876
877 SDValue DAGTypeLegalizer::PromoteIntOp_BUILD_PAIR(SDNode *N) {
878   // Since the result type is legal, the operands must promote to it.
879   EVT OVT = N->getOperand(0).getValueType();
880   SDValue Lo = ZExtPromotedInteger(N->getOperand(0));
881   SDValue Hi = GetPromotedInteger(N->getOperand(1));
882   assert(Lo.getValueType() == N->getValueType(0) && "Operand over promoted?");
883   DebugLoc dl = N->getDebugLoc();
884
885   Hi = DAG.getNode(ISD::SHL, dl, N->getValueType(0), Hi,
886                    DAG.getConstant(OVT.getSizeInBits(), TLI.getPointerTy()));
887   return DAG.getNode(ISD::OR, dl, N->getValueType(0), Lo, Hi);
888 }
889
890 SDValue DAGTypeLegalizer::PromoteIntOp_BUILD_VECTOR(SDNode *N) {
891   // The vector type is legal but the element type is not.  This implies
892   // that the vector is a power-of-two in length and that the element
893   // type does not have a strange size (eg: it is not i1).
894   EVT VecVT = N->getValueType(0);
895   unsigned NumElts = VecVT.getVectorNumElements();
896   assert(!(NumElts & 1) && "Legal vector of one illegal element?");
897
898   // Promote the inserted value.  The type does not need to match the
899   // vector element type.  Check that any extra bits introduced will be
900   // truncated away.
901   assert(N->getOperand(0).getValueType().getSizeInBits() >=
902          N->getValueType(0).getVectorElementType().getSizeInBits() &&
903          "Type of inserted value narrower than vector element type!");
904
905   SmallVector<SDValue, 16> NewOps;
906   for (unsigned i = 0; i < NumElts; ++i)
907     NewOps.push_back(GetPromotedInteger(N->getOperand(i)));
908
909   return SDValue(DAG.UpdateNodeOperands(N, &NewOps[0], NumElts), 0);
910 }
911
912 SDValue DAGTypeLegalizer::PromoteIntOp_CONVERT_RNDSAT(SDNode *N) {
913   ISD::CvtCode CvtCode = cast<CvtRndSatSDNode>(N)->getCvtCode();
914   assert ((CvtCode == ISD::CVT_SS || CvtCode == ISD::CVT_SU ||
915            CvtCode == ISD::CVT_US || CvtCode == ISD::CVT_UU ||
916            CvtCode == ISD::CVT_FS || CvtCode == ISD::CVT_FU) &&
917            "can only promote integer arguments");
918   SDValue InOp = GetPromotedInteger(N->getOperand(0));
919   return DAG.getConvertRndSat(N->getValueType(0), N->getDebugLoc(), InOp,
920                               N->getOperand(1), N->getOperand(2),
921                               N->getOperand(3), N->getOperand(4), CvtCode);
922 }
923
924 SDValue DAGTypeLegalizer::PromoteIntOp_INSERT_VECTOR_ELT(SDNode *N,
925                                                          unsigned OpNo) {
926   if (OpNo == 1) {
927     // Promote the inserted value.  This is valid because the type does not
928     // have to match the vector element type.
929
930     // Check that any extra bits introduced will be truncated away.
931     assert(N->getOperand(1).getValueType().getSizeInBits() >=
932            N->getValueType(0).getVectorElementType().getSizeInBits() &&
933            "Type of inserted value narrower than vector element type!");
934     return SDValue(DAG.UpdateNodeOperands(N, N->getOperand(0),
935                                   GetPromotedInteger(N->getOperand(1)),
936                                   N->getOperand(2)),
937                    0);
938   }
939
940   assert(OpNo == 2 && "Different operand and result vector types?");
941
942   // Promote the index.
943   SDValue Idx = ZExtPromotedInteger(N->getOperand(2));
944   return SDValue(DAG.UpdateNodeOperands(N, N->getOperand(0),
945                                 N->getOperand(1), Idx), 0);
946 }
947
948 SDValue DAGTypeLegalizer::PromoteIntOp_MEMBARRIER(SDNode *N) {
949   SDValue NewOps[6];
950   DebugLoc dl = N->getDebugLoc();
951   NewOps[0] = N->getOperand(0);
952   for (unsigned i = 1; i < array_lengthof(NewOps); ++i) {
953     SDValue Flag = GetPromotedInteger(N->getOperand(i));
954     NewOps[i] = DAG.getZeroExtendInReg(Flag, dl, MVT::i1);
955   }
956   return SDValue(DAG.UpdateNodeOperands(N, NewOps, array_lengthof(NewOps)), 0);
957 }
958
959 SDValue DAGTypeLegalizer::PromoteIntOp_SCALAR_TO_VECTOR(SDNode *N) {
960   // Integer SCALAR_TO_VECTOR operands are implicitly truncated, so just promote
961   // the operand in place.
962   return SDValue(DAG.UpdateNodeOperands(N,
963                                 GetPromotedInteger(N->getOperand(0))), 0);
964 }
965
966 SDValue DAGTypeLegalizer::PromoteIntOp_SELECT(SDNode *N, unsigned OpNo) {
967   assert(OpNo == 0 && "Only know how to promote the condition!");
968   SDValue Cond = N->getOperand(0);
969   EVT OpTy = N->getOperand(1).getValueType();
970
971   // Promote all the way up to the canonical SetCC type.
972   EVT SVT = TLI.getSetCCResultType(N->getOpcode() == ISD::SELECT ?
973                                    OpTy.getScalarType() : OpTy);
974   Cond = PromoteTargetBoolean(Cond, SVT);
975
976   return SDValue(DAG.UpdateNodeOperands(N, Cond, N->getOperand(1),
977                                         N->getOperand(2)), 0);
978 }
979
980 SDValue DAGTypeLegalizer::PromoteIntOp_SELECT_CC(SDNode *N, unsigned OpNo) {
981   assert(OpNo == 0 && "Don't know how to promote this operand!");
982
983   SDValue LHS = N->getOperand(0);
984   SDValue RHS = N->getOperand(1);
985   PromoteSetCCOperands(LHS, RHS, cast<CondCodeSDNode>(N->getOperand(4))->get());
986
987   // The CC (#4) and the possible return values (#2 and #3) have legal types.
988   return SDValue(DAG.UpdateNodeOperands(N, LHS, RHS, N->getOperand(2),
989                                 N->getOperand(3), N->getOperand(4)), 0);
990 }
991
992 SDValue DAGTypeLegalizer::PromoteIntOp_SETCC(SDNode *N, unsigned OpNo) {
993   assert(OpNo == 0 && "Don't know how to promote this operand!");
994
995   SDValue LHS = N->getOperand(0);
996   SDValue RHS = N->getOperand(1);
997   PromoteSetCCOperands(LHS, RHS, cast<CondCodeSDNode>(N->getOperand(2))->get());
998
999   // The CC (#2) is always legal.
1000   return SDValue(DAG.UpdateNodeOperands(N, LHS, RHS, N->getOperand(2)), 0);
1001 }
1002
1003 SDValue DAGTypeLegalizer::PromoteIntOp_Shift(SDNode *N) {
1004   return SDValue(DAG.UpdateNodeOperands(N, N->getOperand(0),
1005                                 ZExtPromotedInteger(N->getOperand(1))), 0);
1006 }
1007
1008 SDValue DAGTypeLegalizer::PromoteIntOp_SIGN_EXTEND(SDNode *N) {
1009   SDValue Op = GetPromotedInteger(N->getOperand(0));
1010   DebugLoc dl = N->getDebugLoc();
1011   Op = DAG.getNode(ISD::ANY_EXTEND, dl, N->getValueType(0), Op);
1012   return DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, Op.getValueType(),
1013                      Op, DAG.getValueType(N->getOperand(0).getValueType()));
1014 }
1015
1016 SDValue DAGTypeLegalizer::PromoteIntOp_SINT_TO_FP(SDNode *N) {
1017   return SDValue(DAG.UpdateNodeOperands(N,
1018                                 SExtPromotedInteger(N->getOperand(0))), 0);
1019 }
1020
1021 SDValue DAGTypeLegalizer::PromoteIntOp_STORE(StoreSDNode *N, unsigned OpNo){
1022   assert(ISD::isUNINDEXEDStore(N) && "Indexed store during type legalization!");
1023   SDValue Ch = N->getChain(), Ptr = N->getBasePtr();
1024   unsigned Alignment = N->getAlignment();
1025   bool isVolatile = N->isVolatile();
1026   bool isNonTemporal = N->isNonTemporal();
1027   DebugLoc dl = N->getDebugLoc();
1028
1029   SDValue Val = GetPromotedInteger(N->getValue());  // Get promoted value.
1030
1031   // Truncate the value and store the result.
1032   return DAG.getTruncStore(Ch, dl, Val, Ptr, N->getPointerInfo(),
1033                            N->getMemoryVT(),
1034                            isVolatile, isNonTemporal, Alignment);
1035 }
1036
1037 SDValue DAGTypeLegalizer::PromoteIntOp_TRUNCATE(SDNode *N) {
1038   SDValue Op = GetPromotedInteger(N->getOperand(0));
1039   return DAG.getNode(ISD::TRUNCATE, N->getDebugLoc(), N->getValueType(0), Op);
1040 }
1041
1042 SDValue DAGTypeLegalizer::PromoteIntOp_UINT_TO_FP(SDNode *N) {
1043   return SDValue(DAG.UpdateNodeOperands(N,
1044                                 ZExtPromotedInteger(N->getOperand(0))), 0);
1045 }
1046
1047 SDValue DAGTypeLegalizer::PromoteIntOp_ZERO_EXTEND(SDNode *N) {
1048   DebugLoc dl = N->getDebugLoc();
1049   SDValue Op = GetPromotedInteger(N->getOperand(0));
1050   Op = DAG.getNode(ISD::ANY_EXTEND, dl, N->getValueType(0), Op);
1051   return DAG.getZeroExtendInReg(Op, dl,
1052                                 N->getOperand(0).getValueType().getScalarType());
1053 }
1054
1055
1056 //===----------------------------------------------------------------------===//
1057 //  Integer Result Expansion
1058 //===----------------------------------------------------------------------===//
1059
1060 /// ExpandIntegerResult - This method is called when the specified result of the
1061 /// specified node is found to need expansion.  At this point, the node may also
1062 /// have invalid operands or may have other results that need promotion, we just
1063 /// know that (at least) one result needs expansion.
1064 void DAGTypeLegalizer::ExpandIntegerResult(SDNode *N, unsigned ResNo) {
1065   DEBUG(dbgs() << "Expand integer result: "; N->dump(&DAG); dbgs() << "\n");
1066   SDValue Lo, Hi;
1067   Lo = Hi = SDValue();
1068
1069   // See if the target wants to custom expand this node.
1070   if (CustomLowerNode(N, N->getValueType(ResNo), true))
1071     return;
1072
1073   switch (N->getOpcode()) {
1074   default:
1075 #ifndef NDEBUG
1076     dbgs() << "ExpandIntegerResult #" << ResNo << ": ";
1077     N->dump(&DAG); dbgs() << "\n";
1078 #endif
1079     llvm_unreachable("Do not know how to expand the result of this operator!");
1080
1081   case ISD::MERGE_VALUES: SplitRes_MERGE_VALUES(N, ResNo, Lo, Hi); break;
1082   case ISD::SELECT:       SplitRes_SELECT(N, Lo, Hi); break;
1083   case ISD::SELECT_CC:    SplitRes_SELECT_CC(N, Lo, Hi); break;
1084   case ISD::UNDEF:        SplitRes_UNDEF(N, Lo, Hi); break;
1085
1086   case ISD::BITCAST:            ExpandRes_BITCAST(N, Lo, Hi); break;
1087   case ISD::BUILD_PAIR:         ExpandRes_BUILD_PAIR(N, Lo, Hi); break;
1088   case ISD::EXTRACT_ELEMENT:    ExpandRes_EXTRACT_ELEMENT(N, Lo, Hi); break;
1089   case ISD::EXTRACT_VECTOR_ELT: ExpandRes_EXTRACT_VECTOR_ELT(N, Lo, Hi); break;
1090   case ISD::VAARG:              ExpandRes_VAARG(N, Lo, Hi); break;
1091
1092   case ISD::ANY_EXTEND:  ExpandIntRes_ANY_EXTEND(N, Lo, Hi); break;
1093   case ISD::AssertSext:  ExpandIntRes_AssertSext(N, Lo, Hi); break;
1094   case ISD::AssertZext:  ExpandIntRes_AssertZext(N, Lo, Hi); break;
1095   case ISD::BSWAP:       ExpandIntRes_BSWAP(N, Lo, Hi); break;
1096   case ISD::Constant:    ExpandIntRes_Constant(N, Lo, Hi); break;
1097   case ISD::CTLZ:        ExpandIntRes_CTLZ(N, Lo, Hi); break;
1098   case ISD::CTPOP:       ExpandIntRes_CTPOP(N, Lo, Hi); break;
1099   case ISD::CTTZ:        ExpandIntRes_CTTZ(N, Lo, Hi); break;
1100   case ISD::FP_TO_SINT:  ExpandIntRes_FP_TO_SINT(N, Lo, Hi); break;
1101   case ISD::FP_TO_UINT:  ExpandIntRes_FP_TO_UINT(N, Lo, Hi); break;
1102   case ISD::LOAD:        ExpandIntRes_LOAD(cast<LoadSDNode>(N), Lo, Hi); break;
1103   case ISD::MUL:         ExpandIntRes_MUL(N, Lo, Hi); break;
1104   case ISD::SDIV:        ExpandIntRes_SDIV(N, Lo, Hi); break;
1105   case ISD::SIGN_EXTEND: ExpandIntRes_SIGN_EXTEND(N, Lo, Hi); break;
1106   case ISD::SIGN_EXTEND_INREG: ExpandIntRes_SIGN_EXTEND_INREG(N, Lo, Hi); break;
1107   case ISD::SREM:        ExpandIntRes_SREM(N, Lo, Hi); break;
1108   case ISD::TRUNCATE:    ExpandIntRes_TRUNCATE(N, Lo, Hi); break;
1109   case ISD::UDIV:        ExpandIntRes_UDIV(N, Lo, Hi); break;
1110   case ISD::UREM:        ExpandIntRes_UREM(N, Lo, Hi); break;
1111   case ISD::ZERO_EXTEND: ExpandIntRes_ZERO_EXTEND(N, Lo, Hi); break;
1112   case ISD::ATOMIC_LOAD: ExpandIntRes_ATOMIC_LOAD(N, Lo, Hi); break;
1113
1114   case ISD::ATOMIC_LOAD_ADD:
1115   case ISD::ATOMIC_LOAD_SUB:
1116   case ISD::ATOMIC_LOAD_AND:
1117   case ISD::ATOMIC_LOAD_OR:
1118   case ISD::ATOMIC_LOAD_XOR:
1119   case ISD::ATOMIC_LOAD_NAND:
1120   case ISD::ATOMIC_LOAD_MIN:
1121   case ISD::ATOMIC_LOAD_MAX:
1122   case ISD::ATOMIC_LOAD_UMIN:
1123   case ISD::ATOMIC_LOAD_UMAX:
1124   case ISD::ATOMIC_SWAP: {
1125     std::pair<SDValue, SDValue> Tmp = ExpandAtomic(N);
1126     SplitInteger(Tmp.first, Lo, Hi);
1127     ReplaceValueWith(SDValue(N, 1), Tmp.second);
1128     break;
1129   }
1130
1131   case ISD::AND:
1132   case ISD::OR:
1133   case ISD::XOR: ExpandIntRes_Logical(N, Lo, Hi); break;
1134
1135   case ISD::ADD:
1136   case ISD::SUB: ExpandIntRes_ADDSUB(N, Lo, Hi); break;
1137
1138   case ISD::ADDC:
1139   case ISD::SUBC: ExpandIntRes_ADDSUBC(N, Lo, Hi); break;
1140
1141   case ISD::ADDE:
1142   case ISD::SUBE: ExpandIntRes_ADDSUBE(N, Lo, Hi); break;
1143
1144   case ISD::SHL:
1145   case ISD::SRA:
1146   case ISD::SRL: ExpandIntRes_Shift(N, Lo, Hi); break;
1147
1148   case ISD::SADDO:
1149   case ISD::SSUBO: ExpandIntRes_SADDSUBO(N, Lo, Hi); break;
1150   case ISD::UADDO:
1151   case ISD::USUBO: ExpandIntRes_UADDSUBO(N, Lo, Hi); break;
1152   case ISD::UMULO:
1153   case ISD::SMULO: ExpandIntRes_XMULO(N, Lo, Hi); break;
1154   }
1155
1156   // If Lo/Hi is null, the sub-method took care of registering results etc.
1157   if (Lo.getNode())
1158     SetExpandedInteger(SDValue(N, ResNo), Lo, Hi);
1159 }
1160
1161 /// Lower an atomic node to the appropriate builtin call.
1162 std::pair <SDValue, SDValue> DAGTypeLegalizer::ExpandAtomic(SDNode *Node) {
1163   unsigned Opc = Node->getOpcode();
1164   MVT VT = cast<AtomicSDNode>(Node)->getMemoryVT().getSimpleVT();
1165   RTLIB::Libcall LC;
1166
1167   switch (Opc) {
1168   default:
1169     llvm_unreachable("Unhandled atomic intrinsic Expand!");
1170     break;
1171   case ISD::ATOMIC_SWAP:
1172     switch (VT.SimpleTy) {
1173     default: llvm_unreachable("Unexpected value type for atomic!");
1174     case MVT::i8:  LC = RTLIB::SYNC_LOCK_TEST_AND_SET_1; break;
1175     case MVT::i16: LC = RTLIB::SYNC_LOCK_TEST_AND_SET_2; break;
1176     case MVT::i32: LC = RTLIB::SYNC_LOCK_TEST_AND_SET_4; break;
1177     case MVT::i64: LC = RTLIB::SYNC_LOCK_TEST_AND_SET_8; break;
1178     }
1179     break;
1180   case ISD::ATOMIC_CMP_SWAP:
1181     switch (VT.SimpleTy) {
1182     default: llvm_unreachable("Unexpected value type for atomic!");
1183     case MVT::i8:  LC = RTLIB::SYNC_VAL_COMPARE_AND_SWAP_1; break;
1184     case MVT::i16: LC = RTLIB::SYNC_VAL_COMPARE_AND_SWAP_2; break;
1185     case MVT::i32: LC = RTLIB::SYNC_VAL_COMPARE_AND_SWAP_4; break;
1186     case MVT::i64: LC = RTLIB::SYNC_VAL_COMPARE_AND_SWAP_8; break;
1187     }
1188     break;
1189   case ISD::ATOMIC_LOAD_ADD:
1190     switch (VT.SimpleTy) {
1191     default: llvm_unreachable("Unexpected value type for atomic!");
1192     case MVT::i8:  LC = RTLIB::SYNC_FETCH_AND_ADD_1; break;
1193     case MVT::i16: LC = RTLIB::SYNC_FETCH_AND_ADD_2; break;
1194     case MVT::i32: LC = RTLIB::SYNC_FETCH_AND_ADD_4; break;
1195     case MVT::i64: LC = RTLIB::SYNC_FETCH_AND_ADD_8; break;
1196     }
1197     break;
1198   case ISD::ATOMIC_LOAD_SUB:
1199     switch (VT.SimpleTy) {
1200     default: llvm_unreachable("Unexpected value type for atomic!");
1201     case MVT::i8:  LC = RTLIB::SYNC_FETCH_AND_SUB_1; break;
1202     case MVT::i16: LC = RTLIB::SYNC_FETCH_AND_SUB_2; break;
1203     case MVT::i32: LC = RTLIB::SYNC_FETCH_AND_SUB_4; break;
1204     case MVT::i64: LC = RTLIB::SYNC_FETCH_AND_SUB_8; break;
1205     }
1206     break;
1207   case ISD::ATOMIC_LOAD_AND:
1208     switch (VT.SimpleTy) {
1209     default: llvm_unreachable("Unexpected value type for atomic!");
1210     case MVT::i8:  LC = RTLIB::SYNC_FETCH_AND_AND_1; break;
1211     case MVT::i16: LC = RTLIB::SYNC_FETCH_AND_AND_2; break;
1212     case MVT::i32: LC = RTLIB::SYNC_FETCH_AND_AND_4; break;
1213     case MVT::i64: LC = RTLIB::SYNC_FETCH_AND_AND_8; break;
1214     }
1215     break;
1216   case ISD::ATOMIC_LOAD_OR:
1217     switch (VT.SimpleTy) {
1218     default: llvm_unreachable("Unexpected value type for atomic!");
1219     case MVT::i8:  LC = RTLIB::SYNC_FETCH_AND_OR_1; break;
1220     case MVT::i16: LC = RTLIB::SYNC_FETCH_AND_OR_2; break;
1221     case MVT::i32: LC = RTLIB::SYNC_FETCH_AND_OR_4; break;
1222     case MVT::i64: LC = RTLIB::SYNC_FETCH_AND_OR_8; break;
1223     }
1224     break;
1225   case ISD::ATOMIC_LOAD_XOR:
1226     switch (VT.SimpleTy) {
1227     default: llvm_unreachable("Unexpected value type for atomic!");
1228     case MVT::i8:  LC = RTLIB::SYNC_FETCH_AND_XOR_1; break;
1229     case MVT::i16: LC = RTLIB::SYNC_FETCH_AND_XOR_2; break;
1230     case MVT::i32: LC = RTLIB::SYNC_FETCH_AND_XOR_4; break;
1231     case MVT::i64: LC = RTLIB::SYNC_FETCH_AND_XOR_8; break;
1232     }
1233     break;
1234   case ISD::ATOMIC_LOAD_NAND:
1235     switch (VT.SimpleTy) {
1236     default: llvm_unreachable("Unexpected value type for atomic!");
1237     case MVT::i8:  LC = RTLIB::SYNC_FETCH_AND_NAND_1; break;
1238     case MVT::i16: LC = RTLIB::SYNC_FETCH_AND_NAND_2; break;
1239     case MVT::i32: LC = RTLIB::SYNC_FETCH_AND_NAND_4; break;
1240     case MVT::i64: LC = RTLIB::SYNC_FETCH_AND_NAND_8; break;
1241     }
1242     break;
1243   }
1244
1245   return ExpandChainLibCall(LC, Node, false);
1246 }
1247
1248 /// ExpandShiftByConstant - N is a shift by a value that needs to be expanded,
1249 /// and the shift amount is a constant 'Amt'.  Expand the operation.
1250 void DAGTypeLegalizer::ExpandShiftByConstant(SDNode *N, unsigned Amt,
1251                                              SDValue &Lo, SDValue &Hi) {
1252   DebugLoc DL = N->getDebugLoc();
1253   // Expand the incoming operand to be shifted, so that we have its parts
1254   SDValue InL, InH;
1255   GetExpandedInteger(N->getOperand(0), InL, InH);
1256
1257   EVT NVT = InL.getValueType();
1258   unsigned VTBits = N->getValueType(0).getSizeInBits();
1259   unsigned NVTBits = NVT.getSizeInBits();
1260   EVT ShTy = N->getOperand(1).getValueType();
1261
1262   if (N->getOpcode() == ISD::SHL) {
1263     if (Amt > VTBits) {
1264       Lo = Hi = DAG.getConstant(0, NVT);
1265     } else if (Amt > NVTBits) {
1266       Lo = DAG.getConstant(0, NVT);
1267       Hi = DAG.getNode(ISD::SHL, DL,
1268                        NVT, InL, DAG.getConstant(Amt-NVTBits, ShTy));
1269     } else if (Amt == NVTBits) {
1270       Lo = DAG.getConstant(0, NVT);
1271       Hi = InL;
1272     } else if (Amt == 1 &&
1273                TLI.isOperationLegalOrCustom(ISD::ADDC,
1274                               TLI.getTypeToExpandTo(*DAG.getContext(), NVT))) {
1275       // Emit this X << 1 as X+X.
1276       SDVTList VTList = DAG.getVTList(NVT, MVT::Glue);
1277       SDValue LoOps[2] = { InL, InL };
1278       Lo = DAG.getNode(ISD::ADDC, DL, VTList, LoOps, 2);
1279       SDValue HiOps[3] = { InH, InH, Lo.getValue(1) };
1280       Hi = DAG.getNode(ISD::ADDE, DL, VTList, HiOps, 3);
1281     } else {
1282       Lo = DAG.getNode(ISD::SHL, DL, NVT, InL, DAG.getConstant(Amt, ShTy));
1283       Hi = DAG.getNode(ISD::OR, DL, NVT,
1284                        DAG.getNode(ISD::SHL, DL, NVT, InH,
1285                                    DAG.getConstant(Amt, ShTy)),
1286                        DAG.getNode(ISD::SRL, DL, NVT, InL,
1287                                    DAG.getConstant(NVTBits-Amt, ShTy)));
1288     }
1289     return;
1290   }
1291
1292   if (N->getOpcode() == ISD::SRL) {
1293     if (Amt > VTBits) {
1294       Lo = DAG.getConstant(0, NVT);
1295       Hi = DAG.getConstant(0, NVT);
1296     } else if (Amt > NVTBits) {
1297       Lo = DAG.getNode(ISD::SRL, DL,
1298                        NVT, InH, DAG.getConstant(Amt-NVTBits,ShTy));
1299       Hi = DAG.getConstant(0, NVT);
1300     } else if (Amt == NVTBits) {
1301       Lo = InH;
1302       Hi = DAG.getConstant(0, NVT);
1303     } else {
1304       Lo = DAG.getNode(ISD::OR, DL, NVT,
1305                        DAG.getNode(ISD::SRL, DL, NVT, InL,
1306                                    DAG.getConstant(Amt, ShTy)),
1307                        DAG.getNode(ISD::SHL, DL, NVT, InH,
1308                                    DAG.getConstant(NVTBits-Amt, ShTy)));
1309       Hi = DAG.getNode(ISD::SRL, DL, NVT, InH, DAG.getConstant(Amt, ShTy));
1310     }
1311     return;
1312   }
1313
1314   assert(N->getOpcode() == ISD::SRA && "Unknown shift!");
1315   if (Amt > VTBits) {
1316     Hi = Lo = DAG.getNode(ISD::SRA, DL, NVT, InH,
1317                           DAG.getConstant(NVTBits-1, ShTy));
1318   } else if (Amt > NVTBits) {
1319     Lo = DAG.getNode(ISD::SRA, DL, NVT, InH,
1320                      DAG.getConstant(Amt-NVTBits, ShTy));
1321     Hi = DAG.getNode(ISD::SRA, DL, NVT, InH,
1322                      DAG.getConstant(NVTBits-1, ShTy));
1323   } else if (Amt == NVTBits) {
1324     Lo = InH;
1325     Hi = DAG.getNode(ISD::SRA, DL, NVT, InH,
1326                      DAG.getConstant(NVTBits-1, ShTy));
1327   } else {
1328     Lo = DAG.getNode(ISD::OR, DL, NVT,
1329                      DAG.getNode(ISD::SRL, DL, NVT, InL,
1330                                  DAG.getConstant(Amt, ShTy)),
1331                      DAG.getNode(ISD::SHL, DL, NVT, InH,
1332                                  DAG.getConstant(NVTBits-Amt, ShTy)));
1333     Hi = DAG.getNode(ISD::SRA, DL, NVT, InH, DAG.getConstant(Amt, ShTy));
1334   }
1335 }
1336
1337 /// ExpandShiftWithKnownAmountBit - Try to determine whether we can simplify
1338 /// this shift based on knowledge of the high bit of the shift amount.  If we
1339 /// can tell this, we know that it is >= 32 or < 32, without knowing the actual
1340 /// shift amount.
1341 bool DAGTypeLegalizer::
1342 ExpandShiftWithKnownAmountBit(SDNode *N, SDValue &Lo, SDValue &Hi) {
1343   SDValue Amt = N->getOperand(1);
1344   EVT NVT = TLI.getTypeToTransformTo(*DAG.getContext(), N->getValueType(0));
1345   EVT ShTy = Amt.getValueType();
1346   unsigned ShBits = ShTy.getScalarType().getSizeInBits();
1347   unsigned NVTBits = NVT.getScalarType().getSizeInBits();
1348   assert(isPowerOf2_32(NVTBits) &&
1349          "Expanded integer type size not a power of two!");
1350   DebugLoc dl = N->getDebugLoc();
1351
1352   APInt HighBitMask = APInt::getHighBitsSet(ShBits, ShBits - Log2_32(NVTBits));
1353   APInt KnownZero, KnownOne;
1354   DAG.ComputeMaskedBits(N->getOperand(1), HighBitMask, KnownZero, KnownOne);
1355
1356   // If we don't know anything about the high bits, exit.
1357   if (((KnownZero|KnownOne) & HighBitMask) == 0)
1358     return false;
1359
1360   // Get the incoming operand to be shifted.
1361   SDValue InL, InH;
1362   GetExpandedInteger(N->getOperand(0), InL, InH);
1363
1364   // If we know that any of the high bits of the shift amount are one, then we
1365   // can do this as a couple of simple shifts.
1366   if (KnownOne.intersects(HighBitMask)) {
1367     // Mask out the high bit, which we know is set.
1368     Amt = DAG.getNode(ISD::AND, dl, ShTy, Amt,
1369                       DAG.getConstant(~HighBitMask, ShTy));
1370
1371     switch (N->getOpcode()) {
1372     default: llvm_unreachable("Unknown shift");
1373     case ISD::SHL:
1374       Lo = DAG.getConstant(0, NVT);              // Low part is zero.
1375       Hi = DAG.getNode(ISD::SHL, dl, NVT, InL, Amt); // High part from Lo part.
1376       return true;
1377     case ISD::SRL:
1378       Hi = DAG.getConstant(0, NVT);              // Hi part is zero.
1379       Lo = DAG.getNode(ISD::SRL, dl, NVT, InH, Amt); // Lo part from Hi part.
1380       return true;
1381     case ISD::SRA:
1382       Hi = DAG.getNode(ISD::SRA, dl, NVT, InH,       // Sign extend high part.
1383                        DAG.getConstant(NVTBits-1, ShTy));
1384       Lo = DAG.getNode(ISD::SRA, dl, NVT, InH, Amt); // Lo part from Hi part.
1385       return true;
1386     }
1387   }
1388
1389 #if 0
1390   // FIXME: This code is broken for shifts with a zero amount!
1391   // If we know that all of the high bits of the shift amount are zero, then we
1392   // can do this as a couple of simple shifts.
1393   if ((KnownZero & HighBitMask) == HighBitMask) {
1394     // Compute 32-amt.
1395     SDValue Amt2 = DAG.getNode(ISD::SUB, ShTy,
1396                                  DAG.getConstant(NVTBits, ShTy),
1397                                  Amt);
1398     unsigned Op1, Op2;
1399     switch (N->getOpcode()) {
1400     default: llvm_unreachable("Unknown shift");
1401     case ISD::SHL:  Op1 = ISD::SHL; Op2 = ISD::SRL; break;
1402     case ISD::SRL:
1403     case ISD::SRA:  Op1 = ISD::SRL; Op2 = ISD::SHL; break;
1404     }
1405
1406     Lo = DAG.getNode(N->getOpcode(), NVT, InL, Amt);
1407     Hi = DAG.getNode(ISD::OR, NVT,
1408                      DAG.getNode(Op1, NVT, InH, Amt),
1409                      DAG.getNode(Op2, NVT, InL, Amt2));
1410     return true;
1411   }
1412 #endif
1413
1414   return false;
1415 }
1416
1417 /// ExpandShiftWithUnknownAmountBit - Fully general expansion of integer shift
1418 /// of any size.
1419 bool DAGTypeLegalizer::
1420 ExpandShiftWithUnknownAmountBit(SDNode *N, SDValue &Lo, SDValue &Hi) {
1421   SDValue Amt = N->getOperand(1);
1422   EVT NVT = TLI.getTypeToTransformTo(*DAG.getContext(), N->getValueType(0));
1423   EVT ShTy = Amt.getValueType();
1424   unsigned NVTBits = NVT.getSizeInBits();
1425   assert(isPowerOf2_32(NVTBits) &&
1426          "Expanded integer type size not a power of two!");
1427   DebugLoc dl = N->getDebugLoc();
1428
1429   // Get the incoming operand to be shifted.
1430   SDValue InL, InH;
1431   GetExpandedInteger(N->getOperand(0), InL, InH);
1432
1433   SDValue NVBitsNode = DAG.getConstant(NVTBits, ShTy);
1434   SDValue AmtExcess = DAG.getNode(ISD::SUB, dl, ShTy, Amt, NVBitsNode);
1435   SDValue AmtLack = DAG.getNode(ISD::SUB, dl, ShTy, NVBitsNode, Amt);
1436   SDValue isShort = DAG.getSetCC(dl, TLI.getSetCCResultType(ShTy),
1437                                  Amt, NVBitsNode, ISD::SETULT);
1438
1439   SDValue LoS, HiS, LoL, HiL;
1440   switch (N->getOpcode()) {
1441   default: llvm_unreachable("Unknown shift");
1442   case ISD::SHL:
1443     // Short: ShAmt < NVTBits
1444     LoS = DAG.getNode(ISD::SHL, dl, NVT, InL, Amt);
1445     HiS = DAG.getNode(ISD::OR, dl, NVT,
1446                       DAG.getNode(ISD::SHL, dl, NVT, InH, Amt),
1447     // FIXME: If Amt is zero, the following shift generates an undefined result
1448     // on some architectures.
1449                       DAG.getNode(ISD::SRL, dl, NVT, InL, AmtLack));
1450
1451     // Long: ShAmt >= NVTBits
1452     LoL = DAG.getConstant(0, NVT);                        // Lo part is zero.
1453     HiL = DAG.getNode(ISD::SHL, dl, NVT, InL, AmtExcess); // Hi from Lo part.
1454
1455     Lo = DAG.getNode(ISD::SELECT, dl, NVT, isShort, LoS, LoL);
1456     Hi = DAG.getNode(ISD::SELECT, dl, NVT, isShort, HiS, HiL);
1457     return true;
1458   case ISD::SRL:
1459     // Short: ShAmt < NVTBits
1460     HiS = DAG.getNode(ISD::SRL, dl, NVT, InH, Amt);
1461     LoS = DAG.getNode(ISD::OR, dl, NVT,
1462                       DAG.getNode(ISD::SRL, dl, NVT, InL, Amt),
1463     // FIXME: If Amt is zero, the following shift generates an undefined result
1464     // on some architectures.
1465                       DAG.getNode(ISD::SHL, dl, NVT, InH, AmtLack));
1466
1467     // Long: ShAmt >= NVTBits
1468     HiL = DAG.getConstant(0, NVT);                        // Hi part is zero.
1469     LoL = DAG.getNode(ISD::SRL, dl, NVT, InH, AmtExcess); // Lo from Hi part.
1470
1471     Lo = DAG.getNode(ISD::SELECT, dl, NVT, isShort, LoS, LoL);
1472     Hi = DAG.getNode(ISD::SELECT, dl, NVT, isShort, HiS, HiL);
1473     return true;
1474   case ISD::SRA:
1475     // Short: ShAmt < NVTBits
1476     HiS = DAG.getNode(ISD::SRA, dl, NVT, InH, Amt);
1477     LoS = DAG.getNode(ISD::OR, dl, NVT,
1478                       DAG.getNode(ISD::SRL, dl, NVT, InL, Amt),
1479     // FIXME: If Amt is zero, the following shift generates an undefined result
1480     // on some architectures.
1481                       DAG.getNode(ISD::SHL, dl, NVT, InH, AmtLack));
1482
1483     // Long: ShAmt >= NVTBits
1484     HiL = DAG.getNode(ISD::SRA, dl, NVT, InH,             // Sign of Hi part.
1485                       DAG.getConstant(NVTBits-1, ShTy));
1486     LoL = DAG.getNode(ISD::SRA, dl, NVT, InH, AmtExcess); // Lo from Hi part.
1487
1488     Lo = DAG.getNode(ISD::SELECT, dl, NVT, isShort, LoS, LoL);
1489     Hi = DAG.getNode(ISD::SELECT, dl, NVT, isShort, HiS, HiL);
1490     return true;
1491   }
1492
1493   return false;
1494 }
1495
1496 void DAGTypeLegalizer::ExpandIntRes_ADDSUB(SDNode *N,
1497                                            SDValue &Lo, SDValue &Hi) {
1498   DebugLoc dl = N->getDebugLoc();
1499   // Expand the subcomponents.
1500   SDValue LHSL, LHSH, RHSL, RHSH;
1501   GetExpandedInteger(N->getOperand(0), LHSL, LHSH);
1502   GetExpandedInteger(N->getOperand(1), RHSL, RHSH);
1503
1504   EVT NVT = LHSL.getValueType();
1505   SDValue LoOps[2] = { LHSL, RHSL };
1506   SDValue HiOps[3] = { LHSH, RHSH };
1507
1508   // Do not generate ADDC/ADDE or SUBC/SUBE if the target does not support
1509   // them.  TODO: Teach operation legalization how to expand unsupported
1510   // ADDC/ADDE/SUBC/SUBE.  The problem is that these operations generate
1511   // a carry of type MVT::Glue, but there doesn't seem to be any way to
1512   // generate a value of this type in the expanded code sequence.
1513   bool hasCarry =
1514     TLI.isOperationLegalOrCustom(N->getOpcode() == ISD::ADD ?
1515                                    ISD::ADDC : ISD::SUBC,
1516                                  TLI.getTypeToExpandTo(*DAG.getContext(), NVT));
1517
1518   if (hasCarry) {
1519     SDVTList VTList = DAG.getVTList(NVT, MVT::Glue);
1520     if (N->getOpcode() == ISD::ADD) {
1521       Lo = DAG.getNode(ISD::ADDC, dl, VTList, LoOps, 2);
1522       HiOps[2] = Lo.getValue(1);
1523       Hi = DAG.getNode(ISD::ADDE, dl, VTList, HiOps, 3);
1524     } else {
1525       Lo = DAG.getNode(ISD::SUBC, dl, VTList, LoOps, 2);
1526       HiOps[2] = Lo.getValue(1);
1527       Hi = DAG.getNode(ISD::SUBE, dl, VTList, HiOps, 3);
1528     }
1529     return;
1530   }
1531
1532   if (N->getOpcode() == ISD::ADD) {
1533     Lo = DAG.getNode(ISD::ADD, dl, NVT, LoOps, 2);
1534     Hi = DAG.getNode(ISD::ADD, dl, NVT, HiOps, 2);
1535     SDValue Cmp1 = DAG.getSetCC(dl, TLI.getSetCCResultType(NVT), Lo, LoOps[0],
1536                                 ISD::SETULT);
1537     SDValue Carry1 = DAG.getNode(ISD::SELECT, dl, NVT, Cmp1,
1538                                  DAG.getConstant(1, NVT),
1539                                  DAG.getConstant(0, NVT));
1540     SDValue Cmp2 = DAG.getSetCC(dl, TLI.getSetCCResultType(NVT), Lo, LoOps[1],
1541                                 ISD::SETULT);
1542     SDValue Carry2 = DAG.getNode(ISD::SELECT, dl, NVT, Cmp2,
1543                                  DAG.getConstant(1, NVT), Carry1);
1544     Hi = DAG.getNode(ISD::ADD, dl, NVT, Hi, Carry2);
1545   } else {
1546     Lo = DAG.getNode(ISD::SUB, dl, NVT, LoOps, 2);
1547     Hi = DAG.getNode(ISD::SUB, dl, NVT, HiOps, 2);
1548     SDValue Cmp =
1549       DAG.getSetCC(dl, TLI.getSetCCResultType(LoOps[0].getValueType()),
1550                    LoOps[0], LoOps[1], ISD::SETULT);
1551     SDValue Borrow = DAG.getNode(ISD::SELECT, dl, NVT, Cmp,
1552                                  DAG.getConstant(1, NVT),
1553                                  DAG.getConstant(0, NVT));
1554     Hi = DAG.getNode(ISD::SUB, dl, NVT, Hi, Borrow);
1555   }
1556 }
1557
1558 void DAGTypeLegalizer::ExpandIntRes_ADDSUBC(SDNode *N,
1559                                             SDValue &Lo, SDValue &Hi) {
1560   // Expand the subcomponents.
1561   SDValue LHSL, LHSH, RHSL, RHSH;
1562   DebugLoc dl = N->getDebugLoc();
1563   GetExpandedInteger(N->getOperand(0), LHSL, LHSH);
1564   GetExpandedInteger(N->getOperand(1), RHSL, RHSH);
1565   SDVTList VTList = DAG.getVTList(LHSL.getValueType(), MVT::Glue);
1566   SDValue LoOps[2] = { LHSL, RHSL };
1567   SDValue HiOps[3] = { LHSH, RHSH };
1568
1569   if (N->getOpcode() == ISD::ADDC) {
1570     Lo = DAG.getNode(ISD::ADDC, dl, VTList, LoOps, 2);
1571     HiOps[2] = Lo.getValue(1);
1572     Hi = DAG.getNode(ISD::ADDE, dl, VTList, HiOps, 3);
1573   } else {
1574     Lo = DAG.getNode(ISD::SUBC, dl, VTList, LoOps, 2);
1575     HiOps[2] = Lo.getValue(1);
1576     Hi = DAG.getNode(ISD::SUBE, dl, VTList, HiOps, 3);
1577   }
1578
1579   // Legalized the flag result - switch anything that used the old flag to
1580   // use the new one.
1581   ReplaceValueWith(SDValue(N, 1), Hi.getValue(1));
1582 }
1583
1584 void DAGTypeLegalizer::ExpandIntRes_ADDSUBE(SDNode *N,
1585                                             SDValue &Lo, SDValue &Hi) {
1586   // Expand the subcomponents.
1587   SDValue LHSL, LHSH, RHSL, RHSH;
1588   DebugLoc dl = N->getDebugLoc();
1589   GetExpandedInteger(N->getOperand(0), LHSL, LHSH);
1590   GetExpandedInteger(N->getOperand(1), RHSL, RHSH);
1591   SDVTList VTList = DAG.getVTList(LHSL.getValueType(), MVT::Glue);
1592   SDValue LoOps[3] = { LHSL, RHSL, N->getOperand(2) };
1593   SDValue HiOps[3] = { LHSH, RHSH };
1594
1595   Lo = DAG.getNode(N->getOpcode(), dl, VTList, LoOps, 3);
1596   HiOps[2] = Lo.getValue(1);
1597   Hi = DAG.getNode(N->getOpcode(), dl, VTList, HiOps, 3);
1598
1599   // Legalized the flag result - switch anything that used the old flag to
1600   // use the new one.
1601   ReplaceValueWith(SDValue(N, 1), Hi.getValue(1));
1602 }
1603
1604 void DAGTypeLegalizer::ExpandIntRes_MERGE_VALUES(SDNode *N, unsigned ResNo,
1605                                                  SDValue &Lo, SDValue &Hi) {
1606   SDValue Res = DisintegrateMERGE_VALUES(N, ResNo);
1607   SplitInteger(Res, Lo, Hi);
1608 }
1609
1610 void DAGTypeLegalizer::ExpandIntRes_ANY_EXTEND(SDNode *N,
1611                                                SDValue &Lo, SDValue &Hi) {
1612   EVT NVT = TLI.getTypeToTransformTo(*DAG.getContext(), N->getValueType(0));
1613   DebugLoc dl = N->getDebugLoc();
1614   SDValue Op = N->getOperand(0);
1615   if (Op.getValueType().bitsLE(NVT)) {
1616     // The low part is any extension of the input (which degenerates to a copy).
1617     Lo = DAG.getNode(ISD::ANY_EXTEND, dl, NVT, Op);
1618     Hi = DAG.getUNDEF(NVT);   // The high part is undefined.
1619   } else {
1620     // For example, extension of an i48 to an i64.  The operand type necessarily
1621     // promotes to the result type, so will end up being expanded too.
1622     assert(getTypeAction(Op.getValueType()) ==
1623            TargetLowering::TypePromoteInteger &&
1624            "Only know how to promote this result!");
1625     SDValue Res = GetPromotedInteger(Op);
1626     assert(Res.getValueType() == N->getValueType(0) &&
1627            "Operand over promoted?");
1628     // Split the promoted operand.  This will simplify when it is expanded.
1629     SplitInteger(Res, Lo, Hi);
1630   }
1631 }
1632
1633 void DAGTypeLegalizer::ExpandIntRes_AssertSext(SDNode *N,
1634                                                SDValue &Lo, SDValue &Hi) {
1635   DebugLoc dl = N->getDebugLoc();
1636   GetExpandedInteger(N->getOperand(0), Lo, Hi);
1637   EVT NVT = Lo.getValueType();
1638   EVT EVT = cast<VTSDNode>(N->getOperand(1))->getVT();
1639   unsigned NVTBits = NVT.getSizeInBits();
1640   unsigned EVTBits = EVT.getSizeInBits();
1641
1642   if (NVTBits < EVTBits) {
1643     Hi = DAG.getNode(ISD::AssertSext, dl, NVT, Hi,
1644                      DAG.getValueType(EVT::getIntegerVT(*DAG.getContext(),
1645                                                         EVTBits - NVTBits)));
1646   } else {
1647     Lo = DAG.getNode(ISD::AssertSext, dl, NVT, Lo, DAG.getValueType(EVT));
1648     // The high part replicates the sign bit of Lo, make it explicit.
1649     Hi = DAG.getNode(ISD::SRA, dl, NVT, Lo,
1650                      DAG.getConstant(NVTBits-1, TLI.getPointerTy()));
1651   }
1652 }
1653
1654 void DAGTypeLegalizer::ExpandIntRes_AssertZext(SDNode *N,
1655                                                SDValue &Lo, SDValue &Hi) {
1656   DebugLoc dl = N->getDebugLoc();
1657   GetExpandedInteger(N->getOperand(0), Lo, Hi);
1658   EVT NVT = Lo.getValueType();
1659   EVT EVT = cast<VTSDNode>(N->getOperand(1))->getVT();
1660   unsigned NVTBits = NVT.getSizeInBits();
1661   unsigned EVTBits = EVT.getSizeInBits();
1662
1663   if (NVTBits < EVTBits) {
1664     Hi = DAG.getNode(ISD::AssertZext, dl, NVT, Hi,
1665                      DAG.getValueType(EVT::getIntegerVT(*DAG.getContext(),
1666                                                         EVTBits - NVTBits)));
1667   } else {
1668     Lo = DAG.getNode(ISD::AssertZext, dl, NVT, Lo, DAG.getValueType(EVT));
1669     // The high part must be zero, make it explicit.
1670     Hi = DAG.getConstant(0, NVT);
1671   }
1672 }
1673
1674 void DAGTypeLegalizer::ExpandIntRes_BSWAP(SDNode *N,
1675                                           SDValue &Lo, SDValue &Hi) {
1676   DebugLoc dl = N->getDebugLoc();
1677   GetExpandedInteger(N->getOperand(0), Hi, Lo);  // Note swapped operands.
1678   Lo = DAG.getNode(ISD::BSWAP, dl, Lo.getValueType(), Lo);
1679   Hi = DAG.getNode(ISD::BSWAP, dl, Hi.getValueType(), Hi);
1680 }
1681
1682 void DAGTypeLegalizer::ExpandIntRes_Constant(SDNode *N,
1683                                              SDValue &Lo, SDValue &Hi) {
1684   EVT NVT = TLI.getTypeToTransformTo(*DAG.getContext(), N->getValueType(0));
1685   unsigned NBitWidth = NVT.getSizeInBits();
1686   const APInt &Cst = cast<ConstantSDNode>(N)->getAPIntValue();
1687   Lo = DAG.getConstant(Cst.trunc(NBitWidth), NVT);
1688   Hi = DAG.getConstant(Cst.lshr(NBitWidth).trunc(NBitWidth), NVT);
1689 }
1690
1691 void DAGTypeLegalizer::ExpandIntRes_CTLZ(SDNode *N,
1692                                          SDValue &Lo, SDValue &Hi) {
1693   DebugLoc dl = N->getDebugLoc();
1694   // ctlz (HiLo) -> Hi != 0 ? ctlz(Hi) : (ctlz(Lo)+32)
1695   GetExpandedInteger(N->getOperand(0), Lo, Hi);
1696   EVT NVT = Lo.getValueType();
1697
1698   SDValue HiNotZero = DAG.getSetCC(dl, TLI.getSetCCResultType(NVT), Hi,
1699                                    DAG.getConstant(0, NVT), ISD::SETNE);
1700
1701   SDValue LoLZ = DAG.getNode(ISD::CTLZ, dl, NVT, Lo);
1702   SDValue HiLZ = DAG.getNode(ISD::CTLZ, dl, NVT, Hi);
1703
1704   Lo = DAG.getNode(ISD::SELECT, dl, NVT, HiNotZero, HiLZ,
1705                    DAG.getNode(ISD::ADD, dl, NVT, LoLZ,
1706                                DAG.getConstant(NVT.getSizeInBits(), NVT)));
1707   Hi = DAG.getConstant(0, NVT);
1708 }
1709
1710 void DAGTypeLegalizer::ExpandIntRes_CTPOP(SDNode *N,
1711                                           SDValue &Lo, SDValue &Hi) {
1712   DebugLoc dl = N->getDebugLoc();
1713   // ctpop(HiLo) -> ctpop(Hi)+ctpop(Lo)
1714   GetExpandedInteger(N->getOperand(0), Lo, Hi);
1715   EVT NVT = Lo.getValueType();
1716   Lo = DAG.getNode(ISD::ADD, dl, NVT, DAG.getNode(ISD::CTPOP, dl, NVT, Lo),
1717                    DAG.getNode(ISD::CTPOP, dl, NVT, Hi));
1718   Hi = DAG.getConstant(0, NVT);
1719 }
1720
1721 void DAGTypeLegalizer::ExpandIntRes_CTTZ(SDNode *N,
1722                                          SDValue &Lo, SDValue &Hi) {
1723   DebugLoc dl = N->getDebugLoc();
1724   // cttz (HiLo) -> Lo != 0 ? cttz(Lo) : (cttz(Hi)+32)
1725   GetExpandedInteger(N->getOperand(0), Lo, Hi);
1726   EVT NVT = Lo.getValueType();
1727
1728   SDValue LoNotZero = DAG.getSetCC(dl, TLI.getSetCCResultType(NVT), Lo,
1729                                    DAG.getConstant(0, NVT), ISD::SETNE);
1730
1731   SDValue LoLZ = DAG.getNode(ISD::CTTZ, dl, NVT, Lo);
1732   SDValue HiLZ = DAG.getNode(ISD::CTTZ, dl, NVT, Hi);
1733
1734   Lo = DAG.getNode(ISD::SELECT, dl, NVT, LoNotZero, LoLZ,
1735                    DAG.getNode(ISD::ADD, dl, NVT, HiLZ,
1736                                DAG.getConstant(NVT.getSizeInBits(), NVT)));
1737   Hi = DAG.getConstant(0, NVT);
1738 }
1739
1740 void DAGTypeLegalizer::ExpandIntRes_FP_TO_SINT(SDNode *N, SDValue &Lo,
1741                                                SDValue &Hi) {
1742   DebugLoc dl = N->getDebugLoc();
1743   EVT VT = N->getValueType(0);
1744   SDValue Op = N->getOperand(0);
1745   RTLIB::Libcall LC = RTLIB::getFPTOSINT(Op.getValueType(), VT);
1746   assert(LC != RTLIB::UNKNOWN_LIBCALL && "Unexpected fp-to-sint conversion!");
1747   SplitInteger(MakeLibCall(LC, VT, &Op, 1, true/*irrelevant*/, dl), Lo, Hi);
1748 }
1749
1750 void DAGTypeLegalizer::ExpandIntRes_FP_TO_UINT(SDNode *N, SDValue &Lo,
1751                                                SDValue &Hi) {
1752   DebugLoc dl = N->getDebugLoc();
1753   EVT VT = N->getValueType(0);
1754   SDValue Op = N->getOperand(0);
1755   RTLIB::Libcall LC = RTLIB::getFPTOUINT(Op.getValueType(), VT);
1756   assert(LC != RTLIB::UNKNOWN_LIBCALL && "Unexpected fp-to-uint conversion!");
1757   SplitInteger(MakeLibCall(LC, VT, &Op, 1, false/*irrelevant*/, dl), Lo, Hi);
1758 }
1759
1760 void DAGTypeLegalizer::ExpandIntRes_LOAD(LoadSDNode *N,
1761                                          SDValue &Lo, SDValue &Hi) {
1762   if (ISD::isNormalLoad(N)) {
1763     ExpandRes_NormalLoad(N, Lo, Hi);
1764     return;
1765   }
1766
1767   assert(ISD::isUNINDEXEDLoad(N) && "Indexed load during type legalization!");
1768
1769   EVT VT = N->getValueType(0);
1770   EVT NVT = TLI.getTypeToTransformTo(*DAG.getContext(), VT);
1771   SDValue Ch  = N->getChain();
1772   SDValue Ptr = N->getBasePtr();
1773   ISD::LoadExtType ExtType = N->getExtensionType();
1774   unsigned Alignment = N->getAlignment();
1775   bool isVolatile = N->isVolatile();
1776   bool isNonTemporal = N->isNonTemporal();
1777   DebugLoc dl = N->getDebugLoc();
1778
1779   assert(NVT.isByteSized() && "Expanded type not byte sized!");
1780
1781   if (N->getMemoryVT().bitsLE(NVT)) {
1782     EVT MemVT = N->getMemoryVT();
1783
1784     Lo = DAG.getExtLoad(ExtType, dl, NVT, Ch, Ptr, N->getPointerInfo(),
1785                         MemVT, isVolatile, isNonTemporal, Alignment);
1786
1787     // Remember the chain.
1788     Ch = Lo.getValue(1);
1789
1790     if (ExtType == ISD::SEXTLOAD) {
1791       // The high part is obtained by SRA'ing all but one of the bits of the
1792       // lo part.
1793       unsigned LoSize = Lo.getValueType().getSizeInBits();
1794       Hi = DAG.getNode(ISD::SRA, dl, NVT, Lo,
1795                        DAG.getConstant(LoSize-1, TLI.getPointerTy()));
1796     } else if (ExtType == ISD::ZEXTLOAD) {
1797       // The high part is just a zero.
1798       Hi = DAG.getConstant(0, NVT);
1799     } else {
1800       assert(ExtType == ISD::EXTLOAD && "Unknown extload!");
1801       // The high part is undefined.
1802       Hi = DAG.getUNDEF(NVT);
1803     }
1804   } else if (TLI.isLittleEndian()) {
1805     // Little-endian - low bits are at low addresses.
1806     Lo = DAG.getLoad(NVT, dl, Ch, Ptr, N->getPointerInfo(),
1807                      isVolatile, isNonTemporal, Alignment);
1808
1809     unsigned ExcessBits =
1810       N->getMemoryVT().getSizeInBits() - NVT.getSizeInBits();
1811     EVT NEVT = EVT::getIntegerVT(*DAG.getContext(), ExcessBits);
1812
1813     // Increment the pointer to the other half.
1814     unsigned IncrementSize = NVT.getSizeInBits()/8;
1815     Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr,
1816                       DAG.getIntPtrConstant(IncrementSize));
1817     Hi = DAG.getExtLoad(ExtType, dl, NVT, Ch, Ptr,
1818                         N->getPointerInfo().getWithOffset(IncrementSize), NEVT,
1819                         isVolatile, isNonTemporal,
1820                         MinAlign(Alignment, IncrementSize));
1821
1822     // Build a factor node to remember that this load is independent of the
1823     // other one.
1824     Ch = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Lo.getValue(1),
1825                      Hi.getValue(1));
1826   } else {
1827     // Big-endian - high bits are at low addresses.  Favor aligned loads at
1828     // the cost of some bit-fiddling.
1829     EVT MemVT = N->getMemoryVT();
1830     unsigned EBytes = MemVT.getStoreSize();
1831     unsigned IncrementSize = NVT.getSizeInBits()/8;
1832     unsigned ExcessBits = (EBytes - IncrementSize)*8;
1833
1834     // Load both the high bits and maybe some of the low bits.
1835     Hi = DAG.getExtLoad(ExtType, dl, NVT, Ch, Ptr, N->getPointerInfo(),
1836                         EVT::getIntegerVT(*DAG.getContext(),
1837                                           MemVT.getSizeInBits() - ExcessBits),
1838                         isVolatile, isNonTemporal, Alignment);
1839
1840     // Increment the pointer to the other half.
1841     Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr,
1842                       DAG.getIntPtrConstant(IncrementSize));
1843     // Load the rest of the low bits.
1844     Lo = DAG.getExtLoad(ISD::ZEXTLOAD, dl, NVT, Ch, Ptr,
1845                         N->getPointerInfo().getWithOffset(IncrementSize),
1846                         EVT::getIntegerVT(*DAG.getContext(), ExcessBits),
1847                         isVolatile, isNonTemporal,
1848                         MinAlign(Alignment, IncrementSize));
1849
1850     // Build a factor node to remember that this load is independent of the
1851     // other one.
1852     Ch = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Lo.getValue(1),
1853                      Hi.getValue(1));
1854
1855     if (ExcessBits < NVT.getSizeInBits()) {
1856       // Transfer low bits from the bottom of Hi to the top of Lo.
1857       Lo = DAG.getNode(ISD::OR, dl, NVT, Lo,
1858                        DAG.getNode(ISD::SHL, dl, NVT, Hi,
1859                                    DAG.getConstant(ExcessBits,
1860                                                    TLI.getPointerTy())));
1861       // Move high bits to the right position in Hi.
1862       Hi = DAG.getNode(ExtType == ISD::SEXTLOAD ? ISD::SRA : ISD::SRL, dl,
1863                        NVT, Hi,
1864                        DAG.getConstant(NVT.getSizeInBits() - ExcessBits,
1865                                        TLI.getPointerTy()));
1866     }
1867   }
1868
1869   // Legalized the chain result - switch anything that used the old chain to
1870   // use the new one.
1871   ReplaceValueWith(SDValue(N, 1), Ch);
1872 }
1873
1874 void DAGTypeLegalizer::ExpandIntRes_Logical(SDNode *N,
1875                                             SDValue &Lo, SDValue &Hi) {
1876   DebugLoc dl = N->getDebugLoc();
1877   SDValue LL, LH, RL, RH;
1878   GetExpandedInteger(N->getOperand(0), LL, LH);
1879   GetExpandedInteger(N->getOperand(1), RL, RH);
1880   Lo = DAG.getNode(N->getOpcode(), dl, LL.getValueType(), LL, RL);
1881   Hi = DAG.getNode(N->getOpcode(), dl, LL.getValueType(), LH, RH);
1882 }
1883
1884 void DAGTypeLegalizer::ExpandIntRes_MUL(SDNode *N,
1885                                         SDValue &Lo, SDValue &Hi) {
1886   EVT VT = N->getValueType(0);
1887   EVT NVT = TLI.getTypeToTransformTo(*DAG.getContext(), VT);
1888   DebugLoc dl = N->getDebugLoc();
1889
1890   bool HasMULHS = TLI.isOperationLegalOrCustom(ISD::MULHS, NVT);
1891   bool HasMULHU = TLI.isOperationLegalOrCustom(ISD::MULHU, NVT);
1892   bool HasSMUL_LOHI = TLI.isOperationLegalOrCustom(ISD::SMUL_LOHI, NVT);
1893   bool HasUMUL_LOHI = TLI.isOperationLegalOrCustom(ISD::UMUL_LOHI, NVT);
1894   if (HasMULHU || HasMULHS || HasUMUL_LOHI || HasSMUL_LOHI) {
1895     SDValue LL, LH, RL, RH;
1896     GetExpandedInteger(N->getOperand(0), LL, LH);
1897     GetExpandedInteger(N->getOperand(1), RL, RH);
1898     unsigned OuterBitSize = VT.getSizeInBits();
1899     unsigned InnerBitSize = NVT.getSizeInBits();
1900     unsigned LHSSB = DAG.ComputeNumSignBits(N->getOperand(0));
1901     unsigned RHSSB = DAG.ComputeNumSignBits(N->getOperand(1));
1902
1903     APInt HighMask = APInt::getHighBitsSet(OuterBitSize, InnerBitSize);
1904     if (DAG.MaskedValueIsZero(N->getOperand(0), HighMask) &&
1905         DAG.MaskedValueIsZero(N->getOperand(1), HighMask)) {
1906       // The inputs are both zero-extended.
1907       if (HasUMUL_LOHI) {
1908         // We can emit a umul_lohi.
1909         Lo = DAG.getNode(ISD::UMUL_LOHI, dl, DAG.getVTList(NVT, NVT), LL, RL);
1910         Hi = SDValue(Lo.getNode(), 1);
1911         return;
1912       }
1913       if (HasMULHU) {
1914         // We can emit a mulhu+mul.
1915         Lo = DAG.getNode(ISD::MUL, dl, NVT, LL, RL);
1916         Hi = DAG.getNode(ISD::MULHU, dl, NVT, LL, RL);
1917         return;
1918       }
1919     }
1920     if (LHSSB > InnerBitSize && RHSSB > InnerBitSize) {
1921       // The input values are both sign-extended.
1922       if (HasSMUL_LOHI) {
1923         // We can emit a smul_lohi.
1924         Lo = DAG.getNode(ISD::SMUL_LOHI, dl, DAG.getVTList(NVT, NVT), LL, RL);
1925         Hi = SDValue(Lo.getNode(), 1);
1926         return;
1927       }
1928       if (HasMULHS) {
1929         // We can emit a mulhs+mul.
1930         Lo = DAG.getNode(ISD::MUL, dl, NVT, LL, RL);
1931         Hi = DAG.getNode(ISD::MULHS, dl, NVT, LL, RL);
1932         return;
1933       }
1934     }
1935     if (HasUMUL_LOHI) {
1936       // Lo,Hi = umul LHS, RHS.
1937       SDValue UMulLOHI = DAG.getNode(ISD::UMUL_LOHI, dl,
1938                                        DAG.getVTList(NVT, NVT), LL, RL);
1939       Lo = UMulLOHI;
1940       Hi = UMulLOHI.getValue(1);
1941       RH = DAG.getNode(ISD::MUL, dl, NVT, LL, RH);
1942       LH = DAG.getNode(ISD::MUL, dl, NVT, LH, RL);
1943       Hi = DAG.getNode(ISD::ADD, dl, NVT, Hi, RH);
1944       Hi = DAG.getNode(ISD::ADD, dl, NVT, Hi, LH);
1945       return;
1946     }
1947     if (HasMULHU) {
1948       Lo = DAG.getNode(ISD::MUL, dl, NVT, LL, RL);
1949       Hi = DAG.getNode(ISD::MULHU, dl, NVT, LL, RL);
1950       RH = DAG.getNode(ISD::MUL, dl, NVT, LL, RH);
1951       LH = DAG.getNode(ISD::MUL, dl, NVT, LH, RL);
1952       Hi = DAG.getNode(ISD::ADD, dl, NVT, Hi, RH);
1953       Hi = DAG.getNode(ISD::ADD, dl, NVT, Hi, LH);
1954       return;
1955     }
1956   }
1957
1958   // If nothing else, we can make a libcall.
1959   RTLIB::Libcall LC = RTLIB::UNKNOWN_LIBCALL;
1960   if (VT == MVT::i16)
1961     LC = RTLIB::MUL_I16;
1962   else if (VT == MVT::i32)
1963     LC = RTLIB::MUL_I32;
1964   else if (VT == MVT::i64)
1965     LC = RTLIB::MUL_I64;
1966   else if (VT == MVT::i128)
1967     LC = RTLIB::MUL_I128;
1968   assert(LC != RTLIB::UNKNOWN_LIBCALL && "Unsupported MUL!");
1969
1970   SDValue Ops[2] = { N->getOperand(0), N->getOperand(1) };
1971   SplitInteger(MakeLibCall(LC, VT, Ops, 2, true/*irrelevant*/, dl), Lo, Hi);
1972 }
1973
1974 void DAGTypeLegalizer::ExpandIntRes_SADDSUBO(SDNode *Node,
1975                                              SDValue &Lo, SDValue &Hi) {
1976   SDValue LHS = Node->getOperand(0);
1977   SDValue RHS = Node->getOperand(1);
1978   DebugLoc dl = Node->getDebugLoc();
1979
1980   // Expand the result by simply replacing it with the equivalent
1981   // non-overflow-checking operation.
1982   SDValue Sum = DAG.getNode(Node->getOpcode() == ISD::SADDO ?
1983                             ISD::ADD : ISD::SUB, dl, LHS.getValueType(),
1984                             LHS, RHS);
1985   SplitInteger(Sum, Lo, Hi);
1986
1987   // Compute the overflow.
1988   //
1989   //   LHSSign -> LHS >= 0
1990   //   RHSSign -> RHS >= 0
1991   //   SumSign -> Sum >= 0
1992   //
1993   //   Add:
1994   //   Overflow -> (LHSSign == RHSSign) && (LHSSign != SumSign)
1995   //   Sub:
1996   //   Overflow -> (LHSSign != RHSSign) && (LHSSign != SumSign)
1997   //
1998   EVT OType = Node->getValueType(1);
1999   SDValue Zero = DAG.getConstant(0, LHS.getValueType());
2000
2001   SDValue LHSSign = DAG.getSetCC(dl, OType, LHS, Zero, ISD::SETGE);
2002   SDValue RHSSign = DAG.getSetCC(dl, OType, RHS, Zero, ISD::SETGE);
2003   SDValue SignsMatch = DAG.getSetCC(dl, OType, LHSSign, RHSSign,
2004                                     Node->getOpcode() == ISD::SADDO ?
2005                                     ISD::SETEQ : ISD::SETNE);
2006
2007   SDValue SumSign = DAG.getSetCC(dl, OType, Sum, Zero, ISD::SETGE);
2008   SDValue SumSignNE = DAG.getSetCC(dl, OType, LHSSign, SumSign, ISD::SETNE);
2009
2010   SDValue Cmp = DAG.getNode(ISD::AND, dl, OType, SignsMatch, SumSignNE);
2011
2012   // Use the calculated overflow everywhere.
2013   ReplaceValueWith(SDValue(Node, 1), Cmp);
2014 }
2015
2016 void DAGTypeLegalizer::ExpandIntRes_SDIV(SDNode *N,
2017                                          SDValue &Lo, SDValue &Hi) {
2018   EVT VT = N->getValueType(0);
2019   DebugLoc dl = N->getDebugLoc();
2020
2021   RTLIB::Libcall LC = RTLIB::UNKNOWN_LIBCALL;
2022   if (VT == MVT::i16)
2023     LC = RTLIB::SDIV_I16;
2024   else if (VT == MVT::i32)
2025     LC = RTLIB::SDIV_I32;
2026   else if (VT == MVT::i64)
2027     LC = RTLIB::SDIV_I64;
2028   else if (VT == MVT::i128)
2029     LC = RTLIB::SDIV_I128;
2030   assert(LC != RTLIB::UNKNOWN_LIBCALL && "Unsupported SDIV!");
2031
2032   SDValue Ops[2] = { N->getOperand(0), N->getOperand(1) };
2033   SplitInteger(MakeLibCall(LC, VT, Ops, 2, true, dl), Lo, Hi);
2034 }
2035
2036 void DAGTypeLegalizer::ExpandIntRes_Shift(SDNode *N,
2037                                           SDValue &Lo, SDValue &Hi) {
2038   EVT VT = N->getValueType(0);
2039   DebugLoc dl = N->getDebugLoc();
2040
2041   // If we can emit an efficient shift operation, do so now.  Check to see if
2042   // the RHS is a constant.
2043   if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N->getOperand(1)))
2044     return ExpandShiftByConstant(N, CN->getZExtValue(), Lo, Hi);
2045
2046   // If we can determine that the high bit of the shift is zero or one, even if
2047   // the low bits are variable, emit this shift in an optimized form.
2048   if (ExpandShiftWithKnownAmountBit(N, Lo, Hi))
2049     return;
2050
2051   // If this target supports shift_PARTS, use it.  First, map to the _PARTS opc.
2052   unsigned PartsOpc;
2053   if (N->getOpcode() == ISD::SHL) {
2054     PartsOpc = ISD::SHL_PARTS;
2055   } else if (N->getOpcode() == ISD::SRL) {
2056     PartsOpc = ISD::SRL_PARTS;
2057   } else {
2058     assert(N->getOpcode() == ISD::SRA && "Unknown shift!");
2059     PartsOpc = ISD::SRA_PARTS;
2060   }
2061
2062   // Next check to see if the target supports this SHL_PARTS operation or if it
2063   // will custom expand it.
2064   EVT NVT = TLI.getTypeToTransformTo(*DAG.getContext(), VT);
2065   TargetLowering::LegalizeAction Action = TLI.getOperationAction(PartsOpc, NVT);
2066   if ((Action == TargetLowering::Legal && TLI.isTypeLegal(NVT)) ||
2067       Action == TargetLowering::Custom) {
2068     // Expand the subcomponents.
2069     SDValue LHSL, LHSH;
2070     GetExpandedInteger(N->getOperand(0), LHSL, LHSH);
2071
2072     SDValue Ops[] = { LHSL, LHSH, N->getOperand(1) };
2073     EVT VT = LHSL.getValueType();
2074     Lo = DAG.getNode(PartsOpc, dl, DAG.getVTList(VT, VT), Ops, 3);
2075     Hi = Lo.getValue(1);
2076     return;
2077   }
2078
2079   // Otherwise, emit a libcall.
2080   RTLIB::Libcall LC = RTLIB::UNKNOWN_LIBCALL;
2081   bool isSigned;
2082   if (N->getOpcode() == ISD::SHL) {
2083     isSigned = false; /*sign irrelevant*/
2084     if (VT == MVT::i16)
2085       LC = RTLIB::SHL_I16;
2086     else if (VT == MVT::i32)
2087       LC = RTLIB::SHL_I32;
2088     else if (VT == MVT::i64)
2089       LC = RTLIB::SHL_I64;
2090     else if (VT == MVT::i128)
2091       LC = RTLIB::SHL_I128;
2092   } else if (N->getOpcode() == ISD::SRL) {
2093     isSigned = false;
2094     if (VT == MVT::i16)
2095       LC = RTLIB::SRL_I16;
2096     else if (VT == MVT::i32)
2097       LC = RTLIB::SRL_I32;
2098     else if (VT == MVT::i64)
2099       LC = RTLIB::SRL_I64;
2100     else if (VT == MVT::i128)
2101       LC = RTLIB::SRL_I128;
2102   } else {
2103     assert(N->getOpcode() == ISD::SRA && "Unknown shift!");
2104     isSigned = true;
2105     if (VT == MVT::i16)
2106       LC = RTLIB::SRA_I16;
2107     else if (VT == MVT::i32)
2108       LC = RTLIB::SRA_I32;
2109     else if (VT == MVT::i64)
2110       LC = RTLIB::SRA_I64;
2111     else if (VT == MVT::i128)
2112       LC = RTLIB::SRA_I128;
2113   }
2114
2115   if (LC != RTLIB::UNKNOWN_LIBCALL && TLI.getLibcallName(LC)) {
2116     SDValue Ops[2] = { N->getOperand(0), N->getOperand(1) };
2117     SplitInteger(MakeLibCall(LC, VT, Ops, 2, isSigned, dl), Lo, Hi);
2118     return;
2119   }
2120
2121   if (!ExpandShiftWithUnknownAmountBit(N, Lo, Hi))
2122     llvm_unreachable("Unsupported shift!");
2123 }
2124
2125 void DAGTypeLegalizer::ExpandIntRes_SIGN_EXTEND(SDNode *N,
2126                                                 SDValue &Lo, SDValue &Hi) {
2127   EVT NVT = TLI.getTypeToTransformTo(*DAG.getContext(), N->getValueType(0));
2128   DebugLoc dl = N->getDebugLoc();
2129   SDValue Op = N->getOperand(0);
2130   if (Op.getValueType().bitsLE(NVT)) {
2131     // The low part is sign extension of the input (degenerates to a copy).
2132     Lo = DAG.getNode(ISD::SIGN_EXTEND, dl, NVT, N->getOperand(0));
2133     // The high part is obtained by SRA'ing all but one of the bits of low part.
2134     unsigned LoSize = NVT.getSizeInBits();
2135     Hi = DAG.getNode(ISD::SRA, dl, NVT, Lo,
2136                      DAG.getConstant(LoSize-1, TLI.getPointerTy()));
2137   } else {
2138     // For example, extension of an i48 to an i64.  The operand type necessarily
2139     // promotes to the result type, so will end up being expanded too.
2140     assert(getTypeAction(Op.getValueType()) ==
2141            TargetLowering::TypePromoteInteger &&
2142            "Only know how to promote this result!");
2143     SDValue Res = GetPromotedInteger(Op);
2144     assert(Res.getValueType() == N->getValueType(0) &&
2145            "Operand over promoted?");
2146     // Split the promoted operand.  This will simplify when it is expanded.
2147     SplitInteger(Res, Lo, Hi);
2148     unsigned ExcessBits =
2149       Op.getValueType().getSizeInBits() - NVT.getSizeInBits();
2150     Hi = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, Hi.getValueType(), Hi,
2151                      DAG.getValueType(EVT::getIntegerVT(*DAG.getContext(),
2152                                                         ExcessBits)));
2153   }
2154 }
2155
2156 void DAGTypeLegalizer::
2157 ExpandIntRes_SIGN_EXTEND_INREG(SDNode *N, SDValue &Lo, SDValue &Hi) {
2158   DebugLoc dl = N->getDebugLoc();
2159   GetExpandedInteger(N->getOperand(0), Lo, Hi);
2160   EVT EVT = cast<VTSDNode>(N->getOperand(1))->getVT();
2161
2162   if (EVT.bitsLE(Lo.getValueType())) {
2163     // sext_inreg the low part if needed.
2164     Lo = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, Lo.getValueType(), Lo,
2165                      N->getOperand(1));
2166
2167     // The high part gets the sign extension from the lo-part.  This handles
2168     // things like sextinreg V:i64 from i8.
2169     Hi = DAG.getNode(ISD::SRA, dl, Hi.getValueType(), Lo,
2170                      DAG.getConstant(Hi.getValueType().getSizeInBits()-1,
2171                                      TLI.getPointerTy()));
2172   } else {
2173     // For example, extension of an i48 to an i64.  Leave the low part alone,
2174     // sext_inreg the high part.
2175     unsigned ExcessBits =
2176       EVT.getSizeInBits() - Lo.getValueType().getSizeInBits();
2177     Hi = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, Hi.getValueType(), Hi,
2178                      DAG.getValueType(EVT::getIntegerVT(*DAG.getContext(),
2179                                                         ExcessBits)));
2180   }
2181 }
2182
2183 void DAGTypeLegalizer::ExpandIntRes_SREM(SDNode *N,
2184                                          SDValue &Lo, SDValue &Hi) {
2185   EVT VT = N->getValueType(0);
2186   DebugLoc dl = N->getDebugLoc();
2187
2188   RTLIB::Libcall LC = RTLIB::UNKNOWN_LIBCALL;
2189   if (VT == MVT::i16)
2190     LC = RTLIB::SREM_I16;
2191   else if (VT == MVT::i32)
2192     LC = RTLIB::SREM_I32;
2193   else if (VT == MVT::i64)
2194     LC = RTLIB::SREM_I64;
2195   else if (VT == MVT::i128)
2196     LC = RTLIB::SREM_I128;
2197   assert(LC != RTLIB::UNKNOWN_LIBCALL && "Unsupported SREM!");
2198
2199   SDValue Ops[2] = { N->getOperand(0), N->getOperand(1) };
2200   SplitInteger(MakeLibCall(LC, VT, Ops, 2, true, dl), Lo, Hi);
2201 }
2202
2203 void DAGTypeLegalizer::ExpandIntRes_TRUNCATE(SDNode *N,
2204                                              SDValue &Lo, SDValue &Hi) {
2205   EVT NVT = TLI.getTypeToTransformTo(*DAG.getContext(), N->getValueType(0));
2206   DebugLoc dl = N->getDebugLoc();
2207   Lo = DAG.getNode(ISD::TRUNCATE, dl, NVT, N->getOperand(0));
2208   Hi = DAG.getNode(ISD::SRL, dl,
2209                    N->getOperand(0).getValueType(), N->getOperand(0),
2210                    DAG.getConstant(NVT.getSizeInBits(), TLI.getPointerTy()));
2211   Hi = DAG.getNode(ISD::TRUNCATE, dl, NVT, Hi);
2212 }
2213
2214 void DAGTypeLegalizer::ExpandIntRes_UADDSUBO(SDNode *N,
2215                                              SDValue &Lo, SDValue &Hi) {
2216   SDValue LHS = N->getOperand(0);
2217   SDValue RHS = N->getOperand(1);
2218   DebugLoc dl = N->getDebugLoc();
2219
2220   // Expand the result by simply replacing it with the equivalent
2221   // non-overflow-checking operation.
2222   SDValue Sum = DAG.getNode(N->getOpcode() == ISD::UADDO ?
2223                             ISD::ADD : ISD::SUB, dl, LHS.getValueType(),
2224                             LHS, RHS);
2225   SplitInteger(Sum, Lo, Hi);
2226
2227   // Calculate the overflow: addition overflows iff a + b < a, and subtraction
2228   // overflows iff a - b > a.
2229   SDValue Ofl = DAG.getSetCC(dl, N->getValueType(1), Sum, LHS,
2230                              N->getOpcode () == ISD::UADDO ?
2231                              ISD::SETULT : ISD::SETUGT);
2232
2233   // Use the calculated overflow everywhere.
2234   ReplaceValueWith(SDValue(N, 1), Ofl);
2235 }
2236
2237 void DAGTypeLegalizer::ExpandIntRes_XMULO(SDNode *N,
2238                                           SDValue &Lo, SDValue &Hi) {
2239   EVT VT = N->getValueType(0);
2240   Type *RetTy = VT.getTypeForEVT(*DAG.getContext());
2241   EVT PtrVT = TLI.getPointerTy();
2242   Type *PtrTy = PtrVT.getTypeForEVT(*DAG.getContext());
2243   DebugLoc dl = N->getDebugLoc();
2244
2245   // A divide for UMULO should be faster than a function call.
2246   if (N->getOpcode() == ISD::UMULO) {
2247     SDValue LHS = N->getOperand(0), RHS = N->getOperand(1);
2248     DebugLoc DL = N->getDebugLoc();
2249
2250     SDValue MUL = DAG.getNode(ISD::MUL, DL, LHS.getValueType(), LHS, RHS);
2251     SplitInteger(MUL, Lo, Hi);
2252
2253     // A divide for UMULO will be faster than a function call. Select to
2254     // make sure we aren't using 0.
2255     SDValue isZero = DAG.getSetCC(dl, TLI.getSetCCResultType(VT),
2256                                   RHS, DAG.getConstant(0, VT), ISD::SETNE);
2257     SDValue NotZero = DAG.getNode(ISD::SELECT, dl, VT, isZero,
2258                                   DAG.getConstant(1, VT), RHS);
2259     SDValue DIV = DAG.getNode(ISD::UDIV, DL, LHS.getValueType(), MUL, NotZero);
2260     SDValue Overflow;
2261     Overflow = DAG.getSetCC(DL, N->getValueType(1), DIV, LHS, ISD::SETNE);
2262     ReplaceValueWith(SDValue(N, 1), Overflow);
2263     return;
2264   }
2265
2266   // Replace this with a libcall that will check overflow.
2267   RTLIB::Libcall LC = RTLIB::UNKNOWN_LIBCALL;
2268   if (VT == MVT::i32)
2269     LC = RTLIB::MULO_I32;
2270   else if (VT == MVT::i64)
2271     LC = RTLIB::MULO_I64;
2272   else if (VT == MVT::i128)
2273     LC = RTLIB::MULO_I128;
2274   assert(LC != RTLIB::UNKNOWN_LIBCALL && "Unsupported XMULO!");
2275
2276   SDValue Temp = DAG.CreateStackTemporary(PtrVT);
2277   // Temporary for the overflow value, default it to zero.
2278   SDValue Chain = DAG.getStore(DAG.getEntryNode(), dl,
2279                                DAG.getConstant(0, PtrVT), Temp,
2280                                MachinePointerInfo(), false, false, 0);
2281
2282   TargetLowering::ArgListTy Args;
2283   TargetLowering::ArgListEntry Entry;
2284   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
2285     EVT ArgVT = N->getOperand(i).getValueType();
2286     Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
2287     Entry.Node = N->getOperand(i);
2288     Entry.Ty = ArgTy;
2289     Entry.isSExt = true;
2290     Entry.isZExt = false;
2291     Args.push_back(Entry);
2292   }
2293
2294   // Also pass the address of the overflow check.
2295   Entry.Node = Temp;
2296   Entry.Ty = PtrTy->getPointerTo();
2297   Entry.isSExt = true;
2298   Entry.isZExt = false;
2299   Args.push_back(Entry);
2300
2301   SDValue Func = DAG.getExternalSymbol(TLI.getLibcallName(LC), PtrVT);
2302   std::pair<SDValue, SDValue> CallInfo =
2303     TLI.LowerCallTo(Chain, RetTy, true, false, false, false,
2304                     0, TLI.getLibcallCallingConv(LC), false,
2305                     true, Func, Args, DAG, dl);
2306
2307   SplitInteger(CallInfo.first, Lo, Hi);
2308   SDValue Temp2 = DAG.getLoad(PtrVT, dl, CallInfo.second, Temp,
2309                               MachinePointerInfo(), false, false, 0);
2310   SDValue Ofl = DAG.getSetCC(dl, N->getValueType(1), Temp2,
2311                              DAG.getConstant(0, PtrVT),
2312                              ISD::SETNE);
2313   // Use the overflow from the libcall everywhere.
2314   ReplaceValueWith(SDValue(N, 1), Ofl);
2315 }
2316
2317 void DAGTypeLegalizer::ExpandIntRes_UDIV(SDNode *N,
2318                                          SDValue &Lo, SDValue &Hi) {
2319   EVT VT = N->getValueType(0);
2320   DebugLoc dl = N->getDebugLoc();
2321
2322   RTLIB::Libcall LC = RTLIB::UNKNOWN_LIBCALL;
2323   if (VT == MVT::i16)
2324     LC = RTLIB::UDIV_I16;
2325   else if (VT == MVT::i32)
2326     LC = RTLIB::UDIV_I32;
2327   else if (VT == MVT::i64)
2328     LC = RTLIB::UDIV_I64;
2329   else if (VT == MVT::i128)
2330     LC = RTLIB::UDIV_I128;
2331   assert(LC != RTLIB::UNKNOWN_LIBCALL && "Unsupported UDIV!");
2332
2333   SDValue Ops[2] = { N->getOperand(0), N->getOperand(1) };
2334   SplitInteger(MakeLibCall(LC, VT, Ops, 2, false, dl), Lo, Hi);
2335 }
2336
2337 void DAGTypeLegalizer::ExpandIntRes_UREM(SDNode *N,
2338                                          SDValue &Lo, SDValue &Hi) {
2339   EVT VT = N->getValueType(0);
2340   DebugLoc dl = N->getDebugLoc();
2341
2342   RTLIB::Libcall LC = RTLIB::UNKNOWN_LIBCALL;
2343   if (VT == MVT::i16)
2344     LC = RTLIB::UREM_I16;
2345   else if (VT == MVT::i32)
2346     LC = RTLIB::UREM_I32;
2347   else if (VT == MVT::i64)
2348     LC = RTLIB::UREM_I64;
2349   else if (VT == MVT::i128)
2350     LC = RTLIB::UREM_I128;
2351   assert(LC != RTLIB::UNKNOWN_LIBCALL && "Unsupported UREM!");
2352
2353   SDValue Ops[2] = { N->getOperand(0), N->getOperand(1) };
2354   SplitInteger(MakeLibCall(LC, VT, Ops, 2, false, dl), Lo, Hi);
2355 }
2356
2357 void DAGTypeLegalizer::ExpandIntRes_ZERO_EXTEND(SDNode *N,
2358                                                 SDValue &Lo, SDValue &Hi) {
2359   EVT NVT = TLI.getTypeToTransformTo(*DAG.getContext(), N->getValueType(0));
2360   DebugLoc dl = N->getDebugLoc();
2361   SDValue Op = N->getOperand(0);
2362   if (Op.getValueType().bitsLE(NVT)) {
2363     // The low part is zero extension of the input (degenerates to a copy).
2364     Lo = DAG.getNode(ISD::ZERO_EXTEND, dl, NVT, N->getOperand(0));
2365     Hi = DAG.getConstant(0, NVT);   // The high part is just a zero.
2366   } else {
2367     // For example, extension of an i48 to an i64.  The operand type necessarily
2368     // promotes to the result type, so will end up being expanded too.
2369     assert(getTypeAction(Op.getValueType()) ==
2370            TargetLowering::TypePromoteInteger &&
2371            "Only know how to promote this result!");
2372     SDValue Res = GetPromotedInteger(Op);
2373     assert(Res.getValueType() == N->getValueType(0) &&
2374            "Operand over promoted?");
2375     // Split the promoted operand.  This will simplify when it is expanded.
2376     SplitInteger(Res, Lo, Hi);
2377     unsigned ExcessBits =
2378       Op.getValueType().getSizeInBits() - NVT.getSizeInBits();
2379     Hi = DAG.getZeroExtendInReg(Hi, dl,
2380                                 EVT::getIntegerVT(*DAG.getContext(),
2381                                                   ExcessBits));
2382   }
2383 }
2384
2385 void DAGTypeLegalizer::ExpandIntRes_ATOMIC_LOAD(SDNode *N,
2386                                                 SDValue &Lo, SDValue &Hi) {
2387   DebugLoc dl = N->getDebugLoc();
2388   EVT VT = cast<AtomicSDNode>(N)->getMemoryVT();
2389   SDValue Zero = DAG.getConstant(0, VT);
2390   SDValue Swap = DAG.getAtomic(ISD::ATOMIC_CMP_SWAP, dl, VT,
2391                                N->getOperand(0),
2392                                N->getOperand(1), Zero, Zero,
2393                                cast<AtomicSDNode>(N)->getMemOperand(),
2394                                cast<AtomicSDNode>(N)->getOrdering(),
2395                                cast<AtomicSDNode>(N)->getSynchScope());
2396   ReplaceValueWith(SDValue(N, 0), Swap.getValue(0));
2397   ReplaceValueWith(SDValue(N, 1), Swap.getValue(1));
2398 }
2399
2400 //===----------------------------------------------------------------------===//
2401 //  Integer Operand Expansion
2402 //===----------------------------------------------------------------------===//
2403
2404 /// ExpandIntegerOperand - This method is called when the specified operand of
2405 /// the specified node is found to need expansion.  At this point, all of the
2406 /// result types of the node are known to be legal, but other operands of the
2407 /// node may need promotion or expansion as well as the specified one.
2408 bool DAGTypeLegalizer::ExpandIntegerOperand(SDNode *N, unsigned OpNo) {
2409   DEBUG(dbgs() << "Expand integer operand: "; N->dump(&DAG); dbgs() << "\n");
2410   SDValue Res = SDValue();
2411
2412   if (CustomLowerNode(N, N->getOperand(OpNo).getValueType(), false))
2413     return false;
2414
2415   switch (N->getOpcode()) {
2416   default:
2417   #ifndef NDEBUG
2418     dbgs() << "ExpandIntegerOperand Op #" << OpNo << ": ";
2419     N->dump(&DAG); dbgs() << "\n";
2420   #endif
2421     llvm_unreachable("Do not know how to expand this operator's operand!");
2422
2423   case ISD::BITCAST:           Res = ExpandOp_BITCAST(N); break;
2424   case ISD::BR_CC:             Res = ExpandIntOp_BR_CC(N); break;
2425   case ISD::BUILD_VECTOR:      Res = ExpandOp_BUILD_VECTOR(N); break;
2426   case ISD::EXTRACT_ELEMENT:   Res = ExpandOp_EXTRACT_ELEMENT(N); break;
2427   case ISD::INSERT_VECTOR_ELT: Res = ExpandOp_INSERT_VECTOR_ELT(N); break;
2428   case ISD::SCALAR_TO_VECTOR:  Res = ExpandOp_SCALAR_TO_VECTOR(N); break;
2429   case ISD::SELECT_CC:         Res = ExpandIntOp_SELECT_CC(N); break;
2430   case ISD::SETCC:             Res = ExpandIntOp_SETCC(N); break;
2431   case ISD::SINT_TO_FP:        Res = ExpandIntOp_SINT_TO_FP(N); break;
2432   case ISD::STORE:   Res = ExpandIntOp_STORE(cast<StoreSDNode>(N), OpNo); break;
2433   case ISD::TRUNCATE:          Res = ExpandIntOp_TRUNCATE(N); break;
2434   case ISD::UINT_TO_FP:        Res = ExpandIntOp_UINT_TO_FP(N); break;
2435
2436   case ISD::SHL:
2437   case ISD::SRA:
2438   case ISD::SRL:
2439   case ISD::ROTL:
2440   case ISD::ROTR:              Res = ExpandIntOp_Shift(N); break;
2441   case ISD::RETURNADDR:
2442   case ISD::FRAMEADDR:         Res = ExpandIntOp_RETURNADDR(N); break;
2443
2444   case ISD::ATOMIC_STORE:      Res = ExpandIntOp_ATOMIC_STORE(N); break;
2445   }
2446
2447   // If the result is null, the sub-method took care of registering results etc.
2448   if (!Res.getNode()) return false;
2449
2450   // If the result is N, the sub-method updated N in place.  Tell the legalizer
2451   // core about this.
2452   if (Res.getNode() == N)
2453     return true;
2454
2455   assert(Res.getValueType() == N->getValueType(0) && N->getNumValues() == 1 &&
2456          "Invalid operand expansion");
2457
2458   ReplaceValueWith(SDValue(N, 0), Res);
2459   return false;
2460 }
2461
2462 /// IntegerExpandSetCCOperands - Expand the operands of a comparison.  This code
2463 /// is shared among BR_CC, SELECT_CC, and SETCC handlers.
2464 void DAGTypeLegalizer::IntegerExpandSetCCOperands(SDValue &NewLHS,
2465                                                   SDValue &NewRHS,
2466                                                   ISD::CondCode &CCCode,
2467                                                   DebugLoc dl) {
2468   SDValue LHSLo, LHSHi, RHSLo, RHSHi;
2469   GetExpandedInteger(NewLHS, LHSLo, LHSHi);
2470   GetExpandedInteger(NewRHS, RHSLo, RHSHi);
2471
2472   if (CCCode == ISD::SETEQ || CCCode == ISD::SETNE) {
2473     if (RHSLo == RHSHi) {
2474       if (ConstantSDNode *RHSCST = dyn_cast<ConstantSDNode>(RHSLo)) {
2475         if (RHSCST->isAllOnesValue()) {
2476           // Equality comparison to -1.
2477           NewLHS = DAG.getNode(ISD::AND, dl,
2478                                LHSLo.getValueType(), LHSLo, LHSHi);
2479           NewRHS = RHSLo;
2480           return;
2481         }
2482       }
2483     }
2484
2485     NewLHS = DAG.getNode(ISD::XOR, dl, LHSLo.getValueType(), LHSLo, RHSLo);
2486     NewRHS = DAG.getNode(ISD::XOR, dl, LHSLo.getValueType(), LHSHi, RHSHi);
2487     NewLHS = DAG.getNode(ISD::OR, dl, NewLHS.getValueType(), NewLHS, NewRHS);
2488     NewRHS = DAG.getConstant(0, NewLHS.getValueType());
2489     return;
2490   }
2491
2492   // If this is a comparison of the sign bit, just look at the top part.
2493   // X > -1,  x < 0
2494   if (ConstantSDNode *CST = dyn_cast<ConstantSDNode>(NewRHS))
2495     if ((CCCode == ISD::SETLT && CST->isNullValue()) ||     // X < 0
2496         (CCCode == ISD::SETGT && CST->isAllOnesValue())) {  // X > -1
2497       NewLHS = LHSHi;
2498       NewRHS = RHSHi;
2499       return;
2500     }
2501
2502   // FIXME: This generated code sucks.
2503   ISD::CondCode LowCC;
2504   switch (CCCode) {
2505   default: llvm_unreachable("Unknown integer setcc!");
2506   case ISD::SETLT:
2507   case ISD::SETULT: LowCC = ISD::SETULT; break;
2508   case ISD::SETGT:
2509   case ISD::SETUGT: LowCC = ISD::SETUGT; break;
2510   case ISD::SETLE:
2511   case ISD::SETULE: LowCC = ISD::SETULE; break;
2512   case ISD::SETGE:
2513   case ISD::SETUGE: LowCC = ISD::SETUGE; break;
2514   }
2515
2516   // Tmp1 = lo(op1) < lo(op2)   // Always unsigned comparison
2517   // Tmp2 = hi(op1) < hi(op2)   // Signedness depends on operands
2518   // dest = hi(op1) == hi(op2) ? Tmp1 : Tmp2;
2519
2520   // NOTE: on targets without efficient SELECT of bools, we can always use
2521   // this identity: (B1 ? B2 : B3) --> (B1 & B2)|(!B1&B3)
2522   TargetLowering::DAGCombinerInfo DagCombineInfo(DAG, false, true, true, NULL);
2523   SDValue Tmp1, Tmp2;
2524   Tmp1 = TLI.SimplifySetCC(TLI.getSetCCResultType(LHSLo.getValueType()),
2525                            LHSLo, RHSLo, LowCC, false, DagCombineInfo, dl);
2526   if (!Tmp1.getNode())
2527     Tmp1 = DAG.getSetCC(dl, TLI.getSetCCResultType(LHSLo.getValueType()),
2528                         LHSLo, RHSLo, LowCC);
2529   Tmp2 = TLI.SimplifySetCC(TLI.getSetCCResultType(LHSHi.getValueType()),
2530                            LHSHi, RHSHi, CCCode, false, DagCombineInfo, dl);
2531   if (!Tmp2.getNode())
2532     Tmp2 = DAG.getNode(ISD::SETCC, dl,
2533                        TLI.getSetCCResultType(LHSHi.getValueType()),
2534                        LHSHi, RHSHi, DAG.getCondCode(CCCode));
2535
2536   ConstantSDNode *Tmp1C = dyn_cast<ConstantSDNode>(Tmp1.getNode());
2537   ConstantSDNode *Tmp2C = dyn_cast<ConstantSDNode>(Tmp2.getNode());
2538   if ((Tmp1C && Tmp1C->isNullValue()) ||
2539       (Tmp2C && Tmp2C->isNullValue() &&
2540        (CCCode == ISD::SETLE || CCCode == ISD::SETGE ||
2541         CCCode == ISD::SETUGE || CCCode == ISD::SETULE)) ||
2542       (Tmp2C && Tmp2C->getAPIntValue() == 1 &&
2543        (CCCode == ISD::SETLT || CCCode == ISD::SETGT ||
2544         CCCode == ISD::SETUGT || CCCode == ISD::SETULT))) {
2545     // low part is known false, returns high part.
2546     // For LE / GE, if high part is known false, ignore the low part.
2547     // For LT / GT, if high part is known true, ignore the low part.
2548     NewLHS = Tmp2;
2549     NewRHS = SDValue();
2550     return;
2551   }
2552
2553   NewLHS = TLI.SimplifySetCC(TLI.getSetCCResultType(LHSHi.getValueType()),
2554                              LHSHi, RHSHi, ISD::SETEQ, false,
2555                              DagCombineInfo, dl);
2556   if (!NewLHS.getNode())
2557     NewLHS = DAG.getSetCC(dl, TLI.getSetCCResultType(LHSHi.getValueType()),
2558                           LHSHi, RHSHi, ISD::SETEQ);
2559   NewLHS = DAG.getNode(ISD::SELECT, dl, Tmp1.getValueType(),
2560                        NewLHS, Tmp1, Tmp2);
2561   NewRHS = SDValue();
2562 }
2563
2564 SDValue DAGTypeLegalizer::ExpandIntOp_BR_CC(SDNode *N) {
2565   SDValue NewLHS = N->getOperand(2), NewRHS = N->getOperand(3);
2566   ISD::CondCode CCCode = cast<CondCodeSDNode>(N->getOperand(1))->get();
2567   IntegerExpandSetCCOperands(NewLHS, NewRHS, CCCode, N->getDebugLoc());
2568
2569   // If ExpandSetCCOperands returned a scalar, we need to compare the result
2570   // against zero to select between true and false values.
2571   if (NewRHS.getNode() == 0) {
2572     NewRHS = DAG.getConstant(0, NewLHS.getValueType());
2573     CCCode = ISD::SETNE;
2574   }
2575
2576   // Update N to have the operands specified.
2577   return SDValue(DAG.UpdateNodeOperands(N, N->getOperand(0),
2578                                 DAG.getCondCode(CCCode), NewLHS, NewRHS,
2579                                 N->getOperand(4)), 0);
2580 }
2581
2582 SDValue DAGTypeLegalizer::ExpandIntOp_SELECT_CC(SDNode *N) {
2583   SDValue NewLHS = N->getOperand(0), NewRHS = N->getOperand(1);
2584   ISD::CondCode CCCode = cast<CondCodeSDNode>(N->getOperand(4))->get();
2585   IntegerExpandSetCCOperands(NewLHS, NewRHS, CCCode, N->getDebugLoc());
2586
2587   // If ExpandSetCCOperands returned a scalar, we need to compare the result
2588   // against zero to select between true and false values.
2589   if (NewRHS.getNode() == 0) {
2590     NewRHS = DAG.getConstant(0, NewLHS.getValueType());
2591     CCCode = ISD::SETNE;
2592   }
2593
2594   // Update N to have the operands specified.
2595   return SDValue(DAG.UpdateNodeOperands(N, NewLHS, NewRHS,
2596                                 N->getOperand(2), N->getOperand(3),
2597                                 DAG.getCondCode(CCCode)), 0);
2598 }
2599
2600 SDValue DAGTypeLegalizer::ExpandIntOp_SETCC(SDNode *N) {
2601   SDValue NewLHS = N->getOperand(0), NewRHS = N->getOperand(1);
2602   ISD::CondCode CCCode = cast<CondCodeSDNode>(N->getOperand(2))->get();
2603   IntegerExpandSetCCOperands(NewLHS, NewRHS, CCCode, N->getDebugLoc());
2604
2605   // If ExpandSetCCOperands returned a scalar, use it.
2606   if (NewRHS.getNode() == 0) {
2607     assert(NewLHS.getValueType() == N->getValueType(0) &&
2608            "Unexpected setcc expansion!");
2609     return NewLHS;
2610   }
2611
2612   // Otherwise, update N to have the operands specified.
2613   return SDValue(DAG.UpdateNodeOperands(N, NewLHS, NewRHS,
2614                                 DAG.getCondCode(CCCode)), 0);
2615 }
2616
2617 SDValue DAGTypeLegalizer::ExpandIntOp_Shift(SDNode *N) {
2618   // The value being shifted is legal, but the shift amount is too big.
2619   // It follows that either the result of the shift is undefined, or the
2620   // upper half of the shift amount is zero.  Just use the lower half.
2621   SDValue Lo, Hi;
2622   GetExpandedInteger(N->getOperand(1), Lo, Hi);
2623   return SDValue(DAG.UpdateNodeOperands(N, N->getOperand(0), Lo), 0);
2624 }
2625
2626 SDValue DAGTypeLegalizer::ExpandIntOp_RETURNADDR(SDNode *N) {
2627   // The argument of RETURNADDR / FRAMEADDR builtin is 32 bit contant.  This
2628   // surely makes pretty nice problems on 8/16 bit targets. Just truncate this
2629   // constant to valid type.
2630   SDValue Lo, Hi;
2631   GetExpandedInteger(N->getOperand(0), Lo, Hi);
2632   return SDValue(DAG.UpdateNodeOperands(N, Lo), 0);
2633 }
2634
2635 SDValue DAGTypeLegalizer::ExpandIntOp_SINT_TO_FP(SDNode *N) {
2636   SDValue Op = N->getOperand(0);
2637   EVT DstVT = N->getValueType(0);
2638   RTLIB::Libcall LC = RTLIB::getSINTTOFP(Op.getValueType(), DstVT);
2639   assert(LC != RTLIB::UNKNOWN_LIBCALL &&
2640          "Don't know how to expand this SINT_TO_FP!");
2641   return MakeLibCall(LC, DstVT, &Op, 1, true, N->getDebugLoc());
2642 }
2643
2644 SDValue DAGTypeLegalizer::ExpandIntOp_STORE(StoreSDNode *N, unsigned OpNo) {
2645   if (ISD::isNormalStore(N))
2646     return ExpandOp_NormalStore(N, OpNo);
2647
2648   assert(ISD::isUNINDEXEDStore(N) && "Indexed store during type legalization!");
2649   assert(OpNo == 1 && "Can only expand the stored value so far");
2650
2651   EVT VT = N->getOperand(1).getValueType();
2652   EVT NVT = TLI.getTypeToTransformTo(*DAG.getContext(), VT);
2653   SDValue Ch  = N->getChain();
2654   SDValue Ptr = N->getBasePtr();
2655   unsigned Alignment = N->getAlignment();
2656   bool isVolatile = N->isVolatile();
2657   bool isNonTemporal = N->isNonTemporal();
2658   DebugLoc dl = N->getDebugLoc();
2659   SDValue Lo, Hi;
2660
2661   assert(NVT.isByteSized() && "Expanded type not byte sized!");
2662
2663   if (N->getMemoryVT().bitsLE(NVT)) {
2664     GetExpandedInteger(N->getValue(), Lo, Hi);
2665     return DAG.getTruncStore(Ch, dl, Lo, Ptr, N->getPointerInfo(),
2666                              N->getMemoryVT(), isVolatile, isNonTemporal,
2667                              Alignment);
2668   }
2669
2670   if (TLI.isLittleEndian()) {
2671     // Little-endian - low bits are at low addresses.
2672     GetExpandedInteger(N->getValue(), Lo, Hi);
2673
2674     Lo = DAG.getStore(Ch, dl, Lo, Ptr, N->getPointerInfo(),
2675                       isVolatile, isNonTemporal, Alignment);
2676
2677     unsigned ExcessBits =
2678       N->getMemoryVT().getSizeInBits() - NVT.getSizeInBits();
2679     EVT NEVT = EVT::getIntegerVT(*DAG.getContext(), ExcessBits);
2680
2681     // Increment the pointer to the other half.
2682     unsigned IncrementSize = NVT.getSizeInBits()/8;
2683     Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr,
2684                       DAG.getIntPtrConstant(IncrementSize));
2685     Hi = DAG.getTruncStore(Ch, dl, Hi, Ptr,
2686                            N->getPointerInfo().getWithOffset(IncrementSize),
2687                            NEVT, isVolatile, isNonTemporal,
2688                            MinAlign(Alignment, IncrementSize));
2689     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Lo, Hi);
2690   }
2691
2692   // Big-endian - high bits are at low addresses.  Favor aligned stores at
2693   // the cost of some bit-fiddling.
2694   GetExpandedInteger(N->getValue(), Lo, Hi);
2695
2696   EVT ExtVT = N->getMemoryVT();
2697   unsigned EBytes = ExtVT.getStoreSize();
2698   unsigned IncrementSize = NVT.getSizeInBits()/8;
2699   unsigned ExcessBits = (EBytes - IncrementSize)*8;
2700   EVT HiVT = EVT::getIntegerVT(*DAG.getContext(),
2701                                ExtVT.getSizeInBits() - ExcessBits);
2702
2703   if (ExcessBits < NVT.getSizeInBits()) {
2704     // Transfer high bits from the top of Lo to the bottom of Hi.
2705     Hi = DAG.getNode(ISD::SHL, dl, NVT, Hi,
2706                      DAG.getConstant(NVT.getSizeInBits() - ExcessBits,
2707                                      TLI.getPointerTy()));
2708     Hi = DAG.getNode(ISD::OR, dl, NVT, Hi,
2709                      DAG.getNode(ISD::SRL, dl, NVT, Lo,
2710                                  DAG.getConstant(ExcessBits,
2711                                                  TLI.getPointerTy())));
2712   }
2713
2714   // Store both the high bits and maybe some of the low bits.
2715   Hi = DAG.getTruncStore(Ch, dl, Hi, Ptr, N->getPointerInfo(),
2716                          HiVT, isVolatile, isNonTemporal, Alignment);
2717
2718   // Increment the pointer to the other half.
2719   Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr,
2720                     DAG.getIntPtrConstant(IncrementSize));
2721   // Store the lowest ExcessBits bits in the second half.
2722   Lo = DAG.getTruncStore(Ch, dl, Lo, Ptr,
2723                          N->getPointerInfo().getWithOffset(IncrementSize),
2724                          EVT::getIntegerVT(*DAG.getContext(), ExcessBits),
2725                          isVolatile, isNonTemporal,
2726                          MinAlign(Alignment, IncrementSize));
2727   return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Lo, Hi);
2728 }
2729
2730 SDValue DAGTypeLegalizer::ExpandIntOp_TRUNCATE(SDNode *N) {
2731   SDValue InL, InH;
2732   GetExpandedInteger(N->getOperand(0), InL, InH);
2733   // Just truncate the low part of the source.
2734   return DAG.getNode(ISD::TRUNCATE, N->getDebugLoc(), N->getValueType(0), InL);
2735 }
2736
2737 static const fltSemantics *EVTToAPFloatSemantics(EVT VT) {
2738   switch (VT.getSimpleVT().SimpleTy) {
2739   default: llvm_unreachable("Unknown FP format");
2740   case MVT::f32:     return &APFloat::IEEEsingle;
2741   case MVT::f64:     return &APFloat::IEEEdouble;
2742   case MVT::f80:     return &APFloat::x87DoubleExtended;
2743   case MVT::f128:    return &APFloat::IEEEquad;
2744   case MVT::ppcf128: return &APFloat::PPCDoubleDouble;
2745   }
2746 }
2747
2748 SDValue DAGTypeLegalizer::ExpandIntOp_UINT_TO_FP(SDNode *N) {
2749   SDValue Op = N->getOperand(0);
2750   EVT SrcVT = Op.getValueType();
2751   EVT DstVT = N->getValueType(0);
2752   DebugLoc dl = N->getDebugLoc();
2753
2754   // The following optimization is valid only if every value in SrcVT (when
2755   // treated as signed) is representable in DstVT.  Check that the mantissa
2756   // size of DstVT is >= than the number of bits in SrcVT -1.
2757   const fltSemantics *sem = EVTToAPFloatSemantics(DstVT);
2758   if (APFloat::semanticsPrecision(*sem) >= SrcVT.getSizeInBits()-1 &&
2759       TLI.getOperationAction(ISD::SINT_TO_FP, SrcVT) == TargetLowering::Custom){
2760     // Do a signed conversion then adjust the result.
2761     SDValue SignedConv = DAG.getNode(ISD::SINT_TO_FP, dl, DstVT, Op);
2762     SignedConv = TLI.LowerOperation(SignedConv, DAG);
2763
2764     // The result of the signed conversion needs adjusting if the 'sign bit' of
2765     // the incoming integer was set.  To handle this, we dynamically test to see
2766     // if it is set, and, if so, add a fudge factor.
2767
2768     const uint64_t F32TwoE32  = 0x4F800000ULL;
2769     const uint64_t F32TwoE64  = 0x5F800000ULL;
2770     const uint64_t F32TwoE128 = 0x7F800000ULL;
2771
2772     APInt FF(32, 0);
2773     if (SrcVT == MVT::i32)
2774       FF = APInt(32, F32TwoE32);
2775     else if (SrcVT == MVT::i64)
2776       FF = APInt(32, F32TwoE64);
2777     else if (SrcVT == MVT::i128)
2778       FF = APInt(32, F32TwoE128);
2779     else
2780       assert(false && "Unsupported UINT_TO_FP!");
2781
2782     // Check whether the sign bit is set.
2783     SDValue Lo, Hi;
2784     GetExpandedInteger(Op, Lo, Hi);
2785     SDValue SignSet = DAG.getSetCC(dl,
2786                                    TLI.getSetCCResultType(Hi.getValueType()),
2787                                    Hi, DAG.getConstant(0, Hi.getValueType()),
2788                                    ISD::SETLT);
2789
2790     // Build a 64 bit pair (0, FF) in the constant pool, with FF in the lo bits.
2791     SDValue FudgePtr = DAG.getConstantPool(
2792                                ConstantInt::get(*DAG.getContext(), FF.zext(64)),
2793                                            TLI.getPointerTy());
2794
2795     // Get a pointer to FF if the sign bit was set, or to 0 otherwise.
2796     SDValue Zero = DAG.getIntPtrConstant(0);
2797     SDValue Four = DAG.getIntPtrConstant(4);
2798     if (TLI.isBigEndian()) std::swap(Zero, Four);
2799     SDValue Offset = DAG.getNode(ISD::SELECT, dl, Zero.getValueType(), SignSet,
2800                                  Zero, Four);
2801     unsigned Alignment = cast<ConstantPoolSDNode>(FudgePtr)->getAlignment();
2802     FudgePtr = DAG.getNode(ISD::ADD, dl, TLI.getPointerTy(), FudgePtr, Offset);
2803     Alignment = std::min(Alignment, 4u);
2804
2805     // Load the value out, extending it from f32 to the destination float type.
2806     // FIXME: Avoid the extend by constructing the right constant pool?
2807     SDValue Fudge = DAG.getExtLoad(ISD::EXTLOAD, dl, DstVT, DAG.getEntryNode(),
2808                                    FudgePtr,
2809                                    MachinePointerInfo::getConstantPool(),
2810                                    MVT::f32,
2811                                    false, false, Alignment);
2812     return DAG.getNode(ISD::FADD, dl, DstVT, SignedConv, Fudge);
2813   }
2814
2815   // Otherwise, use a libcall.
2816   RTLIB::Libcall LC = RTLIB::getUINTTOFP(SrcVT, DstVT);
2817   assert(LC != RTLIB::UNKNOWN_LIBCALL &&
2818          "Don't know how to expand this UINT_TO_FP!");
2819   return MakeLibCall(LC, DstVT, &Op, 1, true, dl);
2820 }
2821
2822 SDValue DAGTypeLegalizer::ExpandIntOp_ATOMIC_STORE(SDNode *N) {
2823   DebugLoc dl = N->getDebugLoc();
2824   SDValue Swap = DAG.getAtomic(ISD::ATOMIC_SWAP, dl,
2825                                cast<AtomicSDNode>(N)->getMemoryVT(),
2826                                N->getOperand(0),
2827                                N->getOperand(1), N->getOperand(2),
2828                                cast<AtomicSDNode>(N)->getMemOperand(),
2829                                cast<AtomicSDNode>(N)->getOrdering(),
2830                                cast<AtomicSDNode>(N)->getSynchScope());
2831   return Swap.getValue(1);
2832 }
2833
2834
2835 SDValue DAGTypeLegalizer::PromoteIntRes_EXTRACT_SUBVECTOR(SDNode *N) {
2836   SDValue InOp0 = N->getOperand(0);
2837   EVT InVT = InOp0.getValueType();
2838
2839   EVT OutVT = N->getValueType(0);
2840   EVT NOutVT = TLI.getTypeToTransformTo(*DAG.getContext(), OutVT);
2841   assert(NOutVT.isVector() && "This type must be promoted to a vector type");
2842   unsigned OutNumElems = OutVT.getVectorNumElements();
2843   EVT NOutVTElem = NOutVT.getVectorElementType();
2844
2845   DebugLoc dl = N->getDebugLoc();
2846   SDValue BaseIdx = N->getOperand(1);
2847
2848   SmallVector<SDValue, 8> Ops;
2849   Ops.reserve(OutNumElems);
2850   for (unsigned i = 0; i != OutNumElems; ++i) {
2851
2852     // Extract the element from the original vector.
2853     SDValue Index = DAG.getNode(ISD::ADD, dl, BaseIdx.getValueType(),
2854       BaseIdx, DAG.getIntPtrConstant(i));
2855     SDValue Ext = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
2856       InVT.getVectorElementType(), N->getOperand(0), Index);
2857
2858     SDValue Op = DAG.getNode(ISD::ANY_EXTEND, dl, NOutVTElem, Ext);
2859     // Insert the converted element to the new vector.
2860     Ops.push_back(Op);
2861   }
2862
2863   return DAG.getNode(ISD::BUILD_VECTOR, dl, NOutVT, &Ops[0], Ops.size());
2864 }
2865
2866
2867 SDValue DAGTypeLegalizer::PromoteIntRes_VECTOR_SHUFFLE(SDNode *N) {
2868   ShuffleVectorSDNode *SV = cast<ShuffleVectorSDNode>(N);
2869   EVT VT = N->getValueType(0);
2870   DebugLoc dl = N->getDebugLoc();
2871
2872   unsigned NumElts = VT.getVectorNumElements();
2873   SmallVector<int, 8> NewMask;
2874   for (unsigned i = 0; i != NumElts; ++i) {
2875     NewMask.push_back(SV->getMaskElt(i));
2876   }
2877
2878   SDValue V0 = GetPromotedInteger(N->getOperand(0));
2879   SDValue V1 = GetPromotedInteger(N->getOperand(1));
2880   EVT OutVT = V0.getValueType();
2881
2882   return DAG.getVectorShuffle(OutVT, dl, V0, V1, &NewMask[0]);
2883 }
2884
2885
2886 SDValue DAGTypeLegalizer::PromoteIntRes_BUILD_VECTOR(SDNode *N) {
2887   EVT OutVT = N->getValueType(0);
2888   EVT NOutVT = TLI.getTypeToTransformTo(*DAG.getContext(), OutVT);
2889   assert(NOutVT.isVector() && "This type must be promoted to a vector type");
2890   unsigned NumElems = N->getNumOperands();
2891   EVT NOutVTElem = NOutVT.getVectorElementType();
2892
2893   DebugLoc dl = N->getDebugLoc();
2894
2895   SmallVector<SDValue, 8> Ops;
2896   Ops.reserve(NumElems);
2897   for (unsigned i = 0; i != NumElems; ++i) {
2898     SDValue Op = DAG.getNode(ISD::ANY_EXTEND, dl, NOutVTElem, N->getOperand(i));
2899     Ops.push_back(Op);
2900   }
2901
2902   return DAG.getNode(ISD::BUILD_VECTOR, dl, NOutVT, &Ops[0], Ops.size());
2903 }
2904
2905 SDValue DAGTypeLegalizer::PromoteIntRes_SCALAR_TO_VECTOR(SDNode *N) {
2906
2907   DebugLoc dl = N->getDebugLoc();
2908
2909   assert(!N->getOperand(0).getValueType().isVector() &&
2910          "Input must be a scalar");
2911
2912   EVT OutVT = N->getValueType(0);
2913   EVT NOutVT = TLI.getTypeToTransformTo(*DAG.getContext(), OutVT);
2914   assert(NOutVT.isVector() && "This type must be promoted to a vector type");
2915   EVT NOutVTElem = NOutVT.getVectorElementType();
2916
2917   SDValue Op = DAG.getNode(ISD::ANY_EXTEND, dl, NOutVTElem, N->getOperand(0));
2918
2919   return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, NOutVT, Op);
2920 }
2921
2922 SDValue DAGTypeLegalizer::PromoteIntRes_CONCAT_VECTORS(SDNode *N) {
2923   DebugLoc dl = N->getDebugLoc();
2924
2925   SDValue Op0 = N->getOperand(1);
2926   SDValue Op1 = N->getOperand(1);
2927   assert(Op0.getValueType() == Op1.getValueType() &&
2928          "Invalid input vector types");
2929
2930   EVT OutVT = N->getValueType(0);
2931   EVT NOutVT = TLI.getTypeToTransformTo(*DAG.getContext(), OutVT);
2932   assert(NOutVT.isVector() && "This type must be promoted to a vector type");
2933
2934   EVT OutElemTy = NOutVT.getVectorElementType();
2935
2936   unsigned NumElem0 = Op0.getValueType().getVectorNumElements();
2937   unsigned NumElem1 = Op1.getValueType().getVectorNumElements();
2938   unsigned NumOutElem = NOutVT.getVectorNumElements();
2939   assert(NumElem0 + NumElem1 == NumOutElem &&
2940          "Invalid number of incoming elements");
2941
2942   // Take the elements from the first vector.
2943   SmallVector<SDValue, 8> Ops(NumOutElem);
2944   for (unsigned i = 0; i < NumElem0; ++i) {
2945     SDValue Ext = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
2946                               Op0.getValueType().getScalarType(), Op0,
2947                               DAG.getIntPtrConstant(i));
2948     Ops[i] = DAG.getNode(ISD::ANY_EXTEND, dl, OutElemTy, Ext);
2949   }
2950
2951   // Take the elements from the second vector
2952   for (unsigned i = 0; i < NumElem1; ++i) {
2953     SDValue Ext = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
2954                               Op1.getValueType().getScalarType(), Op1,
2955                               DAG.getIntPtrConstant(i));
2956     Ops[i + NumElem0] = DAG.getNode(ISD::ANY_EXTEND, dl, OutElemTy, Ext);
2957   }
2958
2959   return DAG.getNode(ISD::BUILD_VECTOR, dl, NOutVT, &Ops[0], Ops.size());
2960 }
2961
2962 SDValue DAGTypeLegalizer::PromoteIntRes_INSERT_VECTOR_ELT(SDNode *N) {
2963   EVT OutVT = N->getValueType(0);
2964   EVT NOutVT = TLI.getTypeToTransformTo(*DAG.getContext(), OutVT);
2965   assert(NOutVT.isVector() && "This type must be promoted to a vector type");
2966
2967   EVT NOutVTElem = NOutVT.getVectorElementType();
2968
2969   DebugLoc dl = N->getDebugLoc();
2970   SDValue V0 = GetPromotedInteger(N->getOperand(0));
2971
2972   SDValue ConvElem = DAG.getNode(ISD::ANY_EXTEND, dl,
2973     NOutVTElem, N->getOperand(1));
2974   return DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, NOutVT,
2975     V0, ConvElem, N->getOperand(2));
2976 }
2977
2978 SDValue DAGTypeLegalizer::PromoteIntOp_EXTRACT_VECTOR_ELT(SDNode *N) {
2979   DebugLoc dl = N->getDebugLoc();
2980   SDValue V0 = GetPromotedInteger(N->getOperand(0));
2981   SDValue V1 = N->getOperand(1);
2982   SDValue Ext = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
2983     V0->getValueType(0).getScalarType(), V0, V1);
2984
2985   return DAG.getNode(ISD::TRUNCATE, dl, N->getValueType(0), Ext);
2986
2987 }
2988
2989 SDValue DAGTypeLegalizer::PromoteIntOp_CONCAT_VECTORS(SDNode *N) {
2990   DebugLoc dl = N->getDebugLoc();
2991   unsigned NumElems = N->getNumOperands();
2992
2993   EVT RetSclrTy = N->getValueType(0).getVectorElementType();
2994
2995   SmallVector<SDValue, 8> NewOps;
2996   NewOps.reserve(NumElems);
2997
2998   // For each incoming vector
2999   for (unsigned VecIdx = 0; VecIdx != NumElems; ++VecIdx) {
3000     SDValue Incoming = GetPromotedInteger(N->getOperand(VecIdx));
3001     EVT SclrTy = Incoming->getValueType(0).getVectorElementType();
3002     unsigned NumElem = Incoming->getValueType(0).getVectorNumElements();
3003
3004     for (unsigned i=0; i<NumElem; ++i) {
3005       // Extract element from incoming vector
3006       SDValue Ex = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, SclrTy,
3007       Incoming, DAG.getIntPtrConstant(i));
3008       SDValue Tr = DAG.getNode(ISD::TRUNCATE, dl, RetSclrTy, Ex);
3009       NewOps.push_back(Tr);
3010     }
3011   }
3012
3013   return DAG.getNode(ISD::BUILD_VECTOR, dl,  N->getValueType(0),
3014     &NewOps[0], NewOps.size());
3015   }