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