Home | History | Annotate | Download | only in TableGen
      1 //===- IntrinsicEmitter.cpp - Generate intrinsic information --------------===//
      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 emits information about intrinsic functions.
     11 //
     12 //===----------------------------------------------------------------------===//
     13 
     14 #include "CodeGenIntrinsics.h"
     15 #include "CodeGenTarget.h"
     16 #include "SequenceToOffsetTable.h"
     17 #include "llvm/ADT/StringExtras.h"
     18 #include "llvm/TableGen/Error.h"
     19 #include "llvm/TableGen/Record.h"
     20 #include "llvm/TableGen/StringMatcher.h"
     21 #include "llvm/TableGen/TableGenBackend.h"
     22 #include <algorithm>
     23 using namespace llvm;
     24 
     25 namespace {
     26 class IntrinsicEmitter {
     27   RecordKeeper &Records;
     28   bool TargetOnly;
     29   std::string TargetPrefix;
     30 
     31 public:
     32   IntrinsicEmitter(RecordKeeper &R, bool T)
     33     : Records(R), TargetOnly(T) {}
     34 
     35   void run(raw_ostream &OS);
     36 
     37   void EmitPrefix(raw_ostream &OS);
     38 
     39   void EmitEnumInfo(const std::vector<CodeGenIntrinsic> &Ints,
     40                     raw_ostream &OS);
     41 
     42   void EmitFnNameRecognizer(const std::vector<CodeGenIntrinsic> &Ints,
     43                             raw_ostream &OS);
     44   void EmitIntrinsicToNameTable(const std::vector<CodeGenIntrinsic> &Ints,
     45                                 raw_ostream &OS);
     46   void EmitIntrinsicToOverloadTable(const std::vector<CodeGenIntrinsic> &Ints,
     47                                     raw_ostream &OS);
     48   void EmitVerifier(const std::vector<CodeGenIntrinsic> &Ints,
     49                     raw_ostream &OS);
     50   void EmitGenerator(const std::vector<CodeGenIntrinsic> &Ints,
     51                      raw_ostream &OS);
     52   void EmitAttributes(const std::vector<CodeGenIntrinsic> &Ints,
     53                       raw_ostream &OS);
     54   void EmitModRefBehavior(const std::vector<CodeGenIntrinsic> &Ints,
     55                           raw_ostream &OS);
     56   void EmitIntrinsicToGCCBuiltinMap(const std::vector<CodeGenIntrinsic> &Ints,
     57                                     raw_ostream &OS);
     58   void EmitSuffix(raw_ostream &OS);
     59 };
     60 } // End anonymous namespace
     61 
     62 //===----------------------------------------------------------------------===//
     63 // IntrinsicEmitter Implementation
     64 //===----------------------------------------------------------------------===//
     65 
     66 void IntrinsicEmitter::run(raw_ostream &OS) {
     67   emitSourceFileHeader("Intrinsic Function Source Fragment", OS);
     68 
     69   std::vector<CodeGenIntrinsic> Ints = LoadIntrinsics(Records, TargetOnly);
     70 
     71   if (TargetOnly && !Ints.empty())
     72     TargetPrefix = Ints[0].TargetPrefix;
     73 
     74   EmitPrefix(OS);
     75 
     76   // Emit the enum information.
     77   EmitEnumInfo(Ints, OS);
     78 
     79   // Emit the intrinsic ID -> name table.
     80   EmitIntrinsicToNameTable(Ints, OS);
     81 
     82   // Emit the intrinsic ID -> overload table.
     83   EmitIntrinsicToOverloadTable(Ints, OS);
     84 
     85   // Emit the function name recognizer.
     86   EmitFnNameRecognizer(Ints, OS);
     87 
     88   // Emit the intrinsic declaration generator.
     89   EmitGenerator(Ints, OS);
     90 
     91   // Emit the intrinsic parameter attributes.
     92   EmitAttributes(Ints, OS);
     93 
     94   // Emit intrinsic alias analysis mod/ref behavior.
     95   EmitModRefBehavior(Ints, OS);
     96 
     97   // Emit code to translate GCC builtins into LLVM intrinsics.
     98   EmitIntrinsicToGCCBuiltinMap(Ints, OS);
     99 
    100   EmitSuffix(OS);
    101 }
    102 
    103 void IntrinsicEmitter::EmitPrefix(raw_ostream &OS) {
    104   OS << "// VisualStudio defines setjmp as _setjmp\n"
    105         "#if defined(_MSC_VER) && defined(setjmp) && \\\n"
    106         "                         !defined(setjmp_undefined_for_msvc)\n"
    107         "#  pragma push_macro(\"setjmp\")\n"
    108         "#  undef setjmp\n"
    109         "#  define setjmp_undefined_for_msvc\n"
    110         "#endif\n\n";
    111 }
    112 
    113 void IntrinsicEmitter::EmitSuffix(raw_ostream &OS) {
    114   OS << "#if defined(_MSC_VER) && defined(setjmp_undefined_for_msvc)\n"
    115         "// let's return it to _setjmp state\n"
    116         "#  pragma pop_macro(\"setjmp\")\n"
    117         "#  undef setjmp_undefined_for_msvc\n"
    118         "#endif\n\n";
    119 }
    120 
    121 void IntrinsicEmitter::EmitEnumInfo(const std::vector<CodeGenIntrinsic> &Ints,
    122                                     raw_ostream &OS) {
    123   OS << "// Enum values for Intrinsics.h\n";
    124   OS << "#ifdef GET_INTRINSIC_ENUM_VALUES\n";
    125   for (unsigned i = 0, e = Ints.size(); i != e; ++i) {
    126     OS << "    " << Ints[i].EnumName;
    127     OS << ((i != e-1) ? ", " : "  ");
    128     OS << std::string(40-Ints[i].EnumName.size(), ' ')
    129       << "// " << Ints[i].Name << "\n";
    130   }
    131   OS << "#endif\n\n";
    132 }
    133 
    134 struct IntrinsicNameSorter {
    135   IntrinsicNameSorter(const std::vector<CodeGenIntrinsic> &I)
    136   : Ints(I) {}
    137 
    138   // Sort in reverse order of intrinsic name so "abc.def" appears after
    139   // "abd.def.ghi" in the overridden name matcher
    140   bool operator()(unsigned i, unsigned j) {
    141     return Ints[i].Name > Ints[j].Name;
    142   }
    143 
    144 private:
    145   const std::vector<CodeGenIntrinsic> &Ints;
    146 };
    147 
    148 void IntrinsicEmitter::
    149 EmitFnNameRecognizer(const std::vector<CodeGenIntrinsic> &Ints,
    150                      raw_ostream &OS) {
    151   // Build a 'first character of function name' -> intrinsic # mapping.
    152   std::map<char, std::vector<unsigned> > IntMapping;
    153   for (unsigned i = 0, e = Ints.size(); i != e; ++i)
    154     IntMapping[Ints[i].Name[5]].push_back(i);
    155 
    156   OS << "// Function name -> enum value recognizer code.\n";
    157   OS << "#ifdef GET_FUNCTION_RECOGNIZER\n";
    158   OS << "  StringRef NameR(Name+6, Len-6);   // Skip over 'llvm.'\n";
    159   OS << "  switch (Name[5]) {                  // Dispatch on first letter.\n";
    160   OS << "  default: break;\n";
    161   IntrinsicNameSorter Sorter(Ints);
    162   // Emit the intrinsic matching stuff by first letter.
    163   for (std::map<char, std::vector<unsigned> >::iterator I = IntMapping.begin(),
    164        E = IntMapping.end(); I != E; ++I) {
    165     OS << "  case '" << I->first << "':\n";
    166     std::vector<unsigned> &IntList = I->second;
    167 
    168     // Sort intrinsics in reverse order of their names
    169     std::sort(IntList.begin(), IntList.end(), Sorter);
    170 
    171     // Emit all the overloaded intrinsics first, build a table of the
    172     // non-overloaded ones.
    173     std::vector<StringMatcher::StringPair> MatchTable;
    174 
    175     for (unsigned i = 0, e = IntList.size(); i != e; ++i) {
    176       unsigned IntNo = IntList[i];
    177       std::string Result = "return " + TargetPrefix + "Intrinsic::" +
    178         Ints[IntNo].EnumName + ";";
    179 
    180       if (!Ints[IntNo].isOverloaded) {
    181         MatchTable.push_back(std::make_pair(Ints[IntNo].Name.substr(6),Result));
    182         continue;
    183       }
    184 
    185       // For overloaded intrinsics, only the prefix needs to match
    186       std::string TheStr = Ints[IntNo].Name.substr(6);
    187       TheStr += '.';  // Require "bswap." instead of bswap.
    188       OS << "    if (NameR.startswith(\"" << TheStr << "\")) "
    189          << Result << '\n';
    190     }
    191 
    192     // Emit the matcher logic for the fixed length strings.
    193     StringMatcher("NameR", MatchTable, OS).Emit(1);
    194     OS << "    break;  // end of '" << I->first << "' case.\n";
    195   }
    196 
    197   OS << "  }\n";
    198   OS << "#endif\n\n";
    199 }
    200 
    201 void IntrinsicEmitter::
    202 EmitIntrinsicToNameTable(const std::vector<CodeGenIntrinsic> &Ints,
    203                          raw_ostream &OS) {
    204   OS << "// Intrinsic ID to name table\n";
    205   OS << "#ifdef GET_INTRINSIC_NAME_TABLE\n";
    206   OS << "  // Note that entry #0 is the invalid intrinsic!\n";
    207   for (unsigned i = 0, e = Ints.size(); i != e; ++i)
    208     OS << "  \"" << Ints[i].Name << "\",\n";
    209   OS << "#endif\n\n";
    210 }
    211 
    212 void IntrinsicEmitter::
    213 EmitIntrinsicToOverloadTable(const std::vector<CodeGenIntrinsic> &Ints,
    214                          raw_ostream &OS) {
    215   OS << "// Intrinsic ID to overload bitset\n";
    216   OS << "#ifdef GET_INTRINSIC_OVERLOAD_TABLE\n";
    217   OS << "static const uint8_t OTable[] = {\n";
    218   OS << "  0";
    219   for (unsigned i = 0, e = Ints.size(); i != e; ++i) {
    220     // Add one to the index so we emit a null bit for the invalid #0 intrinsic.
    221     if ((i+1)%8 == 0)
    222       OS << ",\n  0";
    223     if (Ints[i].isOverloaded)
    224       OS << " | (1<<" << (i+1)%8 << ')';
    225   }
    226   OS << "\n};\n\n";
    227   // OTable contains a true bit at the position if the intrinsic is overloaded.
    228   OS << "return (OTable[id/8] & (1 << (id%8))) != 0;\n";
    229   OS << "#endif\n\n";
    230 }
    231 
    232 
    233 // NOTE: This must be kept in synch with the copy in lib/VMCore/Function.cpp!
    234 enum IIT_Info {
    235   // Common values should be encoded with 0-15.
    236   IIT_Done = 0,
    237   IIT_I1   = 1,
    238   IIT_I8   = 2,
    239   IIT_I16  = 3,
    240   IIT_I32  = 4,
    241   IIT_I64  = 5,
    242   IIT_F16  = 6,
    243   IIT_F32  = 7,
    244   IIT_F64  = 8,
    245   IIT_V2   = 9,
    246   IIT_V4   = 10,
    247   IIT_V8   = 11,
    248   IIT_V16  = 12,
    249   IIT_V32  = 13,
    250   IIT_PTR  = 14,
    251   IIT_ARG  = 15,
    252 
    253   // Values from 16+ are only encodable with the inefficient encoding.
    254   IIT_MMX  = 16,
    255   IIT_METADATA = 17,
    256   IIT_EMPTYSTRUCT = 18,
    257   IIT_STRUCT2 = 19,
    258   IIT_STRUCT3 = 20,
    259   IIT_STRUCT4 = 21,
    260   IIT_STRUCT5 = 22,
    261   IIT_EXTEND_VEC_ARG = 23,
    262   IIT_TRUNC_VEC_ARG = 24,
    263   IIT_ANYPTR = 25
    264 };
    265 
    266 
    267 static void EncodeFixedValueType(MVT::SimpleValueType VT,
    268                                  std::vector<unsigned char> &Sig) {
    269   if (EVT(VT).isInteger()) {
    270     unsigned BitWidth = EVT(VT).getSizeInBits();
    271     switch (BitWidth) {
    272     default: PrintFatalError("unhandled integer type width in intrinsic!");
    273     case 1: return Sig.push_back(IIT_I1);
    274     case 8: return Sig.push_back(IIT_I8);
    275     case 16: return Sig.push_back(IIT_I16);
    276     case 32: return Sig.push_back(IIT_I32);
    277     case 64: return Sig.push_back(IIT_I64);
    278     }
    279   }
    280 
    281   switch (VT) {
    282   default: PrintFatalError("unhandled MVT in intrinsic!");
    283   case MVT::f16: return Sig.push_back(IIT_F16);
    284   case MVT::f32: return Sig.push_back(IIT_F32);
    285   case MVT::f64: return Sig.push_back(IIT_F64);
    286   case MVT::Metadata: return Sig.push_back(IIT_METADATA);
    287   case MVT::x86mmx: return Sig.push_back(IIT_MMX);
    288   // MVT::OtherVT is used to mean the empty struct type here.
    289   case MVT::Other: return Sig.push_back(IIT_EMPTYSTRUCT);
    290   }
    291 }
    292 
    293 #ifdef _MSC_VER
    294 #pragma optimize("",off) // MSVC 2010 optimizer can't deal with this function.
    295 #endif
    296 
    297 static void EncodeFixedType(Record *R, std::vector<unsigned char> &ArgCodes,
    298                             std::vector<unsigned char> &Sig) {
    299 
    300   if (R->isSubClassOf("LLVMMatchType")) {
    301     unsigned Number = R->getValueAsInt("Number");
    302     assert(Number < ArgCodes.size() && "Invalid matching number!");
    303     if (R->isSubClassOf("LLVMExtendedElementVectorType"))
    304       Sig.push_back(IIT_EXTEND_VEC_ARG);
    305     else if (R->isSubClassOf("LLVMTruncatedElementVectorType"))
    306       Sig.push_back(IIT_TRUNC_VEC_ARG);
    307     else
    308       Sig.push_back(IIT_ARG);
    309     return Sig.push_back((Number << 2) | ArgCodes[Number]);
    310   }
    311 
    312   MVT::SimpleValueType VT = getValueType(R->getValueAsDef("VT"));
    313 
    314   unsigned Tmp = 0;
    315   switch (VT) {
    316   default: break;
    317   case MVT::iPTRAny: ++Tmp; // FALL THROUGH.
    318   case MVT::vAny: ++Tmp; // FALL THROUGH.
    319   case MVT::fAny: ++Tmp; // FALL THROUGH.
    320   case MVT::iAny: {
    321     // If this is an "any" valuetype, then the type is the type of the next
    322     // type in the list specified to getIntrinsic().
    323     Sig.push_back(IIT_ARG);
    324 
    325     // Figure out what arg # this is consuming, and remember what kind it was.
    326     unsigned ArgNo = ArgCodes.size();
    327     ArgCodes.push_back(Tmp);
    328 
    329     // Encode what sort of argument it must be in the low 2 bits of the ArgNo.
    330     return Sig.push_back((ArgNo << 2) | Tmp);
    331   }
    332 
    333   case MVT::iPTR: {
    334     unsigned AddrSpace = 0;
    335     if (R->isSubClassOf("LLVMQualPointerType")) {
    336       AddrSpace = R->getValueAsInt("AddrSpace");
    337       assert(AddrSpace < 256 && "Address space exceeds 255");
    338     }
    339     if (AddrSpace) {
    340       Sig.push_back(IIT_ANYPTR);
    341       Sig.push_back(AddrSpace);
    342     } else {
    343       Sig.push_back(IIT_PTR);
    344     }
    345     return EncodeFixedType(R->getValueAsDef("ElTy"), ArgCodes, Sig);
    346   }
    347   }
    348 
    349   if (EVT(VT).isVector()) {
    350     EVT VVT = VT;
    351     switch (VVT.getVectorNumElements()) {
    352     default: PrintFatalError("unhandled vector type width in intrinsic!");
    353     case 2: Sig.push_back(IIT_V2); break;
    354     case 4: Sig.push_back(IIT_V4); break;
    355     case 8: Sig.push_back(IIT_V8); break;
    356     case 16: Sig.push_back(IIT_V16); break;
    357     case 32: Sig.push_back(IIT_V32); break;
    358     }
    359 
    360     return EncodeFixedValueType(VVT.getVectorElementType().
    361                                 getSimpleVT().SimpleTy, Sig);
    362   }
    363 
    364   EncodeFixedValueType(VT, Sig);
    365 }
    366 
    367 #ifdef _MSC_VER
    368 #pragma optimize("",on)
    369 #endif
    370 
    371 /// ComputeFixedEncoding - If we can encode the type signature for this
    372 /// intrinsic into 32 bits, return it.  If not, return ~0U.
    373 static void ComputeFixedEncoding(const CodeGenIntrinsic &Int,
    374                                  std::vector<unsigned char> &TypeSig) {
    375   std::vector<unsigned char> ArgCodes;
    376 
    377   if (Int.IS.RetVTs.empty())
    378     TypeSig.push_back(IIT_Done);
    379   else if (Int.IS.RetVTs.size() == 1 &&
    380            Int.IS.RetVTs[0] == MVT::isVoid)
    381     TypeSig.push_back(IIT_Done);
    382   else {
    383     switch (Int.IS.RetVTs.size()) {
    384       case 1: break;
    385       case 2: TypeSig.push_back(IIT_STRUCT2); break;
    386       case 3: TypeSig.push_back(IIT_STRUCT3); break;
    387       case 4: TypeSig.push_back(IIT_STRUCT4); break;
    388       case 5: TypeSig.push_back(IIT_STRUCT5); break;
    389       default: assert(0 && "Unhandled case in struct");
    390     }
    391 
    392     for (unsigned i = 0, e = Int.IS.RetVTs.size(); i != e; ++i)
    393       EncodeFixedType(Int.IS.RetTypeDefs[i], ArgCodes, TypeSig);
    394   }
    395 
    396   for (unsigned i = 0, e = Int.IS.ParamTypeDefs.size(); i != e; ++i)
    397     EncodeFixedType(Int.IS.ParamTypeDefs[i], ArgCodes, TypeSig);
    398 }
    399 
    400 static void printIITEntry(raw_ostream &OS, unsigned char X) {
    401   OS << (unsigned)X;
    402 }
    403 
    404 void IntrinsicEmitter::EmitGenerator(const std::vector<CodeGenIntrinsic> &Ints,
    405                                      raw_ostream &OS) {
    406   // If we can compute a 32-bit fixed encoding for this intrinsic, do so and
    407   // capture it in this vector, otherwise store a ~0U.
    408   std::vector<unsigned> FixedEncodings;
    409 
    410   SequenceToOffsetTable<std::vector<unsigned char> > LongEncodingTable;
    411 
    412   std::vector<unsigned char> TypeSig;
    413 
    414   // Compute the unique argument type info.
    415   for (unsigned i = 0, e = Ints.size(); i != e; ++i) {
    416     // Get the signature for the intrinsic.
    417     TypeSig.clear();
    418     ComputeFixedEncoding(Ints[i], TypeSig);
    419 
    420     // Check to see if we can encode it into a 32-bit word.  We can only encode
    421     // 8 nibbles into a 32-bit word.
    422     if (TypeSig.size() <= 8) {
    423       bool Failed = false;
    424       unsigned Result = 0;
    425       for (unsigned i = 0, e = TypeSig.size(); i != e; ++i) {
    426         // If we had an unencodable argument, bail out.
    427         if (TypeSig[i] > 15) {
    428           Failed = true;
    429           break;
    430         }
    431         Result = (Result << 4) | TypeSig[e-i-1];
    432       }
    433 
    434       // If this could be encoded into a 31-bit word, return it.
    435       if (!Failed && (Result >> 31) == 0) {
    436         FixedEncodings.push_back(Result);
    437         continue;
    438       }
    439     }
    440 
    441     // Otherwise, we're going to unique the sequence into the
    442     // LongEncodingTable, and use its offset in the 32-bit table instead.
    443     LongEncodingTable.add(TypeSig);
    444 
    445     // This is a placehold that we'll replace after the table is laid out.
    446     FixedEncodings.push_back(~0U);
    447   }
    448 
    449   LongEncodingTable.layout();
    450 
    451   OS << "// Global intrinsic function declaration type table.\n";
    452   OS << "#ifdef GET_INTRINSIC_GENERATOR_GLOBAL\n";
    453 
    454   OS << "static const unsigned IIT_Table[] = {\n  ";
    455 
    456   for (unsigned i = 0, e = FixedEncodings.size(); i != e; ++i) {
    457     if ((i & 7) == 7)
    458       OS << "\n  ";
    459 
    460     // If the entry fit in the table, just emit it.
    461     if (FixedEncodings[i] != ~0U) {
    462       OS << "0x" << utohexstr(FixedEncodings[i]) << ", ";
    463       continue;
    464     }
    465 
    466     TypeSig.clear();
    467     ComputeFixedEncoding(Ints[i], TypeSig);
    468 
    469 
    470     // Otherwise, emit the offset into the long encoding table.  We emit it this
    471     // way so that it is easier to read the offset in the .def file.
    472     OS << "(1U<<31) | " << LongEncodingTable.get(TypeSig) << ", ";
    473   }
    474 
    475   OS << "0\n};\n\n";
    476 
    477   // Emit the shared table of register lists.
    478   OS << "static const unsigned char IIT_LongEncodingTable[] = {\n";
    479   if (!LongEncodingTable.empty())
    480     LongEncodingTable.emit(OS, printIITEntry);
    481   OS << "  255\n};\n\n";
    482 
    483   OS << "#endif\n\n";  // End of GET_INTRINSIC_GENERATOR_GLOBAL
    484 }
    485 
    486 enum ModRefKind {
    487   MRK_none,
    488   MRK_readonly,
    489   MRK_readnone
    490 };
    491 
    492 static ModRefKind getModRefKind(const CodeGenIntrinsic &intrinsic) {
    493   switch (intrinsic.ModRef) {
    494   case CodeGenIntrinsic::NoMem:
    495     return MRK_readnone;
    496   case CodeGenIntrinsic::ReadArgMem:
    497   case CodeGenIntrinsic::ReadMem:
    498     return MRK_readonly;
    499   case CodeGenIntrinsic::ReadWriteArgMem:
    500   case CodeGenIntrinsic::ReadWriteMem:
    501     return MRK_none;
    502   }
    503   llvm_unreachable("bad mod-ref kind");
    504 }
    505 
    506 namespace {
    507 struct AttributeComparator {
    508   bool operator()(const CodeGenIntrinsic *L, const CodeGenIntrinsic *R) const {
    509     // Sort throwing intrinsics after non-throwing intrinsics.
    510     if (L->canThrow != R->canThrow)
    511       return R->canThrow;
    512 
    513     if (L->isNoReturn != R->isNoReturn)
    514       return R->isNoReturn;
    515 
    516     // Try to order by readonly/readnone attribute.
    517     ModRefKind LK = getModRefKind(*L);
    518     ModRefKind RK = getModRefKind(*R);
    519     if (LK != RK) return (LK > RK);
    520 
    521     // Order by argument attributes.
    522     // This is reliable because each side is already sorted internally.
    523     return (L->ArgumentAttributes < R->ArgumentAttributes);
    524   }
    525 };
    526 } // End anonymous namespace
    527 
    528 /// EmitAttributes - This emits the Intrinsic::getAttributes method.
    529 void IntrinsicEmitter::
    530 EmitAttributes(const std::vector<CodeGenIntrinsic> &Ints, raw_ostream &OS) {
    531   OS << "// Add parameter attributes that are not common to all intrinsics.\n";
    532   OS << "#ifdef GET_INTRINSIC_ATTRIBUTES\n";
    533   if (TargetOnly)
    534     OS << "static AttributeSet getAttributes(LLVMContext &C, " << TargetPrefix
    535        << "Intrinsic::ID id) {\n";
    536   else
    537     OS << "AttributeSet Intrinsic::getAttributes(LLVMContext &C, ID id) {\n";
    538 
    539   // Compute the maximum number of attribute arguments and the map
    540   typedef std::map<const CodeGenIntrinsic*, unsigned,
    541                    AttributeComparator> UniqAttrMapTy;
    542   UniqAttrMapTy UniqAttributes;
    543   unsigned maxArgAttrs = 0;
    544   unsigned AttrNum = 0;
    545   for (unsigned i = 0, e = Ints.size(); i != e; ++i) {
    546     const CodeGenIntrinsic &intrinsic = Ints[i];
    547     maxArgAttrs =
    548       std::max(maxArgAttrs, unsigned(intrinsic.ArgumentAttributes.size()));
    549     unsigned &N = UniqAttributes[&intrinsic];
    550     if (N) continue;
    551     assert(AttrNum < 256 && "Too many unique attributes for table!");
    552     N = ++AttrNum;
    553   }
    554 
    555   // Emit an array of AttributeSet.  Most intrinsics will have at least one
    556   // entry, for the function itself (index ~1), which is usually nounwind.
    557   OS << "  static const uint8_t IntrinsicsToAttributesMap[] = {\n";
    558 
    559   for (unsigned i = 0, e = Ints.size(); i != e; ++i) {
    560     const CodeGenIntrinsic &intrinsic = Ints[i];
    561 
    562     OS << "    " << UniqAttributes[&intrinsic] << ", // "
    563        << intrinsic.Name << "\n";
    564   }
    565   OS << "  };\n\n";
    566 
    567   OS << "  AttributeSet AS[" << maxArgAttrs+1 << "];\n";
    568   OS << "  unsigned NumAttrs = 0;\n";
    569   OS << "  if (id != 0) {\n";
    570   OS << "    SmallVector<Attribute::AttrKind, 8> AttrVec;\n";
    571   OS << "    switch(IntrinsicsToAttributesMap[id - ";
    572   if (TargetOnly)
    573     OS << "Intrinsic::num_intrinsics";
    574   else
    575     OS << "1";
    576   OS << "]) {\n";
    577   OS << "    default: llvm_unreachable(\"Invalid attribute number\");\n";
    578   for (UniqAttrMapTy::const_iterator I = UniqAttributes.begin(),
    579        E = UniqAttributes.end(); I != E; ++I) {
    580     OS << "    case " << I->second << ":\n";
    581 
    582     const CodeGenIntrinsic &intrinsic = *(I->first);
    583 
    584     // Keep track of the number of attributes we're writing out.
    585     unsigned numAttrs = 0;
    586 
    587     // The argument attributes are alreadys sorted by argument index.
    588     unsigned ai = 0, ae = intrinsic.ArgumentAttributes.size();
    589     if (ae) {
    590       while (ai != ae) {
    591         unsigned argNo = intrinsic.ArgumentAttributes[ai].first;
    592 
    593         OS << "      AttrVec.clear();\n";
    594 
    595         do {
    596           switch (intrinsic.ArgumentAttributes[ai].second) {
    597           case CodeGenIntrinsic::NoCapture:
    598             OS << "      AttrVec.push_back(Attribute::NoCapture);\n";
    599             break;
    600           case CodeGenIntrinsic::ReadOnly:
    601             OS << "      AttrVec.push_back(Attribute::ReadOnly);\n";
    602             break;
    603           case CodeGenIntrinsic::ReadNone:
    604             OS << "      AttrVec.push_back(Attribute::ReadNone);\n";
    605             break;
    606           }
    607 
    608           ++ai;
    609         } while (ai != ae && intrinsic.ArgumentAttributes[ai].first == argNo);
    610 
    611         OS << "      AS[" << numAttrs++ << "] = AttributeSet::get(C, "
    612            << argNo+1 << ", AttrVec);\n";
    613       }
    614     }
    615 
    616     ModRefKind modRef = getModRefKind(intrinsic);
    617 
    618     if (!intrinsic.canThrow || modRef || intrinsic.isNoReturn) {
    619       OS << "      AttrVec.clear();\n";
    620 
    621       if (!intrinsic.canThrow)
    622         OS << "      AttrVec.push_back(Attribute::NoUnwind);\n";
    623       if (intrinsic.isNoReturn)
    624         OS << "      AttrVec.push_back(Attribute::NoReturn);\n";
    625 
    626       switch (modRef) {
    627       case MRK_none: break;
    628       case MRK_readonly:
    629         OS << "      AttrVec.push_back(Attribute::ReadOnly);\n";
    630         break;
    631       case MRK_readnone:
    632         OS << "      AttrVec.push_back(Attribute::ReadNone);\n";
    633         break;
    634       }
    635       OS << "      AS[" << numAttrs++ << "] = AttributeSet::get(C, "
    636          << "AttributeSet::FunctionIndex, AttrVec);\n";
    637     }
    638 
    639     if (numAttrs) {
    640       OS << "      NumAttrs = " << numAttrs << ";\n";
    641       OS << "      break;\n";
    642     } else {
    643       OS << "      return AttributeSet();\n";
    644     }
    645   }
    646 
    647   OS << "    }\n";
    648   OS << "  }\n";
    649   OS << "  return AttributeSet::get(C, ArrayRef<AttributeSet>(AS, "
    650              "NumAttrs));\n";
    651   OS << "}\n";
    652   OS << "#endif // GET_INTRINSIC_ATTRIBUTES\n\n";
    653 }
    654 
    655 /// EmitModRefBehavior - Determine intrinsic alias analysis mod/ref behavior.
    656 void IntrinsicEmitter::
    657 EmitModRefBehavior(const std::vector<CodeGenIntrinsic> &Ints, raw_ostream &OS){
    658   OS << "// Determine intrinsic alias analysis mod/ref behavior.\n"
    659      << "#ifdef GET_INTRINSIC_MODREF_BEHAVIOR\n"
    660      << "assert(iid <= Intrinsic::" << Ints.back().EnumName << " && "
    661      << "\"Unknown intrinsic.\");\n\n";
    662 
    663   OS << "static const uint8_t IntrinsicModRefBehavior[] = {\n"
    664      << "  /* invalid */ UnknownModRefBehavior,\n";
    665   for (unsigned i = 0, e = Ints.size(); i != e; ++i) {
    666     OS << "  /* " << TargetPrefix << Ints[i].EnumName << " */ ";
    667     switch (Ints[i].ModRef) {
    668     case CodeGenIntrinsic::NoMem:
    669       OS << "DoesNotAccessMemory,\n";
    670       break;
    671     case CodeGenIntrinsic::ReadArgMem:
    672       OS << "OnlyReadsArgumentPointees,\n";
    673       break;
    674     case CodeGenIntrinsic::ReadMem:
    675       OS << "OnlyReadsMemory,\n";
    676       break;
    677     case CodeGenIntrinsic::ReadWriteArgMem:
    678       OS << "OnlyAccessesArgumentPointees,\n";
    679       break;
    680     case CodeGenIntrinsic::ReadWriteMem:
    681       OS << "UnknownModRefBehavior,\n";
    682       break;
    683     }
    684   }
    685   OS << "};\n\n"
    686      << "return static_cast<ModRefBehavior>(IntrinsicModRefBehavior[iid]);\n"
    687      << "#endif // GET_INTRINSIC_MODREF_BEHAVIOR\n\n";
    688 }
    689 
    690 /// EmitTargetBuiltins - All of the builtins in the specified map are for the
    691 /// same target, and we already checked it.
    692 static void EmitTargetBuiltins(const std::map<std::string, std::string> &BIM,
    693                                const std::string &TargetPrefix,
    694                                raw_ostream &OS) {
    695 
    696   std::vector<StringMatcher::StringPair> Results;
    697 
    698   for (std::map<std::string, std::string>::const_iterator I = BIM.begin(),
    699        E = BIM.end(); I != E; ++I) {
    700     std::string ResultCode =
    701     "return " + TargetPrefix + "Intrinsic::" + I->second + ";";
    702     Results.push_back(StringMatcher::StringPair(I->first, ResultCode));
    703   }
    704 
    705   StringMatcher("BuiltinName", Results, OS).Emit();
    706 }
    707 
    708 
    709 void IntrinsicEmitter::
    710 EmitIntrinsicToGCCBuiltinMap(const std::vector<CodeGenIntrinsic> &Ints,
    711                              raw_ostream &OS) {
    712   typedef std::map<std::string, std::map<std::string, std::string> > BIMTy;
    713   BIMTy BuiltinMap;
    714   for (unsigned i = 0, e = Ints.size(); i != e; ++i) {
    715     if (!Ints[i].GCCBuiltinName.empty()) {
    716       // Get the map for this target prefix.
    717       std::map<std::string, std::string> &BIM =BuiltinMap[Ints[i].TargetPrefix];
    718 
    719       if (!BIM.insert(std::make_pair(Ints[i].GCCBuiltinName,
    720                                      Ints[i].EnumName)).second)
    721         PrintFatalError("Intrinsic '" + Ints[i].TheDef->getName() +
    722               "': duplicate GCC builtin name!");
    723     }
    724   }
    725 
    726   OS << "// Get the LLVM intrinsic that corresponds to a GCC builtin.\n";
    727   OS << "// This is used by the C front-end.  The GCC builtin name is passed\n";
    728   OS << "// in as BuiltinName, and a target prefix (e.g. 'ppc') is passed\n";
    729   OS << "// in as TargetPrefix.  The result is assigned to 'IntrinsicID'.\n";
    730   OS << "#ifdef GET_LLVM_INTRINSIC_FOR_GCC_BUILTIN\n";
    731 
    732   if (TargetOnly) {
    733     OS << "static " << TargetPrefix << "Intrinsic::ID "
    734        << "getIntrinsicForGCCBuiltin(const char "
    735        << "*TargetPrefixStr, const char *BuiltinNameStr) {\n";
    736   } else {
    737     OS << "Intrinsic::ID Intrinsic::getIntrinsicForGCCBuiltin(const char "
    738        << "*TargetPrefixStr, const char *BuiltinNameStr) {\n";
    739   }
    740 
    741   OS << "  StringRef BuiltinName(BuiltinNameStr);\n";
    742   OS << "  StringRef TargetPrefix(TargetPrefixStr);\n\n";
    743 
    744   // Note: this could emit significantly better code if we cared.
    745   for (BIMTy::iterator I = BuiltinMap.begin(), E = BuiltinMap.end();I != E;++I){
    746     OS << "  ";
    747     if (!I->first.empty())
    748       OS << "if (TargetPrefix == \"" << I->first << "\") ";
    749     else
    750       OS << "/* Target Independent Builtins */ ";
    751     OS << "{\n";
    752 
    753     // Emit the comparisons for this target prefix.
    754     EmitTargetBuiltins(I->second, TargetPrefix, OS);
    755     OS << "  }\n";
    756   }
    757   OS << "  return ";
    758   if (!TargetPrefix.empty())
    759     OS << "(" << TargetPrefix << "Intrinsic::ID)";
    760   OS << "Intrinsic::not_intrinsic;\n";
    761   OS << "}\n";
    762   OS << "#endif\n\n";
    763 }
    764 
    765 namespace llvm {
    766 
    767 void EmitIntrinsics(RecordKeeper &RK, raw_ostream &OS, bool TargetOnly = false) {
    768   IntrinsicEmitter(RK, TargetOnly).run(OS);
    769 }
    770 
    771 } // End llvm namespace
    772