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