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