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