New feature: add support for target intrinsics being defined in the
[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 "Record.h"
17 #include "llvm/ADT/StringExtras.h"
18 #include <algorithm>
19 using namespace llvm;
20
21 //===----------------------------------------------------------------------===//
22 // IntrinsicEmitter Implementation
23 //===----------------------------------------------------------------------===//
24
25 void IntrinsicEmitter::run(std::ostream &OS) {
26   EmitSourceFileHeader("Intrinsic Function Source Fragment", OS);
27   
28   std::vector<CodeGenIntrinsic> Ints = LoadIntrinsics(Records, TargetOnly);
29   
30   if (TargetOnly && !Ints.empty())
31     TargetPrefix = Ints[0].TargetPrefix;
32
33   // Emit the enum information.
34   EmitEnumInfo(Ints, OS);
35
36   // Emit the intrinsic ID -> name table.
37   EmitIntrinsicToNameTable(Ints, OS);
38   
39   // Emit the function name recognizer.
40   EmitFnNameRecognizer(Ints, OS);
41   
42   // Emit the intrinsic verifier.
43   EmitVerifier(Ints, OS);
44   
45   // Emit the intrinsic declaration generator.
46   EmitGenerator(Ints, OS);
47   
48   // Emit the intrinsic parameter attributes.
49   EmitAttributes(Ints, OS);
50
51   // Emit a list of intrinsics with corresponding GCC builtins.
52   EmitGCCBuiltinList(Ints, OS);
53
54   // Emit code to translate GCC builtins into LLVM intrinsics.
55   EmitIntrinsicToGCCBuiltinMap(Ints, OS);
56 }
57
58 void IntrinsicEmitter::EmitEnumInfo(const std::vector<CodeGenIntrinsic> &Ints,
59                                     std::ostream &OS) {
60   OS << "// Enum values for Intrinsics.h\n";
61   OS << "#ifdef GET_INTRINSIC_ENUM_VALUES\n";
62   for (unsigned i = 0, e = Ints.size(); i != e; ++i) {
63     OS << "    " << Ints[i].EnumName;
64     OS << ((i != e-1) ? ", " : "  ");
65     OS << std::string(40-Ints[i].EnumName.size(), ' ') 
66       << "// " << Ints[i].Name << "\n";
67   }
68   OS << "#endif\n\n";
69 }
70
71 void IntrinsicEmitter::
72 EmitFnNameRecognizer(const std::vector<CodeGenIntrinsic> &Ints, 
73                      std::ostream &OS) {
74   // Build a function name -> intrinsic name mapping.
75   std::map<std::string, unsigned> IntMapping;
76   for (unsigned i = 0, e = Ints.size(); i != e; ++i)
77     IntMapping[Ints[i].Name] = i;
78     
79   OS << "// Function name -> enum value recognizer code.\n";
80   OS << "#ifdef GET_FUNCTION_RECOGNIZER\n";
81   OS << "  switch (Name[5]) {\n";
82   OS << "  default:\n";
83   // Emit the intrinsics in sorted order.
84   char LastChar = 0;
85   for (std::map<std::string, unsigned>::iterator I = IntMapping.begin(),
86        E = IntMapping.end(); I != E; ++I) {
87     if (I->first[5] != LastChar) {
88       LastChar = I->first[5];
89       OS << "    break;\n";
90       OS << "  case '" << LastChar << "':\n";
91     }
92     
93     // For overloaded intrinsics, only the prefix needs to match
94     if (Ints[I->second].isOverloaded)
95       OS << "    if (Len > " << I->first.size()
96        << " && !memcmp(Name, \"" << I->first << ".\", "
97        << (I->first.size() + 1) << ")) return " << TargetPrefix << "Intrinsic::"
98        << Ints[I->second].EnumName << ";\n";
99     else 
100       OS << "    if (Len == " << I->first.size()
101          << " && !memcmp(Name, \"" << I->first << "\", "
102          << I->first.size() << ")) return " << TargetPrefix << "Intrinsic::"
103          << Ints[I->second].EnumName << ";\n";
104   }
105   OS << "  }\n";
106   OS << "#endif\n\n";
107 }
108
109 void IntrinsicEmitter::
110 EmitIntrinsicToNameTable(const std::vector<CodeGenIntrinsic> &Ints, 
111                          std::ostream &OS) {
112   OS << "// Intrinsic ID to name table\n";
113   OS << "#ifdef GET_INTRINSIC_NAME_TABLE\n";
114   OS << "  // Note that entry #0 is the invalid intrinsic!\n";
115   for (unsigned i = 0, e = Ints.size(); i != e; ++i)
116     OS << "  \"" << Ints[i].Name << "\",\n";
117   OS << "#endif\n\n";
118 }
119
120 static void EmitTypeForValueType(std::ostream &OS, MVT::SimpleValueType VT) {
121   if (MVT(VT).isInteger()) {
122     unsigned BitWidth = MVT(VT).getSizeInBits();
123     OS << "IntegerType::get(" << BitWidth << ")";
124   } else if (VT == MVT::Other) {
125     // MVT::OtherVT is used to mean the empty struct type here.
126     OS << "StructType::get(std::vector<const Type *>())";
127   } else if (VT == MVT::f32) {
128     OS << "Type::FloatTy";
129   } else if (VT == MVT::f64) {
130     OS << "Type::DoubleTy";
131   } else if (VT == MVT::f80) {
132     OS << "Type::X86_FP80Ty";
133   } else if (VT == MVT::f128) {
134     OS << "Type::FP128Ty";
135   } else if (VT == MVT::ppcf128) {
136     OS << "Type::PPC_FP128Ty";
137   } else if (VT == MVT::isVoid) {
138     OS << "Type::VoidTy";
139   } else {
140     assert(false && "Unsupported ValueType!");
141   }
142 }
143
144 static void EmitTypeGenerate(std::ostream &OS, const Record *ArgType,
145                              unsigned &ArgNo);
146
147 static void EmitTypeGenerate(std::ostream &OS,
148                              const std::vector<Record*> &ArgTypes,
149                              unsigned &ArgNo) {
150   if (ArgTypes.size() == 1) {
151     EmitTypeGenerate(OS, ArgTypes.front(), ArgNo);
152     return;
153   }
154
155   OS << "StructType::get(";
156
157   for (std::vector<Record*>::const_iterator
158          I = ArgTypes.begin(), E = ArgTypes.end(); I != E; ++I) {
159     EmitTypeGenerate(OS, *I, ArgNo);
160     OS << ", ";
161   }
162
163   OS << " NULL)";
164 }
165
166 static void EmitTypeGenerate(std::ostream &OS, const Record *ArgType,
167                              unsigned &ArgNo) {
168   MVT::SimpleValueType VT = getValueType(ArgType->getValueAsDef("VT"));
169
170   if (ArgType->isSubClassOf("LLVMMatchType")) {
171     unsigned Number = ArgType->getValueAsInt("Number");
172     assert(Number < ArgNo && "Invalid matching number!");
173     if (ArgType->isSubClassOf("LLVMExtendedElementVectorType"))
174       OS << "VectorType::getExtendedElementVectorType"
175          << "(dyn_cast<VectorType>(Tys[" << Number << "]))";
176     else if (ArgType->isSubClassOf("LLVMTruncatedElementVectorType"))
177       OS << "VectorType::getTruncatedElementVectorType"
178          << "(dyn_cast<VectorType>(Tys[" << Number << "]))";
179     else
180       OS << "Tys[" << Number << "]";
181   } else if (VT == MVT::iAny || VT == MVT::fAny) {
182     // NOTE: The ArgNo variable here is not the absolute argument number, it is
183     // the index of the "arbitrary" type in the Tys array passed to the
184     // Intrinsic::getDeclaration function. Consequently, we only want to
185     // increment it when we actually hit an overloaded type. Getting this wrong
186     // leads to very subtle bugs!
187     OS << "Tys[" << ArgNo++ << "]";
188   } else if (MVT(VT).isVector()) {
189     MVT VVT = VT;
190     OS << "VectorType::get(";
191     EmitTypeForValueType(OS, VVT.getVectorElementType().getSimpleVT());
192     OS << ", " << VVT.getVectorNumElements() << ")";
193   } else if (VT == MVT::iPTR) {
194     OS << "PointerType::getUnqual(";
195     EmitTypeGenerate(OS, ArgType->getValueAsDef("ElTy"), ArgNo);
196     OS << ")";
197   } else if (VT == MVT::iPTRAny) {
198     // Make sure the user has passed us an argument type to overload. If not,
199     // treat it as an ordinary (not overloaded) intrinsic.
200     OS << "(" << ArgNo << " < numTys) ? Tys[" << ArgNo 
201     << "] : PointerType::getUnqual(";
202     EmitTypeGenerate(OS, ArgType->getValueAsDef("ElTy"), ArgNo);
203     OS << ")";
204     ++ArgNo;
205   } else if (VT == MVT::isVoid) {
206     if (ArgNo == 0)
207       OS << "Type::VoidTy";
208     else
209       // MVT::isVoid is used to mean varargs here.
210       OS << "...";
211   } else {
212     EmitTypeForValueType(OS, VT);
213   }
214 }
215
216 /// RecordListComparator - Provide a determinstic comparator for lists of
217 /// records.
218 namespace {
219   typedef std::pair<std::vector<Record*>, std::vector<Record*> > RecPair;
220   struct RecordListComparator {
221     bool operator()(const RecPair &LHS,
222                     const RecPair &RHS) const {
223       unsigned i = 0;
224       const std::vector<Record*> *LHSVec = &LHS.first;
225       const std::vector<Record*> *RHSVec = &RHS.first;
226       unsigned RHSSize = RHSVec->size();
227       unsigned LHSSize = LHSVec->size();
228
229       do {
230         if (i == RHSSize) return false;  // RHS is shorter than LHS.
231         if ((*LHSVec)[i] != (*RHSVec)[i])
232           return (*LHSVec)[i]->getName() < (*RHSVec)[i]->getName();
233       } while (++i != LHSSize);
234
235       if (i != RHSSize) return true;
236
237       i = 0;
238       LHSVec = &LHS.second;
239       RHSVec = &RHS.second;
240       RHSSize = RHSVec->size();
241       LHSSize = LHSVec->size();
242
243       for (i = 0; i != LHSSize; ++i) {
244         if (i == RHSSize) return false;  // RHS is shorter than LHS.
245         if ((*LHSVec)[i] != (*RHSVec)[i])
246           return (*LHSVec)[i]->getName() < (*RHSVec)[i]->getName();
247       }
248
249       return i != RHSSize;
250     }
251   };
252 }
253
254 void IntrinsicEmitter::EmitVerifier(const std::vector<CodeGenIntrinsic> &Ints, 
255                                     std::ostream &OS) {
256   OS << "// Verifier::visitIntrinsicFunctionCall code.\n";
257   OS << "#ifdef GET_INTRINSIC_VERIFIER\n";
258   OS << "  switch (ID) {\n";
259   OS << "  default: assert(0 && \"Invalid intrinsic!\");\n";
260   
261   // This checking can emit a lot of very common code.  To reduce the amount of
262   // code that we emit, batch up cases that have identical types.  This avoids
263   // problems where GCC can run out of memory compiling Verifier.cpp.
264   typedef std::map<RecPair, std::vector<unsigned>, RecordListComparator> MapTy;
265   MapTy UniqueArgInfos;
266   
267   // Compute the unique argument type info.
268   for (unsigned i = 0, e = Ints.size(); i != e; ++i)
269     UniqueArgInfos[make_pair(Ints[i].IS.RetTypeDefs,
270                              Ints[i].IS.ParamTypeDefs)].push_back(i);
271
272   // Loop through the array, emitting one comparison for each batch.
273   for (MapTy::iterator I = UniqueArgInfos.begin(),
274        E = UniqueArgInfos.end(); I != E; ++I) {
275     for (unsigned i = 0, e = I->second.size(); i != e; ++i)
276       OS << "  case Intrinsic::" << Ints[I->second[i]].EnumName << ":\t\t// "
277          << Ints[I->second[i]].Name << "\n";
278     
279     const RecPair &ArgTypes = I->first;
280     const std::vector<Record*> &RetTys = ArgTypes.first;
281     const std::vector<Record*> &ParamTys = ArgTypes.second;
282
283     OS << "    VerifyIntrinsicPrototype(ID, IF, " << RetTys.size() << ", "
284        << ParamTys.size();
285
286     // Emit return types.
287     for (unsigned j = 0, je = RetTys.size(); j != je; ++j) {
288       Record *ArgType = RetTys[j];
289       OS << ", ";
290
291       if (ArgType->isSubClassOf("LLVMMatchType")) {
292         unsigned Number = ArgType->getValueAsInt("Number");
293         assert(Number < j && "Invalid matching number!");
294         if (ArgType->isSubClassOf("LLVMExtendedElementVectorType"))
295           OS << "~(ExtendedElementVectorType | " << Number << ")";
296         else if (ArgType->isSubClassOf("LLVMTruncatedElementVectorType"))
297           OS << "~(TruncatedElementVectorType | " << Number << ")";
298         else
299           OS << "~" << Number;
300       } else {
301         MVT::SimpleValueType VT = getValueType(ArgType->getValueAsDef("VT"));
302         OS << getEnumName(VT);
303
304         if (VT == MVT::isVoid && j != 0 && j != je - 1)
305           throw "Var arg type not last argument";
306       }
307     }
308
309     // Emit the parameter types.
310     for (unsigned j = 0, je = ParamTys.size(); j != je; ++j) {
311       Record *ArgType = ParamTys[j];
312       OS << ", ";
313
314       if (ArgType->isSubClassOf("LLVMMatchType")) {
315         unsigned Number = ArgType->getValueAsInt("Number");
316         assert(Number < j + RetTys.size() && "Invalid matching number!");
317         if (ArgType->isSubClassOf("LLVMExtendedElementVectorType"))
318           OS << "~(ExtendedElementVectorType | " << Number << ")";
319         else if (ArgType->isSubClassOf("LLVMTruncatedElementVectorType"))
320           OS << "~(TruncatedElementVectorType | " << Number << ")";
321         else
322           OS << "~" << Number;
323       } else {
324         MVT::SimpleValueType VT = getValueType(ArgType->getValueAsDef("VT"));
325         OS << getEnumName(VT);
326
327         if (VT == MVT::isVoid && j != 0 && j != je - 1)
328           throw "Var arg type not last argument";
329       }
330     }
331       
332     OS << ");\n";
333     OS << "    break;\n";
334   }
335   OS << "  }\n";
336   OS << "#endif\n\n";
337 }
338
339 void IntrinsicEmitter::EmitGenerator(const std::vector<CodeGenIntrinsic> &Ints, 
340                                      std::ostream &OS) {
341   OS << "// Code for generating Intrinsic function declarations.\n";
342   OS << "#ifdef GET_INTRINSIC_GENERATOR\n";
343   OS << "  switch (id) {\n";
344   OS << "  default: assert(0 && \"Invalid intrinsic!\");\n";
345   
346   // Similar to GET_INTRINSIC_VERIFIER, batch up cases that have identical
347   // types.
348   typedef std::map<RecPair, std::vector<unsigned>, RecordListComparator> MapTy;
349   MapTy UniqueArgInfos;
350   
351   // Compute the unique argument type info.
352   for (unsigned i = 0, e = Ints.size(); i != e; ++i)
353     UniqueArgInfos[make_pair(Ints[i].IS.RetTypeDefs,
354                              Ints[i].IS.ParamTypeDefs)].push_back(i);
355
356   // Loop through the array, emitting one generator for each batch.
357   std::string IntrinsicStr = TargetPrefix + "Intrinsic::";
358   
359   for (MapTy::iterator I = UniqueArgInfos.begin(),
360        E = UniqueArgInfos.end(); I != E; ++I) {
361     for (unsigned i = 0, e = I->second.size(); i != e; ++i)
362       OS << "  case " << IntrinsicStr << Ints[I->second[i]].EnumName 
363          << ":\t\t// " << Ints[I->second[i]].Name << "\n";
364     
365     const RecPair &ArgTypes = I->first;
366     const std::vector<Record*> &RetTys = ArgTypes.first;
367     const std::vector<Record*> &ParamTys = ArgTypes.second;
368
369     unsigned N = ParamTys.size();
370
371     if (N > 1 &&
372         getValueType(ParamTys[N - 1]->getValueAsDef("VT")) == MVT::isVoid) {
373       OS << "    IsVarArg = true;\n";
374       --N;
375     }
376
377     unsigned ArgNo = 0;
378     OS << "    ResultTy = ";
379     EmitTypeGenerate(OS, RetTys, ArgNo);
380     OS << ";\n";
381     
382     for (unsigned j = 0; j != N; ++j) {
383       OS << "    ArgTys.push_back(";
384       EmitTypeGenerate(OS, ParamTys[j], ArgNo);
385       OS << ");\n";
386     }
387
388     OS << "    break;\n";
389   }
390
391   OS << "  }\n";
392   OS << "#endif\n\n";
393 }
394
395 /// EmitAttributes - This emits the Intrinsic::getAttributes method.
396 void IntrinsicEmitter::
397 EmitAttributes(const std::vector<CodeGenIntrinsic> &Ints, std::ostream &OS) {
398   OS << "// Add parameter attributes that are not common to all intrinsics.\n";
399   OS << "#ifdef GET_INTRINSIC_ATTRIBUTES\n";
400   if (TargetOnly)
401     OS << "static AttrListPtr getAttributes(" << TargetPrefix 
402        << "Intrinsic::ID id) {";
403   else
404     OS << "AttrListPtr Intrinsic::getAttributes(ID id) {";
405   OS << "  // No intrinsic can throw exceptions.\n";
406   OS << "  Attributes Attr = Attribute::NoUnwind;\n";
407   OS << "  switch (id) {\n";
408   OS << "  default: break;\n";
409   unsigned MaxArgAttrs = 0;
410   for (unsigned i = 0, e = Ints.size(); i != e; ++i) {
411     MaxArgAttrs =
412       std::max(MaxArgAttrs, unsigned(Ints[i].ArgumentAttributes.size()));
413     switch (Ints[i].ModRef) {
414     default: break;
415     case CodeGenIntrinsic::NoMem:
416       OS << "  case " << TargetPrefix << "Intrinsic::" << Ints[i].EnumName 
417          << ":\n";
418       break;
419     }
420   }
421   OS << "    Attr |= Attribute::ReadNone; // These do not access memory.\n";
422   OS << "    break;\n";
423   for (unsigned i = 0, e = Ints.size(); i != e; ++i) {
424     switch (Ints[i].ModRef) {
425     default: break;
426     case CodeGenIntrinsic::ReadArgMem:
427     case CodeGenIntrinsic::ReadMem:
428       OS << "  case " << TargetPrefix << "Intrinsic::" << Ints[i].EnumName 
429          << ":\n";
430       break;
431     }
432   }
433   OS << "    Attr |= Attribute::ReadOnly; // These do not write memory.\n";
434   OS << "    break;\n";
435   OS << "  }\n";
436   OS << "  AttributeWithIndex AWI[" << MaxArgAttrs+1 << "];\n";
437   OS << "  unsigned NumAttrs = 0;\n";
438   OS << "  switch (id) {\n";
439   OS << "  default: break;\n";
440   
441   // Add argument attributes for any intrinsics that have them.
442   for (unsigned i = 0, e = Ints.size(); i != e; ++i) {
443     if (Ints[i].ArgumentAttributes.empty()) continue;
444     
445     OS << "  case " << TargetPrefix << "Intrinsic::" << Ints[i].EnumName 
446        << ":\n";
447
448     std::vector<std::pair<unsigned, CodeGenIntrinsic::ArgAttribute> > ArgAttrs =
449       Ints[i].ArgumentAttributes;
450     // Sort by argument index.
451     std::sort(ArgAttrs.begin(), ArgAttrs.end());
452
453     unsigned NumArgsWithAttrs = 0;
454
455     while (!ArgAttrs.empty()) {
456       unsigned ArgNo = ArgAttrs[0].first;
457       
458       OS << "    AWI[" << NumArgsWithAttrs++ << "] = AttributeWithIndex::get("
459          << ArgNo+1 << ", 0";
460
461       while (!ArgAttrs.empty() && ArgAttrs[0].first == ArgNo) {
462         switch (ArgAttrs[0].second) {
463         default: assert(0 && "Unknown arg attribute");
464         case CodeGenIntrinsic::NoCapture:
465           OS << "|Attribute::NoCapture";
466           break;
467         }
468         ArgAttrs.erase(ArgAttrs.begin());
469       }
470       OS << ");\n";
471     }
472     
473     OS << "    NumAttrs = " << NumArgsWithAttrs << ";\n";
474     OS << "    break;\n";
475   }
476   
477   OS << "  }\n";
478   OS << "  AWI[NumAttrs] = AttributeWithIndex::get(~0, Attr);\n";
479   OS << "  return AttrListPtr::get(AWI, NumAttrs+1);\n";
480   OS << "}\n";
481   OS << "#endif // GET_INTRINSIC_ATTRIBUTES\n\n";
482 }
483
484 void IntrinsicEmitter::
485 EmitGCCBuiltinList(const std::vector<CodeGenIntrinsic> &Ints, std::ostream &OS){
486   OS << "// Get the GCC builtin that corresponds to an LLVM intrinsic.\n";
487   OS << "#ifdef GET_GCC_BUILTIN_NAME\n";
488   OS << "  switch (F->getIntrinsicID()) {\n";
489   OS << "  default: BuiltinName = \"\"; break;\n";
490   for (unsigned i = 0, e = Ints.size(); i != e; ++i) {
491     if (!Ints[i].GCCBuiltinName.empty()) {
492       OS << "  case Intrinsic::" << Ints[i].EnumName << ": BuiltinName = \""
493          << Ints[i].GCCBuiltinName << "\"; break;\n";
494     }
495   }
496   OS << "  }\n";
497   OS << "#endif\n\n";
498 }
499
500 /// EmitBuiltinComparisons - Emit comparisons to determine whether the specified
501 /// sorted range of builtin names is equal to the current builtin.  This breaks
502 /// it down into a simple tree.
503 ///
504 /// At this point, we know that all the builtins in the range have the same name
505 /// for the first 'CharStart' characters.  Only the end of the name needs to be
506 /// discriminated.
507 typedef std::map<std::string, std::string>::const_iterator StrMapIterator;
508 static void EmitBuiltinComparisons(StrMapIterator Start, StrMapIterator End,
509                                    unsigned CharStart, unsigned Indent,
510                                    std::string TargetPrefix, std::ostream &OS) {
511   if (Start == End) return; // empty range.
512   
513   // Determine what, if anything, is the same about all these strings.
514   std::string CommonString = Start->first;
515   unsigned NumInRange = 0;
516   for (StrMapIterator I = Start; I != End; ++I, ++NumInRange) {
517     // Find the first character that doesn't match.
518     const std::string &ThisStr = I->first;
519     unsigned NonMatchChar = CharStart;
520     while (NonMatchChar < CommonString.size() && 
521            NonMatchChar < ThisStr.size() &&
522            CommonString[NonMatchChar] == ThisStr[NonMatchChar])
523       ++NonMatchChar;
524     // Truncate off pieces that don't match.
525     CommonString.resize(NonMatchChar);
526   }
527   
528   // Just compare the rest of the string.
529   if (NumInRange == 1) {
530     if (CharStart != CommonString.size()) {
531       OS << std::string(Indent*2, ' ') << "if (!memcmp(BuiltinName";
532       if (CharStart) OS << "+" << CharStart;
533       OS << ", \"" << (CommonString.c_str()+CharStart) << "\", ";
534       OS << CommonString.size() - CharStart << "))\n";
535       ++Indent;
536     }
537     OS << std::string(Indent*2, ' ') << "IntrinsicID = " << TargetPrefix
538        << "Intrinsic::";
539     OS << Start->second << ";\n";
540     return;
541   }
542
543   // At this point, we potentially have a common prefix for these builtins, emit
544   // a check for this common prefix.
545   if (CommonString.size() != CharStart) {
546     OS << std::string(Indent*2, ' ') << "if (!memcmp(BuiltinName";
547     if (CharStart) OS << "+" << CharStart;
548     OS << ", \"" << (CommonString.c_str()+CharStart) << "\", ";
549     OS << CommonString.size()-CharStart << ")) {\n";
550     
551     EmitBuiltinComparisons(Start, End, CommonString.size(), Indent+1, 
552                            TargetPrefix, OS);
553     OS << std::string(Indent*2, ' ') << "}\n";
554     return;
555   }
556   
557   // Output a switch on the character that differs across the set.
558   OS << std::string(Indent*2, ' ') << "switch (BuiltinName[" << CharStart
559       << "]) {";
560   if (CharStart)
561     OS << "  // \"" << std::string(Start->first.begin(), 
562                                    Start->first.begin()+CharStart) << "\"";
563   OS << "\n";
564   
565   for (StrMapIterator I = Start; I != End; ) {
566     char ThisChar = I->first[CharStart];
567     OS << std::string(Indent*2, ' ') << "case '" << ThisChar << "':\n";
568     // Figure out the range that has this common character.
569     StrMapIterator NextChar = I;
570     for (++NextChar; NextChar != End && NextChar->first[CharStart] == ThisChar;
571          ++NextChar)
572       /*empty*/;
573     EmitBuiltinComparisons(I, NextChar, CharStart+1, Indent+1, TargetPrefix,OS);
574     OS << std::string(Indent*2, ' ') << "  break;\n";
575     I = NextChar;
576   }
577   OS << std::string(Indent*2, ' ') << "}\n";
578 }
579
580 /// EmitTargetBuiltins - All of the builtins in the specified map are for the
581 /// same target, and we already checked it.
582 static void EmitTargetBuiltins(const std::map<std::string, std::string> &BIM,
583                                const std::string &TargetPrefix,
584                                std::ostream &OS) {
585   // Rearrange the builtins by length.
586   std::vector<std::map<std::string, std::string> > BuiltinsByLen;
587   BuiltinsByLen.reserve(100);
588   
589   for (StrMapIterator I = BIM.begin(), E = BIM.end(); I != E; ++I) {
590     if (I->first.size() >= BuiltinsByLen.size())
591       BuiltinsByLen.resize(I->first.size()+1);
592     BuiltinsByLen[I->first.size()].insert(*I);
593   }
594   
595   // Now that we have all the builtins by their length, emit a switch stmt.
596   OS << "    switch (strlen(BuiltinName)) {\n";
597   OS << "    default: break;\n";
598   for (unsigned i = 0, e = BuiltinsByLen.size(); i != e; ++i) {
599     if (BuiltinsByLen[i].empty()) continue;
600     OS << "    case " << i << ":\n";
601     EmitBuiltinComparisons(BuiltinsByLen[i].begin(), BuiltinsByLen[i].end(),
602                            0, 3, TargetPrefix, OS);
603     OS << "      break;\n";
604   }
605   OS << "    }\n";
606 }
607
608         
609 void IntrinsicEmitter::
610 EmitIntrinsicToGCCBuiltinMap(const std::vector<CodeGenIntrinsic> &Ints, 
611                              std::ostream &OS) {
612   typedef std::map<std::string, std::map<std::string, std::string> > BIMTy;
613   BIMTy BuiltinMap;
614   for (unsigned i = 0, e = Ints.size(); i != e; ++i) {
615     if (!Ints[i].GCCBuiltinName.empty()) {
616       // Get the map for this target prefix.
617       std::map<std::string, std::string> &BIM =BuiltinMap[Ints[i].TargetPrefix];
618       
619       if (!BIM.insert(std::make_pair(Ints[i].GCCBuiltinName,
620                                      Ints[i].EnumName)).second)
621         throw "Intrinsic '" + Ints[i].TheDef->getName() +
622               "': duplicate GCC builtin name!";
623     }
624   }
625   
626   OS << "// Get the LLVM intrinsic that corresponds to a GCC builtin.\n";
627   OS << "// This is used by the C front-end.  The GCC builtin name is passed\n";
628   OS << "// in as BuiltinName, and a target prefix (e.g. 'ppc') is passed\n";
629   OS << "// in as TargetPrefix.  The result is assigned to 'IntrinsicID'.\n";
630   OS << "#ifdef GET_LLVM_INTRINSIC_FOR_GCC_BUILTIN\n";
631   
632   if (TargetOnly) {
633     OS << "static " << TargetPrefix << "Intrinsic::ID "
634        << "getIntrinsicForGCCBuiltin(const char "
635        << "*TargetPrefix, const char *BuiltinName) {\n";
636     OS << "  " << TargetPrefix << "Intrinsic::ID IntrinsicID = ";
637   } else {
638     OS << "Intrinsic::ID Intrinsic::getIntrinsicForGCCBuiltin(const char "
639        << "*TargetPrefix, const char *BuiltinName) {\n";
640     OS << "  Intrinsic::ID IntrinsicID = ";
641   }
642   
643   if (TargetOnly)
644     OS << "(" << TargetPrefix<< "Intrinsic::ID)";
645
646   OS << "Intrinsic::not_intrinsic;\n";
647   
648   // Note: this could emit significantly better code if we cared.
649   for (BIMTy::iterator I = BuiltinMap.begin(), E = BuiltinMap.end();I != E;++I){
650     OS << "  ";
651     if (!I->first.empty())
652       OS << "if (!strcmp(TargetPrefix, \"" << I->first << "\")) ";
653     else
654       OS << "/* Target Independent Builtins */ ";
655     OS << "{\n";
656
657     // Emit the comparisons for this target prefix.
658     EmitTargetBuiltins(I->second, TargetPrefix, OS);
659     OS << "  }\n";
660   }
661   OS << "  return IntrinsicID;\n";
662   OS << "}\n";
663   OS << "#endif\n\n";
664 }