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