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