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