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