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