Add operators for vabdl and vabal so they can be implemented without builtins.
[oota-llvm.git] / utils / TableGen / NeonEmitter.cpp
1 //===- NeonEmitter.cpp - Generate arm_neon.h for use with clang -*- C++ -*-===//
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 tablegen backend is responsible for emitting arm_neon.h, which includes
11 // a declaration and definition of each function specified by the ARM NEON
12 // compiler interface.  See ARM document DUI0348B.
13 //
14 // Each NEON instruction is implemented in terms of 1 or more functions which
15 // are suffixed with the element type of the input vectors.  Functions may be
16 // implemented in terms of generic vector operations such as +, *, -, etc. or
17 // by calling a __builtin_-prefixed function which will be handled by clang's
18 // CodeGen library.
19 //
20 // Additional validation code can be generated by this file when runHeader() is
21 // called, rather than the normal run() entry point.
22 //
23 //===----------------------------------------------------------------------===//
24
25 #include "NeonEmitter.h"
26 #include "llvm/ADT/SmallString.h"
27 #include "llvm/ADT/SmallVector.h"
28 #include "llvm/ADT/StringExtras.h"
29 #include <string>
30
31 using namespace llvm;
32
33 /// ParseTypes - break down a string such as "fQf" into a vector of StringRefs,
34 /// which each StringRef representing a single type declared in the string.
35 /// for "fQf" we would end up with 2 StringRefs, "f", and "Qf", representing
36 /// 2xfloat and 4xfloat respectively.
37 static void ParseTypes(Record *r, std::string &s,
38                        SmallVectorImpl<StringRef> &TV) {
39   const char *data = s.data();
40   int len = 0;
41
42   for (unsigned i = 0, e = s.size(); i != e; ++i, ++len) {
43     if (data[len] == 'P' || data[len] == 'Q' || data[len] == 'U')
44       continue;
45
46     switch (data[len]) {
47       case 'c':
48       case 's':
49       case 'i':
50       case 'l':
51       case 'h':
52       case 'f':
53         break;
54       default:
55         throw TGError(r->getLoc(),
56                       "Unexpected letter: " + std::string(data + len, 1));
57         break;
58     }
59     TV.push_back(StringRef(data, len + 1));
60     data += len + 1;
61     len = -1;
62   }
63 }
64
65 /// Widen - Convert a type code into the next wider type.  char -> short,
66 /// short -> int, etc.
67 static char Widen(const char t) {
68   switch (t) {
69     case 'c':
70       return 's';
71     case 's':
72       return 'i';
73     case 'i':
74       return 'l';
75     default: throw "unhandled type in widen!";
76   }
77   return '\0';
78 }
79
80 /// Narrow - Convert a type code into the next smaller type.  short -> char,
81 /// float -> half float, etc.
82 static char Narrow(const char t) {
83   switch (t) {
84     case 's':
85       return 'c';
86     case 'i':
87       return 's';
88     case 'l':
89       return 'i';
90     case 'f':
91       return 'h';
92     default: throw "unhandled type in narrow!";
93   }
94   return '\0';
95 }
96
97 /// For a particular StringRef, return the base type code, and whether it has
98 /// the quad-vector, polynomial, or unsigned modifiers set.
99 static char ClassifyType(StringRef ty, bool &quad, bool &poly, bool &usgn) {
100   unsigned off = 0;
101
102   // remember quad.
103   if (ty[off] == 'Q') {
104     quad = true;
105     ++off;
106   }
107
108   // remember poly.
109   if (ty[off] == 'P') {
110     poly = true;
111     ++off;
112   }
113
114   // remember unsigned.
115   if (ty[off] == 'U') {
116     usgn = true;
117     ++off;
118   }
119
120   // base type to get the type string for.
121   return ty[off];
122 }
123
124 /// ModType - Transform a type code and its modifiers based on a mod code. The
125 /// mod code definitions may be found at the top of arm_neon.td.
126 static char ModType(const char mod, char type, bool &quad, bool &poly,
127                     bool &usgn, bool &scal, bool &cnst, bool &pntr) {
128   switch (mod) {
129     case 't':
130       if (poly) {
131         poly = false;
132         usgn = true;
133       }
134       break;
135     case 'u':
136       usgn = true;
137       poly = false;
138       if (type == 'f')
139         type = 'i';
140       break;
141     case 'x':
142       usgn = false;
143       poly = false;
144       if (type == 'f')
145         type = 'i';
146       break;
147     case 'f':
148       if (type == 'h')
149         quad = true;
150       type = 'f';
151       usgn = false;
152       break;
153     case 'g':
154       quad = false;
155       break;
156     case 'w':
157       type = Widen(type);
158       quad = true;
159       break;
160     case 'n':
161       type = Widen(type);
162       break;
163     case 'i':
164       type = 'i';
165       scal = true;
166       break;
167     case 'l':
168       type = 'l';
169       scal = true;
170       usgn = true;
171       break;
172     case 's':
173     case 'a':
174       scal = true;
175       break;
176     case 'k':
177       quad = true;
178       break;
179     case 'c':
180       cnst = true;
181     case 'p':
182       pntr = true;
183       scal = true;
184       break;
185     case 'h':
186       type = Narrow(type);
187       if (type == 'h')
188         quad = false;
189       break;
190     case 'e':
191       type = Narrow(type);
192       usgn = true;
193       break;
194     default:
195       break;
196   }
197   return type;
198 }
199
200 /// TypeString - for a modifier and type, generate the name of the typedef for
201 /// that type.  QUc -> uint8x8_t.
202 static std::string TypeString(const char mod, StringRef typestr) {
203   bool quad = false;
204   bool poly = false;
205   bool usgn = false;
206   bool scal = false;
207   bool cnst = false;
208   bool pntr = false;
209
210   if (mod == 'v')
211     return "void";
212   if (mod == 'i')
213     return "int";
214
215   // base type to get the type string for.
216   char type = ClassifyType(typestr, quad, poly, usgn);
217
218   // Based on the modifying character, change the type and width if necessary.
219   type = ModType(mod, type, quad, poly, usgn, scal, cnst, pntr);
220
221   SmallString<128> s;
222
223   if (usgn)
224     s.push_back('u');
225
226   switch (type) {
227     case 'c':
228       s += poly ? "poly8" : "int8";
229       if (scal)
230         break;
231       s += quad ? "x16" : "x8";
232       break;
233     case 's':
234       s += poly ? "poly16" : "int16";
235       if (scal)
236         break;
237       s += quad ? "x8" : "x4";
238       break;
239     case 'i':
240       s += "int32";
241       if (scal)
242         break;
243       s += quad ? "x4" : "x2";
244       break;
245     case 'l':
246       s += "int64";
247       if (scal)
248         break;
249       s += quad ? "x2" : "x1";
250       break;
251     case 'h':
252       s += "float16";
253       if (scal)
254         break;
255       s += quad ? "x8" : "x4";
256       break;
257     case 'f':
258       s += "float32";
259       if (scal)
260         break;
261       s += quad ? "x4" : "x2";
262       break;
263     default:
264       throw "unhandled type!";
265       break;
266   }
267
268   if (mod == '2')
269     s += "x2";
270   if (mod == '3')
271     s += "x3";
272   if (mod == '4')
273     s += "x4";
274
275   // Append _t, finishing the type string typedef type.
276   s += "_t";
277
278   if (cnst)
279     s += " const";
280
281   if (pntr)
282     s += " *";
283
284   return s.str();
285 }
286
287 /// BuiltinTypeString - for a modifier and type, generate the clang
288 /// BuiltinsARM.def prototype code for the function.  See the top of clang's
289 /// Builtins.def for a description of the type strings.
290 static std::string BuiltinTypeString(const char mod, StringRef typestr,
291                                      ClassKind ck, bool ret) {
292   bool quad = false;
293   bool poly = false;
294   bool usgn = false;
295   bool scal = false;
296   bool cnst = false;
297   bool pntr = false;
298
299   if (mod == 'v')
300     return "v"; // void
301   if (mod == 'i')
302     return "i"; // int
303
304   // base type to get the type string for.
305   char type = ClassifyType(typestr, quad, poly, usgn);
306
307   // Based on the modifying character, change the type and width if necessary.
308   type = ModType(mod, type, quad, poly, usgn, scal, cnst, pntr);
309
310   // All pointers are void* pointers.  Change type to 'v' now.
311   if (pntr) {
312     usgn = false;
313     poly = false;
314     type = 'v';
315   }
316   // Treat half-float ('h') types as unsigned short ('s') types.
317   if (type == 'h') {
318     type = 's';
319     usgn = true;
320   }
321   usgn = usgn | poly | ((ck == ClassI || ck == ClassW) && scal && type != 'f');
322
323   if (scal) {
324     SmallString<128> s;
325
326     if (usgn)
327       s.push_back('U');
328     else if (type == 'c')
329       s.push_back('S'); // make chars explicitly signed
330
331     if (type == 'l') // 64-bit long
332       s += "LLi";
333     else
334       s.push_back(type);
335
336     if (cnst)
337       s.push_back('C');
338     if (pntr)
339       s.push_back('*');
340     return s.str();
341   }
342
343   // Since the return value must be one type, return a vector type of the
344   // appropriate width which we will bitcast.  An exception is made for
345   // returning structs of 2, 3, or 4 vectors which are returned in a sret-like
346   // fashion, storing them to a pointer arg.
347   if (ret) {
348     if (mod >= '2' && mod <= '4')
349       return "vv*"; // void result with void* first argument
350     if (mod == 'f' || (ck != ClassB && type == 'f'))
351       return quad ? "V4f" : "V2f";
352     if (ck != ClassB && type == 's')
353       return quad ? "V8s" : "V4s";
354     if (ck != ClassB && type == 'i')
355       return quad ? "V4i" : "V2i";
356     if (ck != ClassB && type == 'l')
357       return quad ? "V2LLi" : "V1LLi";
358
359     return quad ? "V16Sc" : "V8Sc";
360   }
361
362   // Non-return array types are passed as individual vectors.
363   if (mod == '2')
364     return quad ? "V16ScV16Sc" : "V8ScV8Sc";
365   if (mod == '3')
366     return quad ? "V16ScV16ScV16Sc" : "V8ScV8ScV8Sc";
367   if (mod == '4')
368     return quad ? "V16ScV16ScV16ScV16Sc" : "V8ScV8ScV8ScV8Sc";
369
370   if (mod == 'f' || (ck != ClassB && type == 'f'))
371     return quad ? "V4f" : "V2f";
372   if (ck != ClassB && type == 's')
373     return quad ? "V8s" : "V4s";
374   if (ck != ClassB && type == 'i')
375     return quad ? "V4i" : "V2i";
376   if (ck != ClassB && type == 'l')
377     return quad ? "V2LLi" : "V1LLi";
378
379   return quad ? "V16Sc" : "V8Sc";
380 }
381
382 /// MangleName - Append a type or width suffix to a base neon function name,
383 /// and insert a 'q' in the appropriate location if the operation works on
384 /// 128b rather than 64b.   E.g. turn "vst2_lane" into "vst2q_lane_f32", etc.
385 static std::string MangleName(const std::string &name, StringRef typestr,
386                               ClassKind ck) {
387   if (name == "vcvt_f32_f16")
388     return name;
389
390   bool quad = false;
391   bool poly = false;
392   bool usgn = false;
393   char type = ClassifyType(typestr, quad, poly, usgn);
394
395   std::string s = name;
396
397   switch (type) {
398   case 'c':
399     switch (ck) {
400     case ClassS: s += poly ? "_p8" : usgn ? "_u8" : "_s8"; break;
401     case ClassI: s += "_i8"; break;
402     case ClassW: s += "_8"; break;
403     default: break;
404     }
405     break;
406   case 's':
407     switch (ck) {
408     case ClassS: s += poly ? "_p16" : usgn ? "_u16" : "_s16"; break;
409     case ClassI: s += "_i16"; break;
410     case ClassW: s += "_16"; break;
411     default: break;
412     }
413     break;
414   case 'i':
415     switch (ck) {
416     case ClassS: s += usgn ? "_u32" : "_s32"; break;
417     case ClassI: s += "_i32"; break;
418     case ClassW: s += "_32"; break;
419     default: break;
420     }
421     break;
422   case 'l':
423     switch (ck) {
424     case ClassS: s += usgn ? "_u64" : "_s64"; break;
425     case ClassI: s += "_i64"; break;
426     case ClassW: s += "_64"; break;
427     default: break;
428     }
429     break;
430   case 'h':
431     switch (ck) {
432     case ClassS:
433     case ClassI: s += "_f16"; break;
434     case ClassW: s += "_16"; break;
435     default: break;
436     }
437     break;
438   case 'f':
439     switch (ck) {
440     case ClassS:
441     case ClassI: s += "_f32"; break;
442     case ClassW: s += "_32"; break;
443     default: break;
444     }
445     break;
446   default:
447     throw "unhandled type!";
448     break;
449   }
450   if (ck == ClassB)
451     s += "_v";
452
453   // Insert a 'q' before the first '_' character so that it ends up before
454   // _lane or _n on vector-scalar operations.
455   if (quad) {
456     size_t pos = s.find('_');
457     s = s.insert(pos, "q");
458   }
459   return s;
460 }
461
462 // Generate the string "(argtype a, argtype b, ...)"
463 static std::string GenArgs(const std::string &proto, StringRef typestr) {
464   bool define = proto.find('i') != std::string::npos;
465   char arg = 'a';
466
467   std::string s;
468   s += "(";
469
470   for (unsigned i = 1, e = proto.size(); i != e; ++i, ++arg) {
471     if (define) {
472       // Immediate macro arguments are used directly instead of being assigned
473       // to local temporaries; prepend an underscore prefix to make their
474       // names consistent with the local temporaries.
475       if (proto[i] == 'i')
476         s += "__";
477     } else {
478       s += TypeString(proto[i], typestr) + " __";
479     }
480     s.push_back(arg);
481     if ((i + 1) < e)
482       s += ", ";
483   }
484
485   s += ")";
486   return s;
487 }
488
489 // Macro arguments are not type-checked like inline function arguments, so
490 // assign them to local temporaries to get the right type checking.
491 static std::string GenMacroLocals(const std::string &proto, StringRef typestr) {
492   char arg = 'a';
493   std::string s;
494
495   for (unsigned i = 1, e = proto.size(); i != e; ++i, ++arg) {
496     // Do not create a temporary for an immediate argument.
497     // That would defeat the whole point of using a macro!
498     if (proto[i] == 'i') continue;
499
500     s += TypeString(proto[i], typestr) + " __";
501     s.push_back(arg);
502     s += " = (";
503     s.push_back(arg);
504     s += "); ";
505   }
506
507   s += "\\\n  ";
508   return s;
509 }
510
511 // Use the vmovl builtin to sign-extend or zero-extend a vector.
512 static std::string Extend(StringRef typestr, const std::string &a) {
513   std::string s;
514   s = MangleName("vmovl", typestr, ClassS);
515   s += "(" + a + ")";
516   return s;
517 }
518
519 static std::string Duplicate(unsigned nElts, StringRef typestr,
520                              const std::string &a) {
521   std::string s;
522
523   s = "(" + TypeString('d', typestr) + "){ ";
524   for (unsigned i = 0; i != nElts; ++i) {
525     s += a;
526     if ((i + 1) < nElts)
527       s += ", ";
528   }
529   s += " }";
530
531   return s;
532 }
533
534 static std::string SplatLane(unsigned nElts, const std::string &vec,
535                              const std::string &lane) {
536   std::string s = "__builtin_shufflevector(" + vec + ", " + vec;
537   for (unsigned i = 0; i < nElts; ++i)
538     s += ", " + lane;
539   s += ")";
540   return s;
541 }
542
543 static unsigned GetNumElements(StringRef typestr, bool &quad) {
544   quad = false;
545   bool dummy = false;
546   char type = ClassifyType(typestr, quad, dummy, dummy);
547   unsigned nElts = 0;
548   switch (type) {
549   case 'c': nElts = 8; break;
550   case 's': nElts = 4; break;
551   case 'i': nElts = 2; break;
552   case 'l': nElts = 1; break;
553   case 'h': nElts = 4; break;
554   case 'f': nElts = 2; break;
555   default:
556     throw "unhandled type!";
557     break;
558   }
559   if (quad) nElts <<= 1;
560   return nElts;
561 }
562
563 // Generate the definition for this intrinsic, e.g. "a + b" for OpAdd.
564 static std::string GenOpString(OpKind op, const std::string &proto,
565                                StringRef typestr) {
566   bool quad;
567   unsigned nElts = GetNumElements(typestr, quad);
568
569   // If this builtin takes an immediate argument, we need to #define it rather
570   // than use a standard declaration, so that SemaChecking can range check
571   // the immediate passed by the user.
572   bool define = proto.find('i') != std::string::npos;
573
574   std::string ts = TypeString(proto[0], typestr);
575   std::string s;
576   if (op == OpHi || op == OpLo) {
577     s = "union { " + ts + " r; double d; } u; u.d = ";
578   } else if (!define) {
579     s = "return ";
580   }
581
582   switch(op) {
583   case OpAdd:
584     s += "__a + __b;";
585     break;
586   case OpAddl:
587     s += Extend(typestr, "__a") + " + " + Extend(typestr, "__b") + ";";
588     break;
589   case OpAddw:
590     s += "__a + " + Extend(typestr, "__b") + ";";
591     break;
592   case OpSub:
593     s += "__a - __b;";
594     break;
595   case OpSubl:
596     s += Extend(typestr, "__a") + " - " + Extend(typestr, "__b") + ";";
597     break;
598   case OpSubw:
599     s += "__a - " + Extend(typestr, "__b") + ";";
600     break;
601   case OpMulN:
602     s += "__a * " + Duplicate(nElts, typestr, "__b") + ";";
603     break;
604   case OpMulLane:
605     s += "__a * " + SplatLane(nElts, "__b", "__c") + ";";
606     break;
607   case OpMul:
608     s += "__a * __b;";
609     break;
610   case OpMullN:
611     s += Extend(typestr, "__a") + " * " +
612       Extend(typestr, Duplicate(nElts << (int)quad, typestr, "__b")) + ";";
613     break;
614   case OpMullLane:
615     s += Extend(typestr, "__a") + " * " +
616       Extend(typestr, SplatLane(nElts, "__b", "__c")) + ";";
617     break;
618   case OpMull:
619     s += Extend(typestr, "__a") + " * " + Extend(typestr, "__b") + ";";
620     break;
621   case OpMlaN:
622     s += "__a + (__b * " + Duplicate(nElts, typestr, "__c") + ");";
623     break;
624   case OpMlaLane:
625     s += "__a + (__b * " + SplatLane(nElts, "__c", "__d") + ");";
626     break;
627   case OpMla:
628     s += "__a + (__b * __c);";
629     break;
630   case OpMlalN:
631     s += "__a + (" + Extend(typestr, "__b") + " * " +
632       Extend(typestr, Duplicate(nElts, typestr, "__c")) + ");";
633     break;
634   case OpMlalLane:
635     s += "__a + (" + Extend(typestr, "__b") + " * " +
636       Extend(typestr, SplatLane(nElts, "__c", "__d")) + ");";
637     break;
638   case OpMlal:
639     s += "__a + (" + Extend(typestr, "__b") + " * " +
640       Extend(typestr, "__c") + ");";
641     break;
642   case OpMlsN:
643     s += "__a - (__b * " + Duplicate(nElts, typestr, "__c") + ");";
644     break;
645   case OpMlsLane:
646     s += "__a - (__b * " + SplatLane(nElts, "__c", "__d") + ");";
647     break;
648   case OpMls:
649     s += "__a - (__b * __c);";
650     break;
651   case OpMlslN:
652     s += "__a - (" + Extend(typestr, "__b") + " * " +
653       Extend(typestr, Duplicate(nElts, typestr, "__c")) + ");";
654     break;
655   case OpMlslLane:
656     s += "__a - (" + Extend(typestr, "__b") + " * " +
657       Extend(typestr, SplatLane(nElts, "__c", "__d")) + ");";
658     break;
659   case OpMlsl:
660     s += "__a - (" + Extend(typestr, "__b") + " * " +
661       Extend(typestr, "__c") + ");";
662     break;
663   case OpEq:
664     s += "(" + ts + ")(__a == __b);";
665     break;
666   case OpGe:
667     s += "(" + ts + ")(__a >= __b);";
668     break;
669   case OpLe:
670     s += "(" + ts + ")(__a <= __b);";
671     break;
672   case OpGt:
673     s += "(" + ts + ")(__a > __b);";
674     break;
675   case OpLt:
676     s += "(" + ts + ")(__a < __b);";
677     break;
678   case OpNeg:
679     s += " -__a;";
680     break;
681   case OpNot:
682     s += " ~__a;";
683     break;
684   case OpAnd:
685     s += "__a & __b;";
686     break;
687   case OpOr:
688     s += "__a | __b;";
689     break;
690   case OpXor:
691     s += "__a ^ __b;";
692     break;
693   case OpAndNot:
694     s += "__a & ~__b;";
695     break;
696   case OpOrNot:
697     s += "__a | ~__b;";
698     break;
699   case OpCast:
700     s += "(" + ts + ")__a;";
701     break;
702   case OpConcat:
703     s += "(" + ts + ")__builtin_shufflevector((int64x1_t)__a";
704     s += ", (int64x1_t)__b, 0, 1);";
705     break;
706   case OpHi:
707     s += "(((float64x2_t)__a)[1]);";
708     break;
709   case OpLo:
710     s += "(((float64x2_t)__a)[0]);";
711     break;
712   case OpDup:
713     s += Duplicate(nElts, typestr, "__a") + ";";
714     break;
715   case OpDupLane:
716     s += SplatLane(nElts, "__a", "__b") + ";";
717     break;
718   case OpSelect:
719     // ((0 & 1) | (~0 & 2))
720     s += "(" + ts + ")";
721     ts = TypeString(proto[1], typestr);
722     s += "((__a & (" + ts + ")__b) | ";
723     s += "(~__a & (" + ts + ")__c));";
724     break;
725   case OpRev16:
726     s += "__builtin_shufflevector(__a, __a";
727     for (unsigned i = 2; i <= nElts; i += 2)
728       for (unsigned j = 0; j != 2; ++j)
729         s += ", " + utostr(i - j - 1);
730     s += ");";
731     break;
732   case OpRev32: {
733     unsigned WordElts = nElts >> (1 + (int)quad);
734     s += "__builtin_shufflevector(__a, __a";
735     for (unsigned i = WordElts; i <= nElts; i += WordElts)
736       for (unsigned j = 0; j != WordElts; ++j)
737         s += ", " + utostr(i - j - 1);
738     s += ");";
739     break;
740   }
741   case OpRev64: {
742     unsigned DblWordElts = nElts >> (int)quad;
743     s += "__builtin_shufflevector(__a, __a";
744     for (unsigned i = DblWordElts; i <= nElts; i += DblWordElts)
745       for (unsigned j = 0; j != DblWordElts; ++j)
746         s += ", " + utostr(i - j - 1);
747     s += ");";
748     break;
749   }
750   case OpAbdl: {
751     std::string abd = MangleName("vabd", typestr, ClassS) + "(__a, __b)";
752     if (typestr[0] != 'U') {
753       // vabd results are always unsigned and must be zero-extended.
754       std::string utype = "U" + typestr.str();
755       s += "(" + TypeString(proto[0], typestr) + ")";
756       abd = "(" + TypeString('d', utype) + ")" + abd;
757       s += Extend(utype, abd) + ";";
758     } else {
759       s += Extend(typestr, abd) + ";";
760     }
761     break;
762   }
763   case OpAba:
764     s += "__a + " + MangleName("vabd", typestr, ClassS) + "(__b, __c);";
765     break;
766   case OpAbal: {
767     s += "__a + ";
768     std::string abd = MangleName("vabd", typestr, ClassS) + "(__b, __c)";
769     if (typestr[0] != 'U') {
770       // vabd results are always unsigned and must be zero-extended.
771       std::string utype = "U" + typestr.str();
772       s += "(" + TypeString(proto[0], typestr) + ")";
773       abd = "(" + TypeString('d', utype) + ")" + abd;
774       s += Extend(utype, abd) + ";";
775     } else {
776       s += Extend(typestr, abd) + ";";
777     }
778     break;
779   }
780   default:
781     throw "unknown OpKind!";
782     break;
783   }
784   if (op == OpHi || op == OpLo) {
785     if (!define)
786       s += " return";
787     s += " u.r;";
788   }
789   return s;
790 }
791
792 static unsigned GetNeonEnum(const std::string &proto, StringRef typestr) {
793   unsigned mod = proto[0];
794   unsigned ret = 0;
795
796   if (mod == 'v' || mod == 'f')
797     mod = proto[1];
798
799   bool quad = false;
800   bool poly = false;
801   bool usgn = false;
802   bool scal = false;
803   bool cnst = false;
804   bool pntr = false;
805
806   // Base type to get the type string for.
807   char type = ClassifyType(typestr, quad, poly, usgn);
808
809   // Based on the modifying character, change the type and width if necessary.
810   type = ModType(mod, type, quad, poly, usgn, scal, cnst, pntr);
811
812   if (usgn)
813     ret |= 0x08;
814   if (quad && proto[1] != 'g')
815     ret |= 0x10;
816
817   switch (type) {
818     case 'c':
819       ret |= poly ? 5 : 0;
820       break;
821     case 's':
822       ret |= poly ? 6 : 1;
823       break;
824     case 'i':
825       ret |= 2;
826       break;
827     case 'l':
828       ret |= 3;
829       break;
830     case 'h':
831       ret |= 7;
832       break;
833     case 'f':
834       ret |= 4;
835       break;
836     default:
837       throw "unhandled type!";
838       break;
839   }
840   return ret;
841 }
842
843 // Generate the definition for this intrinsic, e.g. __builtin_neon_cls(a)
844 static std::string GenBuiltin(const std::string &name, const std::string &proto,
845                               StringRef typestr, ClassKind ck) {
846   std::string s;
847
848   // If this builtin returns a struct 2, 3, or 4 vectors, pass it as an implicit
849   // sret-like argument.
850   bool sret = (proto[0] >= '2' && proto[0] <= '4');
851
852   // If this builtin takes an immediate argument, we need to #define it rather
853   // than use a standard declaration, so that SemaChecking can range check
854   // the immediate passed by the user.
855   bool define = proto.find('i') != std::string::npos;
856
857   // Check if the prototype has a scalar operand with the type of the vector
858   // elements.  If not, bitcasting the args will take care of arg checking.
859   // The actual signedness etc. will be taken care of with special enums.
860   if (proto.find('s') == std::string::npos)
861     ck = ClassB;
862
863   if (proto[0] != 'v') {
864     std::string ts = TypeString(proto[0], typestr);
865
866     if (define) {
867       if (sret)
868         s += ts + " r; ";
869       else
870         s += "(" + ts + ")";
871     } else if (sret) {
872       s += ts + " r; ";
873     } else {
874       s += "return (" + ts + ")";
875     }
876   }
877
878   bool splat = proto.find('a') != std::string::npos;
879
880   s += "__builtin_neon_";
881   if (splat) {
882     // Call the non-splat builtin: chop off the "_n" suffix from the name.
883     std::string vname(name, 0, name.size()-2);
884     s += MangleName(vname, typestr, ck);
885   } else {
886     s += MangleName(name, typestr, ck);
887   }
888   s += "(";
889
890   // Pass the address of the return variable as the first argument to sret-like
891   // builtins.
892   if (sret)
893     s += "&r, ";
894
895   char arg = 'a';
896   for (unsigned i = 1, e = proto.size(); i != e; ++i, ++arg) {
897     std::string args = std::string(&arg, 1);
898
899     // Use the local temporaries instead of the macro arguments.
900     args = "__" + args;
901
902     bool argQuad = false;
903     bool argPoly = false;
904     bool argUsgn = false;
905     bool argScalar = false;
906     bool dummy = false;
907     char argType = ClassifyType(typestr, argQuad, argPoly, argUsgn);
908     argType = ModType(proto[i], argType, argQuad, argPoly, argUsgn, argScalar,
909                       dummy, dummy);
910
911     // Handle multiple-vector values specially, emitting each subvector as an
912     // argument to the __builtin.
913     if (proto[i] >= '2' && proto[i] <= '4') {
914       // Check if an explicit cast is needed.
915       if (argType != 'c' || argPoly || argUsgn)
916         args = (argQuad ? "(int8x16_t)" : "(int8x8_t)") + args;
917
918       for (unsigned vi = 0, ve = proto[i] - '0'; vi != ve; ++vi) {
919         s += args + ".val[" + utostr(vi) + "]";
920         if ((vi + 1) < ve)
921           s += ", ";
922       }
923       if ((i + 1) < e)
924         s += ", ";
925
926       continue;
927     }
928
929     if (splat && (i + 1) == e)
930       args = Duplicate(GetNumElements(typestr, argQuad), typestr, args);
931
932     // Check if an explicit cast is needed.
933     if ((splat || !argScalar) &&
934         ((ck == ClassB && argType != 'c') || argPoly || argUsgn)) {
935       std::string argTypeStr = "c";
936       if (ck != ClassB)
937         argTypeStr = argType;
938       if (argQuad)
939         argTypeStr = "Q" + argTypeStr;
940       args = "(" + TypeString('d', argTypeStr) + ")" + args;
941     }
942
943     s += args;
944     if ((i + 1) < e)
945       s += ", ";
946   }
947
948   // Extra constant integer to hold type class enum for this function, e.g. s8
949   if (ck == ClassB)
950     s += ", " + utostr(GetNeonEnum(proto, typestr));
951
952   s += ");";
953
954   if (proto[0] != 'v' && sret) {
955     if (define)
956       s += " r;";
957     else
958       s += " return r;";
959   }
960   return s;
961 }
962
963 static std::string GenBuiltinDef(const std::string &name,
964                                  const std::string &proto,
965                                  StringRef typestr, ClassKind ck) {
966   std::string s("BUILTIN(__builtin_neon_");
967
968   // If all types are the same size, bitcasting the args will take care
969   // of arg checking.  The actual signedness etc. will be taken care of with
970   // special enums.
971   if (proto.find('s') == std::string::npos)
972     ck = ClassB;
973
974   s += MangleName(name, typestr, ck);
975   s += ", \"";
976
977   for (unsigned i = 0, e = proto.size(); i != e; ++i)
978     s += BuiltinTypeString(proto[i], typestr, ck, i == 0);
979
980   // Extra constant integer to hold type class enum for this function, e.g. s8
981   if (ck == ClassB)
982     s += "i";
983
984   s += "\", \"n\")";
985   return s;
986 }
987
988 static std::string GenIntrinsic(const std::string &name,
989                                 const std::string &proto,
990                                 StringRef outTypeStr, StringRef inTypeStr,
991                                 OpKind kind, ClassKind classKind) {
992   assert(!proto.empty() && "");
993   bool define = proto.find('i') != std::string::npos;
994   std::string s;
995
996   // static always inline + return type
997   if (define)
998     s += "#define ";
999   else
1000     s += "__ai " + TypeString(proto[0], outTypeStr) + " ";
1001
1002   // Function name with type suffix
1003   std::string mangledName = MangleName(name, outTypeStr, ClassS);
1004   if (outTypeStr != inTypeStr) {
1005     // If the input type is different (e.g., for vreinterpret), append a suffix
1006     // for the input type.  String off a "Q" (quad) prefix so that MangleName
1007     // does not insert another "q" in the name.
1008     unsigned typeStrOff = (inTypeStr[0] == 'Q' ? 1 : 0);
1009     StringRef inTypeNoQuad = inTypeStr.substr(typeStrOff);
1010     mangledName = MangleName(mangledName, inTypeNoQuad, ClassS);
1011   }
1012   s += mangledName;
1013
1014   // Function arguments
1015   s += GenArgs(proto, inTypeStr);
1016
1017   // Definition.
1018   if (define) {
1019     s += " __extension__ ({ \\\n  ";
1020     s += GenMacroLocals(proto, inTypeStr);
1021   } else {
1022     s += " { \\\n  ";
1023   }
1024
1025   if (kind != OpNone)
1026     s += GenOpString(kind, proto, outTypeStr);
1027   else
1028     s += GenBuiltin(name, proto, outTypeStr, classKind);
1029   if (define)
1030     s += " })";
1031   else
1032     s += " }";
1033   s += "\n";
1034   return s;
1035 }
1036
1037 /// run - Read the records in arm_neon.td and output arm_neon.h.  arm_neon.h
1038 /// is comprised of type definitions and function declarations.
1039 void NeonEmitter::run(raw_ostream &OS) {
1040   EmitSourceFileHeader("ARM NEON Header", OS);
1041
1042   // FIXME: emit license into file?
1043
1044   OS << "#ifndef __ARM_NEON_H\n";
1045   OS << "#define __ARM_NEON_H\n\n";
1046
1047   OS << "#ifndef __ARM_NEON__\n";
1048   OS << "#error \"NEON support not enabled\"\n";
1049   OS << "#endif\n\n";
1050
1051   OS << "#include <stdint.h>\n\n";
1052
1053   // Emit NEON-specific scalar typedefs.
1054   OS << "typedef float float32_t;\n";
1055   OS << "typedef int8_t poly8_t;\n";
1056   OS << "typedef int16_t poly16_t;\n";
1057   OS << "typedef uint16_t float16_t;\n";
1058
1059   // Emit Neon vector typedefs.
1060   std::string TypedefTypes("cQcsQsiQilQlUcQUcUsQUsUiQUiUlQUlhQhfQfPcQPcPsQPs");
1061   SmallVector<StringRef, 24> TDTypeVec;
1062   ParseTypes(0, TypedefTypes, TDTypeVec);
1063
1064   // Emit vector typedefs.
1065   for (unsigned i = 0, e = TDTypeVec.size(); i != e; ++i) {
1066     bool dummy, quad = false, poly = false;
1067     (void) ClassifyType(TDTypeVec[i], quad, poly, dummy);
1068     if (poly)
1069       OS << "typedef __attribute__((neon_polyvector_type(";
1070     else
1071       OS << "typedef __attribute__((neon_vector_type(";
1072
1073     unsigned nElts = GetNumElements(TDTypeVec[i], quad);
1074     OS << utostr(nElts) << "))) ";
1075     if (nElts < 10)
1076       OS << " ";
1077
1078     OS << TypeString('s', TDTypeVec[i]);
1079     OS << " " << TypeString('d', TDTypeVec[i]) << ";\n";
1080   }
1081   OS << "\n";
1082   OS << "typedef __attribute__((__vector_size__(8)))  "
1083     "double float64x1_t;\n";
1084   OS << "typedef __attribute__((__vector_size__(16))) "
1085     "double float64x2_t;\n";
1086   OS << "\n";
1087
1088   // Emit struct typedefs.
1089   for (unsigned vi = 2; vi != 5; ++vi) {
1090     for (unsigned i = 0, e = TDTypeVec.size(); i != e; ++i) {
1091       std::string ts = TypeString('d', TDTypeVec[i]);
1092       std::string vs = TypeString('0' + vi, TDTypeVec[i]);
1093       OS << "typedef struct " << vs << " {\n";
1094       OS << "  " << ts << " val";
1095       OS << "[" << utostr(vi) << "]";
1096       OS << ";\n} ";
1097       OS << vs << ";\n\n";
1098     }
1099   }
1100
1101   OS << "#define __ai static __attribute__((__always_inline__))\n\n";
1102
1103   std::vector<Record*> RV = Records.getAllDerivedDefinitions("Inst");
1104
1105   // Emit vmovl and vabd intrinsics first so they can be used by other
1106   // intrinsics.
1107   emitIntrinsic(OS, Records.getDef("VMOVL"));
1108   emitIntrinsic(OS, Records.getDef("VABD"));
1109
1110   // Unique the return+pattern types, and assign them.
1111   for (unsigned i = 0, e = RV.size(); i != e; ++i) {
1112     Record *R = RV[i];
1113     if (R->getName() != "VMOVL" && R->getName() != "VABD")
1114       emitIntrinsic(OS, R);
1115   }
1116
1117   OS << "#undef __ai\n\n";
1118   OS << "#endif /* __ARM_NEON_H */\n";
1119 }
1120
1121 /// emitIntrinsic - Write out the arm_neon.h header file definitions for the
1122 /// intrinsics specified by record R.
1123 void NeonEmitter::emitIntrinsic(raw_ostream &OS, Record *R) {
1124   std::string name = R->getValueAsString("Name");
1125   std::string Proto = R->getValueAsString("Prototype");
1126   std::string Types = R->getValueAsString("Types");
1127
1128   SmallVector<StringRef, 16> TypeVec;
1129   ParseTypes(R, Types, TypeVec);
1130
1131   OpKind kind = OpMap[R->getValueAsDef("Operand")->getName()];
1132
1133   ClassKind classKind = ClassNone;
1134   if (R->getSuperClasses().size() >= 2)
1135     classKind = ClassMap[R->getSuperClasses()[1]];
1136   if (classKind == ClassNone && kind == OpNone)
1137     throw TGError(R->getLoc(), "Builtin has no class kind");
1138
1139   for (unsigned ti = 0, te = TypeVec.size(); ti != te; ++ti) {
1140     if (kind == OpReinterpret) {
1141       bool outQuad = false;
1142       bool dummy = false;
1143       (void)ClassifyType(TypeVec[ti], outQuad, dummy, dummy);
1144       for (unsigned srcti = 0, srcte = TypeVec.size();
1145            srcti != srcte; ++srcti) {
1146         bool inQuad = false;
1147         (void)ClassifyType(TypeVec[srcti], inQuad, dummy, dummy);
1148         if (srcti == ti || inQuad != outQuad)
1149           continue;
1150         OS << GenIntrinsic(name, Proto, TypeVec[ti], TypeVec[srcti],
1151                            OpCast, ClassS);
1152       }
1153     } else {
1154       OS << GenIntrinsic(name, Proto, TypeVec[ti], TypeVec[ti],
1155                          kind, classKind);
1156     }
1157   }
1158   OS << "\n";
1159 }
1160
1161 static unsigned RangeFromType(StringRef typestr) {
1162   // base type to get the type string for.
1163   bool quad = false, dummy = false;
1164   char type = ClassifyType(typestr, quad, dummy, dummy);
1165
1166   switch (type) {
1167     case 'c':
1168       return (8 << (int)quad) - 1;
1169     case 'h':
1170     case 's':
1171       return (4 << (int)quad) - 1;
1172     case 'f':
1173     case 'i':
1174       return (2 << (int)quad) - 1;
1175     case 'l':
1176       return (1 << (int)quad) - 1;
1177     default:
1178       throw "unhandled type!";
1179       break;
1180   }
1181   assert(0 && "unreachable");
1182   return 0;
1183 }
1184
1185 /// runHeader - Emit a file with sections defining:
1186 /// 1. the NEON section of BuiltinsARM.def.
1187 /// 2. the SemaChecking code for the type overload checking.
1188 /// 3. the SemaChecking code for validation of intrinsic immedate arguments.
1189 void NeonEmitter::runHeader(raw_ostream &OS) {
1190   std::vector<Record*> RV = Records.getAllDerivedDefinitions("Inst");
1191
1192   StringMap<OpKind> EmittedMap;
1193
1194   // Generate BuiltinsARM.def for NEON
1195   OS << "#ifdef GET_NEON_BUILTINS\n";
1196   for (unsigned i = 0, e = RV.size(); i != e; ++i) {
1197     Record *R = RV[i];
1198     OpKind k = OpMap[R->getValueAsDef("Operand")->getName()];
1199     if (k != OpNone)
1200       continue;
1201
1202     std::string Proto = R->getValueAsString("Prototype");
1203
1204     // Functions with 'a' (the splat code) in the type prototype should not get
1205     // their own builtin as they use the non-splat variant.
1206     if (Proto.find('a') != std::string::npos)
1207       continue;
1208
1209     std::string Types = R->getValueAsString("Types");
1210     SmallVector<StringRef, 16> TypeVec;
1211     ParseTypes(R, Types, TypeVec);
1212
1213     if (R->getSuperClasses().size() < 2)
1214       throw TGError(R->getLoc(), "Builtin has no class kind");
1215
1216     std::string name = R->getValueAsString("Name");
1217     ClassKind ck = ClassMap[R->getSuperClasses()[1]];
1218
1219     for (unsigned ti = 0, te = TypeVec.size(); ti != te; ++ti) {
1220       // Generate the BuiltinsARM.def declaration for this builtin, ensuring
1221       // that each unique BUILTIN() macro appears only once in the output
1222       // stream.
1223       std::string bd = GenBuiltinDef(name, Proto, TypeVec[ti], ck);
1224       if (EmittedMap.count(bd))
1225         continue;
1226
1227       EmittedMap[bd] = OpNone;
1228       OS << bd << "\n";
1229     }
1230   }
1231   OS << "#endif\n\n";
1232
1233   // Generate the overloaded type checking code for SemaChecking.cpp
1234   OS << "#ifdef GET_NEON_OVERLOAD_CHECK\n";
1235   for (unsigned i = 0, e = RV.size(); i != e; ++i) {
1236     Record *R = RV[i];
1237     OpKind k = OpMap[R->getValueAsDef("Operand")->getName()];
1238     if (k != OpNone)
1239       continue;
1240
1241     std::string Proto = R->getValueAsString("Prototype");
1242     std::string Types = R->getValueAsString("Types");
1243     std::string name = R->getValueAsString("Name");
1244
1245     // Functions with 'a' (the splat code) in the type prototype should not get
1246     // their own builtin as they use the non-splat variant.
1247     if (Proto.find('a') != std::string::npos)
1248       continue;
1249
1250     // Functions which have a scalar argument cannot be overloaded, no need to
1251     // check them if we are emitting the type checking code.
1252     if (Proto.find('s') != std::string::npos)
1253       continue;
1254
1255     SmallVector<StringRef, 16> TypeVec;
1256     ParseTypes(R, Types, TypeVec);
1257
1258     if (R->getSuperClasses().size() < 2)
1259       throw TGError(R->getLoc(), "Builtin has no class kind");
1260
1261     int si = -1, qi = -1;
1262     unsigned mask = 0, qmask = 0;
1263     for (unsigned ti = 0, te = TypeVec.size(); ti != te; ++ti) {
1264       // Generate the switch case(s) for this builtin for the type validation.
1265       bool quad = false, poly = false, usgn = false;
1266       (void) ClassifyType(TypeVec[ti], quad, poly, usgn);
1267
1268       if (quad) {
1269         qi = ti;
1270         qmask |= 1 << GetNeonEnum(Proto, TypeVec[ti]);
1271       } else {
1272         si = ti;
1273         mask |= 1 << GetNeonEnum(Proto, TypeVec[ti]);
1274       }
1275     }
1276     if (mask)
1277       OS << "case ARM::BI__builtin_neon_"
1278          << MangleName(name, TypeVec[si], ClassB)
1279          << ": mask = " << "0x" << utohexstr(mask) << "; break;\n";
1280     if (qmask)
1281       OS << "case ARM::BI__builtin_neon_"
1282          << MangleName(name, TypeVec[qi], ClassB)
1283          << ": mask = " << "0x" << utohexstr(qmask) << "; break;\n";
1284   }
1285   OS << "#endif\n\n";
1286
1287   // Generate the intrinsic range checking code for shift/lane immediates.
1288   OS << "#ifdef GET_NEON_IMMEDIATE_CHECK\n";
1289   for (unsigned i = 0, e = RV.size(); i != e; ++i) {
1290     Record *R = RV[i];
1291
1292     OpKind k = OpMap[R->getValueAsDef("Operand")->getName()];
1293     if (k != OpNone)
1294       continue;
1295
1296     std::string name = R->getValueAsString("Name");
1297     std::string Proto = R->getValueAsString("Prototype");
1298     std::string Types = R->getValueAsString("Types");
1299
1300     // Functions with 'a' (the splat code) in the type prototype should not get
1301     // their own builtin as they use the non-splat variant.
1302     if (Proto.find('a') != std::string::npos)
1303       continue;
1304
1305     // Functions which do not have an immediate do not need to have range
1306     // checking code emitted.
1307     if (Proto.find('i') == std::string::npos)
1308       continue;
1309
1310     SmallVector<StringRef, 16> TypeVec;
1311     ParseTypes(R, Types, TypeVec);
1312
1313     if (R->getSuperClasses().size() < 2)
1314       throw TGError(R->getLoc(), "Builtin has no class kind");
1315
1316     ClassKind ck = ClassMap[R->getSuperClasses()[1]];
1317
1318     for (unsigned ti = 0, te = TypeVec.size(); ti != te; ++ti) {
1319       std::string namestr, shiftstr, rangestr;
1320
1321       // Builtins which are overloaded by type will need to have their upper
1322       // bound computed at Sema time based on the type constant.
1323       if (Proto.find('s') == std::string::npos) {
1324         ck = ClassB;
1325         if (R->getValueAsBit("isShift")) {
1326           shiftstr = ", true";
1327
1328           // Right shifts have an 'r' in the name, left shifts do not.
1329           if (name.find('r') != std::string::npos)
1330             rangestr = "l = 1; ";
1331         }
1332         rangestr += "u = RFT(TV" + shiftstr + ")";
1333       } else {
1334         rangestr = "u = " + utostr(RangeFromType(TypeVec[ti]));
1335       }
1336       // Make sure cases appear only once by uniquing them in a string map.
1337       namestr = MangleName(name, TypeVec[ti], ck);
1338       if (EmittedMap.count(namestr))
1339         continue;
1340       EmittedMap[namestr] = OpNone;
1341
1342       // Calculate the index of the immediate that should be range checked.
1343       unsigned immidx = 0;
1344
1345       // Builtins that return a struct of multiple vectors have an extra
1346       // leading arg for the struct return.
1347       if (Proto[0] >= '2' && Proto[0] <= '4')
1348         ++immidx;
1349
1350       // Add one to the index for each argument until we reach the immediate
1351       // to be checked.  Structs of vectors are passed as multiple arguments.
1352       for (unsigned ii = 1, ie = Proto.size(); ii != ie; ++ii) {
1353         switch (Proto[ii]) {
1354           default:  immidx += 1; break;
1355           case '2': immidx += 2; break;
1356           case '3': immidx += 3; break;
1357           case '4': immidx += 4; break;
1358           case 'i': ie = ii + 1; break;
1359         }
1360       }
1361       OS << "case ARM::BI__builtin_neon_" << MangleName(name, TypeVec[ti], ck)
1362          << ": i = " << immidx << "; " << rangestr << "; break;\n";
1363     }
1364   }
1365   OS << "#endif\n\n";
1366 }