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