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