1 //===- NeonEmitter.cpp - Generate arm_neon.h for use with clang -*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
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.
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
20 // Additional validation code can be generated by this file when runHeader() is
21 // called, rather than the normal run() entry point. A complete set of tests
22 // for Neon intrinsics can be generated by calling the runTests() entry point.
24 //===----------------------------------------------------------------------===//
26 #include "NeonEmitter.h"
27 #include "llvm/ADT/SmallString.h"
28 #include "llvm/ADT/SmallVector.h"
29 #include "llvm/ADT/StringExtras.h"
34 /// ParseTypes - break down a string such as "fQf" into a vector of StringRefs,
35 /// which each StringRef representing a single type declared in the string.
36 /// for "fQf" we would end up with 2 StringRefs, "f", and "Qf", representing
37 /// 2xfloat and 4xfloat respectively.
38 static void ParseTypes(Record *r, std::string &s,
39 SmallVectorImpl<StringRef> &TV) {
40 const char *data = s.data();
43 for (unsigned i = 0, e = s.size(); i != e; ++i, ++len) {
44 if (data[len] == 'P' || data[len] == 'Q' || data[len] == 'U')
56 throw TGError(r->getLoc(),
57 "Unexpected letter: " + std::string(data + len, 1));
60 TV.push_back(StringRef(data, len + 1));
66 /// Widen - Convert a type code into the next wider type. char -> short,
67 /// short -> int, etc.
68 static char Widen(const char t) {
78 default: throw "unhandled type in widen!";
83 /// Narrow - Convert a type code into the next smaller type. short -> char,
84 /// float -> half float, etc.
85 static char Narrow(const char t) {
95 default: throw "unhandled type in narrow!";
100 /// For a particular StringRef, return the base type code, and whether it has
101 /// the quad-vector, polynomial, or unsigned modifiers set.
102 static char ClassifyType(StringRef ty, bool &quad, bool &poly, bool &usgn) {
106 if (ty[off] == 'Q') {
112 if (ty[off] == 'P') {
117 // remember unsigned.
118 if (ty[off] == 'U') {
123 // base type to get the type string for.
127 /// ModType - Transform a type code and its modifiers based on a mod code. The
128 /// mod code definitions may be found at the top of arm_neon.td.
129 static char ModType(const char mod, char type, bool &quad, bool &poly,
130 bool &usgn, bool &scal, bool &cnst, bool &pntr) {
203 /// TypeString - for a modifier and type, generate the name of the typedef for
204 /// that type. QUc -> uint8x8_t.
205 static std::string TypeString(const char mod, StringRef typestr) {
218 // base type to get the type string for.
219 char type = ClassifyType(typestr, quad, poly, usgn);
221 // Based on the modifying character, change the type and width if necessary.
222 type = ModType(mod, type, quad, poly, usgn, scal, cnst, pntr);
231 s += poly ? "poly8" : "int8";
234 s += quad ? "x16" : "x8";
237 s += poly ? "poly16" : "int16";
240 s += quad ? "x8" : "x4";
246 s += quad ? "x4" : "x2";
252 s += quad ? "x2" : "x1";
258 s += quad ? "x8" : "x4";
264 s += quad ? "x4" : "x2";
267 throw "unhandled type!";
278 // Append _t, finishing the type string typedef type.
290 /// BuiltinTypeString - for a modifier and type, generate the clang
291 /// BuiltinsARM.def prototype code for the function. See the top of clang's
292 /// Builtins.def for a description of the type strings.
293 static std::string BuiltinTypeString(const char mod, StringRef typestr,
294 ClassKind ck, bool ret) {
307 // base type to get the type string for.
308 char type = ClassifyType(typestr, quad, poly, usgn);
310 // Based on the modifying character, change the type and width if necessary.
311 type = ModType(mod, type, quad, poly, usgn, scal, cnst, pntr);
313 // All pointers are void* pointers. Change type to 'v' now.
319 // Treat half-float ('h') types as unsigned short ('s') types.
324 usgn = usgn | poly | ((ck == ClassI || ck == ClassW) && scal && type != 'f');
331 else if (type == 'c')
332 s.push_back('S'); // make chars explicitly signed
334 if (type == 'l') // 64-bit long
346 // Since the return value must be one type, return a vector type of the
347 // appropriate width which we will bitcast. An exception is made for
348 // returning structs of 2, 3, or 4 vectors which are returned in a sret-like
349 // fashion, storing them to a pointer arg.
351 if (mod >= '2' && mod <= '4')
352 return "vv*"; // void result with void* first argument
353 if (mod == 'f' || (ck != ClassB && type == 'f'))
354 return quad ? "V4f" : "V2f";
355 if (ck != ClassB && type == 's')
356 return quad ? "V8s" : "V4s";
357 if (ck != ClassB && type == 'i')
358 return quad ? "V4i" : "V2i";
359 if (ck != ClassB && type == 'l')
360 return quad ? "V2LLi" : "V1LLi";
362 return quad ? "V16Sc" : "V8Sc";
365 // Non-return array types are passed as individual vectors.
367 return quad ? "V16ScV16Sc" : "V8ScV8Sc";
369 return quad ? "V16ScV16ScV16Sc" : "V8ScV8ScV8Sc";
371 return quad ? "V16ScV16ScV16ScV16Sc" : "V8ScV8ScV8ScV8Sc";
373 if (mod == 'f' || (ck != ClassB && type == 'f'))
374 return quad ? "V4f" : "V2f";
375 if (ck != ClassB && type == 's')
376 return quad ? "V8s" : "V4s";
377 if (ck != ClassB && type == 'i')
378 return quad ? "V4i" : "V2i";
379 if (ck != ClassB && type == 'l')
380 return quad ? "V2LLi" : "V1LLi";
382 return quad ? "V16Sc" : "V8Sc";
385 /// MangleName - Append a type or width suffix to a base neon function name,
386 /// and insert a 'q' in the appropriate location if the operation works on
387 /// 128b rather than 64b. E.g. turn "vst2_lane" into "vst2q_lane_f32", etc.
388 static std::string MangleName(const std::string &name, StringRef typestr,
390 if (name == "vcvt_f32_f16")
396 char type = ClassifyType(typestr, quad, poly, usgn);
398 std::string s = name;
403 case ClassS: s += poly ? "_p8" : usgn ? "_u8" : "_s8"; break;
404 case ClassI: s += "_i8"; break;
405 case ClassW: s += "_8"; break;
411 case ClassS: s += poly ? "_p16" : usgn ? "_u16" : "_s16"; break;
412 case ClassI: s += "_i16"; break;
413 case ClassW: s += "_16"; break;
419 case ClassS: s += usgn ? "_u32" : "_s32"; break;
420 case ClassI: s += "_i32"; break;
421 case ClassW: s += "_32"; break;
427 case ClassS: s += usgn ? "_u64" : "_s64"; break;
428 case ClassI: s += "_i64"; break;
429 case ClassW: s += "_64"; break;
436 case ClassI: s += "_f16"; break;
437 case ClassW: s += "_16"; break;
444 case ClassI: s += "_f32"; break;
445 case ClassW: s += "_32"; break;
450 throw "unhandled type!";
456 // Insert a 'q' before the first '_' character so that it ends up before
457 // _lane or _n on vector-scalar operations.
459 size_t pos = s.find('_');
460 s = s.insert(pos, "q");
465 /// UseMacro - Examine the prototype string to determine if the intrinsic
466 /// should be defined as a preprocessor macro instead of an inline function.
467 static bool UseMacro(const std::string &proto) {
468 // If this builtin takes an immediate argument, we need to #define it rather
469 // than use a standard declaration, so that SemaChecking can range check
470 // the immediate passed by the user.
471 if (proto.find('i') != std::string::npos)
474 // Pointer arguments need to use macros to avoid hiding aligned attributes
475 // from the pointer type.
476 if (proto.find('p') != std::string::npos ||
477 proto.find('c') != std::string::npos)
483 /// MacroArgUsedDirectly - Return true if argument i for an intrinsic that is
484 /// defined as a macro should be accessed directly instead of being first
485 /// assigned to a local temporary.
486 static bool MacroArgUsedDirectly(const std::string &proto, unsigned i) {
487 return (proto[i] == 'i' || proto[i] == 'p' || proto[i] == 'c');
490 // Generate the string "(argtype a, argtype b, ...)"
491 static std::string GenArgs(const std::string &proto, StringRef typestr) {
492 bool define = UseMacro(proto);
498 for (unsigned i = 1, e = proto.size(); i != e; ++i, ++arg) {
500 // Some macro arguments are used directly instead of being assigned
501 // to local temporaries; prepend an underscore prefix to make their
502 // names consistent with the local temporaries.
503 if (MacroArgUsedDirectly(proto, i))
506 s += TypeString(proto[i], typestr) + " __";
517 // Macro arguments are not type-checked like inline function arguments, so
518 // assign them to local temporaries to get the right type checking.
519 static std::string GenMacroLocals(const std::string &proto, StringRef typestr) {
522 bool generatedLocal = false;
524 for (unsigned i = 1, e = proto.size(); i != e; ++i, ++arg) {
525 // Do not create a temporary for an immediate argument.
526 // That would defeat the whole point of using a macro!
529 generatedLocal = true;
531 // For other (non-immediate) arguments that are used directly, a local
532 // temporary is still needed to get the correct type checking, even though
533 // that temporary is not used for anything.
534 if (MacroArgUsedDirectly(proto, i)) {
535 s += TypeString(proto[i], typestr) + " __";
545 s += TypeString(proto[i], typestr) + " __";
557 // Use the vmovl builtin to sign-extend or zero-extend a vector.
558 static std::string Extend(StringRef typestr, const std::string &a) {
560 s = MangleName("vmovl", typestr, ClassS);
565 static std::string Duplicate(unsigned nElts, StringRef typestr,
566 const std::string &a) {
569 s = "(" + TypeString('d', typestr) + "){ ";
570 for (unsigned i = 0; i != nElts; ++i) {
580 static std::string SplatLane(unsigned nElts, const std::string &vec,
581 const std::string &lane) {
582 std::string s = "__builtin_shufflevector(" + vec + ", " + vec;
583 for (unsigned i = 0; i < nElts; ++i)
589 static unsigned GetNumElements(StringRef typestr, bool &quad) {
592 char type = ClassifyType(typestr, quad, dummy, dummy);
595 case 'c': nElts = 8; break;
596 case 's': nElts = 4; break;
597 case 'i': nElts = 2; break;
598 case 'l': nElts = 1; break;
599 case 'h': nElts = 4; break;
600 case 'f': nElts = 2; break;
602 throw "unhandled type!";
605 if (quad) nElts <<= 1;
609 // Generate the definition for this intrinsic, e.g. "a + b" for OpAdd.
610 static std::string GenOpString(OpKind op, const std::string &proto,
613 unsigned nElts = GetNumElements(typestr, quad);
614 bool define = UseMacro(proto);
616 std::string ts = TypeString(proto[0], typestr);
627 s += Extend(typestr, "__a") + " + " + Extend(typestr, "__b") + ";";
630 s += "__a + " + Extend(typestr, "__b") + ";";
636 s += Extend(typestr, "__a") + " - " + Extend(typestr, "__b") + ";";
639 s += "__a - " + Extend(typestr, "__b") + ";";
642 s += "__a * " + Duplicate(nElts, typestr, "__b") + ";";
645 s += "__a * " + SplatLane(nElts, "__b", "__c") + ";";
651 s += MangleName("vmull", typestr, ClassS) + "(__a, " +
652 SplatLane(nElts, "__b", "__c") + ");";
655 s += "__a + (__b * " + Duplicate(nElts, typestr, "__c") + ");";
658 s += "__a + (__b * " + SplatLane(nElts, "__c", "__d") + ");";
661 s += "__a + (__b * __c);";
664 s += "__a + " + MangleName("vmull", typestr, ClassS) + "(__b, " +
665 Duplicate(nElts, typestr, "__c") + ");";
668 s += "__a + " + MangleName("vmull", typestr, ClassS) + "(__b, " +
669 SplatLane(nElts, "__c", "__d") + ");";
672 s += "__a + " + MangleName("vmull", typestr, ClassS) + "(__b, __c);";
675 s += "__a - (__b * " + Duplicate(nElts, typestr, "__c") + ");";
678 s += "__a - (__b * " + SplatLane(nElts, "__c", "__d") + ");";
681 s += "__a - (__b * __c);";
684 s += "__a - " + MangleName("vmull", typestr, ClassS) + "(__b, " +
685 Duplicate(nElts, typestr, "__c") + ");";
688 s += "__a - " + MangleName("vmull", typestr, ClassS) + "(__b, " +
689 SplatLane(nElts, "__c", "__d") + ");";
692 s += "__a - " + MangleName("vmull", typestr, ClassS) + "(__b, __c);";
695 s += MangleName("vqdmull", typestr, ClassS) + "(__a, " +
696 SplatLane(nElts, "__b", "__c") + ");";
699 s += MangleName("vqdmlal", typestr, ClassS) + "(__a, __b, " +
700 SplatLane(nElts, "__c", "__d") + ");";
703 s += MangleName("vqdmlsl", typestr, ClassS) + "(__a, __b, " +
704 SplatLane(nElts, "__c", "__d") + ");";
707 s += MangleName("vqdmulh", typestr, ClassS) + "(__a, " +
708 SplatLane(nElts, "__b", "__c") + ");";
711 s += MangleName("vqrdmulh", typestr, ClassS) + "(__a, " +
712 SplatLane(nElts, "__b", "__c") + ");";
715 s += "(" + ts + ")(__a == __b);";
718 s += "(" + ts + ")(__a >= __b);";
721 s += "(" + ts + ")(__a <= __b);";
724 s += "(" + ts + ")(__a > __b);";
727 s += "(" + ts + ")(__a < __b);";
751 s += "(" + ts + ")__a;";
754 s += "(" + ts + ")__builtin_shufflevector((int64x1_t)__a";
755 s += ", (int64x1_t)__b, 0, 1);";
759 ")__builtin_shufflevector((int64x2_t)__a, (int64x2_t)__a, 1);";
763 ")__builtin_shufflevector((int64x2_t)__a, (int64x2_t)__a, 0);";
766 s += Duplicate(nElts, typestr, "__a") + ";";
769 s += SplatLane(nElts, "__a", "__b") + ";";
772 // ((0 & 1) | (~0 & 2))
774 ts = TypeString(proto[1], typestr);
775 s += "((__a & (" + ts + ")__b) | ";
776 s += "(~__a & (" + ts + ")__c));";
779 s += "__builtin_shufflevector(__a, __a";
780 for (unsigned i = 2; i <= nElts; i += 2)
781 for (unsigned j = 0; j != 2; ++j)
782 s += ", " + utostr(i - j - 1);
786 unsigned WordElts = nElts >> (1 + (int)quad);
787 s += "__builtin_shufflevector(__a, __a";
788 for (unsigned i = WordElts; i <= nElts; i += WordElts)
789 for (unsigned j = 0; j != WordElts; ++j)
790 s += ", " + utostr(i - j - 1);
795 unsigned DblWordElts = nElts >> (int)quad;
796 s += "__builtin_shufflevector(__a, __a";
797 for (unsigned i = DblWordElts; i <= nElts; i += DblWordElts)
798 for (unsigned j = 0; j != DblWordElts; ++j)
799 s += ", " + utostr(i - j - 1);
804 std::string abd = MangleName("vabd", typestr, ClassS) + "(__a, __b)";
805 if (typestr[0] != 'U') {
806 // vabd results are always unsigned and must be zero-extended.
807 std::string utype = "U" + typestr.str();
808 s += "(" + TypeString(proto[0], typestr) + ")";
809 abd = "(" + TypeString('d', utype) + ")" + abd;
810 s += Extend(utype, abd) + ";";
812 s += Extend(typestr, abd) + ";";
817 s += "__a + " + MangleName("vabd", typestr, ClassS) + "(__b, __c);";
821 std::string abd = MangleName("vabd", typestr, ClassS) + "(__b, __c)";
822 if (typestr[0] != 'U') {
823 // vabd results are always unsigned and must be zero-extended.
824 std::string utype = "U" + typestr.str();
825 s += "(" + TypeString(proto[0], typestr) + ")";
826 abd = "(" + TypeString('d', utype) + ")" + abd;
827 s += Extend(utype, abd) + ";";
829 s += Extend(typestr, abd) + ";";
834 throw "unknown OpKind!";
840 static unsigned GetNeonEnum(const std::string &proto, StringRef typestr) {
841 unsigned mod = proto[0];
844 if (mod == 'v' || mod == 'f')
854 // Base type to get the type string for.
855 char type = ClassifyType(typestr, quad, poly, usgn);
857 // Based on the modifying character, change the type and width if necessary.
858 type = ModType(mod, type, quad, poly, usgn, scal, cnst, pntr);
862 if (quad && proto[1] != 'g')
885 throw "unhandled type!";
891 // Generate the definition for this intrinsic, e.g. __builtin_neon_cls(a)
892 static std::string GenBuiltin(const std::string &name, const std::string &proto,
893 StringRef typestr, ClassKind ck) {
896 // If this builtin returns a struct 2, 3, or 4 vectors, pass it as an implicit
897 // sret-like argument.
898 bool sret = (proto[0] >= '2' && proto[0] <= '4');
900 bool define = UseMacro(proto);
902 // Check if the prototype has a scalar operand with the type of the vector
903 // elements. If not, bitcasting the args will take care of arg checking.
904 // The actual signedness etc. will be taken care of with special enums.
905 if (proto.find('s') == std::string::npos)
908 if (proto[0] != 'v') {
909 std::string ts = TypeString(proto[0], typestr);
919 s += "return (" + ts + ")";
923 bool splat = proto.find('a') != std::string::npos;
925 s += "__builtin_neon_";
927 // Call the non-splat builtin: chop off the "_n" suffix from the name.
928 std::string vname(name, 0, name.size()-2);
929 s += MangleName(vname, typestr, ck);
931 s += MangleName(name, typestr, ck);
935 // Pass the address of the return variable as the first argument to sret-like
941 for (unsigned i = 1, e = proto.size(); i != e; ++i, ++arg) {
942 std::string args = std::string(&arg, 1);
944 // Use the local temporaries instead of the macro arguments.
947 bool argQuad = false;
948 bool argPoly = false;
949 bool argUsgn = false;
950 bool argScalar = false;
952 char argType = ClassifyType(typestr, argQuad, argPoly, argUsgn);
953 argType = ModType(proto[i], argType, argQuad, argPoly, argUsgn, argScalar,
956 // Handle multiple-vector values specially, emitting each subvector as an
957 // argument to the __builtin.
958 if (proto[i] >= '2' && proto[i] <= '4') {
959 // Check if an explicit cast is needed.
960 if (argType != 'c' || argPoly || argUsgn)
961 args = (argQuad ? "(int8x16_t)" : "(int8x8_t)") + args;
963 for (unsigned vi = 0, ve = proto[i] - '0'; vi != ve; ++vi) {
964 s += args + ".val[" + utostr(vi) + "]";
974 if (splat && (i + 1) == e)
975 args = Duplicate(GetNumElements(typestr, argQuad), typestr, args);
977 // Check if an explicit cast is needed.
978 if ((splat || !argScalar) &&
979 ((ck == ClassB && argType != 'c') || argPoly || argUsgn)) {
980 std::string argTypeStr = "c";
982 argTypeStr = argType;
984 argTypeStr = "Q" + argTypeStr;
985 args = "(" + TypeString('d', argTypeStr) + ")" + args;
993 // Extra constant integer to hold type class enum for this function, e.g. s8
995 s += ", " + utostr(GetNeonEnum(proto, typestr));
999 if (proto[0] != 'v' && sret) {
1008 static std::string GenBuiltinDef(const std::string &name,
1009 const std::string &proto,
1010 StringRef typestr, ClassKind ck) {
1011 std::string s("BUILTIN(__builtin_neon_");
1013 // If all types are the same size, bitcasting the args will take care
1014 // of arg checking. The actual signedness etc. will be taken care of with
1016 if (proto.find('s') == std::string::npos)
1019 s += MangleName(name, typestr, ck);
1022 for (unsigned i = 0, e = proto.size(); i != e; ++i)
1023 s += BuiltinTypeString(proto[i], typestr, ck, i == 0);
1025 // Extra constant integer to hold type class enum for this function, e.g. s8
1033 static std::string GenIntrinsic(const std::string &name,
1034 const std::string &proto,
1035 StringRef outTypeStr, StringRef inTypeStr,
1036 OpKind kind, ClassKind classKind) {
1037 assert(!proto.empty() && "");
1038 bool define = UseMacro(proto);
1041 // static always inline + return type
1045 s += "__ai " + TypeString(proto[0], outTypeStr) + " ";
1047 // Function name with type suffix
1048 std::string mangledName = MangleName(name, outTypeStr, ClassS);
1049 if (outTypeStr != inTypeStr) {
1050 // If the input type is different (e.g., for vreinterpret), append a suffix
1051 // for the input type. String off a "Q" (quad) prefix so that MangleName
1052 // does not insert another "q" in the name.
1053 unsigned typeStrOff = (inTypeStr[0] == 'Q' ? 1 : 0);
1054 StringRef inTypeNoQuad = inTypeStr.substr(typeStrOff);
1055 mangledName = MangleName(mangledName, inTypeNoQuad, ClassS);
1059 // Function arguments
1060 s += GenArgs(proto, inTypeStr);
1064 s += " __extension__ ({ \\\n ";
1065 s += GenMacroLocals(proto, inTypeStr);
1071 s += GenOpString(kind, proto, outTypeStr);
1073 s += GenBuiltin(name, proto, outTypeStr, classKind);
1082 /// run - Read the records in arm_neon.td and output arm_neon.h. arm_neon.h
1083 /// is comprised of type definitions and function declarations.
1084 void NeonEmitter::run(raw_ostream &OS) {
1086 "/*===---- arm_neon.h - ARM Neon intrinsics ------------------------------"
1089 " * Permission is hereby granted, free of charge, to any person obtaining "
1091 " * of this software and associated documentation files (the \"Software\"),"
1093 " * in the Software without restriction, including without limitation the "
1095 " * to use, copy, modify, merge, publish, distribute, sublicense, "
1097 " * copies of the Software, and to permit persons to whom the Software is\n"
1098 " * furnished to do so, subject to the following conditions:\n"
1100 " * The above copyright notice and this permission notice shall be "
1102 " * all copies or substantial portions of the Software.\n"
1104 " * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, "
1106 " * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF "
1107 "MERCHANTABILITY,\n"
1108 " * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT "
1110 " * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR "
1112 " * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, "
1114 " * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER "
1116 " * THE SOFTWARE.\n"
1118 " *===--------------------------------------------------------------------"
1122 OS << "#ifndef __ARM_NEON_H\n";
1123 OS << "#define __ARM_NEON_H\n\n";
1125 OS << "#ifndef __ARM_NEON__\n";
1126 OS << "#error \"NEON support not enabled\"\n";
1129 OS << "#include <stdint.h>\n\n";
1131 // Emit NEON-specific scalar typedefs.
1132 OS << "typedef float float32_t;\n";
1133 OS << "typedef int8_t poly8_t;\n";
1134 OS << "typedef int16_t poly16_t;\n";
1135 OS << "typedef uint16_t float16_t;\n";
1137 // Emit Neon vector typedefs.
1138 std::string TypedefTypes("cQcsQsiQilQlUcQUcUsQUsUiQUiUlQUlhQhfQfPcQPcPsQPs");
1139 SmallVector<StringRef, 24> TDTypeVec;
1140 ParseTypes(0, TypedefTypes, TDTypeVec);
1142 // Emit vector typedefs.
1143 for (unsigned i = 0, e = TDTypeVec.size(); i != e; ++i) {
1144 bool dummy, quad = false, poly = false;
1145 (void) ClassifyType(TDTypeVec[i], quad, poly, dummy);
1147 OS << "typedef __attribute__((neon_polyvector_type(";
1149 OS << "typedef __attribute__((neon_vector_type(";
1151 unsigned nElts = GetNumElements(TDTypeVec[i], quad);
1152 OS << utostr(nElts) << "))) ";
1156 OS << TypeString('s', TDTypeVec[i]);
1157 OS << " " << TypeString('d', TDTypeVec[i]) << ";\n";
1161 // Emit struct typedefs.
1162 for (unsigned vi = 2; vi != 5; ++vi) {
1163 for (unsigned i = 0, e = TDTypeVec.size(); i != e; ++i) {
1164 std::string ts = TypeString('d', TDTypeVec[i]);
1165 std::string vs = TypeString('0' + vi, TDTypeVec[i]);
1166 OS << "typedef struct " << vs << " {\n";
1167 OS << " " << ts << " val";
1168 OS << "[" << utostr(vi) << "]";
1170 OS << vs << ";\n\n";
1174 OS << "#define __ai static __attribute__((__always_inline__))\n\n";
1176 std::vector<Record*> RV = Records.getAllDerivedDefinitions("Inst");
1178 // Emit vmovl, vmull and vabd intrinsics first so they can be used by other
1179 // intrinsics. (Some of the saturating multiply instructions are also
1180 // used to implement the corresponding "_lane" variants, but tablegen
1181 // sorts the records into alphabetical order so that the "_lane" variants
1182 // come after the intrinsics they use.)
1183 emitIntrinsic(OS, Records.getDef("VMOVL"));
1184 emitIntrinsic(OS, Records.getDef("VMULL"));
1185 emitIntrinsic(OS, Records.getDef("VABD"));
1187 for (unsigned i = 0, e = RV.size(); i != e; ++i) {
1189 if (R->getName() != "VMOVL" &&
1190 R->getName() != "VMULL" &&
1191 R->getName() != "VABD")
1192 emitIntrinsic(OS, R);
1195 OS << "#undef __ai\n\n";
1196 OS << "#endif /* __ARM_NEON_H */\n";
1199 /// emitIntrinsic - Write out the arm_neon.h header file definitions for the
1200 /// intrinsics specified by record R.
1201 void NeonEmitter::emitIntrinsic(raw_ostream &OS, Record *R) {
1202 std::string name = R->getValueAsString("Name");
1203 std::string Proto = R->getValueAsString("Prototype");
1204 std::string Types = R->getValueAsString("Types");
1206 SmallVector<StringRef, 16> TypeVec;
1207 ParseTypes(R, Types, TypeVec);
1209 OpKind kind = OpMap[R->getValueAsDef("Operand")->getName()];
1211 ClassKind classKind = ClassNone;
1212 if (R->getSuperClasses().size() >= 2)
1213 classKind = ClassMap[R->getSuperClasses()[1]];
1214 if (classKind == ClassNone && kind == OpNone)
1215 throw TGError(R->getLoc(), "Builtin has no class kind");
1217 for (unsigned ti = 0, te = TypeVec.size(); ti != te; ++ti) {
1218 if (kind == OpReinterpret) {
1219 bool outQuad = false;
1221 (void)ClassifyType(TypeVec[ti], outQuad, dummy, dummy);
1222 for (unsigned srcti = 0, srcte = TypeVec.size();
1223 srcti != srcte; ++srcti) {
1224 bool inQuad = false;
1225 (void)ClassifyType(TypeVec[srcti], inQuad, dummy, dummy);
1226 if (srcti == ti || inQuad != outQuad)
1228 OS << GenIntrinsic(name, Proto, TypeVec[ti], TypeVec[srcti],
1232 OS << GenIntrinsic(name, Proto, TypeVec[ti], TypeVec[ti],
1239 static unsigned RangeFromType(const char mod, StringRef typestr) {
1240 // base type to get the type string for.
1241 bool quad = false, dummy = false;
1242 char type = ClassifyType(typestr, quad, dummy, dummy);
1243 type = ModType(mod, type, quad, dummy, dummy, dummy, dummy, dummy);
1247 return (8 << (int)quad) - 1;
1250 return (4 << (int)quad) - 1;
1253 return (2 << (int)quad) - 1;
1255 return (1 << (int)quad) - 1;
1257 throw "unhandled type!";
1260 assert(0 && "unreachable");
1264 /// runHeader - Emit a file with sections defining:
1265 /// 1. the NEON section of BuiltinsARM.def.
1266 /// 2. the SemaChecking code for the type overload checking.
1267 /// 3. the SemaChecking code for validation of intrinsic immedate arguments.
1268 void NeonEmitter::runHeader(raw_ostream &OS) {
1269 std::vector<Record*> RV = Records.getAllDerivedDefinitions("Inst");
1271 StringMap<OpKind> EmittedMap;
1273 // Generate BuiltinsARM.def for NEON
1274 OS << "#ifdef GET_NEON_BUILTINS\n";
1275 for (unsigned i = 0, e = RV.size(); i != e; ++i) {
1277 OpKind k = OpMap[R->getValueAsDef("Operand")->getName()];
1281 std::string Proto = R->getValueAsString("Prototype");
1283 // Functions with 'a' (the splat code) in the type prototype should not get
1284 // their own builtin as they use the non-splat variant.
1285 if (Proto.find('a') != std::string::npos)
1288 std::string Types = R->getValueAsString("Types");
1289 SmallVector<StringRef, 16> TypeVec;
1290 ParseTypes(R, Types, TypeVec);
1292 if (R->getSuperClasses().size() < 2)
1293 throw TGError(R->getLoc(), "Builtin has no class kind");
1295 std::string name = R->getValueAsString("Name");
1296 ClassKind ck = ClassMap[R->getSuperClasses()[1]];
1298 for (unsigned ti = 0, te = TypeVec.size(); ti != te; ++ti) {
1299 // Generate the BuiltinsARM.def declaration for this builtin, ensuring
1300 // that each unique BUILTIN() macro appears only once in the output
1302 std::string bd = GenBuiltinDef(name, Proto, TypeVec[ti], ck);
1303 if (EmittedMap.count(bd))
1306 EmittedMap[bd] = OpNone;
1312 // Generate the overloaded type checking code for SemaChecking.cpp
1313 OS << "#ifdef GET_NEON_OVERLOAD_CHECK\n";
1314 for (unsigned i = 0, e = RV.size(); i != e; ++i) {
1316 OpKind k = OpMap[R->getValueAsDef("Operand")->getName()];
1320 std::string Proto = R->getValueAsString("Prototype");
1321 std::string Types = R->getValueAsString("Types");
1322 std::string name = R->getValueAsString("Name");
1324 // Functions with 'a' (the splat code) in the type prototype should not get
1325 // their own builtin as they use the non-splat variant.
1326 if (Proto.find('a') != std::string::npos)
1329 // Functions which have a scalar argument cannot be overloaded, no need to
1330 // check them if we are emitting the type checking code.
1331 if (Proto.find('s') != std::string::npos)
1334 SmallVector<StringRef, 16> TypeVec;
1335 ParseTypes(R, Types, TypeVec);
1337 if (R->getSuperClasses().size() < 2)
1338 throw TGError(R->getLoc(), "Builtin has no class kind");
1340 int si = -1, qi = -1;
1341 unsigned mask = 0, qmask = 0;
1342 for (unsigned ti = 0, te = TypeVec.size(); ti != te; ++ti) {
1343 // Generate the switch case(s) for this builtin for the type validation.
1344 bool quad = false, poly = false, usgn = false;
1345 (void) ClassifyType(TypeVec[ti], quad, poly, usgn);
1349 qmask |= 1 << GetNeonEnum(Proto, TypeVec[ti]);
1352 mask |= 1 << GetNeonEnum(Proto, TypeVec[ti]);
1356 OS << "case ARM::BI__builtin_neon_"
1357 << MangleName(name, TypeVec[si], ClassB)
1358 << ": mask = " << "0x" << utohexstr(mask) << "; break;\n";
1360 OS << "case ARM::BI__builtin_neon_"
1361 << MangleName(name, TypeVec[qi], ClassB)
1362 << ": mask = " << "0x" << utohexstr(qmask) << "; break;\n";
1366 // Generate the intrinsic range checking code for shift/lane immediates.
1367 OS << "#ifdef GET_NEON_IMMEDIATE_CHECK\n";
1368 for (unsigned i = 0, e = RV.size(); i != e; ++i) {
1371 OpKind k = OpMap[R->getValueAsDef("Operand")->getName()];
1375 std::string name = R->getValueAsString("Name");
1376 std::string Proto = R->getValueAsString("Prototype");
1377 std::string Types = R->getValueAsString("Types");
1379 // Functions with 'a' (the splat code) in the type prototype should not get
1380 // their own builtin as they use the non-splat variant.
1381 if (Proto.find('a') != std::string::npos)
1384 // Functions which do not have an immediate do not need to have range
1385 // checking code emitted.
1386 size_t immPos = Proto.find('i');
1387 if (immPos == std::string::npos)
1390 SmallVector<StringRef, 16> TypeVec;
1391 ParseTypes(R, Types, TypeVec);
1393 if (R->getSuperClasses().size() < 2)
1394 throw TGError(R->getLoc(), "Builtin has no class kind");
1396 ClassKind ck = ClassMap[R->getSuperClasses()[1]];
1398 for (unsigned ti = 0, te = TypeVec.size(); ti != te; ++ti) {
1399 std::string namestr, shiftstr, rangestr;
1401 if (R->getValueAsBit("isVCVT_N")) {
1402 // VCVT between floating- and fixed-point values takes an immediate
1403 // in the range 1 to 32.
1405 rangestr = "l = 1; u = 31"; // upper bound = l + u
1406 } else if (Proto.find('s') == std::string::npos) {
1407 // Builtins which are overloaded by type will need to have their upper
1408 // bound computed at Sema time based on the type constant.
1410 if (R->getValueAsBit("isShift")) {
1411 shiftstr = ", true";
1413 // Right shifts have an 'r' in the name, left shifts do not.
1414 if (name.find('r') != std::string::npos)
1415 rangestr = "l = 1; ";
1417 rangestr += "u = RFT(TV" + shiftstr + ")";
1419 // The immediate generally refers to a lane in the preceding argument.
1420 assert(immPos > 0 && "unexpected immediate operand");
1421 rangestr = "u = " + utostr(RangeFromType(Proto[immPos-1], TypeVec[ti]));
1423 // Make sure cases appear only once by uniquing them in a string map.
1424 namestr = MangleName(name, TypeVec[ti], ck);
1425 if (EmittedMap.count(namestr))
1427 EmittedMap[namestr] = OpNone;
1429 // Calculate the index of the immediate that should be range checked.
1430 unsigned immidx = 0;
1432 // Builtins that return a struct of multiple vectors have an extra
1433 // leading arg for the struct return.
1434 if (Proto[0] >= '2' && Proto[0] <= '4')
1437 // Add one to the index for each argument until we reach the immediate
1438 // to be checked. Structs of vectors are passed as multiple arguments.
1439 for (unsigned ii = 1, ie = Proto.size(); ii != ie; ++ii) {
1440 switch (Proto[ii]) {
1441 default: immidx += 1; break;
1442 case '2': immidx += 2; break;
1443 case '3': immidx += 3; break;
1444 case '4': immidx += 4; break;
1445 case 'i': ie = ii + 1; break;
1448 OS << "case ARM::BI__builtin_neon_" << MangleName(name, TypeVec[ti], ck)
1449 << ": i = " << immidx << "; " << rangestr << "; break;\n";
1455 /// GenTest - Write out a test for the intrinsic specified by the name and
1456 /// type strings, including the embedded patterns for FileCheck to match.
1457 static std::string GenTest(const std::string &name,
1458 const std::string &proto,
1459 StringRef outTypeStr, StringRef inTypeStr,
1461 assert(!proto.empty() && "");
1464 // Function name with type suffix
1465 std::string mangledName = MangleName(name, outTypeStr, ClassS);
1466 if (outTypeStr != inTypeStr) {
1467 // If the input type is different (e.g., for vreinterpret), append a suffix
1468 // for the input type. String off a "Q" (quad) prefix so that MangleName
1469 // does not insert another "q" in the name.
1470 unsigned typeStrOff = (inTypeStr[0] == 'Q' ? 1 : 0);
1471 StringRef inTypeNoQuad = inTypeStr.substr(typeStrOff);
1472 mangledName = MangleName(mangledName, inTypeNoQuad, ClassS);
1475 // Emit the FileCheck patterns.
1476 s += "// CHECK: test_" + mangledName + "\n";
1477 // s += "// CHECK: \n"; // FIXME: + expected instruction opcode.
1479 // Emit the start of the test function.
1480 s += TypeString(proto[0], outTypeStr) + " test_" + mangledName + "(";
1483 for (unsigned i = 1, e = proto.size(); i != e; ++i, ++arg) {
1484 // Do not create arguments for values that must be immediate constants.
1485 if (proto[i] == 'i')
1487 s += comma + TypeString(proto[i], inTypeStr) + " ";
1493 if (proto[0] != 'v')
1495 s += mangledName + "(";
1497 for (unsigned i = 1, e = proto.size(); i != e; ++i, ++arg) {
1498 if (proto[i] == 'i') {
1499 // For immediate operands, test the maximum value.
1503 // The immediate generally refers to a lane in the preceding argument.
1504 s += utostr(RangeFromType(proto[i-1], inTypeStr));
1515 /// runTests - Write out a complete set of tests for all of the Neon
1517 void NeonEmitter::runTests(raw_ostream &OS) {
1519 "// RUN: %clang_cc1 -triple thumbv7-apple-darwin \\\n"
1520 "// RUN: -target-cpu cortex-a9 -ffreestanding -S -o - %s | FileCheck %s\n"
1522 "#include <arm_neon.h>\n"
1525 std::vector<Record*> RV = Records.getAllDerivedDefinitions("Inst");
1526 for (unsigned i = 0, e = RV.size(); i != e; ++i) {
1528 std::string name = R->getValueAsString("Name");
1529 std::string Proto = R->getValueAsString("Prototype");
1530 std::string Types = R->getValueAsString("Types");
1531 bool isShift = R->getValueAsBit("isShift");
1533 SmallVector<StringRef, 16> TypeVec;
1534 ParseTypes(R, Types, TypeVec);
1536 OpKind kind = OpMap[R->getValueAsDef("Operand")->getName()];
1537 for (unsigned ti = 0, te = TypeVec.size(); ti != te; ++ti) {
1538 if (kind == OpReinterpret) {
1539 bool outQuad = false;
1541 (void)ClassifyType(TypeVec[ti], outQuad, dummy, dummy);
1542 for (unsigned srcti = 0, srcte = TypeVec.size();
1543 srcti != srcte; ++srcti) {
1544 bool inQuad = false;
1545 (void)ClassifyType(TypeVec[srcti], inQuad, dummy, dummy);
1546 if (srcti == ti || inQuad != outQuad)
1548 OS << GenTest(name, Proto, TypeVec[ti], TypeVec[srcti], isShift);
1551 OS << GenTest(name, Proto, TypeVec[ti], TypeVec[ti], isShift);