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