enhance the intrinsic info stuff to emit encodings that don't fit in 32-bits into a
[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 version emitted to the .gen file!
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 };
343
344
345 static void EncodeFixedValueType(MVT::SimpleValueType VT,
346                                  std::vector<unsigned char> &Sig) {
347   if (EVT(VT).isInteger()) {
348     unsigned BitWidth = EVT(VT).getSizeInBits();
349     switch (BitWidth) {
350     default: throw "unhandled integer type width in intrinsic!";
351     case 1: return Sig.push_back(IIT_I1);
352     case 8: return Sig.push_back(IIT_I8);
353     case 16: return Sig.push_back(IIT_I16);
354     case 32: return Sig.push_back(IIT_I32);
355     case 64: return Sig.push_back(IIT_I64);
356     }
357   }
358   
359   switch (VT) {
360   default: throw "unhandled MVT in intrinsic!";
361   case MVT::f32: return Sig.push_back(IIT_F32);
362   case MVT::f64: return Sig.push_back(IIT_F64);
363   case MVT::Metadata: return Sig.push_back(IIT_METADATA);
364   case MVT::x86mmx: return Sig.push_back(IIT_MMX);
365   // MVT::OtherVT is used to mean the empty struct type here.
366   case MVT::Other: return Sig.push_back(IIT_EMPTYSTRUCT);
367   }
368 }
369
370 #ifdef _MSC_VER
371 #pragma optimize("",off) // MSVC 2010 optimizer can't deal with this function.
372 #endif 
373
374 static void EncodeFixedType(Record *R, unsigned &NextArgNo,
375                             std::vector<unsigned char> &Sig) {
376   
377   if (R->isSubClassOf("LLVMMatchType")) {
378     unsigned Number = R->getValueAsInt("Number");
379     assert(Number < NextArgNo && "Invalid matching number!");
380     if (R->isSubClassOf("LLVMExtendedElementVectorType"))
381       Sig.push_back(IIT_EXTEND_VEC_ARG);
382     else if (R->isSubClassOf("LLVMTruncatedElementVectorType"))
383       Sig.push_back(IIT_TRUNC_VEC_ARG);
384     else
385       Sig.push_back(IIT_ARG);
386     return Sig.push_back(Number);
387   }
388   
389   MVT::SimpleValueType VT = getValueType(R->getValueAsDef("VT"));
390
391   // If this is an "any" valuetype, then the type is the type of the next
392   // type in the list specified to getIntrinsic().  
393   if (VT == MVT::iAny || VT == MVT::fAny || VT == MVT::vAny ||
394       VT == MVT::iPTRAny) {
395     Sig.push_back(IIT_ARG);
396     return Sig.push_back(NextArgNo++);
397   }
398   
399   if (EVT(VT).isVector()) {
400     EVT VVT = VT;
401     switch (VVT.getVectorNumElements()) {
402     default: throw "unhandled vector type width in intrinsic!";
403     case 2: Sig.push_back(IIT_V2); break;
404     case 4: Sig.push_back(IIT_V4); break;
405     case 8: Sig.push_back(IIT_V8); break;
406     case 16: Sig.push_back(IIT_V16); break;
407     case 32: Sig.push_back(IIT_V32); break;
408     }
409     
410     return EncodeFixedValueType(VVT.getVectorElementType().
411                                 getSimpleVT().SimpleTy, Sig);
412   }
413   
414   if (VT == MVT::iPTR) {
415     Sig.push_back(IIT_PTR);
416     return EncodeFixedType(R->getValueAsDef("ElTy"), NextArgNo, Sig);
417   }
418   
419   EncodeFixedValueType(VT, Sig);
420 }
421
422 #ifdef _MSC_VER
423 #pragma optimize("",on)
424 #endif
425
426 /// ComputeFixedEncoding - If we can encode the type signature for this
427 /// intrinsic into 32 bits, return it.  If not, return ~0U.
428 static void ComputeFixedEncoding(const CodeGenIntrinsic &Int,
429                                  std::vector<unsigned char> &TypeSig) {
430   unsigned NextArgNo = 0;
431   
432   if (Int.IS.RetVTs.empty())
433     TypeSig.push_back(IIT_Done);
434   else if (Int.IS.RetVTs.size() == 1 &&
435            Int.IS.RetVTs[0] == MVT::isVoid)
436     TypeSig.push_back(IIT_Done);
437   else {
438     switch (Int.IS.RetVTs.size()) {
439       case 1: break;
440       case 2: TypeSig.push_back(IIT_STRUCT2); break;
441       case 3: TypeSig.push_back(IIT_STRUCT3); break;
442       case 4: TypeSig.push_back(IIT_STRUCT4); break;
443       case 5: TypeSig.push_back(IIT_STRUCT5); break;
444       default: assert(0 && "Unhandled case in struct");
445     }
446     
447     for (unsigned i = 0, e = Int.IS.RetVTs.size(); i != e; ++i)
448       EncodeFixedType(Int.IS.RetTypeDefs[i], NextArgNo, TypeSig);
449   }
450   
451   for (unsigned i = 0, e = Int.IS.ParamTypeDefs.size(); i != e; ++i)
452     EncodeFixedType(Int.IS.ParamTypeDefs[i], NextArgNo, TypeSig);
453 }
454
455 void printIITEntry(raw_ostream &OS, unsigned char X) {
456   OS << (unsigned)X;
457 }
458
459 void IntrinsicEmitter::EmitGenerator(const std::vector<CodeGenIntrinsic> &Ints, 
460                                      raw_ostream &OS) {
461   OS << "// Global intrinsic function declaration type table.\n";
462   OS << "#ifdef GET_INTRINSTIC_GENERATOR_GLOBAL\n";
463   // NOTE: These enums must be kept in sync with the ones above!
464   OS << "enum IIT_Info {\n";
465   OS << "  IIT_Done = 0,\n";
466   OS << "  IIT_I1   = 1,\n";
467   OS << "  IIT_I8   = 2,\n";
468   OS << "  IIT_I16  = 3,\n";
469   OS << "  IIT_I32  = 4,\n";
470   OS << "  IIT_I64  = 5,\n";
471   OS << "  IIT_F32  = 6,\n";
472   OS << "  IIT_F64  = 7,\n";
473   OS << "  IIT_V2   = 8,\n";
474   OS << "  IIT_V4   = 9,\n";
475   OS << "  IIT_V8   = 10,\n";
476   OS << "  IIT_V16  = 11,\n";
477   OS << "  IIT_V32  = 12,\n";
478   OS << "  IIT_MMX  = 13,\n";
479   OS << "  IIT_PTR  = 14,\n";
480   OS << "  IIT_ARG  = 15,\n";
481   OS << "  IIT_METADATA = 16,\n";
482   OS << "  IIT_EMPTYSTRUCT = 17,\n";
483   OS << "  IIT_STRUCT2 = 18,\n";
484   OS << "  IIT_STRUCT3 = 19,\n";
485   OS << "  IIT_STRUCT4 = 20,\n";
486   OS << "  IIT_STRUCT5 = 21,\n";
487   OS << "  IIT_EXTEND_VEC_ARG = 22,\n";
488   OS << "  IIT_TRUNC_VEC_ARG = 23\n";
489   OS << "};\n\n";
490
491   
492   // If we can compute a 32-bit fixed encoding for this intrinsic, do so and
493   // capture it in this vector, otherwise store a ~0U.
494   std::vector<unsigned> FixedEncodings;
495   
496   SequenceToOffsetTable<std::vector<unsigned char> > LongEncodingTable;
497   
498   std::vector<unsigned char> TypeSig;
499   
500   // Compute the unique argument type info.
501   for (unsigned i = 0, e = Ints.size(); i != e; ++i) {
502     // Get the signature for the intrinsic.
503     TypeSig.clear();
504     ComputeFixedEncoding(Ints[i], TypeSig);
505
506     // Check to see if we can encode it into a 32-bit word.  We can only encode
507     // 8 nibbles into a 32-bit word.
508     if (TypeSig.size() <= 8) {
509       bool Failed = false;
510       unsigned Result = 0;
511       for (unsigned i = 0, e = TypeSig.size(); i != e; ++i) {
512         // If we had an unencodable argument, bail out.
513         if (TypeSig[i] > 15) {
514           Failed = true;
515           break;
516         }
517         Result = (Result << 4) | TypeSig[e-i-1];
518       }
519       
520       // If this could be encoded into a 31-bit word, return it.
521       if (!Failed && (Result >> 31) == 0) {
522         FixedEncodings.push_back(Result);
523         continue;
524       }
525     }
526
527     // Otherwise, we're going to unique the sequence into the
528     // LongEncodingTable, and use its offset in the 32-bit table instead.
529     LongEncodingTable.add(TypeSig);
530       
531     // This is a placehold that we'll replace after the table is laid out.
532     FixedEncodings.push_back(~0U);
533   }
534   
535   LongEncodingTable.layout();
536   
537   OS << "static const unsigned IIT_Table[] = {\n  ";
538   
539   for (unsigned i = 0, e = FixedEncodings.size(); i != e; ++i) {
540     if ((i & 7) == 7)
541       OS << "\n  ";
542     
543     // If the entry fit in the table, just emit it.
544     if (FixedEncodings[i] != ~0U) {
545       OS << "0x" << utohexstr(FixedEncodings[i]) << ", ";
546       continue;
547     }
548     
549     TypeSig.clear();
550     ComputeFixedEncoding(Ints[i], TypeSig);
551
552     
553     // Otherwise, emit the offset into the long encoding table.  We emit it this
554     // way so that it is easier to read the offset in the .def file.
555     OS << "(1U<<31) | " << LongEncodingTable.get(TypeSig) << ", ";
556   }
557   
558   OS << "0\n};\n\n";
559   
560   // Emit the shared table of register lists.
561   OS << "static const unsigned char IIT_LongEncodingTable[] = {\n";
562   if (!LongEncodingTable.empty())
563     LongEncodingTable.emit(OS, printIITEntry);
564   OS << "  255\n};\n\n";
565   
566   OS << "#endif\n\n";  // End of GET_INTRINSTIC_GENERATOR_GLOBAL
567 }
568
569 namespace {
570   enum ModRefKind {
571     MRK_none,
572     MRK_readonly,
573     MRK_readnone
574   };
575
576   ModRefKind getModRefKind(const CodeGenIntrinsic &intrinsic) {
577     switch (intrinsic.ModRef) {
578     case CodeGenIntrinsic::NoMem:
579       return MRK_readnone;
580     case CodeGenIntrinsic::ReadArgMem:
581     case CodeGenIntrinsic::ReadMem:
582       return MRK_readonly;
583     case CodeGenIntrinsic::ReadWriteArgMem:
584     case CodeGenIntrinsic::ReadWriteMem:
585       return MRK_none;
586     }
587     llvm_unreachable("bad mod-ref kind");
588   }
589
590   struct AttributeComparator {
591     bool operator()(const CodeGenIntrinsic *L, const CodeGenIntrinsic *R) const {
592       // Sort throwing intrinsics after non-throwing intrinsics.
593       if (L->canThrow != R->canThrow)
594         return R->canThrow;
595
596       // Try to order by readonly/readnone attribute.
597       ModRefKind LK = getModRefKind(*L);
598       ModRefKind RK = getModRefKind(*R);
599       if (LK != RK) return (LK > RK);
600
601       // Order by argument attributes.
602       // This is reliable because each side is already sorted internally.
603       return (L->ArgumentAttributes < R->ArgumentAttributes);
604     }
605   };
606 }
607
608 /// EmitAttributes - This emits the Intrinsic::getAttributes method.
609 void IntrinsicEmitter::
610 EmitAttributes(const std::vector<CodeGenIntrinsic> &Ints, raw_ostream &OS) {
611   OS << "// Add parameter attributes that are not common to all intrinsics.\n";
612   OS << "#ifdef GET_INTRINSIC_ATTRIBUTES\n";
613   if (TargetOnly)
614     OS << "static AttrListPtr getAttributes(" << TargetPrefix 
615        << "Intrinsic::ID id) {\n";
616   else
617     OS << "AttrListPtr Intrinsic::getAttributes(ID id) {\n";
618
619   // Compute the maximum number of attribute arguments and the map
620   typedef std::map<const CodeGenIntrinsic*, unsigned,
621                    AttributeComparator> UniqAttrMapTy;
622   UniqAttrMapTy UniqAttributes;
623   unsigned maxArgAttrs = 0;
624   unsigned AttrNum = 0;
625   for (unsigned i = 0, e = Ints.size(); i != e; ++i) {
626     const CodeGenIntrinsic &intrinsic = Ints[i];
627     maxArgAttrs =
628       std::max(maxArgAttrs, unsigned(intrinsic.ArgumentAttributes.size()));
629     unsigned &N = UniqAttributes[&intrinsic];
630     if (N) continue;
631     assert(AttrNum < 256 && "Too many unique attributes for table!");
632     N = ++AttrNum;
633   }
634
635   // Emit an array of AttributeWithIndex.  Most intrinsics will have
636   // at least one entry, for the function itself (index ~1), which is
637   // usually nounwind.
638   OS << "  static const uint8_t IntrinsicsToAttributesMap[] = {\n";
639
640   for (unsigned i = 0, e = Ints.size(); i != e; ++i) {
641     const CodeGenIntrinsic &intrinsic = Ints[i];
642
643     OS << "    " << UniqAttributes[&intrinsic] << ", // "
644        << intrinsic.Name << "\n";
645   }
646   OS << "  };\n\n";
647
648   OS << "  AttributeWithIndex AWI[" << maxArgAttrs+1 << "];\n";
649   OS << "  unsigned NumAttrs = 0;\n";
650   OS << "  if (id != 0) {\n";
651   OS << "    switch(IntrinsicsToAttributesMap[id - ";
652   if (TargetOnly)
653     OS << "Intrinsic::num_intrinsics";
654   else
655     OS << "1";
656   OS << "]) {\n";
657   OS << "    default: llvm_unreachable(\"Invalid attribute number\");\n";
658   for (UniqAttrMapTy::const_iterator I = UniqAttributes.begin(),
659        E = UniqAttributes.end(); I != E; ++I) {
660     OS << "    case " << I->second << ":\n";
661
662     const CodeGenIntrinsic &intrinsic = *(I->first);
663
664     // Keep track of the number of attributes we're writing out.
665     unsigned numAttrs = 0;
666
667     // The argument attributes are alreadys sorted by argument index.
668     for (unsigned ai = 0, ae = intrinsic.ArgumentAttributes.size(); ai != ae;) {
669       unsigned argNo = intrinsic.ArgumentAttributes[ai].first;
670
671       OS << "      AWI[" << numAttrs++ << "] = AttributeWithIndex::get("
672          << argNo+1 << ", ";
673
674       bool moreThanOne = false;
675
676       do {
677         if (moreThanOne) OS << '|';
678
679         switch (intrinsic.ArgumentAttributes[ai].second) {
680         case CodeGenIntrinsic::NoCapture:
681           OS << "Attribute::NoCapture";
682           break;
683         }
684
685         ++ai;
686         moreThanOne = true;
687       } while (ai != ae && intrinsic.ArgumentAttributes[ai].first == argNo);
688
689       OS << ");\n";
690     }
691
692     ModRefKind modRef = getModRefKind(intrinsic);
693
694     if (!intrinsic.canThrow || modRef) {
695       OS << "      AWI[" << numAttrs++ << "] = AttributeWithIndex::get(~0, ";
696       if (!intrinsic.canThrow) {
697         OS << "Attribute::NoUnwind";
698         if (modRef) OS << '|';
699       }
700       switch (modRef) {
701       case MRK_none: break;
702       case MRK_readonly: OS << "Attribute::ReadOnly"; break;
703       case MRK_readnone: OS << "Attribute::ReadNone"; break;
704       }
705       OS << ");\n";
706     }
707
708     if (numAttrs) {
709       OS << "      NumAttrs = " << numAttrs << ";\n";
710       OS << "      break;\n";
711     } else {
712       OS << "      return AttrListPtr();\n";
713     }
714   }
715   
716   OS << "    }\n";
717   OS << "  }\n";
718   OS << "  return AttrListPtr::get(AWI, NumAttrs);\n";
719   OS << "}\n";
720   OS << "#endif // GET_INTRINSIC_ATTRIBUTES\n\n";
721 }
722
723 /// EmitModRefBehavior - Determine intrinsic alias analysis mod/ref behavior.
724 void IntrinsicEmitter::
725 EmitModRefBehavior(const std::vector<CodeGenIntrinsic> &Ints, raw_ostream &OS){
726   OS << "// Determine intrinsic alias analysis mod/ref behavior.\n"
727      << "#ifdef GET_INTRINSIC_MODREF_BEHAVIOR\n"
728      << "assert(iid <= Intrinsic::" << Ints.back().EnumName << " && "
729      << "\"Unknown intrinsic.\");\n\n";
730
731   OS << "static const uint8_t IntrinsicModRefBehavior[] = {\n"
732      << "  /* invalid */ UnknownModRefBehavior,\n";
733   for (unsigned i = 0, e = Ints.size(); i != e; ++i) {
734     OS << "  /* " << TargetPrefix << Ints[i].EnumName << " */ ";
735     switch (Ints[i].ModRef) {
736     case CodeGenIntrinsic::NoMem:
737       OS << "DoesNotAccessMemory,\n";
738       break;
739     case CodeGenIntrinsic::ReadArgMem:
740       OS << "OnlyReadsArgumentPointees,\n";
741       break;
742     case CodeGenIntrinsic::ReadMem:
743       OS << "OnlyReadsMemory,\n";
744       break;
745     case CodeGenIntrinsic::ReadWriteArgMem:
746       OS << "OnlyAccessesArgumentPointees,\n";
747       break;
748     case CodeGenIntrinsic::ReadWriteMem:
749       OS << "UnknownModRefBehavior,\n";
750       break;
751     }
752   }
753   OS << "};\n\n"
754      << "return static_cast<ModRefBehavior>(IntrinsicModRefBehavior[iid]);\n"
755      << "#endif // GET_INTRINSIC_MODREF_BEHAVIOR\n\n";
756 }
757
758 /// EmitTargetBuiltins - All of the builtins in the specified map are for the
759 /// same target, and we already checked it.
760 static void EmitTargetBuiltins(const std::map<std::string, std::string> &BIM,
761                                const std::string &TargetPrefix,
762                                raw_ostream &OS) {
763   
764   std::vector<StringMatcher::StringPair> Results;
765   
766   for (std::map<std::string, std::string>::const_iterator I = BIM.begin(),
767        E = BIM.end(); I != E; ++I) {
768     std::string ResultCode =
769     "return " + TargetPrefix + "Intrinsic::" + I->second + ";";
770     Results.push_back(StringMatcher::StringPair(I->first, ResultCode));
771   }
772
773   StringMatcher("BuiltinName", Results, OS).Emit();
774 }
775
776         
777 void IntrinsicEmitter::
778 EmitIntrinsicToGCCBuiltinMap(const std::vector<CodeGenIntrinsic> &Ints, 
779                              raw_ostream &OS) {
780   typedef std::map<std::string, std::map<std::string, std::string> > BIMTy;
781   BIMTy BuiltinMap;
782   for (unsigned i = 0, e = Ints.size(); i != e; ++i) {
783     if (!Ints[i].GCCBuiltinName.empty()) {
784       // Get the map for this target prefix.
785       std::map<std::string, std::string> &BIM =BuiltinMap[Ints[i].TargetPrefix];
786       
787       if (!BIM.insert(std::make_pair(Ints[i].GCCBuiltinName,
788                                      Ints[i].EnumName)).second)
789         throw "Intrinsic '" + Ints[i].TheDef->getName() +
790               "': duplicate GCC builtin name!";
791     }
792   }
793   
794   OS << "// Get the LLVM intrinsic that corresponds to a GCC builtin.\n";
795   OS << "// This is used by the C front-end.  The GCC builtin name is passed\n";
796   OS << "// in as BuiltinName, and a target prefix (e.g. 'ppc') is passed\n";
797   OS << "// in as TargetPrefix.  The result is assigned to 'IntrinsicID'.\n";
798   OS << "#ifdef GET_LLVM_INTRINSIC_FOR_GCC_BUILTIN\n";
799   
800   if (TargetOnly) {
801     OS << "static " << TargetPrefix << "Intrinsic::ID "
802        << "getIntrinsicForGCCBuiltin(const char "
803        << "*TargetPrefixStr, const char *BuiltinNameStr) {\n";
804   } else {
805     OS << "Intrinsic::ID Intrinsic::getIntrinsicForGCCBuiltin(const char "
806        << "*TargetPrefixStr, const char *BuiltinNameStr) {\n";
807   }
808   
809   OS << "  StringRef BuiltinName(BuiltinNameStr);\n";
810   OS << "  StringRef TargetPrefix(TargetPrefixStr);\n\n";
811   
812   // Note: this could emit significantly better code if we cared.
813   for (BIMTy::iterator I = BuiltinMap.begin(), E = BuiltinMap.end();I != E;++I){
814     OS << "  ";
815     if (!I->first.empty())
816       OS << "if (TargetPrefix == \"" << I->first << "\") ";
817     else
818       OS << "/* Target Independent Builtins */ ";
819     OS << "{\n";
820
821     // Emit the comparisons for this target prefix.
822     EmitTargetBuiltins(I->second, TargetPrefix, OS);
823     OS << "  }\n";
824   }
825   OS << "  return ";
826   if (!TargetPrefix.empty())
827     OS << "(" << TargetPrefix << "Intrinsic::ID)";
828   OS << "Intrinsic::not_intrinsic;\n";
829   OS << "}\n";
830   OS << "#endif\n\n";
831 }