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.
23 // See also the documentation in include/clang/Basic/arm_neon.td.
25 //===----------------------------------------------------------------------===//
27 #include "llvm/ADT/DenseMap.h"
28 #include "llvm/ADT/STLExtras.h"
29 #include "llvm/ADT/SmallString.h"
30 #include "llvm/ADT/SmallVector.h"
31 #include "llvm/ADT/StringExtras.h"
32 #include "llvm/ADT/StringMap.h"
33 #include "llvm/Support/ErrorHandling.h"
34 #include "llvm/TableGen/Error.h"
35 #include "llvm/TableGen/Record.h"
36 #include "llvm/TableGen/SetTheory.h"
37 #include "llvm/TableGen/TableGenBackend.h"
48 // While globals are generally bad, this one allows us to perform assertions
49 // liberally and somehow still trace them back to the def they indirectly
51 static Record *CurrentRecord = nullptr;
52 static void assert_with_loc(bool Assertion, const std::string &Str) {
55 PrintFatalError(CurrentRecord->getLoc(), Str);
63 ClassI, // generic integer instruction, e.g., "i8" suffix
64 ClassS, // signed/unsigned/poly, e.g., "s8", "u8" or "p8" suffix
65 ClassW, // width-specific instruction, e.g., "8" suffix
66 ClassB, // bitcast arguments with enum argument to specify type
67 ClassL, // Logical instructions which are op instructions
68 // but we need to not emit any suffix for in our
70 ClassNoTest // Instructions which we do not test since they are
71 // not TRUE instructions.
74 /// NeonTypeFlags - Flags to identify the types for overloaded Neon
75 /// builtins. These must be kept in sync with the flags in
76 /// include/clang/Basic/TargetBuiltins.h.
77 namespace NeonTypeFlags {
78 enum { EltTypeMask = 0xf, UnsignedFlag = 0x10, QuadFlag = 0x20 };
100 //===----------------------------------------------------------------------===//
102 //===----------------------------------------------------------------------===//
104 /// A TypeSpec is just a simple wrapper around a string, but gets its own type
105 /// for strong typing purposes.
107 /// A TypeSpec can be used to create a type.
108 class TypeSpec : public std::string {
110 static std::vector<TypeSpec> fromTypeSpecs(StringRef Str) {
111 std::vector<TypeSpec> Ret;
113 for (char I : Str.str()) {
116 Ret.push_back(TypeSpec(Acc));
126 //===----------------------------------------------------------------------===//
128 //===----------------------------------------------------------------------===//
130 /// A Type. Not much more to say here.
135 bool Float, Signed, Immediate, Void, Poly, Constant, Pointer;
136 // ScalarForMangling and NoManglingQ are really not suited to live here as
137 // they are not related to the type. But they live in the TypeSpec (not the
138 // prototype), so this is really the only place to store them.
139 bool ScalarForMangling, NoManglingQ;
140 unsigned Bitwidth, ElementBitwidth, NumVectors;
144 : Float(false), Signed(false), Immediate(false), Void(true), Poly(false),
145 Constant(false), Pointer(false), ScalarForMangling(false),
146 NoManglingQ(false), Bitwidth(0), ElementBitwidth(0), NumVectors(0) {}
148 Type(TypeSpec TS, char CharMod)
149 : TS(TS), Float(false), Signed(false), Immediate(false), Void(false),
150 Poly(false), Constant(false), Pointer(false), ScalarForMangling(false),
151 NoManglingQ(false), Bitwidth(0), ElementBitwidth(0), NumVectors(0) {
152 applyModifier(CharMod);
155 /// Returns a type representing "void".
156 static Type getVoid() { return Type(); }
158 bool operator==(const Type &Other) const { return str() == Other.str(); }
159 bool operator!=(const Type &Other) const { return !operator==(Other); }
164 bool isScalarForMangling() const { return ScalarForMangling; }
165 bool noManglingQ() const { return NoManglingQ; }
167 bool isPointer() const { return Pointer; }
168 bool isFloating() const { return Float; }
169 bool isInteger() const { return !Float && !Poly; }
170 bool isSigned() const { return Signed; }
171 bool isImmediate() const { return Immediate; }
172 bool isScalar() const { return NumVectors == 0; }
173 bool isVector() const { return NumVectors > 0; }
174 bool isFloat() const { return Float && ElementBitwidth == 32; }
175 bool isDouble() const { return Float && ElementBitwidth == 64; }
176 bool isHalf() const { return Float && ElementBitwidth == 16; }
177 bool isPoly() const { return Poly; }
178 bool isChar() const { return ElementBitwidth == 8; }
179 bool isShort() const { return !Float && ElementBitwidth == 16; }
180 bool isInt() const { return !Float && ElementBitwidth == 32; }
181 bool isLong() const { return !Float && ElementBitwidth == 64; }
182 bool isVoid() const { return Void; }
183 unsigned getNumElements() const { return Bitwidth / ElementBitwidth; }
184 unsigned getSizeInBits() const { return Bitwidth; }
185 unsigned getElementSizeInBits() const { return ElementBitwidth; }
186 unsigned getNumVectors() const { return NumVectors; }
191 void makeUnsigned() { Signed = false; }
192 void makeSigned() { Signed = true; }
193 void makeInteger(unsigned ElemWidth, bool Sign) {
198 ElementBitwidth = ElemWidth;
200 void makeImmediate(unsigned ElemWidth) {
205 ElementBitwidth = ElemWidth;
208 Bitwidth = ElementBitwidth;
211 void makeOneVector() {
216 assert_with_loc(Bitwidth != 128, "Can't get bigger than 128!");
220 assert_with_loc(Bitwidth != 64, "Can't get smaller than 64!");
224 /// Return the C string representation of a type, which is the typename
225 /// defined in stdint.h or arm_neon.h.
226 std::string str() const;
228 /// Return the string representation of a type, which is an encoded
229 /// string for passing to the BUILTIN() macro in Builtins.def.
230 std::string builtin_str() const;
232 /// Return the value in NeonTypeFlags for this type.
233 unsigned getNeonEnum() const;
235 /// Parse a type from a stdint.h or arm_neon.h typedef name,
236 /// for example uint32x2_t or int64_t.
237 static Type fromTypedefName(StringRef Name);
240 /// Creates the type based on the typespec string in TS.
241 /// Sets "Quad" to true if the "Q" or "H" modifiers were
242 /// seen. This is needed by applyModifier as some modifiers
243 /// only take effect if the type size was changed by "Q" or "H".
244 void applyTypespec(bool &Quad);
245 /// Applies a prototype modifier to the type.
246 void applyModifier(char Mod);
249 //===----------------------------------------------------------------------===//
251 //===----------------------------------------------------------------------===//
253 /// A variable is a simple class that just has a type and a name.
259 Variable() : T(Type::getVoid()), N("") {}
260 Variable(Type T, std::string N) : T(T), N(N) {}
262 Type getType() const { return T; }
263 std::string getName() const { return "__" + N; }
266 //===----------------------------------------------------------------------===//
268 //===----------------------------------------------------------------------===//
270 /// The main grunt class. This represents an instantiation of an intrinsic with
271 /// a particular typespec and prototype.
273 friend class DagEmitter;
275 /// The Record this intrinsic was created from.
277 /// The unmangled name and prototype.
278 std::string Name, Proto;
279 /// The input and output typespecs. InTS == OutTS except when
280 /// CartesianProductOfTypes is 1 - this is the case for vreinterpret.
281 TypeSpec OutTS, InTS;
282 /// The base class kind. Most intrinsics use ClassS, which has full type
283 /// info for integers (s32/u32). Some use ClassI, which doesn't care about
284 /// signedness (i32), while some (ClassB) have no type at all, only a width
287 /// The list of DAGs for the body. May be empty, in which case we should
288 /// emit a builtin call.
290 /// The architectural #ifdef guard.
292 /// Set if the Unvailable bit is 1. This means we don't generate a body,
293 /// just an "unavailable" attribute on a declaration.
295 /// Is this intrinsic safe for big-endian? or does it need its arguments
299 /// The types of return value [0] and parameters [1..].
300 std::vector<Type> Types;
301 /// The local variables defined.
302 std::map<std::string, Variable> Variables;
303 /// NeededEarly - set if any other intrinsic depends on this intrinsic.
305 /// UseMacro - set if we should implement using a macro or unset for a
308 /// The set of intrinsics that this intrinsic uses/requires.
309 std::set<Intrinsic *> Dependencies;
310 /// The "base type", which is Type('d', OutTS). InBaseType is only
311 /// different if CartesianProductOfTypes = 1 (for vreinterpret).
312 Type BaseType, InBaseType;
313 /// The return variable.
315 /// A postfix to apply to every variable. Defaults to "".
316 std::string VariablePostfix;
318 NeonEmitter &Emitter;
319 std::stringstream OS;
322 Intrinsic(Record *R, StringRef Name, StringRef Proto, TypeSpec OutTS,
323 TypeSpec InTS, ClassKind CK, ListInit *Body, NeonEmitter &Emitter,
324 StringRef Guard, bool IsUnavailable, bool BigEndianSafe)
325 : R(R), Name(Name.str()), Proto(Proto.str()), OutTS(OutTS), InTS(InTS),
326 CK(CK), Body(Body), Guard(Guard.str()), IsUnavailable(IsUnavailable),
327 BigEndianSafe(BigEndianSafe), NeededEarly(false), UseMacro(false),
328 BaseType(OutTS, 'd'), InBaseType(InTS, 'd'), Emitter(Emitter) {
329 // If this builtin takes an immediate argument, we need to #define it rather
330 // than use a standard declaration, so that SemaChecking can range check
331 // the immediate passed by the user.
332 if (Proto.find('i') != std::string::npos)
335 // Pointer arguments need to use macros to avoid hiding aligned attributes
336 // from the pointer type.
337 if (Proto.find('p') != std::string::npos ||
338 Proto.find('c') != std::string::npos)
341 // It is not permitted to pass or return an __fp16 by value, so intrinsics
342 // taking a scalar float16_t must be implemented as macros.
343 if (OutTS.find('h') != std::string::npos &&
344 Proto.find('s') != std::string::npos)
347 // Modify the TypeSpec per-argument to get a concrete Type, and create
348 // known variables for each.
349 // Types[0] is the return value.
350 Types.emplace_back(OutTS, Proto[0]);
351 for (unsigned I = 1; I < Proto.size(); ++I)
352 Types.emplace_back(InTS, Proto[I]);
355 /// Get the Record that this intrinsic is based off.
356 Record *getRecord() const { return R; }
357 /// Get the set of Intrinsics that this intrinsic calls.
358 /// this is the set of immediate dependencies, NOT the
359 /// transitive closure.
360 const std::set<Intrinsic *> &getDependencies() const { return Dependencies; }
361 /// Get the architectural guard string (#ifdef).
362 std::string getGuard() const { return Guard; }
363 /// Get the non-mangled name.
364 std::string getName() const { return Name; }
366 /// Return true if the intrinsic takes an immediate operand.
367 bool hasImmediate() const {
368 return Proto.find('i') != std::string::npos;
370 /// Return the parameter index of the immediate operand.
371 unsigned getImmediateIdx() const {
372 assert(hasImmediate());
373 unsigned Idx = Proto.find('i');
374 assert(Idx > 0 && "Can't return an immediate!");
378 /// Return true if the intrinsic takes an splat operand.
379 bool hasSplat() const { return Proto.find('a') != std::string::npos; }
380 /// Return the parameter index of the splat operand.
381 unsigned getSplatIdx() const {
383 unsigned Idx = Proto.find('a');
384 assert(Idx > 0 && "Can't return a splat!");
388 unsigned getNumParams() const { return Proto.size() - 1; }
389 Type getReturnType() const { return Types[0]; }
390 Type getParamType(unsigned I) const { return Types[I + 1]; }
391 Type getBaseType() const { return BaseType; }
392 /// Return the raw prototype string.
393 std::string getProto() const { return Proto; }
395 /// Return true if the prototype has a scalar argument.
396 /// This does not return true for the "splat" code ('a').
397 bool protoHasScalar() const;
399 /// Return the index that parameter PIndex will sit at
400 /// in a generated function call. This is often just PIndex,
401 /// but may not be as things such as multiple-vector operands
402 /// and sret parameters need to be taken into accont.
403 unsigned getGeneratedParamIdx(unsigned PIndex) {
405 if (getReturnType().getNumVectors() > 1)
406 // Multiple vectors are passed as sret.
409 for (unsigned I = 0; I < PIndex; ++I)
410 Idx += std::max(1U, getParamType(I).getNumVectors());
415 bool hasBody() const { return Body && Body->getValues().size() > 0; }
417 void setNeededEarly() { NeededEarly = true; }
419 bool operator<(const Intrinsic &Other) const {
420 // Sort lexicographically on a two-tuple (Guard, Name)
421 if (Guard != Other.Guard)
422 return Guard < Other.Guard;
423 return Name < Other.Name;
426 ClassKind getClassKind(bool UseClassBIfScalar = false) {
427 if (UseClassBIfScalar && !protoHasScalar())
432 /// Return the name, mangled with type information.
433 /// If ForceClassS is true, use ClassS (u32/s32) instead
434 /// of the intrinsic's own type class.
435 std::string getMangledName(bool ForceClassS = false) const;
436 /// Return the type code for a builtin function call.
437 std::string getInstTypeCode(Type T, ClassKind CK) const;
438 /// Return the type string for a BUILTIN() macro in Builtins.def.
439 std::string getBuiltinTypeStr();
441 /// Generate the intrinsic, returning code.
442 std::string generate();
443 /// Perform type checking and populate the dependency graph, but
444 /// don't generate code yet.
448 std::string mangleName(std::string Name, ClassKind CK) const;
450 void initVariables();
451 std::string replaceParamsIn(std::string S);
453 void emitBodyAsBuiltinCall();
455 void generateImpl(bool ReverseArguments,
456 StringRef NamePrefix, StringRef CallPrefix);
458 void emitBody(StringRef CallPrefix);
459 void emitShadowedArgs();
460 void emitArgumentReversal();
461 void emitReturnReversal();
462 void emitReverseVariable(Variable &Dest, Variable &Src);
464 void emitClosingBrace();
465 void emitOpeningBrace();
466 void emitPrototype(StringRef NamePrefix);
470 StringRef CallPrefix;
473 DagEmitter(Intrinsic &Intr, StringRef CallPrefix) :
474 Intr(Intr), CallPrefix(CallPrefix) {
476 std::pair<Type, std::string> emitDagArg(Init *Arg, std::string ArgName);
477 std::pair<Type, std::string> emitDagSaveTemp(DagInit *DI);
478 std::pair<Type, std::string> emitDagSplat(DagInit *DI);
479 std::pair<Type, std::string> emitDagDup(DagInit *DI);
480 std::pair<Type, std::string> emitDagShuffle(DagInit *DI);
481 std::pair<Type, std::string> emitDagCast(DagInit *DI, bool IsBitCast);
482 std::pair<Type, std::string> emitDagCall(DagInit *DI);
483 std::pair<Type, std::string> emitDagNameReplace(DagInit *DI);
484 std::pair<Type, std::string> emitDagLiteral(DagInit *DI);
485 std::pair<Type, std::string> emitDagOp(DagInit *DI);
486 std::pair<Type, std::string> emitDag(DagInit *DI);
491 //===----------------------------------------------------------------------===//
493 //===----------------------------------------------------------------------===//
496 RecordKeeper &Records;
497 DenseMap<Record *, ClassKind> ClassMap;
498 std::map<std::string, std::deque<Intrinsic>> IntrinsicMap;
499 unsigned UniqueNumber;
501 void createIntrinsic(Record *R, SmallVectorImpl<Intrinsic *> &Out);
502 void genBuiltinsDef(raw_ostream &OS, SmallVectorImpl<Intrinsic *> &Defs);
503 void genOverloadTypeCheckCode(raw_ostream &OS,
504 SmallVectorImpl<Intrinsic *> &Defs);
505 void genIntrinsicRangeCheckCode(raw_ostream &OS,
506 SmallVectorImpl<Intrinsic *> &Defs);
509 /// Called by Intrinsic - this attempts to get an intrinsic that takes
510 /// the given types as arguments.
511 Intrinsic &getIntrinsic(StringRef Name, ArrayRef<Type> Types);
513 /// Called by Intrinsic - returns a globally-unique number.
514 unsigned getUniqueNumber() { return UniqueNumber++; }
516 NeonEmitter(RecordKeeper &R) : Records(R), UniqueNumber(0) {
517 Record *SI = R.getClass("SInst");
518 Record *II = R.getClass("IInst");
519 Record *WI = R.getClass("WInst");
520 Record *SOpI = R.getClass("SOpInst");
521 Record *IOpI = R.getClass("IOpInst");
522 Record *WOpI = R.getClass("WOpInst");
523 Record *LOpI = R.getClass("LOpInst");
524 Record *NoTestOpI = R.getClass("NoTestOpInst");
526 ClassMap[SI] = ClassS;
527 ClassMap[II] = ClassI;
528 ClassMap[WI] = ClassW;
529 ClassMap[SOpI] = ClassS;
530 ClassMap[IOpI] = ClassI;
531 ClassMap[WOpI] = ClassW;
532 ClassMap[LOpI] = ClassL;
533 ClassMap[NoTestOpI] = ClassNoTest;
536 // run - Emit arm_neon.h.inc
537 void run(raw_ostream &o);
539 // runHeader - Emit all the __builtin prototypes used in arm_neon.h
540 void runHeader(raw_ostream &o);
542 // runTests - Emit tests for all the Neon intrinsics.
543 void runTests(raw_ostream &o);
546 } // end anonymous namespace
548 //===----------------------------------------------------------------------===//
549 // Type implementation
550 //===----------------------------------------------------------------------===//
552 std::string Type::str() const {
557 if (!Signed && isInteger())
567 S += utostr(ElementBitwidth);
569 S += "x" + utostr(getNumElements());
571 S += "x" + utostr(NumVectors);
582 std::string Type::builtin_str() const {
588 // All pointers are void pointers.
590 else if (isInteger())
591 switch (ElementBitwidth) {
592 case 8: S += "c"; break;
593 case 16: S += "s"; break;
594 case 32: S += "i"; break;
595 case 64: S += "Wi"; break;
596 case 128: S += "LLLi"; break;
597 default: llvm_unreachable("Unhandled case!");
600 switch (ElementBitwidth) {
601 case 16: S += "h"; break;
602 case 32: S += "f"; break;
603 case 64: S += "d"; break;
604 default: llvm_unreachable("Unhandled case!");
607 if (isChar() && !Pointer)
608 // Make chars explicitly signed.
610 else if (isInteger() && !Pointer && !Signed)
613 // Constant indices are "int", but have the "constant expression" modifier.
615 assert(isInteger() && isSigned());
620 if (Constant) S += "C";
621 if (Pointer) S += "*";
626 for (unsigned I = 0; I < NumVectors; ++I)
627 Ret += "V" + utostr(getNumElements()) + S;
632 unsigned Type::getNeonEnum() const {
634 switch (ElementBitwidth) {
635 case 8: Addend = 0; break;
636 case 16: Addend = 1; break;
637 case 32: Addend = 2; break;
638 case 64: Addend = 3; break;
639 case 128: Addend = 4; break;
640 default: llvm_unreachable("Unhandled element bitwidth!");
643 unsigned Base = (unsigned)NeonTypeFlags::Int8 + Addend;
645 // Adjustment needed because Poly32 doesn't exist.
648 Base = (unsigned)NeonTypeFlags::Poly8 + Addend;
651 assert(Addend != 0 && "Float8 doesn't exist!");
652 Base = (unsigned)NeonTypeFlags::Float16 + (Addend - 1);
656 Base |= (unsigned)NeonTypeFlags::QuadFlag;
657 if (isInteger() && !Signed)
658 Base |= (unsigned)NeonTypeFlags::UnsignedFlag;
663 Type Type::fromTypedefName(StringRef Name) {
669 if (Name.front() == 'u') {
671 Name = Name.drop_front();
676 if (Name.startswith("float")) {
678 Name = Name.drop_front(5);
679 } else if (Name.startswith("poly")) {
681 Name = Name.drop_front(4);
683 assert(Name.startswith("int"));
684 Name = Name.drop_front(3);
688 for (I = 0; I < Name.size(); ++I) {
689 if (!isdigit(Name[I]))
692 Name.substr(0, I).getAsInteger(10, T.ElementBitwidth);
693 Name = Name.drop_front(I);
695 T.Bitwidth = T.ElementBitwidth;
698 if (Name.front() == 'x') {
699 Name = Name.drop_front();
701 for (I = 0; I < Name.size(); ++I) {
702 if (!isdigit(Name[I]))
706 Name.substr(0, I).getAsInteger(10, NumLanes);
707 Name = Name.drop_front(I);
708 T.Bitwidth = T.ElementBitwidth * NumLanes;
713 if (Name.front() == 'x') {
714 Name = Name.drop_front();
716 for (I = 0; I < Name.size(); ++I) {
717 if (!isdigit(Name[I]))
720 Name.substr(0, I).getAsInteger(10, T.NumVectors);
721 Name = Name.drop_front(I);
724 assert(Name.startswith("_t") && "Malformed typedef!");
728 void Type::applyTypespec(bool &Quad) {
730 ScalarForMangling = false;
732 Poly = Float = false;
733 ElementBitwidth = ~0U;
740 ScalarForMangling = true;
762 ElementBitwidth = 16;
768 ElementBitwidth = 32;
774 ElementBitwidth = 64;
777 ElementBitwidth = 128;
778 // Poly doesn't have a 128x1 type.
783 llvm_unreachable("Unhandled type code!");
786 assert(ElementBitwidth != ~0U && "Bad element bitwidth!");
788 Bitwidth = Quad ? 128 : 64;
791 void Type::applyModifier(char Mod) {
792 bool AppliedQuad = false;
793 applyTypespec(AppliedQuad);
810 Bitwidth = ElementBitwidth;
817 Bitwidth = ElementBitwidth;
826 assert(!Poly && "'u' can't be used with poly types!");
830 Bitwidth = ElementBitwidth = 64;
835 Bitwidth = ElementBitwidth = 32;
841 ElementBitwidth = 32;
845 ElementBitwidth = 64;
856 ElementBitwidth *= 2;
860 ElementBitwidth *= 2;
865 ElementBitwidth = Bitwidth = 32;
873 ElementBitwidth = Bitwidth = 64;
879 ElementBitwidth /= 2;
880 Bitwidth = ElementBitwidth;
884 ElementBitwidth *= 2;
885 Bitwidth = ElementBitwidth;
890 Bitwidth = ElementBitwidth;
901 Bitwidth = ElementBitwidth;
905 ElementBitwidth /= 2;
908 ElementBitwidth /= 2;
912 ElementBitwidth /= 2;
916 ElementBitwidth /= 2;
946 llvm_unreachable("Unhandled character!");
950 //===----------------------------------------------------------------------===//
951 // Intrinsic implementation
952 //===----------------------------------------------------------------------===//
954 std::string Intrinsic::getInstTypeCode(Type T, ClassKind CK) const {
955 char typeCode = '\0';
956 bool printNumber = true;
963 else if (T.isInteger())
964 typeCode = T.isSigned() ? 's' : 'u';
984 if (typeCode != '\0')
985 S.push_back(typeCode);
987 S += utostr(T.getElementSizeInBits());
992 static bool isFloatingPointProtoModifier(char Mod) {
993 return Mod == 'F' || Mod == 'f';
996 std::string Intrinsic::getBuiltinTypeStr() {
997 ClassKind LocalCK = getClassKind(true);
1000 Type RetT = getReturnType();
1001 if ((LocalCK == ClassI || LocalCK == ClassW) && RetT.isScalar() &&
1003 RetT.makeInteger(RetT.getElementSizeInBits(), false);
1005 // Since the return value must be one type, return a vector type of the
1006 // appropriate width which we will bitcast. An exception is made for
1007 // returning structs of 2, 3, or 4 vectors which are returned in a sret-like
1008 // fashion, storing them to a pointer arg.
1009 if (RetT.getNumVectors() > 1) {
1010 S += "vv*"; // void result with void* first argument
1013 RetT.makeInteger(RetT.getElementSizeInBits(), false);
1014 if (!RetT.isScalar() && !RetT.isSigned())
1017 bool ForcedVectorFloatingType = isFloatingPointProtoModifier(Proto[0]);
1018 if (LocalCK == ClassB && !RetT.isScalar() && !ForcedVectorFloatingType)
1019 // Cast to vector of 8-bit elements.
1020 RetT.makeInteger(8, true);
1022 S += RetT.builtin_str();
1025 for (unsigned I = 0; I < getNumParams(); ++I) {
1026 Type T = getParamType(I);
1028 T.makeInteger(T.getElementSizeInBits(), false);
1030 bool ForcedFloatingType = isFloatingPointProtoModifier(Proto[I + 1]);
1031 if (LocalCK == ClassB && !T.isScalar() && !ForcedFloatingType)
1032 T.makeInteger(8, true);
1033 // Halves always get converted to 8-bit elements.
1034 if (T.isHalf() && T.isVector() && !T.isScalarForMangling())
1035 T.makeInteger(8, true);
1037 if (LocalCK == ClassI)
1040 if (hasImmediate() && getImmediateIdx() == I)
1041 T.makeImmediate(32);
1043 S += T.builtin_str();
1046 // Extra constant integer to hold type class enum for this function, e.g. s8
1047 if (LocalCK == ClassB)
1053 std::string Intrinsic::getMangledName(bool ForceClassS) const {
1054 // Check if the prototype has a scalar operand with the type of the vector
1055 // elements. If not, bitcasting the args will take care of arg checking.
1056 // The actual signedness etc. will be taken care of with special enums.
1057 ClassKind LocalCK = CK;
1058 if (!protoHasScalar())
1061 return mangleName(Name, ForceClassS ? ClassS : LocalCK);
1064 std::string Intrinsic::mangleName(std::string Name, ClassKind LocalCK) const {
1065 std::string typeCode = getInstTypeCode(BaseType, LocalCK);
1066 std::string S = Name;
1068 if (Name == "vcvt_f16_f32" || Name == "vcvt_f32_f16" ||
1069 Name == "vcvt_f32_f64" || Name == "vcvt_f64_f32")
1072 if (typeCode.size() > 0) {
1073 // If the name ends with _xN (N = 2,3,4), insert the typeCode before _xN.
1074 if (Name.size() >= 3 && isdigit(Name.back()) &&
1075 Name[Name.length() - 2] == 'x' && Name[Name.length() - 3] == '_')
1076 S.insert(S.length() - 3, "_" + typeCode);
1078 S += "_" + typeCode;
1081 if (BaseType != InBaseType) {
1082 // A reinterpret - out the input base type at the end.
1083 S += "_" + getInstTypeCode(InBaseType, LocalCK);
1086 if (LocalCK == ClassB)
1089 // Insert a 'q' before the first '_' character so that it ends up before
1090 // _lane or _n on vector-scalar operations.
1091 if (BaseType.getSizeInBits() == 128 && !BaseType.noManglingQ()) {
1092 size_t Pos = S.find('_');
1097 if (BaseType.isScalarForMangling()) {
1098 switch (BaseType.getElementSizeInBits()) {
1099 case 8: Suffix = 'b'; break;
1100 case 16: Suffix = 'h'; break;
1101 case 32: Suffix = 's'; break;
1102 case 64: Suffix = 'd'; break;
1103 default: llvm_unreachable("Bad suffix!");
1106 if (Suffix != '\0') {
1107 size_t Pos = S.find('_');
1108 S.insert(Pos, &Suffix, 1);
1114 std::string Intrinsic::replaceParamsIn(std::string S) {
1115 while (S.find('$') != std::string::npos) {
1116 size_t Pos = S.find('$');
1117 size_t End = Pos + 1;
1118 while (isalpha(S[End]))
1121 std::string VarName = S.substr(Pos + 1, End - Pos - 1);
1122 assert_with_loc(Variables.find(VarName) != Variables.end(),
1123 "Variable not defined!");
1124 S.replace(Pos, End - Pos, Variables.find(VarName)->second.getName());
1130 void Intrinsic::initVariables() {
1133 // Modify the TypeSpec per-argument to get a concrete Type, and create
1134 // known variables for each.
1135 for (unsigned I = 1; I < Proto.size(); ++I) {
1136 char NameC = '0' + (I - 1);
1137 std::string Name = "p";
1138 Name.push_back(NameC);
1140 Variables[Name] = Variable(Types[I], Name + VariablePostfix);
1142 RetVar = Variable(Types[0], "ret" + VariablePostfix);
1145 void Intrinsic::emitPrototype(StringRef NamePrefix) {
1149 OS << "__ai " << Types[0].str() << " ";
1151 OS << NamePrefix.str() << mangleName(Name, ClassS) << "(";
1153 for (unsigned I = 0; I < getNumParams(); ++I) {
1157 char NameC = '0' + I;
1158 std::string Name = "p";
1159 Name.push_back(NameC);
1160 assert(Variables.find(Name) != Variables.end());
1161 Variable &V = Variables[Name];
1164 OS << V.getType().str() << " ";
1171 void Intrinsic::emitOpeningBrace() {
1173 OS << " __extension__ ({";
1179 void Intrinsic::emitClosingBrace() {
1186 void Intrinsic::emitNewLine() {
1193 void Intrinsic::emitReverseVariable(Variable &Dest, Variable &Src) {
1194 if (Dest.getType().getNumVectors() > 1) {
1197 for (unsigned K = 0; K < Dest.getType().getNumVectors(); ++K) {
1198 OS << " " << Dest.getName() << ".val[" << utostr(K) << "] = "
1199 << "__builtin_shufflevector("
1200 << Src.getName() << ".val[" << utostr(K) << "], "
1201 << Src.getName() << ".val[" << utostr(K) << "]";
1202 for (int J = Dest.getType().getNumElements() - 1; J >= 0; --J)
1203 OS << ", " << utostr(J);
1208 OS << " " << Dest.getName()
1209 << " = __builtin_shufflevector(" << Src.getName() << ", " << Src.getName();
1210 for (int J = Dest.getType().getNumElements() - 1; J >= 0; --J)
1211 OS << ", " << utostr(J);
1217 void Intrinsic::emitArgumentReversal() {
1221 // Reverse all vector arguments.
1222 for (unsigned I = 0; I < getNumParams(); ++I) {
1223 std::string Name = "p" + utostr(I);
1224 std::string NewName = "rev" + utostr(I);
1226 Variable &V = Variables[Name];
1227 Variable NewV(V.getType(), NewName + VariablePostfix);
1229 if (!NewV.getType().isVector() || NewV.getType().getNumElements() == 1)
1232 OS << " " << NewV.getType().str() << " " << NewV.getName() << ";";
1233 emitReverseVariable(NewV, V);
1238 void Intrinsic::emitReturnReversal() {
1241 if (!getReturnType().isVector() || getReturnType().isVoid() ||
1242 getReturnType().getNumElements() == 1)
1244 emitReverseVariable(RetVar, RetVar);
1248 void Intrinsic::emitShadowedArgs() {
1249 // Macro arguments are not type-checked like inline function arguments,
1250 // so assign them to local temporaries to get the right type checking.
1254 for (unsigned I = 0; I < getNumParams(); ++I) {
1255 // Do not create a temporary for an immediate argument.
1256 // That would defeat the whole point of using a macro!
1257 if (hasImmediate() && Proto[I+1] == 'i')
1259 // Do not create a temporary for pointer arguments. The input
1260 // pointer may have an alignment hint.
1261 if (getParamType(I).isPointer())
1264 std::string Name = "p" + utostr(I);
1266 assert(Variables.find(Name) != Variables.end());
1267 Variable &V = Variables[Name];
1269 std::string NewName = "s" + utostr(I);
1270 Variable V2(V.getType(), NewName + VariablePostfix);
1272 OS << " " << V2.getType().str() << " " << V2.getName() << " = "
1273 << V.getName() << ";";
1280 // We don't check 'a' in this function, because for builtin function the
1281 // argument matching to 'a' uses a vector type splatted from a scalar type.
1282 bool Intrinsic::protoHasScalar() const {
1283 return (Proto.find('s') != std::string::npos ||
1284 Proto.find('z') != std::string::npos ||
1285 Proto.find('r') != std::string::npos ||
1286 Proto.find('b') != std::string::npos ||
1287 Proto.find('$') != std::string::npos ||
1288 Proto.find('y') != std::string::npos ||
1289 Proto.find('o') != std::string::npos);
1292 void Intrinsic::emitBodyAsBuiltinCall() {
1295 // If this builtin returns a struct 2, 3, or 4 vectors, pass it as an implicit
1296 // sret-like argument.
1297 bool SRet = getReturnType().getNumVectors() >= 2;
1301 // Call the non-splat builtin: chop off the "_n" suffix from the name.
1302 assert(N.endswith("_n"));
1306 ClassKind LocalCK = CK;
1307 if (!protoHasScalar())
1310 if (!getReturnType().isVoid() && !SRet)
1311 S += "(" + RetVar.getType().str() + ") ";
1313 S += "__builtin_neon_" + mangleName(N, LocalCK) + "(";
1316 S += "&" + RetVar.getName() + ", ";
1318 for (unsigned I = 0; I < getNumParams(); ++I) {
1319 Variable &V = Variables["p" + utostr(I)];
1320 Type T = V.getType();
1322 // Handle multiple-vector values specially, emitting each subvector as an
1323 // argument to the builtin.
1324 if (T.getNumVectors() > 1) {
1325 // Check if an explicit cast is needed.
1327 if (T.isChar() || T.isPoly() || !T.isSigned()) {
1330 T2.makeInteger(8, /*Signed=*/true);
1331 Cast = "(" + T2.str() + ")";
1334 for (unsigned J = 0; J < T.getNumVectors(); ++J)
1335 S += Cast + V.getName() + ".val[" + utostr(J) + "], ";
1340 Type CastToType = T;
1341 if (hasSplat() && I == getSplatIdx()) {
1342 Arg = "(" + BaseType.str() + ") {";
1343 for (unsigned J = 0; J < BaseType.getNumElements(); ++J) {
1350 CastToType = BaseType;
1355 // Check if an explicit cast is needed.
1356 if (CastToType.isVector()) {
1357 CastToType.makeInteger(8, true);
1358 Arg = "(" + CastToType.str() + ")" + Arg;
1364 // Extra constant integer to hold type class enum for this function, e.g. s8
1365 if (getClassKind(true) == ClassB) {
1366 Type ThisTy = getReturnType();
1367 if (Proto[0] == 'v' || isFloatingPointProtoModifier(Proto[0]))
1368 ThisTy = getParamType(0);
1369 if (ThisTy.isPointer())
1370 ThisTy = getParamType(1);
1372 S += utostr(ThisTy.getNeonEnum());
1374 // Remove extraneous ", ".
1380 std::string RetExpr;
1381 if (!SRet && !RetVar.getType().isVoid())
1382 RetExpr = RetVar.getName() + " = ";
1384 OS << " " << RetExpr << S;
1388 void Intrinsic::emitBody(StringRef CallPrefix) {
1389 std::vector<std::string> Lines;
1391 assert(RetVar.getType() == Types[0]);
1392 // Create a return variable, if we're not void.
1393 if (!RetVar.getType().isVoid()) {
1394 OS << " " << RetVar.getType().str() << " " << RetVar.getName() << ";";
1398 if (!Body || Body->getValues().size() == 0) {
1399 // Nothing specific to output - must output a builtin.
1400 emitBodyAsBuiltinCall();
1404 // We have a list of "things to output". The last should be returned.
1405 for (auto *I : Body->getValues()) {
1406 if (StringInit *SI = dyn_cast<StringInit>(I)) {
1407 Lines.push_back(replaceParamsIn(SI->getAsString()));
1408 } else if (DagInit *DI = dyn_cast<DagInit>(I)) {
1409 DagEmitter DE(*this, CallPrefix);
1410 Lines.push_back(DE.emitDag(DI).second + ";");
1414 assert(!Lines.empty() && "Empty def?");
1415 if (!RetVar.getType().isVoid())
1416 Lines.back().insert(0, RetVar.getName() + " = ");
1418 for (auto &L : Lines) {
1424 void Intrinsic::emitReturn() {
1425 if (RetVar.getType().isVoid())
1428 OS << " " << RetVar.getName() << ";";
1430 OS << " return " << RetVar.getName() << ";";
1434 std::pair<Type, std::string> Intrinsic::DagEmitter::emitDag(DagInit *DI) {
1435 // At this point we should only be seeing a def.
1436 DefInit *DefI = cast<DefInit>(DI->getOperator());
1437 std::string Op = DefI->getAsString();
1439 if (Op == "cast" || Op == "bitcast")
1440 return emitDagCast(DI, Op == "bitcast");
1441 if (Op == "shuffle")
1442 return emitDagShuffle(DI);
1444 return emitDagDup(DI);
1446 return emitDagSplat(DI);
1447 if (Op == "save_temp")
1448 return emitDagSaveTemp(DI);
1450 return emitDagOp(DI);
1452 return emitDagCall(DI);
1453 if (Op == "name_replace")
1454 return emitDagNameReplace(DI);
1455 if (Op == "literal")
1456 return emitDagLiteral(DI);
1457 assert_with_loc(false, "Unknown operation!");
1458 return std::make_pair(Type::getVoid(), "");
1461 std::pair<Type, std::string> Intrinsic::DagEmitter::emitDagOp(DagInit *DI) {
1462 std::string Op = cast<StringInit>(DI->getArg(0))->getAsUnquotedString();
1463 if (DI->getNumArgs() == 2) {
1465 std::pair<Type, std::string> R =
1466 emitDagArg(DI->getArg(1), DI->getArgName(1));
1467 return std::make_pair(R.first, Op + R.second);
1469 assert(DI->getNumArgs() == 3 && "Can only handle unary and binary ops!");
1470 std::pair<Type, std::string> R1 =
1471 emitDagArg(DI->getArg(1), DI->getArgName(1));
1472 std::pair<Type, std::string> R2 =
1473 emitDagArg(DI->getArg(2), DI->getArgName(2));
1474 assert_with_loc(R1.first == R2.first, "Argument type mismatch!");
1475 return std::make_pair(R1.first, R1.second + " " + Op + " " + R2.second);
1479 std::pair<Type, std::string> Intrinsic::DagEmitter::emitDagCall(DagInit *DI) {
1480 std::vector<Type> Types;
1481 std::vector<std::string> Values;
1482 for (unsigned I = 0; I < DI->getNumArgs() - 1; ++I) {
1483 std::pair<Type, std::string> R =
1484 emitDagArg(DI->getArg(I + 1), DI->getArgName(I + 1));
1485 Types.push_back(R.first);
1486 Values.push_back(R.second);
1489 // Look up the called intrinsic.
1491 if (StringInit *SI = dyn_cast<StringInit>(DI->getArg(0)))
1492 N = SI->getAsUnquotedString();
1494 N = emitDagArg(DI->getArg(0), "").second;
1495 Intrinsic &Callee = Intr.Emitter.getIntrinsic(N, Types);
1497 // Make sure the callee is known as an early def.
1498 Callee.setNeededEarly();
1499 Intr.Dependencies.insert(&Callee);
1501 // Now create the call itself.
1502 std::string S = CallPrefix.str() + Callee.getMangledName(true) + "(";
1503 for (unsigned I = 0; I < DI->getNumArgs() - 1; ++I) {
1510 return std::make_pair(Callee.getReturnType(), S);
1513 std::pair<Type, std::string> Intrinsic::DagEmitter::emitDagCast(DagInit *DI,
1515 // (cast MOD* VAL) -> cast VAL to type given by MOD.
1516 std::pair<Type, std::string> R = emitDagArg(
1517 DI->getArg(DI->getNumArgs() - 1), DI->getArgName(DI->getNumArgs() - 1));
1518 Type castToType = R.first;
1519 for (unsigned ArgIdx = 0; ArgIdx < DI->getNumArgs() - 1; ++ArgIdx) {
1521 // MOD can take several forms:
1522 // 1. $X - take the type of parameter / variable X.
1523 // 2. The value "R" - take the type of the return type.
1525 // 4. The value "U" or "S" to switch the signedness.
1526 // 5. The value "H" or "D" to half or double the bitwidth.
1527 // 6. The value "8" to convert to 8-bit (signed) integer lanes.
1528 if (DI->getArgName(ArgIdx).size()) {
1529 assert_with_loc(Intr.Variables.find(DI->getArgName(ArgIdx)) !=
1530 Intr.Variables.end(),
1531 "Variable not found");
1532 castToType = Intr.Variables[DI->getArgName(ArgIdx)].getType();
1534 StringInit *SI = dyn_cast<StringInit>(DI->getArg(ArgIdx));
1535 assert_with_loc(SI, "Expected string type or $Name for cast type");
1537 if (SI->getAsUnquotedString() == "R") {
1538 castToType = Intr.getReturnType();
1539 } else if (SI->getAsUnquotedString() == "U") {
1540 castToType.makeUnsigned();
1541 } else if (SI->getAsUnquotedString() == "S") {
1542 castToType.makeSigned();
1543 } else if (SI->getAsUnquotedString() == "H") {
1544 castToType.halveLanes();
1545 } else if (SI->getAsUnquotedString() == "D") {
1546 castToType.doubleLanes();
1547 } else if (SI->getAsUnquotedString() == "8") {
1548 castToType.makeInteger(8, true);
1550 castToType = Type::fromTypedefName(SI->getAsUnquotedString());
1551 assert_with_loc(!castToType.isVoid(), "Unknown typedef");
1558 // Emit a reinterpret cast. The second operand must be an lvalue, so create
1560 std::string N = "reint";
1562 while (Intr.Variables.find(N) != Intr.Variables.end())
1563 N = "reint" + utostr(++I);
1564 Intr.Variables[N] = Variable(R.first, N + Intr.VariablePostfix);
1566 Intr.OS << R.first.str() << " " << Intr.Variables[N].getName() << " = "
1570 S = "*(" + castToType.str() + " *) &" + Intr.Variables[N].getName() + "";
1572 // Emit a normal (static) cast.
1573 S = "(" + castToType.str() + ")(" + R.second + ")";
1576 return std::make_pair(castToType, S);
1579 std::pair<Type, std::string> Intrinsic::DagEmitter::emitDagShuffle(DagInit *DI){
1580 // See the documentation in arm_neon.td for a description of these operators.
1581 class LowHalf : public SetTheory::Operator {
1583 void apply(SetTheory &ST, DagInit *Expr, SetTheory::RecSet &Elts,
1584 ArrayRef<SMLoc> Loc) override {
1585 SetTheory::RecSet Elts2;
1586 ST.evaluate(Expr->arg_begin(), Expr->arg_end(), Elts2, Loc);
1587 Elts.insert(Elts2.begin(), Elts2.begin() + (Elts2.size() / 2));
1590 class HighHalf : public SetTheory::Operator {
1592 void apply(SetTheory &ST, DagInit *Expr, SetTheory::RecSet &Elts,
1593 ArrayRef<SMLoc> Loc) override {
1594 SetTheory::RecSet Elts2;
1595 ST.evaluate(Expr->arg_begin(), Expr->arg_end(), Elts2, Loc);
1596 Elts.insert(Elts2.begin() + (Elts2.size() / 2), Elts2.end());
1599 class Rev : public SetTheory::Operator {
1600 unsigned ElementSize;
1603 Rev(unsigned ElementSize) : ElementSize(ElementSize) {}
1604 void apply(SetTheory &ST, DagInit *Expr, SetTheory::RecSet &Elts,
1605 ArrayRef<SMLoc> Loc) override {
1606 SetTheory::RecSet Elts2;
1607 ST.evaluate(Expr->arg_begin() + 1, Expr->arg_end(), Elts2, Loc);
1609 int64_t VectorSize = cast<IntInit>(Expr->getArg(0))->getValue();
1610 VectorSize /= ElementSize;
1612 std::vector<Record *> Revved;
1613 for (unsigned VI = 0; VI < Elts2.size(); VI += VectorSize) {
1614 for (int LI = VectorSize - 1; LI >= 0; --LI) {
1615 Revved.push_back(Elts2[VI + LI]);
1619 Elts.insert(Revved.begin(), Revved.end());
1622 class MaskExpander : public SetTheory::Expander {
1626 MaskExpander(unsigned N) : N(N) {}
1627 void expand(SetTheory &ST, Record *R, SetTheory::RecSet &Elts) override {
1628 unsigned Addend = 0;
1629 if (R->getName() == "mask0")
1631 else if (R->getName() == "mask1")
1635 for (unsigned I = 0; I < N; ++I)
1636 Elts.insert(R->getRecords().getDef("sv" + utostr(I + Addend)));
1640 // (shuffle arg1, arg2, sequence)
1641 std::pair<Type, std::string> Arg1 =
1642 emitDagArg(DI->getArg(0), DI->getArgName(0));
1643 std::pair<Type, std::string> Arg2 =
1644 emitDagArg(DI->getArg(1), DI->getArgName(1));
1645 assert_with_loc(Arg1.first == Arg2.first,
1646 "Different types in arguments to shuffle!");
1649 SetTheory::RecSet Elts;
1650 ST.addOperator("lowhalf", llvm::make_unique<LowHalf>());
1651 ST.addOperator("highhalf", llvm::make_unique<HighHalf>());
1652 ST.addOperator("rev",
1653 llvm::make_unique<Rev>(Arg1.first.getElementSizeInBits()));
1654 ST.addExpander("MaskExpand",
1655 llvm::make_unique<MaskExpander>(Arg1.first.getNumElements()));
1656 ST.evaluate(DI->getArg(2), Elts, None);
1658 std::string S = "__builtin_shufflevector(" + Arg1.second + ", " + Arg2.second;
1659 for (auto &E : Elts) {
1660 StringRef Name = E->getName();
1661 assert_with_loc(Name.startswith("sv"),
1662 "Incorrect element kind in shuffle mask!");
1663 S += ", " + Name.drop_front(2).str();
1667 // Recalculate the return type - the shuffle may have halved or doubled it.
1669 if (Elts.size() > T.getNumElements()) {
1671 Elts.size() == T.getNumElements() * 2,
1672 "Can only double or half the number of elements in a shuffle!");
1674 } else if (Elts.size() < T.getNumElements()) {
1676 Elts.size() == T.getNumElements() / 2,
1677 "Can only double or half the number of elements in a shuffle!");
1681 return std::make_pair(T, S);
1684 std::pair<Type, std::string> Intrinsic::DagEmitter::emitDagDup(DagInit *DI) {
1685 assert_with_loc(DI->getNumArgs() == 1, "dup() expects one argument");
1686 std::pair<Type, std::string> A = emitDagArg(DI->getArg(0), DI->getArgName(0));
1687 assert_with_loc(A.first.isScalar(), "dup() expects a scalar argument");
1689 Type T = Intr.getBaseType();
1690 assert_with_loc(T.isVector(), "dup() used but default type is scalar!");
1691 std::string S = "(" + T.str() + ") {";
1692 for (unsigned I = 0; I < T.getNumElements(); ++I) {
1699 return std::make_pair(T, S);
1702 std::pair<Type, std::string> Intrinsic::DagEmitter::emitDagSplat(DagInit *DI) {
1703 assert_with_loc(DI->getNumArgs() == 2, "splat() expects two arguments");
1704 std::pair<Type, std::string> A = emitDagArg(DI->getArg(0), DI->getArgName(0));
1705 std::pair<Type, std::string> B = emitDagArg(DI->getArg(1), DI->getArgName(1));
1707 assert_with_loc(B.first.isScalar(),
1708 "splat() requires a scalar int as the second argument");
1710 std::string S = "__builtin_shufflevector(" + A.second + ", " + A.second;
1711 for (unsigned I = 0; I < Intr.getBaseType().getNumElements(); ++I) {
1712 S += ", " + B.second;
1716 return std::make_pair(Intr.getBaseType(), S);
1719 std::pair<Type, std::string> Intrinsic::DagEmitter::emitDagSaveTemp(DagInit *DI) {
1720 assert_with_loc(DI->getNumArgs() == 2, "save_temp() expects two arguments");
1721 std::pair<Type, std::string> A = emitDagArg(DI->getArg(1), DI->getArgName(1));
1723 assert_with_loc(!A.first.isVoid(),
1724 "Argument to save_temp() must have non-void type!");
1726 std::string N = DI->getArgName(0);
1727 assert_with_loc(N.size(), "save_temp() expects a name as the first argument");
1729 assert_with_loc(Intr.Variables.find(N) == Intr.Variables.end(),
1730 "Variable already defined!");
1731 Intr.Variables[N] = Variable(A.first, N + Intr.VariablePostfix);
1734 A.first.str() + " " + Intr.Variables[N].getName() + " = " + A.second;
1736 return std::make_pair(Type::getVoid(), S);
1739 std::pair<Type, std::string>
1740 Intrinsic::DagEmitter::emitDagNameReplace(DagInit *DI) {
1741 std::string S = Intr.Name;
1743 assert_with_loc(DI->getNumArgs() == 2, "name_replace requires 2 arguments!");
1744 std::string ToReplace = cast<StringInit>(DI->getArg(0))->getAsUnquotedString();
1745 std::string ReplaceWith = cast<StringInit>(DI->getArg(1))->getAsUnquotedString();
1747 size_t Idx = S.find(ToReplace);
1749 assert_with_loc(Idx != std::string::npos, "name should contain '" + ToReplace + "'!");
1750 S.replace(Idx, ToReplace.size(), ReplaceWith);
1752 return std::make_pair(Type::getVoid(), S);
1755 std::pair<Type, std::string> Intrinsic::DagEmitter::emitDagLiteral(DagInit *DI){
1756 std::string Ty = cast<StringInit>(DI->getArg(0))->getAsUnquotedString();
1757 std::string Value = cast<StringInit>(DI->getArg(1))->getAsUnquotedString();
1758 return std::make_pair(Type::fromTypedefName(Ty), Value);
1761 std::pair<Type, std::string>
1762 Intrinsic::DagEmitter::emitDagArg(Init *Arg, std::string ArgName) {
1763 if (ArgName.size()) {
1764 assert_with_loc(!Arg->isComplete(),
1765 "Arguments must either be DAGs or names, not both!");
1766 assert_with_loc(Intr.Variables.find(ArgName) != Intr.Variables.end(),
1767 "Variable not defined!");
1768 Variable &V = Intr.Variables[ArgName];
1769 return std::make_pair(V.getType(), V.getName());
1772 assert(Arg && "Neither ArgName nor Arg?!");
1773 DagInit *DI = dyn_cast<DagInit>(Arg);
1774 assert_with_loc(DI, "Arguments must either be DAGs or names!");
1779 std::string Intrinsic::generate() {
1780 // Little endian intrinsics are simple and don't require any argument
1782 OS << "#ifdef __LITTLE_ENDIAN__\n";
1784 generateImpl(false, "", "");
1788 // Big endian intrinsics are more complex. The user intended these
1789 // intrinsics to operate on a vector "as-if" loaded by (V)LDR,
1790 // but we load as-if (V)LD1. So we should swap all arguments and
1791 // swap the return value too.
1793 // If we call sub-intrinsics, we should call a version that does
1794 // not re-swap the arguments!
1795 generateImpl(true, "", "__noswap_");
1797 // If we're needed early, create a non-swapping variant for
1800 generateImpl(false, "__noswap_", "__noswap_");
1807 void Intrinsic::generateImpl(bool ReverseArguments,
1808 StringRef NamePrefix, StringRef CallPrefix) {
1811 // If we call a macro, our local variables may be corrupted due to
1812 // lack of proper lexical scoping. So, add a globally unique postfix
1813 // to every variable.
1815 // indexBody() should have set up the Dependencies set by now.
1816 for (auto *I : Dependencies)
1818 VariablePostfix = "_" + utostr(Emitter.getUniqueNumber());
1824 emitPrototype(NamePrefix);
1826 if (IsUnavailable) {
1827 OS << " __attribute__((unavailable));";
1831 if (ReverseArguments)
1832 emitArgumentReversal();
1833 emitBody(CallPrefix);
1834 if (ReverseArguments)
1835 emitReturnReversal();
1841 CurrentRecord = nullptr;
1844 void Intrinsic::indexBody() {
1851 CurrentRecord = nullptr;
1854 //===----------------------------------------------------------------------===//
1855 // NeonEmitter implementation
1856 //===----------------------------------------------------------------------===//
1858 Intrinsic &NeonEmitter::getIntrinsic(StringRef Name, ArrayRef<Type> Types) {
1859 // First, look up the name in the intrinsic map.
1860 assert_with_loc(IntrinsicMap.find(Name.str()) != IntrinsicMap.end(),
1861 ("Intrinsic '" + Name + "' not found!").str());
1862 auto &V = IntrinsicMap.find(Name.str())->second;
1863 std::vector<Intrinsic *> GoodVec;
1865 // Create a string to print if we end up failing.
1866 std::string ErrMsg = "looking up intrinsic '" + Name.str() + "(";
1867 for (unsigned I = 0; I < Types.size(); ++I) {
1870 ErrMsg += Types[I].str();
1873 ErrMsg += "Available overloads:\n";
1875 // Now, look through each intrinsic implementation and see if the types are
1878 ErrMsg += " - " + I.getReturnType().str() + " " + I.getMangledName();
1880 for (unsigned A = 0; A < I.getNumParams(); ++A) {
1883 ErrMsg += I.getParamType(A).str();
1887 if (I.getNumParams() != Types.size())
1891 for (unsigned Arg = 0; Arg < Types.size(); ++Arg) {
1892 if (I.getParamType(Arg) != Types[Arg]) {
1898 GoodVec.push_back(&I);
1901 assert_with_loc(GoodVec.size() > 0,
1902 "No compatible intrinsic found - " + ErrMsg);
1903 assert_with_loc(GoodVec.size() == 1, "Multiple overloads found - " + ErrMsg);
1905 return *GoodVec.front();
1908 void NeonEmitter::createIntrinsic(Record *R,
1909 SmallVectorImpl<Intrinsic *> &Out) {
1910 std::string Name = R->getValueAsString("Name");
1911 std::string Proto = R->getValueAsString("Prototype");
1912 std::string Types = R->getValueAsString("Types");
1913 Record *OperationRec = R->getValueAsDef("Operation");
1914 bool CartesianProductOfTypes = R->getValueAsBit("CartesianProductOfTypes");
1915 bool BigEndianSafe = R->getValueAsBit("BigEndianSafe");
1916 std::string Guard = R->getValueAsString("ArchGuard");
1917 bool IsUnavailable = OperationRec->getValueAsBit("Unavailable");
1919 // Set the global current record. This allows assert_with_loc to produce
1920 // decent location information even when highly nested.
1923 ListInit *Body = OperationRec->getValueAsListInit("Ops");
1925 std::vector<TypeSpec> TypeSpecs = TypeSpec::fromTypeSpecs(Types);
1927 ClassKind CK = ClassNone;
1928 if (R->getSuperClasses().size() >= 2)
1929 CK = ClassMap[R->getSuperClasses()[1]];
1931 std::vector<std::pair<TypeSpec, TypeSpec>> NewTypeSpecs;
1932 for (auto TS : TypeSpecs) {
1933 if (CartesianProductOfTypes) {
1934 Type DefaultT(TS, 'd');
1935 for (auto SrcTS : TypeSpecs) {
1936 Type DefaultSrcT(SrcTS, 'd');
1938 DefaultSrcT.getSizeInBits() != DefaultT.getSizeInBits())
1940 NewTypeSpecs.push_back(std::make_pair(TS, SrcTS));
1943 NewTypeSpecs.push_back(std::make_pair(TS, TS));
1947 std::sort(NewTypeSpecs.begin(), NewTypeSpecs.end());
1948 NewTypeSpecs.erase(std::unique(NewTypeSpecs.begin(), NewTypeSpecs.end()),
1949 NewTypeSpecs.end());
1950 auto &Entry = IntrinsicMap[Name];
1952 for (auto &I : NewTypeSpecs) {
1953 Entry.emplace_back(R, Name, Proto, I.first, I.second, CK, Body, *this,
1954 Guard, IsUnavailable, BigEndianSafe);
1955 Out.push_back(&Entry.back());
1958 CurrentRecord = nullptr;
1961 /// genBuiltinsDef: Generate the BuiltinsARM.def and BuiltinsAArch64.def
1962 /// declaration of builtins, checking for unique builtin declarations.
1963 void NeonEmitter::genBuiltinsDef(raw_ostream &OS,
1964 SmallVectorImpl<Intrinsic *> &Defs) {
1965 OS << "#ifdef GET_NEON_BUILTINS\n";
1967 // We only want to emit a builtin once, and we want to emit them in
1968 // alphabetical order, so use a std::set.
1969 std::set<std::string> Builtins;
1971 for (auto *Def : Defs) {
1974 // Functions with 'a' (the splat code) in the type prototype should not get
1975 // their own builtin as they use the non-splat variant.
1976 if (Def->hasSplat())
1979 std::string S = "BUILTIN(__builtin_neon_" + Def->getMangledName() + ", \"";
1981 S += Def->getBuiltinTypeStr();
1987 for (auto &S : Builtins)
1992 /// Generate the ARM and AArch64 overloaded type checking code for
1993 /// SemaChecking.cpp, checking for unique builtin declarations.
1994 void NeonEmitter::genOverloadTypeCheckCode(raw_ostream &OS,
1995 SmallVectorImpl<Intrinsic *> &Defs) {
1996 OS << "#ifdef GET_NEON_OVERLOAD_CHECK\n";
1998 // We record each overload check line before emitting because subsequent Inst
1999 // definitions may extend the number of permitted types (i.e. augment the
2000 // Mask). Use std::map to avoid sorting the table by hash number.
2001 struct OverloadInfo {
2005 OverloadInfo() : Mask(0ULL), PtrArgNum(0), HasConstPtr(false) {}
2007 std::map<std::string, OverloadInfo> OverloadMap;
2009 for (auto *Def : Defs) {
2010 // If the def has a body (that is, it has Operation DAGs), it won't call
2011 // __builtin_neon_* so we don't need to generate a definition for it.
2014 // Functions with 'a' (the splat code) in the type prototype should not get
2015 // their own builtin as they use the non-splat variant.
2016 if (Def->hasSplat())
2018 // Functions which have a scalar argument cannot be overloaded, no need to
2019 // check them if we are emitting the type checking code.
2020 if (Def->protoHasScalar())
2023 uint64_t Mask = 0ULL;
2024 Type Ty = Def->getReturnType();
2025 if (Def->getProto()[0] == 'v' ||
2026 isFloatingPointProtoModifier(Def->getProto()[0]))
2027 Ty = Def->getParamType(0);
2029 Ty = Def->getParamType(1);
2031 Mask |= 1ULL << Ty.getNeonEnum();
2033 // Check if the function has a pointer or const pointer argument.
2034 std::string Proto = Def->getProto();
2036 bool HasConstPtr = false;
2037 for (unsigned I = 0; I < Def->getNumParams(); ++I) {
2038 char ArgType = Proto[I + 1];
2039 if (ArgType == 'c') {
2044 if (ArgType == 'p') {
2049 // For sret builtins, adjust the pointer argument index.
2050 if (PtrArgNum >= 0 && Def->getReturnType().getNumVectors() > 1)
2053 std::string Name = Def->getName();
2054 // Omit type checking for the pointer arguments of vld1_lane, vld1_dup,
2055 // and vst1_lane intrinsics. Using a pointer to the vector element
2056 // type with one of those operations causes codegen to select an aligned
2057 // load/store instruction. If you want an unaligned operation,
2058 // the pointer argument needs to have less alignment than element type,
2059 // so just accept any pointer type.
2060 if (Name == "vld1_lane" || Name == "vld1_dup" || Name == "vst1_lane") {
2062 HasConstPtr = false;
2066 std::string Name = Def->getMangledName();
2067 OverloadMap.insert(std::make_pair(Name, OverloadInfo()));
2068 OverloadInfo &OI = OverloadMap[Name];
2070 OI.PtrArgNum |= PtrArgNum;
2071 OI.HasConstPtr = HasConstPtr;
2075 for (auto &I : OverloadMap) {
2076 OverloadInfo &OI = I.second;
2078 OS << "case NEON::BI__builtin_neon_" << I.first << ": ";
2079 OS << "mask = 0x" << utohexstr(OI.Mask) << "ULL";
2080 if (OI.PtrArgNum >= 0)
2081 OS << "; PtrArgNum = " << OI.PtrArgNum;
2083 OS << "; HasConstPtr = true";
2090 NeonEmitter::genIntrinsicRangeCheckCode(raw_ostream &OS,
2091 SmallVectorImpl<Intrinsic *> &Defs) {
2092 OS << "#ifdef GET_NEON_IMMEDIATE_CHECK\n";
2094 std::set<std::string> Emitted;
2096 for (auto *Def : Defs) {
2099 // Functions with 'a' (the splat code) in the type prototype should not get
2100 // their own builtin as they use the non-splat variant.
2101 if (Def->hasSplat())
2103 // Functions which do not have an immediate do not need to have range
2104 // checking code emitted.
2105 if (!Def->hasImmediate())
2107 if (Emitted.find(Def->getMangledName()) != Emitted.end())
2110 std::string LowerBound, UpperBound;
2112 Record *R = Def->getRecord();
2113 if (R->getValueAsBit("isVCVT_N")) {
2114 // VCVT between floating- and fixed-point values takes an immediate
2115 // in the range [1, 32) for f32 or [1, 64) for f64.
2117 if (Def->getBaseType().getElementSizeInBits() == 32)
2121 } else if (R->getValueAsBit("isScalarShift")) {
2122 // Right shifts have an 'r' in the name, left shifts do not. Convert
2123 // instructions have the same bounds and right shifts.
2124 if (Def->getName().find('r') != std::string::npos ||
2125 Def->getName().find("cvt") != std::string::npos)
2128 UpperBound = utostr(Def->getReturnType().getElementSizeInBits() - 1);
2129 } else if (R->getValueAsBit("isShift")) {
2130 // Builtins which are overloaded by type will need to have their upper
2131 // bound computed at Sema time based on the type constant.
2133 // Right shifts have an 'r' in the name, left shifts do not.
2134 if (Def->getName().find('r') != std::string::npos)
2136 UpperBound = "RFT(TV, true)";
2137 } else if (Def->getClassKind(true) == ClassB) {
2138 // ClassB intrinsics have a type (and hence lane number) that is only
2139 // known at runtime.
2140 if (R->getValueAsBit("isLaneQ"))
2141 UpperBound = "RFT(TV, false, true)";
2143 UpperBound = "RFT(TV, false, false)";
2145 // The immediate generally refers to a lane in the preceding argument.
2146 assert(Def->getImmediateIdx() > 0);
2147 Type T = Def->getParamType(Def->getImmediateIdx() - 1);
2148 UpperBound = utostr(T.getNumElements() - 1);
2151 // Calculate the index of the immediate that should be range checked.
2152 unsigned Idx = Def->getNumParams();
2153 if (Def->hasImmediate())
2154 Idx = Def->getGeneratedParamIdx(Def->getImmediateIdx());
2156 OS << "case NEON::BI__builtin_neon_" << Def->getMangledName() << ": "
2157 << "i = " << Idx << ";";
2158 if (LowerBound.size())
2159 OS << " l = " << LowerBound << ";";
2160 if (UpperBound.size())
2161 OS << " u = " << UpperBound << ";";
2164 Emitted.insert(Def->getMangledName());
2170 /// runHeader - Emit a file with sections defining:
2171 /// 1. the NEON section of BuiltinsARM.def and BuiltinsAArch64.def.
2172 /// 2. the SemaChecking code for the type overload checking.
2173 /// 3. the SemaChecking code for validation of intrinsic immediate arguments.
2174 void NeonEmitter::runHeader(raw_ostream &OS) {
2175 std::vector<Record *> RV = Records.getAllDerivedDefinitions("Inst");
2177 SmallVector<Intrinsic *, 128> Defs;
2179 createIntrinsic(R, Defs);
2181 // Generate shared BuiltinsXXX.def
2182 genBuiltinsDef(OS, Defs);
2184 // Generate ARM overloaded type checking code for SemaChecking.cpp
2185 genOverloadTypeCheckCode(OS, Defs);
2187 // Generate ARM range checking code for shift/lane immediates.
2188 genIntrinsicRangeCheckCode(OS, Defs);
2191 /// run - Read the records in arm_neon.td and output arm_neon.h. arm_neon.h
2192 /// is comprised of type definitions and function declarations.
2193 void NeonEmitter::run(raw_ostream &OS) {
2194 OS << "/*===---- arm_neon.h - ARM Neon intrinsics "
2195 "------------------------------"
2198 " * Permission is hereby granted, free of charge, to any person "
2201 " * of this software and associated documentation files (the "
2204 " * in the Software without restriction, including without limitation "
2207 " * to use, copy, modify, merge, publish, distribute, sublicense, "
2209 " * copies of the Software, and to permit persons to whom the Software "
2211 " * furnished to do so, subject to the following conditions:\n"
2213 " * The above copyright notice and this permission notice shall be "
2215 " * all copies or substantial portions of the Software.\n"
2217 " * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, "
2219 " * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF "
2220 "MERCHANTABILITY,\n"
2221 " * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT "
2223 " * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR "
2225 " * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, "
2227 " * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER "
2229 " * THE SOFTWARE.\n"
2231 " *===-----------------------------------------------------------------"
2236 OS << "#ifndef __ARM_NEON_H\n";
2237 OS << "#define __ARM_NEON_H\n\n";
2239 OS << "#if !defined(__ARM_NEON)\n";
2240 OS << "#error \"NEON support not enabled\"\n";
2243 OS << "#include <stdint.h>\n\n";
2245 // Emit NEON-specific scalar typedefs.
2246 OS << "typedef float float32_t;\n";
2247 OS << "typedef __fp16 float16_t;\n";
2249 OS << "#ifdef __aarch64__\n";
2250 OS << "typedef double float64_t;\n";
2253 // For now, signedness of polynomial types depends on target
2254 OS << "#ifdef __aarch64__\n";
2255 OS << "typedef uint8_t poly8_t;\n";
2256 OS << "typedef uint16_t poly16_t;\n";
2257 OS << "typedef uint64_t poly64_t;\n";
2258 OS << "typedef __uint128_t poly128_t;\n";
2260 OS << "typedef int8_t poly8_t;\n";
2261 OS << "typedef int16_t poly16_t;\n";
2264 // Emit Neon vector typedefs.
2265 std::string TypedefTypes(
2266 "cQcsQsiQilQlUcQUcUsQUsUiQUiUlQUlhQhfQfdQdPcQPcPsQPsPlQPl");
2267 std::vector<TypeSpec> TDTypeVec = TypeSpec::fromTypeSpecs(TypedefTypes);
2269 // Emit vector typedefs.
2270 bool InIfdef = false;
2271 for (auto &TS : TDTypeVec) {
2274 if (T.isDouble() || (T.isPoly() && T.isLong()))
2277 if (InIfdef && !IsA64) {
2281 if (!InIfdef && IsA64) {
2282 OS << "#ifdef __aarch64__\n";
2287 OS << "typedef __attribute__((neon_polyvector_type(";
2289 OS << "typedef __attribute__((neon_vector_type(";
2293 OS << utostr(T.getNumElements()) << "))) ";
2295 OS << " " << T.str() << ";\n";
2301 // Emit struct typedefs.
2303 for (unsigned NumMembers = 2; NumMembers <= 4; ++NumMembers) {
2304 for (auto &TS : TDTypeVec) {
2307 if (T.isDouble() || (T.isPoly() && T.isLong()))
2310 if (InIfdef && !IsA64) {
2314 if (!InIfdef && IsA64) {
2315 OS << "#ifdef __aarch64__\n";
2319 char M = '2' + (NumMembers - 2);
2321 OS << "typedef struct " << VT.str() << " {\n";
2322 OS << " " << T.str() << " val";
2323 OS << "[" << utostr(NumMembers) << "]";
2325 OS << VT.str() << ";\n";
2333 OS << "#define __ai static inline __attribute__((__always_inline__, "
2334 "__nodebug__))\n\n";
2336 SmallVector<Intrinsic *, 128> Defs;
2337 std::vector<Record *> RV = Records.getAllDerivedDefinitions("Inst");
2339 createIntrinsic(R, Defs);
2341 for (auto *I : Defs)
2345 Defs.begin(), Defs.end(),
2346 [](const Intrinsic *A, const Intrinsic *B) { return *A < *B; });
2348 // Only emit a def when its requirements have been met.
2349 // FIXME: This loop could be made faster, but it's fast enough for now.
2350 bool MadeProgress = true;
2351 std::string InGuard = "";
2352 while (!Defs.empty() && MadeProgress) {
2353 MadeProgress = false;
2355 for (SmallVector<Intrinsic *, 128>::iterator I = Defs.begin();
2356 I != Defs.end(); /*No step*/) {
2357 bool DependenciesSatisfied = true;
2358 for (auto *II : (*I)->getDependencies()) {
2359 if (std::find(Defs.begin(), Defs.end(), II) != Defs.end())
2360 DependenciesSatisfied = false;
2362 if (!DependenciesSatisfied) {
2363 // Try the next one.
2368 // Emit #endif/#if pair if needed.
2369 if ((*I)->getGuard() != InGuard) {
2370 if (!InGuard.empty())
2372 InGuard = (*I)->getGuard();
2373 if (!InGuard.empty())
2374 OS << "#if " << InGuard << "\n";
2377 // Actually generate the intrinsic code.
2378 OS << (*I)->generate();
2380 MadeProgress = true;
2384 assert(Defs.empty() && "Some requirements were not satisfied!");
2385 if (!InGuard.empty())
2389 OS << "#undef __ai\n\n";
2390 OS << "#endif /* __ARM_NEON_H */\n";
2394 void EmitNeon(RecordKeeper &Records, raw_ostream &OS) {
2395 NeonEmitter(Records).run(OS);
2397 void EmitNeonSema(RecordKeeper &Records, raw_ostream &OS) {
2398 NeonEmitter(Records).runHeader(OS);
2400 void EmitNeonTest(RecordKeeper &Records, raw_ostream &OS) {
2401 llvm_unreachable("Neon test generation no longer implemented!");
2403 } // End namespace clang