b7c8093875ce4db053a9f125a018567676d9ebdd
[oota-llvm.git] / utils / TableGen / IntrinsicEmitter.cpp
1 //===- IntrinsicEmitter.cpp - Generate intrinsic information --------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file was developed by Chris Lattner and is distributed under
6 // the University of Illinois Open Source 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);
29
30   // Emit the enum information.
31   EmitEnumInfo(Ints, OS);
32
33   // Emit the intrinsic ID -> name table.
34   EmitIntrinsicToNameTable(Ints, OS);
35   
36   // Emit the function name recognizer.
37   EmitFnNameRecognizer(Ints, OS);
38   
39   // Emit the intrinsic verifier.
40   EmitVerifier(Ints, OS);
41   
42   // Emit the intrinsic declaration generator.
43   EmitGenerator(Ints, OS);
44   
45   // Emit mod/ref info for each function.
46   EmitModRefInfo(Ints, OS);
47   
48   // Emit table of non-memory accessing intrinsics.
49   EmitNoMemoryInfo(Ints, OS);
50   
51   // Emit side effect info for each intrinsic.
52   EmitSideEffectInfo(Ints, OS);
53
54   // Emit a list of intrinsics with corresponding GCC builtins.
55   EmitGCCBuiltinList(Ints, OS);
56
57   // Emit code to translate GCC builtins into LLVM intrinsics.
58   EmitIntrinsicToGCCBuiltinMap(Ints, OS);
59 }
60
61 void IntrinsicEmitter::EmitEnumInfo(const std::vector<CodeGenIntrinsic> &Ints,
62                                     std::ostream &OS) {
63   OS << "// Enum values for Intrinsics.h\n";
64   OS << "#ifdef GET_INTRINSIC_ENUM_VALUES\n";
65   for (unsigned i = 0, e = Ints.size(); i != e; ++i) {
66     OS << "    " << Ints[i].EnumName;
67     OS << ((i != e-1) ? ", " : "  ");
68     OS << std::string(40-Ints[i].EnumName.size(), ' ') 
69       << "// " << Ints[i].Name << "\n";
70   }
71   OS << "#endif\n\n";
72 }
73
74 void IntrinsicEmitter::
75 EmitFnNameRecognizer(const std::vector<CodeGenIntrinsic> &Ints, 
76                      std::ostream &OS) {
77   // Build a function name -> intrinsic name mapping.
78   std::map<std::string, unsigned> IntMapping;
79   for (unsigned i = 0, e = Ints.size(); i != e; ++i)
80     IntMapping[Ints[i].Name] = i;
81     
82   OS << "// Function name -> enum value recognizer code.\n";
83   OS << "#ifdef GET_FUNCTION_RECOGNIZER\n";
84   OS << "  switch (Name[5]) {\n";
85   OS << "  default:\n";
86   // Emit the intrinsics in sorted order.
87   char LastChar = 0;
88   for (std::map<std::string, unsigned>::iterator I = IntMapping.begin(),
89        E = IntMapping.end(); I != E; ++I) {
90     if (I->first[5] != LastChar) {
91       LastChar = I->first[5];
92       OS << "    break;\n";
93       OS << "  case '" << LastChar << "':\n";
94     }
95     
96     // For overloaded intrinsics, only the prefix needs to match
97     if (Ints[I->second].isOverloaded)
98       OS << "    if (Len > " << I->first.size()
99        << " && !memcmp(Name, \"" << I->first << ".\", "
100        << (I->first.size() + 1) << ")) return Intrinsic::"
101        << Ints[I->second].EnumName << ";\n";
102     else 
103       OS << "    if (Len == " << I->first.size()
104          << " && !memcmp(Name, \"" << I->first << "\", "
105          << I->first.size() << ")) return Intrinsic::"
106          << Ints[I->second].EnumName << ";\n";
107   }
108   OS << "  }\n";
109   OS << "#endif\n\n";
110 }
111
112 void IntrinsicEmitter::
113 EmitIntrinsicToNameTable(const std::vector<CodeGenIntrinsic> &Ints, 
114                          std::ostream &OS) {
115   OS << "// Intrinsic ID to name table\n";
116   OS << "#ifdef GET_INTRINSIC_NAME_TABLE\n";
117   OS << "  // Note that entry #0 is the invalid intrinsic!\n";
118   for (unsigned i = 0, e = Ints.size(); i != e; ++i)
119     OS << "  \"" << Ints[i].Name << "\",\n";
120   OS << "#endif\n\n";
121 }
122
123 static void EmitTypeForValueType(std::ostream &OS, MVT::ValueType VT) {
124   if (MVT::isInteger(VT)) {
125     unsigned BitWidth = MVT::getSizeInBits(VT);
126     OS << "IntegerType::get(" << BitWidth << ")";
127   } else if (VT == MVT::Other) {
128     // MVT::OtherVT is used to mean the empty struct type here.
129     OS << "StructType::get(std::vector<const Type *>())";
130   } else if (VT == MVT::f32) {
131     OS << "Type::FloatTy";
132   } else if (VT == MVT::f64) {
133     OS << "Type::DoubleTy";
134   } else if (VT == MVT::f80) {
135     OS << "Type::X86_FP80Ty";
136   } else if (VT == MVT::f128) {
137     OS << "Type::FP128Ty";
138   } else if (VT == MVT::ppcf128) {
139     OS << "Type::PPC_FP128Ty";
140   } else if (VT == MVT::isVoid) {
141     OS << "Type::VoidTy";
142   } else {
143     assert(false && "Unsupported ValueType!");
144   }
145 }
146
147 static void EmitTypeGenerate(std::ostream &OS, Record *ArgType, 
148                              unsigned &ArgNo) {
149   MVT::ValueType VT = getValueType(ArgType->getValueAsDef("VT"));
150
151   if (ArgType->isSubClassOf("LLVMMatchType")) {
152     unsigned Number = ArgType->getValueAsInt("Number");
153     assert(Number < ArgNo && "Invalid matching number!");
154     OS << "Tys[" << Number << "]";
155   } else if (VT == MVT::iAny || VT == MVT::fAny) {
156     // NOTE: The ArgNo variable here is not the absolute argument number, it is
157     // the index of the "arbitrary" type in the Tys array passed to the
158     // Intrinsic::getDeclaration function. Consequently, we only want to
159     // increment it when we actually hit an overloaded type. Getting this wrong
160     // leads to very subtle bugs!
161     OS << "Tys[" << ArgNo++ << "]";
162   } else if (MVT::isVector(VT)) {
163     OS << "VectorType::get(";
164     EmitTypeForValueType(OS, MVT::getVectorElementType(VT));
165     OS << ", " << MVT::getVectorNumElements(VT) << ")";
166   } else if (VT == MVT::iPTR) {
167     OS << "PointerType::get(";
168     EmitTypeGenerate(OS, ArgType->getValueAsDef("ElTy"), ArgNo);
169     OS << ")";
170   } else if (VT == MVT::isVoid) {
171     if (ArgNo == 0)
172       OS << "Type::VoidTy";
173     else
174       // MVT::isVoid is used to mean varargs here.
175       OS << "...";
176   } else {
177     EmitTypeForValueType(OS, VT);
178   }
179 }
180
181 /// RecordListComparator - Provide a determinstic comparator for lists of
182 /// records.
183 namespace {
184   struct RecordListComparator {
185     bool operator()(const std::vector<Record*> &LHS,
186                     const std::vector<Record*> &RHS) const {
187       unsigned i = 0;
188       do {
189         if (i == RHS.size()) return false;  // RHS is shorter than LHS.
190         if (LHS[i] != RHS[i])
191           return LHS[i]->getName() < RHS[i]->getName();
192       } while (++i != LHS.size());
193       
194       return i != RHS.size();
195     }
196   };
197 }
198
199 void IntrinsicEmitter::EmitVerifier(const std::vector<CodeGenIntrinsic> &Ints, 
200                                     std::ostream &OS) {
201   OS << "// Verifier::visitIntrinsicFunctionCall code.\n";
202   OS << "#ifdef GET_INTRINSIC_VERIFIER\n";
203   OS << "  switch (ID) {\n";
204   OS << "  default: assert(0 && \"Invalid intrinsic!\");\n";
205   
206   // This checking can emit a lot of very common code.  To reduce the amount of
207   // code that we emit, batch up cases that have identical types.  This avoids
208   // problems where GCC can run out of memory compiling Verifier.cpp.
209   typedef std::map<std::vector<Record*>, std::vector<unsigned>, 
210     RecordListComparator> MapTy;
211   MapTy UniqueArgInfos;
212   
213   // Compute the unique argument type info.
214   for (unsigned i = 0, e = Ints.size(); i != e; ++i)
215     UniqueArgInfos[Ints[i].ArgTypeDefs].push_back(i);
216
217   // Loop through the array, emitting one comparison for each batch.
218   for (MapTy::iterator I = UniqueArgInfos.begin(),
219        E = UniqueArgInfos.end(); I != E; ++I) {
220     for (unsigned i = 0, e = I->second.size(); i != e; ++i) {
221       OS << "  case Intrinsic::" << Ints[I->second[i]].EnumName << ":\t\t// "
222          << Ints[I->second[i]].Name << "\n";
223     }
224     
225     const std::vector<Record*> &ArgTypes = I->first;
226     OS << "    VerifyIntrinsicPrototype(ID, IF, " << ArgTypes.size() << ", ";
227     for (unsigned j = 0; j != ArgTypes.size(); ++j) {
228       Record *ArgType = ArgTypes[j];
229       if (ArgType->isSubClassOf("LLVMMatchType")) {
230         unsigned Number = ArgType->getValueAsInt("Number");
231         assert(Number < j && "Invalid matching number!");
232         OS << "~" << Number;
233       } else {
234         MVT::ValueType VT = getValueType(ArgType->getValueAsDef("VT"));
235         OS << getEnumName(VT);
236         if (VT == MVT::isVoid && j != 0 && j != ArgTypes.size()-1)
237           throw "Var arg type not last argument";
238       }
239       if (j != ArgTypes.size()-1)
240         OS << ", ";
241     }
242       
243     OS << ");\n";
244     OS << "    break;\n";
245   }
246   OS << "  }\n";
247   OS << "#endif\n\n";
248 }
249
250 void IntrinsicEmitter::EmitGenerator(const std::vector<CodeGenIntrinsic> &Ints, 
251                                      std::ostream &OS) {
252   OS << "// Code for generating Intrinsic function declarations.\n";
253   OS << "#ifdef GET_INTRINSIC_GENERATOR\n";
254   OS << "  switch (id) {\n";
255   OS << "  default: assert(0 && \"Invalid intrinsic!\");\n";
256   
257   // Similar to GET_INTRINSIC_VERIFIER, batch up cases that have identical
258   // types.
259   typedef std::map<std::vector<Record*>, std::vector<unsigned>, 
260     RecordListComparator> MapTy;
261   MapTy UniqueArgInfos;
262   
263   // Compute the unique argument type info.
264   for (unsigned i = 0, e = Ints.size(); i != e; ++i)
265     UniqueArgInfos[Ints[i].ArgTypeDefs].push_back(i);
266
267   // Loop through the array, emitting one generator for each batch.
268   for (MapTy::iterator I = UniqueArgInfos.begin(),
269        E = UniqueArgInfos.end(); I != E; ++I) {
270     for (unsigned i = 0, e = I->second.size(); i != e; ++i) {
271       OS << "  case Intrinsic::" << Ints[I->second[i]].EnumName << ":\t\t// "
272          << Ints[I->second[i]].Name << "\n";
273     }
274     
275     const std::vector<Record*> &ArgTypes = I->first;
276     unsigned N = ArgTypes.size();
277
278     if (N > 1 &&
279         getValueType(ArgTypes[N-1]->getValueAsDef("VT")) == MVT::isVoid) {
280       OS << "    IsVarArg = true;\n";
281       --N;
282     }
283     
284     unsigned ArgNo = 0;
285     OS << "    ResultTy = ";
286     EmitTypeGenerate(OS, ArgTypes[0], ArgNo);
287     OS << ";\n";
288     
289     for (unsigned j = 1; j != N; ++j) {
290       OS << "    ArgTys.push_back(";
291       EmitTypeGenerate(OS, ArgTypes[j], ArgNo);
292       OS << ");\n";
293     }
294     OS << "    break;\n";
295   }
296   OS << "  }\n";
297   OS << "#endif\n\n";
298 }
299
300 void IntrinsicEmitter::EmitModRefInfo(const std::vector<CodeGenIntrinsic> &Ints,
301                                       std::ostream &OS) {
302   OS << "// BasicAliasAnalysis code.\n";
303   OS << "#ifdef GET_MODREF_BEHAVIOR\n";
304   for (unsigned i = 0, e = Ints.size(); i != e; ++i) {
305     switch (Ints[i].ModRef) {
306     default: break;
307     case CodeGenIntrinsic::NoMem:
308       OS << "  NoMemoryIntrinsics->set(Intrinsic::" << Ints[i].EnumName << ");\n";
309       break;
310     case CodeGenIntrinsic::ReadArgMem:
311     case CodeGenIntrinsic::ReadMem:
312       OS << "  OnlyReadsMemoryIntrinsics->set(Intrinsic::" << Ints[i].EnumName << ");\n";
313       break;
314     }
315   }
316   OS << "#endif\n\n";
317 }
318
319 void IntrinsicEmitter::
320 EmitNoMemoryInfo(const std::vector<CodeGenIntrinsic> &Ints, std::ostream &OS) {
321   OS << "// SelectionDAGIsel code.\n";
322   OS << "#ifdef GET_NO_MEMORY_INTRINSICS\n";
323   OS << "  switch (IntrinsicID) {\n";
324   OS << "  default: break;\n";
325   for (unsigned i = 0, e = Ints.size(); i != e; ++i) {
326     switch (Ints[i].ModRef) {
327     default: break;
328     case CodeGenIntrinsic::NoMem:
329       OS << "  case Intrinsic::" << Ints[i].EnumName << ":\n";
330       break;
331     }
332   }
333   OS << "    return true; // These intrinsics do not reference memory.\n";
334   OS << "  }\n";
335   OS << "#endif\n\n";
336 }
337
338 void IntrinsicEmitter::
339 EmitSideEffectInfo(const std::vector<CodeGenIntrinsic> &Ints, std::ostream &OS){
340   OS << "// Return true if doesn't access or only reads memory.\n";
341   OS << "#ifdef GET_SIDE_EFFECT_INFO\n";
342   OS << "  switch (IntrinsicID) {\n";
343   OS << "  default: break;\n";
344   for (unsigned i = 0, e = Ints.size(); i != e; ++i) {
345     switch (Ints[i].ModRef) {
346     default: break;
347     case CodeGenIntrinsic::NoMem:
348     case CodeGenIntrinsic::ReadArgMem:
349     case CodeGenIntrinsic::ReadMem:
350       OS << "  case Intrinsic::" << Ints[i].EnumName << ":\n";
351       break;
352     }
353   }
354   OS << "    return true; // These intrinsics have no side effects.\n";
355   OS << "  }\n";
356   OS << "#endif\n\n";
357 }
358
359 void IntrinsicEmitter::
360 EmitGCCBuiltinList(const std::vector<CodeGenIntrinsic> &Ints, std::ostream &OS){
361   OS << "// Get the GCC builtin that corresponds to an LLVM intrinsic.\n";
362   OS << "#ifdef GET_GCC_BUILTIN_NAME\n";
363   OS << "  switch (F->getIntrinsicID()) {\n";
364   OS << "  default: BuiltinName = \"\"; break;\n";
365   for (unsigned i = 0, e = Ints.size(); i != e; ++i) {
366     if (!Ints[i].GCCBuiltinName.empty()) {
367       OS << "  case Intrinsic::" << Ints[i].EnumName << ": BuiltinName = \""
368          << Ints[i].GCCBuiltinName << "\"; break;\n";
369     }
370   }
371   OS << "  }\n";
372   OS << "#endif\n\n";
373 }
374
375 void IntrinsicEmitter::
376 EmitIntrinsicToGCCBuiltinMap(const std::vector<CodeGenIntrinsic> &Ints, 
377                              std::ostream &OS) {
378   typedef std::map<std::pair<std::string, std::string>, std::string> BIMTy;
379   BIMTy BuiltinMap;
380   for (unsigned i = 0, e = Ints.size(); i != e; ++i) {
381     if (!Ints[i].GCCBuiltinName.empty()) {
382       std::pair<std::string, std::string> Key(Ints[i].GCCBuiltinName,
383                                               Ints[i].TargetPrefix);
384       if (!BuiltinMap.insert(std::make_pair(Key, Ints[i].EnumName)).second)
385         throw "Intrinsic '" + Ints[i].TheDef->getName() +
386               "': duplicate GCC builtin name!";
387     }
388   }
389   
390   OS << "// Get the LLVM intrinsic that corresponds to a GCC builtin.\n";
391   OS << "// This is used by the C front-end.  The GCC builtin name is passed\n";
392   OS << "// in as BuiltinName, and a target prefix (e.g. 'ppc') is passed\n";
393   OS << "// in as TargetPrefix.  The result is assigned to 'IntrinsicID'.\n";
394   OS << "#ifdef GET_LLVM_INTRINSIC_FOR_GCC_BUILTIN\n";
395   OS << "  if (0);\n";
396   // Note: this could emit significantly better code if we cared.
397   for (BIMTy::iterator I = BuiltinMap.begin(), E = BuiltinMap.end();I != E;++I){
398     OS << "  else if (";
399     if (!I->first.second.empty()) {
400       // Emit this as a strcmp, so it can be constant folded by the FE.
401       OS << "!strcmp(TargetPrefix, \"" << I->first.second << "\") &&\n"
402          << "           ";
403     }
404     OS << "!strcmp(BuiltinName, \"" << I->first.first << "\"))\n";
405     OS << "    IntrinsicID = Intrinsic::" << I->second << ";\n";
406   }
407   OS << "  else\n";
408   OS << "    IntrinsicID = Intrinsic::not_intrinsic;\n";
409   OS << "#endif\n\n";
410 }