OSDN Git Service

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