xref: /openbsd-src/gnu/llvm/clang/utils/TableGen/NeonEmitter.cpp (revision 12c855180aad702bbcca06e0398d774beeafb155)
1e5dd7070Spatrick //===- NeonEmitter.cpp - Generate arm_neon.h for use with clang -*- C++ -*-===//
2e5dd7070Spatrick //
3e5dd7070Spatrick // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4e5dd7070Spatrick // See https://llvm.org/LICENSE.txt for license information.
5e5dd7070Spatrick // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6e5dd7070Spatrick //
7e5dd7070Spatrick //===----------------------------------------------------------------------===//
8e5dd7070Spatrick //
9e5dd7070Spatrick // This tablegen backend is responsible for emitting arm_neon.h, which includes
10e5dd7070Spatrick // a declaration and definition of each function specified by the ARM NEON
11e5dd7070Spatrick // compiler interface.  See ARM document DUI0348B.
12e5dd7070Spatrick //
13e5dd7070Spatrick // Each NEON instruction is implemented in terms of 1 or more functions which
14e5dd7070Spatrick // are suffixed with the element type of the input vectors.  Functions may be
15e5dd7070Spatrick // implemented in terms of generic vector operations such as +, *, -, etc. or
16e5dd7070Spatrick // by calling a __builtin_-prefixed function which will be handled by clang's
17e5dd7070Spatrick // CodeGen library.
18e5dd7070Spatrick //
19e5dd7070Spatrick // Additional validation code can be generated by this file when runHeader() is
20e5dd7070Spatrick // called, rather than the normal run() entry point.
21e5dd7070Spatrick //
22e5dd7070Spatrick // See also the documentation in include/clang/Basic/arm_neon.td.
23e5dd7070Spatrick //
24e5dd7070Spatrick //===----------------------------------------------------------------------===//
25e5dd7070Spatrick 
26e5dd7070Spatrick #include "TableGenBackends.h"
27e5dd7070Spatrick #include "llvm/ADT/ArrayRef.h"
28e5dd7070Spatrick #include "llvm/ADT/DenseMap.h"
29e5dd7070Spatrick #include "llvm/ADT/STLExtras.h"
30ec727ea7Spatrick #include "llvm/ADT/SmallVector.h"
31e5dd7070Spatrick #include "llvm/ADT/StringExtras.h"
32e5dd7070Spatrick #include "llvm/ADT/StringRef.h"
33e5dd7070Spatrick #include "llvm/Support/Casting.h"
34e5dd7070Spatrick #include "llvm/Support/ErrorHandling.h"
35e5dd7070Spatrick #include "llvm/Support/raw_ostream.h"
36e5dd7070Spatrick #include "llvm/TableGen/Error.h"
37e5dd7070Spatrick #include "llvm/TableGen/Record.h"
38e5dd7070Spatrick #include "llvm/TableGen/SetTheory.h"
39e5dd7070Spatrick #include <algorithm>
40e5dd7070Spatrick #include <cassert>
41e5dd7070Spatrick #include <cctype>
42e5dd7070Spatrick #include <cstddef>
43e5dd7070Spatrick #include <cstdint>
44e5dd7070Spatrick #include <deque>
45e5dd7070Spatrick #include <map>
46*12c85518Srobert #include <optional>
47e5dd7070Spatrick #include <set>
48e5dd7070Spatrick #include <sstream>
49e5dd7070Spatrick #include <string>
50e5dd7070Spatrick #include <utility>
51e5dd7070Spatrick #include <vector>
52e5dd7070Spatrick 
53e5dd7070Spatrick using namespace llvm;
54e5dd7070Spatrick 
55e5dd7070Spatrick namespace {
56e5dd7070Spatrick 
57e5dd7070Spatrick // While globals are generally bad, this one allows us to perform assertions
58e5dd7070Spatrick // liberally and somehow still trace them back to the def they indirectly
59e5dd7070Spatrick // came from.
60e5dd7070Spatrick static Record *CurrentRecord = nullptr;
assert_with_loc(bool Assertion,const std::string & Str)61e5dd7070Spatrick static void assert_with_loc(bool Assertion, const std::string &Str) {
62e5dd7070Spatrick   if (!Assertion) {
63e5dd7070Spatrick     if (CurrentRecord)
64e5dd7070Spatrick       PrintFatalError(CurrentRecord->getLoc(), Str);
65e5dd7070Spatrick     else
66e5dd7070Spatrick       PrintFatalError(Str);
67e5dd7070Spatrick   }
68e5dd7070Spatrick }
69e5dd7070Spatrick 
70e5dd7070Spatrick enum ClassKind {
71e5dd7070Spatrick   ClassNone,
72e5dd7070Spatrick   ClassI,     // generic integer instruction, e.g., "i8" suffix
73e5dd7070Spatrick   ClassS,     // signed/unsigned/poly, e.g., "s8", "u8" or "p8" suffix
74e5dd7070Spatrick   ClassW,     // width-specific instruction, e.g., "8" suffix
75e5dd7070Spatrick   ClassB,     // bitcast arguments with enum argument to specify type
76e5dd7070Spatrick   ClassL,     // Logical instructions which are op instructions
77e5dd7070Spatrick               // but we need to not emit any suffix for in our
78e5dd7070Spatrick               // tests.
79e5dd7070Spatrick   ClassNoTest // Instructions which we do not test since they are
80e5dd7070Spatrick               // not TRUE instructions.
81e5dd7070Spatrick };
82e5dd7070Spatrick 
83e5dd7070Spatrick /// NeonTypeFlags - Flags to identify the types for overloaded Neon
84e5dd7070Spatrick /// builtins.  These must be kept in sync with the flags in
85e5dd7070Spatrick /// include/clang/Basic/TargetBuiltins.h.
86e5dd7070Spatrick namespace NeonTypeFlags {
87e5dd7070Spatrick 
88e5dd7070Spatrick enum { EltTypeMask = 0xf, UnsignedFlag = 0x10, QuadFlag = 0x20 };
89e5dd7070Spatrick 
90e5dd7070Spatrick enum EltType {
91e5dd7070Spatrick   Int8,
92e5dd7070Spatrick   Int16,
93e5dd7070Spatrick   Int32,
94e5dd7070Spatrick   Int64,
95e5dd7070Spatrick   Poly8,
96e5dd7070Spatrick   Poly16,
97e5dd7070Spatrick   Poly64,
98e5dd7070Spatrick   Poly128,
99e5dd7070Spatrick   Float16,
100e5dd7070Spatrick   Float32,
101ec727ea7Spatrick   Float64,
102ec727ea7Spatrick   BFloat16
103e5dd7070Spatrick };
104e5dd7070Spatrick 
105e5dd7070Spatrick } // end namespace NeonTypeFlags
106e5dd7070Spatrick 
107e5dd7070Spatrick class NeonEmitter;
108e5dd7070Spatrick 
109e5dd7070Spatrick //===----------------------------------------------------------------------===//
110e5dd7070Spatrick // TypeSpec
111e5dd7070Spatrick //===----------------------------------------------------------------------===//
112e5dd7070Spatrick 
113e5dd7070Spatrick /// A TypeSpec is just a simple wrapper around a string, but gets its own type
114e5dd7070Spatrick /// for strong typing purposes.
115e5dd7070Spatrick ///
116e5dd7070Spatrick /// A TypeSpec can be used to create a type.
117e5dd7070Spatrick class TypeSpec : public std::string {
118e5dd7070Spatrick public:
fromTypeSpecs(StringRef Str)119e5dd7070Spatrick   static std::vector<TypeSpec> fromTypeSpecs(StringRef Str) {
120e5dd7070Spatrick     std::vector<TypeSpec> Ret;
121e5dd7070Spatrick     TypeSpec Acc;
122e5dd7070Spatrick     for (char I : Str.str()) {
123e5dd7070Spatrick       if (islower(I)) {
124e5dd7070Spatrick         Acc.push_back(I);
125e5dd7070Spatrick         Ret.push_back(TypeSpec(Acc));
126e5dd7070Spatrick         Acc.clear();
127e5dd7070Spatrick       } else {
128e5dd7070Spatrick         Acc.push_back(I);
129e5dd7070Spatrick       }
130e5dd7070Spatrick     }
131e5dd7070Spatrick     return Ret;
132e5dd7070Spatrick   }
133e5dd7070Spatrick };
134e5dd7070Spatrick 
135e5dd7070Spatrick //===----------------------------------------------------------------------===//
136e5dd7070Spatrick // Type
137e5dd7070Spatrick //===----------------------------------------------------------------------===//
138e5dd7070Spatrick 
139e5dd7070Spatrick /// A Type. Not much more to say here.
140e5dd7070Spatrick class Type {
141e5dd7070Spatrick private:
142e5dd7070Spatrick   TypeSpec TS;
143e5dd7070Spatrick 
144e5dd7070Spatrick   enum TypeKind {
145e5dd7070Spatrick     Void,
146e5dd7070Spatrick     Float,
147e5dd7070Spatrick     SInt,
148e5dd7070Spatrick     UInt,
149e5dd7070Spatrick     Poly,
150ec727ea7Spatrick     BFloat16,
151e5dd7070Spatrick   };
152e5dd7070Spatrick   TypeKind Kind;
153e5dd7070Spatrick   bool Immediate, Constant, Pointer;
154e5dd7070Spatrick   // ScalarForMangling and NoManglingQ are really not suited to live here as
155e5dd7070Spatrick   // they are not related to the type. But they live in the TypeSpec (not the
156e5dd7070Spatrick   // prototype), so this is really the only place to store them.
157e5dd7070Spatrick   bool ScalarForMangling, NoManglingQ;
158e5dd7070Spatrick   unsigned Bitwidth, ElementBitwidth, NumVectors;
159e5dd7070Spatrick 
160e5dd7070Spatrick public:
Type()161e5dd7070Spatrick   Type()
162e5dd7070Spatrick       : Kind(Void), Immediate(false), Constant(false),
163e5dd7070Spatrick         Pointer(false), ScalarForMangling(false), NoManglingQ(false),
164e5dd7070Spatrick         Bitwidth(0), ElementBitwidth(0), NumVectors(0) {}
165e5dd7070Spatrick 
Type(TypeSpec TS,StringRef CharMods)166e5dd7070Spatrick   Type(TypeSpec TS, StringRef CharMods)
167e5dd7070Spatrick       : TS(std::move(TS)), Kind(Void), Immediate(false),
168e5dd7070Spatrick         Constant(false), Pointer(false), ScalarForMangling(false),
169e5dd7070Spatrick         NoManglingQ(false), Bitwidth(0), ElementBitwidth(0), NumVectors(0) {
170e5dd7070Spatrick     applyModifiers(CharMods);
171e5dd7070Spatrick   }
172e5dd7070Spatrick 
173e5dd7070Spatrick   /// Returns a type representing "void".
getVoid()174e5dd7070Spatrick   static Type getVoid() { return Type(); }
175e5dd7070Spatrick 
operator ==(const Type & Other) const176e5dd7070Spatrick   bool operator==(const Type &Other) const { return str() == Other.str(); }
operator !=(const Type & Other) const177e5dd7070Spatrick   bool operator!=(const Type &Other) const { return !operator==(Other); }
178e5dd7070Spatrick 
179e5dd7070Spatrick   //
180e5dd7070Spatrick   // Query functions
181e5dd7070Spatrick   //
isScalarForMangling() const182e5dd7070Spatrick   bool isScalarForMangling() const { return ScalarForMangling; }
noManglingQ() const183e5dd7070Spatrick   bool noManglingQ() const { return NoManglingQ; }
184e5dd7070Spatrick 
isPointer() const185e5dd7070Spatrick   bool isPointer() const { return Pointer; }
isValue() const186e5dd7070Spatrick   bool isValue() const { return !isVoid() && !isPointer(); }
isScalar() const187e5dd7070Spatrick   bool isScalar() const { return isValue() && NumVectors == 0; }
isVector() const188e5dd7070Spatrick   bool isVector() const { return isValue() && NumVectors > 0; }
isConstPointer() const189e5dd7070Spatrick   bool isConstPointer() const { return Constant; }
isFloating() const190e5dd7070Spatrick   bool isFloating() const { return Kind == Float; }
isInteger() const191e5dd7070Spatrick   bool isInteger() const { return Kind == SInt || Kind == UInt; }
isPoly() const192e5dd7070Spatrick   bool isPoly() const { return Kind == Poly; }
isSigned() const193e5dd7070Spatrick   bool isSigned() const { return Kind == SInt; }
isImmediate() const194e5dd7070Spatrick   bool isImmediate() const { return Immediate; }
isFloat() const195e5dd7070Spatrick   bool isFloat() const { return isFloating() && ElementBitwidth == 32; }
isDouble() const196e5dd7070Spatrick   bool isDouble() const { return isFloating() && ElementBitwidth == 64; }
isHalf() const197e5dd7070Spatrick   bool isHalf() const { return isFloating() && ElementBitwidth == 16; }
isChar() const198e5dd7070Spatrick   bool isChar() const { return ElementBitwidth == 8; }
isShort() const199e5dd7070Spatrick   bool isShort() const { return isInteger() && ElementBitwidth == 16; }
isInt() const200e5dd7070Spatrick   bool isInt() const { return isInteger() && ElementBitwidth == 32; }
isLong() const201e5dd7070Spatrick   bool isLong() const { return isInteger() && ElementBitwidth == 64; }
isVoid() const202e5dd7070Spatrick   bool isVoid() const { return Kind == Void; }
isBFloat16() const203ec727ea7Spatrick   bool isBFloat16() const { return Kind == BFloat16; }
getNumElements() const204e5dd7070Spatrick   unsigned getNumElements() const { return Bitwidth / ElementBitwidth; }
getSizeInBits() const205e5dd7070Spatrick   unsigned getSizeInBits() const { return Bitwidth; }
getElementSizeInBits() const206e5dd7070Spatrick   unsigned getElementSizeInBits() const { return ElementBitwidth; }
getNumVectors() const207e5dd7070Spatrick   unsigned getNumVectors() const { return NumVectors; }
208e5dd7070Spatrick 
209e5dd7070Spatrick   //
210e5dd7070Spatrick   // Mutator functions
211e5dd7070Spatrick   //
makeUnsigned()212e5dd7070Spatrick   void makeUnsigned() {
213e5dd7070Spatrick     assert(!isVoid() && "not a potentially signed type");
214e5dd7070Spatrick     Kind = UInt;
215e5dd7070Spatrick   }
makeSigned()216e5dd7070Spatrick   void makeSigned() {
217e5dd7070Spatrick     assert(!isVoid() && "not a potentially signed type");
218e5dd7070Spatrick     Kind = SInt;
219e5dd7070Spatrick   }
220e5dd7070Spatrick 
makeInteger(unsigned ElemWidth,bool Sign)221e5dd7070Spatrick   void makeInteger(unsigned ElemWidth, bool Sign) {
222e5dd7070Spatrick     assert(!isVoid() && "converting void to int probably not useful");
223e5dd7070Spatrick     Kind = Sign ? SInt : UInt;
224e5dd7070Spatrick     Immediate = false;
225e5dd7070Spatrick     ElementBitwidth = ElemWidth;
226e5dd7070Spatrick   }
227e5dd7070Spatrick 
makeImmediate(unsigned ElemWidth)228e5dd7070Spatrick   void makeImmediate(unsigned ElemWidth) {
229e5dd7070Spatrick     Kind = SInt;
230e5dd7070Spatrick     Immediate = true;
231e5dd7070Spatrick     ElementBitwidth = ElemWidth;
232e5dd7070Spatrick   }
233e5dd7070Spatrick 
makeScalar()234e5dd7070Spatrick   void makeScalar() {
235e5dd7070Spatrick     Bitwidth = ElementBitwidth;
236e5dd7070Spatrick     NumVectors = 0;
237e5dd7070Spatrick   }
238e5dd7070Spatrick 
makeOneVector()239e5dd7070Spatrick   void makeOneVector() {
240e5dd7070Spatrick     assert(isVector());
241e5dd7070Spatrick     NumVectors = 1;
242e5dd7070Spatrick   }
243e5dd7070Spatrick 
make32BitElement()244ec727ea7Spatrick   void make32BitElement() {
245ec727ea7Spatrick     assert_with_loc(Bitwidth > 32, "Not enough bits to make it 32!");
246ec727ea7Spatrick     ElementBitwidth = 32;
247ec727ea7Spatrick   }
248ec727ea7Spatrick 
doubleLanes()249e5dd7070Spatrick   void doubleLanes() {
250e5dd7070Spatrick     assert_with_loc(Bitwidth != 128, "Can't get bigger than 128!");
251e5dd7070Spatrick     Bitwidth = 128;
252e5dd7070Spatrick   }
253e5dd7070Spatrick 
halveLanes()254e5dd7070Spatrick   void halveLanes() {
255e5dd7070Spatrick     assert_with_loc(Bitwidth != 64, "Can't get smaller than 64!");
256e5dd7070Spatrick     Bitwidth = 64;
257e5dd7070Spatrick   }
258e5dd7070Spatrick 
259e5dd7070Spatrick   /// Return the C string representation of a type, which is the typename
260e5dd7070Spatrick   /// defined in stdint.h or arm_neon.h.
261e5dd7070Spatrick   std::string str() const;
262e5dd7070Spatrick 
263e5dd7070Spatrick   /// Return the string representation of a type, which is an encoded
264e5dd7070Spatrick   /// string for passing to the BUILTIN() macro in Builtins.def.
265e5dd7070Spatrick   std::string builtin_str() const;
266e5dd7070Spatrick 
267e5dd7070Spatrick   /// Return the value in NeonTypeFlags for this type.
268e5dd7070Spatrick   unsigned getNeonEnum() const;
269e5dd7070Spatrick 
270e5dd7070Spatrick   /// Parse a type from a stdint.h or arm_neon.h typedef name,
271e5dd7070Spatrick   /// for example uint32x2_t or int64_t.
272e5dd7070Spatrick   static Type fromTypedefName(StringRef Name);
273e5dd7070Spatrick 
274e5dd7070Spatrick private:
275e5dd7070Spatrick   /// Creates the type based on the typespec string in TS.
276e5dd7070Spatrick   /// Sets "Quad" to true if the "Q" or "H" modifiers were
277e5dd7070Spatrick   /// seen. This is needed by applyModifier as some modifiers
278e5dd7070Spatrick   /// only take effect if the type size was changed by "Q" or "H".
279e5dd7070Spatrick   void applyTypespec(bool &Quad);
280e5dd7070Spatrick   /// Applies prototype modifiers to the type.
281e5dd7070Spatrick   void applyModifiers(StringRef Mods);
282e5dd7070Spatrick };
283e5dd7070Spatrick 
284e5dd7070Spatrick //===----------------------------------------------------------------------===//
285e5dd7070Spatrick // Variable
286e5dd7070Spatrick //===----------------------------------------------------------------------===//
287e5dd7070Spatrick 
288e5dd7070Spatrick /// A variable is a simple class that just has a type and a name.
289e5dd7070Spatrick class Variable {
290e5dd7070Spatrick   Type T;
291e5dd7070Spatrick   std::string N;
292e5dd7070Spatrick 
293e5dd7070Spatrick public:
Variable()294*12c85518Srobert   Variable() : T(Type::getVoid()) {}
Variable(Type T,std::string N)295e5dd7070Spatrick   Variable(Type T, std::string N) : T(std::move(T)), N(std::move(N)) {}
296e5dd7070Spatrick 
getType() const297e5dd7070Spatrick   Type getType() const { return T; }
getName() const298e5dd7070Spatrick   std::string getName() const { return "__" + N; }
299e5dd7070Spatrick };
300e5dd7070Spatrick 
301e5dd7070Spatrick //===----------------------------------------------------------------------===//
302e5dd7070Spatrick // Intrinsic
303e5dd7070Spatrick //===----------------------------------------------------------------------===//
304e5dd7070Spatrick 
305e5dd7070Spatrick /// The main grunt class. This represents an instantiation of an intrinsic with
306e5dd7070Spatrick /// a particular typespec and prototype.
307e5dd7070Spatrick class Intrinsic {
308e5dd7070Spatrick   /// The Record this intrinsic was created from.
309e5dd7070Spatrick   Record *R;
310e5dd7070Spatrick   /// The unmangled name.
311e5dd7070Spatrick   std::string Name;
312e5dd7070Spatrick   /// The input and output typespecs. InTS == OutTS except when
313ec727ea7Spatrick   /// CartesianProductWith is non-empty - this is the case for vreinterpret.
314e5dd7070Spatrick   TypeSpec OutTS, InTS;
315e5dd7070Spatrick   /// The base class kind. Most intrinsics use ClassS, which has full type
316e5dd7070Spatrick   /// info for integers (s32/u32). Some use ClassI, which doesn't care about
317e5dd7070Spatrick   /// signedness (i32), while some (ClassB) have no type at all, only a width
318e5dd7070Spatrick   /// (32).
319e5dd7070Spatrick   ClassKind CK;
320e5dd7070Spatrick   /// The list of DAGs for the body. May be empty, in which case we should
321e5dd7070Spatrick   /// emit a builtin call.
322e5dd7070Spatrick   ListInit *Body;
323*12c85518Srobert   /// The architectural ifdef guard.
324*12c85518Srobert   std::string ArchGuard;
325*12c85518Srobert   /// The architectural target() guard.
326*12c85518Srobert   std::string TargetGuard;
327e5dd7070Spatrick   /// Set if the Unavailable bit is 1. This means we don't generate a body,
328e5dd7070Spatrick   /// just an "unavailable" attribute on a declaration.
329e5dd7070Spatrick   bool IsUnavailable;
330e5dd7070Spatrick   /// Is this intrinsic safe for big-endian? or does it need its arguments
331e5dd7070Spatrick   /// reversing?
332e5dd7070Spatrick   bool BigEndianSafe;
333e5dd7070Spatrick 
334e5dd7070Spatrick   /// The types of return value [0] and parameters [1..].
335e5dd7070Spatrick   std::vector<Type> Types;
336e5dd7070Spatrick   /// The index of the key type passed to CGBuiltin.cpp for polymorphic calls.
337e5dd7070Spatrick   int PolymorphicKeyType;
338e5dd7070Spatrick   /// The local variables defined.
339e5dd7070Spatrick   std::map<std::string, Variable> Variables;
340e5dd7070Spatrick   /// NeededEarly - set if any other intrinsic depends on this intrinsic.
341e5dd7070Spatrick   bool NeededEarly;
342e5dd7070Spatrick   /// UseMacro - set if we should implement using a macro or unset for a
343e5dd7070Spatrick   ///            function.
344e5dd7070Spatrick   bool UseMacro;
345e5dd7070Spatrick   /// The set of intrinsics that this intrinsic uses/requires.
346e5dd7070Spatrick   std::set<Intrinsic *> Dependencies;
347e5dd7070Spatrick   /// The "base type", which is Type('d', OutTS). InBaseType is only
348ec727ea7Spatrick   /// different if CartesianProductWith is non-empty (for vreinterpret).
349e5dd7070Spatrick   Type BaseType, InBaseType;
350e5dd7070Spatrick   /// The return variable.
351e5dd7070Spatrick   Variable RetVar;
352e5dd7070Spatrick   /// A postfix to apply to every variable. Defaults to "".
353e5dd7070Spatrick   std::string VariablePostfix;
354e5dd7070Spatrick 
355e5dd7070Spatrick   NeonEmitter &Emitter;
356e5dd7070Spatrick   std::stringstream OS;
357e5dd7070Spatrick 
isBigEndianSafe() const358e5dd7070Spatrick   bool isBigEndianSafe() const {
359e5dd7070Spatrick     if (BigEndianSafe)
360e5dd7070Spatrick       return true;
361e5dd7070Spatrick 
362e5dd7070Spatrick     for (const auto &T : Types){
363e5dd7070Spatrick       if (T.isVector() && T.getNumElements() > 1)
364e5dd7070Spatrick         return false;
365e5dd7070Spatrick     }
366e5dd7070Spatrick     return true;
367e5dd7070Spatrick   }
368e5dd7070Spatrick 
369e5dd7070Spatrick public:
Intrinsic(Record * R,StringRef Name,StringRef Proto,TypeSpec OutTS,TypeSpec InTS,ClassKind CK,ListInit * Body,NeonEmitter & Emitter,StringRef ArchGuard,StringRef TargetGuard,bool IsUnavailable,bool BigEndianSafe)370e5dd7070Spatrick   Intrinsic(Record *R, StringRef Name, StringRef Proto, TypeSpec OutTS,
371e5dd7070Spatrick             TypeSpec InTS, ClassKind CK, ListInit *Body, NeonEmitter &Emitter,
372*12c85518Srobert             StringRef ArchGuard, StringRef TargetGuard, bool IsUnavailable, bool BigEndianSafe)
373e5dd7070Spatrick       : R(R), Name(Name.str()), OutTS(OutTS), InTS(InTS), CK(CK), Body(Body),
374*12c85518Srobert         ArchGuard(ArchGuard.str()), TargetGuard(TargetGuard.str()), IsUnavailable(IsUnavailable),
375e5dd7070Spatrick         BigEndianSafe(BigEndianSafe), PolymorphicKeyType(0), NeededEarly(false),
376e5dd7070Spatrick         UseMacro(false), BaseType(OutTS, "."), InBaseType(InTS, "."),
377e5dd7070Spatrick         Emitter(Emitter) {
378e5dd7070Spatrick     // Modify the TypeSpec per-argument to get a concrete Type, and create
379e5dd7070Spatrick     // known variables for each.
380e5dd7070Spatrick     // Types[0] is the return value.
381e5dd7070Spatrick     unsigned Pos = 0;
382e5dd7070Spatrick     Types.emplace_back(OutTS, getNextModifiers(Proto, Pos));
383e5dd7070Spatrick     StringRef Mods = getNextModifiers(Proto, Pos);
384e5dd7070Spatrick     while (!Mods.empty()) {
385e5dd7070Spatrick       Types.emplace_back(InTS, Mods);
386*12c85518Srobert       if (Mods.contains('!'))
387e5dd7070Spatrick         PolymorphicKeyType = Types.size() - 1;
388e5dd7070Spatrick 
389e5dd7070Spatrick       Mods = getNextModifiers(Proto, Pos);
390e5dd7070Spatrick     }
391e5dd7070Spatrick 
392e5dd7070Spatrick     for (auto Type : Types) {
393e5dd7070Spatrick       // If this builtin takes an immediate argument, we need to #define it rather
394e5dd7070Spatrick       // than use a standard declaration, so that SemaChecking can range check
395e5dd7070Spatrick       // the immediate passed by the user.
396e5dd7070Spatrick 
397e5dd7070Spatrick       // Pointer arguments need to use macros to avoid hiding aligned attributes
398e5dd7070Spatrick       // from the pointer type.
399e5dd7070Spatrick 
400e5dd7070Spatrick       // It is not permitted to pass or return an __fp16 by value, so intrinsics
401e5dd7070Spatrick       // taking a scalar float16_t must be implemented as macros.
402e5dd7070Spatrick       if (Type.isImmediate() || Type.isPointer() ||
403e5dd7070Spatrick           (Type.isScalar() && Type.isHalf()))
404e5dd7070Spatrick         UseMacro = true;
405e5dd7070Spatrick     }
406e5dd7070Spatrick   }
407e5dd7070Spatrick 
408e5dd7070Spatrick   /// Get the Record that this intrinsic is based off.
getRecord() const409e5dd7070Spatrick   Record *getRecord() const { return R; }
410e5dd7070Spatrick   /// Get the set of Intrinsics that this intrinsic calls.
411e5dd7070Spatrick   /// this is the set of immediate dependencies, NOT the
412e5dd7070Spatrick   /// transitive closure.
getDependencies() const413e5dd7070Spatrick   const std::set<Intrinsic *> &getDependencies() const { return Dependencies; }
414e5dd7070Spatrick   /// Get the architectural guard string (#ifdef).
getArchGuard() const415*12c85518Srobert   std::string getArchGuard() const { return ArchGuard; }
getTargetGuard() const416*12c85518Srobert   std::string getTargetGuard() const { return TargetGuard; }
417e5dd7070Spatrick   /// Get the non-mangled name.
getName() const418e5dd7070Spatrick   std::string getName() const { return Name; }
419e5dd7070Spatrick 
420e5dd7070Spatrick   /// Return true if the intrinsic takes an immediate operand.
hasImmediate() const421e5dd7070Spatrick   bool hasImmediate() const {
422*12c85518Srobert     return llvm::any_of(Types, [](const Type &T) { return T.isImmediate(); });
423e5dd7070Spatrick   }
424e5dd7070Spatrick 
425e5dd7070Spatrick   /// Return the parameter index of the immediate operand.
getImmediateIdx() const426e5dd7070Spatrick   unsigned getImmediateIdx() const {
427e5dd7070Spatrick     for (unsigned Idx = 0; Idx < Types.size(); ++Idx)
428e5dd7070Spatrick       if (Types[Idx].isImmediate())
429e5dd7070Spatrick         return Idx - 1;
430e5dd7070Spatrick     llvm_unreachable("Intrinsic has no immediate");
431e5dd7070Spatrick   }
432e5dd7070Spatrick 
433e5dd7070Spatrick 
getNumParams() const434e5dd7070Spatrick   unsigned getNumParams() const { return Types.size() - 1; }
getReturnType() const435e5dd7070Spatrick   Type getReturnType() const { return Types[0]; }
getParamType(unsigned I) const436e5dd7070Spatrick   Type getParamType(unsigned I) const { return Types[I + 1]; }
getBaseType() const437e5dd7070Spatrick   Type getBaseType() const { return BaseType; }
getPolymorphicKeyType() const438e5dd7070Spatrick   Type getPolymorphicKeyType() const { return Types[PolymorphicKeyType]; }
439e5dd7070Spatrick 
440e5dd7070Spatrick   /// Return true if the prototype has a scalar argument.
441e5dd7070Spatrick   bool protoHasScalar() const;
442e5dd7070Spatrick 
443e5dd7070Spatrick   /// Return the index that parameter PIndex will sit at
444e5dd7070Spatrick   /// in a generated function call. This is often just PIndex,
445e5dd7070Spatrick   /// but may not be as things such as multiple-vector operands
446*12c85518Srobert   /// and sret parameters need to be taken into account.
getGeneratedParamIdx(unsigned PIndex)447e5dd7070Spatrick   unsigned getGeneratedParamIdx(unsigned PIndex) {
448e5dd7070Spatrick     unsigned Idx = 0;
449e5dd7070Spatrick     if (getReturnType().getNumVectors() > 1)
450e5dd7070Spatrick       // Multiple vectors are passed as sret.
451e5dd7070Spatrick       ++Idx;
452e5dd7070Spatrick 
453e5dd7070Spatrick     for (unsigned I = 0; I < PIndex; ++I)
454e5dd7070Spatrick       Idx += std::max(1U, getParamType(I).getNumVectors());
455e5dd7070Spatrick 
456e5dd7070Spatrick     return Idx;
457e5dd7070Spatrick   }
458e5dd7070Spatrick 
hasBody() const459e5dd7070Spatrick   bool hasBody() const { return Body && !Body->getValues().empty(); }
460e5dd7070Spatrick 
setNeededEarly()461e5dd7070Spatrick   void setNeededEarly() { NeededEarly = true; }
462e5dd7070Spatrick 
operator <(const Intrinsic & Other) const463e5dd7070Spatrick   bool operator<(const Intrinsic &Other) const {
464*12c85518Srobert     // Sort lexicographically on a three-tuple (ArchGuard, TargetGuard, Name)
465*12c85518Srobert     if (ArchGuard != Other.ArchGuard)
466*12c85518Srobert       return ArchGuard < Other.ArchGuard;
467*12c85518Srobert     if (TargetGuard != Other.TargetGuard)
468*12c85518Srobert       return TargetGuard < Other.TargetGuard;
469e5dd7070Spatrick     return Name < Other.Name;
470e5dd7070Spatrick   }
471e5dd7070Spatrick 
getClassKind(bool UseClassBIfScalar=false)472e5dd7070Spatrick   ClassKind getClassKind(bool UseClassBIfScalar = false) {
473e5dd7070Spatrick     if (UseClassBIfScalar && !protoHasScalar())
474e5dd7070Spatrick       return ClassB;
475e5dd7070Spatrick     return CK;
476e5dd7070Spatrick   }
477e5dd7070Spatrick 
478e5dd7070Spatrick   /// Return the name, mangled with type information.
479e5dd7070Spatrick   /// If ForceClassS is true, use ClassS (u32/s32) instead
480e5dd7070Spatrick   /// of the intrinsic's own type class.
481e5dd7070Spatrick   std::string getMangledName(bool ForceClassS = false) const;
482e5dd7070Spatrick   /// Return the type code for a builtin function call.
483e5dd7070Spatrick   std::string getInstTypeCode(Type T, ClassKind CK) const;
484e5dd7070Spatrick   /// Return the type string for a BUILTIN() macro in Builtins.def.
485e5dd7070Spatrick   std::string getBuiltinTypeStr();
486e5dd7070Spatrick 
487e5dd7070Spatrick   /// Generate the intrinsic, returning code.
488e5dd7070Spatrick   std::string generate();
489e5dd7070Spatrick   /// Perform type checking and populate the dependency graph, but
490e5dd7070Spatrick   /// don't generate code yet.
491e5dd7070Spatrick   void indexBody();
492e5dd7070Spatrick 
493e5dd7070Spatrick private:
494e5dd7070Spatrick   StringRef getNextModifiers(StringRef Proto, unsigned &Pos) const;
495e5dd7070Spatrick 
496e5dd7070Spatrick   std::string mangleName(std::string Name, ClassKind CK) const;
497e5dd7070Spatrick 
498e5dd7070Spatrick   void initVariables();
499e5dd7070Spatrick   std::string replaceParamsIn(std::string S);
500e5dd7070Spatrick 
501e5dd7070Spatrick   void emitBodyAsBuiltinCall();
502e5dd7070Spatrick 
503e5dd7070Spatrick   void generateImpl(bool ReverseArguments,
504e5dd7070Spatrick                     StringRef NamePrefix, StringRef CallPrefix);
505e5dd7070Spatrick   void emitReturn();
506e5dd7070Spatrick   void emitBody(StringRef CallPrefix);
507e5dd7070Spatrick   void emitShadowedArgs();
508e5dd7070Spatrick   void emitArgumentReversal();
509*12c85518Srobert   void emitReturnVarDecl();
510e5dd7070Spatrick   void emitReturnReversal();
511e5dd7070Spatrick   void emitReverseVariable(Variable &Dest, Variable &Src);
512e5dd7070Spatrick   void emitNewLine();
513e5dd7070Spatrick   void emitClosingBrace();
514e5dd7070Spatrick   void emitOpeningBrace();
515e5dd7070Spatrick   void emitPrototype(StringRef NamePrefix);
516e5dd7070Spatrick 
517e5dd7070Spatrick   class DagEmitter {
518e5dd7070Spatrick     Intrinsic &Intr;
519e5dd7070Spatrick     StringRef CallPrefix;
520e5dd7070Spatrick 
521e5dd7070Spatrick   public:
DagEmitter(Intrinsic & Intr,StringRef CallPrefix)522e5dd7070Spatrick     DagEmitter(Intrinsic &Intr, StringRef CallPrefix) :
523e5dd7070Spatrick       Intr(Intr), CallPrefix(CallPrefix) {
524e5dd7070Spatrick     }
525e5dd7070Spatrick     std::pair<Type, std::string> emitDagArg(Init *Arg, std::string ArgName);
526e5dd7070Spatrick     std::pair<Type, std::string> emitDagSaveTemp(DagInit *DI);
527e5dd7070Spatrick     std::pair<Type, std::string> emitDagSplat(DagInit *DI);
528e5dd7070Spatrick     std::pair<Type, std::string> emitDagDup(DagInit *DI);
529e5dd7070Spatrick     std::pair<Type, std::string> emitDagDupTyped(DagInit *DI);
530e5dd7070Spatrick     std::pair<Type, std::string> emitDagShuffle(DagInit *DI);
531e5dd7070Spatrick     std::pair<Type, std::string> emitDagCast(DagInit *DI, bool IsBitCast);
532ec727ea7Spatrick     std::pair<Type, std::string> emitDagCall(DagInit *DI,
533ec727ea7Spatrick                                              bool MatchMangledName);
534e5dd7070Spatrick     std::pair<Type, std::string> emitDagNameReplace(DagInit *DI);
535e5dd7070Spatrick     std::pair<Type, std::string> emitDagLiteral(DagInit *DI);
536e5dd7070Spatrick     std::pair<Type, std::string> emitDagOp(DagInit *DI);
537e5dd7070Spatrick     std::pair<Type, std::string> emitDag(DagInit *DI);
538e5dd7070Spatrick   };
539e5dd7070Spatrick };
540e5dd7070Spatrick 
541e5dd7070Spatrick //===----------------------------------------------------------------------===//
542e5dd7070Spatrick // NeonEmitter
543e5dd7070Spatrick //===----------------------------------------------------------------------===//
544e5dd7070Spatrick 
545e5dd7070Spatrick class NeonEmitter {
546e5dd7070Spatrick   RecordKeeper &Records;
547e5dd7070Spatrick   DenseMap<Record *, ClassKind> ClassMap;
548e5dd7070Spatrick   std::map<std::string, std::deque<Intrinsic>> IntrinsicMap;
549e5dd7070Spatrick   unsigned UniqueNumber;
550e5dd7070Spatrick 
551e5dd7070Spatrick   void createIntrinsic(Record *R, SmallVectorImpl<Intrinsic *> &Out);
552e5dd7070Spatrick   void genBuiltinsDef(raw_ostream &OS, SmallVectorImpl<Intrinsic *> &Defs);
553e5dd7070Spatrick   void genOverloadTypeCheckCode(raw_ostream &OS,
554e5dd7070Spatrick                                 SmallVectorImpl<Intrinsic *> &Defs);
555e5dd7070Spatrick   void genIntrinsicRangeCheckCode(raw_ostream &OS,
556e5dd7070Spatrick                                   SmallVectorImpl<Intrinsic *> &Defs);
557e5dd7070Spatrick 
558e5dd7070Spatrick public:
559e5dd7070Spatrick   /// Called by Intrinsic - this attempts to get an intrinsic that takes
560e5dd7070Spatrick   /// the given types as arguments.
561ec727ea7Spatrick   Intrinsic &getIntrinsic(StringRef Name, ArrayRef<Type> Types,
562*12c85518Srobert                           std::optional<std::string> MangledName);
563e5dd7070Spatrick 
564e5dd7070Spatrick   /// Called by Intrinsic - returns a globally-unique number.
getUniqueNumber()565e5dd7070Spatrick   unsigned getUniqueNumber() { return UniqueNumber++; }
566e5dd7070Spatrick 
NeonEmitter(RecordKeeper & R)567e5dd7070Spatrick   NeonEmitter(RecordKeeper &R) : Records(R), UniqueNumber(0) {
568e5dd7070Spatrick     Record *SI = R.getClass("SInst");
569e5dd7070Spatrick     Record *II = R.getClass("IInst");
570e5dd7070Spatrick     Record *WI = R.getClass("WInst");
571e5dd7070Spatrick     Record *SOpI = R.getClass("SOpInst");
572e5dd7070Spatrick     Record *IOpI = R.getClass("IOpInst");
573e5dd7070Spatrick     Record *WOpI = R.getClass("WOpInst");
574e5dd7070Spatrick     Record *LOpI = R.getClass("LOpInst");
575e5dd7070Spatrick     Record *NoTestOpI = R.getClass("NoTestOpInst");
576e5dd7070Spatrick 
577e5dd7070Spatrick     ClassMap[SI] = ClassS;
578e5dd7070Spatrick     ClassMap[II] = ClassI;
579e5dd7070Spatrick     ClassMap[WI] = ClassW;
580e5dd7070Spatrick     ClassMap[SOpI] = ClassS;
581e5dd7070Spatrick     ClassMap[IOpI] = ClassI;
582e5dd7070Spatrick     ClassMap[WOpI] = ClassW;
583e5dd7070Spatrick     ClassMap[LOpI] = ClassL;
584e5dd7070Spatrick     ClassMap[NoTestOpI] = ClassNoTest;
585e5dd7070Spatrick   }
586e5dd7070Spatrick 
587a9ac8606Spatrick   // Emit arm_neon.h.inc
588e5dd7070Spatrick   void run(raw_ostream &o);
589e5dd7070Spatrick 
590a9ac8606Spatrick   // Emit arm_fp16.h.inc
591e5dd7070Spatrick   void runFP16(raw_ostream &o);
592e5dd7070Spatrick 
593a9ac8606Spatrick   // Emit arm_bf16.h.inc
594ec727ea7Spatrick   void runBF16(raw_ostream &o);
595ec727ea7Spatrick 
596a9ac8606Spatrick   // Emit all the __builtin prototypes used in arm_neon.h, arm_fp16.h and
597a9ac8606Spatrick   // arm_bf16.h
598e5dd7070Spatrick   void runHeader(raw_ostream &o);
599e5dd7070Spatrick };
600e5dd7070Spatrick 
601e5dd7070Spatrick } // end anonymous namespace
602e5dd7070Spatrick 
603e5dd7070Spatrick //===----------------------------------------------------------------------===//
604e5dd7070Spatrick // Type implementation
605e5dd7070Spatrick //===----------------------------------------------------------------------===//
606e5dd7070Spatrick 
str() const607e5dd7070Spatrick std::string Type::str() const {
608e5dd7070Spatrick   if (isVoid())
609e5dd7070Spatrick     return "void";
610e5dd7070Spatrick   std::string S;
611e5dd7070Spatrick 
612e5dd7070Spatrick   if (isInteger() && !isSigned())
613e5dd7070Spatrick     S += "u";
614e5dd7070Spatrick 
615e5dd7070Spatrick   if (isPoly())
616e5dd7070Spatrick     S += "poly";
617e5dd7070Spatrick   else if (isFloating())
618e5dd7070Spatrick     S += "float";
619ec727ea7Spatrick   else if (isBFloat16())
620ec727ea7Spatrick     S += "bfloat";
621e5dd7070Spatrick   else
622e5dd7070Spatrick     S += "int";
623e5dd7070Spatrick 
624e5dd7070Spatrick   S += utostr(ElementBitwidth);
625e5dd7070Spatrick   if (isVector())
626e5dd7070Spatrick     S += "x" + utostr(getNumElements());
627e5dd7070Spatrick   if (NumVectors > 1)
628e5dd7070Spatrick     S += "x" + utostr(NumVectors);
629e5dd7070Spatrick   S += "_t";
630e5dd7070Spatrick 
631e5dd7070Spatrick   if (Constant)
632e5dd7070Spatrick     S += " const";
633e5dd7070Spatrick   if (Pointer)
634e5dd7070Spatrick     S += " *";
635e5dd7070Spatrick 
636e5dd7070Spatrick   return S;
637e5dd7070Spatrick }
638e5dd7070Spatrick 
builtin_str() const639e5dd7070Spatrick std::string Type::builtin_str() const {
640e5dd7070Spatrick   std::string S;
641e5dd7070Spatrick   if (isVoid())
642e5dd7070Spatrick     return "v";
643e5dd7070Spatrick 
644e5dd7070Spatrick   if (isPointer()) {
645e5dd7070Spatrick     // All pointers are void pointers.
646e5dd7070Spatrick     S = "v";
647e5dd7070Spatrick     if (isConstPointer())
648e5dd7070Spatrick       S += "C";
649e5dd7070Spatrick     S += "*";
650e5dd7070Spatrick     return S;
651e5dd7070Spatrick   } else if (isInteger())
652e5dd7070Spatrick     switch (ElementBitwidth) {
653e5dd7070Spatrick     case 8: S += "c"; break;
654e5dd7070Spatrick     case 16: S += "s"; break;
655e5dd7070Spatrick     case 32: S += "i"; break;
656e5dd7070Spatrick     case 64: S += "Wi"; break;
657e5dd7070Spatrick     case 128: S += "LLLi"; break;
658e5dd7070Spatrick     default: llvm_unreachable("Unhandled case!");
659e5dd7070Spatrick     }
660ec727ea7Spatrick   else if (isBFloat16()) {
661ec727ea7Spatrick     assert(ElementBitwidth == 16 && "BFloat16 can only be 16 bits");
662ec727ea7Spatrick     S += "y";
663ec727ea7Spatrick   } else
664e5dd7070Spatrick     switch (ElementBitwidth) {
665e5dd7070Spatrick     case 16: S += "h"; break;
666e5dd7070Spatrick     case 32: S += "f"; break;
667e5dd7070Spatrick     case 64: S += "d"; break;
668e5dd7070Spatrick     default: llvm_unreachable("Unhandled case!");
669e5dd7070Spatrick     }
670e5dd7070Spatrick 
671e5dd7070Spatrick   // FIXME: NECESSARY???????????????????????????????????????????????????????????????????????
672e5dd7070Spatrick   if (isChar() && !isPointer() && isSigned())
673e5dd7070Spatrick     // Make chars explicitly signed.
674e5dd7070Spatrick     S = "S" + S;
675e5dd7070Spatrick   else if (isInteger() && !isSigned())
676e5dd7070Spatrick     S = "U" + S;
677e5dd7070Spatrick 
678e5dd7070Spatrick   // Constant indices are "int", but have the "constant expression" modifier.
679e5dd7070Spatrick   if (isImmediate()) {
680e5dd7070Spatrick     assert(isInteger() && isSigned());
681e5dd7070Spatrick     S = "I" + S;
682e5dd7070Spatrick   }
683e5dd7070Spatrick 
684e5dd7070Spatrick   if (isScalar())
685e5dd7070Spatrick     return S;
686e5dd7070Spatrick 
687e5dd7070Spatrick   std::string Ret;
688e5dd7070Spatrick   for (unsigned I = 0; I < NumVectors; ++I)
689e5dd7070Spatrick     Ret += "V" + utostr(getNumElements()) + S;
690e5dd7070Spatrick 
691e5dd7070Spatrick   return Ret;
692e5dd7070Spatrick }
693e5dd7070Spatrick 
getNeonEnum() const694e5dd7070Spatrick unsigned Type::getNeonEnum() const {
695e5dd7070Spatrick   unsigned Addend;
696e5dd7070Spatrick   switch (ElementBitwidth) {
697e5dd7070Spatrick   case 8: Addend = 0; break;
698e5dd7070Spatrick   case 16: Addend = 1; break;
699e5dd7070Spatrick   case 32: Addend = 2; break;
700e5dd7070Spatrick   case 64: Addend = 3; break;
701e5dd7070Spatrick   case 128: Addend = 4; break;
702e5dd7070Spatrick   default: llvm_unreachable("Unhandled element bitwidth!");
703e5dd7070Spatrick   }
704e5dd7070Spatrick 
705e5dd7070Spatrick   unsigned Base = (unsigned)NeonTypeFlags::Int8 + Addend;
706e5dd7070Spatrick   if (isPoly()) {
707e5dd7070Spatrick     // Adjustment needed because Poly32 doesn't exist.
708e5dd7070Spatrick     if (Addend >= 2)
709e5dd7070Spatrick       --Addend;
710e5dd7070Spatrick     Base = (unsigned)NeonTypeFlags::Poly8 + Addend;
711e5dd7070Spatrick   }
712e5dd7070Spatrick   if (isFloating()) {
713e5dd7070Spatrick     assert(Addend != 0 && "Float8 doesn't exist!");
714e5dd7070Spatrick     Base = (unsigned)NeonTypeFlags::Float16 + (Addend - 1);
715e5dd7070Spatrick   }
716e5dd7070Spatrick 
717ec727ea7Spatrick   if (isBFloat16()) {
718ec727ea7Spatrick     assert(Addend == 1 && "BFloat16 is only 16 bit");
719ec727ea7Spatrick     Base = (unsigned)NeonTypeFlags::BFloat16;
720ec727ea7Spatrick   }
721ec727ea7Spatrick 
722e5dd7070Spatrick   if (Bitwidth == 128)
723e5dd7070Spatrick     Base |= (unsigned)NeonTypeFlags::QuadFlag;
724e5dd7070Spatrick   if (isInteger() && !isSigned())
725e5dd7070Spatrick     Base |= (unsigned)NeonTypeFlags::UnsignedFlag;
726e5dd7070Spatrick 
727e5dd7070Spatrick   return Base;
728e5dd7070Spatrick }
729e5dd7070Spatrick 
fromTypedefName(StringRef Name)730e5dd7070Spatrick Type Type::fromTypedefName(StringRef Name) {
731e5dd7070Spatrick   Type T;
732e5dd7070Spatrick   T.Kind = SInt;
733e5dd7070Spatrick 
734e5dd7070Spatrick   if (Name.front() == 'u') {
735e5dd7070Spatrick     T.Kind = UInt;
736e5dd7070Spatrick     Name = Name.drop_front();
737e5dd7070Spatrick   }
738e5dd7070Spatrick 
739e5dd7070Spatrick   if (Name.startswith("float")) {
740e5dd7070Spatrick     T.Kind = Float;
741e5dd7070Spatrick     Name = Name.drop_front(5);
742e5dd7070Spatrick   } else if (Name.startswith("poly")) {
743e5dd7070Spatrick     T.Kind = Poly;
744e5dd7070Spatrick     Name = Name.drop_front(4);
745ec727ea7Spatrick   } else if (Name.startswith("bfloat")) {
746ec727ea7Spatrick     T.Kind = BFloat16;
747ec727ea7Spatrick     Name = Name.drop_front(6);
748e5dd7070Spatrick   } else {
749e5dd7070Spatrick     assert(Name.startswith("int"));
750e5dd7070Spatrick     Name = Name.drop_front(3);
751e5dd7070Spatrick   }
752e5dd7070Spatrick 
753e5dd7070Spatrick   unsigned I = 0;
754e5dd7070Spatrick   for (I = 0; I < Name.size(); ++I) {
755e5dd7070Spatrick     if (!isdigit(Name[I]))
756e5dd7070Spatrick       break;
757e5dd7070Spatrick   }
758e5dd7070Spatrick   Name.substr(0, I).getAsInteger(10, T.ElementBitwidth);
759e5dd7070Spatrick   Name = Name.drop_front(I);
760e5dd7070Spatrick 
761e5dd7070Spatrick   T.Bitwidth = T.ElementBitwidth;
762e5dd7070Spatrick   T.NumVectors = 1;
763e5dd7070Spatrick 
764e5dd7070Spatrick   if (Name.front() == 'x') {
765e5dd7070Spatrick     Name = Name.drop_front();
766e5dd7070Spatrick     unsigned I = 0;
767e5dd7070Spatrick     for (I = 0; I < Name.size(); ++I) {
768e5dd7070Spatrick       if (!isdigit(Name[I]))
769e5dd7070Spatrick         break;
770e5dd7070Spatrick     }
771e5dd7070Spatrick     unsigned NumLanes;
772e5dd7070Spatrick     Name.substr(0, I).getAsInteger(10, NumLanes);
773e5dd7070Spatrick     Name = Name.drop_front(I);
774e5dd7070Spatrick     T.Bitwidth = T.ElementBitwidth * NumLanes;
775e5dd7070Spatrick   } else {
776e5dd7070Spatrick     // Was scalar.
777e5dd7070Spatrick     T.NumVectors = 0;
778e5dd7070Spatrick   }
779e5dd7070Spatrick   if (Name.front() == 'x') {
780e5dd7070Spatrick     Name = Name.drop_front();
781e5dd7070Spatrick     unsigned I = 0;
782e5dd7070Spatrick     for (I = 0; I < Name.size(); ++I) {
783e5dd7070Spatrick       if (!isdigit(Name[I]))
784e5dd7070Spatrick         break;
785e5dd7070Spatrick     }
786e5dd7070Spatrick     Name.substr(0, I).getAsInteger(10, T.NumVectors);
787e5dd7070Spatrick     Name = Name.drop_front(I);
788e5dd7070Spatrick   }
789e5dd7070Spatrick 
790e5dd7070Spatrick   assert(Name.startswith("_t") && "Malformed typedef!");
791e5dd7070Spatrick   return T;
792e5dd7070Spatrick }
793e5dd7070Spatrick 
applyTypespec(bool & Quad)794e5dd7070Spatrick void Type::applyTypespec(bool &Quad) {
795e5dd7070Spatrick   std::string S = TS;
796e5dd7070Spatrick   ScalarForMangling = false;
797e5dd7070Spatrick   Kind = SInt;
798e5dd7070Spatrick   ElementBitwidth = ~0U;
799e5dd7070Spatrick   NumVectors = 1;
800e5dd7070Spatrick 
801e5dd7070Spatrick   for (char I : S) {
802e5dd7070Spatrick     switch (I) {
803e5dd7070Spatrick     case 'S':
804e5dd7070Spatrick       ScalarForMangling = true;
805e5dd7070Spatrick       break;
806e5dd7070Spatrick     case 'H':
807e5dd7070Spatrick       NoManglingQ = true;
808e5dd7070Spatrick       Quad = true;
809e5dd7070Spatrick       break;
810e5dd7070Spatrick     case 'Q':
811e5dd7070Spatrick       Quad = true;
812e5dd7070Spatrick       break;
813e5dd7070Spatrick     case 'P':
814e5dd7070Spatrick       Kind = Poly;
815e5dd7070Spatrick       break;
816e5dd7070Spatrick     case 'U':
817e5dd7070Spatrick       Kind = UInt;
818e5dd7070Spatrick       break;
819e5dd7070Spatrick     case 'c':
820e5dd7070Spatrick       ElementBitwidth = 8;
821e5dd7070Spatrick       break;
822e5dd7070Spatrick     case 'h':
823e5dd7070Spatrick       Kind = Float;
824*12c85518Srobert       [[fallthrough]];
825e5dd7070Spatrick     case 's':
826e5dd7070Spatrick       ElementBitwidth = 16;
827e5dd7070Spatrick       break;
828e5dd7070Spatrick     case 'f':
829e5dd7070Spatrick       Kind = Float;
830*12c85518Srobert       [[fallthrough]];
831e5dd7070Spatrick     case 'i':
832e5dd7070Spatrick       ElementBitwidth = 32;
833e5dd7070Spatrick       break;
834e5dd7070Spatrick     case 'd':
835e5dd7070Spatrick       Kind = Float;
836*12c85518Srobert       [[fallthrough]];
837e5dd7070Spatrick     case 'l':
838e5dd7070Spatrick       ElementBitwidth = 64;
839e5dd7070Spatrick       break;
840e5dd7070Spatrick     case 'k':
841e5dd7070Spatrick       ElementBitwidth = 128;
842e5dd7070Spatrick       // Poly doesn't have a 128x1 type.
843e5dd7070Spatrick       if (isPoly())
844e5dd7070Spatrick         NumVectors = 0;
845e5dd7070Spatrick       break;
846ec727ea7Spatrick     case 'b':
847ec727ea7Spatrick       Kind = BFloat16;
848ec727ea7Spatrick       ElementBitwidth = 16;
849ec727ea7Spatrick       break;
850e5dd7070Spatrick     default:
851e5dd7070Spatrick       llvm_unreachable("Unhandled type code!");
852e5dd7070Spatrick     }
853e5dd7070Spatrick   }
854e5dd7070Spatrick   assert(ElementBitwidth != ~0U && "Bad element bitwidth!");
855e5dd7070Spatrick 
856e5dd7070Spatrick   Bitwidth = Quad ? 128 : 64;
857e5dd7070Spatrick }
858e5dd7070Spatrick 
applyModifiers(StringRef Mods)859e5dd7070Spatrick void Type::applyModifiers(StringRef Mods) {
860e5dd7070Spatrick   bool AppliedQuad = false;
861e5dd7070Spatrick   applyTypespec(AppliedQuad);
862e5dd7070Spatrick 
863e5dd7070Spatrick   for (char Mod : Mods) {
864e5dd7070Spatrick     switch (Mod) {
865e5dd7070Spatrick     case '.':
866e5dd7070Spatrick       break;
867e5dd7070Spatrick     case 'v':
868e5dd7070Spatrick       Kind = Void;
869e5dd7070Spatrick       break;
870e5dd7070Spatrick     case 'S':
871e5dd7070Spatrick       Kind = SInt;
872e5dd7070Spatrick       break;
873e5dd7070Spatrick     case 'U':
874e5dd7070Spatrick       Kind = UInt;
875e5dd7070Spatrick       break;
876ec727ea7Spatrick     case 'B':
877ec727ea7Spatrick       Kind = BFloat16;
878ec727ea7Spatrick       ElementBitwidth = 16;
879ec727ea7Spatrick       break;
880e5dd7070Spatrick     case 'F':
881e5dd7070Spatrick       Kind = Float;
882e5dd7070Spatrick       break;
883e5dd7070Spatrick     case 'P':
884e5dd7070Spatrick       Kind = Poly;
885e5dd7070Spatrick       break;
886e5dd7070Spatrick     case '>':
887e5dd7070Spatrick       assert(ElementBitwidth < 128);
888e5dd7070Spatrick       ElementBitwidth *= 2;
889e5dd7070Spatrick       break;
890e5dd7070Spatrick     case '<':
891e5dd7070Spatrick       assert(ElementBitwidth > 8);
892e5dd7070Spatrick       ElementBitwidth /= 2;
893e5dd7070Spatrick       break;
894e5dd7070Spatrick     case '1':
895e5dd7070Spatrick       NumVectors = 0;
896e5dd7070Spatrick       break;
897e5dd7070Spatrick     case '2':
898e5dd7070Spatrick       NumVectors = 2;
899e5dd7070Spatrick       break;
900e5dd7070Spatrick     case '3':
901e5dd7070Spatrick       NumVectors = 3;
902e5dd7070Spatrick       break;
903e5dd7070Spatrick     case '4':
904e5dd7070Spatrick       NumVectors = 4;
905e5dd7070Spatrick       break;
906e5dd7070Spatrick     case '*':
907e5dd7070Spatrick       Pointer = true;
908e5dd7070Spatrick       break;
909e5dd7070Spatrick     case 'c':
910e5dd7070Spatrick       Constant = true;
911e5dd7070Spatrick       break;
912e5dd7070Spatrick     case 'Q':
913e5dd7070Spatrick       Bitwidth = 128;
914e5dd7070Spatrick       break;
915e5dd7070Spatrick     case 'q':
916e5dd7070Spatrick       Bitwidth = 64;
917e5dd7070Spatrick       break;
918e5dd7070Spatrick     case 'I':
919e5dd7070Spatrick       Kind = SInt;
920e5dd7070Spatrick       ElementBitwidth = Bitwidth = 32;
921e5dd7070Spatrick       NumVectors = 0;
922e5dd7070Spatrick       Immediate = true;
923e5dd7070Spatrick       break;
924e5dd7070Spatrick     case 'p':
925e5dd7070Spatrick       if (isPoly())
926e5dd7070Spatrick         Kind = UInt;
927e5dd7070Spatrick       break;
928e5dd7070Spatrick     case '!':
929e5dd7070Spatrick       // Key type, handled elsewhere.
930e5dd7070Spatrick       break;
931e5dd7070Spatrick     default:
932e5dd7070Spatrick       llvm_unreachable("Unhandled character!");
933e5dd7070Spatrick     }
934e5dd7070Spatrick   }
935e5dd7070Spatrick }
936e5dd7070Spatrick 
937e5dd7070Spatrick //===----------------------------------------------------------------------===//
938e5dd7070Spatrick // Intrinsic implementation
939e5dd7070Spatrick //===----------------------------------------------------------------------===//
940e5dd7070Spatrick 
getNextModifiers(StringRef Proto,unsigned & Pos) const941e5dd7070Spatrick StringRef Intrinsic::getNextModifiers(StringRef Proto, unsigned &Pos) const {
942e5dd7070Spatrick   if (Proto.size() == Pos)
943e5dd7070Spatrick     return StringRef();
944e5dd7070Spatrick   else if (Proto[Pos] != '(')
945e5dd7070Spatrick     return Proto.substr(Pos++, 1);
946e5dd7070Spatrick 
947e5dd7070Spatrick   size_t Start = Pos + 1;
948e5dd7070Spatrick   size_t End = Proto.find(')', Start);
949e5dd7070Spatrick   assert_with_loc(End != StringRef::npos, "unmatched modifier group paren");
950e5dd7070Spatrick   Pos = End + 1;
951e5dd7070Spatrick   return Proto.slice(Start, End);
952e5dd7070Spatrick }
953e5dd7070Spatrick 
getInstTypeCode(Type T,ClassKind CK) const954e5dd7070Spatrick std::string Intrinsic::getInstTypeCode(Type T, ClassKind CK) const {
955e5dd7070Spatrick   char typeCode = '\0';
956e5dd7070Spatrick   bool printNumber = true;
957e5dd7070Spatrick 
958*12c85518Srobert   if (CK == ClassB && TargetGuard == "")
959e5dd7070Spatrick     return "";
960e5dd7070Spatrick 
961ec727ea7Spatrick   if (T.isBFloat16())
962ec727ea7Spatrick     return "bf16";
963ec727ea7Spatrick 
964e5dd7070Spatrick   if (T.isPoly())
965e5dd7070Spatrick     typeCode = 'p';
966e5dd7070Spatrick   else if (T.isInteger())
967e5dd7070Spatrick     typeCode = T.isSigned() ? 's' : 'u';
968e5dd7070Spatrick   else
969e5dd7070Spatrick     typeCode = 'f';
970e5dd7070Spatrick 
971e5dd7070Spatrick   if (CK == ClassI) {
972e5dd7070Spatrick     switch (typeCode) {
973e5dd7070Spatrick     default:
974e5dd7070Spatrick       break;
975e5dd7070Spatrick     case 's':
976e5dd7070Spatrick     case 'u':
977e5dd7070Spatrick     case 'p':
978e5dd7070Spatrick       typeCode = 'i';
979e5dd7070Spatrick       break;
980e5dd7070Spatrick     }
981e5dd7070Spatrick   }
982*12c85518Srobert   if (CK == ClassB && TargetGuard == "") {
983e5dd7070Spatrick     typeCode = '\0';
984e5dd7070Spatrick   }
985e5dd7070Spatrick 
986e5dd7070Spatrick   std::string S;
987e5dd7070Spatrick   if (typeCode != '\0')
988e5dd7070Spatrick     S.push_back(typeCode);
989e5dd7070Spatrick   if (printNumber)
990e5dd7070Spatrick     S += utostr(T.getElementSizeInBits());
991e5dd7070Spatrick 
992e5dd7070Spatrick   return S;
993e5dd7070Spatrick }
994e5dd7070Spatrick 
getBuiltinTypeStr()995e5dd7070Spatrick std::string Intrinsic::getBuiltinTypeStr() {
996e5dd7070Spatrick   ClassKind LocalCK = getClassKind(true);
997e5dd7070Spatrick   std::string S;
998e5dd7070Spatrick 
999e5dd7070Spatrick   Type RetT = getReturnType();
1000e5dd7070Spatrick   if ((LocalCK == ClassI || LocalCK == ClassW) && RetT.isScalar() &&
1001ec727ea7Spatrick       !RetT.isFloating() && !RetT.isBFloat16())
1002e5dd7070Spatrick     RetT.makeInteger(RetT.getElementSizeInBits(), false);
1003e5dd7070Spatrick 
1004e5dd7070Spatrick   // Since the return value must be one type, return a vector type of the
1005e5dd7070Spatrick   // appropriate width which we will bitcast.  An exception is made for
1006e5dd7070Spatrick   // returning structs of 2, 3, or 4 vectors which are returned in a sret-like
1007e5dd7070Spatrick   // fashion, storing them to a pointer arg.
1008e5dd7070Spatrick   if (RetT.getNumVectors() > 1) {
1009e5dd7070Spatrick     S += "vv*"; // void result with void* first argument
1010e5dd7070Spatrick   } else {
1011e5dd7070Spatrick     if (RetT.isPoly())
1012e5dd7070Spatrick       RetT.makeInteger(RetT.getElementSizeInBits(), false);
1013e5dd7070Spatrick     if (!RetT.isScalar() && RetT.isInteger() && !RetT.isSigned())
1014e5dd7070Spatrick       RetT.makeSigned();
1015e5dd7070Spatrick 
1016e5dd7070Spatrick     if (LocalCK == ClassB && RetT.isValue() && !RetT.isScalar())
1017e5dd7070Spatrick       // Cast to vector of 8-bit elements.
1018e5dd7070Spatrick       RetT.makeInteger(8, true);
1019e5dd7070Spatrick 
1020e5dd7070Spatrick     S += RetT.builtin_str();
1021e5dd7070Spatrick   }
1022e5dd7070Spatrick 
1023e5dd7070Spatrick   for (unsigned I = 0; I < getNumParams(); ++I) {
1024e5dd7070Spatrick     Type T = getParamType(I);
1025e5dd7070Spatrick     if (T.isPoly())
1026e5dd7070Spatrick       T.makeInteger(T.getElementSizeInBits(), false);
1027e5dd7070Spatrick 
1028e5dd7070Spatrick     if (LocalCK == ClassB && !T.isScalar())
1029e5dd7070Spatrick       T.makeInteger(8, true);
1030e5dd7070Spatrick     // Halves always get converted to 8-bit elements.
1031e5dd7070Spatrick     if (T.isHalf() && T.isVector() && !T.isScalarForMangling())
1032e5dd7070Spatrick       T.makeInteger(8, true);
1033e5dd7070Spatrick 
1034e5dd7070Spatrick     if (LocalCK == ClassI && T.isInteger())
1035e5dd7070Spatrick       T.makeSigned();
1036e5dd7070Spatrick 
1037e5dd7070Spatrick     if (hasImmediate() && getImmediateIdx() == I)
1038e5dd7070Spatrick       T.makeImmediate(32);
1039e5dd7070Spatrick 
1040e5dd7070Spatrick     S += T.builtin_str();
1041e5dd7070Spatrick   }
1042e5dd7070Spatrick 
1043e5dd7070Spatrick   // Extra constant integer to hold type class enum for this function, e.g. s8
1044e5dd7070Spatrick   if (LocalCK == ClassB)
1045e5dd7070Spatrick     S += "i";
1046e5dd7070Spatrick 
1047e5dd7070Spatrick   return S;
1048e5dd7070Spatrick }
1049e5dd7070Spatrick 
getMangledName(bool ForceClassS) const1050e5dd7070Spatrick std::string Intrinsic::getMangledName(bool ForceClassS) const {
1051e5dd7070Spatrick   // Check if the prototype has a scalar operand with the type of the vector
1052e5dd7070Spatrick   // elements.  If not, bitcasting the args will take care of arg checking.
1053e5dd7070Spatrick   // The actual signedness etc. will be taken care of with special enums.
1054e5dd7070Spatrick   ClassKind LocalCK = CK;
1055e5dd7070Spatrick   if (!protoHasScalar())
1056e5dd7070Spatrick     LocalCK = ClassB;
1057e5dd7070Spatrick 
1058e5dd7070Spatrick   return mangleName(Name, ForceClassS ? ClassS : LocalCK);
1059e5dd7070Spatrick }
1060e5dd7070Spatrick 
mangleName(std::string Name,ClassKind LocalCK) const1061e5dd7070Spatrick std::string Intrinsic::mangleName(std::string Name, ClassKind LocalCK) const {
1062e5dd7070Spatrick   std::string typeCode = getInstTypeCode(BaseType, LocalCK);
1063e5dd7070Spatrick   std::string S = Name;
1064e5dd7070Spatrick 
1065e5dd7070Spatrick   if (Name == "vcvt_f16_f32" || Name == "vcvt_f32_f16" ||
1066ec727ea7Spatrick       Name == "vcvt_f32_f64" || Name == "vcvt_f64_f32" ||
1067ec727ea7Spatrick       Name == "vcvt_f32_bf16")
1068e5dd7070Spatrick     return Name;
1069e5dd7070Spatrick 
1070e5dd7070Spatrick   if (!typeCode.empty()) {
1071e5dd7070Spatrick     // If the name ends with _xN (N = 2,3,4), insert the typeCode before _xN.
1072e5dd7070Spatrick     if (Name.size() >= 3 && isdigit(Name.back()) &&
1073e5dd7070Spatrick         Name[Name.length() - 2] == 'x' && Name[Name.length() - 3] == '_')
1074e5dd7070Spatrick       S.insert(S.length() - 3, "_" + typeCode);
1075e5dd7070Spatrick     else
1076e5dd7070Spatrick       S += "_" + typeCode;
1077e5dd7070Spatrick   }
1078e5dd7070Spatrick 
1079e5dd7070Spatrick   if (BaseType != InBaseType) {
1080e5dd7070Spatrick     // A reinterpret - out the input base type at the end.
1081e5dd7070Spatrick     S += "_" + getInstTypeCode(InBaseType, LocalCK);
1082e5dd7070Spatrick   }
1083e5dd7070Spatrick 
1084*12c85518Srobert   if (LocalCK == ClassB && TargetGuard == "")
1085e5dd7070Spatrick     S += "_v";
1086e5dd7070Spatrick 
1087e5dd7070Spatrick   // Insert a 'q' before the first '_' character so that it ends up before
1088e5dd7070Spatrick   // _lane or _n on vector-scalar operations.
1089e5dd7070Spatrick   if (BaseType.getSizeInBits() == 128 && !BaseType.noManglingQ()) {
1090e5dd7070Spatrick     size_t Pos = S.find('_');
1091e5dd7070Spatrick     S.insert(Pos, "q");
1092e5dd7070Spatrick   }
1093e5dd7070Spatrick 
1094e5dd7070Spatrick   char Suffix = '\0';
1095e5dd7070Spatrick   if (BaseType.isScalarForMangling()) {
1096e5dd7070Spatrick     switch (BaseType.getElementSizeInBits()) {
1097e5dd7070Spatrick     case 8: Suffix = 'b'; break;
1098e5dd7070Spatrick     case 16: Suffix = 'h'; break;
1099e5dd7070Spatrick     case 32: Suffix = 's'; break;
1100e5dd7070Spatrick     case 64: Suffix = 'd'; break;
1101e5dd7070Spatrick     default: llvm_unreachable("Bad suffix!");
1102e5dd7070Spatrick     }
1103e5dd7070Spatrick   }
1104e5dd7070Spatrick   if (Suffix != '\0') {
1105e5dd7070Spatrick     size_t Pos = S.find('_');
1106e5dd7070Spatrick     S.insert(Pos, &Suffix, 1);
1107e5dd7070Spatrick   }
1108e5dd7070Spatrick 
1109e5dd7070Spatrick   return S;
1110e5dd7070Spatrick }
1111e5dd7070Spatrick 
replaceParamsIn(std::string S)1112e5dd7070Spatrick std::string Intrinsic::replaceParamsIn(std::string S) {
1113e5dd7070Spatrick   while (S.find('$') != std::string::npos) {
1114e5dd7070Spatrick     size_t Pos = S.find('$');
1115e5dd7070Spatrick     size_t End = Pos + 1;
1116e5dd7070Spatrick     while (isalpha(S[End]))
1117e5dd7070Spatrick       ++End;
1118e5dd7070Spatrick 
1119e5dd7070Spatrick     std::string VarName = S.substr(Pos + 1, End - Pos - 1);
1120e5dd7070Spatrick     assert_with_loc(Variables.find(VarName) != Variables.end(),
1121e5dd7070Spatrick                     "Variable not defined!");
1122e5dd7070Spatrick     S.replace(Pos, End - Pos, Variables.find(VarName)->second.getName());
1123e5dd7070Spatrick   }
1124e5dd7070Spatrick 
1125e5dd7070Spatrick   return S;
1126e5dd7070Spatrick }
1127e5dd7070Spatrick 
initVariables()1128e5dd7070Spatrick void Intrinsic::initVariables() {
1129e5dd7070Spatrick   Variables.clear();
1130e5dd7070Spatrick 
1131e5dd7070Spatrick   // Modify the TypeSpec per-argument to get a concrete Type, and create
1132e5dd7070Spatrick   // known variables for each.
1133e5dd7070Spatrick   for (unsigned I = 1; I < Types.size(); ++I) {
1134e5dd7070Spatrick     char NameC = '0' + (I - 1);
1135e5dd7070Spatrick     std::string Name = "p";
1136e5dd7070Spatrick     Name.push_back(NameC);
1137e5dd7070Spatrick 
1138e5dd7070Spatrick     Variables[Name] = Variable(Types[I], Name + VariablePostfix);
1139e5dd7070Spatrick   }
1140e5dd7070Spatrick   RetVar = Variable(Types[0], "ret" + VariablePostfix);
1141e5dd7070Spatrick }
1142e5dd7070Spatrick 
emitPrototype(StringRef NamePrefix)1143e5dd7070Spatrick void Intrinsic::emitPrototype(StringRef NamePrefix) {
1144*12c85518Srobert   if (UseMacro) {
1145e5dd7070Spatrick     OS << "#define ";
1146*12c85518Srobert   } else {
1147*12c85518Srobert     OS << "__ai ";
1148*12c85518Srobert     if (TargetGuard != "")
1149*12c85518Srobert       OS << "__attribute__((target(\"" << TargetGuard << "\"))) ";
1150*12c85518Srobert     OS << Types[0].str() << " ";
1151*12c85518Srobert   }
1152e5dd7070Spatrick 
1153e5dd7070Spatrick   OS << NamePrefix.str() << mangleName(Name, ClassS) << "(";
1154e5dd7070Spatrick 
1155e5dd7070Spatrick   for (unsigned I = 0; I < getNumParams(); ++I) {
1156e5dd7070Spatrick     if (I != 0)
1157e5dd7070Spatrick       OS << ", ";
1158e5dd7070Spatrick 
1159e5dd7070Spatrick     char NameC = '0' + I;
1160e5dd7070Spatrick     std::string Name = "p";
1161e5dd7070Spatrick     Name.push_back(NameC);
1162e5dd7070Spatrick     assert(Variables.find(Name) != Variables.end());
1163e5dd7070Spatrick     Variable &V = Variables[Name];
1164e5dd7070Spatrick 
1165e5dd7070Spatrick     if (!UseMacro)
1166e5dd7070Spatrick       OS << V.getType().str() << " ";
1167e5dd7070Spatrick     OS << V.getName();
1168e5dd7070Spatrick   }
1169e5dd7070Spatrick 
1170e5dd7070Spatrick   OS << ")";
1171e5dd7070Spatrick }
1172e5dd7070Spatrick 
emitOpeningBrace()1173e5dd7070Spatrick void Intrinsic::emitOpeningBrace() {
1174e5dd7070Spatrick   if (UseMacro)
1175e5dd7070Spatrick     OS << " __extension__ ({";
1176e5dd7070Spatrick   else
1177e5dd7070Spatrick     OS << " {";
1178e5dd7070Spatrick   emitNewLine();
1179e5dd7070Spatrick }
1180e5dd7070Spatrick 
emitClosingBrace()1181e5dd7070Spatrick void Intrinsic::emitClosingBrace() {
1182e5dd7070Spatrick   if (UseMacro)
1183e5dd7070Spatrick     OS << "})";
1184e5dd7070Spatrick   else
1185e5dd7070Spatrick     OS << "}";
1186e5dd7070Spatrick }
1187e5dd7070Spatrick 
emitNewLine()1188e5dd7070Spatrick void Intrinsic::emitNewLine() {
1189e5dd7070Spatrick   if (UseMacro)
1190e5dd7070Spatrick     OS << " \\\n";
1191e5dd7070Spatrick   else
1192e5dd7070Spatrick     OS << "\n";
1193e5dd7070Spatrick }
1194e5dd7070Spatrick 
emitReverseVariable(Variable & Dest,Variable & Src)1195e5dd7070Spatrick void Intrinsic::emitReverseVariable(Variable &Dest, Variable &Src) {
1196e5dd7070Spatrick   if (Dest.getType().getNumVectors() > 1) {
1197e5dd7070Spatrick     emitNewLine();
1198e5dd7070Spatrick 
1199e5dd7070Spatrick     for (unsigned K = 0; K < Dest.getType().getNumVectors(); ++K) {
1200e5dd7070Spatrick       OS << "  " << Dest.getName() << ".val[" << K << "] = "
1201e5dd7070Spatrick          << "__builtin_shufflevector("
1202e5dd7070Spatrick          << Src.getName() << ".val[" << K << "], "
1203e5dd7070Spatrick          << Src.getName() << ".val[" << K << "]";
1204e5dd7070Spatrick       for (int J = Dest.getType().getNumElements() - 1; J >= 0; --J)
1205e5dd7070Spatrick         OS << ", " << J;
1206e5dd7070Spatrick       OS << ");";
1207e5dd7070Spatrick       emitNewLine();
1208e5dd7070Spatrick     }
1209e5dd7070Spatrick   } else {
1210e5dd7070Spatrick     OS << "  " << Dest.getName()
1211e5dd7070Spatrick        << " = __builtin_shufflevector(" << Src.getName() << ", " << Src.getName();
1212e5dd7070Spatrick     for (int J = Dest.getType().getNumElements() - 1; J >= 0; --J)
1213e5dd7070Spatrick       OS << ", " << J;
1214e5dd7070Spatrick     OS << ");";
1215e5dd7070Spatrick     emitNewLine();
1216e5dd7070Spatrick   }
1217e5dd7070Spatrick }
1218e5dd7070Spatrick 
emitArgumentReversal()1219e5dd7070Spatrick void Intrinsic::emitArgumentReversal() {
1220e5dd7070Spatrick   if (isBigEndianSafe())
1221e5dd7070Spatrick     return;
1222e5dd7070Spatrick 
1223e5dd7070Spatrick   // Reverse all vector arguments.
1224e5dd7070Spatrick   for (unsigned I = 0; I < getNumParams(); ++I) {
1225e5dd7070Spatrick     std::string Name = "p" + utostr(I);
1226e5dd7070Spatrick     std::string NewName = "rev" + utostr(I);
1227e5dd7070Spatrick 
1228e5dd7070Spatrick     Variable &V = Variables[Name];
1229e5dd7070Spatrick     Variable NewV(V.getType(), NewName + VariablePostfix);
1230e5dd7070Spatrick 
1231e5dd7070Spatrick     if (!NewV.getType().isVector() || NewV.getType().getNumElements() == 1)
1232e5dd7070Spatrick       continue;
1233e5dd7070Spatrick 
1234e5dd7070Spatrick     OS << "  " << NewV.getType().str() << " " << NewV.getName() << ";";
1235e5dd7070Spatrick     emitReverseVariable(NewV, V);
1236e5dd7070Spatrick     V = NewV;
1237e5dd7070Spatrick   }
1238e5dd7070Spatrick }
1239e5dd7070Spatrick 
emitReturnVarDecl()1240*12c85518Srobert void Intrinsic::emitReturnVarDecl() {
1241*12c85518Srobert   assert(RetVar.getType() == Types[0]);
1242*12c85518Srobert   // Create a return variable, if we're not void.
1243*12c85518Srobert   if (!RetVar.getType().isVoid()) {
1244*12c85518Srobert     OS << "  " << RetVar.getType().str() << " " << RetVar.getName() << ";";
1245*12c85518Srobert     emitNewLine();
1246*12c85518Srobert   }
1247*12c85518Srobert }
1248*12c85518Srobert 
emitReturnReversal()1249e5dd7070Spatrick void Intrinsic::emitReturnReversal() {
1250e5dd7070Spatrick   if (isBigEndianSafe())
1251e5dd7070Spatrick     return;
1252e5dd7070Spatrick   if (!getReturnType().isVector() || getReturnType().isVoid() ||
1253e5dd7070Spatrick       getReturnType().getNumElements() == 1)
1254e5dd7070Spatrick     return;
1255e5dd7070Spatrick   emitReverseVariable(RetVar, RetVar);
1256e5dd7070Spatrick }
1257e5dd7070Spatrick 
emitShadowedArgs()1258e5dd7070Spatrick void Intrinsic::emitShadowedArgs() {
1259e5dd7070Spatrick   // Macro arguments are not type-checked like inline function arguments,
1260e5dd7070Spatrick   // so assign them to local temporaries to get the right type checking.
1261e5dd7070Spatrick   if (!UseMacro)
1262e5dd7070Spatrick     return;
1263e5dd7070Spatrick 
1264e5dd7070Spatrick   for (unsigned I = 0; I < getNumParams(); ++I) {
1265e5dd7070Spatrick     // Do not create a temporary for an immediate argument.
1266e5dd7070Spatrick     // That would defeat the whole point of using a macro!
1267e5dd7070Spatrick     if (getParamType(I).isImmediate())
1268e5dd7070Spatrick       continue;
1269e5dd7070Spatrick     // Do not create a temporary for pointer arguments. The input
1270e5dd7070Spatrick     // pointer may have an alignment hint.
1271e5dd7070Spatrick     if (getParamType(I).isPointer())
1272e5dd7070Spatrick       continue;
1273e5dd7070Spatrick 
1274e5dd7070Spatrick     std::string Name = "p" + utostr(I);
1275e5dd7070Spatrick 
1276e5dd7070Spatrick     assert(Variables.find(Name) != Variables.end());
1277e5dd7070Spatrick     Variable &V = Variables[Name];
1278e5dd7070Spatrick 
1279e5dd7070Spatrick     std::string NewName = "s" + utostr(I);
1280e5dd7070Spatrick     Variable V2(V.getType(), NewName + VariablePostfix);
1281e5dd7070Spatrick 
1282e5dd7070Spatrick     OS << "  " << V2.getType().str() << " " << V2.getName() << " = "
1283e5dd7070Spatrick        << V.getName() << ";";
1284e5dd7070Spatrick     emitNewLine();
1285e5dd7070Spatrick 
1286e5dd7070Spatrick     V = V2;
1287e5dd7070Spatrick   }
1288e5dd7070Spatrick }
1289e5dd7070Spatrick 
protoHasScalar() const1290e5dd7070Spatrick bool Intrinsic::protoHasScalar() const {
1291*12c85518Srobert   return llvm::any_of(
1292*12c85518Srobert       Types, [](const Type &T) { return T.isScalar() && !T.isImmediate(); });
1293e5dd7070Spatrick }
1294e5dd7070Spatrick 
emitBodyAsBuiltinCall()1295e5dd7070Spatrick void Intrinsic::emitBodyAsBuiltinCall() {
1296e5dd7070Spatrick   std::string S;
1297e5dd7070Spatrick 
1298e5dd7070Spatrick   // If this builtin returns a struct 2, 3, or 4 vectors, pass it as an implicit
1299e5dd7070Spatrick   // sret-like argument.
1300e5dd7070Spatrick   bool SRet = getReturnType().getNumVectors() >= 2;
1301e5dd7070Spatrick 
1302e5dd7070Spatrick   StringRef N = Name;
1303e5dd7070Spatrick   ClassKind LocalCK = CK;
1304e5dd7070Spatrick   if (!protoHasScalar())
1305e5dd7070Spatrick     LocalCK = ClassB;
1306e5dd7070Spatrick 
1307e5dd7070Spatrick   if (!getReturnType().isVoid() && !SRet)
1308e5dd7070Spatrick     S += "(" + RetVar.getType().str() + ") ";
1309e5dd7070Spatrick 
1310ec727ea7Spatrick   S += "__builtin_neon_" + mangleName(std::string(N), LocalCK) + "(";
1311e5dd7070Spatrick 
1312e5dd7070Spatrick   if (SRet)
1313e5dd7070Spatrick     S += "&" + RetVar.getName() + ", ";
1314e5dd7070Spatrick 
1315e5dd7070Spatrick   for (unsigned I = 0; I < getNumParams(); ++I) {
1316e5dd7070Spatrick     Variable &V = Variables["p" + utostr(I)];
1317e5dd7070Spatrick     Type T = V.getType();
1318e5dd7070Spatrick 
1319e5dd7070Spatrick     // Handle multiple-vector values specially, emitting each subvector as an
1320e5dd7070Spatrick     // argument to the builtin.
1321e5dd7070Spatrick     if (T.getNumVectors() > 1) {
1322e5dd7070Spatrick       // Check if an explicit cast is needed.
1323e5dd7070Spatrick       std::string Cast;
1324e5dd7070Spatrick       if (LocalCK == ClassB) {
1325e5dd7070Spatrick         Type T2 = T;
1326e5dd7070Spatrick         T2.makeOneVector();
1327*12c85518Srobert         T2.makeInteger(8, /*Sign=*/true);
1328e5dd7070Spatrick         Cast = "(" + T2.str() + ")";
1329e5dd7070Spatrick       }
1330e5dd7070Spatrick 
1331e5dd7070Spatrick       for (unsigned J = 0; J < T.getNumVectors(); ++J)
1332e5dd7070Spatrick         S += Cast + V.getName() + ".val[" + utostr(J) + "], ";
1333e5dd7070Spatrick       continue;
1334e5dd7070Spatrick     }
1335e5dd7070Spatrick 
1336e5dd7070Spatrick     std::string Arg = V.getName();
1337e5dd7070Spatrick     Type CastToType = T;
1338e5dd7070Spatrick 
1339e5dd7070Spatrick     // Check if an explicit cast is needed.
1340e5dd7070Spatrick     if (CastToType.isVector() &&
1341e5dd7070Spatrick         (LocalCK == ClassB || (T.isHalf() && !T.isScalarForMangling()))) {
1342e5dd7070Spatrick       CastToType.makeInteger(8, true);
1343e5dd7070Spatrick       Arg = "(" + CastToType.str() + ")" + Arg;
1344e5dd7070Spatrick     } else if (CastToType.isVector() && LocalCK == ClassI) {
1345e5dd7070Spatrick       if (CastToType.isInteger())
1346e5dd7070Spatrick         CastToType.makeSigned();
1347e5dd7070Spatrick       Arg = "(" + CastToType.str() + ")" + Arg;
1348e5dd7070Spatrick     }
1349e5dd7070Spatrick 
1350e5dd7070Spatrick     S += Arg + ", ";
1351e5dd7070Spatrick   }
1352e5dd7070Spatrick 
1353e5dd7070Spatrick   // Extra constant integer to hold type class enum for this function, e.g. s8
1354e5dd7070Spatrick   if (getClassKind(true) == ClassB) {
1355e5dd7070Spatrick     S += utostr(getPolymorphicKeyType().getNeonEnum());
1356e5dd7070Spatrick   } else {
1357e5dd7070Spatrick     // Remove extraneous ", ".
1358e5dd7070Spatrick     S.pop_back();
1359e5dd7070Spatrick     S.pop_back();
1360e5dd7070Spatrick   }
1361e5dd7070Spatrick   S += ");";
1362e5dd7070Spatrick 
1363e5dd7070Spatrick   std::string RetExpr;
1364e5dd7070Spatrick   if (!SRet && !RetVar.getType().isVoid())
1365e5dd7070Spatrick     RetExpr = RetVar.getName() + " = ";
1366e5dd7070Spatrick 
1367e5dd7070Spatrick   OS << "  " << RetExpr << S;
1368e5dd7070Spatrick   emitNewLine();
1369e5dd7070Spatrick }
1370e5dd7070Spatrick 
emitBody(StringRef CallPrefix)1371e5dd7070Spatrick void Intrinsic::emitBody(StringRef CallPrefix) {
1372e5dd7070Spatrick   std::vector<std::string> Lines;
1373e5dd7070Spatrick 
1374e5dd7070Spatrick   if (!Body || Body->getValues().empty()) {
1375e5dd7070Spatrick     // Nothing specific to output - must output a builtin.
1376e5dd7070Spatrick     emitBodyAsBuiltinCall();
1377e5dd7070Spatrick     return;
1378e5dd7070Spatrick   }
1379e5dd7070Spatrick 
1380e5dd7070Spatrick   // We have a list of "things to output". The last should be returned.
1381e5dd7070Spatrick   for (auto *I : Body->getValues()) {
1382e5dd7070Spatrick     if (StringInit *SI = dyn_cast<StringInit>(I)) {
1383e5dd7070Spatrick       Lines.push_back(replaceParamsIn(SI->getAsString()));
1384e5dd7070Spatrick     } else if (DagInit *DI = dyn_cast<DagInit>(I)) {
1385e5dd7070Spatrick       DagEmitter DE(*this, CallPrefix);
1386e5dd7070Spatrick       Lines.push_back(DE.emitDag(DI).second + ";");
1387e5dd7070Spatrick     }
1388e5dd7070Spatrick   }
1389e5dd7070Spatrick 
1390e5dd7070Spatrick   assert(!Lines.empty() && "Empty def?");
1391e5dd7070Spatrick   if (!RetVar.getType().isVoid())
1392e5dd7070Spatrick     Lines.back().insert(0, RetVar.getName() + " = ");
1393e5dd7070Spatrick 
1394e5dd7070Spatrick   for (auto &L : Lines) {
1395e5dd7070Spatrick     OS << "  " << L;
1396e5dd7070Spatrick     emitNewLine();
1397e5dd7070Spatrick   }
1398e5dd7070Spatrick }
1399e5dd7070Spatrick 
emitReturn()1400e5dd7070Spatrick void Intrinsic::emitReturn() {
1401e5dd7070Spatrick   if (RetVar.getType().isVoid())
1402e5dd7070Spatrick     return;
1403e5dd7070Spatrick   if (UseMacro)
1404e5dd7070Spatrick     OS << "  " << RetVar.getName() << ";";
1405e5dd7070Spatrick   else
1406e5dd7070Spatrick     OS << "  return " << RetVar.getName() << ";";
1407e5dd7070Spatrick   emitNewLine();
1408e5dd7070Spatrick }
1409e5dd7070Spatrick 
emitDag(DagInit * DI)1410e5dd7070Spatrick std::pair<Type, std::string> Intrinsic::DagEmitter::emitDag(DagInit *DI) {
1411e5dd7070Spatrick   // At this point we should only be seeing a def.
1412e5dd7070Spatrick   DefInit *DefI = cast<DefInit>(DI->getOperator());
1413e5dd7070Spatrick   std::string Op = DefI->getAsString();
1414e5dd7070Spatrick 
1415e5dd7070Spatrick   if (Op == "cast" || Op == "bitcast")
1416e5dd7070Spatrick     return emitDagCast(DI, Op == "bitcast");
1417e5dd7070Spatrick   if (Op == "shuffle")
1418e5dd7070Spatrick     return emitDagShuffle(DI);
1419e5dd7070Spatrick   if (Op == "dup")
1420e5dd7070Spatrick     return emitDagDup(DI);
1421e5dd7070Spatrick   if (Op == "dup_typed")
1422e5dd7070Spatrick     return emitDagDupTyped(DI);
1423e5dd7070Spatrick   if (Op == "splat")
1424e5dd7070Spatrick     return emitDagSplat(DI);
1425e5dd7070Spatrick   if (Op == "save_temp")
1426e5dd7070Spatrick     return emitDagSaveTemp(DI);
1427e5dd7070Spatrick   if (Op == "op")
1428e5dd7070Spatrick     return emitDagOp(DI);
1429ec727ea7Spatrick   if (Op == "call" || Op == "call_mangled")
1430ec727ea7Spatrick     return emitDagCall(DI, Op == "call_mangled");
1431e5dd7070Spatrick   if (Op == "name_replace")
1432e5dd7070Spatrick     return emitDagNameReplace(DI);
1433e5dd7070Spatrick   if (Op == "literal")
1434e5dd7070Spatrick     return emitDagLiteral(DI);
1435e5dd7070Spatrick   assert_with_loc(false, "Unknown operation!");
1436e5dd7070Spatrick   return std::make_pair(Type::getVoid(), "");
1437e5dd7070Spatrick }
1438e5dd7070Spatrick 
emitDagOp(DagInit * DI)1439e5dd7070Spatrick std::pair<Type, std::string> Intrinsic::DagEmitter::emitDagOp(DagInit *DI) {
1440e5dd7070Spatrick   std::string Op = cast<StringInit>(DI->getArg(0))->getAsUnquotedString();
1441e5dd7070Spatrick   if (DI->getNumArgs() == 2) {
1442e5dd7070Spatrick     // Unary op.
1443e5dd7070Spatrick     std::pair<Type, std::string> R =
1444ec727ea7Spatrick         emitDagArg(DI->getArg(1), std::string(DI->getArgNameStr(1)));
1445e5dd7070Spatrick     return std::make_pair(R.first, Op + R.second);
1446e5dd7070Spatrick   } else {
1447e5dd7070Spatrick     assert(DI->getNumArgs() == 3 && "Can only handle unary and binary ops!");
1448e5dd7070Spatrick     std::pair<Type, std::string> R1 =
1449ec727ea7Spatrick         emitDagArg(DI->getArg(1), std::string(DI->getArgNameStr(1)));
1450e5dd7070Spatrick     std::pair<Type, std::string> R2 =
1451ec727ea7Spatrick         emitDagArg(DI->getArg(2), std::string(DI->getArgNameStr(2)));
1452e5dd7070Spatrick     assert_with_loc(R1.first == R2.first, "Argument type mismatch!");
1453e5dd7070Spatrick     return std::make_pair(R1.first, R1.second + " " + Op + " " + R2.second);
1454e5dd7070Spatrick   }
1455e5dd7070Spatrick }
1456e5dd7070Spatrick 
1457ec727ea7Spatrick std::pair<Type, std::string>
emitDagCall(DagInit * DI,bool MatchMangledName)1458ec727ea7Spatrick Intrinsic::DagEmitter::emitDagCall(DagInit *DI, bool MatchMangledName) {
1459e5dd7070Spatrick   std::vector<Type> Types;
1460e5dd7070Spatrick   std::vector<std::string> Values;
1461e5dd7070Spatrick   for (unsigned I = 0; I < DI->getNumArgs() - 1; ++I) {
1462e5dd7070Spatrick     std::pair<Type, std::string> R =
1463ec727ea7Spatrick         emitDagArg(DI->getArg(I + 1), std::string(DI->getArgNameStr(I + 1)));
1464e5dd7070Spatrick     Types.push_back(R.first);
1465e5dd7070Spatrick     Values.push_back(R.second);
1466e5dd7070Spatrick   }
1467e5dd7070Spatrick 
1468e5dd7070Spatrick   // Look up the called intrinsic.
1469e5dd7070Spatrick   std::string N;
1470e5dd7070Spatrick   if (StringInit *SI = dyn_cast<StringInit>(DI->getArg(0)))
1471e5dd7070Spatrick     N = SI->getAsUnquotedString();
1472e5dd7070Spatrick   else
1473e5dd7070Spatrick     N = emitDagArg(DI->getArg(0), "").second;
1474*12c85518Srobert   std::optional<std::string> MangledName;
1475ec727ea7Spatrick   if (MatchMangledName) {
1476ec727ea7Spatrick     if (Intr.getRecord()->getValueAsBit("isLaneQ"))
1477ec727ea7Spatrick       N += "q";
1478ec727ea7Spatrick     MangledName = Intr.mangleName(N, ClassS);
1479ec727ea7Spatrick   }
1480ec727ea7Spatrick   Intrinsic &Callee = Intr.Emitter.getIntrinsic(N, Types, MangledName);
1481e5dd7070Spatrick 
1482e5dd7070Spatrick   // Make sure the callee is known as an early def.
1483e5dd7070Spatrick   Callee.setNeededEarly();
1484e5dd7070Spatrick   Intr.Dependencies.insert(&Callee);
1485e5dd7070Spatrick 
1486e5dd7070Spatrick   // Now create the call itself.
1487*12c85518Srobert   std::string S;
1488e5dd7070Spatrick   if (!Callee.isBigEndianSafe())
1489e5dd7070Spatrick     S += CallPrefix.str();
1490e5dd7070Spatrick   S += Callee.getMangledName(true) + "(";
1491e5dd7070Spatrick   for (unsigned I = 0; I < DI->getNumArgs() - 1; ++I) {
1492e5dd7070Spatrick     if (I != 0)
1493e5dd7070Spatrick       S += ", ";
1494e5dd7070Spatrick     S += Values[I];
1495e5dd7070Spatrick   }
1496e5dd7070Spatrick   S += ")";
1497e5dd7070Spatrick 
1498e5dd7070Spatrick   return std::make_pair(Callee.getReturnType(), S);
1499e5dd7070Spatrick }
1500e5dd7070Spatrick 
emitDagCast(DagInit * DI,bool IsBitCast)1501e5dd7070Spatrick std::pair<Type, std::string> Intrinsic::DagEmitter::emitDagCast(DagInit *DI,
1502e5dd7070Spatrick                                                                 bool IsBitCast){
1503e5dd7070Spatrick   // (cast MOD* VAL) -> cast VAL to type given by MOD.
1504ec727ea7Spatrick   std::pair<Type, std::string> R =
1505ec727ea7Spatrick       emitDagArg(DI->getArg(DI->getNumArgs() - 1),
1506ec727ea7Spatrick                  std::string(DI->getArgNameStr(DI->getNumArgs() - 1)));
1507e5dd7070Spatrick   Type castToType = R.first;
1508e5dd7070Spatrick   for (unsigned ArgIdx = 0; ArgIdx < DI->getNumArgs() - 1; ++ArgIdx) {
1509e5dd7070Spatrick 
1510e5dd7070Spatrick     // MOD can take several forms:
1511e5dd7070Spatrick     //   1. $X - take the type of parameter / variable X.
1512e5dd7070Spatrick     //   2. The value "R" - take the type of the return type.
1513e5dd7070Spatrick     //   3. a type string
1514e5dd7070Spatrick     //   4. The value "U" or "S" to switch the signedness.
1515e5dd7070Spatrick     //   5. The value "H" or "D" to half or double the bitwidth.
1516e5dd7070Spatrick     //   6. The value "8" to convert to 8-bit (signed) integer lanes.
1517e5dd7070Spatrick     if (!DI->getArgNameStr(ArgIdx).empty()) {
1518ec727ea7Spatrick       assert_with_loc(Intr.Variables.find(std::string(
1519ec727ea7Spatrick                           DI->getArgNameStr(ArgIdx))) != Intr.Variables.end(),
1520e5dd7070Spatrick                       "Variable not found");
1521ec727ea7Spatrick       castToType =
1522ec727ea7Spatrick           Intr.Variables[std::string(DI->getArgNameStr(ArgIdx))].getType();
1523e5dd7070Spatrick     } else {
1524e5dd7070Spatrick       StringInit *SI = dyn_cast<StringInit>(DI->getArg(ArgIdx));
1525e5dd7070Spatrick       assert_with_loc(SI, "Expected string type or $Name for cast type");
1526e5dd7070Spatrick 
1527e5dd7070Spatrick       if (SI->getAsUnquotedString() == "R") {
1528e5dd7070Spatrick         castToType = Intr.getReturnType();
1529e5dd7070Spatrick       } else if (SI->getAsUnquotedString() == "U") {
1530e5dd7070Spatrick         castToType.makeUnsigned();
1531e5dd7070Spatrick       } else if (SI->getAsUnquotedString() == "S") {
1532e5dd7070Spatrick         castToType.makeSigned();
1533e5dd7070Spatrick       } else if (SI->getAsUnquotedString() == "H") {
1534e5dd7070Spatrick         castToType.halveLanes();
1535e5dd7070Spatrick       } else if (SI->getAsUnquotedString() == "D") {
1536e5dd7070Spatrick         castToType.doubleLanes();
1537e5dd7070Spatrick       } else if (SI->getAsUnquotedString() == "8") {
1538e5dd7070Spatrick         castToType.makeInteger(8, true);
1539ec727ea7Spatrick       } else if (SI->getAsUnquotedString() == "32") {
1540ec727ea7Spatrick         castToType.make32BitElement();
1541e5dd7070Spatrick       } else {
1542e5dd7070Spatrick         castToType = Type::fromTypedefName(SI->getAsUnquotedString());
1543e5dd7070Spatrick         assert_with_loc(!castToType.isVoid(), "Unknown typedef");
1544e5dd7070Spatrick       }
1545e5dd7070Spatrick     }
1546e5dd7070Spatrick   }
1547e5dd7070Spatrick 
1548e5dd7070Spatrick   std::string S;
1549e5dd7070Spatrick   if (IsBitCast) {
1550e5dd7070Spatrick     // Emit a reinterpret cast. The second operand must be an lvalue, so create
1551e5dd7070Spatrick     // a temporary.
1552e5dd7070Spatrick     std::string N = "reint";
1553e5dd7070Spatrick     unsigned I = 0;
1554e5dd7070Spatrick     while (Intr.Variables.find(N) != Intr.Variables.end())
1555e5dd7070Spatrick       N = "reint" + utostr(++I);
1556e5dd7070Spatrick     Intr.Variables[N] = Variable(R.first, N + Intr.VariablePostfix);
1557e5dd7070Spatrick 
1558e5dd7070Spatrick     Intr.OS << R.first.str() << " " << Intr.Variables[N].getName() << " = "
1559e5dd7070Spatrick             << R.second << ";";
1560e5dd7070Spatrick     Intr.emitNewLine();
1561e5dd7070Spatrick 
1562e5dd7070Spatrick     S = "*(" + castToType.str() + " *) &" + Intr.Variables[N].getName() + "";
1563e5dd7070Spatrick   } else {
1564e5dd7070Spatrick     // Emit a normal (static) cast.
1565e5dd7070Spatrick     S = "(" + castToType.str() + ")(" + R.second + ")";
1566e5dd7070Spatrick   }
1567e5dd7070Spatrick 
1568e5dd7070Spatrick   return std::make_pair(castToType, S);
1569e5dd7070Spatrick }
1570e5dd7070Spatrick 
emitDagShuffle(DagInit * DI)1571e5dd7070Spatrick std::pair<Type, std::string> Intrinsic::DagEmitter::emitDagShuffle(DagInit *DI){
1572e5dd7070Spatrick   // See the documentation in arm_neon.td for a description of these operators.
1573e5dd7070Spatrick   class LowHalf : public SetTheory::Operator {
1574e5dd7070Spatrick   public:
1575e5dd7070Spatrick     void apply(SetTheory &ST, DagInit *Expr, SetTheory::RecSet &Elts,
1576e5dd7070Spatrick                ArrayRef<SMLoc> Loc) override {
1577e5dd7070Spatrick       SetTheory::RecSet Elts2;
1578e5dd7070Spatrick       ST.evaluate(Expr->arg_begin(), Expr->arg_end(), Elts2, Loc);
1579e5dd7070Spatrick       Elts.insert(Elts2.begin(), Elts2.begin() + (Elts2.size() / 2));
1580e5dd7070Spatrick     }
1581e5dd7070Spatrick   };
1582e5dd7070Spatrick 
1583e5dd7070Spatrick   class HighHalf : public SetTheory::Operator {
1584e5dd7070Spatrick   public:
1585e5dd7070Spatrick     void apply(SetTheory &ST, DagInit *Expr, SetTheory::RecSet &Elts,
1586e5dd7070Spatrick                ArrayRef<SMLoc> Loc) override {
1587e5dd7070Spatrick       SetTheory::RecSet Elts2;
1588e5dd7070Spatrick       ST.evaluate(Expr->arg_begin(), Expr->arg_end(), Elts2, Loc);
1589e5dd7070Spatrick       Elts.insert(Elts2.begin() + (Elts2.size() / 2), Elts2.end());
1590e5dd7070Spatrick     }
1591e5dd7070Spatrick   };
1592e5dd7070Spatrick 
1593e5dd7070Spatrick   class Rev : public SetTheory::Operator {
1594e5dd7070Spatrick     unsigned ElementSize;
1595e5dd7070Spatrick 
1596e5dd7070Spatrick   public:
1597e5dd7070Spatrick     Rev(unsigned ElementSize) : ElementSize(ElementSize) {}
1598e5dd7070Spatrick 
1599e5dd7070Spatrick     void apply(SetTheory &ST, DagInit *Expr, SetTheory::RecSet &Elts,
1600e5dd7070Spatrick                ArrayRef<SMLoc> Loc) override {
1601e5dd7070Spatrick       SetTheory::RecSet Elts2;
1602e5dd7070Spatrick       ST.evaluate(Expr->arg_begin() + 1, Expr->arg_end(), Elts2, Loc);
1603e5dd7070Spatrick 
1604e5dd7070Spatrick       int64_t VectorSize = cast<IntInit>(Expr->getArg(0))->getValue();
1605e5dd7070Spatrick       VectorSize /= ElementSize;
1606e5dd7070Spatrick 
1607e5dd7070Spatrick       std::vector<Record *> Revved;
1608e5dd7070Spatrick       for (unsigned VI = 0; VI < Elts2.size(); VI += VectorSize) {
1609e5dd7070Spatrick         for (int LI = VectorSize - 1; LI >= 0; --LI) {
1610e5dd7070Spatrick           Revved.push_back(Elts2[VI + LI]);
1611e5dd7070Spatrick         }
1612e5dd7070Spatrick       }
1613e5dd7070Spatrick 
1614e5dd7070Spatrick       Elts.insert(Revved.begin(), Revved.end());
1615e5dd7070Spatrick     }
1616e5dd7070Spatrick   };
1617e5dd7070Spatrick 
1618e5dd7070Spatrick   class MaskExpander : public SetTheory::Expander {
1619e5dd7070Spatrick     unsigned N;
1620e5dd7070Spatrick 
1621e5dd7070Spatrick   public:
1622e5dd7070Spatrick     MaskExpander(unsigned N) : N(N) {}
1623e5dd7070Spatrick 
1624e5dd7070Spatrick     void expand(SetTheory &ST, Record *R, SetTheory::RecSet &Elts) override {
1625e5dd7070Spatrick       unsigned Addend = 0;
1626e5dd7070Spatrick       if (R->getName() == "mask0")
1627e5dd7070Spatrick         Addend = 0;
1628e5dd7070Spatrick       else if (R->getName() == "mask1")
1629e5dd7070Spatrick         Addend = N;
1630e5dd7070Spatrick       else
1631e5dd7070Spatrick         return;
1632e5dd7070Spatrick       for (unsigned I = 0; I < N; ++I)
1633e5dd7070Spatrick         Elts.insert(R->getRecords().getDef("sv" + utostr(I + Addend)));
1634e5dd7070Spatrick     }
1635e5dd7070Spatrick   };
1636e5dd7070Spatrick 
1637e5dd7070Spatrick   // (shuffle arg1, arg2, sequence)
1638e5dd7070Spatrick   std::pair<Type, std::string> Arg1 =
1639ec727ea7Spatrick       emitDagArg(DI->getArg(0), std::string(DI->getArgNameStr(0)));
1640e5dd7070Spatrick   std::pair<Type, std::string> Arg2 =
1641ec727ea7Spatrick       emitDagArg(DI->getArg(1), std::string(DI->getArgNameStr(1)));
1642e5dd7070Spatrick   assert_with_loc(Arg1.first == Arg2.first,
1643e5dd7070Spatrick                   "Different types in arguments to shuffle!");
1644e5dd7070Spatrick 
1645e5dd7070Spatrick   SetTheory ST;
1646e5dd7070Spatrick   SetTheory::RecSet Elts;
1647e5dd7070Spatrick   ST.addOperator("lowhalf", std::make_unique<LowHalf>());
1648e5dd7070Spatrick   ST.addOperator("highhalf", std::make_unique<HighHalf>());
1649e5dd7070Spatrick   ST.addOperator("rev",
1650e5dd7070Spatrick                  std::make_unique<Rev>(Arg1.first.getElementSizeInBits()));
1651e5dd7070Spatrick   ST.addExpander("MaskExpand",
1652e5dd7070Spatrick                  std::make_unique<MaskExpander>(Arg1.first.getNumElements()));
1653*12c85518Srobert   ST.evaluate(DI->getArg(2), Elts, std::nullopt);
1654e5dd7070Spatrick 
1655e5dd7070Spatrick   std::string S = "__builtin_shufflevector(" + Arg1.second + ", " + Arg2.second;
1656e5dd7070Spatrick   for (auto &E : Elts) {
1657e5dd7070Spatrick     StringRef Name = E->getName();
1658e5dd7070Spatrick     assert_with_loc(Name.startswith("sv"),
1659e5dd7070Spatrick                     "Incorrect element kind in shuffle mask!");
1660e5dd7070Spatrick     S += ", " + Name.drop_front(2).str();
1661e5dd7070Spatrick   }
1662e5dd7070Spatrick   S += ")";
1663e5dd7070Spatrick 
1664e5dd7070Spatrick   // Recalculate the return type - the shuffle may have halved or doubled it.
1665e5dd7070Spatrick   Type T(Arg1.first);
1666e5dd7070Spatrick   if (Elts.size() > T.getNumElements()) {
1667e5dd7070Spatrick     assert_with_loc(
1668e5dd7070Spatrick         Elts.size() == T.getNumElements() * 2,
1669e5dd7070Spatrick         "Can only double or half the number of elements in a shuffle!");
1670e5dd7070Spatrick     T.doubleLanes();
1671e5dd7070Spatrick   } else if (Elts.size() < T.getNumElements()) {
1672e5dd7070Spatrick     assert_with_loc(
1673e5dd7070Spatrick         Elts.size() == T.getNumElements() / 2,
1674e5dd7070Spatrick         "Can only double or half the number of elements in a shuffle!");
1675e5dd7070Spatrick     T.halveLanes();
1676e5dd7070Spatrick   }
1677e5dd7070Spatrick 
1678e5dd7070Spatrick   return std::make_pair(T, S);
1679e5dd7070Spatrick }
1680e5dd7070Spatrick 
emitDagDup(DagInit * DI)1681e5dd7070Spatrick std::pair<Type, std::string> Intrinsic::DagEmitter::emitDagDup(DagInit *DI) {
1682e5dd7070Spatrick   assert_with_loc(DI->getNumArgs() == 1, "dup() expects one argument");
1683ec727ea7Spatrick   std::pair<Type, std::string> A =
1684ec727ea7Spatrick       emitDagArg(DI->getArg(0), std::string(DI->getArgNameStr(0)));
1685e5dd7070Spatrick   assert_with_loc(A.first.isScalar(), "dup() expects a scalar argument");
1686e5dd7070Spatrick 
1687e5dd7070Spatrick   Type T = Intr.getBaseType();
1688e5dd7070Spatrick   assert_with_loc(T.isVector(), "dup() used but default type is scalar!");
1689e5dd7070Spatrick   std::string S = "(" + T.str() + ") {";
1690e5dd7070Spatrick   for (unsigned I = 0; I < T.getNumElements(); ++I) {
1691e5dd7070Spatrick     if (I != 0)
1692e5dd7070Spatrick       S += ", ";
1693e5dd7070Spatrick     S += A.second;
1694e5dd7070Spatrick   }
1695e5dd7070Spatrick   S += "}";
1696e5dd7070Spatrick 
1697e5dd7070Spatrick   return std::make_pair(T, S);
1698e5dd7070Spatrick }
1699e5dd7070Spatrick 
emitDagDupTyped(DagInit * DI)1700e5dd7070Spatrick std::pair<Type, std::string> Intrinsic::DagEmitter::emitDagDupTyped(DagInit *DI) {
1701e5dd7070Spatrick   assert_with_loc(DI->getNumArgs() == 2, "dup_typed() expects two arguments");
1702ec727ea7Spatrick   std::pair<Type, std::string> B =
1703ec727ea7Spatrick       emitDagArg(DI->getArg(1), std::string(DI->getArgNameStr(1)));
1704e5dd7070Spatrick   assert_with_loc(B.first.isScalar(),
1705e5dd7070Spatrick                   "dup_typed() requires a scalar as the second argument");
1706a9ac8606Spatrick   Type T;
1707a9ac8606Spatrick   // If the type argument is a constant string, construct the type directly.
1708a9ac8606Spatrick   if (StringInit *SI = dyn_cast<StringInit>(DI->getArg(0))) {
1709a9ac8606Spatrick     T = Type::fromTypedefName(SI->getAsUnquotedString());
1710a9ac8606Spatrick     assert_with_loc(!T.isVoid(), "Unknown typedef");
1711a9ac8606Spatrick   } else
1712a9ac8606Spatrick     T = emitDagArg(DI->getArg(0), std::string(DI->getArgNameStr(0))).first;
1713e5dd7070Spatrick 
1714e5dd7070Spatrick   assert_with_loc(T.isVector(), "dup_typed() used but target type is scalar!");
1715e5dd7070Spatrick   std::string S = "(" + T.str() + ") {";
1716e5dd7070Spatrick   for (unsigned I = 0; I < T.getNumElements(); ++I) {
1717e5dd7070Spatrick     if (I != 0)
1718e5dd7070Spatrick       S += ", ";
1719e5dd7070Spatrick     S += B.second;
1720e5dd7070Spatrick   }
1721e5dd7070Spatrick   S += "}";
1722e5dd7070Spatrick 
1723e5dd7070Spatrick   return std::make_pair(T, S);
1724e5dd7070Spatrick }
1725e5dd7070Spatrick 
emitDagSplat(DagInit * DI)1726e5dd7070Spatrick std::pair<Type, std::string> Intrinsic::DagEmitter::emitDagSplat(DagInit *DI) {
1727e5dd7070Spatrick   assert_with_loc(DI->getNumArgs() == 2, "splat() expects two arguments");
1728ec727ea7Spatrick   std::pair<Type, std::string> A =
1729ec727ea7Spatrick       emitDagArg(DI->getArg(0), std::string(DI->getArgNameStr(0)));
1730ec727ea7Spatrick   std::pair<Type, std::string> B =
1731ec727ea7Spatrick       emitDagArg(DI->getArg(1), std::string(DI->getArgNameStr(1)));
1732e5dd7070Spatrick 
1733e5dd7070Spatrick   assert_with_loc(B.first.isScalar(),
1734e5dd7070Spatrick                   "splat() requires a scalar int as the second argument");
1735e5dd7070Spatrick 
1736e5dd7070Spatrick   std::string S = "__builtin_shufflevector(" + A.second + ", " + A.second;
1737e5dd7070Spatrick   for (unsigned I = 0; I < Intr.getBaseType().getNumElements(); ++I) {
1738e5dd7070Spatrick     S += ", " + B.second;
1739e5dd7070Spatrick   }
1740e5dd7070Spatrick   S += ")";
1741e5dd7070Spatrick 
1742e5dd7070Spatrick   return std::make_pair(Intr.getBaseType(), S);
1743e5dd7070Spatrick }
1744e5dd7070Spatrick 
emitDagSaveTemp(DagInit * DI)1745e5dd7070Spatrick std::pair<Type, std::string> Intrinsic::DagEmitter::emitDagSaveTemp(DagInit *DI) {
1746e5dd7070Spatrick   assert_with_loc(DI->getNumArgs() == 2, "save_temp() expects two arguments");
1747ec727ea7Spatrick   std::pair<Type, std::string> A =
1748ec727ea7Spatrick       emitDagArg(DI->getArg(1), std::string(DI->getArgNameStr(1)));
1749e5dd7070Spatrick 
1750e5dd7070Spatrick   assert_with_loc(!A.first.isVoid(),
1751e5dd7070Spatrick                   "Argument to save_temp() must have non-void type!");
1752e5dd7070Spatrick 
1753ec727ea7Spatrick   std::string N = std::string(DI->getArgNameStr(0));
1754e5dd7070Spatrick   assert_with_loc(!N.empty(),
1755e5dd7070Spatrick                   "save_temp() expects a name as the first argument");
1756e5dd7070Spatrick 
1757e5dd7070Spatrick   assert_with_loc(Intr.Variables.find(N) == Intr.Variables.end(),
1758e5dd7070Spatrick                   "Variable already defined!");
1759e5dd7070Spatrick   Intr.Variables[N] = Variable(A.first, N + Intr.VariablePostfix);
1760e5dd7070Spatrick 
1761e5dd7070Spatrick   std::string S =
1762e5dd7070Spatrick       A.first.str() + " " + Intr.Variables[N].getName() + " = " + A.second;
1763e5dd7070Spatrick 
1764e5dd7070Spatrick   return std::make_pair(Type::getVoid(), S);
1765e5dd7070Spatrick }
1766e5dd7070Spatrick 
1767e5dd7070Spatrick std::pair<Type, std::string>
emitDagNameReplace(DagInit * DI)1768e5dd7070Spatrick Intrinsic::DagEmitter::emitDagNameReplace(DagInit *DI) {
1769e5dd7070Spatrick   std::string S = Intr.Name;
1770e5dd7070Spatrick 
1771e5dd7070Spatrick   assert_with_loc(DI->getNumArgs() == 2, "name_replace requires 2 arguments!");
1772e5dd7070Spatrick   std::string ToReplace = cast<StringInit>(DI->getArg(0))->getAsUnquotedString();
1773e5dd7070Spatrick   std::string ReplaceWith = cast<StringInit>(DI->getArg(1))->getAsUnquotedString();
1774e5dd7070Spatrick 
1775e5dd7070Spatrick   size_t Idx = S.find(ToReplace);
1776e5dd7070Spatrick 
1777e5dd7070Spatrick   assert_with_loc(Idx != std::string::npos, "name should contain '" + ToReplace + "'!");
1778e5dd7070Spatrick   S.replace(Idx, ToReplace.size(), ReplaceWith);
1779e5dd7070Spatrick 
1780e5dd7070Spatrick   return std::make_pair(Type::getVoid(), S);
1781e5dd7070Spatrick }
1782e5dd7070Spatrick 
emitDagLiteral(DagInit * DI)1783e5dd7070Spatrick std::pair<Type, std::string> Intrinsic::DagEmitter::emitDagLiteral(DagInit *DI){
1784e5dd7070Spatrick   std::string Ty = cast<StringInit>(DI->getArg(0))->getAsUnquotedString();
1785e5dd7070Spatrick   std::string Value = cast<StringInit>(DI->getArg(1))->getAsUnquotedString();
1786e5dd7070Spatrick   return std::make_pair(Type::fromTypedefName(Ty), Value);
1787e5dd7070Spatrick }
1788e5dd7070Spatrick 
1789e5dd7070Spatrick std::pair<Type, std::string>
emitDagArg(Init * Arg,std::string ArgName)1790e5dd7070Spatrick Intrinsic::DagEmitter::emitDagArg(Init *Arg, std::string ArgName) {
1791e5dd7070Spatrick   if (!ArgName.empty()) {
1792e5dd7070Spatrick     assert_with_loc(!Arg->isComplete(),
1793e5dd7070Spatrick                     "Arguments must either be DAGs or names, not both!");
1794e5dd7070Spatrick     assert_with_loc(Intr.Variables.find(ArgName) != Intr.Variables.end(),
1795e5dd7070Spatrick                     "Variable not defined!");
1796e5dd7070Spatrick     Variable &V = Intr.Variables[ArgName];
1797e5dd7070Spatrick     return std::make_pair(V.getType(), V.getName());
1798e5dd7070Spatrick   }
1799e5dd7070Spatrick 
1800e5dd7070Spatrick   assert(Arg && "Neither ArgName nor Arg?!");
1801e5dd7070Spatrick   DagInit *DI = dyn_cast<DagInit>(Arg);
1802e5dd7070Spatrick   assert_with_loc(DI, "Arguments must either be DAGs or names!");
1803e5dd7070Spatrick 
1804e5dd7070Spatrick   return emitDag(DI);
1805e5dd7070Spatrick }
1806e5dd7070Spatrick 
generate()1807e5dd7070Spatrick std::string Intrinsic::generate() {
1808e5dd7070Spatrick   // Avoid duplicated code for big and little endian
1809e5dd7070Spatrick   if (isBigEndianSafe()) {
1810e5dd7070Spatrick     generateImpl(false, "", "");
1811e5dd7070Spatrick     return OS.str();
1812e5dd7070Spatrick   }
1813e5dd7070Spatrick   // Little endian intrinsics are simple and don't require any argument
1814e5dd7070Spatrick   // swapping.
1815e5dd7070Spatrick   OS << "#ifdef __LITTLE_ENDIAN__\n";
1816e5dd7070Spatrick 
1817e5dd7070Spatrick   generateImpl(false, "", "");
1818e5dd7070Spatrick 
1819e5dd7070Spatrick   OS << "#else\n";
1820e5dd7070Spatrick 
1821e5dd7070Spatrick   // Big endian intrinsics are more complex. The user intended these
1822e5dd7070Spatrick   // intrinsics to operate on a vector "as-if" loaded by (V)LDR,
1823e5dd7070Spatrick   // but we load as-if (V)LD1. So we should swap all arguments and
1824e5dd7070Spatrick   // swap the return value too.
1825e5dd7070Spatrick   //
1826e5dd7070Spatrick   // If we call sub-intrinsics, we should call a version that does
1827e5dd7070Spatrick   // not re-swap the arguments!
1828e5dd7070Spatrick   generateImpl(true, "", "__noswap_");
1829e5dd7070Spatrick 
1830e5dd7070Spatrick   // If we're needed early, create a non-swapping variant for
1831e5dd7070Spatrick   // big-endian.
1832e5dd7070Spatrick   if (NeededEarly) {
1833e5dd7070Spatrick     generateImpl(false, "__noswap_", "__noswap_");
1834e5dd7070Spatrick   }
1835e5dd7070Spatrick   OS << "#endif\n\n";
1836e5dd7070Spatrick 
1837e5dd7070Spatrick   return OS.str();
1838e5dd7070Spatrick }
1839e5dd7070Spatrick 
generateImpl(bool ReverseArguments,StringRef NamePrefix,StringRef CallPrefix)1840e5dd7070Spatrick void Intrinsic::generateImpl(bool ReverseArguments,
1841e5dd7070Spatrick                              StringRef NamePrefix, StringRef CallPrefix) {
1842e5dd7070Spatrick   CurrentRecord = R;
1843e5dd7070Spatrick 
1844e5dd7070Spatrick   // If we call a macro, our local variables may be corrupted due to
1845e5dd7070Spatrick   // lack of proper lexical scoping. So, add a globally unique postfix
1846e5dd7070Spatrick   // to every variable.
1847e5dd7070Spatrick   //
1848e5dd7070Spatrick   // indexBody() should have set up the Dependencies set by now.
1849e5dd7070Spatrick   for (auto *I : Dependencies)
1850e5dd7070Spatrick     if (I->UseMacro) {
1851e5dd7070Spatrick       VariablePostfix = "_" + utostr(Emitter.getUniqueNumber());
1852e5dd7070Spatrick       break;
1853e5dd7070Spatrick     }
1854e5dd7070Spatrick 
1855e5dd7070Spatrick   initVariables();
1856e5dd7070Spatrick 
1857e5dd7070Spatrick   emitPrototype(NamePrefix);
1858e5dd7070Spatrick 
1859e5dd7070Spatrick   if (IsUnavailable) {
1860e5dd7070Spatrick     OS << " __attribute__((unavailable));";
1861e5dd7070Spatrick   } else {
1862e5dd7070Spatrick     emitOpeningBrace();
1863*12c85518Srobert     // Emit return variable declaration first as to not trigger
1864*12c85518Srobert     // -Wdeclaration-after-statement.
1865*12c85518Srobert     emitReturnVarDecl();
1866e5dd7070Spatrick     emitShadowedArgs();
1867e5dd7070Spatrick     if (ReverseArguments)
1868e5dd7070Spatrick       emitArgumentReversal();
1869e5dd7070Spatrick     emitBody(CallPrefix);
1870e5dd7070Spatrick     if (ReverseArguments)
1871e5dd7070Spatrick       emitReturnReversal();
1872e5dd7070Spatrick     emitReturn();
1873e5dd7070Spatrick     emitClosingBrace();
1874e5dd7070Spatrick   }
1875e5dd7070Spatrick   OS << "\n";
1876e5dd7070Spatrick 
1877e5dd7070Spatrick   CurrentRecord = nullptr;
1878e5dd7070Spatrick }
1879e5dd7070Spatrick 
indexBody()1880e5dd7070Spatrick void Intrinsic::indexBody() {
1881e5dd7070Spatrick   CurrentRecord = R;
1882e5dd7070Spatrick 
1883e5dd7070Spatrick   initVariables();
1884*12c85518Srobert   // Emit return variable declaration first as to not trigger
1885*12c85518Srobert   // -Wdeclaration-after-statement.
1886*12c85518Srobert   emitReturnVarDecl();
1887e5dd7070Spatrick   emitBody("");
1888e5dd7070Spatrick   OS.str("");
1889e5dd7070Spatrick 
1890e5dd7070Spatrick   CurrentRecord = nullptr;
1891e5dd7070Spatrick }
1892e5dd7070Spatrick 
1893e5dd7070Spatrick //===----------------------------------------------------------------------===//
1894e5dd7070Spatrick // NeonEmitter implementation
1895e5dd7070Spatrick //===----------------------------------------------------------------------===//
1896e5dd7070Spatrick 
getIntrinsic(StringRef Name,ArrayRef<Type> Types,std::optional<std::string> MangledName)1897ec727ea7Spatrick Intrinsic &NeonEmitter::getIntrinsic(StringRef Name, ArrayRef<Type> Types,
1898*12c85518Srobert                                      std::optional<std::string> MangledName) {
1899e5dd7070Spatrick   // First, look up the name in the intrinsic map.
1900e5dd7070Spatrick   assert_with_loc(IntrinsicMap.find(Name.str()) != IntrinsicMap.end(),
1901e5dd7070Spatrick                   ("Intrinsic '" + Name + "' not found!").str());
1902e5dd7070Spatrick   auto &V = IntrinsicMap.find(Name.str())->second;
1903e5dd7070Spatrick   std::vector<Intrinsic *> GoodVec;
1904e5dd7070Spatrick 
1905e5dd7070Spatrick   // Create a string to print if we end up failing.
1906e5dd7070Spatrick   std::string ErrMsg = "looking up intrinsic '" + Name.str() + "(";
1907e5dd7070Spatrick   for (unsigned I = 0; I < Types.size(); ++I) {
1908e5dd7070Spatrick     if (I != 0)
1909e5dd7070Spatrick       ErrMsg += ", ";
1910e5dd7070Spatrick     ErrMsg += Types[I].str();
1911e5dd7070Spatrick   }
1912e5dd7070Spatrick   ErrMsg += ")'\n";
1913e5dd7070Spatrick   ErrMsg += "Available overloads:\n";
1914e5dd7070Spatrick 
1915e5dd7070Spatrick   // Now, look through each intrinsic implementation and see if the types are
1916e5dd7070Spatrick   // compatible.
1917e5dd7070Spatrick   for (auto &I : V) {
1918e5dd7070Spatrick     ErrMsg += "  - " + I.getReturnType().str() + " " + I.getMangledName();
1919e5dd7070Spatrick     ErrMsg += "(";
1920e5dd7070Spatrick     for (unsigned A = 0; A < I.getNumParams(); ++A) {
1921e5dd7070Spatrick       if (A != 0)
1922e5dd7070Spatrick         ErrMsg += ", ";
1923e5dd7070Spatrick       ErrMsg += I.getParamType(A).str();
1924e5dd7070Spatrick     }
1925e5dd7070Spatrick     ErrMsg += ")\n";
1926e5dd7070Spatrick 
1927ec727ea7Spatrick     if (MangledName && MangledName != I.getMangledName(true))
1928ec727ea7Spatrick       continue;
1929ec727ea7Spatrick 
1930e5dd7070Spatrick     if (I.getNumParams() != Types.size())
1931e5dd7070Spatrick       continue;
1932e5dd7070Spatrick 
1933ec727ea7Spatrick     unsigned ArgNum = 0;
1934*12c85518Srobert     bool MatchingArgumentTypes = llvm::all_of(Types, [&](const auto &Type) {
1935ec727ea7Spatrick       return Type == I.getParamType(ArgNum++);
1936ec727ea7Spatrick     });
1937ec727ea7Spatrick 
1938ec727ea7Spatrick     if (MatchingArgumentTypes)
1939e5dd7070Spatrick       GoodVec.push_back(&I);
1940e5dd7070Spatrick   }
1941e5dd7070Spatrick 
1942e5dd7070Spatrick   assert_with_loc(!GoodVec.empty(),
1943e5dd7070Spatrick                   "No compatible intrinsic found - " + ErrMsg);
1944e5dd7070Spatrick   assert_with_loc(GoodVec.size() == 1, "Multiple overloads found - " + ErrMsg);
1945e5dd7070Spatrick 
1946e5dd7070Spatrick   return *GoodVec.front();
1947e5dd7070Spatrick }
1948e5dd7070Spatrick 
createIntrinsic(Record * R,SmallVectorImpl<Intrinsic * > & Out)1949e5dd7070Spatrick void NeonEmitter::createIntrinsic(Record *R,
1950e5dd7070Spatrick                                   SmallVectorImpl<Intrinsic *> &Out) {
1951ec727ea7Spatrick   std::string Name = std::string(R->getValueAsString("Name"));
1952ec727ea7Spatrick   std::string Proto = std::string(R->getValueAsString("Prototype"));
1953ec727ea7Spatrick   std::string Types = std::string(R->getValueAsString("Types"));
1954e5dd7070Spatrick   Record *OperationRec = R->getValueAsDef("Operation");
1955e5dd7070Spatrick   bool BigEndianSafe  = R->getValueAsBit("BigEndianSafe");
1956*12c85518Srobert   std::string ArchGuard = std::string(R->getValueAsString("ArchGuard"));
1957*12c85518Srobert   std::string TargetGuard = std::string(R->getValueAsString("TargetGuard"));
1958e5dd7070Spatrick   bool IsUnavailable = OperationRec->getValueAsBit("Unavailable");
1959ec727ea7Spatrick   std::string CartesianProductWith = std::string(R->getValueAsString("CartesianProductWith"));
1960e5dd7070Spatrick 
1961e5dd7070Spatrick   // Set the global current record. This allows assert_with_loc to produce
1962e5dd7070Spatrick   // decent location information even when highly nested.
1963e5dd7070Spatrick   CurrentRecord = R;
1964e5dd7070Spatrick 
1965e5dd7070Spatrick   ListInit *Body = OperationRec->getValueAsListInit("Ops");
1966e5dd7070Spatrick 
1967e5dd7070Spatrick   std::vector<TypeSpec> TypeSpecs = TypeSpec::fromTypeSpecs(Types);
1968e5dd7070Spatrick 
1969e5dd7070Spatrick   ClassKind CK = ClassNone;
1970e5dd7070Spatrick   if (R->getSuperClasses().size() >= 2)
1971e5dd7070Spatrick     CK = ClassMap[R->getSuperClasses()[1].first];
1972e5dd7070Spatrick 
1973e5dd7070Spatrick   std::vector<std::pair<TypeSpec, TypeSpec>> NewTypeSpecs;
1974ec727ea7Spatrick   if (!CartesianProductWith.empty()) {
1975ec727ea7Spatrick     std::vector<TypeSpec> ProductTypeSpecs = TypeSpec::fromTypeSpecs(CartesianProductWith);
1976e5dd7070Spatrick     for (auto TS : TypeSpecs) {
1977e5dd7070Spatrick       Type DefaultT(TS, ".");
1978ec727ea7Spatrick       for (auto SrcTS : ProductTypeSpecs) {
1979e5dd7070Spatrick         Type DefaultSrcT(SrcTS, ".");
1980e5dd7070Spatrick         if (TS == SrcTS ||
1981e5dd7070Spatrick             DefaultSrcT.getSizeInBits() != DefaultT.getSizeInBits())
1982e5dd7070Spatrick           continue;
1983e5dd7070Spatrick         NewTypeSpecs.push_back(std::make_pair(TS, SrcTS));
1984e5dd7070Spatrick       }
1985ec727ea7Spatrick     }
1986e5dd7070Spatrick   } else {
1987ec727ea7Spatrick     for (auto TS : TypeSpecs) {
1988e5dd7070Spatrick       NewTypeSpecs.push_back(std::make_pair(TS, TS));
1989e5dd7070Spatrick     }
1990e5dd7070Spatrick   }
1991e5dd7070Spatrick 
1992e5dd7070Spatrick   llvm::sort(NewTypeSpecs);
1993e5dd7070Spatrick   NewTypeSpecs.erase(std::unique(NewTypeSpecs.begin(), NewTypeSpecs.end()),
1994e5dd7070Spatrick 		     NewTypeSpecs.end());
1995e5dd7070Spatrick   auto &Entry = IntrinsicMap[Name];
1996e5dd7070Spatrick 
1997e5dd7070Spatrick   for (auto &I : NewTypeSpecs) {
1998e5dd7070Spatrick     Entry.emplace_back(R, Name, Proto, I.first, I.second, CK, Body, *this,
1999*12c85518Srobert                        ArchGuard, TargetGuard, IsUnavailable, BigEndianSafe);
2000e5dd7070Spatrick     Out.push_back(&Entry.back());
2001e5dd7070Spatrick   }
2002e5dd7070Spatrick 
2003e5dd7070Spatrick   CurrentRecord = nullptr;
2004e5dd7070Spatrick }
2005e5dd7070Spatrick 
2006e5dd7070Spatrick /// genBuiltinsDef: Generate the BuiltinsARM.def and  BuiltinsAArch64.def
2007e5dd7070Spatrick /// declaration of builtins, checking for unique builtin declarations.
genBuiltinsDef(raw_ostream & OS,SmallVectorImpl<Intrinsic * > & Defs)2008e5dd7070Spatrick void NeonEmitter::genBuiltinsDef(raw_ostream &OS,
2009e5dd7070Spatrick                                  SmallVectorImpl<Intrinsic *> &Defs) {
2010e5dd7070Spatrick   OS << "#ifdef GET_NEON_BUILTINS\n";
2011e5dd7070Spatrick 
2012e5dd7070Spatrick   // We only want to emit a builtin once, and we want to emit them in
2013e5dd7070Spatrick   // alphabetical order, so use a std::set.
2014*12c85518Srobert   std::set<std::pair<std::string, std::string>> Builtins;
2015e5dd7070Spatrick 
2016e5dd7070Spatrick   for (auto *Def : Defs) {
2017e5dd7070Spatrick     if (Def->hasBody())
2018e5dd7070Spatrick       continue;
2019e5dd7070Spatrick 
2020*12c85518Srobert     std::string S = "__builtin_neon_" + Def->getMangledName() + ", \"";
2021e5dd7070Spatrick     S += Def->getBuiltinTypeStr();
2022*12c85518Srobert     S += "\", \"n\"";
2023e5dd7070Spatrick 
2024*12c85518Srobert     Builtins.emplace(S, Def->getTargetGuard());
2025e5dd7070Spatrick   }
2026e5dd7070Spatrick 
2027*12c85518Srobert   for (auto &S : Builtins) {
2028*12c85518Srobert     if (S.second == "")
2029*12c85518Srobert       OS << "BUILTIN(";
2030*12c85518Srobert     else
2031*12c85518Srobert       OS << "TARGET_BUILTIN(";
2032*12c85518Srobert     OS << S.first;
2033*12c85518Srobert     if (S.second == "")
2034*12c85518Srobert       OS << ")\n";
2035*12c85518Srobert     else
2036*12c85518Srobert       OS << ", \"" << S.second << "\")\n";
2037*12c85518Srobert   }
2038*12c85518Srobert 
2039e5dd7070Spatrick   OS << "#endif\n\n";
2040e5dd7070Spatrick }
2041e5dd7070Spatrick 
2042e5dd7070Spatrick /// Generate the ARM and AArch64 overloaded type checking code for
2043e5dd7070Spatrick /// SemaChecking.cpp, checking for unique builtin declarations.
genOverloadTypeCheckCode(raw_ostream & OS,SmallVectorImpl<Intrinsic * > & Defs)2044e5dd7070Spatrick void NeonEmitter::genOverloadTypeCheckCode(raw_ostream &OS,
2045e5dd7070Spatrick                                            SmallVectorImpl<Intrinsic *> &Defs) {
2046e5dd7070Spatrick   OS << "#ifdef GET_NEON_OVERLOAD_CHECK\n";
2047e5dd7070Spatrick 
2048e5dd7070Spatrick   // We record each overload check line before emitting because subsequent Inst
2049e5dd7070Spatrick   // definitions may extend the number of permitted types (i.e. augment the
2050e5dd7070Spatrick   // Mask). Use std::map to avoid sorting the table by hash number.
2051e5dd7070Spatrick   struct OverloadInfo {
2052e5dd7070Spatrick     uint64_t Mask;
2053e5dd7070Spatrick     int PtrArgNum;
2054e5dd7070Spatrick     bool HasConstPtr;
2055e5dd7070Spatrick     OverloadInfo() : Mask(0ULL), PtrArgNum(0), HasConstPtr(false) {}
2056e5dd7070Spatrick   };
2057e5dd7070Spatrick   std::map<std::string, OverloadInfo> OverloadMap;
2058e5dd7070Spatrick 
2059e5dd7070Spatrick   for (auto *Def : Defs) {
2060e5dd7070Spatrick     // If the def has a body (that is, it has Operation DAGs), it won't call
2061e5dd7070Spatrick     // __builtin_neon_* so we don't need to generate a definition for it.
2062e5dd7070Spatrick     if (Def->hasBody())
2063e5dd7070Spatrick       continue;
2064e5dd7070Spatrick     // Functions which have a scalar argument cannot be overloaded, no need to
2065e5dd7070Spatrick     // check them if we are emitting the type checking code.
2066e5dd7070Spatrick     if (Def->protoHasScalar())
2067e5dd7070Spatrick       continue;
2068e5dd7070Spatrick 
2069e5dd7070Spatrick     uint64_t Mask = 0ULL;
2070e5dd7070Spatrick     Mask |= 1ULL << Def->getPolymorphicKeyType().getNeonEnum();
2071e5dd7070Spatrick 
2072e5dd7070Spatrick     // Check if the function has a pointer or const pointer argument.
2073e5dd7070Spatrick     int PtrArgNum = -1;
2074e5dd7070Spatrick     bool HasConstPtr = false;
2075e5dd7070Spatrick     for (unsigned I = 0; I < Def->getNumParams(); ++I) {
2076e5dd7070Spatrick       const auto &Type = Def->getParamType(I);
2077e5dd7070Spatrick       if (Type.isPointer()) {
2078e5dd7070Spatrick         PtrArgNum = I;
2079e5dd7070Spatrick         HasConstPtr = Type.isConstPointer();
2080e5dd7070Spatrick       }
2081e5dd7070Spatrick     }
2082e5dd7070Spatrick 
2083e5dd7070Spatrick     // For sret builtins, adjust the pointer argument index.
2084e5dd7070Spatrick     if (PtrArgNum >= 0 && Def->getReturnType().getNumVectors() > 1)
2085e5dd7070Spatrick       PtrArgNum += 1;
2086e5dd7070Spatrick 
2087e5dd7070Spatrick     std::string Name = Def->getName();
2088e5dd7070Spatrick     // Omit type checking for the pointer arguments of vld1_lane, vld1_dup,
2089e5dd7070Spatrick     // and vst1_lane intrinsics.  Using a pointer to the vector element
2090e5dd7070Spatrick     // type with one of those operations causes codegen to select an aligned
2091e5dd7070Spatrick     // load/store instruction.  If you want an unaligned operation,
2092e5dd7070Spatrick     // the pointer argument needs to have less alignment than element type,
2093e5dd7070Spatrick     // so just accept any pointer type.
2094e5dd7070Spatrick     if (Name == "vld1_lane" || Name == "vld1_dup" || Name == "vst1_lane") {
2095e5dd7070Spatrick       PtrArgNum = -1;
2096e5dd7070Spatrick       HasConstPtr = false;
2097e5dd7070Spatrick     }
2098e5dd7070Spatrick 
2099e5dd7070Spatrick     if (Mask) {
2100e5dd7070Spatrick       std::string Name = Def->getMangledName();
2101e5dd7070Spatrick       OverloadMap.insert(std::make_pair(Name, OverloadInfo()));
2102e5dd7070Spatrick       OverloadInfo &OI = OverloadMap[Name];
2103e5dd7070Spatrick       OI.Mask |= Mask;
2104e5dd7070Spatrick       OI.PtrArgNum |= PtrArgNum;
2105e5dd7070Spatrick       OI.HasConstPtr = HasConstPtr;
2106e5dd7070Spatrick     }
2107e5dd7070Spatrick   }
2108e5dd7070Spatrick 
2109e5dd7070Spatrick   for (auto &I : OverloadMap) {
2110e5dd7070Spatrick     OverloadInfo &OI = I.second;
2111e5dd7070Spatrick 
2112e5dd7070Spatrick     OS << "case NEON::BI__builtin_neon_" << I.first << ": ";
2113e5dd7070Spatrick     OS << "mask = 0x" << Twine::utohexstr(OI.Mask) << "ULL";
2114e5dd7070Spatrick     if (OI.PtrArgNum >= 0)
2115e5dd7070Spatrick       OS << "; PtrArgNum = " << OI.PtrArgNum;
2116e5dd7070Spatrick     if (OI.HasConstPtr)
2117e5dd7070Spatrick       OS << "; HasConstPtr = true";
2118e5dd7070Spatrick     OS << "; break;\n";
2119e5dd7070Spatrick   }
2120e5dd7070Spatrick   OS << "#endif\n\n";
2121e5dd7070Spatrick }
2122e5dd7070Spatrick 
genIntrinsicRangeCheckCode(raw_ostream & OS,SmallVectorImpl<Intrinsic * > & Defs)2123e5dd7070Spatrick void NeonEmitter::genIntrinsicRangeCheckCode(raw_ostream &OS,
2124e5dd7070Spatrick                                         SmallVectorImpl<Intrinsic *> &Defs) {
2125e5dd7070Spatrick   OS << "#ifdef GET_NEON_IMMEDIATE_CHECK\n";
2126e5dd7070Spatrick 
2127e5dd7070Spatrick   std::set<std::string> Emitted;
2128e5dd7070Spatrick 
2129e5dd7070Spatrick   for (auto *Def : Defs) {
2130e5dd7070Spatrick     if (Def->hasBody())
2131e5dd7070Spatrick       continue;
2132e5dd7070Spatrick     // Functions which do not have an immediate do not need to have range
2133e5dd7070Spatrick     // checking code emitted.
2134e5dd7070Spatrick     if (!Def->hasImmediate())
2135e5dd7070Spatrick       continue;
2136e5dd7070Spatrick     if (Emitted.find(Def->getMangledName()) != Emitted.end())
2137e5dd7070Spatrick       continue;
2138e5dd7070Spatrick 
2139e5dd7070Spatrick     std::string LowerBound, UpperBound;
2140e5dd7070Spatrick 
2141e5dd7070Spatrick     Record *R = Def->getRecord();
2142a9ac8606Spatrick     if (R->getValueAsBit("isVXAR")) {
2143a9ac8606Spatrick       //VXAR takes an immediate in the range [0, 63]
2144a9ac8606Spatrick       LowerBound = "0";
2145a9ac8606Spatrick       UpperBound = "63";
2146a9ac8606Spatrick     } else if (R->getValueAsBit("isVCVT_N")) {
2147e5dd7070Spatrick       // VCVT between floating- and fixed-point values takes an immediate
2148e5dd7070Spatrick       // in the range [1, 32) for f32 or [1, 64) for f64 or [1, 16) for f16.
2149e5dd7070Spatrick       LowerBound = "1";
2150e5dd7070Spatrick 	  if (Def->getBaseType().getElementSizeInBits() == 16 ||
2151e5dd7070Spatrick 		  Def->getName().find('h') != std::string::npos)
2152e5dd7070Spatrick 		// VCVTh operating on FP16 intrinsics in range [1, 16)
2153e5dd7070Spatrick 		UpperBound = "15";
2154e5dd7070Spatrick 	  else if (Def->getBaseType().getElementSizeInBits() == 32)
2155e5dd7070Spatrick         UpperBound = "31";
2156e5dd7070Spatrick 	  else
2157e5dd7070Spatrick         UpperBound = "63";
2158e5dd7070Spatrick     } else if (R->getValueAsBit("isScalarShift")) {
2159e5dd7070Spatrick       // Right shifts have an 'r' in the name, left shifts do not. Convert
2160e5dd7070Spatrick       // instructions have the same bounds and right shifts.
2161e5dd7070Spatrick       if (Def->getName().find('r') != std::string::npos ||
2162e5dd7070Spatrick           Def->getName().find("cvt") != std::string::npos)
2163e5dd7070Spatrick         LowerBound = "1";
2164e5dd7070Spatrick 
2165e5dd7070Spatrick       UpperBound = utostr(Def->getReturnType().getElementSizeInBits() - 1);
2166e5dd7070Spatrick     } else if (R->getValueAsBit("isShift")) {
2167e5dd7070Spatrick       // Builtins which are overloaded by type will need to have their upper
2168e5dd7070Spatrick       // bound computed at Sema time based on the type constant.
2169e5dd7070Spatrick 
2170e5dd7070Spatrick       // Right shifts have an 'r' in the name, left shifts do not.
2171e5dd7070Spatrick       if (Def->getName().find('r') != std::string::npos)
2172e5dd7070Spatrick         LowerBound = "1";
2173e5dd7070Spatrick       UpperBound = "RFT(TV, true)";
2174e5dd7070Spatrick     } else if (Def->getClassKind(true) == ClassB) {
2175e5dd7070Spatrick       // ClassB intrinsics have a type (and hence lane number) that is only
2176e5dd7070Spatrick       // known at runtime.
2177e5dd7070Spatrick       if (R->getValueAsBit("isLaneQ"))
2178e5dd7070Spatrick         UpperBound = "RFT(TV, false, true)";
2179e5dd7070Spatrick       else
2180e5dd7070Spatrick         UpperBound = "RFT(TV, false, false)";
2181e5dd7070Spatrick     } else {
2182e5dd7070Spatrick       // The immediate generally refers to a lane in the preceding argument.
2183e5dd7070Spatrick       assert(Def->getImmediateIdx() > 0);
2184e5dd7070Spatrick       Type T = Def->getParamType(Def->getImmediateIdx() - 1);
2185e5dd7070Spatrick       UpperBound = utostr(T.getNumElements() - 1);
2186e5dd7070Spatrick     }
2187e5dd7070Spatrick 
2188e5dd7070Spatrick     // Calculate the index of the immediate that should be range checked.
2189e5dd7070Spatrick     unsigned Idx = Def->getNumParams();
2190e5dd7070Spatrick     if (Def->hasImmediate())
2191e5dd7070Spatrick       Idx = Def->getGeneratedParamIdx(Def->getImmediateIdx());
2192e5dd7070Spatrick 
2193e5dd7070Spatrick     OS << "case NEON::BI__builtin_neon_" << Def->getMangledName() << ": "
2194e5dd7070Spatrick        << "i = " << Idx << ";";
2195e5dd7070Spatrick     if (!LowerBound.empty())
2196e5dd7070Spatrick       OS << " l = " << LowerBound << ";";
2197e5dd7070Spatrick     if (!UpperBound.empty())
2198e5dd7070Spatrick       OS << " u = " << UpperBound << ";";
2199e5dd7070Spatrick     OS << " break;\n";
2200e5dd7070Spatrick 
2201e5dd7070Spatrick     Emitted.insert(Def->getMangledName());
2202e5dd7070Spatrick   }
2203e5dd7070Spatrick 
2204e5dd7070Spatrick   OS << "#endif\n\n";
2205e5dd7070Spatrick }
2206e5dd7070Spatrick 
2207e5dd7070Spatrick /// runHeader - Emit a file with sections defining:
2208e5dd7070Spatrick /// 1. the NEON section of BuiltinsARM.def and BuiltinsAArch64.def.
2209e5dd7070Spatrick /// 2. the SemaChecking code for the type overload checking.
2210e5dd7070Spatrick /// 3. the SemaChecking code for validation of intrinsic immediate arguments.
runHeader(raw_ostream & OS)2211e5dd7070Spatrick void NeonEmitter::runHeader(raw_ostream &OS) {
2212e5dd7070Spatrick   std::vector<Record *> RV = Records.getAllDerivedDefinitions("Inst");
2213e5dd7070Spatrick 
2214e5dd7070Spatrick   SmallVector<Intrinsic *, 128> Defs;
2215e5dd7070Spatrick   for (auto *R : RV)
2216e5dd7070Spatrick     createIntrinsic(R, Defs);
2217e5dd7070Spatrick 
2218e5dd7070Spatrick   // Generate shared BuiltinsXXX.def
2219e5dd7070Spatrick   genBuiltinsDef(OS, Defs);
2220e5dd7070Spatrick 
2221e5dd7070Spatrick   // Generate ARM overloaded type checking code for SemaChecking.cpp
2222e5dd7070Spatrick   genOverloadTypeCheckCode(OS, Defs);
2223e5dd7070Spatrick 
2224e5dd7070Spatrick   // Generate ARM range checking code for shift/lane immediates.
2225e5dd7070Spatrick   genIntrinsicRangeCheckCode(OS, Defs);
2226e5dd7070Spatrick }
2227e5dd7070Spatrick 
emitNeonTypeDefs(const std::string & types,raw_ostream & OS)2228ec727ea7Spatrick static void emitNeonTypeDefs(const std::string& types, raw_ostream &OS) {
2229ec727ea7Spatrick   std::string TypedefTypes(types);
2230ec727ea7Spatrick   std::vector<TypeSpec> TDTypeVec = TypeSpec::fromTypeSpecs(TypedefTypes);
2231ec727ea7Spatrick 
2232ec727ea7Spatrick   // Emit vector typedefs.
2233ec727ea7Spatrick   bool InIfdef = false;
2234ec727ea7Spatrick   for (auto &TS : TDTypeVec) {
2235ec727ea7Spatrick     bool IsA64 = false;
2236ec727ea7Spatrick     Type T(TS, ".");
2237ec727ea7Spatrick     if (T.isDouble())
2238ec727ea7Spatrick       IsA64 = true;
2239ec727ea7Spatrick 
2240ec727ea7Spatrick     if (InIfdef && !IsA64) {
2241ec727ea7Spatrick       OS << "#endif\n";
2242ec727ea7Spatrick       InIfdef = false;
2243ec727ea7Spatrick     }
2244ec727ea7Spatrick     if (!InIfdef && IsA64) {
2245ec727ea7Spatrick       OS << "#ifdef __aarch64__\n";
2246ec727ea7Spatrick       InIfdef = true;
2247ec727ea7Spatrick     }
2248ec727ea7Spatrick 
2249ec727ea7Spatrick     if (T.isPoly())
2250ec727ea7Spatrick       OS << "typedef __attribute__((neon_polyvector_type(";
2251ec727ea7Spatrick     else
2252ec727ea7Spatrick       OS << "typedef __attribute__((neon_vector_type(";
2253ec727ea7Spatrick 
2254ec727ea7Spatrick     Type T2 = T;
2255ec727ea7Spatrick     T2.makeScalar();
2256ec727ea7Spatrick     OS << T.getNumElements() << "))) ";
2257ec727ea7Spatrick     OS << T2.str();
2258ec727ea7Spatrick     OS << " " << T.str() << ";\n";
2259ec727ea7Spatrick   }
2260ec727ea7Spatrick   if (InIfdef)
2261ec727ea7Spatrick     OS << "#endif\n";
2262ec727ea7Spatrick   OS << "\n";
2263ec727ea7Spatrick 
2264ec727ea7Spatrick   // Emit struct typedefs.
2265ec727ea7Spatrick   InIfdef = false;
2266ec727ea7Spatrick   for (unsigned NumMembers = 2; NumMembers <= 4; ++NumMembers) {
2267ec727ea7Spatrick     for (auto &TS : TDTypeVec) {
2268ec727ea7Spatrick       bool IsA64 = false;
2269ec727ea7Spatrick       Type T(TS, ".");
2270ec727ea7Spatrick       if (T.isDouble())
2271ec727ea7Spatrick         IsA64 = true;
2272ec727ea7Spatrick 
2273ec727ea7Spatrick       if (InIfdef && !IsA64) {
2274ec727ea7Spatrick         OS << "#endif\n";
2275ec727ea7Spatrick         InIfdef = false;
2276ec727ea7Spatrick       }
2277ec727ea7Spatrick       if (!InIfdef && IsA64) {
2278ec727ea7Spatrick         OS << "#ifdef __aarch64__\n";
2279ec727ea7Spatrick         InIfdef = true;
2280ec727ea7Spatrick       }
2281ec727ea7Spatrick 
2282ec727ea7Spatrick       const char Mods[] = { static_cast<char>('2' + (NumMembers - 2)), 0};
2283ec727ea7Spatrick       Type VT(TS, Mods);
2284ec727ea7Spatrick       OS << "typedef struct " << VT.str() << " {\n";
2285ec727ea7Spatrick       OS << "  " << T.str() << " val";
2286ec727ea7Spatrick       OS << "[" << NumMembers << "]";
2287ec727ea7Spatrick       OS << ";\n} ";
2288ec727ea7Spatrick       OS << VT.str() << ";\n";
2289ec727ea7Spatrick       OS << "\n";
2290ec727ea7Spatrick     }
2291ec727ea7Spatrick   }
2292ec727ea7Spatrick   if (InIfdef)
2293ec727ea7Spatrick     OS << "#endif\n";
2294ec727ea7Spatrick }
2295ec727ea7Spatrick 
2296e5dd7070Spatrick /// run - Read the records in arm_neon.td and output arm_neon.h.  arm_neon.h
2297e5dd7070Spatrick /// is comprised of type definitions and function declarations.
run(raw_ostream & OS)2298e5dd7070Spatrick void NeonEmitter::run(raw_ostream &OS) {
2299e5dd7070Spatrick   OS << "/*===---- arm_neon.h - ARM Neon intrinsics "
2300e5dd7070Spatrick         "------------------------------"
2301e5dd7070Spatrick         "---===\n"
2302e5dd7070Spatrick         " *\n"
2303e5dd7070Spatrick         " * Permission is hereby granted, free of charge, to any person "
2304e5dd7070Spatrick         "obtaining "
2305e5dd7070Spatrick         "a copy\n"
2306e5dd7070Spatrick         " * of this software and associated documentation files (the "
2307e5dd7070Spatrick         "\"Software\"),"
2308e5dd7070Spatrick         " to deal\n"
2309e5dd7070Spatrick         " * in the Software without restriction, including without limitation "
2310e5dd7070Spatrick         "the "
2311e5dd7070Spatrick         "rights\n"
2312e5dd7070Spatrick         " * to use, copy, modify, merge, publish, distribute, sublicense, "
2313e5dd7070Spatrick         "and/or sell\n"
2314e5dd7070Spatrick         " * copies of the Software, and to permit persons to whom the Software "
2315e5dd7070Spatrick         "is\n"
2316e5dd7070Spatrick         " * furnished to do so, subject to the following conditions:\n"
2317e5dd7070Spatrick         " *\n"
2318e5dd7070Spatrick         " * The above copyright notice and this permission notice shall be "
2319e5dd7070Spatrick         "included in\n"
2320e5dd7070Spatrick         " * all copies or substantial portions of the Software.\n"
2321e5dd7070Spatrick         " *\n"
2322e5dd7070Spatrick         " * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, "
2323e5dd7070Spatrick         "EXPRESS OR\n"
2324e5dd7070Spatrick         " * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF "
2325e5dd7070Spatrick         "MERCHANTABILITY,\n"
2326e5dd7070Spatrick         " * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT "
2327e5dd7070Spatrick         "SHALL THE\n"
2328e5dd7070Spatrick         " * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR "
2329e5dd7070Spatrick         "OTHER\n"
2330e5dd7070Spatrick         " * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, "
2331e5dd7070Spatrick         "ARISING FROM,\n"
2332e5dd7070Spatrick         " * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER "
2333e5dd7070Spatrick         "DEALINGS IN\n"
2334e5dd7070Spatrick         " * THE SOFTWARE.\n"
2335e5dd7070Spatrick         " *\n"
2336e5dd7070Spatrick         " *===-----------------------------------------------------------------"
2337e5dd7070Spatrick         "---"
2338e5dd7070Spatrick         "---===\n"
2339e5dd7070Spatrick         " */\n\n";
2340e5dd7070Spatrick 
2341e5dd7070Spatrick   OS << "#ifndef __ARM_NEON_H\n";
2342e5dd7070Spatrick   OS << "#define __ARM_NEON_H\n\n";
2343e5dd7070Spatrick 
2344ec727ea7Spatrick   OS << "#ifndef __ARM_FP\n";
2345ec727ea7Spatrick   OS << "#error \"NEON intrinsics not available with the soft-float ABI. "
2346ec727ea7Spatrick         "Please use -mfloat-abi=softfp or -mfloat-abi=hard\"\n";
2347ec727ea7Spatrick   OS << "#else\n\n";
2348ec727ea7Spatrick 
2349e5dd7070Spatrick   OS << "#if !defined(__ARM_NEON)\n";
2350e5dd7070Spatrick   OS << "#error \"NEON support not enabled\"\n";
2351ec727ea7Spatrick   OS << "#else\n\n";
2352e5dd7070Spatrick 
2353e5dd7070Spatrick   OS << "#include <stdint.h>\n\n";
2354e5dd7070Spatrick 
2355ec727ea7Spatrick   OS << "#include <arm_bf16.h>\n";
2356ec727ea7Spatrick   OS << "typedef __bf16 bfloat16_t;\n";
2357ec727ea7Spatrick 
2358e5dd7070Spatrick   // Emit NEON-specific scalar typedefs.
2359e5dd7070Spatrick   OS << "typedef float float32_t;\n";
2360e5dd7070Spatrick   OS << "typedef __fp16 float16_t;\n";
2361e5dd7070Spatrick 
2362e5dd7070Spatrick   OS << "#ifdef __aarch64__\n";
2363e5dd7070Spatrick   OS << "typedef double float64_t;\n";
2364e5dd7070Spatrick   OS << "#endif\n\n";
2365e5dd7070Spatrick 
2366e5dd7070Spatrick   // For now, signedness of polynomial types depends on target
2367e5dd7070Spatrick   OS << "#ifdef __aarch64__\n";
2368e5dd7070Spatrick   OS << "typedef uint8_t poly8_t;\n";
2369e5dd7070Spatrick   OS << "typedef uint16_t poly16_t;\n";
2370e5dd7070Spatrick   OS << "typedef uint64_t poly64_t;\n";
2371e5dd7070Spatrick   OS << "typedef __uint128_t poly128_t;\n";
2372e5dd7070Spatrick   OS << "#else\n";
2373e5dd7070Spatrick   OS << "typedef int8_t poly8_t;\n";
2374e5dd7070Spatrick   OS << "typedef int16_t poly16_t;\n";
2375ec727ea7Spatrick   OS << "typedef int64_t poly64_t;\n";
2376e5dd7070Spatrick   OS << "#endif\n";
2377e5dd7070Spatrick 
2378ec727ea7Spatrick   emitNeonTypeDefs("cQcsQsiQilQlUcQUcUsQUsUiQUiUlQUlhQhfQfdQdPcQPcPsQPsPlQPl", OS);
2379e5dd7070Spatrick 
2380ec727ea7Spatrick   emitNeonTypeDefs("bQb", OS);
2381e5dd7070Spatrick 
2382e5dd7070Spatrick   OS << "#define __ai static __inline__ __attribute__((__always_inline__, "
2383e5dd7070Spatrick         "__nodebug__))\n\n";
2384e5dd7070Spatrick 
2385e5dd7070Spatrick   SmallVector<Intrinsic *, 128> Defs;
2386e5dd7070Spatrick   std::vector<Record *> RV = Records.getAllDerivedDefinitions("Inst");
2387e5dd7070Spatrick   for (auto *R : RV)
2388e5dd7070Spatrick     createIntrinsic(R, Defs);
2389e5dd7070Spatrick 
2390e5dd7070Spatrick   for (auto *I : Defs)
2391e5dd7070Spatrick     I->indexBody();
2392e5dd7070Spatrick 
2393e5dd7070Spatrick   llvm::stable_sort(Defs, llvm::deref<std::less<>>());
2394e5dd7070Spatrick 
2395e5dd7070Spatrick   // Only emit a def when its requirements have been met.
2396e5dd7070Spatrick   // FIXME: This loop could be made faster, but it's fast enough for now.
2397e5dd7070Spatrick   bool MadeProgress = true;
2398e5dd7070Spatrick   std::string InGuard;
2399e5dd7070Spatrick   while (!Defs.empty() && MadeProgress) {
2400e5dd7070Spatrick     MadeProgress = false;
2401e5dd7070Spatrick 
2402e5dd7070Spatrick     for (SmallVector<Intrinsic *, 128>::iterator I = Defs.begin();
2403e5dd7070Spatrick          I != Defs.end(); /*No step*/) {
2404e5dd7070Spatrick       bool DependenciesSatisfied = true;
2405e5dd7070Spatrick       for (auto *II : (*I)->getDependencies()) {
2406e5dd7070Spatrick         if (llvm::is_contained(Defs, II))
2407e5dd7070Spatrick           DependenciesSatisfied = false;
2408e5dd7070Spatrick       }
2409e5dd7070Spatrick       if (!DependenciesSatisfied) {
2410e5dd7070Spatrick         // Try the next one.
2411e5dd7070Spatrick         ++I;
2412e5dd7070Spatrick         continue;
2413e5dd7070Spatrick       }
2414e5dd7070Spatrick 
2415e5dd7070Spatrick       // Emit #endif/#if pair if needed.
2416*12c85518Srobert       if ((*I)->getArchGuard() != InGuard) {
2417e5dd7070Spatrick         if (!InGuard.empty())
2418e5dd7070Spatrick           OS << "#endif\n";
2419*12c85518Srobert         InGuard = (*I)->getArchGuard();
2420e5dd7070Spatrick         if (!InGuard.empty())
2421e5dd7070Spatrick           OS << "#if " << InGuard << "\n";
2422e5dd7070Spatrick       }
2423e5dd7070Spatrick 
2424e5dd7070Spatrick       // Actually generate the intrinsic code.
2425e5dd7070Spatrick       OS << (*I)->generate();
2426e5dd7070Spatrick 
2427e5dd7070Spatrick       MadeProgress = true;
2428e5dd7070Spatrick       I = Defs.erase(I);
2429e5dd7070Spatrick     }
2430e5dd7070Spatrick   }
2431e5dd7070Spatrick   assert(Defs.empty() && "Some requirements were not satisfied!");
2432e5dd7070Spatrick   if (!InGuard.empty())
2433e5dd7070Spatrick     OS << "#endif\n";
2434e5dd7070Spatrick 
2435e5dd7070Spatrick   OS << "\n";
2436e5dd7070Spatrick   OS << "#undef __ai\n\n";
2437ec727ea7Spatrick   OS << "#endif /* if !defined(__ARM_NEON) */\n";
2438ec727ea7Spatrick   OS << "#endif /* ifndef __ARM_FP */\n";
2439e5dd7070Spatrick   OS << "#endif /* __ARM_NEON_H */\n";
2440e5dd7070Spatrick }
2441e5dd7070Spatrick 
2442e5dd7070Spatrick /// run - Read the records in arm_fp16.td and output arm_fp16.h.  arm_fp16.h
2443e5dd7070Spatrick /// is comprised of type definitions and function declarations.
runFP16(raw_ostream & OS)2444e5dd7070Spatrick void NeonEmitter::runFP16(raw_ostream &OS) {
2445e5dd7070Spatrick   OS << "/*===---- arm_fp16.h - ARM FP16 intrinsics "
2446e5dd7070Spatrick         "------------------------------"
2447e5dd7070Spatrick         "---===\n"
2448e5dd7070Spatrick         " *\n"
2449e5dd7070Spatrick         " * Permission is hereby granted, free of charge, to any person "
2450e5dd7070Spatrick         "obtaining a copy\n"
2451e5dd7070Spatrick         " * of this software and associated documentation files (the "
2452e5dd7070Spatrick 				"\"Software\"), to deal\n"
2453e5dd7070Spatrick         " * in the Software without restriction, including without limitation "
2454e5dd7070Spatrick 				"the rights\n"
2455e5dd7070Spatrick         " * to use, copy, modify, merge, publish, distribute, sublicense, "
2456e5dd7070Spatrick 				"and/or sell\n"
2457e5dd7070Spatrick         " * copies of the Software, and to permit persons to whom the Software "
2458e5dd7070Spatrick 				"is\n"
2459e5dd7070Spatrick         " * furnished to do so, subject to the following conditions:\n"
2460e5dd7070Spatrick         " *\n"
2461e5dd7070Spatrick         " * The above copyright notice and this permission notice shall be "
2462e5dd7070Spatrick         "included in\n"
2463e5dd7070Spatrick         " * all copies or substantial portions of the Software.\n"
2464e5dd7070Spatrick         " *\n"
2465e5dd7070Spatrick         " * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, "
2466e5dd7070Spatrick         "EXPRESS OR\n"
2467e5dd7070Spatrick         " * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF "
2468e5dd7070Spatrick         "MERCHANTABILITY,\n"
2469e5dd7070Spatrick         " * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT "
2470e5dd7070Spatrick         "SHALL THE\n"
2471e5dd7070Spatrick         " * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR "
2472e5dd7070Spatrick         "OTHER\n"
2473e5dd7070Spatrick         " * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, "
2474e5dd7070Spatrick         "ARISING FROM,\n"
2475e5dd7070Spatrick         " * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER "
2476e5dd7070Spatrick         "DEALINGS IN\n"
2477e5dd7070Spatrick         " * THE SOFTWARE.\n"
2478e5dd7070Spatrick         " *\n"
2479e5dd7070Spatrick         " *===-----------------------------------------------------------------"
2480e5dd7070Spatrick         "---"
2481e5dd7070Spatrick         "---===\n"
2482e5dd7070Spatrick         " */\n\n";
2483e5dd7070Spatrick 
2484e5dd7070Spatrick   OS << "#ifndef __ARM_FP16_H\n";
2485e5dd7070Spatrick   OS << "#define __ARM_FP16_H\n\n";
2486e5dd7070Spatrick 
2487e5dd7070Spatrick   OS << "#include <stdint.h>\n\n";
2488e5dd7070Spatrick 
2489e5dd7070Spatrick   OS << "typedef __fp16 float16_t;\n";
2490e5dd7070Spatrick 
2491e5dd7070Spatrick   OS << "#define __ai static __inline__ __attribute__((__always_inline__, "
2492e5dd7070Spatrick         "__nodebug__))\n\n";
2493e5dd7070Spatrick 
2494e5dd7070Spatrick   SmallVector<Intrinsic *, 128> Defs;
2495e5dd7070Spatrick   std::vector<Record *> RV = Records.getAllDerivedDefinitions("Inst");
2496e5dd7070Spatrick   for (auto *R : RV)
2497e5dd7070Spatrick     createIntrinsic(R, Defs);
2498e5dd7070Spatrick 
2499e5dd7070Spatrick   for (auto *I : Defs)
2500e5dd7070Spatrick     I->indexBody();
2501e5dd7070Spatrick 
2502e5dd7070Spatrick   llvm::stable_sort(Defs, llvm::deref<std::less<>>());
2503e5dd7070Spatrick 
2504e5dd7070Spatrick   // Only emit a def when its requirements have been met.
2505e5dd7070Spatrick   // FIXME: This loop could be made faster, but it's fast enough for now.
2506e5dd7070Spatrick   bool MadeProgress = true;
2507e5dd7070Spatrick   std::string InGuard;
2508e5dd7070Spatrick   while (!Defs.empty() && MadeProgress) {
2509e5dd7070Spatrick     MadeProgress = false;
2510e5dd7070Spatrick 
2511e5dd7070Spatrick     for (SmallVector<Intrinsic *, 128>::iterator I = Defs.begin();
2512e5dd7070Spatrick          I != Defs.end(); /*No step*/) {
2513e5dd7070Spatrick       bool DependenciesSatisfied = true;
2514e5dd7070Spatrick       for (auto *II : (*I)->getDependencies()) {
2515e5dd7070Spatrick         if (llvm::is_contained(Defs, II))
2516e5dd7070Spatrick           DependenciesSatisfied = false;
2517e5dd7070Spatrick       }
2518e5dd7070Spatrick       if (!DependenciesSatisfied) {
2519e5dd7070Spatrick         // Try the next one.
2520e5dd7070Spatrick         ++I;
2521e5dd7070Spatrick         continue;
2522e5dd7070Spatrick       }
2523e5dd7070Spatrick 
2524e5dd7070Spatrick       // Emit #endif/#if pair if needed.
2525*12c85518Srobert       if ((*I)->getArchGuard() != InGuard) {
2526e5dd7070Spatrick         if (!InGuard.empty())
2527e5dd7070Spatrick           OS << "#endif\n";
2528*12c85518Srobert         InGuard = (*I)->getArchGuard();
2529e5dd7070Spatrick         if (!InGuard.empty())
2530e5dd7070Spatrick           OS << "#if " << InGuard << "\n";
2531e5dd7070Spatrick       }
2532e5dd7070Spatrick 
2533e5dd7070Spatrick       // Actually generate the intrinsic code.
2534e5dd7070Spatrick       OS << (*I)->generate();
2535e5dd7070Spatrick 
2536e5dd7070Spatrick       MadeProgress = true;
2537e5dd7070Spatrick       I = Defs.erase(I);
2538e5dd7070Spatrick     }
2539e5dd7070Spatrick   }
2540e5dd7070Spatrick   assert(Defs.empty() && "Some requirements were not satisfied!");
2541e5dd7070Spatrick   if (!InGuard.empty())
2542e5dd7070Spatrick     OS << "#endif\n";
2543e5dd7070Spatrick 
2544e5dd7070Spatrick   OS << "\n";
2545e5dd7070Spatrick   OS << "#undef __ai\n\n";
2546e5dd7070Spatrick   OS << "#endif /* __ARM_FP16_H */\n";
2547e5dd7070Spatrick }
2548e5dd7070Spatrick 
runBF16(raw_ostream & OS)2549ec727ea7Spatrick void NeonEmitter::runBF16(raw_ostream &OS) {
2550ec727ea7Spatrick   OS << "/*===---- arm_bf16.h - ARM BF16 intrinsics "
2551ec727ea7Spatrick         "-----------------------------------===\n"
2552ec727ea7Spatrick         " *\n"
2553ec727ea7Spatrick         " *\n"
2554ec727ea7Spatrick         " * Part of the LLVM Project, under the Apache License v2.0 with LLVM "
2555ec727ea7Spatrick         "Exceptions.\n"
2556ec727ea7Spatrick         " * See https://llvm.org/LICENSE.txt for license information.\n"
2557ec727ea7Spatrick         " * SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception\n"
2558ec727ea7Spatrick         " *\n"
2559ec727ea7Spatrick         " *===-----------------------------------------------------------------"
2560ec727ea7Spatrick         "------===\n"
2561ec727ea7Spatrick         " */\n\n";
2562ec727ea7Spatrick 
2563ec727ea7Spatrick   OS << "#ifndef __ARM_BF16_H\n";
2564ec727ea7Spatrick   OS << "#define __ARM_BF16_H\n\n";
2565ec727ea7Spatrick 
2566ec727ea7Spatrick   OS << "typedef __bf16 bfloat16_t;\n";
2567ec727ea7Spatrick 
2568ec727ea7Spatrick   OS << "#define __ai static __inline__ __attribute__((__always_inline__, "
2569ec727ea7Spatrick         "__nodebug__))\n\n";
2570ec727ea7Spatrick 
2571ec727ea7Spatrick   SmallVector<Intrinsic *, 128> Defs;
2572ec727ea7Spatrick   std::vector<Record *> RV = Records.getAllDerivedDefinitions("Inst");
2573ec727ea7Spatrick   for (auto *R : RV)
2574ec727ea7Spatrick     createIntrinsic(R, Defs);
2575ec727ea7Spatrick 
2576ec727ea7Spatrick   for (auto *I : Defs)
2577ec727ea7Spatrick     I->indexBody();
2578ec727ea7Spatrick 
2579ec727ea7Spatrick   llvm::stable_sort(Defs, llvm::deref<std::less<>>());
2580ec727ea7Spatrick 
2581ec727ea7Spatrick   // Only emit a def when its requirements have been met.
2582ec727ea7Spatrick   // FIXME: This loop could be made faster, but it's fast enough for now.
2583ec727ea7Spatrick   bool MadeProgress = true;
2584ec727ea7Spatrick   std::string InGuard;
2585ec727ea7Spatrick   while (!Defs.empty() && MadeProgress) {
2586ec727ea7Spatrick     MadeProgress = false;
2587ec727ea7Spatrick 
2588ec727ea7Spatrick     for (SmallVector<Intrinsic *, 128>::iterator I = Defs.begin();
2589ec727ea7Spatrick          I != Defs.end(); /*No step*/) {
2590ec727ea7Spatrick       bool DependenciesSatisfied = true;
2591ec727ea7Spatrick       for (auto *II : (*I)->getDependencies()) {
2592ec727ea7Spatrick         if (llvm::is_contained(Defs, II))
2593ec727ea7Spatrick           DependenciesSatisfied = false;
2594ec727ea7Spatrick       }
2595ec727ea7Spatrick       if (!DependenciesSatisfied) {
2596ec727ea7Spatrick         // Try the next one.
2597ec727ea7Spatrick         ++I;
2598ec727ea7Spatrick         continue;
2599ec727ea7Spatrick       }
2600ec727ea7Spatrick 
2601ec727ea7Spatrick       // Emit #endif/#if pair if needed.
2602*12c85518Srobert       if ((*I)->getArchGuard() != InGuard) {
2603ec727ea7Spatrick         if (!InGuard.empty())
2604ec727ea7Spatrick           OS << "#endif\n";
2605*12c85518Srobert         InGuard = (*I)->getArchGuard();
2606ec727ea7Spatrick         if (!InGuard.empty())
2607ec727ea7Spatrick           OS << "#if " << InGuard << "\n";
2608ec727ea7Spatrick       }
2609ec727ea7Spatrick 
2610ec727ea7Spatrick       // Actually generate the intrinsic code.
2611ec727ea7Spatrick       OS << (*I)->generate();
2612ec727ea7Spatrick 
2613ec727ea7Spatrick       MadeProgress = true;
2614ec727ea7Spatrick       I = Defs.erase(I);
2615ec727ea7Spatrick     }
2616ec727ea7Spatrick   }
2617ec727ea7Spatrick   assert(Defs.empty() && "Some requirements were not satisfied!");
2618ec727ea7Spatrick   if (!InGuard.empty())
2619ec727ea7Spatrick     OS << "#endif\n";
2620ec727ea7Spatrick 
2621ec727ea7Spatrick   OS << "\n";
2622ec727ea7Spatrick   OS << "#undef __ai\n\n";
2623ec727ea7Spatrick 
2624ec727ea7Spatrick   OS << "#endif\n";
2625ec727ea7Spatrick }
2626ec727ea7Spatrick 
EmitNeon(RecordKeeper & Records,raw_ostream & OS)2627e5dd7070Spatrick void clang::EmitNeon(RecordKeeper &Records, raw_ostream &OS) {
2628e5dd7070Spatrick   NeonEmitter(Records).run(OS);
2629e5dd7070Spatrick }
2630e5dd7070Spatrick 
EmitFP16(RecordKeeper & Records,raw_ostream & OS)2631e5dd7070Spatrick void clang::EmitFP16(RecordKeeper &Records, raw_ostream &OS) {
2632e5dd7070Spatrick   NeonEmitter(Records).runFP16(OS);
2633e5dd7070Spatrick }
2634e5dd7070Spatrick 
EmitBF16(RecordKeeper & Records,raw_ostream & OS)2635ec727ea7Spatrick void clang::EmitBF16(RecordKeeper &Records, raw_ostream &OS) {
2636ec727ea7Spatrick   NeonEmitter(Records).runBF16(OS);
2637ec727ea7Spatrick }
2638ec727ea7Spatrick 
EmitNeonSema(RecordKeeper & Records,raw_ostream & OS)2639e5dd7070Spatrick void clang::EmitNeonSema(RecordKeeper &Records, raw_ostream &OS) {
2640e5dd7070Spatrick   NeonEmitter(Records).runHeader(OS);
2641e5dd7070Spatrick }
2642e5dd7070Spatrick 
EmitNeonTest(RecordKeeper & Records,raw_ostream & OS)2643e5dd7070Spatrick void clang::EmitNeonTest(RecordKeeper &Records, raw_ostream &OS) {
2644e5dd7070Spatrick   llvm_unreachable("Neon test generation no longer implemented!");
2645e5dd7070Spatrick }
2646