OSDN Git Service

[SelectionDAG] Don't promote mask when splitting mstore.
[android-x86/external-llvm.git] / lib / CodeGen / SelectionDAG / LegalizeVectorTypes.cpp
1 //===------- LegalizeVectorTypes.cpp - Legalization of vector 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 performs vector type splitting and scalarization for LegalizeTypes.
11 // Scalarization is the act of changing a computation in an illegal one-element
12 // vector type to be a computation in its scalar element type.  For example,
13 // implementing <1 x f32> arithmetic in a scalar f32 register.  This is needed
14 // as a base case when scalarizing vector arithmetic like <4 x f32>, which
15 // eventually decomposes to scalars if the target doesn't support v4f32 or v2f32
16 // types.
17 // Splitting is the act of changing a computation in an invalid vector type to
18 // be a computation in two vectors of half the size.  For example, implementing
19 // <128 x f32> operations in terms of two <64 x f32> operations.
20 //
21 //===----------------------------------------------------------------------===//
22
23 #include "LegalizeTypes.h"
24 #include "llvm/IR/DataLayout.h"
25 #include "llvm/Support/ErrorHandling.h"
26 #include "llvm/Support/raw_ostream.h"
27 using namespace llvm;
28
29 #define DEBUG_TYPE "legalize-types"
30
31 //===----------------------------------------------------------------------===//
32 //  Result Vector Scalarization: <1 x ty> -> ty.
33 //===----------------------------------------------------------------------===//
34
35 void DAGTypeLegalizer::ScalarizeVectorResult(SDNode *N, unsigned ResNo) {
36   DEBUG(dbgs() << "Scalarize node result " << ResNo << ": ";
37         N->dump(&DAG);
38         dbgs() << "\n");
39   SDValue R = SDValue();
40
41   switch (N->getOpcode()) {
42   default:
43 #ifndef NDEBUG
44     dbgs() << "ScalarizeVectorResult #" << ResNo << ": ";
45     N->dump(&DAG);
46     dbgs() << "\n";
47 #endif
48     report_fatal_error("Do not know how to scalarize the result of this "
49                        "operator!\n");
50
51   case ISD::MERGE_VALUES:      R = ScalarizeVecRes_MERGE_VALUES(N, ResNo);break;
52   case ISD::BITCAST:           R = ScalarizeVecRes_BITCAST(N); break;
53   case ISD::BUILD_VECTOR:      R = ScalarizeVecRes_BUILD_VECTOR(N); break;
54   case ISD::EXTRACT_SUBVECTOR: R = ScalarizeVecRes_EXTRACT_SUBVECTOR(N); break;
55   case ISD::FP_ROUND:          R = ScalarizeVecRes_FP_ROUND(N); break;
56   case ISD::FP_ROUND_INREG:    R = ScalarizeVecRes_InregOp(N); break;
57   case ISD::FPOWI:             R = ScalarizeVecRes_FPOWI(N); break;
58   case ISD::INSERT_VECTOR_ELT: R = ScalarizeVecRes_INSERT_VECTOR_ELT(N); break;
59   case ISD::LOAD:           R = ScalarizeVecRes_LOAD(cast<LoadSDNode>(N));break;
60   case ISD::SCALAR_TO_VECTOR:  R = ScalarizeVecRes_SCALAR_TO_VECTOR(N); break;
61   case ISD::SIGN_EXTEND_INREG: R = ScalarizeVecRes_InregOp(N); break;
62   case ISD::VSELECT:           R = ScalarizeVecRes_VSELECT(N); break;
63   case ISD::SELECT:            R = ScalarizeVecRes_SELECT(N); break;
64   case ISD::SELECT_CC:         R = ScalarizeVecRes_SELECT_CC(N); break;
65   case ISD::SETCC:             R = ScalarizeVecRes_SETCC(N); break;
66   case ISD::UNDEF:             R = ScalarizeVecRes_UNDEF(N); break;
67   case ISD::VECTOR_SHUFFLE:    R = ScalarizeVecRes_VECTOR_SHUFFLE(N); break;
68   case ISD::ANY_EXTEND_VECTOR_INREG:
69   case ISD::SIGN_EXTEND_VECTOR_INREG:
70   case ISD::ZERO_EXTEND_VECTOR_INREG:
71     R = ScalarizeVecRes_VecInregOp(N);
72     break;
73   case ISD::ANY_EXTEND:
74   case ISD::BITREVERSE:
75   case ISD::BSWAP:
76   case ISD::CTLZ:
77   case ISD::CTLZ_ZERO_UNDEF:
78   case ISD::CTPOP:
79   case ISD::CTTZ:
80   case ISD::CTTZ_ZERO_UNDEF:
81   case ISD::FABS:
82   case ISD::FCEIL:
83   case ISD::FCOS:
84   case ISD::FEXP:
85   case ISD::FEXP2:
86   case ISD::FFLOOR:
87   case ISD::FLOG:
88   case ISD::FLOG10:
89   case ISD::FLOG2:
90   case ISD::FNEARBYINT:
91   case ISD::FNEG:
92   case ISD::FP_EXTEND:
93   case ISD::FP_TO_SINT:
94   case ISD::FP_TO_UINT:
95   case ISD::FRINT:
96   case ISD::FROUND:
97   case ISD::FSIN:
98   case ISD::FSQRT:
99   case ISD::FTRUNC:
100   case ISD::SIGN_EXTEND:
101   case ISD::SINT_TO_FP:
102   case ISD::TRUNCATE:
103   case ISD::UINT_TO_FP:
104   case ISD::ZERO_EXTEND:
105   case ISD::FCANONICALIZE:
106     R = ScalarizeVecRes_UnaryOp(N);
107     break;
108
109   case ISD::ADD:
110   case ISD::AND:
111   case ISD::FADD:
112   case ISD::FCOPYSIGN:
113   case ISD::FDIV:
114   case ISD::FMUL:
115   case ISD::FMINNUM:
116   case ISD::FMAXNUM:
117   case ISD::FMINNAN:
118   case ISD::FMAXNAN:
119   case ISD::SMIN:
120   case ISD::SMAX:
121   case ISD::UMIN:
122   case ISD::UMAX:
123
124   case ISD::FPOW:
125   case ISD::FREM:
126   case ISD::FSUB:
127   case ISD::MUL:
128   case ISD::OR:
129   case ISD::SDIV:
130   case ISD::SREM:
131   case ISD::SUB:
132   case ISD::UDIV:
133   case ISD::UREM:
134   case ISD::XOR:
135   case ISD::SHL:
136   case ISD::SRA:
137   case ISD::SRL:
138     R = ScalarizeVecRes_BinOp(N);
139     break;
140   case ISD::FMA:
141     R = ScalarizeVecRes_TernaryOp(N);
142     break;
143   }
144
145   // If R is null, the sub-method took care of registering the result.
146   if (R.getNode())
147     SetScalarizedVector(SDValue(N, ResNo), R);
148 }
149
150 SDValue DAGTypeLegalizer::ScalarizeVecRes_BinOp(SDNode *N) {
151   SDValue LHS = GetScalarizedVector(N->getOperand(0));
152   SDValue RHS = GetScalarizedVector(N->getOperand(1));
153   return DAG.getNode(N->getOpcode(), SDLoc(N),
154                      LHS.getValueType(), LHS, RHS, N->getFlags());
155 }
156
157 SDValue DAGTypeLegalizer::ScalarizeVecRes_TernaryOp(SDNode *N) {
158   SDValue Op0 = GetScalarizedVector(N->getOperand(0));
159   SDValue Op1 = GetScalarizedVector(N->getOperand(1));
160   SDValue Op2 = GetScalarizedVector(N->getOperand(2));
161   return DAG.getNode(N->getOpcode(), SDLoc(N),
162                      Op0.getValueType(), Op0, Op1, Op2);
163 }
164
165 SDValue DAGTypeLegalizer::ScalarizeVecRes_MERGE_VALUES(SDNode *N,
166                                                        unsigned ResNo) {
167   SDValue Op = DisintegrateMERGE_VALUES(N, ResNo);
168   return GetScalarizedVector(Op);
169 }
170
171 SDValue DAGTypeLegalizer::ScalarizeVecRes_BITCAST(SDNode *N) {
172   EVT NewVT = N->getValueType(0).getVectorElementType();
173   return DAG.getNode(ISD::BITCAST, SDLoc(N),
174                      NewVT, N->getOperand(0));
175 }
176
177 SDValue DAGTypeLegalizer::ScalarizeVecRes_BUILD_VECTOR(SDNode *N) {
178   EVT EltVT = N->getValueType(0).getVectorElementType();
179   SDValue InOp = N->getOperand(0);
180   // The BUILD_VECTOR operands may be of wider element types and
181   // we may need to truncate them back to the requested return type.
182   if (EltVT.isInteger())
183     return DAG.getNode(ISD::TRUNCATE, SDLoc(N), EltVT, InOp);
184   return InOp;
185 }
186
187 SDValue DAGTypeLegalizer::ScalarizeVecRes_EXTRACT_SUBVECTOR(SDNode *N) {
188   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SDLoc(N),
189                      N->getValueType(0).getVectorElementType(),
190                      N->getOperand(0), N->getOperand(1));
191 }
192
193 SDValue DAGTypeLegalizer::ScalarizeVecRes_FP_ROUND(SDNode *N) {
194   EVT NewVT = N->getValueType(0).getVectorElementType();
195   SDValue Op = GetScalarizedVector(N->getOperand(0));
196   return DAG.getNode(ISD::FP_ROUND, SDLoc(N),
197                      NewVT, Op, N->getOperand(1));
198 }
199
200 SDValue DAGTypeLegalizer::ScalarizeVecRes_FPOWI(SDNode *N) {
201   SDValue Op = GetScalarizedVector(N->getOperand(0));
202   return DAG.getNode(ISD::FPOWI, SDLoc(N),
203                      Op.getValueType(), Op, N->getOperand(1));
204 }
205
206 SDValue DAGTypeLegalizer::ScalarizeVecRes_INSERT_VECTOR_ELT(SDNode *N) {
207   // The value to insert may have a wider type than the vector element type,
208   // so be sure to truncate it to the element type if necessary.
209   SDValue Op = N->getOperand(1);
210   EVT EltVT = N->getValueType(0).getVectorElementType();
211   if (Op.getValueType() != EltVT)
212     // FIXME: Can this happen for floating point types?
213     Op = DAG.getNode(ISD::TRUNCATE, SDLoc(N), EltVT, Op);
214   return Op;
215 }
216
217 SDValue DAGTypeLegalizer::ScalarizeVecRes_LOAD(LoadSDNode *N) {
218   assert(N->isUnindexed() && "Indexed vector load?");
219
220   SDValue Result = DAG.getLoad(
221       ISD::UNINDEXED, N->getExtensionType(),
222       N->getValueType(0).getVectorElementType(), SDLoc(N), N->getChain(),
223       N->getBasePtr(), DAG.getUNDEF(N->getBasePtr().getValueType()),
224       N->getPointerInfo(), N->getMemoryVT().getVectorElementType(),
225       N->getOriginalAlignment(), N->getMemOperand()->getFlags(),
226       N->getAAInfo());
227
228   // Legalize the chain result - switch anything that used the old chain to
229   // use the new one.
230   ReplaceValueWith(SDValue(N, 1), Result.getValue(1));
231   return Result;
232 }
233
234 SDValue DAGTypeLegalizer::ScalarizeVecRes_UnaryOp(SDNode *N) {
235   // Get the dest type - it doesn't always match the input type, e.g. int_to_fp.
236   EVT DestVT = N->getValueType(0).getVectorElementType();
237   SDValue Op = N->getOperand(0);
238   EVT OpVT = Op.getValueType();
239   SDLoc DL(N);
240   // The result needs scalarizing, but it's not a given that the source does.
241   // This is a workaround for targets where it's impossible to scalarize the
242   // result of a conversion, because the source type is legal.
243   // For instance, this happens on AArch64: v1i1 is illegal but v1i{8,16,32}
244   // are widened to v8i8, v4i16, and v2i32, which is legal, because v1i64 is
245   // legal and was not scalarized.
246   // See the similar logic in ScalarizeVecRes_SETCC
247   if (getTypeAction(OpVT) == TargetLowering::TypeScalarizeVector) {
248     Op = GetScalarizedVector(Op);
249   } else {
250     EVT VT = OpVT.getVectorElementType();
251     Op = DAG.getNode(
252         ISD::EXTRACT_VECTOR_ELT, DL, VT, Op,
253         DAG.getConstant(0, DL, TLI.getVectorIdxTy(DAG.getDataLayout())));
254   }
255   return DAG.getNode(N->getOpcode(), SDLoc(N), DestVT, Op);
256 }
257
258 SDValue DAGTypeLegalizer::ScalarizeVecRes_InregOp(SDNode *N) {
259   EVT EltVT = N->getValueType(0).getVectorElementType();
260   EVT ExtVT = cast<VTSDNode>(N->getOperand(1))->getVT().getVectorElementType();
261   SDValue LHS = GetScalarizedVector(N->getOperand(0));
262   return DAG.getNode(N->getOpcode(), SDLoc(N), EltVT,
263                      LHS, DAG.getValueType(ExtVT));
264 }
265
266 SDValue DAGTypeLegalizer::ScalarizeVecRes_VecInregOp(SDNode *N) {
267   SDLoc DL(N);
268   SDValue Op = N->getOperand(0);
269
270   EVT OpVT = Op.getValueType();
271   EVT OpEltVT = OpVT.getVectorElementType();
272   EVT EltVT = N->getValueType(0).getVectorElementType();
273
274   if (getTypeAction(OpVT) == TargetLowering::TypeScalarizeVector) {
275     Op = GetScalarizedVector(Op);
276   } else {
277     Op = DAG.getNode(
278         ISD::EXTRACT_VECTOR_ELT, DL, OpEltVT, Op,
279         DAG.getConstant(0, DL, TLI.getVectorIdxTy(DAG.getDataLayout())));
280   }
281
282   switch (N->getOpcode()) {
283   case ISD::ANY_EXTEND_VECTOR_INREG:
284     return DAG.getNode(ISD::ANY_EXTEND, DL, EltVT, Op);
285   case ISD::SIGN_EXTEND_VECTOR_INREG:
286     return DAG.getNode(ISD::SIGN_EXTEND, DL, EltVT, Op);
287   case ISD::ZERO_EXTEND_VECTOR_INREG:
288     return DAG.getNode(ISD::ZERO_EXTEND, DL, EltVT, Op);
289   }
290
291   llvm_unreachable("Illegal extend_vector_inreg opcode");
292 }
293
294 SDValue DAGTypeLegalizer::ScalarizeVecRes_SCALAR_TO_VECTOR(SDNode *N) {
295   // If the operand is wider than the vector element type then it is implicitly
296   // truncated.  Make that explicit here.
297   EVT EltVT = N->getValueType(0).getVectorElementType();
298   SDValue InOp = N->getOperand(0);
299   if (InOp.getValueType() != EltVT)
300     return DAG.getNode(ISD::TRUNCATE, SDLoc(N), EltVT, InOp);
301   return InOp;
302 }
303
304 SDValue DAGTypeLegalizer::ScalarizeVecRes_VSELECT(SDNode *N) {
305   SDValue Cond = N->getOperand(0);
306   EVT OpVT = Cond.getValueType();
307   SDLoc DL(N);
308   // The vselect result and true/value operands needs scalarizing, but it's
309   // not a given that the Cond does. For instance, in AVX512 v1i1 is legal.
310   // See the similar logic in ScalarizeVecRes_SETCC
311   if (getTypeAction(OpVT) == TargetLowering::TypeScalarizeVector) {
312     Cond = GetScalarizedVector(Cond);
313   } else {
314     EVT VT = OpVT.getVectorElementType();
315     Cond = DAG.getNode(
316         ISD::EXTRACT_VECTOR_ELT, DL, VT, Cond,
317         DAG.getConstant(0, DL, TLI.getVectorIdxTy(DAG.getDataLayout())));
318   }
319
320   SDValue LHS = GetScalarizedVector(N->getOperand(1));
321   TargetLowering::BooleanContent ScalarBool =
322       TLI.getBooleanContents(false, false);
323   TargetLowering::BooleanContent VecBool = TLI.getBooleanContents(true, false);
324
325   // If integer and float booleans have different contents then we can't
326   // reliably optimize in all cases. There is a full explanation for this in
327   // DAGCombiner::visitSELECT() where the same issue affects folding
328   // (select C, 0, 1) to (xor C, 1).
329   if (TLI.getBooleanContents(false, false) !=
330       TLI.getBooleanContents(false, true)) {
331     // At least try the common case where the boolean is generated by a
332     // comparison.
333     if (Cond->getOpcode() == ISD::SETCC) {
334       EVT OpVT = Cond->getOperand(0)->getValueType(0);
335       ScalarBool = TLI.getBooleanContents(OpVT.getScalarType());
336       VecBool = TLI.getBooleanContents(OpVT);
337     } else
338       ScalarBool = TargetLowering::UndefinedBooleanContent;
339   }
340
341   if (ScalarBool != VecBool) {
342     EVT CondVT = Cond.getValueType();
343     switch (ScalarBool) {
344       case TargetLowering::UndefinedBooleanContent:
345         break;
346       case TargetLowering::ZeroOrOneBooleanContent:
347         assert(VecBool == TargetLowering::UndefinedBooleanContent ||
348                VecBool == TargetLowering::ZeroOrNegativeOneBooleanContent);
349         // Vector read from all ones, scalar expects a single 1 so mask.
350         Cond = DAG.getNode(ISD::AND, SDLoc(N), CondVT,
351                            Cond, DAG.getConstant(1, SDLoc(N), CondVT));
352         break;
353       case TargetLowering::ZeroOrNegativeOneBooleanContent:
354         assert(VecBool == TargetLowering::UndefinedBooleanContent ||
355                VecBool == TargetLowering::ZeroOrOneBooleanContent);
356         // Vector reads from a one, scalar from all ones so sign extend.
357         Cond = DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), CondVT,
358                            Cond, DAG.getValueType(MVT::i1));
359         break;
360     }
361   }
362
363   return DAG.getSelect(SDLoc(N),
364                        LHS.getValueType(), Cond, LHS,
365                        GetScalarizedVector(N->getOperand(2)));
366 }
367
368 SDValue DAGTypeLegalizer::ScalarizeVecRes_SELECT(SDNode *N) {
369   SDValue LHS = GetScalarizedVector(N->getOperand(1));
370   return DAG.getSelect(SDLoc(N),
371                        LHS.getValueType(), N->getOperand(0), LHS,
372                        GetScalarizedVector(N->getOperand(2)));
373 }
374
375 SDValue DAGTypeLegalizer::ScalarizeVecRes_SELECT_CC(SDNode *N) {
376   SDValue LHS = GetScalarizedVector(N->getOperand(2));
377   return DAG.getNode(ISD::SELECT_CC, SDLoc(N), LHS.getValueType(),
378                      N->getOperand(0), N->getOperand(1),
379                      LHS, GetScalarizedVector(N->getOperand(3)),
380                      N->getOperand(4));
381 }
382
383 SDValue DAGTypeLegalizer::ScalarizeVecRes_UNDEF(SDNode *N) {
384   return DAG.getUNDEF(N->getValueType(0).getVectorElementType());
385 }
386
387 SDValue DAGTypeLegalizer::ScalarizeVecRes_VECTOR_SHUFFLE(SDNode *N) {
388   // Figure out if the scalar is the LHS or RHS and return it.
389   SDValue Arg = N->getOperand(2).getOperand(0);
390   if (Arg.isUndef())
391     return DAG.getUNDEF(N->getValueType(0).getVectorElementType());
392   unsigned Op = !cast<ConstantSDNode>(Arg)->isNullValue();
393   return GetScalarizedVector(N->getOperand(Op));
394 }
395
396 SDValue DAGTypeLegalizer::ScalarizeVecRes_SETCC(SDNode *N) {
397   assert(N->getValueType(0).isVector() &&
398          N->getOperand(0).getValueType().isVector() &&
399          "Operand types must be vectors");
400   SDValue LHS = N->getOperand(0);
401   SDValue RHS = N->getOperand(1);
402   EVT OpVT = LHS.getValueType();
403   EVT NVT = N->getValueType(0).getVectorElementType();
404   SDLoc DL(N);
405
406   // The result needs scalarizing, but it's not a given that the source does.
407   if (getTypeAction(OpVT) == TargetLowering::TypeScalarizeVector) {
408     LHS = GetScalarizedVector(LHS);
409     RHS = GetScalarizedVector(RHS);
410   } else {
411     EVT VT = OpVT.getVectorElementType();
412     LHS = DAG.getNode(
413         ISD::EXTRACT_VECTOR_ELT, DL, VT, LHS,
414         DAG.getConstant(0, DL, TLI.getVectorIdxTy(DAG.getDataLayout())));
415     RHS = DAG.getNode(
416         ISD::EXTRACT_VECTOR_ELT, DL, VT, RHS,
417         DAG.getConstant(0, DL, TLI.getVectorIdxTy(DAG.getDataLayout())));
418   }
419
420   // Turn it into a scalar SETCC.
421   SDValue Res = DAG.getNode(ISD::SETCC, DL, MVT::i1, LHS, RHS,
422                             N->getOperand(2));
423   // Vectors may have a different boolean contents to scalars.  Promote the
424   // value appropriately.
425   ISD::NodeType ExtendCode =
426       TargetLowering::getExtendForContent(TLI.getBooleanContents(OpVT));
427   return DAG.getNode(ExtendCode, DL, NVT, Res);
428 }
429
430
431 //===----------------------------------------------------------------------===//
432 //  Operand Vector Scalarization <1 x ty> -> ty.
433 //===----------------------------------------------------------------------===//
434
435 bool DAGTypeLegalizer::ScalarizeVectorOperand(SDNode *N, unsigned OpNo) {
436   DEBUG(dbgs() << "Scalarize node operand " << OpNo << ": ";
437         N->dump(&DAG);
438         dbgs() << "\n");
439   SDValue Res = SDValue();
440
441   if (!Res.getNode()) {
442     switch (N->getOpcode()) {
443     default:
444 #ifndef NDEBUG
445       dbgs() << "ScalarizeVectorOperand Op #" << OpNo << ": ";
446       N->dump(&DAG);
447       dbgs() << "\n";
448 #endif
449       report_fatal_error("Do not know how to scalarize this operator's "
450                          "operand!\n");
451     case ISD::BITCAST:
452       Res = ScalarizeVecOp_BITCAST(N);
453       break;
454     case ISD::ANY_EXTEND:
455     case ISD::ZERO_EXTEND:
456     case ISD::SIGN_EXTEND:
457     case ISD::TRUNCATE:
458     case ISD::FP_TO_SINT:
459     case ISD::FP_TO_UINT:
460     case ISD::SINT_TO_FP:
461     case ISD::UINT_TO_FP:
462       Res = ScalarizeVecOp_UnaryOp(N);
463       break;
464     case ISD::CONCAT_VECTORS:
465       Res = ScalarizeVecOp_CONCAT_VECTORS(N);
466       break;
467     case ISD::EXTRACT_VECTOR_ELT:
468       Res = ScalarizeVecOp_EXTRACT_VECTOR_ELT(N);
469       break;
470     case ISD::VSELECT:
471       Res = ScalarizeVecOp_VSELECT(N);
472       break;
473     case ISD::SETCC:
474       Res = ScalarizeVecOp_VSETCC(N);
475       break;
476     case ISD::STORE:
477       Res = ScalarizeVecOp_STORE(cast<StoreSDNode>(N), OpNo);
478       break;
479     case ISD::FP_ROUND:
480       Res = ScalarizeVecOp_FP_ROUND(N, OpNo);
481       break;
482     }
483   }
484
485   // If the result is null, the sub-method took care of registering results etc.
486   if (!Res.getNode()) return false;
487
488   // If the result is N, the sub-method updated N in place.  Tell the legalizer
489   // core about this.
490   if (Res.getNode() == N)
491     return true;
492
493   assert(Res.getValueType() == N->getValueType(0) && N->getNumValues() == 1 &&
494          "Invalid operand expansion");
495
496   ReplaceValueWith(SDValue(N, 0), Res);
497   return false;
498 }
499
500 /// If the value to convert is a vector that needs to be scalarized, it must be
501 /// <1 x ty>. Convert the element instead.
502 SDValue DAGTypeLegalizer::ScalarizeVecOp_BITCAST(SDNode *N) {
503   SDValue Elt = GetScalarizedVector(N->getOperand(0));
504   return DAG.getNode(ISD::BITCAST, SDLoc(N),
505                      N->getValueType(0), Elt);
506 }
507
508 /// If the input is a vector that needs to be scalarized, it must be <1 x ty>.
509 /// Do the operation on the element instead.
510 SDValue DAGTypeLegalizer::ScalarizeVecOp_UnaryOp(SDNode *N) {
511   assert(N->getValueType(0).getVectorNumElements() == 1 &&
512          "Unexpected vector type!");
513   SDValue Elt = GetScalarizedVector(N->getOperand(0));
514   SDValue Op = DAG.getNode(N->getOpcode(), SDLoc(N),
515                            N->getValueType(0).getScalarType(), Elt);
516   // Revectorize the result so the types line up with what the uses of this
517   // expression expect.
518   return DAG.getBuildVector(N->getValueType(0), SDLoc(N), Op);
519 }
520
521 /// The vectors to concatenate have length one - use a BUILD_VECTOR instead.
522 SDValue DAGTypeLegalizer::ScalarizeVecOp_CONCAT_VECTORS(SDNode *N) {
523   SmallVector<SDValue, 8> Ops(N->getNumOperands());
524   for (unsigned i = 0, e = N->getNumOperands(); i < e; ++i)
525     Ops[i] = GetScalarizedVector(N->getOperand(i));
526   return DAG.getBuildVector(N->getValueType(0), SDLoc(N), Ops);
527 }
528
529 /// If the input is a vector that needs to be scalarized, it must be <1 x ty>,
530 /// so just return the element, ignoring the index.
531 SDValue DAGTypeLegalizer::ScalarizeVecOp_EXTRACT_VECTOR_ELT(SDNode *N) {
532   EVT VT = N->getValueType(0);
533   SDValue Res = GetScalarizedVector(N->getOperand(0));
534   if (Res.getValueType() != VT)
535     Res = VT.isFloatingPoint()
536               ? DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, Res)
537               : DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, Res);
538   return Res;
539 }
540
541 /// If the input condition is a vector that needs to be scalarized, it must be
542 /// <1 x i1>, so just convert to a normal ISD::SELECT
543 /// (still with vector output type since that was acceptable if we got here).
544 SDValue DAGTypeLegalizer::ScalarizeVecOp_VSELECT(SDNode *N) {
545   SDValue ScalarCond = GetScalarizedVector(N->getOperand(0));
546   EVT VT = N->getValueType(0);
547
548   return DAG.getNode(ISD::SELECT, SDLoc(N), VT, ScalarCond, N->getOperand(1),
549                      N->getOperand(2));
550 }
551
552 /// If the operand is a vector that needs to be scalarized then the
553 /// result must be v1i1, so just convert to a scalar SETCC and wrap
554 /// with a scalar_to_vector since the res type is legal if we got here
555 SDValue DAGTypeLegalizer::ScalarizeVecOp_VSETCC(SDNode *N) {
556   assert(N->getValueType(0).isVector() &&
557          N->getOperand(0).getValueType().isVector() &&
558          "Operand types must be vectors");
559   assert(N->getValueType(0) == MVT::v1i1 && "Expected v1i1 type");
560
561   EVT VT = N->getValueType(0);
562   SDValue LHS = GetScalarizedVector(N->getOperand(0));
563   SDValue RHS = GetScalarizedVector(N->getOperand(1));
564
565   EVT OpVT = N->getOperand(0).getValueType();
566   EVT NVT = VT.getVectorElementType();
567   SDLoc DL(N);
568   // Turn it into a scalar SETCC.
569   SDValue Res = DAG.getNode(ISD::SETCC, DL, MVT::i1, LHS, RHS,
570       N->getOperand(2));
571
572   // Vectors may have a different boolean contents to scalars.  Promote the
573   // value appropriately.
574   ISD::NodeType ExtendCode =
575       TargetLowering::getExtendForContent(TLI.getBooleanContents(OpVT));
576
577   Res = DAG.getNode(ExtendCode, DL, NVT, Res);
578
579   return DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, VT, Res);
580 }
581
582 /// If the value to store is a vector that needs to be scalarized, it must be
583 /// <1 x ty>. Just store the element.
584 SDValue DAGTypeLegalizer::ScalarizeVecOp_STORE(StoreSDNode *N, unsigned OpNo){
585   assert(N->isUnindexed() && "Indexed store of one-element vector?");
586   assert(OpNo == 1 && "Do not know how to scalarize this operand!");
587   SDLoc dl(N);
588
589   if (N->isTruncatingStore())
590     return DAG.getTruncStore(
591         N->getChain(), dl, GetScalarizedVector(N->getOperand(1)),
592         N->getBasePtr(), N->getPointerInfo(),
593         N->getMemoryVT().getVectorElementType(), N->getAlignment(),
594         N->getMemOperand()->getFlags(), N->getAAInfo());
595
596   return DAG.getStore(N->getChain(), dl, GetScalarizedVector(N->getOperand(1)),
597                       N->getBasePtr(), N->getPointerInfo(),
598                       N->getOriginalAlignment(), N->getMemOperand()->getFlags(),
599                       N->getAAInfo());
600 }
601
602 /// If the value to round is a vector that needs to be scalarized, it must be
603 /// <1 x ty>. Convert the element instead.
604 SDValue DAGTypeLegalizer::ScalarizeVecOp_FP_ROUND(SDNode *N, unsigned OpNo) {
605   SDValue Elt = GetScalarizedVector(N->getOperand(0));
606   SDValue Res = DAG.getNode(ISD::FP_ROUND, SDLoc(N),
607                             N->getValueType(0).getVectorElementType(), Elt,
608                             N->getOperand(1));
609   return DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(N), N->getValueType(0), Res);
610 }
611
612 //===----------------------------------------------------------------------===//
613 //  Result Vector Splitting
614 //===----------------------------------------------------------------------===//
615
616 /// This method is called when the specified result of the specified node is
617 /// found to need vector splitting. At this point, the node may also have
618 /// invalid operands or may have other results that need legalization, we just
619 /// know that (at least) one result needs vector splitting.
620 void DAGTypeLegalizer::SplitVectorResult(SDNode *N, unsigned ResNo) {
621   DEBUG(dbgs() << "Split node result: ";
622         N->dump(&DAG);
623         dbgs() << "\n");
624   SDValue Lo, Hi;
625
626   // See if the target wants to custom expand this node.
627   if (CustomLowerNode(N, N->getValueType(ResNo), true))
628     return;
629
630   switch (N->getOpcode()) {
631   default:
632 #ifndef NDEBUG
633     dbgs() << "SplitVectorResult #" << ResNo << ": ";
634     N->dump(&DAG);
635     dbgs() << "\n";
636 #endif
637     report_fatal_error("Do not know how to split the result of this "
638                        "operator!\n");
639
640   case ISD::MERGE_VALUES: SplitRes_MERGE_VALUES(N, ResNo, Lo, Hi); break;
641   case ISD::VSELECT:
642   case ISD::SELECT:       SplitRes_SELECT(N, Lo, Hi); break;
643   case ISD::SELECT_CC:    SplitRes_SELECT_CC(N, Lo, Hi); break;
644   case ISD::UNDEF:        SplitRes_UNDEF(N, Lo, Hi); break;
645   case ISD::BITCAST:           SplitVecRes_BITCAST(N, Lo, Hi); break;
646   case ISD::BUILD_VECTOR:      SplitVecRes_BUILD_VECTOR(N, Lo, Hi); break;
647   case ISD::CONCAT_VECTORS:    SplitVecRes_CONCAT_VECTORS(N, Lo, Hi); break;
648   case ISD::EXTRACT_SUBVECTOR: SplitVecRes_EXTRACT_SUBVECTOR(N, Lo, Hi); break;
649   case ISD::INSERT_SUBVECTOR:  SplitVecRes_INSERT_SUBVECTOR(N, Lo, Hi); break;
650   case ISD::FP_ROUND_INREG:    SplitVecRes_InregOp(N, Lo, Hi); break;
651   case ISD::FPOWI:             SplitVecRes_FPOWI(N, Lo, Hi); break;
652   case ISD::FCOPYSIGN:         SplitVecRes_FCOPYSIGN(N, Lo, Hi); break;
653   case ISD::INSERT_VECTOR_ELT: SplitVecRes_INSERT_VECTOR_ELT(N, Lo, Hi); break;
654   case ISD::SCALAR_TO_VECTOR:  SplitVecRes_SCALAR_TO_VECTOR(N, Lo, Hi); break;
655   case ISD::SIGN_EXTEND_INREG: SplitVecRes_InregOp(N, Lo, Hi); break;
656   case ISD::LOAD:
657     SplitVecRes_LOAD(cast<LoadSDNode>(N), Lo, Hi);
658     break;
659   case ISD::MLOAD:
660     SplitVecRes_MLOAD(cast<MaskedLoadSDNode>(N), Lo, Hi);
661     break;
662   case ISD::MGATHER:
663     SplitVecRes_MGATHER(cast<MaskedGatherSDNode>(N), Lo, Hi);
664     break;
665   case ISD::SETCC:
666     SplitVecRes_SETCC(N, Lo, Hi);
667     break;
668   case ISD::VECTOR_SHUFFLE:
669     SplitVecRes_VECTOR_SHUFFLE(cast<ShuffleVectorSDNode>(N), Lo, Hi);
670     break;
671
672   case ISD::ANY_EXTEND_VECTOR_INREG:
673   case ISD::SIGN_EXTEND_VECTOR_INREG:
674   case ISD::ZERO_EXTEND_VECTOR_INREG:
675     SplitVecRes_ExtVecInRegOp(N, Lo, Hi);
676     break;
677
678   case ISD::BITREVERSE:
679   case ISD::BSWAP:
680   case ISD::CTLZ:
681   case ISD::CTTZ:
682   case ISD::CTLZ_ZERO_UNDEF:
683   case ISD::CTTZ_ZERO_UNDEF:
684   case ISD::CTPOP:
685   case ISD::FABS:
686   case ISD::FCEIL:
687   case ISD::FCOS:
688   case ISD::FEXP:
689   case ISD::FEXP2:
690   case ISD::FFLOOR:
691   case ISD::FLOG:
692   case ISD::FLOG10:
693   case ISD::FLOG2:
694   case ISD::FNEARBYINT:
695   case ISD::FNEG:
696   case ISD::FP_EXTEND:
697   case ISD::FP_ROUND:
698   case ISD::FP_TO_SINT:
699   case ISD::FP_TO_UINT:
700   case ISD::FRINT:
701   case ISD::FROUND:
702   case ISD::FSIN:
703   case ISD::FSQRT:
704   case ISD::FTRUNC:
705   case ISD::SINT_TO_FP:
706   case ISD::TRUNCATE:
707   case ISD::UINT_TO_FP:
708   case ISD::FCANONICALIZE:
709     SplitVecRes_UnaryOp(N, Lo, Hi);
710     break;
711
712   case ISD::ANY_EXTEND:
713   case ISD::SIGN_EXTEND:
714   case ISD::ZERO_EXTEND:
715     SplitVecRes_ExtendOp(N, Lo, Hi);
716     break;
717
718   case ISD::ADD:
719   case ISD::SUB:
720   case ISD::MUL:
721   case ISD::MULHS:
722   case ISD::MULHU:
723   case ISD::FADD:
724   case ISD::FSUB:
725   case ISD::FMUL:
726   case ISD::FMINNUM:
727   case ISD::FMAXNUM:
728   case ISD::FMINNAN:
729   case ISD::FMAXNAN:
730   case ISD::SDIV:
731   case ISD::UDIV:
732   case ISD::FDIV:
733   case ISD::FPOW:
734   case ISD::AND:
735   case ISD::OR:
736   case ISD::XOR:
737   case ISD::SHL:
738   case ISD::SRA:
739   case ISD::SRL:
740   case ISD::UREM:
741   case ISD::SREM:
742   case ISD::FREM:
743   case ISD::SMIN:
744   case ISD::SMAX:
745   case ISD::UMIN:
746   case ISD::UMAX:
747     SplitVecRes_BinOp(N, Lo, Hi);
748     break;
749   case ISD::FMA:
750     SplitVecRes_TernaryOp(N, Lo, Hi);
751     break;
752   }
753
754   // If Lo/Hi is null, the sub-method took care of registering results etc.
755   if (Lo.getNode())
756     SetSplitVector(SDValue(N, ResNo), Lo, Hi);
757 }
758
759 void DAGTypeLegalizer::SplitVecRes_BinOp(SDNode *N, SDValue &Lo,
760                                          SDValue &Hi) {
761   SDValue LHSLo, LHSHi;
762   GetSplitVector(N->getOperand(0), LHSLo, LHSHi);
763   SDValue RHSLo, RHSHi;
764   GetSplitVector(N->getOperand(1), RHSLo, RHSHi);
765   SDLoc dl(N);
766
767   const SDNodeFlags Flags = N->getFlags();
768   unsigned Opcode = N->getOpcode();
769   Lo = DAG.getNode(Opcode, dl, LHSLo.getValueType(), LHSLo, RHSLo, Flags);
770   Hi = DAG.getNode(Opcode, dl, LHSHi.getValueType(), LHSHi, RHSHi, Flags);
771 }
772
773 void DAGTypeLegalizer::SplitVecRes_TernaryOp(SDNode *N, SDValue &Lo,
774                                              SDValue &Hi) {
775   SDValue Op0Lo, Op0Hi;
776   GetSplitVector(N->getOperand(0), Op0Lo, Op0Hi);
777   SDValue Op1Lo, Op1Hi;
778   GetSplitVector(N->getOperand(1), Op1Lo, Op1Hi);
779   SDValue Op2Lo, Op2Hi;
780   GetSplitVector(N->getOperand(2), Op2Lo, Op2Hi);
781   SDLoc dl(N);
782
783   Lo = DAG.getNode(N->getOpcode(), dl, Op0Lo.getValueType(),
784                    Op0Lo, Op1Lo, Op2Lo);
785   Hi = DAG.getNode(N->getOpcode(), dl, Op0Hi.getValueType(),
786                    Op0Hi, Op1Hi, Op2Hi);
787 }
788
789 void DAGTypeLegalizer::SplitVecRes_BITCAST(SDNode *N, SDValue &Lo,
790                                            SDValue &Hi) {
791   // We know the result is a vector.  The input may be either a vector or a
792   // scalar value.
793   EVT LoVT, HiVT;
794   std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(N->getValueType(0));
795   SDLoc dl(N);
796
797   SDValue InOp = N->getOperand(0);
798   EVT InVT = InOp.getValueType();
799
800   // Handle some special cases efficiently.
801   switch (getTypeAction(InVT)) {
802   case TargetLowering::TypeLegal:
803   case TargetLowering::TypePromoteInteger:
804   case TargetLowering::TypePromoteFloat:
805   case TargetLowering::TypeSoftenFloat:
806   case TargetLowering::TypeScalarizeVector:
807   case TargetLowering::TypeWidenVector:
808     break;
809   case TargetLowering::TypeExpandInteger:
810   case TargetLowering::TypeExpandFloat:
811     // A scalar to vector conversion, where the scalar needs expansion.
812     // If the vector is being split in two then we can just convert the
813     // expanded pieces.
814     if (LoVT == HiVT) {
815       GetExpandedOp(InOp, Lo, Hi);
816       if (DAG.getDataLayout().isBigEndian())
817         std::swap(Lo, Hi);
818       Lo = DAG.getNode(ISD::BITCAST, dl, LoVT, Lo);
819       Hi = DAG.getNode(ISD::BITCAST, dl, HiVT, Hi);
820       return;
821     }
822     break;
823   case TargetLowering::TypeSplitVector:
824     // If the input is a vector that needs to be split, convert each split
825     // piece of the input now.
826     GetSplitVector(InOp, Lo, Hi);
827     Lo = DAG.getNode(ISD::BITCAST, dl, LoVT, Lo);
828     Hi = DAG.getNode(ISD::BITCAST, dl, HiVT, Hi);
829     return;
830   }
831
832   // In the general case, convert the input to an integer and split it by hand.
833   EVT LoIntVT = EVT::getIntegerVT(*DAG.getContext(), LoVT.getSizeInBits());
834   EVT HiIntVT = EVT::getIntegerVT(*DAG.getContext(), HiVT.getSizeInBits());
835   if (DAG.getDataLayout().isBigEndian())
836     std::swap(LoIntVT, HiIntVT);
837
838   SplitInteger(BitConvertToInteger(InOp), LoIntVT, HiIntVT, Lo, Hi);
839
840   if (DAG.getDataLayout().isBigEndian())
841     std::swap(Lo, Hi);
842   Lo = DAG.getNode(ISD::BITCAST, dl, LoVT, Lo);
843   Hi = DAG.getNode(ISD::BITCAST, dl, HiVT, Hi);
844 }
845
846 void DAGTypeLegalizer::SplitVecRes_BUILD_VECTOR(SDNode *N, SDValue &Lo,
847                                                 SDValue &Hi) {
848   EVT LoVT, HiVT;
849   SDLoc dl(N);
850   std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(N->getValueType(0));
851   unsigned LoNumElts = LoVT.getVectorNumElements();
852   SmallVector<SDValue, 8> LoOps(N->op_begin(), N->op_begin()+LoNumElts);
853   Lo = DAG.getBuildVector(LoVT, dl, LoOps);
854
855   SmallVector<SDValue, 8> HiOps(N->op_begin()+LoNumElts, N->op_end());
856   Hi = DAG.getBuildVector(HiVT, dl, HiOps);
857 }
858
859 void DAGTypeLegalizer::SplitVecRes_CONCAT_VECTORS(SDNode *N, SDValue &Lo,
860                                                   SDValue &Hi) {
861   assert(!(N->getNumOperands() & 1) && "Unsupported CONCAT_VECTORS");
862   SDLoc dl(N);
863   unsigned NumSubvectors = N->getNumOperands() / 2;
864   if (NumSubvectors == 1) {
865     Lo = N->getOperand(0);
866     Hi = N->getOperand(1);
867     return;
868   }
869
870   EVT LoVT, HiVT;
871   std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(N->getValueType(0));
872
873   SmallVector<SDValue, 8> LoOps(N->op_begin(), N->op_begin()+NumSubvectors);
874   Lo = DAG.getNode(ISD::CONCAT_VECTORS, dl, LoVT, LoOps);
875
876   SmallVector<SDValue, 8> HiOps(N->op_begin()+NumSubvectors, N->op_end());
877   Hi = DAG.getNode(ISD::CONCAT_VECTORS, dl, HiVT, HiOps);
878 }
879
880 void DAGTypeLegalizer::SplitVecRes_EXTRACT_SUBVECTOR(SDNode *N, SDValue &Lo,
881                                                      SDValue &Hi) {
882   SDValue Vec = N->getOperand(0);
883   SDValue Idx = N->getOperand(1);
884   SDLoc dl(N);
885
886   EVT LoVT, HiVT;
887   std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(N->getValueType(0));
888
889   Lo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, LoVT, Vec, Idx);
890   uint64_t IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
891   Hi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, HiVT, Vec,
892                    DAG.getConstant(IdxVal + LoVT.getVectorNumElements(), dl,
893                                    TLI.getVectorIdxTy(DAG.getDataLayout())));
894 }
895
896 void DAGTypeLegalizer::SplitVecRes_INSERT_SUBVECTOR(SDNode *N, SDValue &Lo,
897                                                     SDValue &Hi) {
898   SDValue Vec = N->getOperand(0);
899   SDValue SubVec = N->getOperand(1);
900   SDValue Idx = N->getOperand(2);
901   SDLoc dl(N);
902   GetSplitVector(Vec, Lo, Hi);
903
904   EVT VecVT = Vec.getValueType();
905   unsigned VecElems = VecVT.getVectorNumElements();
906   unsigned SubElems = SubVec.getValueType().getVectorNumElements();
907
908   // If we know the index is 0, and we know the subvector doesn't cross the
909   // boundary between the halves, we can avoid spilling the vector, and insert
910   // into the lower half of the split vector directly.
911   // TODO: The IdxVal == 0 constraint is artificial, we could do this whenever
912   // the index is constant and there is no boundary crossing. But those cases
913   // don't seem to get hit in practice.
914   if (ConstantSDNode *ConstIdx = dyn_cast<ConstantSDNode>(Idx)) {
915     unsigned IdxVal = ConstIdx->getZExtValue();
916     if ((IdxVal == 0) && (IdxVal + SubElems <= VecElems / 2)) {
917       EVT LoVT, HiVT;
918       std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(N->getValueType(0));
919       Lo = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, LoVT, Lo, SubVec, Idx);
920       return;
921     }
922   }
923
924   // Spill the vector to the stack.
925   SDValue StackPtr = DAG.CreateStackTemporary(VecVT);
926   SDValue Store =
927       DAG.getStore(DAG.getEntryNode(), dl, Vec, StackPtr, MachinePointerInfo());
928
929   // Store the new subvector into the specified index.
930   SDValue SubVecPtr = TLI.getVectorElementPointer(DAG, StackPtr, VecVT, Idx);
931   Type *VecType = VecVT.getTypeForEVT(*DAG.getContext());
932   unsigned Alignment = DAG.getDataLayout().getPrefTypeAlignment(VecType);
933   Store = DAG.getStore(Store, dl, SubVec, SubVecPtr, MachinePointerInfo());
934
935   // Load the Lo part from the stack slot.
936   Lo =
937       DAG.getLoad(Lo.getValueType(), dl, Store, StackPtr, MachinePointerInfo());
938
939   // Increment the pointer to the other part.
940   unsigned IncrementSize = Lo.getValueSizeInBits() / 8;
941   StackPtr =
942       DAG.getNode(ISD::ADD, dl, StackPtr.getValueType(), StackPtr,
943                   DAG.getConstant(IncrementSize, dl, StackPtr.getValueType()));
944
945   // Load the Hi part from the stack slot.
946   Hi = DAG.getLoad(Hi.getValueType(), dl, Store, StackPtr, MachinePointerInfo(),
947                    MinAlign(Alignment, IncrementSize));
948 }
949
950 void DAGTypeLegalizer::SplitVecRes_FPOWI(SDNode *N, SDValue &Lo,
951                                          SDValue &Hi) {
952   SDLoc dl(N);
953   GetSplitVector(N->getOperand(0), Lo, Hi);
954   Lo = DAG.getNode(ISD::FPOWI, dl, Lo.getValueType(), Lo, N->getOperand(1));
955   Hi = DAG.getNode(ISD::FPOWI, dl, Hi.getValueType(), Hi, N->getOperand(1));
956 }
957
958 void DAGTypeLegalizer::SplitVecRes_FCOPYSIGN(SDNode *N, SDValue &Lo,
959                                              SDValue &Hi) {
960   SDValue LHSLo, LHSHi;
961   GetSplitVector(N->getOperand(0), LHSLo, LHSHi);
962   SDLoc DL(N);
963
964   SDValue RHSLo, RHSHi;
965   SDValue RHS = N->getOperand(1);
966   EVT RHSVT = RHS.getValueType();
967   if (getTypeAction(RHSVT) == TargetLowering::TypeSplitVector)
968     GetSplitVector(RHS, RHSLo, RHSHi);
969   else
970     std::tie(RHSLo, RHSHi) = DAG.SplitVector(RHS, SDLoc(RHS));
971
972
973   Lo = DAG.getNode(ISD::FCOPYSIGN, DL, LHSLo.getValueType(), LHSLo, RHSLo);
974   Hi = DAG.getNode(ISD::FCOPYSIGN, DL, LHSHi.getValueType(), LHSHi, RHSHi);
975 }
976
977 void DAGTypeLegalizer::SplitVecRes_InregOp(SDNode *N, SDValue &Lo,
978                                            SDValue &Hi) {
979   SDValue LHSLo, LHSHi;
980   GetSplitVector(N->getOperand(0), LHSLo, LHSHi);
981   SDLoc dl(N);
982
983   EVT LoVT, HiVT;
984   std::tie(LoVT, HiVT) =
985     DAG.GetSplitDestVTs(cast<VTSDNode>(N->getOperand(1))->getVT());
986
987   Lo = DAG.getNode(N->getOpcode(), dl, LHSLo.getValueType(), LHSLo,
988                    DAG.getValueType(LoVT));
989   Hi = DAG.getNode(N->getOpcode(), dl, LHSHi.getValueType(), LHSHi,
990                    DAG.getValueType(HiVT));
991 }
992
993 void DAGTypeLegalizer::SplitVecRes_ExtVecInRegOp(SDNode *N, SDValue &Lo,
994                                                  SDValue &Hi) {
995   unsigned Opcode = N->getOpcode();
996   SDValue N0 = N->getOperand(0);
997
998   SDLoc dl(N);
999   SDValue InLo, InHi;
1000
1001   if (getTypeAction(N0.getValueType()) == TargetLowering::TypeSplitVector)
1002     GetSplitVector(N0, InLo, InHi);
1003   else
1004     std::tie(InLo, InHi) = DAG.SplitVectorOperand(N, 0);
1005
1006   EVT InLoVT = InLo.getValueType();
1007   unsigned InNumElements = InLoVT.getVectorNumElements();
1008
1009   EVT OutLoVT, OutHiVT;
1010   std::tie(OutLoVT, OutHiVT) = DAG.GetSplitDestVTs(N->getValueType(0));
1011   unsigned OutNumElements = OutLoVT.getVectorNumElements();
1012   assert((2 * OutNumElements) <= InNumElements &&
1013          "Illegal extend vector in reg split");
1014
1015   // *_EXTEND_VECTOR_INREG instructions extend the lowest elements of the
1016   // input vector (i.e. we only use InLo):
1017   // OutLo will extend the first OutNumElements from InLo.
1018   // OutHi will extend the next OutNumElements from InLo.
1019
1020   // Shuffle the elements from InLo for OutHi into the bottom elements to
1021   // create a 'fake' InHi.
1022   SmallVector<int, 8> SplitHi(InNumElements, -1);
1023   for (unsigned i = 0; i != OutNumElements; ++i)
1024     SplitHi[i] = i + OutNumElements;
1025   InHi = DAG.getVectorShuffle(InLoVT, dl, InLo, DAG.getUNDEF(InLoVT), SplitHi);
1026
1027   Lo = DAG.getNode(Opcode, dl, OutLoVT, InLo);
1028   Hi = DAG.getNode(Opcode, dl, OutHiVT, InHi);
1029 }
1030
1031 void DAGTypeLegalizer::SplitVecRes_INSERT_VECTOR_ELT(SDNode *N, SDValue &Lo,
1032                                                      SDValue &Hi) {
1033   SDValue Vec = N->getOperand(0);
1034   SDValue Elt = N->getOperand(1);
1035   SDValue Idx = N->getOperand(2);
1036   SDLoc dl(N);
1037   GetSplitVector(Vec, Lo, Hi);
1038
1039   if (ConstantSDNode *CIdx = dyn_cast<ConstantSDNode>(Idx)) {
1040     unsigned IdxVal = CIdx->getZExtValue();
1041     unsigned LoNumElts = Lo.getValueType().getVectorNumElements();
1042     if (IdxVal < LoNumElts)
1043       Lo = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl,
1044                        Lo.getValueType(), Lo, Elt, Idx);
1045     else
1046       Hi =
1047           DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, Hi.getValueType(), Hi, Elt,
1048                       DAG.getConstant(IdxVal - LoNumElts, dl,
1049                                       TLI.getVectorIdxTy(DAG.getDataLayout())));
1050     return;
1051   }
1052
1053   // See if the target wants to custom expand this node.
1054   if (CustomLowerNode(N, N->getValueType(0), true))
1055     return;
1056
1057   // Spill the vector to the stack.
1058   EVT VecVT = Vec.getValueType();
1059   EVT EltVT = VecVT.getVectorElementType();
1060   SDValue StackPtr = DAG.CreateStackTemporary(VecVT);
1061   auto &MF = DAG.getMachineFunction();
1062   auto FrameIndex = cast<FrameIndexSDNode>(StackPtr.getNode())->getIndex();
1063   auto PtrInfo = MachinePointerInfo::getFixedStack(MF, FrameIndex);
1064   SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Vec, StackPtr, PtrInfo);
1065
1066   // Store the new element.  This may be larger than the vector element type,
1067   // so use a truncating store.
1068   SDValue EltPtr = TLI.getVectorElementPointer(DAG, StackPtr, VecVT, Idx);
1069   Type *VecType = VecVT.getTypeForEVT(*DAG.getContext());
1070   unsigned Alignment = DAG.getDataLayout().getPrefTypeAlignment(VecType);
1071   Store = DAG.getTruncStore(Store, dl, Elt, EltPtr,
1072                             MachinePointerInfo::getUnknownStack(MF), EltVT);
1073
1074   // Load the Lo part from the stack slot.
1075   Lo = DAG.getLoad(Lo.getValueType(), dl, Store, StackPtr, PtrInfo);
1076
1077   // Increment the pointer to the other part.
1078   unsigned IncrementSize = Lo.getValueSizeInBits() / 8;
1079   StackPtr = DAG.getNode(ISD::ADD, dl, StackPtr.getValueType(), StackPtr,
1080                          DAG.getConstant(IncrementSize, dl,
1081                                          StackPtr.getValueType()));
1082
1083   // Load the Hi part from the stack slot.
1084   Hi = DAG.getLoad(Hi.getValueType(), dl, Store, StackPtr,
1085                    PtrInfo.getWithOffset(IncrementSize),
1086                    MinAlign(Alignment, IncrementSize));
1087 }
1088
1089 void DAGTypeLegalizer::SplitVecRes_SCALAR_TO_VECTOR(SDNode *N, SDValue &Lo,
1090                                                     SDValue &Hi) {
1091   EVT LoVT, HiVT;
1092   SDLoc dl(N);
1093   std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(N->getValueType(0));
1094   Lo = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, LoVT, N->getOperand(0));
1095   Hi = DAG.getUNDEF(HiVT);
1096 }
1097
1098 void DAGTypeLegalizer::SplitVecRes_LOAD(LoadSDNode *LD, SDValue &Lo,
1099                                         SDValue &Hi) {
1100   assert(ISD::isUNINDEXEDLoad(LD) && "Indexed load during type legalization!");
1101   EVT LoVT, HiVT;
1102   SDLoc dl(LD);
1103   std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(LD->getValueType(0));
1104
1105   ISD::LoadExtType ExtType = LD->getExtensionType();
1106   SDValue Ch = LD->getChain();
1107   SDValue Ptr = LD->getBasePtr();
1108   SDValue Offset = DAG.getUNDEF(Ptr.getValueType());
1109   EVT MemoryVT = LD->getMemoryVT();
1110   unsigned Alignment = LD->getOriginalAlignment();
1111   MachineMemOperand::Flags MMOFlags = LD->getMemOperand()->getFlags();
1112   AAMDNodes AAInfo = LD->getAAInfo();
1113
1114   EVT LoMemVT, HiMemVT;
1115   std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT);
1116
1117   Lo = DAG.getLoad(ISD::UNINDEXED, ExtType, LoVT, dl, Ch, Ptr, Offset,
1118                    LD->getPointerInfo(), LoMemVT, Alignment, MMOFlags, AAInfo);
1119
1120   unsigned IncrementSize = LoMemVT.getSizeInBits()/8;
1121   Ptr = DAG.getObjectPtrOffset(dl, Ptr, IncrementSize);
1122   Hi = DAG.getLoad(ISD::UNINDEXED, ExtType, HiVT, dl, Ch, Ptr, Offset,
1123                    LD->getPointerInfo().getWithOffset(IncrementSize), HiMemVT,
1124                    Alignment, MMOFlags, AAInfo);
1125
1126   // Build a factor node to remember that this load is independent of the
1127   // other one.
1128   Ch = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Lo.getValue(1),
1129                    Hi.getValue(1));
1130
1131   // Legalize the chain result - switch anything that used the old chain to
1132   // use the new one.
1133   ReplaceValueWith(SDValue(LD, 1), Ch);
1134 }
1135
1136 void DAGTypeLegalizer::SplitVecRes_MLOAD(MaskedLoadSDNode *MLD,
1137                                          SDValue &Lo, SDValue &Hi) {
1138   EVT LoVT, HiVT;
1139   SDLoc dl(MLD);
1140   std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(MLD->getValueType(0));
1141
1142   SDValue Ch = MLD->getChain();
1143   SDValue Ptr = MLD->getBasePtr();
1144   SDValue Mask = MLD->getMask();
1145   SDValue Src0 = MLD->getSrc0();
1146   unsigned Alignment = MLD->getOriginalAlignment();
1147   ISD::LoadExtType ExtType = MLD->getExtensionType();
1148
1149   // if Alignment is equal to the vector size,
1150   // take the half of it for the second part
1151   unsigned SecondHalfAlignment =
1152     (Alignment == MLD->getValueType(0).getSizeInBits()/8) ?
1153      Alignment/2 : Alignment;
1154
1155   // Split Mask operand
1156   SDValue MaskLo, MaskHi;
1157   if (getTypeAction(Mask.getValueType()) == TargetLowering::TypeSplitVector)
1158     GetSplitVector(Mask, MaskLo, MaskHi);
1159   else
1160     std::tie(MaskLo, MaskHi) = DAG.SplitVector(Mask, dl);
1161
1162   EVT MemoryVT = MLD->getMemoryVT();
1163   EVT LoMemVT, HiMemVT;
1164   std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT);
1165
1166   SDValue Src0Lo, Src0Hi;
1167   if (getTypeAction(Src0.getValueType()) == TargetLowering::TypeSplitVector)
1168     GetSplitVector(Src0, Src0Lo, Src0Hi);
1169   else
1170     std::tie(Src0Lo, Src0Hi) = DAG.SplitVector(Src0, dl);
1171
1172   MachineMemOperand *MMO = DAG.getMachineFunction().
1173     getMachineMemOperand(MLD->getPointerInfo(),
1174                          MachineMemOperand::MOLoad,  LoMemVT.getStoreSize(),
1175                          Alignment, MLD->getAAInfo(), MLD->getRanges());
1176
1177   Lo = DAG.getMaskedLoad(LoVT, dl, Ch, Ptr, MaskLo, Src0Lo, LoMemVT, MMO,
1178                          ExtType, MLD->isExpandingLoad());
1179
1180   Ptr = TLI.IncrementMemoryAddress(Ptr, MaskLo, dl, LoMemVT, DAG,
1181                                    MLD->isExpandingLoad());
1182
1183   MMO = DAG.getMachineFunction().
1184     getMachineMemOperand(MLD->getPointerInfo(),
1185                          MachineMemOperand::MOLoad,  HiMemVT.getStoreSize(),
1186                          SecondHalfAlignment, MLD->getAAInfo(), MLD->getRanges());
1187
1188   Hi = DAG.getMaskedLoad(HiVT, dl, Ch, Ptr, MaskHi, Src0Hi, HiMemVT, MMO,
1189                          ExtType, MLD->isExpandingLoad());
1190
1191
1192   // Build a factor node to remember that this load is independent of the
1193   // other one.
1194   Ch = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Lo.getValue(1),
1195                    Hi.getValue(1));
1196
1197   // Legalize the chain result - switch anything that used the old chain to
1198   // use the new one.
1199   ReplaceValueWith(SDValue(MLD, 1), Ch);
1200
1201 }
1202
1203 void DAGTypeLegalizer::SplitVecRes_MGATHER(MaskedGatherSDNode *MGT,
1204                                          SDValue &Lo, SDValue &Hi) {
1205   EVT LoVT, HiVT;
1206   SDLoc dl(MGT);
1207   std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(MGT->getValueType(0));
1208
1209   SDValue Ch = MGT->getChain();
1210   SDValue Ptr = MGT->getBasePtr();
1211   SDValue Mask = MGT->getMask();
1212   SDValue Src0 = MGT->getValue();
1213   SDValue Index = MGT->getIndex();
1214   unsigned Alignment = MGT->getOriginalAlignment();
1215
1216   // Split Mask operand
1217   SDValue MaskLo, MaskHi;
1218   if (getTypeAction(Mask.getValueType()) == TargetLowering::TypeSplitVector)
1219     GetSplitVector(Mask, MaskLo, MaskHi);
1220   else
1221     std::tie(MaskLo, MaskHi) = DAG.SplitVector(Mask, dl);
1222
1223   EVT MemoryVT = MGT->getMemoryVT();
1224   EVT LoMemVT, HiMemVT;
1225   // Split MemoryVT
1226   std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT);
1227
1228   SDValue Src0Lo, Src0Hi;
1229   if (getTypeAction(Src0.getValueType()) == TargetLowering::TypeSplitVector)
1230     GetSplitVector(Src0, Src0Lo, Src0Hi);
1231   else
1232     std::tie(Src0Lo, Src0Hi) = DAG.SplitVector(Src0, dl);
1233
1234   SDValue IndexHi, IndexLo;
1235   if (getTypeAction(Index.getValueType()) == TargetLowering::TypeSplitVector)
1236     GetSplitVector(Index, IndexLo, IndexHi);
1237   else
1238     std::tie(IndexLo, IndexHi) = DAG.SplitVector(Index, dl);
1239
1240   MachineMemOperand *MMO = DAG.getMachineFunction().
1241     getMachineMemOperand(MGT->getPointerInfo(),
1242                          MachineMemOperand::MOLoad,  LoMemVT.getStoreSize(),
1243                          Alignment, MGT->getAAInfo(), MGT->getRanges());
1244
1245   SDValue OpsLo[] = {Ch, Src0Lo, MaskLo, Ptr, IndexLo};
1246   Lo = DAG.getMaskedGather(DAG.getVTList(LoVT, MVT::Other), LoVT, dl, OpsLo,
1247                            MMO);
1248
1249   SDValue OpsHi[] = {Ch, Src0Hi, MaskHi, Ptr, IndexHi};
1250   Hi = DAG.getMaskedGather(DAG.getVTList(HiVT, MVT::Other), HiVT, dl, OpsHi,
1251                            MMO);
1252
1253   // Build a factor node to remember that this load is independent of the
1254   // other one.
1255   Ch = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Lo.getValue(1),
1256                    Hi.getValue(1));
1257
1258   // Legalize the chain result - switch anything that used the old chain to
1259   // use the new one.
1260   ReplaceValueWith(SDValue(MGT, 1), Ch);
1261 }
1262
1263
1264 void DAGTypeLegalizer::SplitVecRes_SETCC(SDNode *N, SDValue &Lo, SDValue &Hi) {
1265   assert(N->getValueType(0).isVector() &&
1266          N->getOperand(0).getValueType().isVector() &&
1267          "Operand types must be vectors");
1268
1269   EVT LoVT, HiVT;
1270   SDLoc DL(N);
1271   std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(N->getValueType(0));
1272
1273   // If the input also splits, handle it directly. Otherwise split it by hand.
1274   SDValue LL, LH, RL, RH;
1275   if (getTypeAction(N->getOperand(0).getValueType()) ==
1276       TargetLowering::TypeSplitVector)
1277     GetSplitVector(N->getOperand(0), LL, LH);
1278   else
1279     std::tie(LL, LH) = DAG.SplitVectorOperand(N, 0);
1280
1281   if (getTypeAction(N->getOperand(1).getValueType()) ==
1282       TargetLowering::TypeSplitVector)
1283     GetSplitVector(N->getOperand(1), RL, RH);
1284   else
1285     std::tie(RL, RH) = DAG.SplitVectorOperand(N, 1);
1286
1287   Lo = DAG.getNode(N->getOpcode(), DL, LoVT, LL, RL, N->getOperand(2));
1288   Hi = DAG.getNode(N->getOpcode(), DL, HiVT, LH, RH, N->getOperand(2));
1289 }
1290
1291 void DAGTypeLegalizer::SplitVecRes_UnaryOp(SDNode *N, SDValue &Lo,
1292                                            SDValue &Hi) {
1293   // Get the dest types - they may not match the input types, e.g. int_to_fp.
1294   EVT LoVT, HiVT;
1295   SDLoc dl(N);
1296   std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(N->getValueType(0));
1297
1298   // If the input also splits, handle it directly for a compile time speedup.
1299   // Otherwise split it by hand.
1300   EVT InVT = N->getOperand(0).getValueType();
1301   if (getTypeAction(InVT) == TargetLowering::TypeSplitVector)
1302     GetSplitVector(N->getOperand(0), Lo, Hi);
1303   else
1304     std::tie(Lo, Hi) = DAG.SplitVectorOperand(N, 0);
1305
1306   if (N->getOpcode() == ISD::FP_ROUND) {
1307     Lo = DAG.getNode(N->getOpcode(), dl, LoVT, Lo, N->getOperand(1));
1308     Hi = DAG.getNode(N->getOpcode(), dl, HiVT, Hi, N->getOperand(1));
1309   } else {
1310     Lo = DAG.getNode(N->getOpcode(), dl, LoVT, Lo);
1311     Hi = DAG.getNode(N->getOpcode(), dl, HiVT, Hi);
1312   }
1313 }
1314
1315 void DAGTypeLegalizer::SplitVecRes_ExtendOp(SDNode *N, SDValue &Lo,
1316                                             SDValue &Hi) {
1317   SDLoc dl(N);
1318   EVT SrcVT = N->getOperand(0).getValueType();
1319   EVT DestVT = N->getValueType(0);
1320   EVT LoVT, HiVT;
1321   std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(DestVT);
1322
1323   // We can do better than a generic split operation if the extend is doing
1324   // more than just doubling the width of the elements and the following are
1325   // true:
1326   //   - The number of vector elements is even,
1327   //   - the source type is legal,
1328   //   - the type of a split source is illegal,
1329   //   - the type of an extended (by doubling element size) source is legal, and
1330   //   - the type of that extended source when split is legal.
1331   //
1332   // This won't necessarily completely legalize the operation, but it will
1333   // more effectively move in the right direction and prevent falling down
1334   // to scalarization in many cases due to the input vector being split too
1335   // far.
1336   unsigned NumElements = SrcVT.getVectorNumElements();
1337   if ((NumElements & 1) == 0 &&
1338       SrcVT.getSizeInBits() * 2 < DestVT.getSizeInBits()) {
1339     LLVMContext &Ctx = *DAG.getContext();
1340     EVT NewSrcVT = SrcVT.widenIntegerVectorElementType(Ctx);
1341     EVT SplitSrcVT = SrcVT.getHalfNumVectorElementsVT(Ctx);
1342
1343     EVT SplitLoVT, SplitHiVT;
1344     std::tie(SplitLoVT, SplitHiVT) = DAG.GetSplitDestVTs(NewSrcVT);
1345     if (TLI.isTypeLegal(SrcVT) && !TLI.isTypeLegal(SplitSrcVT) &&
1346         TLI.isTypeLegal(NewSrcVT) && TLI.isTypeLegal(SplitLoVT)) {
1347       DEBUG(dbgs() << "Split vector extend via incremental extend:";
1348             N->dump(&DAG); dbgs() << "\n");
1349       // Extend the source vector by one step.
1350       SDValue NewSrc =
1351           DAG.getNode(N->getOpcode(), dl, NewSrcVT, N->getOperand(0));
1352       // Get the low and high halves of the new, extended one step, vector.
1353       std::tie(Lo, Hi) = DAG.SplitVector(NewSrc, dl);
1354       // Extend those vector halves the rest of the way.
1355       Lo = DAG.getNode(N->getOpcode(), dl, LoVT, Lo);
1356       Hi = DAG.getNode(N->getOpcode(), dl, HiVT, Hi);
1357       return;
1358     }
1359   }
1360   // Fall back to the generic unary operator splitting otherwise.
1361   SplitVecRes_UnaryOp(N, Lo, Hi);
1362 }
1363
1364 void DAGTypeLegalizer::SplitVecRes_VECTOR_SHUFFLE(ShuffleVectorSDNode *N,
1365                                                   SDValue &Lo, SDValue &Hi) {
1366   // The low and high parts of the original input give four input vectors.
1367   SDValue Inputs[4];
1368   SDLoc dl(N);
1369   GetSplitVector(N->getOperand(0), Inputs[0], Inputs[1]);
1370   GetSplitVector(N->getOperand(1), Inputs[2], Inputs[3]);
1371   EVT NewVT = Inputs[0].getValueType();
1372   unsigned NewElts = NewVT.getVectorNumElements();
1373
1374   // If Lo or Hi uses elements from at most two of the four input vectors, then
1375   // express it as a vector shuffle of those two inputs.  Otherwise extract the
1376   // input elements by hand and construct the Lo/Hi output using a BUILD_VECTOR.
1377   SmallVector<int, 16> Ops;
1378   for (unsigned High = 0; High < 2; ++High) {
1379     SDValue &Output = High ? Hi : Lo;
1380
1381     // Build a shuffle mask for the output, discovering on the fly which
1382     // input vectors to use as shuffle operands (recorded in InputUsed).
1383     // If building a suitable shuffle vector proves too hard, then bail
1384     // out with useBuildVector set.
1385     unsigned InputUsed[2] = { -1U, -1U }; // Not yet discovered.
1386     unsigned FirstMaskIdx = High * NewElts;
1387     bool useBuildVector = false;
1388     for (unsigned MaskOffset = 0; MaskOffset < NewElts; ++MaskOffset) {
1389       // The mask element.  This indexes into the input.
1390       int Idx = N->getMaskElt(FirstMaskIdx + MaskOffset);
1391
1392       // The input vector this mask element indexes into.
1393       unsigned Input = (unsigned)Idx / NewElts;
1394
1395       if (Input >= array_lengthof(Inputs)) {
1396         // The mask element does not index into any input vector.
1397         Ops.push_back(-1);
1398         continue;
1399       }
1400
1401       // Turn the index into an offset from the start of the input vector.
1402       Idx -= Input * NewElts;
1403
1404       // Find or create a shuffle vector operand to hold this input.
1405       unsigned OpNo;
1406       for (OpNo = 0; OpNo < array_lengthof(InputUsed); ++OpNo) {
1407         if (InputUsed[OpNo] == Input) {
1408           // This input vector is already an operand.
1409           break;
1410         } else if (InputUsed[OpNo] == -1U) {
1411           // Create a new operand for this input vector.
1412           InputUsed[OpNo] = Input;
1413           break;
1414         }
1415       }
1416
1417       if (OpNo >= array_lengthof(InputUsed)) {
1418         // More than two input vectors used!  Give up on trying to create a
1419         // shuffle vector.  Insert all elements into a BUILD_VECTOR instead.
1420         useBuildVector = true;
1421         break;
1422       }
1423
1424       // Add the mask index for the new shuffle vector.
1425       Ops.push_back(Idx + OpNo * NewElts);
1426     }
1427
1428     if (useBuildVector) {
1429       EVT EltVT = NewVT.getVectorElementType();
1430       SmallVector<SDValue, 16> SVOps;
1431
1432       // Extract the input elements by hand.
1433       for (unsigned MaskOffset = 0; MaskOffset < NewElts; ++MaskOffset) {
1434         // The mask element.  This indexes into the input.
1435         int Idx = N->getMaskElt(FirstMaskIdx + MaskOffset);
1436
1437         // The input vector this mask element indexes into.
1438         unsigned Input = (unsigned)Idx / NewElts;
1439
1440         if (Input >= array_lengthof(Inputs)) {
1441           // The mask element is "undef" or indexes off the end of the input.
1442           SVOps.push_back(DAG.getUNDEF(EltVT));
1443           continue;
1444         }
1445
1446         // Turn the index into an offset from the start of the input vector.
1447         Idx -= Input * NewElts;
1448
1449         // Extract the vector element by hand.
1450         SVOps.push_back(DAG.getNode(
1451             ISD::EXTRACT_VECTOR_ELT, dl, EltVT, Inputs[Input],
1452             DAG.getConstant(Idx, dl, TLI.getVectorIdxTy(DAG.getDataLayout()))));
1453       }
1454
1455       // Construct the Lo/Hi output using a BUILD_VECTOR.
1456       Output = DAG.getBuildVector(NewVT, dl, SVOps);
1457     } else if (InputUsed[0] == -1U) {
1458       // No input vectors were used!  The result is undefined.
1459       Output = DAG.getUNDEF(NewVT);
1460     } else {
1461       SDValue Op0 = Inputs[InputUsed[0]];
1462       // If only one input was used, use an undefined vector for the other.
1463       SDValue Op1 = InputUsed[1] == -1U ?
1464         DAG.getUNDEF(NewVT) : Inputs[InputUsed[1]];
1465       // At least one input vector was used.  Create a new shuffle vector.
1466       Output =  DAG.getVectorShuffle(NewVT, dl, Op0, Op1, Ops);
1467     }
1468
1469     Ops.clear();
1470   }
1471 }
1472
1473
1474 //===----------------------------------------------------------------------===//
1475 //  Operand Vector Splitting
1476 //===----------------------------------------------------------------------===//
1477
1478 /// This method is called when the specified operand of the specified node is
1479 /// found to need vector splitting. At this point, all of the result types of
1480 /// the node are known to be legal, but other operands of the node may need
1481 /// legalization as well as the specified one.
1482 bool DAGTypeLegalizer::SplitVectorOperand(SDNode *N, unsigned OpNo) {
1483   DEBUG(dbgs() << "Split node operand: ";
1484         N->dump(&DAG);
1485         dbgs() << "\n");
1486   SDValue Res = SDValue();
1487
1488   // See if the target wants to custom split this node.
1489   if (CustomLowerNode(N, N->getOperand(OpNo).getValueType(), false))
1490     return false;
1491
1492   if (!Res.getNode()) {
1493     switch (N->getOpcode()) {
1494     default:
1495 #ifndef NDEBUG
1496       dbgs() << "SplitVectorOperand Op #" << OpNo << ": ";
1497       N->dump(&DAG);
1498       dbgs() << "\n";
1499 #endif
1500       report_fatal_error("Do not know how to split this operator's "
1501                          "operand!\n");
1502
1503     case ISD::SETCC:             Res = SplitVecOp_VSETCC(N); break;
1504     case ISD::BITCAST:           Res = SplitVecOp_BITCAST(N); break;
1505     case ISD::EXTRACT_SUBVECTOR: Res = SplitVecOp_EXTRACT_SUBVECTOR(N); break;
1506     case ISD::EXTRACT_VECTOR_ELT:Res = SplitVecOp_EXTRACT_VECTOR_ELT(N); break;
1507     case ISD::CONCAT_VECTORS:    Res = SplitVecOp_CONCAT_VECTORS(N); break;
1508     case ISD::TRUNCATE:
1509       Res = SplitVecOp_TruncateHelper(N);
1510       break;
1511     case ISD::FP_ROUND:          Res = SplitVecOp_FP_ROUND(N); break;
1512     case ISD::FCOPYSIGN:         Res = SplitVecOp_FCOPYSIGN(N); break;
1513     case ISD::STORE:
1514       Res = SplitVecOp_STORE(cast<StoreSDNode>(N), OpNo);
1515       break;
1516     case ISD::MSTORE:
1517       Res = SplitVecOp_MSTORE(cast<MaskedStoreSDNode>(N), OpNo);
1518       break;
1519     case ISD::MSCATTER:
1520       Res = SplitVecOp_MSCATTER(cast<MaskedScatterSDNode>(N), OpNo);
1521       break;
1522     case ISD::MGATHER:
1523       Res = SplitVecOp_MGATHER(cast<MaskedGatherSDNode>(N), OpNo);
1524       break;
1525     case ISD::VSELECT:
1526       Res = SplitVecOp_VSELECT(N, OpNo);
1527       break;
1528     case ISD::FP_TO_SINT:
1529     case ISD::FP_TO_UINT:
1530       if (N->getValueType(0).bitsLT(N->getOperand(0)->getValueType(0)))
1531         Res = SplitVecOp_TruncateHelper(N);
1532       else
1533         Res = SplitVecOp_UnaryOp(N);
1534       break;
1535     case ISD::SINT_TO_FP:
1536     case ISD::UINT_TO_FP:
1537       if (N->getValueType(0).bitsLT(N->getOperand(0)->getValueType(0)))
1538         Res = SplitVecOp_TruncateHelper(N);
1539       else
1540         Res = SplitVecOp_UnaryOp(N);
1541       break;
1542     case ISD::CTTZ:
1543     case ISD::CTLZ:
1544     case ISD::CTPOP:
1545     case ISD::FP_EXTEND:
1546     case ISD::SIGN_EXTEND:
1547     case ISD::ZERO_EXTEND:
1548     case ISD::ANY_EXTEND:
1549     case ISD::FTRUNC:
1550     case ISD::FCANONICALIZE:
1551       Res = SplitVecOp_UnaryOp(N);
1552       break;
1553
1554     case ISD::ANY_EXTEND_VECTOR_INREG:
1555     case ISD::SIGN_EXTEND_VECTOR_INREG:
1556     case ISD::ZERO_EXTEND_VECTOR_INREG:
1557       Res = SplitVecOp_ExtVecInRegOp(N);
1558       break;
1559
1560     case ISD::VECREDUCE_FADD:
1561     case ISD::VECREDUCE_FMUL:
1562     case ISD::VECREDUCE_ADD:
1563     case ISD::VECREDUCE_MUL:
1564     case ISD::VECREDUCE_AND:
1565     case ISD::VECREDUCE_OR:
1566     case ISD::VECREDUCE_XOR:
1567     case ISD::VECREDUCE_SMAX:
1568     case ISD::VECREDUCE_SMIN:
1569     case ISD::VECREDUCE_UMAX:
1570     case ISD::VECREDUCE_UMIN:
1571     case ISD::VECREDUCE_FMAX:
1572     case ISD::VECREDUCE_FMIN:
1573       Res = SplitVecOp_VECREDUCE(N, OpNo);
1574       break;
1575     }
1576   }
1577
1578   // If the result is null, the sub-method took care of registering results etc.
1579   if (!Res.getNode()) return false;
1580
1581   // If the result is N, the sub-method updated N in place.  Tell the legalizer
1582   // core about this.
1583   if (Res.getNode() == N)
1584     return true;
1585
1586   assert(Res.getValueType() == N->getValueType(0) && N->getNumValues() == 1 &&
1587          "Invalid operand expansion");
1588
1589   ReplaceValueWith(SDValue(N, 0), Res);
1590   return false;
1591 }
1592
1593 SDValue DAGTypeLegalizer::SplitVecOp_VSELECT(SDNode *N, unsigned OpNo) {
1594   // The only possibility for an illegal operand is the mask, since result type
1595   // legalization would have handled this node already otherwise.
1596   assert(OpNo == 0 && "Illegal operand must be mask");
1597
1598   SDValue Mask = N->getOperand(0);
1599   SDValue Src0 = N->getOperand(1);
1600   SDValue Src1 = N->getOperand(2);
1601   EVT Src0VT = Src0.getValueType();
1602   SDLoc DL(N);
1603   assert(Mask.getValueType().isVector() && "VSELECT without a vector mask?");
1604
1605   SDValue Lo, Hi;
1606   GetSplitVector(N->getOperand(0), Lo, Hi);
1607   assert(Lo.getValueType() == Hi.getValueType() &&
1608          "Lo and Hi have differing types");
1609
1610   EVT LoOpVT, HiOpVT;
1611   std::tie(LoOpVT, HiOpVT) = DAG.GetSplitDestVTs(Src0VT);
1612   assert(LoOpVT == HiOpVT && "Asymmetric vector split?");
1613
1614   SDValue LoOp0, HiOp0, LoOp1, HiOp1, LoMask, HiMask;
1615   std::tie(LoOp0, HiOp0) = DAG.SplitVector(Src0, DL);
1616   std::tie(LoOp1, HiOp1) = DAG.SplitVector(Src1, DL);
1617   std::tie(LoMask, HiMask) = DAG.SplitVector(Mask, DL);
1618
1619   SDValue LoSelect =
1620     DAG.getNode(ISD::VSELECT, DL, LoOpVT, LoMask, LoOp0, LoOp1);
1621   SDValue HiSelect =
1622     DAG.getNode(ISD::VSELECT, DL, HiOpVT, HiMask, HiOp0, HiOp1);
1623
1624   return DAG.getNode(ISD::CONCAT_VECTORS, DL, Src0VT, LoSelect, HiSelect);
1625 }
1626
1627 SDValue DAGTypeLegalizer::SplitVecOp_VECREDUCE(SDNode *N, unsigned OpNo) {
1628   EVT ResVT = N->getValueType(0);
1629   SDValue Lo, Hi;
1630   SDLoc dl(N);
1631
1632   SDValue VecOp = N->getOperand(OpNo);
1633   EVT VecVT = VecOp.getValueType();
1634   assert(VecVT.isVector() && "Can only split reduce vector operand");
1635   GetSplitVector(VecOp, Lo, Hi);
1636   EVT LoOpVT, HiOpVT;
1637   std::tie(LoOpVT, HiOpVT) = DAG.GetSplitDestVTs(VecVT);
1638
1639   bool NoNaN = N->getFlags().hasNoNaNs();
1640   unsigned CombineOpc = 0;
1641   switch (N->getOpcode()) {
1642   case ISD::VECREDUCE_FADD: CombineOpc = ISD::FADD; break;
1643   case ISD::VECREDUCE_FMUL: CombineOpc = ISD::FMUL; break;
1644   case ISD::VECREDUCE_ADD:  CombineOpc = ISD::ADD; break;
1645   case ISD::VECREDUCE_MUL:  CombineOpc = ISD::MUL; break;
1646   case ISD::VECREDUCE_AND:  CombineOpc = ISD::AND; break;
1647   case ISD::VECREDUCE_OR:   CombineOpc = ISD::OR; break;
1648   case ISD::VECREDUCE_XOR:  CombineOpc = ISD::XOR; break;
1649   case ISD::VECREDUCE_SMAX: CombineOpc = ISD::SMAX; break;
1650   case ISD::VECREDUCE_SMIN: CombineOpc = ISD::SMIN; break;
1651   case ISD::VECREDUCE_UMAX: CombineOpc = ISD::UMAX; break;
1652   case ISD::VECREDUCE_UMIN: CombineOpc = ISD::UMIN; break;
1653   case ISD::VECREDUCE_FMAX:
1654     CombineOpc = NoNaN ? ISD::FMAXNUM : ISD::FMAXNAN;
1655     break;
1656   case ISD::VECREDUCE_FMIN:
1657     CombineOpc = NoNaN ? ISD::FMINNUM : ISD::FMINNAN;
1658     break;
1659   default:
1660     llvm_unreachable("Unexpected reduce ISD node");
1661   }
1662
1663   // Use the appropriate scalar instruction on the split subvectors before
1664   // reducing the now partially reduced smaller vector.
1665   SDValue Partial = DAG.getNode(CombineOpc, dl, LoOpVT, Lo, Hi);
1666   return DAG.getNode(N->getOpcode(), dl, ResVT, Partial);
1667 }
1668
1669 SDValue DAGTypeLegalizer::SplitVecOp_UnaryOp(SDNode *N) {
1670   // The result has a legal vector type, but the input needs splitting.
1671   EVT ResVT = N->getValueType(0);
1672   SDValue Lo, Hi;
1673   SDLoc dl(N);
1674   GetSplitVector(N->getOperand(0), Lo, Hi);
1675   EVT InVT = Lo.getValueType();
1676
1677   EVT OutVT = EVT::getVectorVT(*DAG.getContext(), ResVT.getVectorElementType(),
1678                                InVT.getVectorNumElements());
1679
1680   Lo = DAG.getNode(N->getOpcode(), dl, OutVT, Lo);
1681   Hi = DAG.getNode(N->getOpcode(), dl, OutVT, Hi);
1682
1683   return DAG.getNode(ISD::CONCAT_VECTORS, dl, ResVT, Lo, Hi);
1684 }
1685
1686 SDValue DAGTypeLegalizer::SplitVecOp_BITCAST(SDNode *N) {
1687   // For example, i64 = BITCAST v4i16 on alpha.  Typically the vector will
1688   // end up being split all the way down to individual components.  Convert the
1689   // split pieces into integers and reassemble.
1690   SDValue Lo, Hi;
1691   GetSplitVector(N->getOperand(0), Lo, Hi);
1692   Lo = BitConvertToInteger(Lo);
1693   Hi = BitConvertToInteger(Hi);
1694
1695   if (DAG.getDataLayout().isBigEndian())
1696     std::swap(Lo, Hi);
1697
1698   return DAG.getNode(ISD::BITCAST, SDLoc(N), N->getValueType(0),
1699                      JoinIntegers(Lo, Hi));
1700 }
1701
1702 SDValue DAGTypeLegalizer::SplitVecOp_EXTRACT_SUBVECTOR(SDNode *N) {
1703   // We know that the extracted result type is legal.
1704   EVT SubVT = N->getValueType(0);
1705   SDValue Idx = N->getOperand(1);
1706   SDLoc dl(N);
1707   SDValue Lo, Hi;
1708   GetSplitVector(N->getOperand(0), Lo, Hi);
1709
1710   uint64_t LoElts = Lo.getValueType().getVectorNumElements();
1711   uint64_t IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
1712
1713   if (IdxVal < LoElts) {
1714     assert(IdxVal + SubVT.getVectorNumElements() <= LoElts &&
1715            "Extracted subvector crosses vector split!");
1716     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, SubVT, Lo, Idx);
1717   } else {
1718     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, SubVT, Hi,
1719                        DAG.getConstant(IdxVal - LoElts, dl,
1720                                        Idx.getValueType()));
1721   }
1722 }
1723
1724 SDValue DAGTypeLegalizer::SplitVecOp_EXTRACT_VECTOR_ELT(SDNode *N) {
1725   SDValue Vec = N->getOperand(0);
1726   SDValue Idx = N->getOperand(1);
1727   EVT VecVT = Vec.getValueType();
1728
1729   if (isa<ConstantSDNode>(Idx)) {
1730     uint64_t IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
1731     assert(IdxVal < VecVT.getVectorNumElements() && "Invalid vector index!");
1732
1733     SDValue Lo, Hi;
1734     GetSplitVector(Vec, Lo, Hi);
1735
1736     uint64_t LoElts = Lo.getValueType().getVectorNumElements();
1737
1738     if (IdxVal < LoElts)
1739       return SDValue(DAG.UpdateNodeOperands(N, Lo, Idx), 0);
1740     return SDValue(DAG.UpdateNodeOperands(N, Hi,
1741                                   DAG.getConstant(IdxVal - LoElts, SDLoc(N),
1742                                                   Idx.getValueType())), 0);
1743   }
1744
1745   // See if the target wants to custom expand this node.
1746   if (CustomLowerNode(N, N->getValueType(0), true))
1747     return SDValue();
1748
1749   // Make the vector elements byte-addressable if they aren't already.
1750   SDLoc dl(N);
1751   EVT EltVT = VecVT.getVectorElementType();
1752   if (EltVT.getSizeInBits() < 8) {
1753     SmallVector<SDValue, 4> ElementOps;
1754     for (unsigned i = 0; i < VecVT.getVectorNumElements(); ++i) {
1755       ElementOps.push_back(DAG.getAnyExtOrTrunc(
1756           DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT, Vec,
1757                       DAG.getConstant(i, dl, MVT::i8)),
1758           dl, MVT::i8));
1759     }
1760
1761     EltVT = MVT::i8;
1762     VecVT = EVT::getVectorVT(*DAG.getContext(), EltVT,
1763                              VecVT.getVectorNumElements());
1764     Vec = DAG.getBuildVector(VecVT, dl, ElementOps);
1765   }
1766
1767   // Store the vector to the stack.
1768   SDValue StackPtr = DAG.CreateStackTemporary(VecVT);
1769   auto &MF = DAG.getMachineFunction();
1770   auto FrameIndex = cast<FrameIndexSDNode>(StackPtr.getNode())->getIndex();
1771   auto PtrInfo = MachinePointerInfo::getFixedStack(MF, FrameIndex);
1772   SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Vec, StackPtr, PtrInfo);
1773
1774   // Load back the required element.
1775   StackPtr = TLI.getVectorElementPointer(DAG, StackPtr, VecVT, Idx);
1776   return DAG.getExtLoad(
1777       ISD::EXTLOAD, dl, N->getValueType(0), Store, StackPtr,
1778       MachinePointerInfo::getUnknownStack(DAG.getMachineFunction()), EltVT);
1779 }
1780
1781 SDValue DAGTypeLegalizer::SplitVecOp_ExtVecInRegOp(SDNode *N) {
1782   SDValue Lo, Hi;
1783
1784   // *_EXTEND_VECTOR_INREG only reference the lower half of the input, so
1785   // splitting the result has the same effect as splitting the input operand.
1786   SplitVecRes_ExtVecInRegOp(N, Lo, Hi);
1787
1788   return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), N->getValueType(0), Lo, Hi);
1789 }
1790
1791 SDValue DAGTypeLegalizer::SplitVecOp_MGATHER(MaskedGatherSDNode *MGT,
1792                                              unsigned OpNo) {
1793   EVT LoVT, HiVT;
1794   SDLoc dl(MGT);
1795   std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(MGT->getValueType(0));
1796
1797   SDValue Ch = MGT->getChain();
1798   SDValue Ptr = MGT->getBasePtr();
1799   SDValue Index = MGT->getIndex();
1800   SDValue Mask = MGT->getMask();
1801   SDValue Src0 = MGT->getValue();
1802   unsigned Alignment = MGT->getOriginalAlignment();
1803
1804   SDValue MaskLo, MaskHi;
1805   if (getTypeAction(Mask.getValueType()) == TargetLowering::TypeSplitVector)
1806     // Split Mask operand
1807     GetSplitVector(Mask, MaskLo, MaskHi);
1808   else
1809     std::tie(MaskLo, MaskHi) = DAG.SplitVector(Mask, dl);
1810
1811   EVT MemoryVT = MGT->getMemoryVT();
1812   EVT LoMemVT, HiMemVT;
1813   std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT);
1814
1815   SDValue Src0Lo, Src0Hi;
1816   if (getTypeAction(Src0.getValueType()) == TargetLowering::TypeSplitVector)
1817     GetSplitVector(Src0, Src0Lo, Src0Hi);
1818   else
1819     std::tie(Src0Lo, Src0Hi) = DAG.SplitVector(Src0, dl);
1820
1821   SDValue IndexHi, IndexLo;
1822   if (getTypeAction(Index.getValueType()) == TargetLowering::TypeSplitVector)
1823     GetSplitVector(Index, IndexLo, IndexHi);
1824   else
1825     std::tie(IndexLo, IndexHi) = DAG.SplitVector(Index, dl);
1826
1827   MachineMemOperand *MMO = DAG.getMachineFunction().
1828     getMachineMemOperand(MGT->getPointerInfo(),
1829                          MachineMemOperand::MOLoad,  LoMemVT.getStoreSize(),
1830                          Alignment, MGT->getAAInfo(), MGT->getRanges());
1831
1832   SDValue OpsLo[] = {Ch, Src0Lo, MaskLo, Ptr, IndexLo};
1833   SDValue Lo = DAG.getMaskedGather(DAG.getVTList(LoVT, MVT::Other), LoVT, dl,
1834                                    OpsLo, MMO);
1835
1836   MMO = DAG.getMachineFunction().
1837     getMachineMemOperand(MGT->getPointerInfo(),
1838                          MachineMemOperand::MOLoad,  HiMemVT.getStoreSize(),
1839                          Alignment, MGT->getAAInfo(),
1840                          MGT->getRanges());
1841
1842   SDValue OpsHi[] = {Ch, Src0Hi, MaskHi, Ptr, IndexHi};
1843   SDValue Hi = DAG.getMaskedGather(DAG.getVTList(HiVT, MVT::Other), HiVT, dl,
1844                                    OpsHi, MMO);
1845
1846   // Build a factor node to remember that this load is independent of the
1847   // other one.
1848   Ch = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Lo.getValue(1),
1849                    Hi.getValue(1));
1850
1851   // Legalize the chain result - switch anything that used the old chain to
1852   // use the new one.
1853   ReplaceValueWith(SDValue(MGT, 1), Ch);
1854
1855   SDValue Res = DAG.getNode(ISD::CONCAT_VECTORS, dl, MGT->getValueType(0), Lo,
1856                             Hi);
1857   ReplaceValueWith(SDValue(MGT, 0), Res);
1858   return SDValue();
1859 }
1860
1861 SDValue DAGTypeLegalizer::SplitVecOp_MSTORE(MaskedStoreSDNode *N,
1862                                             unsigned OpNo) {
1863   SDValue Ch  = N->getChain();
1864   SDValue Ptr = N->getBasePtr();
1865   SDValue Mask = N->getMask();
1866   SDValue Data = N->getValue();
1867   EVT MemoryVT = N->getMemoryVT();
1868   unsigned Alignment = N->getOriginalAlignment();
1869   SDLoc DL(N);
1870
1871   EVT LoMemVT, HiMemVT;
1872   std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT);
1873
1874   SDValue DataLo, DataHi;
1875   if (getTypeAction(Data.getValueType()) == TargetLowering::TypeSplitVector)
1876     // Split Data operand
1877     GetSplitVector(Data, DataLo, DataHi);
1878   else
1879     std::tie(DataLo, DataHi) = DAG.SplitVector(Data, DL);
1880
1881   SDValue MaskLo, MaskHi;
1882   if (getTypeAction(Mask.getValueType()) == TargetLowering::TypeSplitVector)
1883     // Split Mask operand
1884     GetSplitVector(Mask, MaskLo, MaskHi);
1885   else
1886     std::tie(MaskLo, MaskHi) = DAG.SplitVector(Mask, DL);
1887
1888   // if Alignment is equal to the vector size,
1889   // take the half of it for the second part
1890   unsigned SecondHalfAlignment =
1891     (Alignment == Data->getValueType(0).getSizeInBits()/8) ?
1892        Alignment/2 : Alignment;
1893
1894   SDValue Lo, Hi;
1895   MachineMemOperand *MMO = DAG.getMachineFunction().
1896     getMachineMemOperand(N->getPointerInfo(),
1897                          MachineMemOperand::MOStore, LoMemVT.getStoreSize(),
1898                          Alignment, N->getAAInfo(), N->getRanges());
1899
1900   Lo = DAG.getMaskedStore(Ch, DL, DataLo, Ptr, MaskLo, LoMemVT, MMO,
1901                           N->isTruncatingStore(),
1902                           N->isCompressingStore());
1903
1904   Ptr = TLI.IncrementMemoryAddress(Ptr, MaskLo, DL, LoMemVT, DAG,
1905                                    N->isCompressingStore());
1906   MMO = DAG.getMachineFunction().
1907     getMachineMemOperand(N->getPointerInfo(),
1908                          MachineMemOperand::MOStore,  HiMemVT.getStoreSize(),
1909                          SecondHalfAlignment, N->getAAInfo(), N->getRanges());
1910
1911   Hi = DAG.getMaskedStore(Ch, DL, DataHi, Ptr, MaskHi, HiMemVT, MMO,
1912                           N->isTruncatingStore(), N->isCompressingStore());
1913
1914   // Build a factor node to remember that this store is independent of the
1915   // other one.
1916   return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo, Hi);
1917 }
1918
1919 SDValue DAGTypeLegalizer::SplitVecOp_MSCATTER(MaskedScatterSDNode *N,
1920                                               unsigned OpNo) {
1921   SDValue Ch  = N->getChain();
1922   SDValue Ptr = N->getBasePtr();
1923   SDValue Mask = N->getMask();
1924   SDValue Index = N->getIndex();
1925   SDValue Data = N->getValue();
1926   EVT MemoryVT = N->getMemoryVT();
1927   unsigned Alignment = N->getOriginalAlignment();
1928   SDLoc DL(N);
1929
1930   // Split all operands
1931   EVT LoMemVT, HiMemVT;
1932   std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT);
1933
1934   SDValue DataLo, DataHi;
1935   if (getTypeAction(Data.getValueType()) == TargetLowering::TypeSplitVector)
1936     // Split Data operand
1937     GetSplitVector(Data, DataLo, DataHi);
1938   else
1939     std::tie(DataLo, DataHi) = DAG.SplitVector(Data, DL);
1940
1941   SDValue MaskLo, MaskHi;
1942   if (getTypeAction(Mask.getValueType()) == TargetLowering::TypeSplitVector)
1943     // Split Mask operand
1944     GetSplitVector(Mask, MaskLo, MaskHi);
1945   else
1946     std::tie(MaskLo, MaskHi) = DAG.SplitVector(Mask, DL);
1947
1948   SDValue IndexHi, IndexLo;
1949   if (getTypeAction(Index.getValueType()) == TargetLowering::TypeSplitVector)
1950     GetSplitVector(Index, IndexLo, IndexHi);
1951   else
1952     std::tie(IndexLo, IndexHi) = DAG.SplitVector(Index, DL);
1953
1954   SDValue Lo;
1955   MachineMemOperand *MMO = DAG.getMachineFunction().
1956     getMachineMemOperand(N->getPointerInfo(),
1957                          MachineMemOperand::MOStore, LoMemVT.getStoreSize(),
1958                          Alignment, N->getAAInfo(), N->getRanges());
1959
1960   SDValue OpsLo[] = {Ch, DataLo, MaskLo, Ptr, IndexLo};
1961   Lo = DAG.getMaskedScatter(DAG.getVTList(MVT::Other), DataLo.getValueType(),
1962                             DL, OpsLo, MMO);
1963
1964   MMO = DAG.getMachineFunction().
1965     getMachineMemOperand(N->getPointerInfo(),
1966                          MachineMemOperand::MOStore,  HiMemVT.getStoreSize(),
1967                          Alignment, N->getAAInfo(), N->getRanges());
1968
1969   // The order of the Scatter operation after split is well defined. The "Hi"
1970   // part comes after the "Lo". So these two operations should be chained one
1971   // after another.
1972   SDValue OpsHi[] = {Lo, DataHi, MaskHi, Ptr, IndexHi};
1973   return DAG.getMaskedScatter(DAG.getVTList(MVT::Other), DataHi.getValueType(),
1974                               DL, OpsHi, MMO);
1975 }
1976
1977 SDValue DAGTypeLegalizer::SplitVecOp_STORE(StoreSDNode *N, unsigned OpNo) {
1978   assert(N->isUnindexed() && "Indexed store of vector?");
1979   assert(OpNo == 1 && "Can only split the stored value");
1980   SDLoc DL(N);
1981
1982   bool isTruncating = N->isTruncatingStore();
1983   SDValue Ch  = N->getChain();
1984   SDValue Ptr = N->getBasePtr();
1985   EVT MemoryVT = N->getMemoryVT();
1986   unsigned Alignment = N->getOriginalAlignment();
1987   MachineMemOperand::Flags MMOFlags = N->getMemOperand()->getFlags();
1988   AAMDNodes AAInfo = N->getAAInfo();
1989   SDValue Lo, Hi;
1990   GetSplitVector(N->getOperand(1), Lo, Hi);
1991
1992   EVT LoMemVT, HiMemVT;
1993   std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT);
1994
1995   unsigned IncrementSize = LoMemVT.getSizeInBits()/8;
1996
1997   if (isTruncating)
1998     Lo = DAG.getTruncStore(Ch, DL, Lo, Ptr, N->getPointerInfo(), LoMemVT,
1999                            Alignment, MMOFlags, AAInfo);
2000   else
2001     Lo = DAG.getStore(Ch, DL, Lo, Ptr, N->getPointerInfo(), Alignment, MMOFlags,
2002                       AAInfo);
2003
2004   // Increment the pointer to the other half.
2005   Ptr = DAG.getObjectPtrOffset(DL, Ptr, IncrementSize);
2006
2007   if (isTruncating)
2008     Hi = DAG.getTruncStore(Ch, DL, Hi, Ptr,
2009                            N->getPointerInfo().getWithOffset(IncrementSize),
2010                            HiMemVT, Alignment, MMOFlags, AAInfo);
2011   else
2012     Hi = DAG.getStore(Ch, DL, Hi, Ptr,
2013                       N->getPointerInfo().getWithOffset(IncrementSize),
2014                       Alignment, MMOFlags, AAInfo);
2015
2016   return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo, Hi);
2017 }
2018
2019 SDValue DAGTypeLegalizer::SplitVecOp_CONCAT_VECTORS(SDNode *N) {
2020   SDLoc DL(N);
2021
2022   // The input operands all must have the same type, and we know the result
2023   // type is valid.  Convert this to a buildvector which extracts all the
2024   // input elements.
2025   // TODO: If the input elements are power-two vectors, we could convert this to
2026   // a new CONCAT_VECTORS node with elements that are half-wide.
2027   SmallVector<SDValue, 32> Elts;
2028   EVT EltVT = N->getValueType(0).getVectorElementType();
2029   for (const SDValue &Op : N->op_values()) {
2030     for (unsigned i = 0, e = Op.getValueType().getVectorNumElements();
2031          i != e; ++i) {
2032       Elts.push_back(DAG.getNode(
2033           ISD::EXTRACT_VECTOR_ELT, DL, EltVT, Op,
2034           DAG.getConstant(i, DL, TLI.getVectorIdxTy(DAG.getDataLayout()))));
2035     }
2036   }
2037
2038   return DAG.getBuildVector(N->getValueType(0), DL, Elts);
2039 }
2040
2041 SDValue DAGTypeLegalizer::SplitVecOp_TruncateHelper(SDNode *N) {
2042   // The result type is legal, but the input type is illegal.  If splitting
2043   // ends up with the result type of each half still being legal, just
2044   // do that.  If, however, that would result in an illegal result type,
2045   // we can try to get more clever with power-two vectors. Specifically,
2046   // split the input type, but also widen the result element size, then
2047   // concatenate the halves and truncate again.  For example, consider a target
2048   // where v8i8 is legal and v8i32 is not (ARM, which doesn't have 256-bit
2049   // vectors). To perform a "%res = v8i8 trunc v8i32 %in" we do:
2050   //   %inlo = v4i32 extract_subvector %in, 0
2051   //   %inhi = v4i32 extract_subvector %in, 4
2052   //   %lo16 = v4i16 trunc v4i32 %inlo
2053   //   %hi16 = v4i16 trunc v4i32 %inhi
2054   //   %in16 = v8i16 concat_vectors v4i16 %lo16, v4i16 %hi16
2055   //   %res = v8i8 trunc v8i16 %in16
2056   //
2057   // Without this transform, the original truncate would end up being
2058   // scalarized, which is pretty much always a last resort.
2059   SDValue InVec = N->getOperand(0);
2060   EVT InVT = InVec->getValueType(0);
2061   EVT OutVT = N->getValueType(0);
2062   unsigned NumElements = OutVT.getVectorNumElements();
2063   bool IsFloat = OutVT.isFloatingPoint();
2064
2065   // Widening should have already made sure this is a power-two vector
2066   // if we're trying to split it at all. assert() that's true, just in case.
2067   assert(!(NumElements & 1) && "Splitting vector, but not in half!");
2068
2069   unsigned InElementSize = InVT.getScalarSizeInBits();
2070   unsigned OutElementSize = OutVT.getScalarSizeInBits();
2071
2072   // If the input elements are only 1/2 the width of the result elements,
2073   // just use the normal splitting. Our trick only work if there's room
2074   // to split more than once.
2075   if (InElementSize <= OutElementSize * 2)
2076     return SplitVecOp_UnaryOp(N);
2077   SDLoc DL(N);
2078
2079   // Extract the halves of the input via extract_subvector.
2080   SDValue InLoVec, InHiVec;
2081   std::tie(InLoVec, InHiVec) = DAG.SplitVector(InVec, DL);
2082   // Truncate them to 1/2 the element size.
2083   EVT HalfElementVT = IsFloat ?
2084     EVT::getFloatingPointVT(InElementSize/2) :
2085     EVT::getIntegerVT(*DAG.getContext(), InElementSize/2);
2086   EVT HalfVT = EVT::getVectorVT(*DAG.getContext(), HalfElementVT,
2087                                 NumElements/2);
2088   SDValue HalfLo = DAG.getNode(N->getOpcode(), DL, HalfVT, InLoVec);
2089   SDValue HalfHi = DAG.getNode(N->getOpcode(), DL, HalfVT, InHiVec);
2090   // Concatenate them to get the full intermediate truncation result.
2091   EVT InterVT = EVT::getVectorVT(*DAG.getContext(), HalfElementVT, NumElements);
2092   SDValue InterVec = DAG.getNode(ISD::CONCAT_VECTORS, DL, InterVT, HalfLo,
2093                                  HalfHi);
2094   // Now finish up by truncating all the way down to the original result
2095   // type. This should normally be something that ends up being legal directly,
2096   // but in theory if a target has very wide vectors and an annoyingly
2097   // restricted set of legal types, this split can chain to build things up.
2098   return IsFloat
2099              ? DAG.getNode(ISD::FP_ROUND, DL, OutVT, InterVec,
2100                            DAG.getTargetConstant(
2101                                0, DL, TLI.getPointerTy(DAG.getDataLayout())))
2102              : DAG.getNode(ISD::TRUNCATE, DL, OutVT, InterVec);
2103 }
2104
2105 SDValue DAGTypeLegalizer::SplitVecOp_VSETCC(SDNode *N) {
2106   assert(N->getValueType(0).isVector() &&
2107          N->getOperand(0).getValueType().isVector() &&
2108          "Operand types must be vectors");
2109   // The result has a legal vector type, but the input needs splitting.
2110   SDValue Lo0, Hi0, Lo1, Hi1, LoRes, HiRes;
2111   SDLoc DL(N);
2112   GetSplitVector(N->getOperand(0), Lo0, Hi0);
2113   GetSplitVector(N->getOperand(1), Lo1, Hi1);
2114   unsigned PartElements = Lo0.getValueType().getVectorNumElements();
2115   EVT PartResVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1, PartElements);
2116   EVT WideResVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1, 2*PartElements);
2117
2118   LoRes = DAG.getNode(ISD::SETCC, DL, PartResVT, Lo0, Lo1, N->getOperand(2));
2119   HiRes = DAG.getNode(ISD::SETCC, DL, PartResVT, Hi0, Hi1, N->getOperand(2));
2120   SDValue Con = DAG.getNode(ISD::CONCAT_VECTORS, DL, WideResVT, LoRes, HiRes);
2121   return PromoteTargetBoolean(Con, N->getValueType(0));
2122 }
2123
2124
2125 SDValue DAGTypeLegalizer::SplitVecOp_FP_ROUND(SDNode *N) {
2126   // The result has a legal vector type, but the input needs splitting.
2127   EVT ResVT = N->getValueType(0);
2128   SDValue Lo, Hi;
2129   SDLoc DL(N);
2130   GetSplitVector(N->getOperand(0), Lo, Hi);
2131   EVT InVT = Lo.getValueType();
2132
2133   EVT OutVT = EVT::getVectorVT(*DAG.getContext(), ResVT.getVectorElementType(),
2134                                InVT.getVectorNumElements());
2135
2136   Lo = DAG.getNode(ISD::FP_ROUND, DL, OutVT, Lo, N->getOperand(1));
2137   Hi = DAG.getNode(ISD::FP_ROUND, DL, OutVT, Hi, N->getOperand(1));
2138
2139   return DAG.getNode(ISD::CONCAT_VECTORS, DL, ResVT, Lo, Hi);
2140 }
2141
2142 SDValue DAGTypeLegalizer::SplitVecOp_FCOPYSIGN(SDNode *N) {
2143   // The result (and the first input) has a legal vector type, but the second
2144   // input needs splitting.
2145   return DAG.UnrollVectorOp(N, N->getValueType(0).getVectorNumElements());
2146 }
2147
2148
2149 //===----------------------------------------------------------------------===//
2150 //  Result Vector Widening
2151 //===----------------------------------------------------------------------===//
2152
2153 void DAGTypeLegalizer::WidenVectorResult(SDNode *N, unsigned ResNo) {
2154   DEBUG(dbgs() << "Widen node result " << ResNo << ": ";
2155         N->dump(&DAG);
2156         dbgs() << "\n");
2157
2158   // See if the target wants to custom widen this node.
2159   if (CustomWidenLowerNode(N, N->getValueType(ResNo)))
2160     return;
2161
2162   SDValue Res = SDValue();
2163   switch (N->getOpcode()) {
2164   default:
2165 #ifndef NDEBUG
2166     dbgs() << "WidenVectorResult #" << ResNo << ": ";
2167     N->dump(&DAG);
2168     dbgs() << "\n";
2169 #endif
2170     llvm_unreachable("Do not know how to widen the result of this operator!");
2171
2172   case ISD::MERGE_VALUES:      Res = WidenVecRes_MERGE_VALUES(N, ResNo); break;
2173   case ISD::BITCAST:           Res = WidenVecRes_BITCAST(N); break;
2174   case ISD::BUILD_VECTOR:      Res = WidenVecRes_BUILD_VECTOR(N); break;
2175   case ISD::CONCAT_VECTORS:    Res = WidenVecRes_CONCAT_VECTORS(N); break;
2176   case ISD::EXTRACT_SUBVECTOR: Res = WidenVecRes_EXTRACT_SUBVECTOR(N); break;
2177   case ISD::FP_ROUND_INREG:    Res = WidenVecRes_InregOp(N); break;
2178   case ISD::INSERT_VECTOR_ELT: Res = WidenVecRes_INSERT_VECTOR_ELT(N); break;
2179   case ISD::LOAD:              Res = WidenVecRes_LOAD(N); break;
2180   case ISD::SCALAR_TO_VECTOR:  Res = WidenVecRes_SCALAR_TO_VECTOR(N); break;
2181   case ISD::SIGN_EXTEND_INREG: Res = WidenVecRes_InregOp(N); break;
2182   case ISD::VSELECT:
2183   case ISD::SELECT:            Res = WidenVecRes_SELECT(N); break;
2184   case ISD::SELECT_CC:         Res = WidenVecRes_SELECT_CC(N); break;
2185   case ISD::SETCC:             Res = WidenVecRes_SETCC(N); break;
2186   case ISD::UNDEF:             Res = WidenVecRes_UNDEF(N); break;
2187   case ISD::VECTOR_SHUFFLE:
2188     Res = WidenVecRes_VECTOR_SHUFFLE(cast<ShuffleVectorSDNode>(N));
2189     break;
2190   case ISD::MLOAD:
2191     Res = WidenVecRes_MLOAD(cast<MaskedLoadSDNode>(N));
2192     break;
2193   case ISD::MGATHER:
2194     Res = WidenVecRes_MGATHER(cast<MaskedGatherSDNode>(N));
2195     break;
2196
2197   case ISD::ADD:
2198   case ISD::AND:
2199   case ISD::MUL:
2200   case ISD::MULHS:
2201   case ISD::MULHU:
2202   case ISD::OR:
2203   case ISD::SUB:
2204   case ISD::XOR:
2205   case ISD::FMINNUM:
2206   case ISD::FMAXNUM:
2207   case ISD::FMINNAN:
2208   case ISD::FMAXNAN:
2209   case ISD::SMIN:
2210   case ISD::SMAX:
2211   case ISD::UMIN:
2212   case ISD::UMAX:
2213     Res = WidenVecRes_Binary(N);
2214     break;
2215
2216   case ISD::FADD:
2217   case ISD::FMUL:
2218   case ISD::FPOW:
2219   case ISD::FSUB:
2220   case ISD::FDIV:
2221   case ISD::FREM:
2222   case ISD::SDIV:
2223   case ISD::UDIV:
2224   case ISD::SREM:
2225   case ISD::UREM:
2226     Res = WidenVecRes_BinaryCanTrap(N);
2227     break;
2228
2229   case ISD::FCOPYSIGN:
2230     Res = WidenVecRes_FCOPYSIGN(N);
2231     break;
2232
2233   case ISD::FPOWI:
2234     Res = WidenVecRes_POWI(N);
2235     break;
2236
2237   case ISD::SHL:
2238   case ISD::SRA:
2239   case ISD::SRL:
2240     Res = WidenVecRes_Shift(N);
2241     break;
2242
2243   case ISD::ANY_EXTEND_VECTOR_INREG:
2244   case ISD::SIGN_EXTEND_VECTOR_INREG:
2245   case ISD::ZERO_EXTEND_VECTOR_INREG:
2246     Res = WidenVecRes_EXTEND_VECTOR_INREG(N);
2247     break;
2248
2249   case ISD::ANY_EXTEND:
2250   case ISD::FP_EXTEND:
2251   case ISD::FP_ROUND:
2252   case ISD::FP_TO_SINT:
2253   case ISD::FP_TO_UINT:
2254   case ISD::SIGN_EXTEND:
2255   case ISD::SINT_TO_FP:
2256   case ISD::TRUNCATE:
2257   case ISD::UINT_TO_FP:
2258   case ISD::ZERO_EXTEND:
2259     Res = WidenVecRes_Convert(N);
2260     break;
2261
2262   case ISD::BITREVERSE:
2263   case ISD::BSWAP:
2264   case ISD::CTLZ:
2265   case ISD::CTPOP:
2266   case ISD::CTTZ:
2267   case ISD::FABS:
2268   case ISD::FCEIL:
2269   case ISD::FCOS:
2270   case ISD::FEXP:
2271   case ISD::FEXP2:
2272   case ISD::FFLOOR:
2273   case ISD::FLOG:
2274   case ISD::FLOG10:
2275   case ISD::FLOG2:
2276   case ISD::FNEARBYINT:
2277   case ISD::FNEG:
2278   case ISD::FRINT:
2279   case ISD::FROUND:
2280   case ISD::FSIN:
2281   case ISD::FSQRT:
2282   case ISD::FTRUNC:
2283     Res = WidenVecRes_Unary(N);
2284     break;
2285   case ISD::FMA:
2286     Res = WidenVecRes_Ternary(N);
2287     break;
2288   }
2289
2290   // If Res is null, the sub-method took care of registering the result.
2291   if (Res.getNode())
2292     SetWidenedVector(SDValue(N, ResNo), Res);
2293 }
2294
2295 SDValue DAGTypeLegalizer::WidenVecRes_Ternary(SDNode *N) {
2296   // Ternary op widening.
2297   SDLoc dl(N);
2298   EVT WidenVT = TLI.getTypeToTransformTo(*DAG.getContext(), N->getValueType(0));
2299   SDValue InOp1 = GetWidenedVector(N->getOperand(0));
2300   SDValue InOp2 = GetWidenedVector(N->getOperand(1));
2301   SDValue InOp3 = GetWidenedVector(N->getOperand(2));
2302   return DAG.getNode(N->getOpcode(), dl, WidenVT, InOp1, InOp2, InOp3);
2303 }
2304
2305 SDValue DAGTypeLegalizer::WidenVecRes_Binary(SDNode *N) {
2306   // Binary op widening.
2307   SDLoc dl(N);
2308   EVT WidenVT = TLI.getTypeToTransformTo(*DAG.getContext(), N->getValueType(0));
2309   SDValue InOp1 = GetWidenedVector(N->getOperand(0));
2310   SDValue InOp2 = GetWidenedVector(N->getOperand(1));
2311   return DAG.getNode(N->getOpcode(), dl, WidenVT, InOp1, InOp2, N->getFlags());
2312 }
2313
2314 SDValue DAGTypeLegalizer::WidenVecRes_BinaryCanTrap(SDNode *N) {
2315   // Binary op widening for operations that can trap.
2316   unsigned Opcode = N->getOpcode();
2317   SDLoc dl(N);
2318   EVT WidenVT = TLI.getTypeToTransformTo(*DAG.getContext(), N->getValueType(0));
2319   EVT WidenEltVT = WidenVT.getVectorElementType();
2320   EVT VT = WidenVT;
2321   unsigned NumElts =  VT.getVectorNumElements();
2322   const SDNodeFlags Flags = N->getFlags();
2323   while (!TLI.isTypeLegal(VT) && NumElts != 1) {
2324     NumElts = NumElts / 2;
2325     VT = EVT::getVectorVT(*DAG.getContext(), WidenEltVT, NumElts);
2326   }
2327
2328   if (NumElts != 1 && !TLI.canOpTrap(N->getOpcode(), VT)) {
2329     // Operation doesn't trap so just widen as normal.
2330     SDValue InOp1 = GetWidenedVector(N->getOperand(0));
2331     SDValue InOp2 = GetWidenedVector(N->getOperand(1));
2332     return DAG.getNode(N->getOpcode(), dl, WidenVT, InOp1, InOp2, Flags);
2333   }
2334
2335   // No legal vector version so unroll the vector operation and then widen.
2336   if (NumElts == 1)
2337     return DAG.UnrollVectorOp(N, WidenVT.getVectorNumElements());
2338
2339   // Since the operation can trap, apply operation on the original vector.
2340   EVT MaxVT = VT;
2341   SDValue InOp1 = GetWidenedVector(N->getOperand(0));
2342   SDValue InOp2 = GetWidenedVector(N->getOperand(1));
2343   unsigned CurNumElts = N->getValueType(0).getVectorNumElements();
2344
2345   SmallVector<SDValue, 16> ConcatOps(CurNumElts);
2346   unsigned ConcatEnd = 0;  // Current ConcatOps index.
2347   int Idx = 0;        // Current Idx into input vectors.
2348
2349   // NumElts := greatest legal vector size (at most WidenVT)
2350   // while (orig. vector has unhandled elements) {
2351   //   take munches of size NumElts from the beginning and add to ConcatOps
2352   //   NumElts := next smaller supported vector size or 1
2353   // }
2354   while (CurNumElts != 0) {
2355     while (CurNumElts >= NumElts) {
2356       SDValue EOp1 = DAG.getNode(
2357           ISD::EXTRACT_SUBVECTOR, dl, VT, InOp1,
2358           DAG.getConstant(Idx, dl, TLI.getVectorIdxTy(DAG.getDataLayout())));
2359       SDValue EOp2 = DAG.getNode(
2360           ISD::EXTRACT_SUBVECTOR, dl, VT, InOp2,
2361           DAG.getConstant(Idx, dl, TLI.getVectorIdxTy(DAG.getDataLayout())));
2362       ConcatOps[ConcatEnd++] = DAG.getNode(Opcode, dl, VT, EOp1, EOp2, Flags);
2363       Idx += NumElts;
2364       CurNumElts -= NumElts;
2365     }
2366     do {
2367       NumElts = NumElts / 2;
2368       VT = EVT::getVectorVT(*DAG.getContext(), WidenEltVT, NumElts);
2369     } while (!TLI.isTypeLegal(VT) && NumElts != 1);
2370
2371     if (NumElts == 1) {
2372       for (unsigned i = 0; i != CurNumElts; ++i, ++Idx) {
2373         SDValue EOp1 = DAG.getNode(
2374             ISD::EXTRACT_VECTOR_ELT, dl, WidenEltVT, InOp1,
2375             DAG.getConstant(Idx, dl, TLI.getVectorIdxTy(DAG.getDataLayout())));
2376         SDValue EOp2 = DAG.getNode(
2377             ISD::EXTRACT_VECTOR_ELT, dl, WidenEltVT, InOp2,
2378             DAG.getConstant(Idx, dl, TLI.getVectorIdxTy(DAG.getDataLayout())));
2379         ConcatOps[ConcatEnd++] = DAG.getNode(Opcode, dl, WidenEltVT,
2380                                              EOp1, EOp2, Flags);
2381       }
2382       CurNumElts = 0;
2383     }
2384   }
2385
2386   // Check to see if we have a single operation with the widen type.
2387   if (ConcatEnd == 1) {
2388     VT = ConcatOps[0].getValueType();
2389     if (VT == WidenVT)
2390       return ConcatOps[0];
2391   }
2392
2393   // while (Some element of ConcatOps is not of type MaxVT) {
2394   //   From the end of ConcatOps, collect elements of the same type and put
2395   //   them into an op of the next larger supported type
2396   // }
2397   while (ConcatOps[ConcatEnd-1].getValueType() != MaxVT) {
2398     Idx = ConcatEnd - 1;
2399     VT = ConcatOps[Idx--].getValueType();
2400     while (Idx >= 0 && ConcatOps[Idx].getValueType() == VT)
2401       Idx--;
2402
2403     int NextSize = VT.isVector() ? VT.getVectorNumElements() : 1;
2404     EVT NextVT;
2405     do {
2406       NextSize *= 2;
2407       NextVT = EVT::getVectorVT(*DAG.getContext(), WidenEltVT, NextSize);
2408     } while (!TLI.isTypeLegal(NextVT));
2409
2410     if (!VT.isVector()) {
2411       // Scalar type, create an INSERT_VECTOR_ELEMENT of type NextVT
2412       SDValue VecOp = DAG.getUNDEF(NextVT);
2413       unsigned NumToInsert = ConcatEnd - Idx - 1;
2414       for (unsigned i = 0, OpIdx = Idx+1; i < NumToInsert; i++, OpIdx++) {
2415         VecOp = DAG.getNode(
2416             ISD::INSERT_VECTOR_ELT, dl, NextVT, VecOp, ConcatOps[OpIdx],
2417             DAG.getConstant(i, dl, TLI.getVectorIdxTy(DAG.getDataLayout())));
2418       }
2419       ConcatOps[Idx+1] = VecOp;
2420       ConcatEnd = Idx + 2;
2421     } else {
2422       // Vector type, create a CONCAT_VECTORS of type NextVT
2423       SDValue undefVec = DAG.getUNDEF(VT);
2424       unsigned OpsToConcat = NextSize/VT.getVectorNumElements();
2425       SmallVector<SDValue, 16> SubConcatOps(OpsToConcat);
2426       unsigned RealVals = ConcatEnd - Idx - 1;
2427       unsigned SubConcatEnd = 0;
2428       unsigned SubConcatIdx = Idx + 1;
2429       while (SubConcatEnd < RealVals)
2430         SubConcatOps[SubConcatEnd++] = ConcatOps[++Idx];
2431       while (SubConcatEnd < OpsToConcat)
2432         SubConcatOps[SubConcatEnd++] = undefVec;
2433       ConcatOps[SubConcatIdx] = DAG.getNode(ISD::CONCAT_VECTORS, dl,
2434                                             NextVT, SubConcatOps);
2435       ConcatEnd = SubConcatIdx + 1;
2436     }
2437   }
2438
2439   // Check to see if we have a single operation with the widen type.
2440   if (ConcatEnd == 1) {
2441     VT = ConcatOps[0].getValueType();
2442     if (VT == WidenVT)
2443       return ConcatOps[0];
2444   }
2445
2446   // add undefs of size MaxVT until ConcatOps grows to length of WidenVT
2447   unsigned NumOps = WidenVT.getVectorNumElements()/MaxVT.getVectorNumElements();
2448   if (NumOps != ConcatEnd ) {
2449     SDValue UndefVal = DAG.getUNDEF(MaxVT);
2450     for (unsigned j = ConcatEnd; j < NumOps; ++j)
2451       ConcatOps[j] = UndefVal;
2452   }
2453   return DAG.getNode(ISD::CONCAT_VECTORS, dl, WidenVT,
2454                      makeArrayRef(ConcatOps.data(), NumOps));
2455 }
2456
2457 SDValue DAGTypeLegalizer::WidenVecRes_Convert(SDNode *N) {
2458   SDValue InOp = N->getOperand(0);
2459   SDLoc DL(N);
2460
2461   EVT WidenVT = TLI.getTypeToTransformTo(*DAG.getContext(), N->getValueType(0));
2462   unsigned WidenNumElts = WidenVT.getVectorNumElements();
2463
2464   EVT InVT = InOp.getValueType();
2465   EVT InEltVT = InVT.getVectorElementType();
2466   EVT InWidenVT = EVT::getVectorVT(*DAG.getContext(), InEltVT, WidenNumElts);
2467
2468   unsigned Opcode = N->getOpcode();
2469   unsigned InVTNumElts = InVT.getVectorNumElements();
2470   const SDNodeFlags Flags = N->getFlags();
2471   if (getTypeAction(InVT) == TargetLowering::TypeWidenVector) {
2472     InOp = GetWidenedVector(N->getOperand(0));
2473     InVT = InOp.getValueType();
2474     InVTNumElts = InVT.getVectorNumElements();
2475     if (InVTNumElts == WidenNumElts) {
2476       if (N->getNumOperands() == 1)
2477         return DAG.getNode(Opcode, DL, WidenVT, InOp);
2478       return DAG.getNode(Opcode, DL, WidenVT, InOp, N->getOperand(1), Flags);
2479     }
2480     if (WidenVT.getSizeInBits() == InVT.getSizeInBits()) {
2481       // If both input and result vector types are of same width, extend
2482       // operations should be done with SIGN/ZERO_EXTEND_VECTOR_INREG, which
2483       // accepts fewer elements in the result than in the input.
2484       if (Opcode == ISD::SIGN_EXTEND)
2485         return DAG.getSignExtendVectorInReg(InOp, DL, WidenVT);
2486       if (Opcode == ISD::ZERO_EXTEND)
2487         return DAG.getZeroExtendVectorInReg(InOp, DL, WidenVT);
2488     }
2489   }
2490
2491   if (TLI.isTypeLegal(InWidenVT)) {
2492     // Because the result and the input are different vector types, widening
2493     // the result could create a legal type but widening the input might make
2494     // it an illegal type that might lead to repeatedly splitting the input
2495     // and then widening it. To avoid this, we widen the input only if
2496     // it results in a legal type.
2497     if (WidenNumElts % InVTNumElts == 0) {
2498       // Widen the input and call convert on the widened input vector.
2499       unsigned NumConcat = WidenNumElts/InVTNumElts;
2500       SmallVector<SDValue, 16> Ops(NumConcat);
2501       Ops[0] = InOp;
2502       SDValue UndefVal = DAG.getUNDEF(InVT);
2503       for (unsigned i = 1; i != NumConcat; ++i)
2504         Ops[i] = UndefVal;
2505       SDValue InVec = DAG.getNode(ISD::CONCAT_VECTORS, DL, InWidenVT, Ops);
2506       if (N->getNumOperands() == 1)
2507         return DAG.getNode(Opcode, DL, WidenVT, InVec);
2508       return DAG.getNode(Opcode, DL, WidenVT, InVec, N->getOperand(1), Flags);
2509     }
2510
2511     if (InVTNumElts % WidenNumElts == 0) {
2512       SDValue InVal = DAG.getNode(
2513           ISD::EXTRACT_SUBVECTOR, DL, InWidenVT, InOp,
2514           DAG.getConstant(0, DL, TLI.getVectorIdxTy(DAG.getDataLayout())));
2515       // Extract the input and convert the shorten input vector.
2516       if (N->getNumOperands() == 1)
2517         return DAG.getNode(Opcode, DL, WidenVT, InVal);
2518       return DAG.getNode(Opcode, DL, WidenVT, InVal, N->getOperand(1), Flags);
2519     }
2520   }
2521
2522   // Otherwise unroll into some nasty scalar code and rebuild the vector.
2523   SmallVector<SDValue, 16> Ops(WidenNumElts);
2524   EVT EltVT = WidenVT.getVectorElementType();
2525   unsigned MinElts = std::min(InVTNumElts, WidenNumElts);
2526   unsigned i;
2527   for (i=0; i < MinElts; ++i) {
2528     SDValue Val = DAG.getNode(
2529         ISD::EXTRACT_VECTOR_ELT, DL, InEltVT, InOp,
2530         DAG.getConstant(i, DL, TLI.getVectorIdxTy(DAG.getDataLayout())));
2531     if (N->getNumOperands() == 1)
2532       Ops[i] = DAG.getNode(Opcode, DL, EltVT, Val);
2533     else
2534       Ops[i] = DAG.getNode(Opcode, DL, EltVT, Val, N->getOperand(1), Flags);
2535   }
2536
2537   SDValue UndefVal = DAG.getUNDEF(EltVT);
2538   for (; i < WidenNumElts; ++i)
2539     Ops[i] = UndefVal;
2540
2541   return DAG.getBuildVector(WidenVT, DL, Ops);
2542 }
2543
2544 SDValue DAGTypeLegalizer::WidenVecRes_EXTEND_VECTOR_INREG(SDNode *N) {
2545   unsigned Opcode = N->getOpcode();
2546   SDValue InOp = N->getOperand(0);
2547   SDLoc DL(N);
2548
2549   EVT WidenVT = TLI.getTypeToTransformTo(*DAG.getContext(), N->getValueType(0));
2550   EVT WidenSVT = WidenVT.getVectorElementType();
2551   unsigned WidenNumElts = WidenVT.getVectorNumElements();
2552
2553   EVT InVT = InOp.getValueType();
2554   EVT InSVT = InVT.getVectorElementType();
2555   unsigned InVTNumElts = InVT.getVectorNumElements();
2556
2557   if (getTypeAction(InVT) == TargetLowering::TypeWidenVector) {
2558     InOp = GetWidenedVector(InOp);
2559     InVT = InOp.getValueType();
2560     if (InVT.getSizeInBits() == WidenVT.getSizeInBits()) {
2561       switch (Opcode) {
2562       case ISD::ANY_EXTEND_VECTOR_INREG:
2563         return DAG.getAnyExtendVectorInReg(InOp, DL, WidenVT);
2564       case ISD::SIGN_EXTEND_VECTOR_INREG:
2565         return DAG.getSignExtendVectorInReg(InOp, DL, WidenVT);
2566       case ISD::ZERO_EXTEND_VECTOR_INREG:
2567         return DAG.getZeroExtendVectorInReg(InOp, DL, WidenVT);
2568       }
2569     }
2570   }
2571
2572   // Unroll, extend the scalars and rebuild the vector.
2573   SmallVector<SDValue, 16> Ops;
2574   for (unsigned i = 0, e = std::min(InVTNumElts, WidenNumElts); i != e; ++i) {
2575     SDValue Val = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, InSVT, InOp,
2576       DAG.getConstant(i, DL, TLI.getVectorIdxTy(DAG.getDataLayout())));
2577     switch (Opcode) {
2578     case ISD::ANY_EXTEND_VECTOR_INREG:
2579       Val = DAG.getNode(ISD::ANY_EXTEND, DL, WidenSVT, Val);
2580       break;
2581     case ISD::SIGN_EXTEND_VECTOR_INREG:
2582       Val = DAG.getNode(ISD::SIGN_EXTEND, DL, WidenSVT, Val);
2583       break;
2584     case ISD::ZERO_EXTEND_VECTOR_INREG:
2585       Val = DAG.getNode(ISD::ZERO_EXTEND, DL, WidenSVT, Val);
2586       break;
2587     default:
2588       llvm_unreachable("A *_EXTEND_VECTOR_INREG node was expected");
2589     }
2590     Ops.push_back(Val);
2591   }
2592
2593   while (Ops.size() != WidenNumElts)
2594     Ops.push_back(DAG.getUNDEF(WidenSVT));
2595
2596   return DAG.getBuildVector(WidenVT, DL, Ops);
2597 }
2598
2599 SDValue DAGTypeLegalizer::WidenVecRes_FCOPYSIGN(SDNode *N) {
2600   // If this is an FCOPYSIGN with same input types, we can treat it as a
2601   // normal (can trap) binary op.
2602   if (N->getOperand(0).getValueType() == N->getOperand(1).getValueType())
2603     return WidenVecRes_BinaryCanTrap(N);
2604
2605   // If the types are different, fall back to unrolling.
2606   EVT WidenVT = TLI.getTypeToTransformTo(*DAG.getContext(), N->getValueType(0));
2607   return DAG.UnrollVectorOp(N, WidenVT.getVectorNumElements());
2608 }
2609
2610 SDValue DAGTypeLegalizer::WidenVecRes_POWI(SDNode *N) {
2611   EVT WidenVT = TLI.getTypeToTransformTo(*DAG.getContext(), N->getValueType(0));
2612   SDValue InOp = GetWidenedVector(N->getOperand(0));
2613   SDValue ShOp = N->getOperand(1);
2614   return DAG.getNode(N->getOpcode(), SDLoc(N), WidenVT, InOp, ShOp);
2615 }
2616
2617 SDValue DAGTypeLegalizer::WidenVecRes_Shift(SDNode *N) {
2618   EVT WidenVT = TLI.getTypeToTransformTo(*DAG.getContext(), N->getValueType(0));
2619   SDValue InOp = GetWidenedVector(N->getOperand(0));
2620   SDValue ShOp = N->getOperand(1);
2621
2622   EVT ShVT = ShOp.getValueType();
2623   if (getTypeAction(ShVT) == TargetLowering::TypeWidenVector) {
2624     ShOp = GetWidenedVector(ShOp);
2625     ShVT = ShOp.getValueType();
2626   }
2627   EVT ShWidenVT = EVT::getVectorVT(*DAG.getContext(),
2628                                    ShVT.getVectorElementType(),
2629                                    WidenVT.getVectorNumElements());
2630   if (ShVT != ShWidenVT)
2631     ShOp = ModifyToType(ShOp, ShWidenVT);
2632
2633   return DAG.getNode(N->getOpcode(), SDLoc(N), WidenVT, InOp, ShOp);
2634 }
2635
2636 SDValue DAGTypeLegalizer::WidenVecRes_Unary(SDNode *N) {
2637   // Unary op widening.
2638   EVT WidenVT = TLI.getTypeToTransformTo(*DAG.getContext(), N->getValueType(0));
2639   SDValue InOp = GetWidenedVector(N->getOperand(0));
2640   return DAG.getNode(N->getOpcode(), SDLoc(N), WidenVT, InOp);
2641 }
2642
2643 SDValue DAGTypeLegalizer::WidenVecRes_InregOp(SDNode *N) {
2644   EVT WidenVT = TLI.getTypeToTransformTo(*DAG.getContext(), N->getValueType(0));
2645   EVT ExtVT = EVT::getVectorVT(*DAG.getContext(),
2646                                cast<VTSDNode>(N->getOperand(1))->getVT()
2647                                  .getVectorElementType(),
2648                                WidenVT.getVectorNumElements());
2649   SDValue WidenLHS = GetWidenedVector(N->getOperand(0));
2650   return DAG.getNode(N->getOpcode(), SDLoc(N),
2651                      WidenVT, WidenLHS, DAG.getValueType(ExtVT));
2652 }
2653
2654 SDValue DAGTypeLegalizer::WidenVecRes_MERGE_VALUES(SDNode *N, unsigned ResNo) {
2655   SDValue WidenVec = DisintegrateMERGE_VALUES(N, ResNo);
2656   return GetWidenedVector(WidenVec);
2657 }
2658
2659 SDValue DAGTypeLegalizer::WidenVecRes_BITCAST(SDNode *N) {
2660   SDValue InOp = N->getOperand(0);
2661   EVT InVT = InOp.getValueType();
2662   EVT VT = N->getValueType(0);
2663   EVT WidenVT = TLI.getTypeToTransformTo(*DAG.getContext(), VT);
2664   SDLoc dl(N);
2665
2666   switch (getTypeAction(InVT)) {
2667   case TargetLowering::TypeLegal:
2668     break;
2669   case TargetLowering::TypePromoteInteger:
2670     // If the incoming type is a vector that is being promoted, then
2671     // we know that the elements are arranged differently and that we
2672     // must perform the conversion using a stack slot.
2673     if (InVT.isVector())
2674       break;
2675
2676     // If the InOp is promoted to the same size, convert it.  Otherwise,
2677     // fall out of the switch and widen the promoted input.
2678     InOp = GetPromotedInteger(InOp);
2679     InVT = InOp.getValueType();
2680     if (WidenVT.bitsEq(InVT))
2681       return DAG.getNode(ISD::BITCAST, dl, WidenVT, InOp);
2682     break;
2683   case TargetLowering::TypeSoftenFloat:
2684   case TargetLowering::TypePromoteFloat:
2685   case TargetLowering::TypeExpandInteger:
2686   case TargetLowering::TypeExpandFloat:
2687   case TargetLowering::TypeScalarizeVector:
2688   case TargetLowering::TypeSplitVector:
2689     break;
2690   case TargetLowering::TypeWidenVector:
2691     // If the InOp is widened to the same size, convert it.  Otherwise, fall
2692     // out of the switch and widen the widened input.
2693     InOp = GetWidenedVector(InOp);
2694     InVT = InOp.getValueType();
2695     if (WidenVT.bitsEq(InVT))
2696       // The input widens to the same size. Convert to the widen value.
2697       return DAG.getNode(ISD::BITCAST, dl, WidenVT, InOp);
2698     break;
2699   }
2700
2701   unsigned WidenSize = WidenVT.getSizeInBits();
2702   unsigned InSize = InVT.getSizeInBits();
2703   // x86mmx is not an acceptable vector element type, so don't try.
2704   if (WidenSize % InSize == 0 && InVT != MVT::x86mmx) {
2705     // Determine new input vector type.  The new input vector type will use
2706     // the same element type (if its a vector) or use the input type as a
2707     // vector.  It is the same size as the type to widen to.
2708     EVT NewInVT;
2709     unsigned NewNumElts = WidenSize / InSize;
2710     if (InVT.isVector()) {
2711       EVT InEltVT = InVT.getVectorElementType();
2712       NewInVT = EVT::getVectorVT(*DAG.getContext(), InEltVT,
2713                                  WidenSize / InEltVT.getSizeInBits());
2714     } else {
2715       NewInVT = EVT::getVectorVT(*DAG.getContext(), InVT, NewNumElts);
2716     }
2717
2718     if (TLI.isTypeLegal(NewInVT)) {
2719       // Because the result and the input are different vector types, widening
2720       // the result could create a legal type but widening the input might make
2721       // it an illegal type that might lead to repeatedly splitting the input
2722       // and then widening it. To avoid this, we widen the input only if
2723       // it results in a legal type.
2724       SmallVector<SDValue, 16> Ops(NewNumElts);
2725       SDValue UndefVal = DAG.getUNDEF(InVT);
2726       Ops[0] = InOp;
2727       for (unsigned i = 1; i < NewNumElts; ++i)
2728         Ops[i] = UndefVal;
2729
2730       SDValue NewVec;
2731       if (InVT.isVector())
2732         NewVec = DAG.getNode(ISD::CONCAT_VECTORS, dl, NewInVT, Ops);
2733       else
2734         NewVec = DAG.getBuildVector(NewInVT, dl, Ops);
2735       return DAG.getNode(ISD::BITCAST, dl, WidenVT, NewVec);
2736     }
2737   }
2738
2739   return CreateStackStoreLoad(InOp, WidenVT);
2740 }
2741
2742 SDValue DAGTypeLegalizer::WidenVecRes_BUILD_VECTOR(SDNode *N) {
2743   SDLoc dl(N);
2744   // Build a vector with undefined for the new nodes.
2745   EVT VT = N->getValueType(0);
2746
2747   // Integer BUILD_VECTOR operands may be larger than the node's vector element
2748   // type. The UNDEFs need to have the same type as the existing operands.
2749   EVT EltVT = N->getOperand(0).getValueType();
2750   unsigned NumElts = VT.getVectorNumElements();
2751
2752   EVT WidenVT = TLI.getTypeToTransformTo(*DAG.getContext(), VT);
2753   unsigned WidenNumElts = WidenVT.getVectorNumElements();
2754
2755   SmallVector<SDValue, 16> NewOps(N->op_begin(), N->op_end());
2756   assert(WidenNumElts >= NumElts && "Shrinking vector instead of widening!");
2757   NewOps.append(WidenNumElts - NumElts, DAG.getUNDEF(EltVT));
2758
2759   return DAG.getBuildVector(WidenVT, dl, NewOps);
2760 }
2761
2762 SDValue DAGTypeLegalizer::WidenVecRes_CONCAT_VECTORS(SDNode *N) {
2763   EVT InVT = N->getOperand(0).getValueType();
2764   EVT WidenVT = TLI.getTypeToTransformTo(*DAG.getContext(), N->getValueType(0));
2765   SDLoc dl(N);
2766   unsigned WidenNumElts = WidenVT.getVectorNumElements();
2767   unsigned NumInElts = InVT.getVectorNumElements();
2768   unsigned NumOperands = N->getNumOperands();
2769
2770   bool InputWidened = false; // Indicates we need to widen the input.
2771   if (getTypeAction(InVT) != TargetLowering::TypeWidenVector) {
2772     if (WidenVT.getVectorNumElements() % InVT.getVectorNumElements() == 0) {
2773       // Add undef vectors to widen to correct length.
2774       unsigned NumConcat = WidenVT.getVectorNumElements() /
2775                            InVT.getVectorNumElements();
2776       SDValue UndefVal = DAG.getUNDEF(InVT);
2777       SmallVector<SDValue, 16> Ops(NumConcat);
2778       for (unsigned i=0; i < NumOperands; ++i)
2779         Ops[i] = N->getOperand(i);
2780       for (unsigned i = NumOperands; i != NumConcat; ++i)
2781         Ops[i] = UndefVal;
2782       return DAG.getNode(ISD::CONCAT_VECTORS, dl, WidenVT, Ops);
2783     }
2784   } else {
2785     InputWidened = true;
2786     if (WidenVT == TLI.getTypeToTransformTo(*DAG.getContext(), InVT)) {
2787       // The inputs and the result are widen to the same value.
2788       unsigned i;
2789       for (i=1; i < NumOperands; ++i)
2790         if (!N->getOperand(i).isUndef())
2791           break;
2792
2793       if (i == NumOperands)
2794         // Everything but the first operand is an UNDEF so just return the
2795         // widened first operand.
2796         return GetWidenedVector(N->getOperand(0));
2797
2798       if (NumOperands == 2) {
2799         // Replace concat of two operands with a shuffle.
2800         SmallVector<int, 16> MaskOps(WidenNumElts, -1);
2801         for (unsigned i = 0; i < NumInElts; ++i) {
2802           MaskOps[i] = i;
2803           MaskOps[i + NumInElts] = i + WidenNumElts;
2804         }
2805         return DAG.getVectorShuffle(WidenVT, dl,
2806                                     GetWidenedVector(N->getOperand(0)),
2807                                     GetWidenedVector(N->getOperand(1)),
2808                                     MaskOps);
2809       }
2810     }
2811   }
2812
2813   // Fall back to use extracts and build vector.
2814   EVT EltVT = WidenVT.getVectorElementType();
2815   SmallVector<SDValue, 16> Ops(WidenNumElts);
2816   unsigned Idx = 0;
2817   for (unsigned i=0; i < NumOperands; ++i) {
2818     SDValue InOp = N->getOperand(i);
2819     if (InputWidened)
2820       InOp = GetWidenedVector(InOp);
2821     for (unsigned j=0; j < NumInElts; ++j)
2822       Ops[Idx++] = DAG.getNode(
2823           ISD::EXTRACT_VECTOR_ELT, dl, EltVT, InOp,
2824           DAG.getConstant(j, dl, TLI.getVectorIdxTy(DAG.getDataLayout())));
2825   }
2826   SDValue UndefVal = DAG.getUNDEF(EltVT);
2827   for (; Idx < WidenNumElts; ++Idx)
2828     Ops[Idx] = UndefVal;
2829   return DAG.getBuildVector(WidenVT, dl, Ops);
2830 }
2831
2832 SDValue DAGTypeLegalizer::WidenVecRes_EXTRACT_SUBVECTOR(SDNode *N) {
2833   EVT      VT = N->getValueType(0);
2834   EVT      WidenVT = TLI.getTypeToTransformTo(*DAG.getContext(), VT);
2835   unsigned WidenNumElts = WidenVT.getVectorNumElements();
2836   SDValue  InOp = N->getOperand(0);
2837   SDValue  Idx  = N->getOperand(1);
2838   SDLoc dl(N);
2839
2840   if (getTypeAction(InOp.getValueType()) == TargetLowering::TypeWidenVector)
2841     InOp = GetWidenedVector(InOp);
2842
2843   EVT InVT = InOp.getValueType();
2844
2845   // Check if we can just return the input vector after widening.
2846   uint64_t IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
2847   if (IdxVal == 0 && InVT == WidenVT)
2848     return InOp;
2849
2850   // Check if we can extract from the vector.
2851   unsigned InNumElts = InVT.getVectorNumElements();
2852   if (IdxVal % WidenNumElts == 0 && IdxVal + WidenNumElts < InNumElts)
2853     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, WidenVT, InOp, Idx);
2854
2855   // We could try widening the input to the right length but for now, extract
2856   // the original elements, fill the rest with undefs and build a vector.
2857   SmallVector<SDValue, 16> Ops(WidenNumElts);
2858   EVT EltVT = VT.getVectorElementType();
2859   unsigned NumElts = VT.getVectorNumElements();
2860   unsigned i;
2861   for (i=0; i < NumElts; ++i)
2862     Ops[i] =
2863         DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT, InOp,
2864                     DAG.getConstant(IdxVal + i, dl,
2865                                     TLI.getVectorIdxTy(DAG.getDataLayout())));
2866
2867   SDValue UndefVal = DAG.getUNDEF(EltVT);
2868   for (; i < WidenNumElts; ++i)
2869     Ops[i] = UndefVal;
2870   return DAG.getBuildVector(WidenVT, dl, Ops);
2871 }
2872
2873 SDValue DAGTypeLegalizer::WidenVecRes_INSERT_VECTOR_ELT(SDNode *N) {
2874   SDValue InOp = GetWidenedVector(N->getOperand(0));
2875   return DAG.getNode(ISD::INSERT_VECTOR_ELT, SDLoc(N),
2876                      InOp.getValueType(), InOp,
2877                      N->getOperand(1), N->getOperand(2));
2878 }
2879
2880 SDValue DAGTypeLegalizer::WidenVecRes_LOAD(SDNode *N) {
2881   LoadSDNode *LD = cast<LoadSDNode>(N);
2882   ISD::LoadExtType ExtType = LD->getExtensionType();
2883
2884   SDValue Result;
2885   SmallVector<SDValue, 16> LdChain;  // Chain for the series of load
2886   if (ExtType != ISD::NON_EXTLOAD)
2887     Result = GenWidenVectorExtLoads(LdChain, LD, ExtType);
2888   else
2889     Result = GenWidenVectorLoads(LdChain, LD);
2890
2891   // If we generate a single load, we can use that for the chain.  Otherwise,
2892   // build a factor node to remember the multiple loads are independent and
2893   // chain to that.
2894   SDValue NewChain;
2895   if (LdChain.size() == 1)
2896     NewChain = LdChain[0];
2897   else
2898     NewChain = DAG.getNode(ISD::TokenFactor, SDLoc(LD), MVT::Other, LdChain);
2899
2900   // Modified the chain - switch anything that used the old chain to use
2901   // the new one.
2902   ReplaceValueWith(SDValue(N, 1), NewChain);
2903
2904   return Result;
2905 }
2906
2907 SDValue DAGTypeLegalizer::WidenVecRes_MLOAD(MaskedLoadSDNode *N) {
2908
2909   EVT WidenVT = TLI.getTypeToTransformTo(*DAG.getContext(),N->getValueType(0));
2910   SDValue Mask = N->getMask();
2911   EVT MaskVT = Mask.getValueType();
2912   SDValue Src0 = GetWidenedVector(N->getSrc0());
2913   ISD::LoadExtType ExtType = N->getExtensionType();
2914   SDLoc dl(N);
2915
2916   // The mask should be widened as well
2917   EVT WideMaskVT = EVT::getVectorVT(*DAG.getContext(),
2918                                     MaskVT.getVectorElementType(),
2919                                     WidenVT.getVectorNumElements());
2920   Mask = ModifyToType(Mask, WideMaskVT, true);
2921
2922   SDValue Res = DAG.getMaskedLoad(WidenVT, dl, N->getChain(), N->getBasePtr(),
2923                                   Mask, Src0, N->getMemoryVT(),
2924                                   N->getMemOperand(), ExtType,
2925                                         N->isExpandingLoad());
2926   // Legalize the chain result - switch anything that used the old chain to
2927   // use the new one.
2928   ReplaceValueWith(SDValue(N, 1), Res.getValue(1));
2929   return Res;
2930 }
2931
2932 SDValue DAGTypeLegalizer::WidenVecRes_MGATHER(MaskedGatherSDNode *N) {
2933
2934   EVT WideVT = TLI.getTypeToTransformTo(*DAG.getContext(), N->getValueType(0));
2935   SDValue Mask = N->getMask();
2936   EVT MaskVT = Mask.getValueType();
2937   SDValue Src0 = GetWidenedVector(N->getValue());
2938   unsigned NumElts = WideVT.getVectorNumElements();
2939   SDLoc dl(N);
2940
2941   // The mask should be widened as well
2942   EVT WideMaskVT = EVT::getVectorVT(*DAG.getContext(),
2943                                     MaskVT.getVectorElementType(),
2944                                     WideVT.getVectorNumElements());
2945   Mask = ModifyToType(Mask, WideMaskVT, true);
2946
2947   // Widen the Index operand
2948   SDValue Index = N->getIndex();
2949   EVT WideIndexVT = EVT::getVectorVT(*DAG.getContext(),
2950                                      Index.getValueType().getScalarType(),
2951                                      NumElts);
2952   Index = ModifyToType(Index, WideIndexVT);
2953   SDValue Ops[] = { N->getChain(), Src0, Mask, N->getBasePtr(), Index };
2954   SDValue Res = DAG.getMaskedGather(DAG.getVTList(WideVT, MVT::Other),
2955                                     N->getMemoryVT(), dl, Ops,
2956                                     N->getMemOperand());
2957
2958   // Legalize the chain result - switch anything that used the old chain to
2959   // use the new one.
2960   ReplaceValueWith(SDValue(N, 1), Res.getValue(1));
2961   return Res;
2962 }
2963
2964 SDValue DAGTypeLegalizer::WidenVecRes_SCALAR_TO_VECTOR(SDNode *N) {
2965   EVT WidenVT = TLI.getTypeToTransformTo(*DAG.getContext(), N->getValueType(0));
2966   return DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(N),
2967                      WidenVT, N->getOperand(0));
2968 }
2969
2970 // Return true if this is a node that could have two SETCCs as operands.
2971 static inline bool isLogicalMaskOp(unsigned Opcode) {
2972   switch (Opcode) {
2973   case ISD::AND:
2974   case ISD::OR:
2975   case ISD::XOR:
2976     return true;
2977   }
2978   return false;
2979 }
2980
2981 // This is used just for the assert in convertMask(). Check that this either
2982 // a SETCC or a previously handled SETCC by convertMask().
2983 #ifndef NDEBUG
2984 static inline bool isSETCCorConvertedSETCC(SDValue N) {
2985   if (N.getOpcode() == ISD::EXTRACT_SUBVECTOR)
2986     N = N.getOperand(0);
2987   else if (N.getOpcode() == ISD::CONCAT_VECTORS) {
2988     for (unsigned i = 1; i < N->getNumOperands(); ++i)
2989       if (!N->getOperand(i)->isUndef())
2990         return false;
2991     N = N.getOperand(0);
2992   }
2993
2994   if (N.getOpcode() == ISD::TRUNCATE)
2995     N = N.getOperand(0);
2996   else if (N.getOpcode() == ISD::SIGN_EXTEND)
2997     N = N.getOperand(0);
2998
2999   if (isLogicalMaskOp(N.getOpcode()))
3000     return isSETCCorConvertedSETCC(N.getOperand(0)) &&
3001            isSETCCorConvertedSETCC(N.getOperand(1));
3002
3003   return (N.getOpcode() == ISD::SETCC ||
3004           ISD::isBuildVectorOfConstantSDNodes(N.getNode()));
3005 }
3006 #endif
3007
3008 // Return a mask of vector type MaskVT to replace InMask. Also adjust MaskVT
3009 // to ToMaskVT if needed with vector extension or truncation.
3010 SDValue DAGTypeLegalizer::convertMask(SDValue InMask, EVT MaskVT,
3011                                       EVT ToMaskVT) {
3012   // Currently a SETCC or a AND/OR/XOR with two SETCCs are handled.
3013   // FIXME: This code seems to be too restrictive, we might consider
3014   // generalizing it or dropping it.
3015   assert(isSETCCorConvertedSETCC(InMask) && "Unexpected mask argument.");
3016
3017   // Make a new Mask node, with a legal result VT.
3018   SmallVector<SDValue, 4> Ops;
3019   for (unsigned i = 0, e = InMask->getNumOperands(); i < e; ++i)
3020     Ops.push_back(InMask->getOperand(i));
3021   SDValue Mask = DAG.getNode(InMask->getOpcode(), SDLoc(InMask), MaskVT, Ops);
3022
3023   // If MaskVT has smaller or bigger elements than ToMaskVT, a vector sign
3024   // extend or truncate is needed.
3025   LLVMContext &Ctx = *DAG.getContext();
3026   unsigned MaskScalarBits = MaskVT.getScalarSizeInBits();
3027   unsigned ToMaskScalBits = ToMaskVT.getScalarSizeInBits();
3028   if (MaskScalarBits < ToMaskScalBits) {
3029     EVT ExtVT = EVT::getVectorVT(Ctx, ToMaskVT.getVectorElementType(),
3030                                  MaskVT.getVectorNumElements());
3031     Mask = DAG.getNode(ISD::SIGN_EXTEND, SDLoc(Mask), ExtVT, Mask);
3032   } else if (MaskScalarBits > ToMaskScalBits) {
3033     EVT TruncVT = EVT::getVectorVT(Ctx, ToMaskVT.getVectorElementType(),
3034                                    MaskVT.getVectorNumElements());
3035     Mask = DAG.getNode(ISD::TRUNCATE, SDLoc(Mask), TruncVT, Mask);
3036   }
3037
3038   assert(Mask->getValueType(0).getScalarSizeInBits() ==
3039              ToMaskVT.getScalarSizeInBits() &&
3040          "Mask should have the right element size by now.");
3041
3042   // Adjust Mask to the right number of elements.
3043   unsigned CurrMaskNumEls = Mask->getValueType(0).getVectorNumElements();
3044   if (CurrMaskNumEls > ToMaskVT.getVectorNumElements()) {
3045     MVT IdxTy = TLI.getVectorIdxTy(DAG.getDataLayout());
3046     SDValue ZeroIdx = DAG.getConstant(0, SDLoc(Mask), IdxTy);
3047     Mask = DAG.getNode(ISD::EXTRACT_SUBVECTOR, SDLoc(Mask), ToMaskVT, Mask,
3048                        ZeroIdx);
3049   } else if (CurrMaskNumEls < ToMaskVT.getVectorNumElements()) {
3050     unsigned NumSubVecs = (ToMaskVT.getVectorNumElements() / CurrMaskNumEls);
3051     EVT SubVT = Mask->getValueType(0);
3052     SmallVector<SDValue, 16> SubOps(NumSubVecs, DAG.getUNDEF(SubVT));
3053     SubOps[0] = Mask;
3054     Mask = DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(Mask), ToMaskVT, SubOps);
3055   }
3056
3057   assert((Mask->getValueType(0) == ToMaskVT) &&
3058          "A mask of ToMaskVT should have been produced by now.");
3059
3060   return Mask;
3061 }
3062
3063 // Get the target mask VT, and widen if needed.
3064 EVT DAGTypeLegalizer::getSETCCWidenedResultTy(SDValue SetCC) {
3065   assert(SetCC->getOpcode() == ISD::SETCC);
3066   LLVMContext &Ctx = *DAG.getContext();
3067   EVT MaskVT = getSetCCResultType(SetCC->getOperand(0).getValueType());
3068   if (getTypeAction(MaskVT) == TargetLowering::TypeWidenVector)
3069     MaskVT = TLI.getTypeToTransformTo(Ctx, MaskVT);
3070   return MaskVT;
3071 }
3072
3073 // This method tries to handle VSELECT and its mask by legalizing operands
3074 // (which may require widening) and if needed adjusting the mask vector type
3075 // to match that of the VSELECT. Without it, many cases end up with
3076 // scalarization of the SETCC, with many unnecessary instructions.
3077 SDValue DAGTypeLegalizer::WidenVSELECTAndMask(SDNode *N) {
3078   LLVMContext &Ctx = *DAG.getContext();
3079   SDValue Cond = N->getOperand(0);
3080
3081   if (N->getOpcode() != ISD::VSELECT)
3082     return SDValue();
3083
3084   if (Cond->getOpcode() != ISD::SETCC && !isLogicalMaskOp(Cond->getOpcode()))
3085     return SDValue();
3086
3087   // If this is a splitted VSELECT that was previously already handled, do
3088   // nothing.
3089   EVT CondVT = Cond->getValueType(0);
3090   if (CondVT.getScalarSizeInBits() != 1)
3091     return SDValue();
3092
3093   EVT VSelVT = N->getValueType(0);
3094   // Only handle vector types which are a power of 2.
3095   if (!isPowerOf2_64(VSelVT.getSizeInBits()))
3096     return SDValue();
3097
3098   // Don't touch if this will be scalarized.
3099   EVT FinalVT = VSelVT;
3100   while (getTypeAction(FinalVT) == TargetLowering::TypeSplitVector)
3101     FinalVT = FinalVT.getHalfNumVectorElementsVT(Ctx);
3102
3103   if (FinalVT.getVectorNumElements() == 1)
3104     return SDValue();
3105
3106   // If there is support for an i1 vector mask, don't touch.
3107   if (Cond.getOpcode() == ISD::SETCC) {
3108     EVT SetCCOpVT = Cond->getOperand(0).getValueType();
3109     while (TLI.getTypeAction(Ctx, SetCCOpVT) != TargetLowering::TypeLegal)
3110       SetCCOpVT = TLI.getTypeToTransformTo(Ctx, SetCCOpVT);
3111     EVT SetCCResVT = getSetCCResultType(SetCCOpVT);
3112     if (SetCCResVT.getScalarSizeInBits() == 1)
3113       return SDValue();
3114   } else if (CondVT.getScalarType() == MVT::i1) {
3115     // If there is support for an i1 vector mask (or only scalar i1 conditions),
3116     // don't touch.
3117     while (TLI.getTypeAction(Ctx, CondVT) != TargetLowering::TypeLegal)
3118       CondVT = TLI.getTypeToTransformTo(Ctx, CondVT);
3119
3120     if (CondVT.getScalarType() == MVT::i1)
3121       return SDValue();
3122   }
3123
3124   // Get the VT and operands for VSELECT, and widen if needed.
3125   SDValue VSelOp1 = N->getOperand(1);
3126   SDValue VSelOp2 = N->getOperand(2);
3127   if (getTypeAction(VSelVT) == TargetLowering::TypeWidenVector) {
3128     VSelVT = TLI.getTypeToTransformTo(Ctx, VSelVT);
3129     VSelOp1 = GetWidenedVector(VSelOp1);
3130     VSelOp2 = GetWidenedVector(VSelOp2);
3131   }
3132
3133   // The mask of the VSELECT should have integer elements.
3134   EVT ToMaskVT = VSelVT;
3135   if (!ToMaskVT.getScalarType().isInteger())
3136     ToMaskVT = ToMaskVT.changeVectorElementTypeToInteger();
3137
3138   SDValue Mask;
3139   if (Cond->getOpcode() == ISD::SETCC) {
3140     EVT MaskVT = getSETCCWidenedResultTy(Cond);
3141     Mask = convertMask(Cond, MaskVT, ToMaskVT);
3142   } else if (isLogicalMaskOp(Cond->getOpcode()) &&
3143              Cond->getOperand(0).getOpcode() == ISD::SETCC &&
3144              Cond->getOperand(1).getOpcode() == ISD::SETCC) {
3145     // Cond is (AND/OR/XOR (SETCC, SETCC))
3146     SDValue SETCC0 = Cond->getOperand(0);
3147     SDValue SETCC1 = Cond->getOperand(1);
3148     EVT VT0 = getSETCCWidenedResultTy(SETCC0);
3149     EVT VT1 = getSETCCWidenedResultTy(SETCC1);
3150     unsigned ScalarBits0 = VT0.getScalarSizeInBits();
3151     unsigned ScalarBits1 = VT1.getScalarSizeInBits();
3152     unsigned ScalarBits_ToMask = ToMaskVT.getScalarSizeInBits();
3153     EVT MaskVT;
3154     // If the two SETCCs have different VTs, either extend/truncate one of
3155     // them to the other "towards" ToMaskVT, or truncate one and extend the
3156     // other to ToMaskVT.
3157     if (ScalarBits0 != ScalarBits1) {
3158       EVT NarrowVT = ((ScalarBits0 < ScalarBits1) ? VT0 : VT1);
3159       EVT WideVT = ((NarrowVT == VT0) ? VT1 : VT0);
3160       if (ScalarBits_ToMask >= WideVT.getScalarSizeInBits())
3161         MaskVT = WideVT;
3162       else if (ScalarBits_ToMask <= NarrowVT.getScalarSizeInBits())
3163         MaskVT = NarrowVT;
3164       else
3165         MaskVT = ToMaskVT;
3166     } else
3167       // If the two SETCCs have the same VT, don't change it.
3168       MaskVT = VT0;
3169
3170     // Make new SETCCs and logical nodes.
3171     SETCC0 = convertMask(SETCC0, VT0, MaskVT);
3172     SETCC1 = convertMask(SETCC1, VT1, MaskVT);
3173     Cond = DAG.getNode(Cond->getOpcode(), SDLoc(Cond), MaskVT, SETCC0, SETCC1);
3174
3175     // Convert the logical op for VSELECT if needed.
3176     Mask = convertMask(Cond, MaskVT, ToMaskVT);
3177   } else
3178     return SDValue();
3179
3180   return DAG.getNode(ISD::VSELECT, SDLoc(N), VSelVT, Mask, VSelOp1, VSelOp2);
3181 }
3182
3183 SDValue DAGTypeLegalizer::WidenVecRes_SELECT(SDNode *N) {
3184   EVT WidenVT = TLI.getTypeToTransformTo(*DAG.getContext(), N->getValueType(0));
3185   unsigned WidenNumElts = WidenVT.getVectorNumElements();
3186
3187   SDValue Cond1 = N->getOperand(0);
3188   EVT CondVT = Cond1.getValueType();
3189   if (CondVT.isVector()) {
3190     if (SDValue Res = WidenVSELECTAndMask(N))
3191       return Res;
3192
3193     EVT CondEltVT = CondVT.getVectorElementType();
3194     EVT CondWidenVT =  EVT::getVectorVT(*DAG.getContext(),
3195                                         CondEltVT, WidenNumElts);
3196     if (getTypeAction(CondVT) == TargetLowering::TypeWidenVector)
3197       Cond1 = GetWidenedVector(Cond1);
3198
3199     // If we have to split the condition there is no point in widening the
3200     // select. This would result in an cycle of widening the select ->
3201     // widening the condition operand -> splitting the condition operand ->
3202     // splitting the select -> widening the select. Instead split this select
3203     // further and widen the resulting type.
3204     if (getTypeAction(CondVT) == TargetLowering::TypeSplitVector) {
3205       SDValue SplitSelect = SplitVecOp_VSELECT(N, 0);
3206       SDValue Res = ModifyToType(SplitSelect, WidenVT);
3207       return Res;
3208     }
3209
3210     if (Cond1.getValueType() != CondWidenVT)
3211       Cond1 = ModifyToType(Cond1, CondWidenVT);
3212   }
3213
3214   SDValue InOp1 = GetWidenedVector(N->getOperand(1));
3215   SDValue InOp2 = GetWidenedVector(N->getOperand(2));
3216   assert(InOp1.getValueType() == WidenVT && InOp2.getValueType() == WidenVT);
3217   return DAG.getNode(N->getOpcode(), SDLoc(N),
3218                      WidenVT, Cond1, InOp1, InOp2);
3219 }
3220
3221 SDValue DAGTypeLegalizer::WidenVecRes_SELECT_CC(SDNode *N) {
3222   SDValue InOp1 = GetWidenedVector(N->getOperand(2));
3223   SDValue InOp2 = GetWidenedVector(N->getOperand(3));
3224   return DAG.getNode(ISD::SELECT_CC, SDLoc(N),
3225                      InOp1.getValueType(), N->getOperand(0),
3226                      N->getOperand(1), InOp1, InOp2, N->getOperand(4));
3227 }
3228
3229 SDValue DAGTypeLegalizer::WidenVecRes_UNDEF(SDNode *N) {
3230  EVT WidenVT = TLI.getTypeToTransformTo(*DAG.getContext(), N->getValueType(0));
3231  return DAG.getUNDEF(WidenVT);
3232 }
3233
3234 SDValue DAGTypeLegalizer::WidenVecRes_VECTOR_SHUFFLE(ShuffleVectorSDNode *N) {
3235   EVT VT = N->getValueType(0);
3236   SDLoc dl(N);
3237
3238   EVT WidenVT = TLI.getTypeToTransformTo(*DAG.getContext(), VT);
3239   unsigned NumElts = VT.getVectorNumElements();
3240   unsigned WidenNumElts = WidenVT.getVectorNumElements();
3241
3242   SDValue InOp1 = GetWidenedVector(N->getOperand(0));
3243   SDValue InOp2 = GetWidenedVector(N->getOperand(1));
3244
3245   // Adjust mask based on new input vector length.
3246   SmallVector<int, 16> NewMask;
3247   for (unsigned i = 0; i != NumElts; ++i) {
3248     int Idx = N->getMaskElt(i);
3249     if (Idx < (int)NumElts)
3250       NewMask.push_back(Idx);
3251     else
3252       NewMask.push_back(Idx - NumElts + WidenNumElts);
3253   }
3254   for (unsigned i = NumElts; i != WidenNumElts; ++i)
3255     NewMask.push_back(-1);
3256   return DAG.getVectorShuffle(WidenVT, dl, InOp1, InOp2, NewMask);
3257 }
3258
3259 SDValue DAGTypeLegalizer::WidenVecRes_SETCC(SDNode *N) {
3260   assert(N->getValueType(0).isVector() &&
3261          N->getOperand(0).getValueType().isVector() &&
3262          "Operands must be vectors");
3263   EVT WidenVT = TLI.getTypeToTransformTo(*DAG.getContext(), N->getValueType(0));
3264   unsigned WidenNumElts = WidenVT.getVectorNumElements();
3265
3266   SDValue InOp1 = N->getOperand(0);
3267   EVT InVT = InOp1.getValueType();
3268   assert(InVT.isVector() && "can not widen non-vector type");
3269   EVT WidenInVT = EVT::getVectorVT(*DAG.getContext(),
3270                                    InVT.getVectorElementType(), WidenNumElts);
3271
3272   // The input and output types often differ here, and it could be that while
3273   // we'd prefer to widen the result type, the input operands have been split.
3274   // In this case, we also need to split the result of this node as well.
3275   if (getTypeAction(InVT) == TargetLowering::TypeSplitVector) {
3276     SDValue SplitVSetCC = SplitVecOp_VSETCC(N);
3277     SDValue Res = ModifyToType(SplitVSetCC, WidenVT);
3278     return Res;
3279   }
3280
3281   InOp1 = GetWidenedVector(InOp1);
3282   SDValue InOp2 = GetWidenedVector(N->getOperand(1));
3283
3284   // Assume that the input and output will be widen appropriately.  If not,
3285   // we will have to unroll it at some point.
3286   assert(InOp1.getValueType() == WidenInVT &&
3287          InOp2.getValueType() == WidenInVT &&
3288          "Input not widened to expected type!");
3289   (void)WidenInVT;
3290   return DAG.getNode(ISD::SETCC, SDLoc(N),
3291                      WidenVT, InOp1, InOp2, N->getOperand(2));
3292 }
3293
3294
3295 //===----------------------------------------------------------------------===//
3296 // Widen Vector Operand
3297 //===----------------------------------------------------------------------===//
3298 bool DAGTypeLegalizer::WidenVectorOperand(SDNode *N, unsigned OpNo) {
3299   DEBUG(dbgs() << "Widen node operand " << OpNo << ": ";
3300         N->dump(&DAG);
3301         dbgs() << "\n");
3302   SDValue Res = SDValue();
3303
3304   // See if the target wants to custom widen this node.
3305   if (CustomLowerNode(N, N->getOperand(OpNo).getValueType(), false))
3306     return false;
3307
3308   switch (N->getOpcode()) {
3309   default:
3310 #ifndef NDEBUG
3311     dbgs() << "WidenVectorOperand op #" << OpNo << ": ";
3312     N->dump(&DAG);
3313     dbgs() << "\n";
3314 #endif
3315     llvm_unreachable("Do not know how to widen this operator's operand!");
3316
3317   case ISD::BITCAST:            Res = WidenVecOp_BITCAST(N); break;
3318   case ISD::CONCAT_VECTORS:     Res = WidenVecOp_CONCAT_VECTORS(N); break;
3319   case ISD::EXTRACT_SUBVECTOR:  Res = WidenVecOp_EXTRACT_SUBVECTOR(N); break;
3320   case ISD::EXTRACT_VECTOR_ELT: Res = WidenVecOp_EXTRACT_VECTOR_ELT(N); break;
3321   case ISD::STORE:              Res = WidenVecOp_STORE(N); break;
3322   case ISD::MSTORE:             Res = WidenVecOp_MSTORE(N, OpNo); break;
3323   case ISD::MSCATTER:           Res = WidenVecOp_MSCATTER(N, OpNo); break;
3324   case ISD::SETCC:              Res = WidenVecOp_SETCC(N); break;
3325   case ISD::FCOPYSIGN:          Res = WidenVecOp_FCOPYSIGN(N); break;
3326
3327   case ISD::ANY_EXTEND:
3328   case ISD::SIGN_EXTEND:
3329   case ISD::ZERO_EXTEND:
3330     Res = WidenVecOp_EXTEND(N);
3331     break;
3332
3333   case ISD::FP_EXTEND:
3334   case ISD::FP_TO_SINT:
3335   case ISD::FP_TO_UINT:
3336   case ISD::SINT_TO_FP:
3337   case ISD::UINT_TO_FP:
3338   case ISD::TRUNCATE:
3339     Res = WidenVecOp_Convert(N);
3340     break;
3341   }
3342
3343   // If Res is null, the sub-method took care of registering the result.
3344   if (!Res.getNode()) return false;
3345
3346   // If the result is N, the sub-method updated N in place.  Tell the legalizer
3347   // core about this.
3348   if (Res.getNode() == N)
3349     return true;
3350
3351
3352   assert(Res.getValueType() == N->getValueType(0) && N->getNumValues() == 1 &&
3353          "Invalid operand expansion");
3354
3355   ReplaceValueWith(SDValue(N, 0), Res);
3356   return false;
3357 }
3358
3359 SDValue DAGTypeLegalizer::WidenVecOp_EXTEND(SDNode *N) {
3360   SDLoc DL(N);
3361   EVT VT = N->getValueType(0);
3362
3363   SDValue InOp = N->getOperand(0);
3364   // If some legalization strategy other than widening is used on the operand,
3365   // we can't safely assume that just extending the low lanes is the correct
3366   // transformation.
3367   if (getTypeAction(InOp.getValueType()) != TargetLowering::TypeWidenVector)
3368     return WidenVecOp_Convert(N);
3369   InOp = GetWidenedVector(InOp);
3370   assert(VT.getVectorNumElements() <
3371              InOp.getValueType().getVectorNumElements() &&
3372          "Input wasn't widened!");
3373
3374   // We may need to further widen the operand until it has the same total
3375   // vector size as the result.
3376   EVT InVT = InOp.getValueType();
3377   if (InVT.getSizeInBits() != VT.getSizeInBits()) {
3378     EVT InEltVT = InVT.getVectorElementType();
3379     for (int i = MVT::FIRST_VECTOR_VALUETYPE, e = MVT::LAST_VECTOR_VALUETYPE; i < e; ++i) {
3380       EVT FixedVT = (MVT::SimpleValueType)i;
3381       EVT FixedEltVT = FixedVT.getVectorElementType();
3382       if (TLI.isTypeLegal(FixedVT) &&
3383           FixedVT.getSizeInBits() == VT.getSizeInBits() &&
3384           FixedEltVT == InEltVT) {
3385         assert(FixedVT.getVectorNumElements() >= VT.getVectorNumElements() &&
3386                "Not enough elements in the fixed type for the operand!");
3387         assert(FixedVT.getVectorNumElements() != InVT.getVectorNumElements() &&
3388                "We can't have the same type as we started with!");
3389         if (FixedVT.getVectorNumElements() > InVT.getVectorNumElements())
3390           InOp = DAG.getNode(
3391               ISD::INSERT_SUBVECTOR, DL, FixedVT, DAG.getUNDEF(FixedVT), InOp,
3392               DAG.getConstant(0, DL, TLI.getVectorIdxTy(DAG.getDataLayout())));
3393         else
3394           InOp = DAG.getNode(
3395               ISD::EXTRACT_SUBVECTOR, DL, FixedVT, InOp,
3396               DAG.getConstant(0, DL, TLI.getVectorIdxTy(DAG.getDataLayout())));
3397         break;
3398       }
3399     }
3400     InVT = InOp.getValueType();
3401     if (InVT.getSizeInBits() != VT.getSizeInBits())
3402       // We couldn't find a legal vector type that was a widening of the input
3403       // and could be extended in-register to the result type, so we have to
3404       // scalarize.
3405       return WidenVecOp_Convert(N);
3406   }
3407
3408   // Use special DAG nodes to represent the operation of extending the
3409   // low lanes.
3410   switch (N->getOpcode()) {
3411   default:
3412     llvm_unreachable("Extend legalization on on extend operation!");
3413   case ISD::ANY_EXTEND:
3414     return DAG.getAnyExtendVectorInReg(InOp, DL, VT);
3415   case ISD::SIGN_EXTEND:
3416     return DAG.getSignExtendVectorInReg(InOp, DL, VT);
3417   case ISD::ZERO_EXTEND:
3418     return DAG.getZeroExtendVectorInReg(InOp, DL, VT);
3419   }
3420 }
3421
3422 SDValue DAGTypeLegalizer::WidenVecOp_FCOPYSIGN(SDNode *N) {
3423   // The result (and first input) is legal, but the second input is illegal.
3424   // We can't do much to fix that, so just unroll and let the extracts off of
3425   // the second input be widened as needed later.
3426   return DAG.UnrollVectorOp(N);
3427 }
3428
3429 SDValue DAGTypeLegalizer::WidenVecOp_Convert(SDNode *N) {
3430   // Since the result is legal and the input is illegal, it is unlikely that we
3431   // can fix the input to a legal type so unroll the convert into some scalar
3432   // code and create a nasty build vector.
3433   EVT VT = N->getValueType(0);
3434   EVT EltVT = VT.getVectorElementType();
3435   SDLoc dl(N);
3436   unsigned NumElts = VT.getVectorNumElements();
3437   SDValue InOp = N->getOperand(0);
3438   if (getTypeAction(InOp.getValueType()) == TargetLowering::TypeWidenVector)
3439     InOp = GetWidenedVector(InOp);
3440   EVT InVT = InOp.getValueType();
3441   EVT InEltVT = InVT.getVectorElementType();
3442
3443   unsigned Opcode = N->getOpcode();
3444   SmallVector<SDValue, 16> Ops(NumElts);
3445   for (unsigned i=0; i < NumElts; ++i)
3446     Ops[i] = DAG.getNode(
3447         Opcode, dl, EltVT,
3448         DAG.getNode(
3449             ISD::EXTRACT_VECTOR_ELT, dl, InEltVT, InOp,
3450             DAG.getConstant(i, dl, TLI.getVectorIdxTy(DAG.getDataLayout()))));
3451
3452   return DAG.getBuildVector(VT, dl, Ops);
3453 }
3454
3455 SDValue DAGTypeLegalizer::WidenVecOp_BITCAST(SDNode *N) {
3456   EVT VT = N->getValueType(0);
3457   SDValue InOp = GetWidenedVector(N->getOperand(0));
3458   EVT InWidenVT = InOp.getValueType();
3459   SDLoc dl(N);
3460
3461   // Check if we can convert between two legal vector types and extract.
3462   unsigned InWidenSize = InWidenVT.getSizeInBits();
3463   unsigned Size = VT.getSizeInBits();
3464   // x86mmx is not an acceptable vector element type, so don't try.
3465   if (InWidenSize % Size == 0 && !VT.isVector() && VT != MVT::x86mmx) {
3466     unsigned NewNumElts = InWidenSize / Size;
3467     EVT NewVT = EVT::getVectorVT(*DAG.getContext(), VT, NewNumElts);
3468     if (TLI.isTypeLegal(NewVT)) {
3469       SDValue BitOp = DAG.getNode(ISD::BITCAST, dl, NewVT, InOp);
3470       return DAG.getNode(
3471           ISD::EXTRACT_VECTOR_ELT, dl, VT, BitOp,
3472           DAG.getConstant(0, dl, TLI.getVectorIdxTy(DAG.getDataLayout())));
3473     }
3474   }
3475
3476   return CreateStackStoreLoad(InOp, VT);
3477 }
3478
3479 SDValue DAGTypeLegalizer::WidenVecOp_CONCAT_VECTORS(SDNode *N) {
3480   // If the input vector is not legal, it is likely that we will not find a
3481   // legal vector of the same size. Replace the concatenate vector with a
3482   // nasty build vector.
3483   EVT VT = N->getValueType(0);
3484   EVT EltVT = VT.getVectorElementType();
3485   SDLoc dl(N);
3486   unsigned NumElts = VT.getVectorNumElements();
3487   SmallVector<SDValue, 16> Ops(NumElts);
3488
3489   EVT InVT = N->getOperand(0).getValueType();
3490   unsigned NumInElts = InVT.getVectorNumElements();
3491
3492   unsigned Idx = 0;
3493   unsigned NumOperands = N->getNumOperands();
3494   for (unsigned i=0; i < NumOperands; ++i) {
3495     SDValue InOp = N->getOperand(i);
3496     if (getTypeAction(InOp.getValueType()) == TargetLowering::TypeWidenVector)
3497       InOp = GetWidenedVector(InOp);
3498     for (unsigned j=0; j < NumInElts; ++j)
3499       Ops[Idx++] = DAG.getNode(
3500           ISD::EXTRACT_VECTOR_ELT, dl, EltVT, InOp,
3501           DAG.getConstant(j, dl, TLI.getVectorIdxTy(DAG.getDataLayout())));
3502   }
3503   return DAG.getBuildVector(VT, dl, Ops);
3504 }
3505
3506 SDValue DAGTypeLegalizer::WidenVecOp_EXTRACT_SUBVECTOR(SDNode *N) {
3507   SDValue InOp = GetWidenedVector(N->getOperand(0));
3508   return DAG.getNode(ISD::EXTRACT_SUBVECTOR, SDLoc(N),
3509                      N->getValueType(0), InOp, N->getOperand(1));
3510 }
3511
3512 SDValue DAGTypeLegalizer::WidenVecOp_EXTRACT_VECTOR_ELT(SDNode *N) {
3513   SDValue InOp = GetWidenedVector(N->getOperand(0));
3514   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SDLoc(N),
3515                      N->getValueType(0), InOp, N->getOperand(1));
3516 }
3517
3518 SDValue DAGTypeLegalizer::WidenVecOp_STORE(SDNode *N) {
3519   // We have to widen the value, but we want only to store the original
3520   // vector type.
3521   StoreSDNode *ST = cast<StoreSDNode>(N);
3522
3523   SmallVector<SDValue, 16> StChain;
3524   if (ST->isTruncatingStore())
3525     GenWidenVectorTruncStores(StChain, ST);
3526   else
3527     GenWidenVectorStores(StChain, ST);
3528
3529   if (StChain.size() == 1)
3530     return StChain[0];
3531   else
3532     return DAG.getNode(ISD::TokenFactor, SDLoc(ST), MVT::Other, StChain);
3533 }
3534
3535 SDValue DAGTypeLegalizer::WidenVecOp_MSTORE(SDNode *N, unsigned OpNo) {
3536   assert(OpNo == 3 && "Can widen only data operand of mstore");
3537   MaskedStoreSDNode *MST = cast<MaskedStoreSDNode>(N);
3538   SDValue Mask = MST->getMask();
3539   SDValue StVal = MST->getValue();
3540   // Widen the value
3541   SDValue WideVal = GetWidenedVector(StVal);
3542   SDLoc dl(N);
3543
3544   // The mask should be widened as well.
3545   Mask = WidenTargetBoolean(Mask, WideVal.getValueType(), true);
3546
3547   assert(Mask.getValueType().getVectorNumElements() ==
3548          WideVal.getValueType().getVectorNumElements() &&
3549          "Mask and data vectors should have the same number of elements");
3550   return DAG.getMaskedStore(MST->getChain(), dl, WideVal, MST->getBasePtr(),
3551                             Mask, MST->getMemoryVT(), MST->getMemOperand(),
3552                             false, MST->isCompressingStore());
3553 }
3554
3555 SDValue DAGTypeLegalizer::WidenVecOp_MSCATTER(SDNode *N, unsigned OpNo) {
3556   assert(OpNo == 1 && "Can widen only data operand of mscatter");
3557   MaskedScatterSDNode *MSC = cast<MaskedScatterSDNode>(N);
3558   SDValue DataOp = MSC->getValue();
3559   SDValue Mask = MSC->getMask();
3560
3561   // Widen the value.
3562   SDValue WideVal = GetWidenedVector(DataOp);
3563   EVT WideVT = WideVal.getValueType();
3564   unsigned NumElts = WideVal.getValueType().getVectorNumElements();
3565   SDLoc dl(N);
3566
3567   // The mask should be widened as well.
3568   Mask = WidenTargetBoolean(Mask, WideVT, true);
3569
3570   // Widen index.
3571   SDValue Index = MSC->getIndex();
3572   EVT WideIndexVT = EVT::getVectorVT(*DAG.getContext(),
3573                                      Index.getValueType().getScalarType(),
3574                                      NumElts);
3575   Index = ModifyToType(Index, WideIndexVT);
3576
3577   SDValue Ops[] = {MSC->getChain(), WideVal, Mask, MSC->getBasePtr(), Index};
3578   return DAG.getMaskedScatter(DAG.getVTList(MVT::Other),
3579                               MSC->getMemoryVT(), dl, Ops,
3580                               MSC->getMemOperand());
3581 }
3582
3583 SDValue DAGTypeLegalizer::WidenVecOp_SETCC(SDNode *N) {
3584   SDValue InOp0 = GetWidenedVector(N->getOperand(0));
3585   SDValue InOp1 = GetWidenedVector(N->getOperand(1));
3586   SDLoc dl(N);
3587
3588   // WARNING: In this code we widen the compare instruction with garbage.
3589   // This garbage may contain denormal floats which may be slow. Is this a real
3590   // concern ? Should we zero the unused lanes if this is a float compare ?
3591
3592   // Get a new SETCC node to compare the newly widened operands.
3593   // Only some of the compared elements are legal.
3594   EVT SVT = TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(),
3595                                    InOp0.getValueType());
3596   SDValue WideSETCC = DAG.getNode(ISD::SETCC, SDLoc(N),
3597                      SVT, InOp0, InOp1, N->getOperand(2));
3598
3599   // Extract the needed results from the result vector.
3600   EVT ResVT = EVT::getVectorVT(*DAG.getContext(),
3601                                SVT.getVectorElementType(),
3602                                N->getValueType(0).getVectorNumElements());
3603   SDValue CC = DAG.getNode(
3604       ISD::EXTRACT_SUBVECTOR, dl, ResVT, WideSETCC,
3605       DAG.getConstant(0, dl, TLI.getVectorIdxTy(DAG.getDataLayout())));
3606
3607   return PromoteTargetBoolean(CC, N->getValueType(0));
3608 }
3609
3610
3611 //===----------------------------------------------------------------------===//
3612 // Vector Widening Utilities
3613 //===----------------------------------------------------------------------===//
3614
3615 // Utility function to find the type to chop up a widen vector for load/store
3616 //  TLI:       Target lowering used to determine legal types.
3617 //  Width:     Width left need to load/store.
3618 //  WidenVT:   The widen vector type to load to/store from
3619 //  Align:     If 0, don't allow use of a wider type
3620 //  WidenEx:   If Align is not 0, the amount additional we can load/store from.
3621
3622 static EVT FindMemType(SelectionDAG& DAG, const TargetLowering &TLI,
3623                        unsigned Width, EVT WidenVT,
3624                        unsigned Align = 0, unsigned WidenEx = 0) {
3625   EVT WidenEltVT = WidenVT.getVectorElementType();
3626   unsigned WidenWidth = WidenVT.getSizeInBits();
3627   unsigned WidenEltWidth = WidenEltVT.getSizeInBits();
3628   unsigned AlignInBits = Align*8;
3629
3630   // If we have one element to load/store, return it.
3631   EVT RetVT = WidenEltVT;
3632   if (Width == WidenEltWidth)
3633     return RetVT;
3634
3635   // See if there is larger legal integer than the element type to load/store.
3636   unsigned VT;
3637   for (VT = (unsigned)MVT::LAST_INTEGER_VALUETYPE;
3638        VT >= (unsigned)MVT::FIRST_INTEGER_VALUETYPE; --VT) {
3639     EVT MemVT((MVT::SimpleValueType) VT);
3640     unsigned MemVTWidth = MemVT.getSizeInBits();
3641     if (MemVT.getSizeInBits() <= WidenEltWidth)
3642       break;
3643     auto Action = TLI.getTypeAction(*DAG.getContext(), MemVT);
3644     if ((Action == TargetLowering::TypeLegal ||
3645          Action == TargetLowering::TypePromoteInteger) &&
3646         (WidenWidth % MemVTWidth) == 0 &&
3647         isPowerOf2_32(WidenWidth / MemVTWidth) &&
3648         (MemVTWidth <= Width ||
3649          (Align!=0 && MemVTWidth<=AlignInBits && MemVTWidth<=Width+WidenEx))) {
3650       RetVT = MemVT;
3651       break;
3652     }
3653   }
3654
3655   // See if there is a larger vector type to load/store that has the same vector
3656   // element type and is evenly divisible with the WidenVT.
3657   for (VT = (unsigned)MVT::LAST_VECTOR_VALUETYPE;
3658        VT >= (unsigned)MVT::FIRST_VECTOR_VALUETYPE; --VT) {
3659     EVT MemVT = (MVT::SimpleValueType) VT;
3660     unsigned MemVTWidth = MemVT.getSizeInBits();
3661     if (TLI.isTypeLegal(MemVT) && WidenEltVT == MemVT.getVectorElementType() &&
3662         (WidenWidth % MemVTWidth) == 0 &&
3663         isPowerOf2_32(WidenWidth / MemVTWidth) &&
3664         (MemVTWidth <= Width ||
3665          (Align!=0 && MemVTWidth<=AlignInBits && MemVTWidth<=Width+WidenEx))) {
3666       if (RetVT.getSizeInBits() < MemVTWidth || MemVT == WidenVT)
3667         return MemVT;
3668     }
3669   }
3670
3671   return RetVT;
3672 }
3673
3674 // Builds a vector type from scalar loads
3675 //  VecTy: Resulting Vector type
3676 //  LDOps: Load operators to build a vector type
3677 //  [Start,End) the list of loads to use.
3678 static SDValue BuildVectorFromScalar(SelectionDAG& DAG, EVT VecTy,
3679                                      SmallVectorImpl<SDValue> &LdOps,
3680                                      unsigned Start, unsigned End) {
3681   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3682   SDLoc dl(LdOps[Start]);
3683   EVT LdTy = LdOps[Start].getValueType();
3684   unsigned Width = VecTy.getSizeInBits();
3685   unsigned NumElts = Width / LdTy.getSizeInBits();
3686   EVT NewVecVT = EVT::getVectorVT(*DAG.getContext(), LdTy, NumElts);
3687
3688   unsigned Idx = 1;
3689   SDValue VecOp = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, NewVecVT,LdOps[Start]);
3690
3691   for (unsigned i = Start + 1; i != End; ++i) {
3692     EVT NewLdTy = LdOps[i].getValueType();
3693     if (NewLdTy != LdTy) {
3694       NumElts = Width / NewLdTy.getSizeInBits();
3695       NewVecVT = EVT::getVectorVT(*DAG.getContext(), NewLdTy, NumElts);
3696       VecOp = DAG.getNode(ISD::BITCAST, dl, NewVecVT, VecOp);
3697       // Readjust position and vector position based on new load type.
3698       Idx = Idx * LdTy.getSizeInBits() / NewLdTy.getSizeInBits();
3699       LdTy = NewLdTy;
3700     }
3701     VecOp = DAG.getNode(
3702         ISD::INSERT_VECTOR_ELT, dl, NewVecVT, VecOp, LdOps[i],
3703         DAG.getConstant(Idx++, dl, TLI.getVectorIdxTy(DAG.getDataLayout())));
3704   }
3705   return DAG.getNode(ISD::BITCAST, dl, VecTy, VecOp);
3706 }
3707
3708 SDValue DAGTypeLegalizer::GenWidenVectorLoads(SmallVectorImpl<SDValue> &LdChain,
3709                                               LoadSDNode *LD) {
3710   // The strategy assumes that we can efficiently load power-of-two widths.
3711   // The routine chops the vector into the largest vector loads with the same
3712   // element type or scalar loads and then recombines it to the widen vector
3713   // type.
3714   EVT WidenVT = TLI.getTypeToTransformTo(*DAG.getContext(),LD->getValueType(0));
3715   unsigned WidenWidth = WidenVT.getSizeInBits();
3716   EVT LdVT    = LD->getMemoryVT();
3717   SDLoc dl(LD);
3718   assert(LdVT.isVector() && WidenVT.isVector());
3719   assert(LdVT.getVectorElementType() == WidenVT.getVectorElementType());
3720
3721   // Load information
3722   SDValue Chain = LD->getChain();
3723   SDValue BasePtr = LD->getBasePtr();
3724   unsigned Align = LD->getAlignment();
3725   MachineMemOperand::Flags MMOFlags = LD->getMemOperand()->getFlags();
3726   AAMDNodes AAInfo = LD->getAAInfo();
3727
3728   int LdWidth = LdVT.getSizeInBits();
3729   int WidthDiff = WidenWidth - LdWidth;
3730   unsigned LdAlign = LD->isVolatile() ? 0 : Align; // Allow wider loads.
3731
3732   // Find the vector type that can load from.
3733   EVT NewVT = FindMemType(DAG, TLI, LdWidth, WidenVT, LdAlign, WidthDiff);
3734   int NewVTWidth = NewVT.getSizeInBits();
3735   SDValue LdOp = DAG.getLoad(NewVT, dl, Chain, BasePtr, LD->getPointerInfo(),
3736                              Align, MMOFlags, AAInfo);
3737   LdChain.push_back(LdOp.getValue(1));
3738
3739   // Check if we can load the element with one instruction.
3740   if (LdWidth <= NewVTWidth) {
3741     if (!NewVT.isVector()) {
3742       unsigned NumElts = WidenWidth / NewVTWidth;
3743       EVT NewVecVT = EVT::getVectorVT(*DAG.getContext(), NewVT, NumElts);
3744       SDValue VecOp = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, NewVecVT, LdOp);
3745       return DAG.getNode(ISD::BITCAST, dl, WidenVT, VecOp);
3746     }
3747     if (NewVT == WidenVT)
3748       return LdOp;
3749
3750     assert(WidenWidth % NewVTWidth == 0);
3751     unsigned NumConcat = WidenWidth / NewVTWidth;
3752     SmallVector<SDValue, 16> ConcatOps(NumConcat);
3753     SDValue UndefVal = DAG.getUNDEF(NewVT);
3754     ConcatOps[0] = LdOp;
3755     for (unsigned i = 1; i != NumConcat; ++i)
3756       ConcatOps[i] = UndefVal;
3757     return DAG.getNode(ISD::CONCAT_VECTORS, dl, WidenVT, ConcatOps);
3758   }
3759
3760   // Load vector by using multiple loads from largest vector to scalar.
3761   SmallVector<SDValue, 16> LdOps;
3762   LdOps.push_back(LdOp);
3763
3764   LdWidth -= NewVTWidth;
3765   unsigned Offset = 0;
3766
3767   while (LdWidth > 0) {
3768     unsigned Increment = NewVTWidth / 8;
3769     Offset += Increment;
3770     BasePtr = DAG.getObjectPtrOffset(dl, BasePtr, Increment);
3771
3772     SDValue L;
3773     if (LdWidth < NewVTWidth) {
3774       // The current type we are using is too large. Find a better size.
3775       NewVT = FindMemType(DAG, TLI, LdWidth, WidenVT, LdAlign, WidthDiff);
3776       NewVTWidth = NewVT.getSizeInBits();
3777       L = DAG.getLoad(NewVT, dl, Chain, BasePtr,
3778                       LD->getPointerInfo().getWithOffset(Offset),
3779                       MinAlign(Align, Increment), MMOFlags, AAInfo);
3780       LdChain.push_back(L.getValue(1));
3781       if (L->getValueType(0).isVector() && NewVTWidth >= LdWidth) {
3782         // Later code assumes the vector loads produced will be mergeable, so we
3783         // must pad the final entry up to the previous width. Scalars are
3784         // combined separately.
3785         SmallVector<SDValue, 16> Loads;
3786         Loads.push_back(L);
3787         unsigned size = L->getValueSizeInBits(0);
3788         while (size < LdOp->getValueSizeInBits(0)) {
3789           Loads.push_back(DAG.getUNDEF(L->getValueType(0)));
3790           size += L->getValueSizeInBits(0);
3791         }
3792         L = DAG.getNode(ISD::CONCAT_VECTORS, dl, LdOp->getValueType(0), Loads);
3793       }
3794     } else {
3795       L = DAG.getLoad(NewVT, dl, Chain, BasePtr,
3796                       LD->getPointerInfo().getWithOffset(Offset),
3797                       MinAlign(Align, Increment), MMOFlags, AAInfo);
3798       LdChain.push_back(L.getValue(1));
3799     }
3800
3801     LdOps.push_back(L);
3802     LdOp = L;
3803
3804     LdWidth -= NewVTWidth;
3805   }
3806
3807   // Build the vector from the load operations.
3808   unsigned End = LdOps.size();
3809   if (!LdOps[0].getValueType().isVector())
3810     // All the loads are scalar loads.
3811     return BuildVectorFromScalar(DAG, WidenVT, LdOps, 0, End);
3812
3813   // If the load contains vectors, build the vector using concat vector.
3814   // All of the vectors used to load are power-of-2, and the scalar loads can be
3815   // combined to make a power-of-2 vector.
3816   SmallVector<SDValue, 16> ConcatOps(End);
3817   int i = End - 1;
3818   int Idx = End;
3819   EVT LdTy = LdOps[i].getValueType();
3820   // First, combine the scalar loads to a vector.
3821   if (!LdTy.isVector())  {
3822     for (--i; i >= 0; --i) {
3823       LdTy = LdOps[i].getValueType();
3824       if (LdTy.isVector())
3825         break;
3826     }
3827     ConcatOps[--Idx] = BuildVectorFromScalar(DAG, LdTy, LdOps, i + 1, End);
3828   }
3829   ConcatOps[--Idx] = LdOps[i];
3830   for (--i; i >= 0; --i) {
3831     EVT NewLdTy = LdOps[i].getValueType();
3832     if (NewLdTy != LdTy) {
3833       // Create a larger vector.
3834       ConcatOps[End-1] = DAG.getNode(ISD::CONCAT_VECTORS, dl, NewLdTy,
3835                                      makeArrayRef(&ConcatOps[Idx], End - Idx));
3836       Idx = End - 1;
3837       LdTy = NewLdTy;
3838     }
3839     ConcatOps[--Idx] = LdOps[i];
3840   }
3841
3842   if (WidenWidth == LdTy.getSizeInBits() * (End - Idx))
3843     return DAG.getNode(ISD::CONCAT_VECTORS, dl, WidenVT,
3844                        makeArrayRef(&ConcatOps[Idx], End - Idx));
3845
3846   // We need to fill the rest with undefs to build the vector.
3847   unsigned NumOps = WidenWidth / LdTy.getSizeInBits();
3848   SmallVector<SDValue, 16> WidenOps(NumOps);
3849   SDValue UndefVal = DAG.getUNDEF(LdTy);
3850   {
3851     unsigned i = 0;
3852     for (; i != End-Idx; ++i)
3853       WidenOps[i] = ConcatOps[Idx+i];
3854     for (; i != NumOps; ++i)
3855       WidenOps[i] = UndefVal;
3856   }
3857   return DAG.getNode(ISD::CONCAT_VECTORS, dl, WidenVT, WidenOps);
3858 }
3859
3860 SDValue
3861 DAGTypeLegalizer::GenWidenVectorExtLoads(SmallVectorImpl<SDValue> &LdChain,
3862                                          LoadSDNode *LD,
3863                                          ISD::LoadExtType ExtType) {
3864   // For extension loads, it may not be more efficient to chop up the vector
3865   // and then extend it. Instead, we unroll the load and build a new vector.
3866   EVT WidenVT = TLI.getTypeToTransformTo(*DAG.getContext(),LD->getValueType(0));
3867   EVT LdVT    = LD->getMemoryVT();
3868   SDLoc dl(LD);
3869   assert(LdVT.isVector() && WidenVT.isVector());
3870
3871   // Load information
3872   SDValue Chain = LD->getChain();
3873   SDValue BasePtr = LD->getBasePtr();
3874   unsigned Align = LD->getAlignment();
3875   MachineMemOperand::Flags MMOFlags = LD->getMemOperand()->getFlags();
3876   AAMDNodes AAInfo = LD->getAAInfo();
3877
3878   EVT EltVT = WidenVT.getVectorElementType();
3879   EVT LdEltVT = LdVT.getVectorElementType();
3880   unsigned NumElts = LdVT.getVectorNumElements();
3881
3882   // Load each element and widen.
3883   unsigned WidenNumElts = WidenVT.getVectorNumElements();
3884   SmallVector<SDValue, 16> Ops(WidenNumElts);
3885   unsigned Increment = LdEltVT.getSizeInBits() / 8;
3886   Ops[0] =
3887       DAG.getExtLoad(ExtType, dl, EltVT, Chain, BasePtr, LD->getPointerInfo(),
3888                      LdEltVT, Align, MMOFlags, AAInfo);
3889   LdChain.push_back(Ops[0].getValue(1));
3890   unsigned i = 0, Offset = Increment;
3891   for (i=1; i < NumElts; ++i, Offset += Increment) {
3892     SDValue NewBasePtr = DAG.getObjectPtrOffset(dl, BasePtr, Offset);
3893     Ops[i] = DAG.getExtLoad(ExtType, dl, EltVT, Chain, NewBasePtr,
3894                             LD->getPointerInfo().getWithOffset(Offset), LdEltVT,
3895                             Align, MMOFlags, AAInfo);
3896     LdChain.push_back(Ops[i].getValue(1));
3897   }
3898
3899   // Fill the rest with undefs.
3900   SDValue UndefVal = DAG.getUNDEF(EltVT);
3901   for (; i != WidenNumElts; ++i)
3902     Ops[i] = UndefVal;
3903
3904   return DAG.getBuildVector(WidenVT, dl, Ops);
3905 }
3906
3907 void DAGTypeLegalizer::GenWidenVectorStores(SmallVectorImpl<SDValue> &StChain,
3908                                             StoreSDNode *ST) {
3909   // The strategy assumes that we can efficiently store power-of-two widths.
3910   // The routine chops the vector into the largest vector stores with the same
3911   // element type or scalar stores.
3912   SDValue  Chain = ST->getChain();
3913   SDValue  BasePtr = ST->getBasePtr();
3914   unsigned Align = ST->getAlignment();
3915   MachineMemOperand::Flags MMOFlags = ST->getMemOperand()->getFlags();
3916   AAMDNodes AAInfo = ST->getAAInfo();
3917   SDValue  ValOp = GetWidenedVector(ST->getValue());
3918   SDLoc dl(ST);
3919
3920   EVT StVT = ST->getMemoryVT();
3921   unsigned StWidth = StVT.getSizeInBits();
3922   EVT ValVT = ValOp.getValueType();
3923   unsigned ValWidth = ValVT.getSizeInBits();
3924   EVT ValEltVT = ValVT.getVectorElementType();
3925   unsigned ValEltWidth = ValEltVT.getSizeInBits();
3926   assert(StVT.getVectorElementType() == ValEltVT);
3927
3928   int Idx = 0;          // current index to store
3929   unsigned Offset = 0;  // offset from base to store
3930   while (StWidth != 0) {
3931     // Find the largest vector type we can store with.
3932     EVT NewVT = FindMemType(DAG, TLI, StWidth, ValVT);
3933     unsigned NewVTWidth = NewVT.getSizeInBits();
3934     unsigned Increment = NewVTWidth / 8;
3935     if (NewVT.isVector()) {
3936       unsigned NumVTElts = NewVT.getVectorNumElements();
3937       do {
3938         SDValue EOp = DAG.getNode(
3939             ISD::EXTRACT_SUBVECTOR, dl, NewVT, ValOp,
3940             DAG.getConstant(Idx, dl, TLI.getVectorIdxTy(DAG.getDataLayout())));
3941         StChain.push_back(DAG.getStore(
3942             Chain, dl, EOp, BasePtr, ST->getPointerInfo().getWithOffset(Offset),
3943             MinAlign(Align, Offset), MMOFlags, AAInfo));
3944         StWidth -= NewVTWidth;
3945         Offset += Increment;
3946         Idx += NumVTElts;
3947
3948         BasePtr = DAG.getObjectPtrOffset(dl, BasePtr, Increment);
3949       } while (StWidth != 0 && StWidth >= NewVTWidth);
3950     } else {
3951       // Cast the vector to the scalar type we can store.
3952       unsigned NumElts = ValWidth / NewVTWidth;
3953       EVT NewVecVT = EVT::getVectorVT(*DAG.getContext(), NewVT, NumElts);
3954       SDValue VecOp = DAG.getNode(ISD::BITCAST, dl, NewVecVT, ValOp);
3955       // Readjust index position based on new vector type.
3956       Idx = Idx * ValEltWidth / NewVTWidth;
3957       do {
3958         SDValue EOp = DAG.getNode(
3959             ISD::EXTRACT_VECTOR_ELT, dl, NewVT, VecOp,
3960             DAG.getConstant(Idx++, dl,
3961                             TLI.getVectorIdxTy(DAG.getDataLayout())));
3962         StChain.push_back(DAG.getStore(
3963             Chain, dl, EOp, BasePtr, ST->getPointerInfo().getWithOffset(Offset),
3964             MinAlign(Align, Offset), MMOFlags, AAInfo));
3965         StWidth -= NewVTWidth;
3966         Offset += Increment;
3967         BasePtr = DAG.getObjectPtrOffset(dl, BasePtr, Increment);
3968       } while (StWidth != 0 && StWidth >= NewVTWidth);
3969       // Restore index back to be relative to the original widen element type.
3970       Idx = Idx * NewVTWidth / ValEltWidth;
3971     }
3972   }
3973 }
3974
3975 void
3976 DAGTypeLegalizer::GenWidenVectorTruncStores(SmallVectorImpl<SDValue> &StChain,
3977                                             StoreSDNode *ST) {
3978   // For extension loads, it may not be more efficient to truncate the vector
3979   // and then store it. Instead, we extract each element and then store it.
3980   SDValue Chain = ST->getChain();
3981   SDValue BasePtr = ST->getBasePtr();
3982   unsigned Align = ST->getAlignment();
3983   MachineMemOperand::Flags MMOFlags = ST->getMemOperand()->getFlags();
3984   AAMDNodes AAInfo = ST->getAAInfo();
3985   SDValue ValOp = GetWidenedVector(ST->getValue());
3986   SDLoc dl(ST);
3987
3988   EVT StVT = ST->getMemoryVT();
3989   EVT ValVT = ValOp.getValueType();
3990
3991   // It must be true that the wide vector type is bigger than where we need to
3992   // store.
3993   assert(StVT.isVector() && ValOp.getValueType().isVector());
3994   assert(StVT.bitsLT(ValOp.getValueType()));
3995
3996   // For truncating stores, we can not play the tricks of chopping legal vector
3997   // types and bitcast it to the right type. Instead, we unroll the store.
3998   EVT StEltVT  = StVT.getVectorElementType();
3999   EVT ValEltVT = ValVT.getVectorElementType();
4000   unsigned Increment = ValEltVT.getSizeInBits() / 8;
4001   unsigned NumElts = StVT.getVectorNumElements();
4002   SDValue EOp = DAG.getNode(
4003       ISD::EXTRACT_VECTOR_ELT, dl, ValEltVT, ValOp,
4004       DAG.getConstant(0, dl, TLI.getVectorIdxTy(DAG.getDataLayout())));
4005   StChain.push_back(DAG.getTruncStore(Chain, dl, EOp, BasePtr,
4006                                       ST->getPointerInfo(), StEltVT, Align,
4007                                       MMOFlags, AAInfo));
4008   unsigned Offset = Increment;
4009   for (unsigned i=1; i < NumElts; ++i, Offset += Increment) {
4010     SDValue NewBasePtr = DAG.getObjectPtrOffset(dl, BasePtr, Offset);
4011     SDValue EOp = DAG.getNode(
4012         ISD::EXTRACT_VECTOR_ELT, dl, ValEltVT, ValOp,
4013         DAG.getConstant(0, dl, TLI.getVectorIdxTy(DAG.getDataLayout())));
4014     StChain.push_back(DAG.getTruncStore(
4015         Chain, dl, EOp, NewBasePtr, ST->getPointerInfo().getWithOffset(Offset),
4016         StEltVT, MinAlign(Align, Offset), MMOFlags, AAInfo));
4017   }
4018 }
4019
4020 /// Modifies a vector input (widen or narrows) to a vector of NVT.  The
4021 /// input vector must have the same element type as NVT.
4022 /// FillWithZeroes specifies that the vector should be widened with zeroes.
4023 SDValue DAGTypeLegalizer::ModifyToType(SDValue InOp, EVT NVT,
4024                                        bool FillWithZeroes) {
4025   // Note that InOp might have been widened so it might already have
4026   // the right width or it might need be narrowed.
4027   EVT InVT = InOp.getValueType();
4028   assert(InVT.getVectorElementType() == NVT.getVectorElementType() &&
4029          "input and widen element type must match");
4030   SDLoc dl(InOp);
4031
4032   // Check if InOp already has the right width.
4033   if (InVT == NVT)
4034     return InOp;
4035
4036   unsigned InNumElts = InVT.getVectorNumElements();
4037   unsigned WidenNumElts = NVT.getVectorNumElements();
4038   if (WidenNumElts > InNumElts && WidenNumElts % InNumElts == 0) {
4039     unsigned NumConcat = WidenNumElts / InNumElts;
4040     SmallVector<SDValue, 16> Ops(NumConcat);
4041     SDValue FillVal = FillWithZeroes ? DAG.getConstant(0, dl, InVT) :
4042       DAG.getUNDEF(InVT);
4043     Ops[0] = InOp;
4044     for (unsigned i = 1; i != NumConcat; ++i)
4045       Ops[i] = FillVal;
4046
4047     return DAG.getNode(ISD::CONCAT_VECTORS, dl, NVT, Ops);
4048   }
4049
4050   if (WidenNumElts < InNumElts && InNumElts % WidenNumElts)
4051     return DAG.getNode(
4052         ISD::EXTRACT_SUBVECTOR, dl, NVT, InOp,
4053         DAG.getConstant(0, dl, TLI.getVectorIdxTy(DAG.getDataLayout())));
4054
4055   // Fall back to extract and build.
4056   SmallVector<SDValue, 16> Ops(WidenNumElts);
4057   EVT EltVT = NVT.getVectorElementType();
4058   unsigned MinNumElts = std::min(WidenNumElts, InNumElts);
4059   unsigned Idx;
4060   for (Idx = 0; Idx < MinNumElts; ++Idx)
4061     Ops[Idx] = DAG.getNode(
4062         ISD::EXTRACT_VECTOR_ELT, dl, EltVT, InOp,
4063         DAG.getConstant(Idx, dl, TLI.getVectorIdxTy(DAG.getDataLayout())));
4064
4065   SDValue FillVal = FillWithZeroes ? DAG.getConstant(0, dl, EltVT) :
4066     DAG.getUNDEF(EltVT);
4067   for ( ; Idx < WidenNumElts; ++Idx)
4068     Ops[Idx] = FillVal;
4069   return DAG.getBuildVector(NVT, dl, Ops);
4070 }