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