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