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