Add support for returning multiple vectors via sret, which is how the ARM target...
[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 widen!";
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     case 'x':
138       poly = false;
139       if (type == 'f')
140         type = 'i';
141       break;
142     case 'f':
143       if (type == 'h')
144         quad = true;
145       type = 'f';
146       usgn = false;
147       break;
148     case 'w':
149       type = Widen(type);
150       quad = true;
151       break;
152     case 'n':
153       type = Widen(type);
154       break;
155     case 'l':
156       type = 'l';
157       scal = true;
158       usgn = true;
159       break;
160     case 's':
161     case 'a':
162       scal = true;
163       break;
164     case 'k':
165       quad = true;
166       break;
167     case 'c':
168       cnst = true;
169     case 'p':
170       pntr = true;
171       scal = true;
172       break;
173     case 'h':
174       type = Narrow(type);
175       if (type == 'h')
176         quad = false;
177       break;
178     case 'e':
179       type = Narrow(type);
180       usgn = true;
181       break;
182     default:
183       break;
184   }
185   return type;
186 }
187
188 /// TypeString - for a modifier and type, generate the name of the typedef for
189 /// that type.  If generic is true, emit the generic vector type rather than
190 /// the public NEON type. QUc -> uint8x8t_t / __neon_uint8x8_t.
191 static std::string TypeString(const char mod, StringRef typestr,
192                               bool generic = false) {
193   bool quad = false;
194   bool poly = false;
195   bool usgn = false;
196   bool scal = false;
197   bool cnst = false;
198   bool pntr = false;
199   
200   if (mod == 'v')
201     return "void";
202   if (mod == 'i')
203     return "int";
204   
205   // base type to get the type string for.
206   char type = ClassifyType(typestr, quad, poly, usgn);
207   
208   // Based on the modifying character, change the type and width if necessary.
209   type = ModType(mod, type, quad, poly, usgn, scal, cnst, pntr);
210   
211   SmallString<128> s;
212   
213   if (generic)
214     s += "__neon_";
215   
216   if (usgn)
217     s.push_back('u');
218   
219   switch (type) {
220     case 'c':
221       s += poly ? "poly8" : "int8";
222       if (scal)
223         break;
224       s += quad ? "x16" : "x8";
225       break;
226     case 's':
227       s += poly ? "poly16" : "int16";
228       if (scal)
229         break;
230       s += quad ? "x8" : "x4";
231       break;
232     case 'i':
233       s += "int32";
234       if (scal)
235         break;
236       s += quad ? "x4" : "x2";
237       break;
238     case 'l':
239       s += "int64";
240       if (scal)
241         break;
242       s += quad ? "x2" : "x1";
243       break;
244     case 'h':
245       s += "float16";
246       if (scal)
247         break;
248       s += quad ? "x8" : "x4";
249       break;
250     case 'f':
251       s += "float32";
252       if (scal)
253         break;
254       s += quad ? "x4" : "x2";
255       break;
256     default:
257       throw "unhandled type!";
258       break;
259   }
260
261   if (mod == '2')
262     s += "x2";
263   if (mod == '3')
264     s += "x3";
265   if (mod == '4')
266     s += "x4";
267   
268   // Append _t, finishing the type string typedef type.
269   s += "_t";
270   
271   if (cnst)
272     s += " const";
273   
274   if (pntr)
275     s += " *";
276   
277   return s.str();
278 }
279
280 /// TypeString - for a modifier and type, generate the clang BuiltinsARM.def 
281 /// prototype code for the function.  See the top of clang's Builtins.def for
282 /// a description of the type strings.
283 static std::string BuiltinTypeString(const char mod, StringRef typestr,
284                                      ClassKind ck, bool ret) {
285   bool quad = false;
286   bool poly = false;
287   bool usgn = false;
288   bool scal = false;
289   bool cnst = false;
290   bool pntr = false;
291   
292   if (mod == 'v')
293     return "v";
294   if (mod == 'i')
295     return "i";
296   
297   // base type to get the type string for.
298   char type = ClassifyType(typestr, quad, poly, usgn);
299   
300   // Based on the modifying character, change the type and width if necessary.
301   type = ModType(mod, type, quad, poly, usgn, scal, cnst, pntr);
302
303   if (pntr) {
304     usgn = false;
305     poly = false;
306     type = 'v';
307   }
308   if (type == 'h') {
309     type = 's';
310     usgn = true;
311   }
312   usgn = usgn | poly | ((ck == ClassI || ck == ClassW) && scal && type != 'f');
313
314   if (scal) {
315     SmallString<128> s;
316
317     if (usgn)
318       s.push_back('U');
319     
320     if (type == 'l')
321       s += "LLi";
322     else
323       s.push_back(type);
324  
325     if (cnst)
326       s.push_back('C');
327     if (pntr)
328       s.push_back('*');
329     return s.str();
330   }
331
332   // Since the return value must be one type, return a vector type of the
333   // appropriate width which we will bitcast.  An exception is made for
334   // returning structs of 2, 3, or 4 vectors which are returned in a sret-like
335   // fashion, storing them to a pointer arg.
336   if (ret) {
337     if (mod == '2' || mod == '3' || mod == '4')
338       return "vv*";
339     if (mod == 'f' || (ck != ClassB && type == 'f'))
340       return quad ? "V4f" : "V2f";
341     if (ck != ClassB && type == 's')
342       return quad ? "V8s" : "V4s";
343     if (ck != ClassB && type == 'i')
344       return quad ? "V4i" : "V2i";
345     if (ck != ClassB && type == 'l')
346       return quad ? "V2LLi" : "V1LLi";
347     
348     return quad ? "V16c" : "V8c";
349   }    
350
351   // Non-return array types are passed as individual vectors.
352   if (mod == '2')
353     return quad ? "V16cV16c" : "V8cV8c";
354   if (mod == '3')
355     return quad ? "V16cV16cV16c" : "V8cV8cV8c";
356   if (mod == '4')
357     return quad ? "V16cV16cV16cV16c" : "V8cV8cV8cV8c";
358
359   if (mod == 'f' || (ck != ClassB && type == 'f'))
360     return quad ? "V4f" : "V2f";
361   if (ck != ClassB && type == 's')
362     return quad ? "V8s" : "V4s";
363   if (ck != ClassB && type == 'i')
364     return quad ? "V4i" : "V2i";
365   if (ck != ClassB && type == 'l')
366     return quad ? "V2LLi" : "V1LLi";
367   
368   return quad ? "V16c" : "V8c";
369 }
370
371 /// MangleName - Append a type or width suffix to a base neon function name, 
372 /// and insert a 'q' in the appropriate location if the operation works on
373 /// 128b rather than 64b.   E.g. turn "vst2_lane" into "vst2q_lane_f32", etc.
374 static std::string MangleName(const std::string &name, StringRef typestr,
375                               ClassKind ck) {
376   if (name == "vcvt_f32_f16")
377     return name;
378   
379   bool quad = false;
380   bool poly = false;
381   bool usgn = false;
382   char type = ClassifyType(typestr, quad, poly, usgn);
383
384   std::string s = name;
385   
386   switch (type) {
387   case 'c':
388     switch (ck) {
389     case ClassS: s += poly ? "_p8" : usgn ? "_u8" : "_s8"; break;
390     case ClassI: s += "_i8"; break;
391     case ClassW: s += "_8"; break;
392     default: break;
393     }
394     break;
395   case 's':
396     switch (ck) {
397     case ClassS: s += poly ? "_p16" : usgn ? "_u16" : "_s16"; break;
398     case ClassI: s += "_i16"; break;
399     case ClassW: s += "_16"; break;
400     default: break;
401     }
402     break;
403   case 'i':
404     switch (ck) {
405     case ClassS: s += usgn ? "_u32" : "_s32"; break;
406     case ClassI: s += "_i32"; break;
407     case ClassW: s += "_32"; break;
408     default: break;
409     }
410     break;
411   case 'l':
412     switch (ck) {
413     case ClassS: s += usgn ? "_u64" : "_s64"; break;
414     case ClassI: s += "_i64"; break;
415     case ClassW: s += "_64"; break;
416     default: break;
417     }
418     break;
419   case 'h':
420     switch (ck) {
421     case ClassS:
422     case ClassI: s += "_f16"; break;
423     case ClassW: s += "_16"; break;
424     default: break;
425     }
426     break;
427   case 'f':
428     switch (ck) {
429     case ClassS:
430     case ClassI: s += "_f32"; break;
431     case ClassW: s += "_32"; break;
432     default: break;
433     }
434     break;
435   default:
436     throw "unhandled type!";
437     break;
438   }
439   if (ck == ClassB)
440     s += "_v";
441     
442   // Insert a 'q' before the first '_' character so that it ends up before 
443   // _lane or _n on vector-scalar operations.
444   if (quad) {
445     size_t pos = s.find('_');
446     s = s.insert(pos, "q");
447   }
448   return s;
449 }
450
451 // Generate the string "(argtype a, argtype b, ...)"
452 static std::string GenArgs(const std::string &proto, StringRef typestr) {
453   bool define = proto.find('i') != std::string::npos;
454   char arg = 'a';
455   
456   std::string s;
457   s += "(";
458   
459   for (unsigned i = 1, e = proto.size(); i != e; ++i, ++arg) {
460     if (!define) {
461       s += TypeString(proto[i], typestr);
462       s.push_back(' ');
463     }
464     s.push_back(arg);
465     if ((i + 1) < e)
466       s += ", ";
467   }
468   
469   s += ")";
470   return s;
471 }
472
473 static std::string Duplicate(unsigned nElts, StringRef typestr, 
474                              const std::string &a) {
475   std::string s;
476   
477   s = "(__neon_" + TypeString('d', typestr) + "){ ";
478   for (unsigned i = 0; i != nElts; ++i) {
479     s += a;
480     if ((i + 1) < nElts)
481       s += ", ";
482   }
483   s += " }";
484   
485   return s;
486 }
487
488 // Generate the definition for this intrinsic, e.g. "a + b" for OpAdd.
489 // If structTypes is true, the NEON types are structs of vector types rather
490 // than vector types, and the call becomes "a.val + b.val"
491 static std::string GenOpString(OpKind op, const std::string &proto,
492                                StringRef typestr, bool structTypes = true) {
493   bool dummy, quad = false;
494   char type = ClassifyType(typestr, quad, dummy, dummy);
495   unsigned nElts = 0;
496   switch (type) {
497     case 'c': nElts = 8; break;
498     case 's': nElts = 4; break;
499     case 'i': nElts = 2; break;
500     case 'l': nElts = 1; break;
501     case 'h': nElts = 4; break;
502     case 'f': nElts = 2; break;
503   }
504   
505   std::string ts = TypeString(proto[0], typestr);
506   std::string s = ts + " r; r";
507   
508   if (structTypes)
509     s += ".val";
510   
511   s += " = ";
512
513   std::string a, b, c;
514   if (proto.size() > 1)
515     a = (structTypes && proto[1] != 'l' && proto[1] != 's') ? "a.val" : "a";
516   b = structTypes ? "b.val" : "b";
517   c = structTypes ? "c.val" : "c";
518   
519   switch(op) {
520   case OpAdd:
521     s += a + " + " + b;
522     break;
523   case OpSub:
524     s += a + " - " + b;
525     break;
526   case OpMulN:
527     b = Duplicate(nElts << (int)quad, typestr, "b");
528   case OpMul:
529     s += a + " * " + b;
530     break;
531   case OpMlaN:
532     c = Duplicate(nElts << (int)quad, typestr, "c");
533   case OpMla:
534     s += a + " + ( " + b + " * " + c + " )";
535     break;
536   case OpMlsN:
537     c = Duplicate(nElts << (int)quad, typestr, "c");
538   case OpMls:
539     s += a + " - ( " + b + " * " + c + " )";
540     break;
541   case OpEq:
542     s += "(__neon_" + ts + ")(" + a + " == " + b + ")";
543     break;
544   case OpGe:
545     s += "(__neon_" + ts + ")(" + a + " >= " + b + ")";
546     break;
547   case OpLe:
548     s += "(__neon_" + ts + ")(" + a + " <= " + b + ")";
549     break;
550   case OpGt:
551     s += "(__neon_" + ts + ")(" + a + " > " + b + ")";
552     break;
553   case OpLt:
554     s += "(__neon_" + ts + ")(" + a + " < " + b + ")";
555     break;
556   case OpNeg:
557     s += " -" + a;
558     break;
559   case OpNot:
560     s += " ~" + a;
561     break;
562   case OpAnd:
563     s += a + " & " + b;
564     break;
565   case OpOr:
566     s += a + " | " + b;
567     break;
568   case OpXor:
569     s += a + " ^ " + b;
570     break;
571   case OpAndNot:
572     s += a + " & ~" + b;
573     break;
574   case OpOrNot:
575     s += a + " | ~" + b;
576     break;
577   case OpCast:
578     s += "(__neon_" + ts + ")" + a;
579     break;
580   case OpConcat:
581     s += "__builtin_shufflevector((__neon_int64x1_t)" + a;
582     s += ", (__neon_int64x1_t)" + b + ", 0, 1)";
583     break;
584   case OpHi:
585     s += "(__neon_int64x1_t)(((__neon_int64x2_t)" + a + ")[1])";
586     break;
587   case OpLo:
588     s += "(__neon_int64x1_t)(((__neon_int64x2_t)" + a + ")[0])";
589     break;
590   case OpDup:
591     s += Duplicate(nElts << (int)quad, typestr, a);
592     break;
593   case OpSelect:
594     // ((0 & 1) | (~0 & 2))
595     ts = TypeString(proto[1], typestr);
596     s += "( " + a + " & (__neon_" + ts + ")" + b + ") | ";
597     s += "(~" + a + " & (__neon_" + ts + ")" + c + ")";
598     break;
599   case OpRev16:
600     s += "__builtin_shufflevector(" + a + ", " + a;
601     for (unsigned i = 2; i <= nElts << (int)quad; i += 2)
602       for (unsigned j = 0; j != 2; ++j)
603         s += ", " + utostr(i - j - 1);
604     s += ")";
605     break;
606   case OpRev32:
607     nElts >>= 1;
608     s += "__builtin_shufflevector(" + a + ", " + a;
609     for (unsigned i = nElts; i <= nElts << (1 + (int)quad); i += nElts)
610       for (unsigned j = 0; j != nElts; ++j)
611         s += ", " + utostr(i - j - 1);
612     s += ")";
613     break;
614   case OpRev64:
615     s += "__builtin_shufflevector(" + a + ", " + a;
616     for (unsigned i = nElts; i <= nElts << (int)quad; i += nElts)
617       for (unsigned j = 0; j != nElts; ++j)
618         s += ", " + utostr(i - j - 1);
619     s += ")";
620     break;
621   default:
622     throw "unknown OpKind!";
623     break;
624   }
625   s += "; return r;";
626   return s;
627 }
628
629 static unsigned GetNeonEnum(const std::string &proto, StringRef typestr) {
630   unsigned mod = proto[0];
631   unsigned ret = 0;
632
633   if (mod == 'v' || mod == 'f')
634     mod = proto[1];
635
636   bool quad = false;
637   bool poly = false;
638   bool usgn = false;
639   bool scal = false;
640   bool cnst = false;
641   bool pntr = false;
642   
643   // base type to get the type string for.
644   char type = ClassifyType(typestr, quad, poly, usgn);
645   
646   // Based on the modifying character, change the type and width if necessary.
647   type = ModType(mod, type, quad, poly, usgn, scal, cnst, pntr);
648   
649   if (usgn)
650     ret |= 0x08;
651   if (quad)
652     ret |= 0x10;
653   
654   switch (type) {
655     case 'c': 
656       ret |= poly ? 5 : 0;
657       break;
658     case 's':
659       ret |= poly ? 6 : 1;
660       break;
661     case 'i':
662       ret |= 2;
663       break;
664     case 'l':
665       ret |= 3;
666       break;
667     case 'h':
668       ret |= 7;
669       break;
670     case 'f':
671       ret |= 4;
672       break;
673     default:
674       throw "unhandled type!";
675       break;
676   }
677   return ret;
678 }
679
680 // Generate the definition for this intrinsic, e.g. __builtin_neon_cls(a)
681 // If structTypes is true, the NEON types are structs of vector types rather
682 // than vector types, and the call becomes __builtin_neon_cls(a.val)
683 static std::string GenBuiltin(const std::string &name, const std::string &proto,
684                               StringRef typestr, ClassKind ck,
685                               bool structTypes = true) {
686   bool dummy, quad = false;
687   char type = ClassifyType(typestr, quad, dummy, dummy);
688   unsigned nElts = 0;
689   switch (type) {
690     case 'c': nElts = 8; break;
691     case 's': nElts = 4; break;
692     case 'i': nElts = 2; break;
693     case 'l': nElts = 1; break;
694     case 'h': nElts = 4; break;
695     case 'f': nElts = 2; break;
696   }
697   if (quad) nElts <<= 1;
698
699   char arg = 'a';
700   std::string s;
701
702   // If this builtin returns a struct 2, 3, or 4 vectors, pass it as an implicit
703   // sret-like argument.
704   bool sret = (proto[0] == '2' || proto[0] == '3' || proto[0] == '4');
705
706   // If this builtin takes an immediate argument, we need to #define it rather
707   // than use a standard declaration, so that SemaChecking can range check
708   // the immediate passed by the user.
709   bool define = proto.find('i') != std::string::npos;
710
711   // If all types are the same size, bitcasting the args will take care 
712   // of arg checking.  The actual signedness etc. will be taken care of with
713   // special enums.
714   if (proto.find('s') == std::string::npos)
715     ck = ClassB;
716
717   if (proto[0] != 'v') {
718     std::string ts = TypeString(proto[0], typestr);
719     
720     if (define) {
721       if (sret)
722         s += "({ " + ts + " r; ";
723       else if (proto[0] != 's')
724         s += "(" + ts + "){(__neon_" + ts + ")";
725     } else if (sret) {
726       s += ts + " r; ";
727     } else {
728       s += ts + " r; r";
729       if (structTypes && proto[0] != 's' && proto[0] != 'i' && proto[0] != 'l')
730         s += ".val";
731       
732       s += " = ";
733     }
734   }
735   
736   bool splat = proto.find('a') != std::string::npos;
737   
738   s += "__builtin_neon_";
739   if (splat) {
740     std::string vname(name, 0, name.size()-2);
741     s += MangleName(vname, typestr, ck);
742   } else {
743     s += MangleName(name, typestr, ck);
744   }
745   s += "(";
746
747   // Pass the address of the return variable as the first argument to sret-like
748   // builtins.
749   if (sret)
750     s += "&r, ";
751   
752   for (unsigned i = 1, e = proto.size(); i != e; ++i, ++arg) {
753     std::string args = std::string(&arg, 1);
754     if (define)
755       args = "(" + args + ")";
756     
757     // Handle multiple-vector values specially, emitting each subvector as an
758     // argument to the __builtin.
759     if (structTypes && (proto[i] == '2' || proto[i] == '3' || proto[i] == '4')){
760       for (unsigned vi = 0, ve = proto[i] - '0'; vi != ve; ++vi) {
761         s += args + ".val[" + utostr(vi) + "]";
762         if ((vi + 1) < ve)
763           s += ", ";
764       }
765       if ((i + 1) < e)
766         s += ", ";
767
768       continue;
769     }
770     
771     if (splat && (i + 1) == e) 
772       s += Duplicate(nElts, typestr, args);
773     else
774       s += args;
775     
776     if (structTypes && proto[i] != 's' && proto[i] != 'i' && proto[i] != 'l' &&
777         proto[i] != 'p' && proto[i] != 'c' && proto[i] != 'a') {
778       s += ".val";
779     }
780     if ((i + 1) < e)
781       s += ", ";
782   }
783   
784   // Extra constant integer to hold type class enum for this function, e.g. s8
785   if (ck == ClassB)
786     s += ", " + utostr(GetNeonEnum(proto, typestr));
787   
788   if (define)
789     s += ")";
790   else
791     s += ");";
792
793   if (proto[0] != 'v') {
794     if (define) {
795       if (sret)
796         s += "; r; })";
797       else if (proto[0] != 's')
798         s += "}";
799     } else {
800       s += " return r;";
801     }
802   }
803   return s;
804 }
805
806 static std::string GenBuiltinDef(const std::string &name, 
807                                  const std::string &proto,
808                                  StringRef typestr, ClassKind ck) {
809   std::string s("BUILTIN(__builtin_neon_");
810
811   // If all types are the same size, bitcasting the args will take care 
812   // of arg checking.  The actual signedness etc. will be taken care of with
813   // special enums.
814   if (proto.find('s') == std::string::npos)
815     ck = ClassB;
816   
817   s += MangleName(name, typestr, ck);
818   s += ", \"";
819   
820   for (unsigned i = 0, e = proto.size(); i != e; ++i)
821     s += BuiltinTypeString(proto[i], typestr, ck, i == 0);
822
823   // Extra constant integer to hold type class enum for this function, e.g. s8
824   if (ck == ClassB)
825     s += "i";
826   
827   s += "\", \"n\")";
828   return s;
829 }
830
831 /// run - Read the records in arm_neon.td and output arm_neon.h.  arm_neon.h
832 /// is comprised of type definitions and function declarations.
833 void NeonEmitter::run(raw_ostream &OS) {
834   EmitSourceFileHeader("ARM NEON Header", OS);
835   
836   // FIXME: emit license into file?
837   
838   OS << "#ifndef __ARM_NEON_H\n";
839   OS << "#define __ARM_NEON_H\n\n";
840   
841   OS << "#ifndef __ARM_NEON__\n";
842   OS << "#error \"NEON support not enabled\"\n";
843   OS << "#endif\n\n";
844
845   OS << "#include <stdint.h>\n\n";
846
847   // Emit NEON-specific scalar typedefs.
848   OS << "typedef float float32_t;\n";
849   OS << "typedef uint8_t poly8_t;\n";
850   OS << "typedef uint16_t poly16_t;\n";
851   OS << "typedef uint16_t float16_t;\n";
852
853   // Emit Neon vector typedefs.
854   std::string TypedefTypes("cQcsQsiQilQlUcQUcUsQUsUiQUiUlQUlhQhfQfPcQPcPsQPs");
855   SmallVector<StringRef, 24> TDTypeVec;
856   ParseTypes(0, TypedefTypes, TDTypeVec);
857
858   // Emit vector typedefs.
859   for (unsigned v = 1; v != 5; ++v) {
860     for (unsigned i = 0, e = TDTypeVec.size(); i != e; ++i) {
861       bool dummy, quad = false;
862       (void) ClassifyType(TDTypeVec[i], quad, dummy, dummy);
863       OS << "typedef __attribute__(( __vector_size__(";
864       
865       OS << utostr(8*v*(quad ? 2 : 1)) << ") )) ";
866       if (!quad)
867         OS << " ";
868       
869       OS << TypeString('s', TDTypeVec[i]);
870       OS << " __neon_";
871       
872       char t = (v == 1) ? 'd' : '0' + v;
873       OS << TypeString(t, TDTypeVec[i]) << ";\n";
874     }
875   }
876   OS << "\n";
877
878   // Emit struct typedefs.
879   for (unsigned vi = 1; vi != 5; ++vi) {
880     for (unsigned i = 0, e = TDTypeVec.size(); i != e; ++i) {
881       std::string ts = TypeString('d', TDTypeVec[i]);
882       std::string vs = (vi > 1) ? TypeString('0' + vi, TDTypeVec[i]) : ts;
883       OS << "typedef struct __" << vs << " {\n";
884       OS << "  __neon_" << ts << " val";
885       if (vi > 1)
886         OS << "[" << utostr(vi) << "]";
887       OS << ";\n} " << vs << ";\n\n";
888     }
889   }
890   
891   OS << "#define __ai static __attribute__((__always_inline__))\n\n";
892
893   std::vector<Record*> RV = Records.getAllDerivedDefinitions("Inst");
894   
895   // Unique the return+pattern types, and assign them.
896   for (unsigned i = 0, e = RV.size(); i != e; ++i) {
897     Record *R = RV[i];
898     std::string name = LowercaseString(R->getName());
899     std::string Proto = R->getValueAsString("Prototype");
900     std::string Types = R->getValueAsString("Types");
901     
902     SmallVector<StringRef, 16> TypeVec;
903     ParseTypes(R, Types, TypeVec);
904     
905     OpKind k = OpMap[R->getValueAsDef("Operand")->getName()];
906     
907     bool define = Proto.find('i') != std::string::npos;
908     
909     for (unsigned ti = 0, te = TypeVec.size(); ti != te; ++ti) {
910       assert(!Proto.empty() && "");
911       
912       // static always inline + return type
913       if (define)
914         OS << "#define";
915       else
916         OS << "__ai " << TypeString(Proto[0], TypeVec[ti]);
917       
918       // Function name with type suffix
919       OS << " " << MangleName(name, TypeVec[ti], ClassS);
920       
921       // Function arguments
922       OS << GenArgs(Proto, TypeVec[ti]);
923       
924       // Definition.
925       if (define)
926         OS << " ";
927       else
928         OS << " { ";
929       
930       if (k != OpNone) {
931         OS << GenOpString(k, Proto, TypeVec[ti]);
932       } else {
933         if (R->getSuperClasses().size() < 2)
934           throw TGError(R->getLoc(), "Builtin has no class kind");
935         
936         ClassKind ck = ClassMap[R->getSuperClasses()[1]];
937
938         if (ck == ClassNone)
939           throw TGError(R->getLoc(), "Builtin has no class kind");
940         OS << GenBuiltin(name, Proto, TypeVec[ti], ck);
941       }
942       if (!define)
943         OS << " }";
944       OS << "\n";
945     }
946     OS << "\n";
947   }
948   OS << "#undef __ai\n\n";
949   OS << "#endif /* __ARM_NEON_H */\n";
950 }
951
952 static unsigned RangeFromType(StringRef typestr) {
953   // base type to get the type string for.
954   bool quad = false, dummy = false;
955   char type = ClassifyType(typestr, quad, dummy, dummy);
956   
957   switch (type) {
958     case 'c':
959       return (8 << (int)quad) - 1;
960     case 'h':
961     case 's':
962       return (4 << (int)quad) - 1;
963     case 'f':
964     case 'i':
965       return (2 << (int)quad) - 1;
966     case 'l':
967       return (1 << (int)quad) - 1;
968     default:
969       throw "unhandled type!";
970       break;
971   }
972 }
973
974 /// runHeader - Emit a file with sections defining:
975 /// 1. the NEON section of BuiltinsARM.def.
976 /// 2. the SemaChecking code for the type overload checking.
977 /// 3. the SemaChecking code for validation of intrinsic immedate arguments.
978 void NeonEmitter::runHeader(raw_ostream &OS) {
979   std::vector<Record*> RV = Records.getAllDerivedDefinitions("Inst");
980
981   StringMap<OpKind> EmittedMap;
982   
983   // Generate BuiltinsARM.def for NEON
984   OS << "#ifdef GET_NEON_BUILTINS\n";
985   for (unsigned i = 0, e = RV.size(); i != e; ++i) {
986     Record *R = RV[i];
987     OpKind k = OpMap[R->getValueAsDef("Operand")->getName()];
988     if (k != OpNone)
989       continue;
990
991     std::string Proto = R->getValueAsString("Prototype");
992     
993     // Functions with 'a' (the splat code) in the type prototype should not get
994     // their own builtin as they use the non-splat variant.
995     if (Proto.find('a') != std::string::npos)
996       continue;
997     
998     std::string Types = R->getValueAsString("Types");
999     SmallVector<StringRef, 16> TypeVec;
1000     ParseTypes(R, Types, TypeVec);
1001     
1002     if (R->getSuperClasses().size() < 2)
1003       throw TGError(R->getLoc(), "Builtin has no class kind");
1004     
1005     std::string name = LowercaseString(R->getName());
1006     ClassKind ck = ClassMap[R->getSuperClasses()[1]];
1007     
1008     for (unsigned ti = 0, te = TypeVec.size(); ti != te; ++ti) {
1009       // Generate the BuiltinsARM.def declaration for this builtin, ensuring
1010       // that each unique BUILTIN() macro appears only once in the output
1011       // stream.
1012       std::string bd = GenBuiltinDef(name, Proto, TypeVec[ti], ck);
1013       if (EmittedMap.count(bd))
1014         continue;
1015       
1016       EmittedMap[bd] = OpNone;
1017       OS << bd << "\n";
1018     }
1019   }
1020   OS << "#endif\n\n";
1021   
1022   // Generate the overloaded type checking code for SemaChecking.cpp
1023   OS << "#ifdef GET_NEON_OVERLOAD_CHECK\n";
1024   for (unsigned i = 0, e = RV.size(); i != e; ++i) {
1025     Record *R = RV[i];
1026     OpKind k = OpMap[R->getValueAsDef("Operand")->getName()];
1027     if (k != OpNone)
1028       continue;
1029     
1030     std::string Proto = R->getValueAsString("Prototype");
1031     std::string Types = R->getValueAsString("Types");
1032     std::string name = LowercaseString(R->getName());
1033     
1034     // Functions with 'a' (the splat code) in the type prototype should not get
1035     // their own builtin as they use the non-splat variant.
1036     if (Proto.find('a') != std::string::npos)
1037       continue;
1038     
1039     // Functions which have a scalar argument cannot be overloaded, no need to
1040     // check them if we are emitting the type checking code.
1041     if (Proto.find('s') != std::string::npos)
1042       continue;
1043     
1044     SmallVector<StringRef, 16> TypeVec;
1045     ParseTypes(R, Types, TypeVec);
1046     
1047     if (R->getSuperClasses().size() < 2)
1048       throw TGError(R->getLoc(), "Builtin has no class kind");
1049     
1050     int si = -1, qi = -1;
1051     unsigned mask = 0, qmask = 0;
1052     for (unsigned ti = 0, te = TypeVec.size(); ti != te; ++ti) {
1053       // Generate the switch case(s) for this builtin for the type validation.
1054       bool quad = false, poly = false, usgn = false;
1055       (void) ClassifyType(TypeVec[ti], quad, poly, usgn);
1056       
1057       if (quad) {
1058         qi = ti;
1059         qmask |= 1 << GetNeonEnum(Proto, TypeVec[ti]);
1060       } else {
1061         si = ti;
1062         mask |= 1 << GetNeonEnum(Proto, TypeVec[ti]);
1063       }
1064     }
1065     if (mask)
1066       OS << "case ARM::BI__builtin_neon_" 
1067       << MangleName(name, TypeVec[si], ClassB)
1068       << ": mask = " << "0x" << utohexstr(mask) << "; break;\n";
1069     if (qmask)
1070       OS << "case ARM::BI__builtin_neon_" 
1071       << MangleName(name, TypeVec[qi], ClassB)
1072       << ": mask = " << "0x" << utohexstr(qmask) << "; break;\n";
1073   }
1074   OS << "#endif\n\n";
1075   
1076   // Generate the intrinsic range checking code for shift/lane immediates.
1077   OS << "#ifdef GET_NEON_IMMEDIATE_CHECK\n";
1078   for (unsigned i = 0, e = RV.size(); i != e; ++i) {
1079     Record *R = RV[i];
1080     
1081     OpKind k = OpMap[R->getValueAsDef("Operand")->getName()];
1082     if (k != OpNone)
1083       continue;
1084     
1085     std::string name = LowercaseString(R->getName());
1086     std::string Proto = R->getValueAsString("Prototype");
1087     std::string Types = R->getValueAsString("Types");
1088     
1089     // Functions with 'a' (the splat code) in the type prototype should not get
1090     // their own builtin as they use the non-splat variant.
1091     if (Proto.find('a') != std::string::npos)
1092       continue;
1093     
1094     // Functions which do not have an immediate do not need to have range
1095     // checking code emitted.
1096     if (Proto.find('i') == std::string::npos)
1097       continue;
1098     
1099     SmallVector<StringRef, 16> TypeVec;
1100     ParseTypes(R, Types, TypeVec);
1101     
1102     if (R->getSuperClasses().size() < 2)
1103       throw TGError(R->getLoc(), "Builtin has no class kind");
1104     
1105     ClassKind ck = ClassMap[R->getSuperClasses()[1]];
1106     
1107     for (unsigned ti = 0, te = TypeVec.size(); ti != te; ++ti) {
1108       std::string namestr, shiftstr, rangestr;
1109       
1110       // Builtins which are overloaded by type will need to have their upper
1111       // bound computed at Sema time based on the type constant.
1112       if (Proto.find('s') == std::string::npos) {
1113         ck = ClassB;
1114         if (R->getValueAsBit("isShift")) {
1115           shiftstr = ", true";
1116           
1117           // Right shifts have an 'r' in the name, left shifts do not.
1118           if (name.find('r') != std::string::npos)
1119             rangestr = "l = 1; ";
1120         }
1121         rangestr += "u = RFT(TV" + shiftstr + ")";
1122       } else {
1123         rangestr = "u = " + utostr(RangeFromType(TypeVec[ti]));
1124       }
1125       // Make sure cases appear only once by uniquing them in a string map.
1126       namestr = MangleName(name, TypeVec[ti], ck);
1127       if (EmittedMap.count(namestr))
1128         continue;
1129       EmittedMap[namestr] = OpNone;
1130
1131       // Calculate the index of the immediate that should be range checked.
1132       unsigned immidx = 0;
1133       
1134       // Builtins that return a struct of multiple vectors have an extra
1135       // leading arg for the struct return.
1136       if (Proto[0] == '2' || Proto[0] == '3' || Proto[0] == '4')
1137         ++immidx;
1138       
1139       // Add one to the index for each argument until we reach the immediate 
1140       // to be checked.  Structs of vectors are passed as multiple arguments.
1141       for (unsigned ii = 1, ie = Proto.size(); ii != ie; ++ii) {
1142         switch (Proto[ii]) {
1143           default:  immidx += 1; break;
1144           case '2': immidx += 2; break;
1145           case '3': immidx += 3; break;
1146           case '4': immidx += 4; break;
1147           case 'i': ie = ii + 1; break;
1148         }
1149       }
1150       OS << "case ARM::BI__builtin_neon_"  << MangleName(name, TypeVec[ti], ck)
1151          << ": i = " << immidx << "; " << rangestr << "; break;\n";
1152     }
1153   }
1154   OS << "#endif\n\n";
1155 }